text
stringlengths
3
1.05M
import { Directive, TemplateRef } from '@angular/core'; import * as i0 from "@angular/core"; /** Decorates the `ng-template` tags and reads out the template from it. */ export class McTabContent { constructor(template) { this.template = template; } } /** @nocollapse */ McTabContent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.2.5", ngImport: i0, type: McTabContent, deps: [{ token: i0.TemplateRef }], target: i0.ɵɵFactoryTarget.Directive }); /** @nocollapse */ McTabContent.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "12.0.0", version: "12.2.5", type: McTabContent, selector: "[mcTabContent]", ngImport: i0 }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.2.5", ngImport: i0, type: McTabContent, decorators: [{ type: Directive, args: [{ selector: '[mcTabContent]' }] }], ctorParameters: function () { return [{ type: i0.TemplateRef }]; } }); //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGFiLWNvbnRlbnQuZGlyZWN0aXZlLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vcGFja2FnZXMvbW9zYWljL3RhYnMvdGFiLWNvbnRlbnQuZGlyZWN0aXZlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQU8sRUFBRSxTQUFTLEVBQUUsV0FBVyxFQUFFLE1BQU0sZUFBZSxDQUFDOztBQUd2RCwyRUFBMkU7QUFFM0UsTUFBTSxPQUFPLFlBQVk7SUFDckIsWUFBbUIsUUFBMEI7UUFBMUIsYUFBUSxHQUFSLFFBQVEsQ0FBa0I7SUFBRyxDQUFDOzs0SEFEeEMsWUFBWTtnSEFBWixZQUFZOzJGQUFaLFlBQVk7a0JBRHhCLFNBQVM7bUJBQUMsRUFBRSxRQUFRLEVBQUUsZ0JBQWdCLEVBQUUiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgeyBEaXJlY3RpdmUsIFRlbXBsYXRlUmVmIH0gZnJvbSAnQGFuZ3VsYXIvY29yZSc7XG5cblxuLyoqIERlY29yYXRlcyB0aGUgYG5nLXRlbXBsYXRlYCB0YWdzIGFuZCByZWFkcyBvdXQgdGhlIHRlbXBsYXRlIGZyb20gaXQuICovXG5ARGlyZWN0aXZlKHsgc2VsZWN0b3I6ICdbbWNUYWJDb250ZW50XScgfSlcbmV4cG9ydCBjbGFzcyBNY1RhYkNvbnRlbnQge1xuICAgIGNvbnN0cnVjdG9yKHB1YmxpYyB0ZW1wbGF0ZTogVGVtcGxhdGVSZWY8YW55Pikge31cbn1cbiJdfQ==
import React from 'react' import RateTier from './RateTier' import {translateInterestPaymentDue, translateLendingRateType} from '../../utils/dict' import * as moment from 'moment' import ecomp from '../../utils/enum-comp' import {makeStyles} from '@material-ui/core' const useStyles = makeStyles(() => ({ sectionTitle: { fontStyle: 'italic' }, sectionContent: { marginTop: 0, marginBottom: 0, paddingLeft: 20 } })) const LendingRate = (props) => { const classes = useStyles() const { lendingRateType, rate, calculationFrequency, applicationFrequency, comparisonRate, interestPaymentDue, tiers, additionalValue, additionalInfo, additionalInfoUri } = props.lendingRate return ( <li> <div>{(rate * 100).toFixed(2)}%</div> {!!comparisonRate && <div>Comparision rate: {(comparisonRate * 100).toFixed(2)}%</div>} <div> {translateLendingRateType(lendingRateType)} { (lendingRateType === 'FIXED' || lendingRateType === 'INTRODUCTORY') && !!additionalValue && <span> - {moment.duration(additionalValue).humanize().replace('a ', 'every ')}</span> } { ( lendingRateType === 'DISCOUNT' || lendingRateType === 'PENALTY' || lendingRateType === 'FLOATING' || lendingRateType === 'MARKET_LINKED' || lendingRateType === 'BUNDLE_DISCOUNT_FIXED' || lendingRateType === 'BUNDLE_DISCOUNT_VARIABLE') && <span> - {additionalValue}</span> } { ( lendingRateType === 'VARIABLE' || lendingRateType === 'PURCHASE' ) && !!additionalValue && <span> - {additionalValue}</span> } </div> {!!calculationFrequency && <div>Calculated {moment.duration(calculationFrequency).humanize().replace('a ', 'every ')}</div>} {!!applicationFrequency && <div>Applied {moment.duration(applicationFrequency).humanize().replace('a ', 'every ')}</div>} {!!interestPaymentDue && <div>Interest Payment {translateInterestPaymentDue(interestPaymentDue)}</div>} { !!tiers && tiers.length > 0 && <div> <div className={classes.sectionTitle}>Rate Tiers:</div> <ul className={classes.sectionContent}> {tiers.sort((a, b)=>ecomp(a.name, b.name)).map((tier, index) => <RateTier key={index} tier={tier}/>)} </ul> </div> } {!!additionalInfo && <div>{additionalInfo}</div>} {!!additionalInfoUri && <div><a href={additionalInfoUri} target='_blank' rel='noopener noreferrer'>More info</a></div>} </li> ) } export default LendingRate
import React from 'react'; import PropTypes from 'prop-types'; import Icon from 'react-icons-kit'; import Tabs, { TabPane } from 'rc-tabs'; import TabContent from 'rc-tabs/lib/TabContent'; import ScrollableInkTabBar from 'rc-tabs/lib/ScrollableInkTabBar'; import 'rc-tabs/assets/index.css'; import Box from 'reusecore/src/elements/Box'; import Text from 'reusecore/src/elements/Text'; import Heading from 'reusecore/src/elements/Heading'; import Image from 'reusecore/src/elements/Image'; import Container from 'common/src/components/UI/Container'; import SectionWrapper from './updateScreen.style'; import { SCREENSHOTS } from 'common/src/data/SaasClassic'; const UpdateScreen = ({ secTitleWrapper, secText, secHeading }) => { return ( <SectionWrapper id="screenshot_section"> <Container> <Box {...secTitleWrapper}> <Text {...secText} content="PRODUCT SCREENSHOT" /> <Heading {...secHeading} content="Easily customize dashboard in minutes" /> </Box> <Tabs renderTabBar={() => <ScrollableInkTabBar />} renderTabContent={() => <TabContent animated={false} />} className="update-screen-tab" > {SCREENSHOTS.map((item, index) => ( <TabPane tab={ <> <Icon icon={item.icon} size={24} /> {item.title} </> } key={index + 1} > <Image src={item.image} alt={`screenshot-${index + 1}`} /> </TabPane> ))} </Tabs> </Container> </SectionWrapper> ); }; UpdateScreen.propTypes = { secTitleWrapper: PropTypes.object, secText: PropTypes.object, secHeading: PropTypes.object, }; UpdateScreen.defaultProps = { secTitleWrapper: { mb: ['60px', '80px'], }, secText: { as: 'span', display: 'block', textAlign: 'center', fontSize: '14px', letterSpacing: '0.15em', fontWeight: '700', color: '#ff4362', mb: '12px', }, secHeading: { textAlign: 'center', fontSize: ['20px', '24px', '36px', '36px'], fontWeight: '700', color: '#0f2137', letterSpacing: '-0.025em', mb: '0', ml: 'auto', mr: 'auto', lineHeight: '1.12', width: '540px', maxWidth: '100%', }, }; export default UpdateScreen;
/*! * Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file. */ import AmpState from 'ampersand-state'; import util from 'util'; import { cloneDeep, isObject, omit } from 'lodash'; import {makeSparkPluginStore} from './storage'; /** * @class */ const SparkPlugin = AmpState.extend({ derived: { boundedStorage: { deps: [], fn() { return makeSparkPluginStore(`bounded`, this); } }, unboundedStorage: { deps: [], fn() { return makeSparkPluginStore(`unbounded`, this); } }, config: { // figure out why caching config breaks the refresh integration test // but not the refresh automation test. cache: false, deps: [ `spark`, `spark.config` ], fn() { if (this.spark && this.spark.config) { const namespace = this.getNamespace(); if (namespace) { return this.spark.config[namespace.toLowerCase()]; } return this.spark.config; } return {}; } }, logger: { deps: [ `spark`, `spark.logger` ], fn() { return this.spark.logger || console; } }, spark: { deps: [`parent`], fn() { if (!this.parent && !this.collection) { throw new Error(`Cannot determine \`this.spark\` without \`this.parent\` or \`this.collection\`. Please initialize \`this\` via \`children\` or \`collection\` or set \`this.parent\` manually`); } /* eslint consistent-this: [0] */ let parent = this; while (parent.parent || parent.collection) { parent = parent.parent || parent.collection; } return parent; } } }, session: { parent: { type: `any` }, /** * Indicates this plugin is ready to be used. Defaults to true but can be * overridden by plugins as appropriate. Used by {@link SparkCore#read} * @instance * @memberof SparkPlugin * @type {boolean} */ ready: { default: true, type: `boolean` } }, /** * Overrides AmpersandState#clear to make sure we never unset `parent` and * recursively visits children/collections. * @instance * @memberof SparkPlugin * @param {Object} options * @returns {SparkPlugin} */ clear(options) { Object.keys(this.attributes).forEach((key) => { if (key !== `parent`) { this.unset(key, options); } }); Object.keys(this._children).forEach((key) => { this[key].clear(); }); Object.keys(this._collections).forEach((key) => { this[key].reset(); }); return this; }, initialize(...args) { Reflect.apply(AmpState.prototype.initialize, this, args); // This is a bit of a hack to allow makeStateDataType work let cloned = false; Object.keys(this._dataTypes).forEach((key) => { const dataType = this._dataTypes[key]; if (dataType.set) { if (!cloned) { this._dataTypes = cloneDeep(this._dataTypes); cloned = true; } dataType.set = dataType.set.bind(this); } }); // Propagate change:[attribute] events from children this.on(`change`, (model, options) => { if (this.parent) { this.parent.trigger(`change:${this.getNamespace().toLowerCase()}`, this.parent, this, options); } }); }, /** * @instance * @memberof SparkPlugin * @param {number} depth * @private * @returns {Object} */ inspect(depth) { return util.inspect(omit(this.serialize({ props: true, session: true, derived: true }), `boundedStorage`, `unboundedStorage`, `config`, `logger`, `spark`, `parent`), {depth}); }, request(...args) { return this.spark.request(...args); }, upload(...args) { return this.spark.upload(...args); }, when(eventName, ...rest) { if (rest && rest.length > 0) { throw new Error(`#when() does not accept a callback, you must attach to its promise`); } return new Promise((resolve) => { this.once(eventName, (...args) => resolve(args)); }); }, /** * Helper function for dealing with both forms of {@link AmpersandState#set()} * @param {string} key * @param {mixed} value * @param {Object} options * @private * @returns {Array<Object, Object>} */ _filterSetParameters(key, value, options) { let attrs; if (isObject(key) || key === null) { attrs = key; options = value; } else { attrs = {}; attrs[key] = value; } options = options || {}; return [attrs, options]; } }); export default SparkPlugin;
import 'whatwg-fetch'; const LOCALE = 'koKR'; const DATA_URL = `https://api.hearthstonejson.com/v1/latest/${LOCALE}/cards.collectible.json`; const FILTER = card => card.type === 'MINION'; export default function fetchJSON(filter = FILTER){ return new Promise((resolve, reject) => fetch(DATA_URL) .then(res => res.json()) .then(json => resolve(json.filter(filter))) .catch(err => reject(err))); }
describe("Gilded Rose", function() { it("should return the name of the item", function() { const gildedRose = new Shop([ new Item("foo", 0, 0), new Item("bar", 0, 0) ]); const items = gildedRose.updateQuality(); expect(items[1].name).toEqual("bar"); }); it("should reduce the quality by double as is past sellIn date", function() { const gildedRose = new Shop([ new Item("foo", 0, 5) ]); const items = gildedRose.updateQuality(); expect(items[0].quality).toEqual(3); }); it("should return not go below 0 for quality even though out of date", function() { const gildedRose = new Shop([ new Item("foo", 0, 1) ]); const items = gildedRose.updateQuality(); expect(items[0].quality).toEqual(0); }); it("should increase the quality of Aged Brie ", function() { const gildedRose = new Shop([ new Item("Aged Brie", 0, 4) ]); const items = gildedRose.updateQuality(); expect(items[0].quality).toEqual(6); }); it("should increase the quality of Aged Brie 2", function() { const gildedRose = new Shop([ new Item("Aged Brie", 0, 4) ]); const items = gildedRose.updateQuality2(); expect(items[0].quality).toEqual(6); }); it("should not increase quality above 50", function() { const gildedRose = new Shop([ new Item("Aged Brie", 0, 49) ]); const items = gildedRose.updateQuality(); expect(items[0].quality).toEqual(50); }); it("should not decrease the quality of Sulfuras, Hand of Ragnaros", function() { const gildedRose = new Shop([ new Item("Sulfuras, Hand of Ragnaros", 0, 49) ]); const items = gildedRose.updateQuality(); expect(items[0].quality).toEqual(49); }); it("should increase quality of Backstage passes by 2 within 10 days of the concert", function() { const gildedRose = new Shop([ new Item("Backstage passes to a TAFKAL80ETC concert", 8, 34) ]); const items = gildedRose.updateQuality(); expect(items[0].quality).toEqual(36); }); it("should increase quality of Backstage passes by 3 within 5 days of the concert", function() { const gildedRose = new Shop([ new Item("Backstage passes to a TAFKAL80ETC concert", 4, 34) ]); const items = gildedRose.updateQuality(); expect(items[0].quality).toEqual(37); }); it("should reduce quality of Backstage passes to 0 after concert", function() { const gildedRose = new Shop([ new Item("Backstage passes to a TAFKAL80ETC concert", 0, 49) ]); const items = gildedRose.updateQuality(); expect(items[0].quality).toEqual(0); }); it("should increase quality of Backstage passes by 2 within 10 days of the concert", function() { const gildedRose = new Shop([ new Item("Backstage passes to a TAFKAL80ETC concert", 8, 34) ]); const items = gildedRose.updateQuality2(); expect(items[0].quality).toEqual(36); }); it("should increase quality of Backstage passes by 3 within 5 days of the concert", function() { const gildedRose = new Shop([ new Item("Backstage passes to a TAFKAL80ETC concert", 4, 34) ]); const items = gildedRose.updateQuality2(); expect(items[0].quality).toEqual(37); }); it("should reduce quality of Backstage passes to 0 after concert", function() { const gildedRose = new Shop([ new Item("Backstage passes to a TAFKAL80ETC concert", 0, 49) ]); const items = gildedRose.updateQuality2(); expect(items[0].quality).toEqual(0); }); });
var paper = {}; var temporalSymbolTable = {}; module.exports.init = function(){ paper = Raphael(document.getElementById("paper"), 0,0); } updateSymbolTable = module.exports.updateSymbolTable = function(updatedSymbolTable){ temporalSymbolTable = updateSymbolTable; draw(); } draw = module.exports.draw = function(){ // get temporal symbol table and draw it //var rect1 = paper.rect(20,20,100,100).attr({fill: "blue"}); }
class LoginFormController { constructor ($rootScope, $auth, $state, $stateParams, API, AclService) { 'ngInject' delete $rootScope.me this.$auth = $auth this.$state = $state this.$stateParams = $stateParams this.AclService = AclService this.registerSuccess = $stateParams.registerSuccess this.successMsg = $stateParams.successMsg this.loginfailed = false this.unverified = false } $onInit(){ this.email = ''; this.password = ''; } login () { this.loginfailed = false this.unverified = false let user = { email: this.email, password: this.password } this.$auth.login(user) .then((response) => { let data = response.data.data let AclService = this.AclService angular.forEach(data.userRole, function (value) { AclService.attachRole(value) }) AclService.setAbilities(data.abilities) this.$auth.setToken(response.data) this.$state.go('app.landing') }) .catch(this.failedLogin.bind(this)) } failedLogin (res) { if (res.status == 401) { this.loginfailed = true } else { if (res.data.errors.message[0] == 'Email Unverified') { this.unverified = true } } } } export const LoginFormComponent = { templateUrl: './views/app/components/login-form/login-form.component.html', controller: LoginFormController, controllerAs: 'vm', bindings: {} }
/** * @author Richard Davey <[email protected]> * @copyright 2020 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ /** * @namespace Phaser.Types.GameObjects.Mesh */
module.exports = { root: true, env: { node: true }, 'extends': [ 'plugin:vue/essential', '@vue/airbnb' ], rules: { 'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off', 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off', 'no-param-reassign': ['error', { 'props': true, "ignorePropertyModificationsFor": ['state'] }], //for vuex state mutations }, parserOptions: { parser: 'babel-eslint' } }
/** * Muuri Packer * Copyright (c) 2016-present, Niklas Rämö <[email protected]> * Released under the MIT license * https://github.com/haltu/muuri/blob/master/src/Packer/LICENSE.md */ import PackerProcessor, { createWorkerProcessors, destroyWorkerProcessors, isWorkerProcessorsSupported, } from './PackerProcessor'; export var FILL_GAPS = 1; export var HORIZONTAL = 2; export var ALIGN_RIGHT = 4; export var ALIGN_BOTTOM = 8; export var ROUNDING = 16; export var PACKET_INDEX_ID = 0; export var PACKET_INDEX_WIDTH = 1; export var PACKET_INDEX_HEIGHT = 2; export var PACKET_INDEX_OPTIONS = 3; export var PACKET_HEADER_SLOTS = 4; /** * @class * @param {Number} [numWorkers=0] * @param {Object} [options] * @param {Boolean} [options.fillGaps=false] * @param {Boolean} [options.horizontal=false] * @param {Boolean} [options.alignRight=false] * @param {Boolean} [options.alignBottom=false] * @param {Boolean} [options.rounding=false] */ function Packer(numWorkers, options) { this._options = 0; this._processor = null; this._layoutQueue = []; this._layouts = {}; this._layoutCallbacks = {}; this._layoutWorkers = {}; this._layoutWorkerData = {}; this._workers = []; this._onWorkerMessage = this._onWorkerMessage.bind(this); // Set initial options. this.setOptions(options); // Init the worker(s) or the processor if workers can't be used. numWorkers = typeof numWorkers === 'number' ? Math.max(0, numWorkers) : 0; if (numWorkers && isWorkerProcessorsSupported()) { try { this._workers = createWorkerProcessors(numWorkers, this._onWorkerMessage); } catch (e) { this._processor = new PackerProcessor(); } } else { this._processor = new PackerProcessor(); } } Packer.prototype._sendToWorker = function () { if (!this._layoutQueue.length || !this._workers.length) return; var layoutId = this._layoutQueue.shift(); var worker = this._workers.pop(); var data = this._layoutWorkerData[layoutId]; delete this._layoutWorkerData[layoutId]; this._layoutWorkers[layoutId] = worker; worker.postMessage(data.buffer, [data.buffer]); }; Packer.prototype._onWorkerMessage = function (msg) { var data = new Float32Array(msg.data); var layoutId = data[PACKET_INDEX_ID]; var layout = this._layouts[layoutId]; var callback = this._layoutCallbacks[layoutId]; var worker = this._layoutWorkers[layoutId]; if (layout) delete this._layouts[layoutId]; if (callback) delete this._layoutCallbacks[layoutId]; if (worker) delete this._layoutWorkers[layoutId]; if (layout && callback) { layout.width = data[PACKET_INDEX_WIDTH]; layout.height = data[PACKET_INDEX_HEIGHT]; layout.slots = data.subarray(PACKET_HEADER_SLOTS, data.length); this._finalizeLayout(layout); callback(layout); } if (worker) { this._workers.push(worker); this._sendToWorker(); } }; Packer.prototype._finalizeLayout = function (layout) { var grid = layout._grid; var isHorizontal = layout._settings & HORIZONTAL; var isBorderBox = grid._boxSizing === 'border-box'; delete layout._grid; delete layout._settings; layout.styles = {}; if (isHorizontal) { layout.styles.width = (isBorderBox ? layout.width + grid._borderLeft + grid._borderRight : layout.width) + 'px'; } else { layout.styles.height = (isBorderBox ? layout.height + grid._borderTop + grid._borderBottom : layout.height) + 'px'; } return layout; }; /** * @public * @param {Object} [options] * @param {Boolean} [options.fillGaps] * @param {Boolean} [options.horizontal] * @param {Boolean} [options.alignRight] * @param {Boolean} [options.alignBottom] * @param {Boolean} [options.rounding] */ Packer.prototype.setOptions = function (options) { if (!options) return; var fillGaps; if (typeof options.fillGaps === 'boolean') { fillGaps = options.fillGaps ? FILL_GAPS : 0; } else { fillGaps = this._options & FILL_GAPS; } var horizontal; if (typeof options.horizontal === 'boolean') { horizontal = options.horizontal ? HORIZONTAL : 0; } else { horizontal = this._options & HORIZONTAL; } var alignRight; if (typeof options.alignRight === 'boolean') { alignRight = options.alignRight ? ALIGN_RIGHT : 0; } else { alignRight = this._options & ALIGN_RIGHT; } var alignBottom; if (typeof options.alignBottom === 'boolean') { alignBottom = options.alignBottom ? ALIGN_BOTTOM : 0; } else { alignBottom = this._options & ALIGN_BOTTOM; } var rounding; if (typeof options.rounding === 'boolean') { rounding = options.rounding ? ROUNDING : 0; } else { rounding = this._options & ROUNDING; } this._options = fillGaps | horizontal | alignRight | alignBottom | rounding; }; /** * @public * @param {Grid} grid * @param {Number} layoutId * @param {Item[]} items * @param {Number} width * @param {Number} height * @param {Function} callback * @returns {?Function} */ Packer.prototype.createLayout = function (grid, layoutId, items, width, height, callback) { if (this._layouts[layoutId]) { throw new Error('A layout with the provided id is currently being processed.'); } var horizontal = this._options & HORIZONTAL; var layout = { id: layoutId, items: items, slots: null, width: horizontal ? 0 : width, height: !horizontal ? 0 : height, // Temporary data, which will be removed before sending the layout data // outside of Packer's context. _grid: grid, _settings: this._options, }; // If there are no items let's call the callback immediately. if (!items.length) { layout.slots = []; this._finalizeLayout(layout); callback(layout); return; } // Create layout synchronously if needed. if (this._processor) { layout.slots = window.Float32Array ? new Float32Array(items.length * 2) : new Array(items.length * 2); this._processor.computeLayout(layout, layout._settings); this._finalizeLayout(layout); callback(layout); return; } // Worker data. var data = new Float32Array(PACKET_HEADER_SLOTS + items.length * 2); // Worker data header. data[PACKET_INDEX_ID] = layoutId; data[PACKET_INDEX_WIDTH] = layout.width; data[PACKET_INDEX_HEIGHT] = layout.height; data[PACKET_INDEX_OPTIONS] = layout._settings; // Worker data items. var i, j, item; for (i = 0, j = PACKET_HEADER_SLOTS - 1, item; i < items.length; i++) { item = items[i]; data[++j] = item._width + item._marginLeft + item._marginRight; data[++j] = item._height + item._marginTop + item._marginBottom; } this._layoutQueue.push(layoutId); this._layouts[layoutId] = layout; this._layoutCallbacks[layoutId] = callback; this._layoutWorkerData[layoutId] = data; this._sendToWorker(); return this.cancelLayout.bind(this, layoutId); }; /** * @public * @param {Number} layoutId */ Packer.prototype.cancelLayout = function (layoutId) { var layout = this._layouts[layoutId]; if (!layout) return; delete this._layouts[layoutId]; delete this._layoutCallbacks[layoutId]; if (this._layoutWorkerData[layoutId]) { delete this._layoutWorkerData[layoutId]; var queueIndex = this._layoutQueue.indexOf(layoutId); if (queueIndex > -1) this._layoutQueue.splice(queueIndex, 1); } }; /** * @public */ Packer.prototype.destroy = function () { // Move all currently used workers back in the workers array. for (var key in this._layoutWorkers) { this._workers.push(this._layoutWorkers[key]); } // Destroy all instance's workers. destroyWorkerProcessors(this._workers); // Reset data. this._workers.length = 0; this._layoutQueue.length = 0; this._layouts = {}; this._layoutCallbacks = {}; this._layoutWorkers = {}; this._layoutWorkerData = {}; }; export default Packer;
from SPARQLWrapper import SPARQLWrapper, JSON from string import Template from sys import argv stream = argv[1].replace("csv","").replace(".stream","") mapping_file = open( argv[2] ) mapping_tmpl = Template( mapping_file.read() ) mappings = {"stream":stream, "next":'$MappingDeclaration'} res = mapping_tmpl.substitute(mappings) text_file = open(argv[3], "a") text_file.write(res) text_file.close() #print ("Finished")doc ##USAGE python <stream name> <stream-mapping-template> <output-file>
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. # This product includes software developed at Datadog (https://www.datadoghq.com/). # Copyright 2019-Present Datadog, Inc. from datadog_api_client.v1.model_utils import ( # noqa: F401 ApiTypeError, ModelComposed, ModelNormal, ModelSimple, cached_property, change_keys_js_to_python, convert_js_args_to_python_args, date, datetime, file_type, none_type, ) def lazy_import(): from datadog_api_client.v1.model.log import Log globals()["Log"] = Log class LogsListResponse(ModelNormal): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. Attributes: allowed_values (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict with a capitalized key describing the allowed value and an allowed value. These dicts store the allowed enum values. attribute_map (dict): The key is attribute name and the value is json key in definition. discriminator_value_class_map (dict): A dict to go from the discriminator variable value to the discriminator class name. validations (dict): The key is the tuple path to the attribute and the for var_name this is (var_name,). The value is a dict that stores validations for max_length, min_length, max_items, min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, inclusive_minimum, and regex. additional_properties_type (tuple): A tuple of classes accepted as additional properties values. """ allowed_values = {} validations = {} additional_properties_type = None _nullable = False @cached_property def openapi_types(): """ This must be a method because a model may have properties that are of type self, this must run after the class is loaded Returns openapi_types (dict): The key is attribute name and the value is attribute type. """ lazy_import() return { "logs": ([Log],), # noqa: E501 "next_log_id": (str,), # noqa: E501 "status": (str,), # noqa: E501 } discriminator = None attribute_map = { "logs": "logs", # noqa: E501 "next_log_id": "nextLogId", # noqa: E501 "status": "status", # noqa: E501 } read_only_vars = {} _composed_schemas = {} @convert_js_args_to_python_args def __init__(self, *args, **kwargs): # noqa: E501 """LogsListResponse - a model defined in OpenAPI Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. Defaults to True _path_to_item (tuple/list): This is a list of keys or values to drill down to the model in received_data when deserializing a response _spec_property_naming (bool): True if the variable names in the input data are serialized names, as specified in the OpenAPI document. False if the variable names in the input data are pythonic names, e.g. snake case (default) _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted If omitted no type conversion is done. _visited_composed_classes (tuple): This stores a tuple of classes that we have traveled through so that if we see that class again we will not use its discriminator again. When traveling through a discriminator, the composed schema that is is traveled through is added to this set. For example if Animal has a discriminator petType and we pass in "Dog", and the class Dog allOf includes Animal, we move through Animal once using the discriminator, and pick Dog. Then in Dog, we will make an instance of the Animal class but this time we won't travel through its discriminator because we passed in _visited_composed_classes = (Animal,) logs ([Log]): Array of logs matching the request and the `nextLogId` if sent.. [optional] # noqa: E501 next_log_id (str): Hash identifier of the next log to return in the list. This parameter is used for the pagination feature.. [optional] # noqa: E501 status (str): Status of the response.. [optional] # noqa: E501 """ super().__init__(kwargs) self._check_pos_args(args) @classmethod @convert_js_args_to_python_args def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 """Helper creating a new instance from a response.""" self = super(LogsListResponse, cls)._from_openapi_data(kwargs) self._check_pos_args(args) return self
import React, { PureComponent } from 'react'; import { Form } from '@ant-design/compatible'; import '@ant-design/compatible/assets/index.css'; import { Input, Modal, message } from 'antd'; import { updatePwd } from '@/services/signin'; import { md5Hash } from '../../utils/utils'; @Form.create() class UpdatePasswordDialog extends PureComponent { state = { submitting: false, }; onOKClick = () => { const { form } = this.props; form.validateFieldsAndScroll((err, values) => { if (err) { return; } if (values.new_password !== values.confirm_new_password) { message.warning('新密码与确认新密码不一致!'); return; } this.setState({ submitting: true }); const formData = { old_password: md5Hash(values.old_password), new_password: md5Hash(values.new_password), }; updatePwd(formData).then(res => { if (res.status === 'OK') { message.success('密码更新成功!'); this.handleCancel(); } this.setState({ submitting: false }); }); }); }; handleCancel = () => { const { onCancel } = this.props; if (onCancel) { onCancel(); } }; dispatch = action => { const { dispatch } = this.props; dispatch(action); }; render() { const { visible, form: { getFieldDecorator }, } = this.props; const { submitting } = this.state; const formItemLayout = { labelCol: { span: 6, }, wrapperCol: { span: 16, }, }; return ( <Modal title="修改个人密码" width={450} visible={visible} maskClosable={false} confirmLoading={submitting} destroyOnClose onOk={this.onOKClick} onCancel={this.handleCancel} style={{ top: 20 }} bodyStyle={{ maxHeight: 'calc( 100vh - 158px )', overflowY: 'auto' }} > <Form> <Form.Item {...formItemLayout} label="旧密码"> {getFieldDecorator('old_password', { rules: [ { required: true, message: '请输入旧密码', }, ], })(<Input type="password" placeholder="请输入旧密码" />)} </Form.Item> <Form.Item {...formItemLayout} label="新密码"> {getFieldDecorator('new_password', { rules: [ { required: true, message: '请输入新密码', }, ], })(<Input type="password" placeholder="请输入新密码" />)} </Form.Item> <Form.Item {...formItemLayout} label="确认新密码"> {getFieldDecorator('confirm_new_password', { rules: [ { required: true, message: '请输入确认新密码', }, ], })(<Input type="password" placeholder="请输入确认新密码" />)} </Form.Item> </Form> </Modal> ); } } export default UpdatePasswordDialog;
/* Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.charting.themes.Grasslands"]){dojo._hasResource["dojox.charting.themes.Grasslands"]=true;dojo.provide("dojox.charting.themes.Grasslands");dojo.require("dojox.charting.Theme");(function(){var _1=dojox.charting;_1.themes.Grasslands=new _1.Theme({colors:["#70803a","#dde574","#788062","#b1cc5d","#eff2c2"]});})();}
$.views.converters({ upper:function(val) { val = "" + val; return val && val.toUpperCase(); }, lower:function(val) { val = "" + val; return val && val.toLowerCase(); } }); var myTmpl = $.templates("#myTmpl"), pageOptions = { noInvalidData: false }, model = { agree: false, name: "Jo", names: [ {name: "Jo"}, {name: "Mary"}, {name: "Xavier"} ] }; myTmpl.link("#page", model, { page: pageOptions, upper: $.views.converters.upper, lower: $.views.converters.lower }) .on("click", "#validate", function() { validation.validate(); }) .on("click", "#clear", function() { validation.clearMessage(); }) .on("click", "#refresh-outer", function() { validation.refresh(); }) .on("click", "#refresh", function() { validation.refreshValidates(); }); var validation = $.view("#validate").ctx.tag;
import React, {Component, Fragment} from 'react'; import PropTypes from 'prop-types'; class LargeScreenMenu extends Component{ constructor(props){ super(props); } static propTypes = { userCategories: PropTypes.array } static defaultProps = { userCategories: [] } render(){ return( <Fragment> <div className="imageRow"> { this.props.menuItems.map((imageData)=>{ return( <div key={imageData.href} className="imageColumn"> <div className="imageContainer" onClick={() => { this.props.history.push(imageData.href) }}> <img src={require("../images/" + imageData.imageName)} alt="Avatar" className="image" style={{width:"100%"}}/> <div className="middle"> <div className="imageTextContainer"> <div className="imageText">{imageData.imageText}</div> </div> </div> </div> </div> ); }) } </div> </Fragment> ); } } export default LargeScreenMenu;
'use strict'; const expect = require('chai').expect; const buttonGroup = require('../../../../../lib/device/validation/buttongroup'); describe('./lib/device/validation/buttongroup.js', function() { it('should try to get non existent button group (undefined)', function() { const result = buttonGroup.get(); expect(result).to.equal(undefined); }); it('should try to get non existent button group', function() { const result = buttonGroup.get('foo'); expect(result).to.equal(undefined); }); it('should get Volume button group', function() { const result = buttonGroup.get('Volume'); expect(result.length).to.equal(3); expect(result).to.deep.equal(['VOLUME UP', 'VOLUME DOWN', 'MUTE TOGGLE']); }); it('should get Volume button group, lower case', function() { const result = buttonGroup.get('volume'); expect(result.length).to.equal(3); }); it('should get Volume button group, mixed case', function() { const result = buttonGroup.get('VolUME'); expect(result.length).to.equal(3); }); it('should get Numpad button group', function() { const result = buttonGroup.get('Numpad'); expect(result.length).to.equal(10); expect(result).to.deep.equal(['DIGIT 0', 'DIGIT 1', 'DIGIT 2', 'DIGIT 3', 'DIGIT 4', 'DIGIT 5', 'DIGIT 6', 'DIGIT 7', 'DIGIT 8', 'DIGIT 9']); }); });
'use strict'; const TTSEngineType = { SpeechSynthesis: 0, GoogleTTS: 1, }; class TTSItem { play() {} } class SpeechTTSItem extends TTSItem { constructor(text, lang, voice) { super(); this.text = text; this.item = new SpeechSynthesisUtterance(text); this.item.lang = lang; this.item.voice = voice; } play() { window.speechSynthesis.speak(this.item); } } class GoogleTTSItem extends TTSItem { constructor(text, lang) { super(); this.lang = lang; this.text = text; let iframe = document.createElement('iframe'); // remove sandbox so we can modify contents/call play on audio element later iframe.removeAttribute('sandbox'); iframe.style.display = 'none'; document.body.appendChild(iframe); let encText = encodeURIComponent(text); iframe.contentDocument.body.innerHTML = '<audio src="https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&tl=' + lang + '&q=' + encText + '" id="TTS">'; this.item = iframe.contentDocument.body.firstElementChild; } play() { this.item.play(); } } class BrowserTTSEngine { constructor(lang) { this.googleTTSLang = lang == 'cn' ? 'zh' : lang; // TODO: should there be options for different voices here so that // everybody isn't forced into Microsoft Anna? const cactbotLangToSpeechLang = { en: 'en-US', de: 'de-DE', fr: 'fr-FR', ja: 'ja-JP', // TODO: maybe need to provide an option of zh-CN, zh-HK, zh-TW? cn: 'zh-CN', ko: 'ko-KR', }; // figure out what TTS engine type we need if (window.speechSynthesis !== undefined) { window.speechSynthesis.onvoiceschanged = () => { const speechLang = cactbotLangToSpeechLang[lang]; const voice = window.speechSynthesis.getVoices().find((voice) => voice.lang === speechLang); if (voice) { this.speechLang = speechLang; this.speechVoice = voice; window.speechSynthesis.onvoiceschanged = null; this.engineType = TTSEngineType.SpeechSynthesis; } }; } this.engineType = TTSEngineType.GoogleTTS; this.ttsItems = {}; } play(text) { try { if (this.ttsItems[text] !== undefined) this.ttsItems[text].play(); else this.playTTS(text); } catch (e) { console.log('Exception performing TTS', e); } } playTTS(text) { switch (this.engineType) { case TTSEngineType.SpeechSynthesis: this.playSpeechTTS(text); break; case TTSEngineType.GoogleTTS: this.playGoogleTTS(text); break; } } playSpeechTTS(text) { this.ttsItems[text] = new SpeechTTSItem(text, this.speechLang, this.speechVoice); this.ttsItems[text].play(); } playGoogleTTS(text) { this.ttsItems[text] = new GoogleTTSItem(text, this.googleTTSLang); this.ttsItems[text].play(); } }
""" Django settings for my_proj project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ from django.core.urlresolvers import reverse_lazy from os.path import dirname, join, exists # Build paths inside the project like this: join(BASE_DIR, "directory") BASE_DIR = dirname(dirname(dirname(__file__))) STATICFILES_DIRS = [join(BASE_DIR, 'static')] MEDIA_ROOT = join(BASE_DIR, 'media') MEDIA_URL = "/media/" # Use Django templates using the new Django 1.8 TEMPLATES settings TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ join(BASE_DIR, 'templates'), # insert more TEMPLATE_DIRS here ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this # list if you haven't customized them: 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], }, }, ] # Use 12factor inspired environment variables or from a file import environ env = environ.Env() # Ideally move env file should be outside the git repo # i.e. BASE_DIR.parent.parent env_file = join(dirname(__file__), 'local.env') if exists(env_file): environ.Env.read_env(str(env_file)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # Raises ImproperlyConfigured exception if SECRET_KEY not in os.environ SECRET_KEY = env('SECRET_KEY') ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.auth', 'django_admin_bootstrapped', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'authtools', 'crispy_forms', 'easy_thumbnails', 'profiles', 'accounts', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'my_proj.urls' WSGI_APPLICATION = 'my_proj.wsgi.application' # Database # https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { # Raises ImproperlyConfigured exception if DATABASE_URL not in # os.environ 'default': env.db(), } # Internationalization # https://docs.djangoproject.com/en/dev/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/dev/howto/static-files/ STATIC_URL = '/static/' ALLOWED_HOSTS = [] # Crispy Form Theme - Bootstrap 3 CRISPY_TEMPLATE_PACK = 'bootstrap3' # For Bootstrap 3, change error alert to 'danger' from django.contrib import messages MESSAGE_TAGS = { messages.ERROR: 'danger' } # Authentication Settings AUTH_USER_MODEL = 'authtools.User' LOGIN_REDIRECT_URL = reverse_lazy("profiles:show_self") LOGIN_URL = reverse_lazy("accounts:login") THUMBNAIL_EXTENSION = 'png' # Or any extn for your thumbnails
const fs = require("fs"); const path = require("path"); const uuid = require("../db/helpers/uuid"); const db = require("../db/db.json") module.exports = app => { fs.readFile(db, 'utf8', (err, data) => { if (err) throw err; var notes = JSON.parse(data); console.log(notes); //GET /api/notes should read the db.json file and return all saved notes as JSON. app.get('/api/notes', (req, res) => { res.json(notes); console.log(`${req.method} request received`); }); app.post('/api/notes', (req, res) => { console.info(`${req.method} request received to add a note!`); console.log(req.body) const { title, text } = req.body; if (title && text) { const addNote = { title, text, id: uuid(), }; fs.readFile(db, 'utf8', (err, data) => { if (err) { console.log(err); } else { notes.push(addNote) fs.writeFile('../db/db.json', JSON.stringify(notes), (writeErr) => { writeErr ? console.err(writeErr) : console.info(`Successfully added your note with ID = ${addNote.id}`) }) } }); const response = { status: 'success', body: addNote, }; console.log(response); res.json(response); } else { res.json('Error posting note :(') } }); // DELETE request to delete a note with a specific ID app.delete('/api/notes/:id', (req, res) => { console.info(`${req.method} request received to delete a note!`); console.log(req.body) const { title, text, id } = req.body; if (typeof req.params.id != "") { const deleteNote = { title, text, id, }; fs.readFile(db, 'utf8', (err, data) => { if (err) { console.log(err); } else { for (let i = 0; i < notes.length; i++) { if (notes[i].id == req.params.id) { notes.splice(i, 1); break; } } fs.writeFile(db, JSON.stringify(notes), (writeErr) => { writeErr ? console.err(writeErr) : console.info(`Successfully deleted note with ID = ${req.params.id}`) }) } }); const response = { status: 'success', body: deleteNote, }; console.log(response); res.json(response); } else { res.json('Error deleting note :(') } }); // VIEW ROUTES // 1. notes.html will be displayed when "http://localhost:3001/notes" is accessed app.get('/notes', (req, res) => { res.sendFile(path.join(__dirname, '../public/notes.html')) }) // 2. index.html will be displayed when any route other than "/notes" is accessed app.get('*', (req, res) => { res.sendFile(path.join(__dirname, '../public/index.html')) }); }); }
import "./profile.css"; import face from "./face1.png"; import flowers from "./flowers.png"; import paint from "./paint.png"; import impression from "./impression.png"; import search from "./search.png"; import mail from "./mail.png"; import bell from "./bell.png"; import exit from "./logout.png"; import logo from "./logo.png"; import name from "./logo1.png"; import arrowright from "./arrowright.png"; import arrowleft from "./arrowleft.png"; function Profile() { return ( <div className="Profile_body"> <div id="Profile_grid"> <div className="Profile_header"> <div className="Profile_searchform"> <form action="/action_page.php" className="Profile_search"> <input className="profileInput" type="text" name="search" /> <button type="submit" className="Profile_button"> <img src={search} /> </button> </form> </div> <img src={mail} alt="email" id="Profile_mail" /> <img src={bell} alt="notifications" id="Profile_bell" /> <img src={exit} alt="logout" id="Profile_exit" /> <img src={face} alt="face" id="Profile_profile" /> </div> <div className="Profile_logo"> <img src={logo} alt="logo" /> <img src={name} alt="museum" /> </div> <div className="Profile_aside"> <button id="Profile_button1">Sign Out</button> <p className="Profile_stats">Total No. Exhibits</p> <p className="Profile_number">46</p> <p className="Profile_stats">Total No. Questions</p>{" "} <p className="Profile_number">13</p> <p className="Profile_stats">Answered Questions</p> <p className="Profile_number">10</p> <p className="Profile_stats">Unanswered Questions</p>{" "} <p className="Profile_number">3</p> </div> <div className="Profile_mainbody"> <p id="Profile_p1">Profile</p> <div className="Profile_container1"> <img src={face} alt="face" id="Profile_face" /> <div className="Profile_info"> <p>Tiffany Fambry</p> <p>[email protected]</p> <p>Curator</p> </div> <p id="Profile_p2">Recently Edited Exhibits</p> <div className="Profile_container2"> <button className="Profile_b2"> <img src={arrowleft} /> </button> <img src={flowers} alt="flowers" id="Profile_flowers" /> <img src={paint} alt="paint" id="Profile_paint" /> <img src={impression} alt="impression" id="Profile_impression" /> <button className="Profile_b2"> <img src={arrowright} /> </button> </div> </div> </div> </div> </div> ); } export default Profile;
// A scalar value that scales the capturing rectangle // If compared to image viewing tools, 1 and 1 means no scaling // 0.5 will zoom in to a 200% view, 3 will zoom out and produce 33% scaling ct.camera.scale.x = 1.2; ct.camera.scale.y = 1.2; ct.camera.scale = 1.2;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CONFIG_OPTIONS = void 0; exports.CONFIG_OPTIONS = "CONFIG_OPTIONS"; //# sourceMappingURL=jwt.constants.js.map
/* * Copyright (c) 2019. The copyright is reserved by Ghode of Harbin Institute * of Technology. Users are free to copy, change or remove. Because no one * will read this. Only I know is that Repeaters are the best of the world. * Only I know is that Repeaters are the best of the world. Only I know is * that Repeaters are the best of the world. Maybe a long copyright text * seems professional. Therefore this text will be a bit lengthy. However, * the author seems to be afraid that one day, this text may be uploaded to * business projects. That is the time you can contact with author via email * [email protected] or directly ignore this, which will be interesting. */ !function(a){"function"==typeof define&&define.amd?define(["jquery","moment"],a):"object"==typeof exports?module.exports=a(require("jquery"),require("moment")):a(jQuery,moment)}(function(a,b){!function(){"use strict";var a=(b.defineLocale||b.lang).call(b,"ar-ma",{months:"يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"),monthsShort:"يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"),weekdays:"الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"),weekdaysShort:"احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت".split("_"),weekdaysMin:"ح_ن_ث_ر_خ_ج_س".split("_"),weekdaysParseExact:!0,longDateFormat:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY HH:mm",LLLL:"dddd D MMMM YYYY HH:mm"},calendar:{sameDay:"[اليوم على الساعة] LT",nextDay:"[غدا على الساعة] LT",nextWeek:"dddd [على الساعة] LT",lastDay:"[أمس على الساعة] LT",lastWeek:"dddd [على الساعة] LT",sameElse:"L"},relativeTime:{future:"في %s",past:"منذ %s",s:"ثوان",m:"دقيقة",mm:"%d دقائق",h:"ساعة",hh:"%d ساعات",d:"يوم",dd:"%d أيام",M:"شهر",MM:"%d أشهر",y:"سنة",yy:"%d سنوات"},week:{dow:6,doy:12}});return a}(),a.fullCalendar.datepickerLang("ar-ma","ar",{closeText:"إغلاق",prevText:"&#x3C;السابق",nextText:"التالي&#x3E;",currentText:"اليوم",monthNames:["يناير","فبراير","مارس","أبريل","مايو","يونيو","يوليو","أغسطس","سبتمبر","أكتوبر","نوفمبر","ديسمبر"],monthNamesShort:["1","2","3","4","5","6","7","8","9","10","11","12"],dayNames:["الأحد","الاثنين","الثلاثاء","الأربعاء","الخميس","الجمعة","السبت"],dayNamesShort:["أحد","اثنين","ثلاثاء","أربعاء","خميس","جمعة","سبت"],dayNamesMin:["ح","ن","ث","ر","خ","ج","س"],weekHeader:"أسبوع",dateFormat:"dd/mm/yy",firstDay:0,isRTL:!0,showMonthAfterYear:!1,yearSuffix:""}),a.fullCalendar.lang("ar-ma",{buttonText:{month:"شهر",week:"أسبوع",day:"يوم",list:"أجندة"},allDayText:"اليوم كله",eventLimitText:"أخرى"})});
class Graph { constructor () { this.adjacencyMap = {} } addVertex (vertex) { this.adjacencyMap[vertex] = [] } containsVertex (vertex) { return typeof (this.adjacencyMap[vertex]) !== 'undefined' } addEdge (vertex1, vertex2) { if (this.containsVertex(vertex1) && this.containsVertex(vertex2)) { this.adjacencyMap[vertex1].push(vertex2) this.adjacencyMap[vertex2].push(vertex1) } } printGraph (output = value => console.log(value)) { const keys = Object.keys(this.adjacencyMap) for (const i of keys) { const values = this.adjacencyMap[i] let vertex = '' for (const j of values) { vertex += j + ' ' } output(i + ' -> ' + vertex) } } /** * Prints the Breadth first traversal of the graph from source. * @param {number} source The source vertex to start BFS. */ bfs (source, output = value => console.log(value)) { const queue = [[source, 0]] // level of source is 0 const visited = new Set() while (queue.length) { const [node, level] = queue.shift() // remove the front of the queue if (visited.has(node)) { // visited continue } visited.add(node) output(`Visited node ${node} at level ${level}.`) for (const next of this.adjacencyMap[node]) { queue.push([next, level + 1]) // level 1 more than current } } } /** * Prints the Depth first traversal of the graph from source. * @param {number} source The source vertex to start DFS. */ dfs (source, visited = new Set(), output = value => console.log(value)) { if (visited.has(source)) { // visited return } output(`Visited node ${source}`) visited.add(source) for (const neighbour of this.adjacencyMap[source]) { this.dfs(neighbour, visited, output) } } } const example = () => { const g = new Graph() g.addVertex(1) g.addVertex(2) g.addVertex(3) g.addVertex(4) g.addVertex(5) g.addEdge(1, 2) g.addEdge(1, 3) g.addEdge(2, 4) g.addEdge(2, 5) // Graph // 1 -> 2 3 // 2 -> 1 4 5 // 3 -> 1 // 4 -> 2 // 5 -> 2 // Printing the adjacency list // g.printGraph() // Breadth first search at node 1 g.bfs(1) // Depth first search at node 1 g.dfs(1) }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ if (typeof(Wicket) == "undefined") Wicket = { }; Wicket.WUPB= { Def : function(formid, statusid, barid, url) { this.formid=formid; this.statusid=statusid; this.barid=barid; this.url=url; }, get : function(id) { return document.getElementById(id); }, start : function(def) { //Wicket.WUPB.get(def.formid).submit(); Wicket.WUPB.get(def.statusid).innerHTML='Upload starting...'; Wicket.WUPB.get(def.barid).firstChild.firstChild.style.width='0%'; Wicket.WUPB.get(def.statusid).style.display='block'; Wicket.WUPB.get(def.barid).style.display='block'; window.setTimeout(function() { Wicket.WUPB.ajax(def); }, 1000); }, ajax : function(def) { transport = false; if(window.XMLHttpRequest) { transport = new XMLHttpRequest(); if(transport.overrideMimeType) { transport.overrideMimeType('text/xml'); } } else if(window.ActiveXObject) { try { transport = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { transport = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } } if(!transport) { alert('Error: could not create XMLHTTP object.'); return false; } transport.onreadystatechange = function() { Wicket.WUPB.update(transport, def); }; transport.open('GET', def.url+'?anticache='+Math.random(), true); transport.send(null); }, update: function(transport, def) { if (transport.readyState == 4) { if (transport.status == 200) { var update = transport.responseText.split('|'); var completed_upload_size = update[2]; var total_upload_size = update[3]; var progressPercent = update[1]; var transferRate = update[4]; var timeRemaining = update[5]; if ((completed_upload_size != "") && (completed_upload_size != 0)) { Wicket.WUPB.get(def.barid).firstChild.firstChild.style.width=progressPercent+'%'; Wicket.WUPB.get(def.statusid).innerHTML=progressPercent + '% finished, ' + completed_upload_size + ' of ' + total_upload_size + ' at ' + transferRate + "; " + timeRemaining; } if (progressPercent == 100) { Wicket.WUPB.get(def.barid).firstChild.firstChild.style.width='100%'; Wicket.WUPB.get(def.statusid).style.display='none'; Wicket.WUPB.get(def.barid).style.display='none'; return null; } window.setTimeout(function() { Wicket.WUPB.ajax(def); }, 1000); } else { alert('Error: got a not-OK status code...'); } } } }
let data = { "body": "<path d=\"M21 21H3v-9.75L9.45 15l3.77-2.2L21 17.29V21M3 8.94V6.75l6.45 3.75l3.77-2.2L21 12.79V15l-7.78-4.5l-3.77 2.17L3 8.94z\" fill=\"currentColor\"/>", "width": 24, "height": 24 }; export default data;
import React from "react" import "./app.css" const AppContainer = ({ children }) => <div>{children}</div> export default AppContainer
# -*- coding: utf-8 -*- """ @file:compete_pctr_yes_test.py @time:2019/6/12 21:10 @author:Tangj @software:Pycharm @Desc """ import pandas as pd import numpy as np import time tt = time.time() fea = pd.DataFrame() test_bid = pd.read_csv('../usingData/test/test_bid.csv') request = pd.read_csv('../usingData/test/Request_list.csv') log = pd.read_csv('../usingData/test/test_log.csv') log = log.fillna(-100) print(request.columns) print(time.localtime(tt)) ''' 统计的仍然是pctr,ecpm和bid等的均值信息,用的是前一天的平移过来的pctr等信息,这里的平移的前一天的是早就已经统计好的信息,是日志中的总的均值等信息 找出对应的人群的,每一个广告都有一个dataframe,然后将那个log文件和它merge起来 也就是这个广告对应的竞争队列,取出竞争队列中的前两个,取均值,应该先输出一下竞争队列的那些值是不是已经排好序的 ''' request_list = request['RequestList'].values test_aid = request['ad_id'].values print(len(request_list)) print(len(test_aid)) log_compete = log['competeAd'].values log_reqid = log['RequestId'].values log_posiId = log['PositionId'].values request = [] for i, k in enumerate(log_reqid): s = str(log_reqid[i]) + ',' + str(log_posiId[i]) request.append(s) log_new = pd.DataFrame() log_new['compete'] = log_compete log_new['request'] = np.array(request) uid_len = [] k = 0 test_com_pctr = [] test_quality_ecpm = [] test_total_ecpm = [] test_com_bid = [] test_new_aid = [] using_rate = pd.read_csv('../usingData/feature/total_ad_pctr.csv') every_day_rate = using_rate[using_rate['day'] == 20190423] everyday_aid = every_day_rate['ad_id'].values everyday_bid = every_day_rate['bid'].values everyday_pctr = every_day_rate['pctr'].values everyday_total = every_day_rate['total_ecpm'].values everyday_quality = every_day_rate['quality_ecpm'].values every_bid = {} every_pctr = {} every_total = {} every_quality = {} for i, k in enumerate(everyday_aid): if k not in every_bid: every_bid[k] = everyday_bid[i] every_pctr[k] = everyday_pctr[i] every_total[k] = everyday_total[i] every_quality[k] = everyday_quality[i] every_bid[-1] = 0.0 every_pctr[-1] = 0.0 every_total[-1] = 0.0 every_quality[-1] = 0.0 # 找出每个aid对应的request集合,然后作为一个dataframe,和上面的进行merge,找出其对应竞争队列 for request_l in request_list: tt = time.time() request_i = request_l.split('|') request_new = pd.DataFrame() request_new['request'] = request_i request_new = pd.merge(request_new, log_new, on='request', how='left') # print(request_new) # 这个是竞争队列的集合,每一个都要取前两个,且是没有被屏蔽的 competeAd = request_new['compete'].values def f1(x): xx = x.split(',') t = xx[-1] return t com_pctr = [] quality_ecpm = [] total_ecpm = [] com_bid = [] for list_i in competeAd: if list_i == -100: continue if pd.isna(list_i): continue ads = list_i.split(';') print(type(ads)) index = list(map(f1, ads)) # list(map(deal, ads)) # 找出两个可以用的index index1 = 0 index2 = 0 for i, k in enumerate(index): if (k != 1) & (index1 == 0): index1 = i continue if (k != 1) & (index2 == 0): index2 = i continue if (index1 != 0) & (index2 != 0): break print(index1) print(index2) aid1 = int(ads[index1].split(',')[0]) aid2 = int(ads[index2].split(',')[0]) if aid1 not in every_bid: aid1 = -1 if aid2 not in every_bid: aid2 = -1 temp_bid1 = (every_bid[aid2] + every_bid[aid1]) / 2 temp_pctr1 = (every_pctr[aid2] + every_pctr[aid1]) / 2 temp_qu_ecpm1 = (every_quality[aid2] + every_quality[aid1]) / 2 temp_to_ecpm1 = (every_total[aid2] + every_total[aid1]) / 2 print(temp_bid1) com_bid.append(temp_bid1) com_pctr.append(temp_pctr1) quality_ecpm.append(temp_qu_ecpm1) total_ecpm.append(temp_to_ecpm1) # 直接将取出来的数组,取均值 test_com_pctr.append(np.mean(com_pctr)) test_quality_ecpm.append(np.mean(quality_ecpm)) test_total_ecpm.append(np.mean(total_ecpm)) test_com_bid.append(np.mean(com_bid)) fea_day = pd.DataFrame() fea_day['ad_id'] = test_aid fea_day['yestoday_compete_bid'] = test_com_bid fea_day['yestoday_compete_pctr'] = test_com_pctr fea_day['yestoday_compete_quality_ecpm'] = test_quality_ecpm fea_day['yestoday_compete_total_ecpm'] = test_total_ecpm fea_day.to_csv('../usingData/feature/compete_test.csv', index=False)
/** * Auto-generated action file for "Sage Business Cloud Accounting - Accounts" API. * * Generated at: 2021-04-22T20:49:29.749Z * Mass generator version: 1.0.0 * * : Sage-Accounting-Component * Copyright © 2020, AG * * All files of this connector are licensed under the Apache 2.0 License. For details * see the file LICENSE on the toplevel directory. * * * Operation: 'getJournalCodeTypesKey' * Endpoint Path: '/journal_code_types/{key}' * Method: 'get' * */ // how to pass the transformation function... no need // pass the meta data // create a new Object // emit the message with the new emit function // securities and auth methods // check how to make the new ferryman and its transform functions functional // no need const Swagger = require('swagger-client'); const processWrapper = require('../services/process-wrapper'); const spec = require('../spec.json'); const uuid = require("uuid"); // this wrapers offers a simplified emitData(data) function module.exports = {process: processAction}; // parameter names for this call const PARAMETERS = [ "key", "attributes" ]; // mappings from connector field names to API field names const FIELD_MAP = { "key": "key", "attributes": "attributes" }; function newMessage(body) { const msg = { id: uuid.v4(), attachments: {}, body, headers: {}, metadata: {}, }; return msg; } function processAction(msg, cfg) { var isVerbose = process.env.debug || cfg.verbose; console.log("msg:",msg); console.log("cfg:",cfg) if (isVerbose) { console.log(`---MSG: ${JSON.stringify(msg)}`); console.log(`---CFG: ${JSON.stringify(cfg)}`); console.log(`---ENV: ${JSON.stringify(process.env)}`); } const contentType = undefined; const body = msg.data; mapFieldNames(body); let parameters = {}; for(let param of PARAMETERS) { parameters[param] = body[param]; } const oihUid = msg.metadata !== undefined && msg.metadata.oihUid !== undefined ? msg.metadata.oihUid : 'oihUid not set yet'; const recordUid = msg.metadata !== undefined && msg.metadata.recordUid !== undefined ? msg.metadata.recordUid : undefined; const applicationUid = msg.metadata !== undefined && msg.metadata.applicationUid !== undefined ? msg.metadata.applicationUid : undefined; const newElement = {}; const oihMeta = { applicationUid, oihUid, recordUid, }; // credentials for this operation let securities = {}; if(cfg.otherServer){ if(!spec.servers){ spec.servers = []; } spec.servers.push({"url":cfg.otherServer}) } let callParams = { spec: spec, operationId: 'getJournalCodeTypesKey', pathName: '/journal_code_types/{key}', method: 'get', parameters: parameters, requestContentType: contentType, requestBody: body, securities: {authorized: securities}, server: spec.servers[cfg.server] || cfg.otherServer, }; if(callParams.method === 'get'){ delete callParams.requestBody; } if (isVerbose) { let out = Object.assign({}, callParams); out.spec = '[omitted]'; console.log(`--SWAGGER CALL: ${JSON.stringify(out)}`); } // Call operation via Swagger client return Swagger.execute(callParams).then(data => { // emit a single message with data console.log("swagger data:",data); delete data.uid; newElement.metadata = oihMeta; newElement.data = data.data this.emit("data",newMessage(newElement)); // if the response contains an array of entities, you can emit them one by one: // data.obj.someItems.forEach((item) => { // this.emitData(item); // } }); } function mapFieldNames(obj) { if(Array.isArray(obj)) { obj.forEach(mapFieldNames); } else if(typeof obj === 'object' && obj) { Object.keys(obj).forEach(key => { mapFieldNames(obj[key]); let goodKey = FIELD_MAP[key]; if(goodKey && goodKey !== key) { obj[goodKey] = obj[key]; delete obj[key]; } }); } }
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_conf ------------ Tests for `complexity.conf` module. """ import logging import sys from complexity import conf if sys.version_info[:2] < (2, 7): import unittest2 as unittest else: import unittest # Log debug and above to console logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.DEBUG) class TestConf(unittest.TestCase): def test_read_conf(self): conf_dict = conf.read_conf('tests/conf_proj') logging.debug("read_conf returned {0}".format(conf_dict)) self.assertTrue(conf_dict) self.assertEqual( conf_dict, { 'output_dir': '../www', 'templates_dir': 'templates', 'unexpanded_templates': ['404.html', '500.html'] } ) def test_get_unexpanded_list(self): conf_dict = { 'output_dir': '../www', 'templates_dir': 'templates', 'unexpanded_templates': ['404.html', '500.html'] } self.assertEqual( conf.get_unexpanded_list(conf_dict), ['404.html', '500.html'] ) def test_get_unexpanded_list_empty(self): self.assertEqual(conf.get_unexpanded_list({}), ()) if __name__ == '__main__': unittest.main()
"use strict"; const {strict: assert} = require("assert"); const {stub_templates} = require("../zjsunit/handlebars"); const {mock_cjs, mock_esm, set_global, zrequire, with_overrides} = require("../zjsunit/namespace"); const {run_test} = require("../zjsunit/test"); const $ = require("../zjsunit/zjquery"); const {page_params} = require("../zjsunit/zpage_params"); const ls_container = new Map(); const noop = () => {}; const localStorage = set_global("localStorage", { getItem(key) { return ls_container.get(key); }, setItem(key, val) { ls_container.set(key, val); }, removeItem(key) { ls_container.delete(key); }, clear() { ls_container.clear(); }, }); mock_cjs("jquery", $); const compose_state = mock_esm("../../static/js/compose_state"); mock_esm("../../static/js/markdown", { apply_markdown: noop, }); mock_esm("../../static/js/stream_data", { get_color() { return "#FFFFFF"; }, }); page_params.twenty_four_hour_time = false; const {localstorage} = zrequire("localstorage"); const drafts = zrequire("drafts"); const timerender = zrequire("timerender"); const legacy_draft = { stream: "stream", subject: "lunch", type: "stream", content: "whatever", }; const compose_args_for_legacy_draft = { stream: "stream", topic: "lunch", type: "stream", content: "whatever", }; const draft_1 = { stream: "stream", topic: "topic", type: "stream", content: "Test stream message", }; const draft_2 = { private_message_recipient: "[email protected]", reply_to: "[email protected]", type: "private", content: "Test private message", }; const short_msg = { stream: "stream", subject: "topic", type: "stream", content: "a", }; function test(label, f) { run_test(label, (override) => { localStorage.clear(); f(override); }); } test("legacy", () => { assert.deepEqual(drafts.restore_message(legacy_draft), compose_args_for_legacy_draft); }); test("draft_model add", (override) => { const draft_model = drafts.draft_model; const ls = localstorage(); assert.equal(ls.get("draft"), undefined); override(Date, "now", () => 1); const expected = {...draft_1}; expected.updatedAt = 1; const id = draft_model.addDraft({...draft_1}); assert.deepEqual(draft_model.getDraft(id), expected); }); test("draft_model edit", () => { const draft_model = drafts.draft_model; const ls = localstorage(); assert.equal(ls.get("draft"), undefined); let id; with_overrides((override) => { override(Date, "now", () => 1); const expected = {...draft_1}; expected.updatedAt = 1; id = draft_model.addDraft({...draft_1}); assert.deepEqual(draft_model.getDraft(id), expected); }); with_overrides((override) => { override(Date, "now", () => 2); const expected = {...draft_2}; expected.updatedAt = 2; draft_model.editDraft(id, {...draft_2}); assert.deepEqual(draft_model.getDraft(id), expected); }); }); test("draft_model delete", (override) => { const draft_model = drafts.draft_model; const ls = localstorage(); assert.equal(ls.get("draft"), undefined); override(Date, "now", () => 1); const expected = {...draft_1}; expected.updatedAt = 1; const id = draft_model.addDraft({...draft_1}); assert.deepEqual(draft_model.getDraft(id), expected); draft_model.deleteDraft(id); assert.deepEqual(draft_model.getDraft(id), false); }); test("snapshot_message", (override) => { let curr_draft; function map(field, f) { override(compose_state, field, f); } map("get_message_type", () => curr_draft.type); map("composing", () => Boolean(curr_draft.type)); map("message_content", () => curr_draft.content); map("stream_name", () => curr_draft.stream); map("topic", () => curr_draft.topic); map("private_message_recipient", () => curr_draft.private_message_recipient); curr_draft = draft_1; assert.deepEqual(drafts.snapshot_message(), draft_1); curr_draft = draft_2; assert.deepEqual(drafts.snapshot_message(), draft_2); curr_draft = short_msg; assert.deepEqual(drafts.snapshot_message(), undefined); curr_draft = {}; assert.equal(drafts.snapshot_message(), undefined); }); test("initialize", (override) => { window.addEventListener = (event_name, f) => { assert.equal(event_name, "beforeunload"); let called = false; override(drafts, "update_draft", () => { called = true; }); f(); assert(called); }; drafts.initialize(); }); test("remove_old_drafts", () => { const draft_3 = { stream: "stream", subject: "topic", type: "stream", content: "Test stream message", updatedAt: Date.now(), }; const draft_4 = { private_message_recipient: "[email protected]", reply_to: "[email protected]", type: "private", content: "Test private message", updatedAt: new Date().setDate(-30), }; const draft_model = drafts.draft_model; const ls = localstorage(); const data = {id3: draft_3, id4: draft_4}; ls.set("drafts", data); assert.deepEqual(draft_model.get(), data); drafts.remove_old_drafts(); assert.deepEqual(draft_model.get(), {id3: draft_3}); }); test("format_drafts", (override) => { override(drafts, "remove_old_drafts", noop); function feb12() { return new Date(1549958107000); // 2/12/2019 07:55:07 AM (UTC+0) } function date(offset) { return feb12().setDate(offset); } const draft_1 = { stream: "stream", topic: "topic", type: "stream", content: "Test stream message", updatedAt: feb12().getTime(), }; const draft_2 = { private_message_recipient: "[email protected]", reply_to: "[email protected]", type: "private", content: "Test private message", updatedAt: date(-1), }; const draft_3 = { stream: "stream 2", subject: "topic", type: "stream", content: "Test stream message 2", updatedAt: date(-10), }; const draft_4 = { private_message_recipient: "[email protected]", reply_to: "[email protected]", type: "private", content: "Test private message 2", updatedAt: date(-5), }; const draft_5 = { private_message_recipient: "[email protected]", reply_to: "[email protected]", type: "private", content: "Test private message 3", updatedAt: date(-2), }; const expected = [ { draft_id: "id1", is_stream: true, stream: "stream", stream_color: "#FFFFFF", dark_background: "", topic: "topic", raw_content: "Test stream message", time_stamp: "7:55 AM", }, { draft_id: "id2", is_stream: false, recipients: "[email protected]", raw_content: "Test private message", time_stamp: "Jan 30", }, { draft_id: "id5", is_stream: false, recipients: "[email protected]", raw_content: "Test private message 3", time_stamp: "Jan 29", }, { draft_id: "id4", is_stream: false, recipients: "[email protected]", raw_content: "Test private message 2", time_stamp: "Jan 26", }, { draft_id: "id3", is_stream: true, stream: "stream 2", stream_color: "#FFFFFF", dark_background: "", topic: "topic", raw_content: "Test stream message 2", time_stamp: "Jan 21", }, ]; $("#drafts_table").append = noop; const draft_model = drafts.draft_model; const ls = localstorage(); const data = {id1: draft_1, id2: draft_2, id3: draft_3, id4: draft_4, id5: draft_5}; ls.set("drafts", data); assert.deepEqual(draft_model.get(), data); const stub_render_now = timerender.render_now; override(timerender, "render_now", (time) => stub_render_now(time, new Date(1549958107000))); stub_templates((template_name, data) => { assert.equal(template_name, "draft_table_body"); // Tests formatting and sorting of drafts assert.deepEqual(data.drafts, expected); return "<draft table stub>"; }); override(drafts, "open_overlay", noop); override(drafts, "set_initial_element", noop); $.create("#drafts_table .draft-row", {children: []}); drafts.launch(); timerender.__Rewire__("render_now", stub_render_now); });
/* * name; */ var BevelSmallEnemy = (function (_super) { function BevelSmallEnemy() { } Laya.class(BevelSmallEnemy, "BevelSmallEnemy", _super); var _proto = BevelSmallEnemy.prototype; // 类名 _proto.className = 'BevelSmallEnemy'; // 动画前缀 _proto.aniPre = 'bevelSmallEnemy_'; // 宽度体型修正 _proto.widthFix = 5; // 高度体型修正 _proto.heightFix = 10; // 默认最大生命值 _proto.maxHp = 2; /** * 初始化 */ _proto.init = function(opts) { this.enemyType = opts.enemyType + '_'; _super.call(this, opts); _super.prototype.init.call(this, opts); opts = opts || {}; this.vy = opts.vy || 2.5; this.vx = opts.vx || 0; this.score = opts.score || 5; } /** * 被攻击时触发 * from: 攻击源 */ _proto.hitBy = function(from) { this.hp -= from.atk; if (this.bar) { this.bar.setValue(this.hp); } switch (this.state) { case this.stateEnum.ALIVE: case this.stateEnum.HURT: if(this.hp > 0){ this.state = this.stateEnum.HURT; GameHolder.increaseScore(GameConfig.HIT_SCORE); } else { this.state = this.stateEnum.DEATH; this.playAction('down'); GameHolder.increaseScore(this.score); } break; case this.stateEnum.DEATH: break; default: console.error('未知的敌机状态:', this.state); } } /** * 播放动画 */ _proto.playAction = function(action){ this.action = action; this.body.play(0, true, this.aniPre + this.enemyType +this.action); //获取动画大小区域t this.bound = this.body.getBounds(); //设置机身居中 this.body.pos(-this.bound.width/2, -this.bound.height/2); } _proto.attack = function() { } _proto.move = function() { if (this.state != this.stateEnum.DEATH) this.y += this.vy; this.x += this.vx; } return BevelSmallEnemy; }(Enemy));
/* eslint no-fallthrough: 0 */ import dateMath from 'date-arithmetic'; import assign from 'lodash/assign'; import localizer from '../localizer'; import { directions } from './constants'; const MILLI = { seconds: 1000, minutes: 1000 * 60, hours: 1000 * 60 * 60, day: 1000 * 60 * 60 * 24 }; let dates = assign(dateMath, { monthsInYear(year) { let months = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], date = new Date(year, 0, 1); return months.map(i => dates.month(date, i)); }, firstVisibleDay(date, culture) { let firstOfMonth = dates.startOf(date, 'month'); return dates.startOf(firstOfMonth, 'week', localizer.startOfWeek(culture)); }, lastVisibleDay(date, culture) { let endOfMonth = dates.endOf(date, 'month'); return dates.endOf(endOfMonth, 'week', localizer.startOfWeek(culture)); }, visibleDays(date, culture) { let current = dates.firstVisibleDay(date, culture), last = dates.lastVisibleDay(date, culture), days = []; while (dates.lte(current, last, 'day')) { days.push(current); current = dates.add(current, 1, 'day'); } return days; }, ceil(date, unit) { let floor = dates.startOf(date, unit); return dates.eq(floor, date) ? floor : dates.add(floor, 1, unit); }, move(date, min, max, unit, direction) { let isUpOrDown = direction === directions.UP || direction === directions.DOWN, addUnit = isUpOrDown ? 'week' : 'day', amount = isUpOrDown ? 4 : 1, newDate; if (direction === directions.UP || direction === directions.LEFT) amount *= -1; newDate = dates.add(date, amount, addUnit); return dates.inRange(newDate, min, max, 'day') ? newDate : date; }, range(start, end, unit = 'day') { let current = start, days = []; while (dates.lte(current, end, unit)) { days.push(current); current = dates.add(current, 1, unit); } return days; }, merge(date, time) { if (time == null && date == null) return null; if (time == null) time = new Date(); if (date == null) date = new Date(); date = dates.startOf(date, 'day'); date = dates.hours(date, dates.hours(time)); date = dates.minutes(date, dates.minutes(time)); date = dates.seconds(date, dates.seconds(time)); return dates.milliseconds(date, dates.milliseconds(time)); }, sameMonth(dateA, dateB) { return dates.eq(dateA, dateB, 'month'); }, isSameDate(dateA, dateB) { return dates.eq(dateA, dateB, 'month') && dates.eq(dateA, dateB, 'day') && dates.eq(dateA, dateB, 'year'); }, eqTime(dateA, dateB) { return ( dates.hours(dateA) === dates.hours(dateB) && dates.minutes(dateA) === dates.minutes(dateB) && dates.seconds(dateA) === dates.seconds(dateB) ); }, isJustDate(date) { return ( dates.hours(date) === 0 && dates.minutes(date) === 0 && dates.seconds(date) === 0 && dates.milliseconds(date) === 0 ); }, duration(start, end, unit, firstOfWeek) { if (unit === 'day') unit = 'date'; return Math.abs(dates[unit](start, undefined, firstOfWeek) - dates[unit](end, undefined, firstOfWeek)); }, diff(dateA, dateB, unit) { if (!unit) return Math.abs(+dateA - +dateB); // the .round() handles an edge case // with DST where the total won't be exact // since one day in the range may be shorter/longer by an hour return Math.round( Math.abs(+dates.startOf(dateA, unit) / MILLI[unit] - +dates.startOf(dateB, unit) / MILLI[unit]) ); }, total(date, unit) { let ms = date.getTime(), div = 1; switch (unit) { case 'week': div *= 7; case 'day': div *= 24; case 'hours': div *= 60; case 'minutes': div *= 60; case 'seconds': div *= 1000; } return ms / div; }, week(date) { let d = new Date(date); d.setHours(0, 0, 0); d.setDate(d.getDate() + 4 - (d.getDay() || 7)); return Math.ceil(((d - new Date(d.getFullYear(), 0, 1)) / 8.64e7 + 1) / 7); }, today() { return dates.startOf(new Date(), 'day'); }, yesterday() { return dates.add(dates.startOf(new Date(), 'day'), -1, 'day'); }, tomorrow() { return dates.add(dates.startOf(new Date(), 'day'), 1, 'day'); } }); export default dates;
/** * CHAT COMPONENT * They are formed by chatController.js chatView.js, chat.js and textProcessor.js * The chat module needs for work OTHelper.js and browser_utils.js * If you want to have the previous status and roomStatus at your connection you need * roomStatus.js too * INCOMING events: outside events that the module will listen for * You could change their default name calling init method with the appropiated variable * (explained later) * - updatedRemotely: This action should be fired to load the history of the chat (previous * messages to our connection) * Default value: roomStatus:updatedRemotely * - chatVisibility: This action should be fired to change the status (visible or hidden) * of the chat. * Default value: roomView:chatVisibility * * OUTGOING events: events that will be fired by the module * - incomingMessage: A new message has been received * NAME: chatController:incomingMessage * - presenceEvent: A new event has been received. A event could be that a new user has * connected or disconnected. * Name: chatController:presenceEvent * - messageDelivered: A message has been sended * Name: chatController:messageDelivered * - outgoingMessage: A message has been sended * name: chatView:outgoingMessage * - hidden: it will be fired when the chat has been hidden * name: chat:hidden * - unreadMessage: There was received a message while the chat was hidden * name: chatView:unreadMessage * * * ----------------- * roomStatus:updatedRemotely | | * ---------------------------------------->| | * chatController:MessageDelivered | | * <-------------------------------------*--| | * chatController:incomingMessage | | ChatController | * <-----------------------------------*-)--| | * chatController:presenceEvent | | | | * <---------------------------------*-)-)--| | * --)-)-)->| | * | | | | | | * | | | | ----------------- * | | | | * | | | | ----------------- * | | | -->| | * | | ---->| | * | ------>| | * chatView:outgoingMessage | | | * <-------------------------------*--------| ChatView | * chatView:unreadMessage | | * <----------------------------------------| | * roomView:chatVisibility | | * ---------------------------------------->| | * ----------------- * * chat:hidden ----------------- * <----------------------------------------| Chat | * ----------------- * */ !(function(exports) { 'use strict'; var _hasStatus; var debug = new Utils.MultiLevelLogger('chatController.js', Utils.MultiLevelLogger.DEFAULT_LEVELS.all); // Contains an object foreach action. // This enables to configure the name of the received event. // The object key is the type of event which is waiting for // Each action has: // - name: (mandatory) event name which is going to be listen for // - handler: (mandatory) function which is going to be executed as respond of the event // - target: (optional) who is listening for the event. It'll be global if it is not specified. // - couldBeChanged: we only allow to modify the event's name of the event that come from the // outside (e.g.: roomView:chatVisibility and roomStatus:updatedRemotely). // We don't allow to change the event's name originating inside the chat module // whether it'll be listened for in other module's component // (e.g. chatView:outgoingMessage) var eventsIn; var _historyChat; var CONN_TEXT = '(has connected)'; var DISCONN_TEXT = '(left the room)'; var STATUS_KEY = 'chat'; function loadHistoryChat() { if (!_hasStatus) { return; } var data = RoomStatus.get(STATUS_KEY); if (data) { _historyChat = data; for (var i = 0, l = _historyChat.length; i < l; i++) { Utils.sendEvent('chatController:incomingMessage', { data: _historyChat[i] }); } } else { _historyChat = []; RoomStatus.set(STATUS_KEY, _historyChat); } } var otHelper; var _chatHandlers = { 'signal:chat': function(evt) { // A signal of the specified type was received from the session. The // SignalEvent class defines this event object. It includes the following // properties: // data — (String) The data string sent with the signal. // from — (Connection) The Connection corresponding to the client that // sent with the signal. // type — (String) The type assigned to the signal (if there is one). var data = JSON.parse(evt.data); _historyChat.push(data); Utils.sendEvent('chatController:incomingMessage', { data: data }); }, connectionCreated: function(evt) { // Dispatched when an new client (including your own) has connected to the // session, and for every client in the session when you first connect // Session object also dispatches a sessionConnected evt when your local // client connects var newUsrName = JSON.parse(evt.connection.data).userName; if (!this.isMyself(evt.connection)) { Utils.sendEvent('chatController:presenceEvent', { userName: newUsrName, text: CONN_TEXT }); } else { otHelper = this; } }, connectionDestroyed: function(evt) { Utils.sendEvent('chatController:presenceEvent', { userName: JSON.parse(evt.connection.data).userName, text: DISCONN_TEXT }); } }; /** * Send the event received as a message */ function sendMsg(evt) { var data = evt.detail; return otHelper.sendSignal('chat', data) .then(function() { Utils.sendEvent('chatController:messageDelivered'); }).catch(function(error) { debug.error('Error sending [', data.text.value, '] to the group. ', error.message); }); } /** * It receives an array of objects or an object with the handlers to be set on OT.session */ function addOTHandlers(aAllHandlers) { if (!Array.isArray(aAllHandlers)) { aAllHandlers = [aAllHandlers]; } aAllHandlers.push(_chatHandlers); return aAllHandlers; } /** * Set the listener for the application custom events. If receives an array * with the new name for the event and it exists here change its name */ function addEventsHandlers(aEvents) { Array.isArray(aEvents) && aEvents.forEach(function(aEvt) { var event = eventsIn[aEvt.type]; event && event.couldBeChanged && (event.name = aEvt.name); }); Utils.addHandlers(eventsIn); } function init(aRoomName, aUsrId, aGlobalHandlers, listenedEvts) { return LazyLoader.dependencyLoad([ '/js/chatView.js' ]).then(function() { eventsIn = { updatedRemotely: { name: 'roomStatus:updatedRemotely', handler: loadHistoryChat, couldBeChanged: true }, outgoingMessage: { name: 'chatView:outgoingMessage', handler: sendMsg } }; _historyChat = []; _hasStatus = (exports.RoomStatus !== undefined); return ChatView.init(aUsrId, aRoomName, listenedEvts) .then(function() { _hasStatus && RoomStatus.set(STATUS_KEY, _historyChat); addEventsHandlers(listenedEvts); return addOTHandlers(aGlobalHandlers); }); }); } exports.ChatController = { init: init }; }(this));
import { ActionTypes } from '../../constants'; const { Sides } = require('../../constants'); export const createGame = async (roomCode, Room) => { try { const game = Room.findOne({ roomCode }) .then(room => room.createGame()) .then(room => { const newGame = room.games[room.games.length - 1]; room.addAction({ type: ActionTypes.NEW_GAME, gameId: newGame.id }); return newGame; }) .catch(e => { console.error(e); return null; }); if (game === null) { throw new Error(`Could not create game in room ${roomCode}`); } return { code: 200, success: true, message: 'Created game', game, }; } catch (e) { return { code: 500, success: false, message: e.toString(), }; } }; export const endTurn = async (name, roomCode, Room) => { try { const game = await Room.findOne( { roomCode }, { games: { $slice: -1 }, players: { $elemMatch: { name } }, actions: 1 } ) .then(room => { const { players: [playerEndingTurn], games: [currentGame], } = room; if (playerEndingTurn.side !== currentGame.turn) { throw new Error(); } currentGame.turn = currentGame.turn === Sides.RED ? Sides.BLUE : Sides.RED; return room .save() .then(() => room.addAction({ type: ActionTypes.END_TURN, playerName: name, playerSide: playerEndingTurn.side, }) ) .then(() => currentGame); }) .catch(e => { console.error(e); return null; }); if (game === null) { throw new Error(`Could not end turn of player ${name} of room ${roomCode}`); } return { code: '200', success: true, message: 'Ended turn', game, }; } catch (e) { return { code: '500', success: false, message: e.toString(), }; } };
from tkinter import * window = Tk() window.title("Find the smallest number") window.geometry("400x300+20+10") def findSmallest(): number = [] number.append(eval(conOfent2.get())) number.append(eval(conOfent3.get())) number.append(eval(conOfent4.get())) smallestNumber.set(min(number)) lbl1 = Label(window, text = "A program that finds the smallest number") lbl1.grid(row=0, column=1, columnspan=2,sticky=EW) lbl2 = Label(window,text = "Enter the first number:") lbl2.grid(row=1, column = 0,sticky=W) conOfent2 = StringVar() ent2 = Entry(window,bd=3,textvariable=conOfent2) ent2.grid(row=1, column = 1) lbl3 = Label(window,text = "Enter the second number:") lbl3.grid(row=2, column=0) conOfent3=StringVar() ent3 = Entry(window,bd=3,textvariable=conOfent3) ent3.grid(row=2,column=1) lbl4 = Label(window,text="Enter the third number:") lbl4.grid(row=3,column =0, sticky=W) conOfent4 = StringVar() ent4 = Entry(window,bd=3,textvariable=conOfent4) ent4.grid(row=3, column=1) btn1 = Button(window,text = "Find Smallest Number",command=findSmallest) btn1.grid(row=4, column = 1) lbl5 = Label(window,text="The smallest number:") lbl5.grid(row=5,column=0,sticky=W) smallestNumber = StringVar() ent5 = Entry(window,bd=3,state="readonly",textvariable=smallestNumber) ent5.grid(row=5,column=1) mainloop()
import axios from 'axios'; // This is a public key... not very reliable const weather_API = 'bf1210455c4549380c43122b3b1e4dcc'; const rootURL = `http://api.openweathermap.org/data/2.5/forecast?appid=${weather_API}`; // ES6 syntax /* api.openweathermap.org/data/2.5/forecast?q={city name},{country code} api.openweathermap.org/data/2.5/forecast?q=London,us&mode=xml http://samples.openweathermap.org/data/2.5/forecast?q=London,us&mode=xml&appid=b6907d289e10d714a6e88b30761fae22 */ // Define action types as constants export const FETCH_WEATHER = 'FETCH_WEATHER'; export function fetchWeather(cityName) { const url = `${rootURL}&q=${cityName},us`; // We're making the country code static US const request = axios.get(url); // This is async. The action only gets created on promise resolve // axios - Promise based HTTP client for the browser and node.js return { type: FETCH_WEATHER, payload: request } }
import { AcquisitionManager as Sdk } from "code-push/script/acquisition-sdk"; import { Alert } from "./AlertAdapter"; import requestFetchAdapter from "./request-fetch-adapter"; import { Platform } from "react-native"; let NativeCodePush = require("react-native").NativeModules.CodePush; const PackageMixins = require("./package-mixins")(NativeCodePush); async function checkForUpdate(deploymentKey = null) { /* * Before we ask the server if an update exists, we * need to retrieve three pieces of information from the * native side: deployment key, app version (e.g. 1.0.1) * and the hash of the currently running update (if there is one). * This allows the client to only receive updates which are targetted * for their specific deployment and version and which are actually * different from the CodePush update they have already installed. */ const nativeConfig = await getConfiguration(); /* * If a deployment key was explicitly provided, * then let's override the one we retrieved * from the native-side of the app. This allows * dynamically "redirecting" end-users at different * deployments (e.g. an early access deployment for insiders). */ const config = deploymentKey ? { ...nativeConfig, ...{ deploymentKey } } : nativeConfig; const sdk = getPromisifiedSdk(requestFetchAdapter, config); // Use dynamically overridden getCurrentPackage() during tests. const localPackage = await module.exports.getCurrentPackage(); /* * If the app has a previously installed update, and that update * was targetted at the same app version that is currently running, * then we want to use its package hash to determine whether a new * release has been made on the server. Otherwise, we only need * to send the app version to the server, since we are interested * in any updates for current app store version, regardless of hash. */ let queryPackage; if (localPackage) { queryPackage = localPackage; } else { queryPackage = { appVersion: config.appVersion }; if (Platform.OS === "ios" && config.packageHash) { queryPackage.packageHash = config.packageHash; } } const update = await sdk.queryUpdateWithCurrentPackage(queryPackage); /* * There are four cases where checkForUpdate will resolve to null: * ---------------------------------------------------------------- * 1) The server said there isn't an update. This is the most common case. * 2) The server said there is an update but it requires a newer binary version. * This would occur when end-users are running an older app store version than * is available, and CodePush is making sure they don't get an update that * potentially wouldn't be compatible with what they are running. * 3) The server said there is an update, but the update's hash is the same as * the currently running update. This should _never_ happen, unless there is a * bug in the server, but we're adding this check just to double-check that the * client app is resilient to a potential issue with the update check. * 4) The server said there is an update, but the update's hash is the same as that * of the binary's currently running version. This should only happen in Android - * unlike iOS, we don't attach the binary's hash to the updateCheck request * because we want to avoid having to install diff updates against the binary's * version, which we can't do yet on Android. */ if (!update || update.updateAppVersion || localPackage && (update.packageHash === localPackage.packageHash) || (!localPackage || localPackage._isDebugOnly) && config.packageHash === update.packageHash) { if (update && update.updateAppVersion) { log("An update is available but it is targeting a newer binary version than you are currently running."); } return null; } else { const remotePackage = { ...update, ...PackageMixins.remote(sdk.reportStatusDownload) }; remotePackage.failedInstall = await NativeCodePush.isFailedUpdate(remotePackage.packageHash); remotePackage.deploymentKey = deploymentKey || nativeConfig.deploymentKey; return remotePackage; } } const getConfiguration = (() => { let config; return async function getConfiguration() { if (config) { return config; } else if (testConfig) { return testConfig; } else { config = await NativeCodePush.getConfiguration(); return config; } } })(); async function getCurrentPackage() { return await getUpdateMetadata(CodePush.UpdateState.LATEST); } async function getUpdateMetadata(updateState) { const updateMetadata = await NativeCodePush.getUpdateMetadata(updateState || CodePush.UpdateState.RUNNING); if (updateMetadata) { updateMetadata.failedInstall = await NativeCodePush.isFailedUpdate(updateMetadata.packageHash); updateMetadata.isFirstRun = await NativeCodePush.isFirstRun(updateMetadata.packageHash); } return updateMetadata; } function getPromisifiedSdk(requestFetchAdapter, config) { // Use dynamically overridden AcquisitionSdk during tests. const sdk = new module.exports.AcquisitionSdk(requestFetchAdapter, config); sdk.queryUpdateWithCurrentPackage = (queryPackage) => { return new Promise((resolve, reject) => { module.exports.AcquisitionSdk.prototype.queryUpdateWithCurrentPackage.call(sdk, queryPackage, (err, update) => { if (err) { reject(err); } else { resolve(update); } }); }); }; sdk.reportStatusDeploy = (deployedPackage, status, previousLabelOrAppVersion, previousDeploymentKey) => { return new Promise((resolve, reject) => { module.exports.AcquisitionSdk.prototype.reportStatusDeploy.call(sdk, deployedPackage, status, previousLabelOrAppVersion, previousDeploymentKey, (err) => { if (err) { reject(err); } else { resolve(); } }); }); }; sdk.reportStatusDownload = (downloadedPackage) => { return new Promise((resolve, reject) => { module.exports.AcquisitionSdk.prototype.reportStatusDownload.call(sdk, downloadedPackage, (err) => { if (err) { reject(err); } else { resolve(); } }); }); }; return sdk; } /* Logs messages to console with the [CodePush] prefix */ function log(message) { console.log(`[CodePush] ${message}`) } // This ensures that notifyApplicationReadyInternal is only called once // in the lifetime of this module instance. const notifyApplicationReady = (() => { let notifyApplicationReadyPromise; return () => { if (!notifyApplicationReadyPromise) { notifyApplicationReadyPromise = notifyApplicationReadyInternal(); } return notifyApplicationReadyPromise; }; })(); async function notifyApplicationReadyInternal() { await NativeCodePush.notifyApplicationReady(); const statusReport = await NativeCodePush.getNewStatusReport(); if (statusReport) { const config = await getConfiguration(); const previousLabelOrAppVersion = statusReport.previousLabelOrAppVersion; const previousDeploymentKey = statusReport.previousDeploymentKey || config.deploymentKey; if (statusReport.appVersion) { const sdk = getPromisifiedSdk(requestFetchAdapter, config); sdk.reportStatusDeploy(/* deployedPackage */ null, /* status */ null, previousLabelOrAppVersion, previousDeploymentKey); } else { config.deploymentKey = statusReport.package.deploymentKey; const sdk = getPromisifiedSdk(requestFetchAdapter, config); sdk.reportStatusDeploy(statusReport.package, statusReport.status, previousLabelOrAppVersion, previousDeploymentKey); } } } function restartApp(onlyIfUpdateIsPending = false) { NativeCodePush.restartApp(onlyIfUpdateIsPending); } var testConfig; // This function is only used for tests. Replaces the default SDK, configuration and native bridge function setUpTestDependencies(testSdk, providedTestConfig, testNativeBridge) { if (testSdk) module.exports.AcquisitionSdk = testSdk; if (providedTestConfig) testConfig = providedTestConfig; if (testNativeBridge) NativeCodePush = testNativeBridge; } // This function allows only one syncInternal operation to proceed at any given time. // Parallel calls to sync() while one is ongoing yields CodePush.SyncStatus.SYNC_IN_PROGRESS. const sync = (() => { let syncInProgress = false; const setSyncCompleted = () => { syncInProgress = false; }; return (options = {}, syncStatusChangeCallback, downloadProgressCallback) => { if (syncInProgress) { typeof syncStatusChangeCallback === "function" ? syncStatusChangeCallback(CodePush.SyncStatus.SYNC_IN_PROGRESS) : log("Sync already in progress."); return Promise.resolve(CodePush.SyncStatus.SYNC_IN_PROGRESS); } syncInProgress = true; const syncPromise = syncInternal(options, syncStatusChangeCallback, downloadProgressCallback); syncPromise .then(setSyncCompleted) .catch(setSyncCompleted); return syncPromise; }; })(); /* * The syncInternal method provides a simple, one-line experience for * incorporating the check, download and installation of an update. * * It simply composes the existing API methods together and adds additional * support for respecting mandatory updates, ignoring previously failed * releases, and displaying a standard confirmation UI to the end-user * when an update is available. */ async function syncInternal(options = {}, syncStatusChangeCallback, downloadProgressCallback) { let resolvedInstallMode; const syncOptions = { deploymentKey: null, ignoreFailedUpdates: true, installMode: CodePush.InstallMode.ON_NEXT_RESTART, mandatoryInstallMode: CodePush.InstallMode.IMMEDIATE, minimumBackgroundDuration: 0, updateDialog: null, ...options }; syncStatusChangeCallback = typeof syncStatusChangeCallback === "function" ? syncStatusChangeCallback : (syncStatus) => { switch(syncStatus) { case CodePush.SyncStatus.CHECKING_FOR_UPDATE: log("Checking for update."); break; case CodePush.SyncStatus.AWAITING_USER_ACTION: log("Awaiting user action."); break; case CodePush.SyncStatus.DOWNLOADING_PACKAGE: log("Downloading package."); break; case CodePush.SyncStatus.INSTALLING_UPDATE: log("Installing update."); break; case CodePush.SyncStatus.UP_TO_DATE: log("App is up to date."); break; case CodePush.SyncStatus.UPDATE_IGNORED: log("User cancelled the update."); break; case CodePush.SyncStatus.UPDATE_INSTALLED: /* * If the install mode is IMMEDIATE, this will not get returned as the * app will be restarted to a new Javascript context. */ if (resolvedInstallMode == CodePush.InstallMode.ON_NEXT_RESTART) { log("Update is installed and will be run on the next app restart."); } else { if (syncOptions.minimumBackgroundDuration > 0) { log(`Update is installed and will be run after the app has been in the background for at least ${syncOptions.minimumBackgroundDuration} seconds.`); } else { log("Update is installed and will be run when the app next resumes."); } } break; case CodePush.SyncStatus.UNKNOWN_ERROR: log("An unknown error occurred."); break; } }; downloadProgressCallback = typeof downloadProgressCallback === "function" ? downloadProgressCallback : (downloadProgress) => { log(`Expecting ${downloadProgress.totalBytes} bytes, received ${downloadProgress.receivedBytes} bytes.`); }; try { await CodePush.notifyApplicationReady(); syncStatusChangeCallback(CodePush.SyncStatus.CHECKING_FOR_UPDATE); const remotePackage = await checkForUpdate(syncOptions.deploymentKey); const doDownloadAndInstall = async () => { syncStatusChangeCallback(CodePush.SyncStatus.DOWNLOADING_PACKAGE); const localPackage = await remotePackage.download(downloadProgressCallback); // Determine the correct install mode based on whether the update is mandatory or not. resolvedInstallMode = localPackage.isMandatory ? syncOptions.mandatoryInstallMode : syncOptions.installMode; syncStatusChangeCallback(CodePush.SyncStatus.INSTALLING_UPDATE); await localPackage.install(resolvedInstallMode, syncOptions.minimumBackgroundDuration, () => { syncStatusChangeCallback(CodePush.SyncStatus.UPDATE_INSTALLED); }); return CodePush.SyncStatus.UPDATE_INSTALLED; }; const updateShouldBeIgnored = remotePackage && (remotePackage.failedInstall && syncOptions.ignoreFailedUpdates); if (!remotePackage || updateShouldBeIgnored) { if (updateShouldBeIgnored) { log("An update is available, but it is being ignored due to having been previously rolled back."); } syncStatusChangeCallback(CodePush.SyncStatus.UP_TO_DATE); return CodePush.SyncStatus.UP_TO_DATE; } else if (syncOptions.updateDialog) { // updateDialog supports any truthy value (e.g. true, "goo", 12), // but we should treat a non-object value as just the default dialog if (typeof syncOptions.updateDialog !== "object") { syncOptions.updateDialog = CodePush.DEFAULT_UPDATE_DIALOG; } else { syncOptions.updateDialog = { ...CodePush.DEFAULT_UPDATE_DIALOG, ...syncOptions.updateDialog }; } return await new Promise((resolve, reject) => { let message = null; const dialogButtons = [{ text: null, onPress: async () => { resolve(await doDownloadAndInstall()); } }]; if (remotePackage.isMandatory) { message = syncOptions.updateDialog.mandatoryUpdateMessage; dialogButtons[0].text = syncOptions.updateDialog.mandatoryContinueButtonLabel; } else { message = syncOptions.updateDialog.optionalUpdateMessage; dialogButtons[0].text = syncOptions.updateDialog.optionalInstallButtonLabel; // Since this is an optional update, add another button // to allow the end-user to ignore it dialogButtons.push({ text: syncOptions.updateDialog.optionalIgnoreButtonLabel, onPress: () => { syncStatusChangeCallback(CodePush.SyncStatus.UPDATE_IGNORED); resolve(CodePush.SyncStatus.UPDATE_IGNORED); } }); } // If the update has a description, and the developer // explicitly chose to display it, then set that as the message if (syncOptions.updateDialog.appendReleaseDescription && remotePackage.description) { message += `${syncOptions.updateDialog.descriptionPrefix} ${remotePackage.description}`; } syncStatusChangeCallback(CodePush.SyncStatus.AWAITING_USER_ACTION); Alert.alert(syncOptions.updateDialog.title, message, dialogButtons); }); } else { return await doDownloadAndInstall(); } } catch (error) { syncStatusChangeCallback(CodePush.SyncStatus.UNKNOWN_ERROR); log(error.message); throw error; } }; let CodePush; // If the "NativeCodePush" variable isn't defined, then // the app didn't properly install the native module, // and therefore, it doesn't make sense initializing // the JS interface when it wouldn't work anyways. if (NativeCodePush) { CodePush = { AcquisitionSdk: Sdk, checkForUpdate, getConfiguration, getCurrentPackage, getUpdateMetadata, log, notifyAppReady: notifyApplicationReady, notifyApplicationReady, restartApp, setUpTestDependencies, sync, InstallMode: { IMMEDIATE: NativeCodePush.codePushInstallModeImmediate, // Restart the app immediately ON_NEXT_RESTART: NativeCodePush.codePushInstallModeOnNextRestart, // Don't artificially restart the app. Allow the update to be "picked up" on the next app restart ON_NEXT_RESUME: NativeCodePush.codePushInstallModeOnNextResume // Restart the app the next time it is resumed from the background }, SyncStatus: { CHECKING_FOR_UPDATE: 0, AWAITING_USER_ACTION: 1, DOWNLOADING_PACKAGE: 2, INSTALLING_UPDATE: 3, UP_TO_DATE: 4, // The running app is up-to-date UPDATE_IGNORED: 5, // The app had an optional update and the end-user chose to ignore it UPDATE_INSTALLED: 6, // The app had an optional/mandatory update that was successfully downloaded and is about to be installed. SYNC_IN_PROGRESS: 7, // There is an ongoing "sync" operation in progress. UNKNOWN_ERROR: -1 }, UpdateState: { RUNNING: NativeCodePush.codePushUpdateStateRunning, PENDING: NativeCodePush.codePushUpdateStatePending, LATEST: NativeCodePush.codePushUpdateStateLatest }, DEFAULT_UPDATE_DIALOG: { appendReleaseDescription: false, descriptionPrefix: " Description: ", mandatoryContinueButtonLabel: "Continue", mandatoryUpdateMessage: "An update is available that must be installed.", optionalIgnoreButtonLabel: "Ignore", optionalInstallButtonLabel: "Install", optionalUpdateMessage: "An update is available. Would you like to install it?", title: "Update available" } }; } else { log("The CodePush module doesn't appear to be properly installed. Please double-check that everything is setup correctly."); } module.exports = CodePush;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SortNumberFormatted = exports.GetYear = exports.DownloadFileFromResponse = exports.ParseFormData = exports.IsKsaMobile = exports.ToNumberFormat = exports.FromNumberFormat = exports.ParseArabicNumber = exports.ArabicNumbersMap = exports.createAuthStorage = void 0; var src_1 = require("./src"); Object.defineProperty(exports, "ArabicNumbersMap", { enumerable: true, get: function () { return src_1.ArabicNumbersMap; } }); Object.defineProperty(exports, "createAuthStorage", { enumerable: true, get: function () { return src_1.createAuthStorage; } }); Object.defineProperty(exports, "DownloadFileFromResponse", { enumerable: true, get: function () { return src_1.DownloadFileFromResponse; } }); Object.defineProperty(exports, "FromNumberFormat", { enumerable: true, get: function () { return src_1.FromNumberFormat; } }); Object.defineProperty(exports, "GetYear", { enumerable: true, get: function () { return src_1.GetYear; } }); Object.defineProperty(exports, "IsKsaMobile", { enumerable: true, get: function () { return src_1.IsKsaMobile; } }); Object.defineProperty(exports, "ParseArabicNumber", { enumerable: true, get: function () { return src_1.ParseArabicNumber; } }); Object.defineProperty(exports, "ParseFormData", { enumerable: true, get: function () { return src_1.ParseFormData; } }); Object.defineProperty(exports, "SortNumberFormatted", { enumerable: true, get: function () { return src_1.SortNumberFormatted; } }); Object.defineProperty(exports, "ToNumberFormat", { enumerable: true, get: function () { return src_1.ToNumberFormat; } }); module.exports = { createAuthStorage: src_1.createAuthStorage, ArabicNumbersMap: src_1.ArabicNumbersMap, ParseArabicNumber: src_1.ParseArabicNumber, FromNumberFormat: src_1.FromNumberFormat, ToNumberFormat: src_1.ToNumberFormat, IsKsaMobile: src_1.IsKsaMobile, ParseFormData: src_1.ParseFormData, DownloadFileFromResponse: src_1.DownloadFileFromResponse, // HijriYear, // HijriMonth, // HijriDay, // TodayDate, // TodayTime, GetYear: src_1.GetYear, SortNumberFormatted: src_1.SortNumberFormatted, };
import { __decorate } from "tslib"; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { NotFoundComponent } from './not-found.component'; const routes = [ { path: '', component: NotFoundComponent } ]; let NotFoundRoutingModule = class NotFoundRoutingModule { }; NotFoundRoutingModule = __decorate([ NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) ], NotFoundRoutingModule); export { NotFoundRoutingModule }; //# sourceMappingURL=not-found-routing.module.js.map
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ import { get } from 'lodash'; import { Metric } from './metric'; import { LARGE_FLOAT } from '../../../../common/formatting'; import { NORMALIZED_DERIVATIVE_UNIT } from '../../../../common/constants'; export class QuotaMetric extends Metric { constructor(opts) { super({ ...opts, format: LARGE_FLOAT, metricAgg: 'max', // makes an average metric of `this.field`, which is the "actual cpu utilization" derivative: true, units: '%' }); this.aggs = { usage: { max: { field: `${this.fieldSource}.${this.usageField}` } }, periods: { max: { field: `${this.fieldSource}.${this.periodsField}` } }, quota: { // Use min for this value. Basically equivalient to max, but picks -1 // as the value if quota is disabled in one of the docs, which affects // the logic by routing to the non-quota scenario min: { field: `${this.fieldSource}.${this.quotaField}` } }, usage_deriv: { derivative: { buckets_path: 'usage', gap_policy: 'skip', unit: NORMALIZED_DERIVATIVE_UNIT } }, periods_deriv: { derivative: { buckets_path: 'periods', gap_policy: 'skip', unit: NORMALIZED_DERIVATIVE_UNIT } } }; this.calculation = bucket => { const quota = get(bucket, 'quota.value'); const deltaUsageDerivNormalizedValue = get( bucket, 'usage_deriv.normalized_value' ); const periodsDerivNormalizedValue = get( bucket, 'periods_deriv.normalized_value' ); if ( deltaUsageDerivNormalizedValue && periodsDerivNormalizedValue && quota > 0 ) { // if throttling is configured const factor = deltaUsageDerivNormalizedValue / (periodsDerivNormalizedValue * quota * 1000); // convert quota from microseconds to nanoseconds by multiplying 1000 return factor * 100; // convert factor to percentage } // if throttling is NOT configured, show nothing. The user should see that something is not configured correctly return null; }; } }
/* Root.js Routes for entire spp */ import React from 'react'; import { HashRouter as Router, Route } from 'react-router-dom'; //import { BrowserRouter as Router, Route } from 'react-router-dom'; import HotCoins from '../HotCoins'; // import NotFound from './NotFound'; import Flex from '../WorkBench/Flex'; import Layout from '../WorkBench/Layout'; const Root = () => ( <Router> <div> <Route exact path="/hotcoins" component={HotCoins} /> <Route exact path="/flex" component={Flex} /> <Route exact path="/layout" component={Layout} /> </div> </Router> ); export default Root; /* <Route exact path="/horizontal" component={Test} /> <Route exact path="/dashboard" component={DashBoard} /> <Route exact path="/not-found" component={NotFound} /> <Redirect to="/not-found" /> <Route exact path='/' component={App} /> */
from . import base from . import mixins import string from datetime import date class TransformedRecord( mixins.GenericCompensationMixin, mixins.GenericIdentifierMixin, mixins.GenericPersonMixin, mixins.MembershipMixin, mixins.OrganizationMixin, mixins.PostMixin, mixins.RaceMixin, mixins.LinkMixin, base.BaseTransformedRecord): MAP = { 'last_name': 'LAST_NAME', 'first_name': 'FIRST_NAME', 'department': 'ORGANIZATION_NAME', 'job_title': 'JOB_NAME', 'hire_date': 'LAST_HIRE_DATE', 'status': 'EMPLOYMENT_CATEGORY', 'compensation': 'ANNUAL', 'gender': 'SEX', 'race': 'ETHNIC', # 'basis': 'SALARY_BASIS' } # The order of the name fields to build a full name. # If `full_name` is in MAP, you don't need this at all. NAME_FIELDS = ('first_name', 'last_name', ) # The name of the organization this WILL SHOW UP ON THE SITE, # so double check it! ORGANIZATION_NAME = 'Dallas County' # What type of organization is this? This MUST match what we use on the # site, double check against salaries.texastribune.org ORGANIZATION_CLASSIFICATION = 'County' # When did you receive the data? NOT when we added it to the site. DATE_PROVIDED = date(2018, 1, 22) # The URL to find the raw data in our S3 bucket. URL = ('http://raw.texastribune.org.s3.amazonaws.com/' 'dallas_county/salaries/2018-01/TX_TRIBUNE_1_2018.xlsx') # basis_map = { # 'EXEMPT': '', # 'NON-EXEMPT': 'Hourly' # } category_map = { 'FR': 'Full Time', 'PR': 'Part Time (More than 20, less than 30 hours per week)', 'PB': 'Part Time (More than 230 hours per week)', 'PT': 'Part Time (Less than 20 hours per week/seasonal)' } @property def is_valid(self): # Adjust to return False on invalid fields. For example: return self.last_name.strip() != '' @property def person(self): name = self.get_name() r = { 'family_name': name.last, 'given_name': name.first, 'additional_name': name.middle, 'name': unicode(name), 'gender': self.gender.strip() } return r @property def description(self): return self.category_map[self.status.upper()] @property def compensation_type(self): emp_type = self.status if emp_type == 'FR': return 'FT' else: return 'PT' @property def compensation(self): if not self.get_mapped_value('compensation'): return 0 return self.get_mapped_value('compensation') # def process_compensation_description(self): # basis = self.basis_map[self.basis.upper()] # category = self.category_map[self.status.upper()] # category_basis = " ".join([category, basis]).strip() # return category_basis # def process_compensation(self): # if self.basis.upper() == 'EXEMPT': # return float(self.compensation) * 12 # else: # return self.compensation # @property # def compensations(self): # # TODO: ADJUST HOUR PAY # compensation_description = self.process_compensation_description() # compensation = self.process_compensation() # compensation_type = 'FT' if compensation_description == 'Full Time Regular' else 'PT' # return [ # { # 'tx_salaries.CompensationType': { # 'name': compensation_type, # 'description': compensation_description # }, # 'tx_salaries.Employee': { # 'hire_date': self.hire_date, # 'compensation': compensation, # 'tenure': self.calculate_tenure() # }, # 'tx_salaries.EmployeeTitle': { # 'name': self.job_title, # }, # } # ] transform = base.transform_factory(TransformedRecord)
import styled from 'styled-components'; const Container = styled.div` margin: 35px 0; background-color: rgb(235, 235, 235); padding: 23px 28px; display: grid; grid-column-gap: 20px; grid-row-gap: 20px; align-items: center; grid-template-areas: 'titles close' 'explanation 0'; @media (min-width: 600px) { grid-template-areas: 'titles explanation close'; grid-row-gap: 0; } `; export default Container;
// Copyright 2013 Google Inc. // Copyright 2014 Volker Sorge // // 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. /** * @fileoverview Utility functions for semantic tree computations. * @author [email protected] (Volker Sorge) */ goog.provide('sre.SemanticUtil'); goog.require('sre.DomUtil'); /** * @constructor */ sre.SemanticUtil = function() { }; /** * Merges keys of objects into an array. * @param {...Object.<string>} var_args Optional objects. * @return {Array.<string>} Array of all keys of the objects. */ sre.SemanticUtil.objectsToKeys = function(var_args) { var_args = Array.prototype.slice.call(arguments, 0); var keys = []; return keys.concat.apply(keys, var_args.map(Object.keys)); }; /** * Merges values of objects into an array. * @param {...Object.<string>} var_args Optional objects. * @return {Array.<string>} Array of all values of the objects. */ sre.SemanticUtil.objectsToValues = function(var_args) { var_args = Array.prototype.slice.call(arguments, 0); var result = []; var collectValues = function(obj) { for (var key in obj) { result.push(obj[key]); } }; var_args.forEach(collectValues); return result; }; /** * Transforms a unicode character into numeric representation. Returns null if * the input string is not a valid unicode character. * @param {string} unicode Character. * @return {?number} The decimal representation if it exists. */ sre.SemanticUtil.unicodeToNumber = function(unicode) { if (!unicode || unicode.length > 2) { return null; } // Treating surrogate pairs. if (unicode.length == 2) { var hi = unicode.charCodeAt(0); var low = unicode.charCodeAt(1); if (0xD800 <= hi && hi <= 0xDBFF && !isNaN(low)) { return ((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000; } return null; } return unicode.charCodeAt(0); }; // TODO: Refactor with similar function in MathSimpleStore. /** * Transforms a numberic representation of a unicode character into its * corresponding string. * @param {number} number Unicode point. * @return {string} The string representation. */ sre.SemanticUtil.numberToUnicode = function(number) { if (number < 0x10000) { return String.fromCharCode(number); } var hi = (number - 0x10000) / 0x0400 + 0xD800; var lo = (number - 0x10000) % 0x0400 + 0xDC00; return String.fromCharCode(hi, lo); }; /** * Splits a unicode string into array of characters. In particular deals * properly with surrogate pairs. * @param {string} str The string to split. * @return {Array.<string>} List of single characters. */ sre.SemanticUtil.splitUnicode = function(str) { var split = str.split(''); var result = []; for (var i = 0, chr; chr = split[i]; i++) { if ('\uD800' <= chr && chr <= '\uDBFF' && split[i + 1]) { result.push(chr + split[++i]); } else { result.push(chr); } } return result; }; /** * List of MathML Tags that are considered to be leafs. * @type {Array.<string>} * @const */ sre.SemanticUtil.LEAFTAGS = ['MO', 'MI', 'MN', 'MTEXT', 'MS']; /** * List of MathML Tags that are to be ignored. * @type {Array.<string>} * @const */ sre.SemanticUtil.IGNORETAGS = [ 'MERROR', 'MPHANTOM', 'MSPACE', 'MALIGNGROUP', 'MALIGNMARK', 'MPRESCRIPTS', 'ANNOTATION', 'ANNOTATION-XML' ]; /** * List of MathML Tags to be ignore if they have no children. * @type {Array.<string>} * @const */ sre.SemanticUtil.EMPTYTAGS = [ 'MATH', 'MROW', 'MPADDED', 'MACTION', 'NONE', 'MSTYLE', 'SEMANTICS' ]; /** * Checks if an element is a node with a math tag. * @param {Element} node The node to check. * @return {boolean} True if element is an math node. */ sre.SemanticUtil.hasMathTag = function(node) { return !!node && sre.DomUtil.tagName(node) === 'MATH'; }; /** * Checks if an element is a node with ignore tag. * @param {Element} node The node to check. * @return {boolean} True if element is an ignore node. */ sre.SemanticUtil.hasIgnoreTag = function(node) { return !!node && sre.SemanticUtil.IGNORETAGS.indexOf( sre.DomUtil.tagName(node)) !== -1; }; /** * Checks if an element is a node with empty tag. * @param {Element} node The node to check. * @return {boolean} True if element is an empty node. */ sre.SemanticUtil.hasEmptyTag = function(node) { return !!node && sre.SemanticUtil.EMPTYTAGS.indexOf(sre.DomUtil.tagName(node)) !== -1; }; /** * Removes elements from a list of MathML nodes that are either to be ignored or * ignored if they have empty children. * Observe that this is currently not recursive, i.e. will not take care of * pathological cases, where content is hidden in incorrectly used tags! * @param {Array.<Element>} nodes The node list to be cleaned. * @return {Array.<Element>} The cleansed list. */ sre.SemanticUtil.purgeNodes = function(nodes) { var nodeArray = []; for (var i = 0, node; node = nodes[i]; i++) { var tagName = sre.DomUtil.tagName(node); if (sre.SemanticUtil.IGNORETAGS.indexOf(tagName) != -1) continue; if (sre.SemanticUtil.EMPTYTAGS.indexOf(tagName) != -1 && node.childNodes.length == 0) continue; nodeArray.push(node); } return nodeArray; }; /** * Determines if an attribute represents zero or negative length. * @param {string} length The lenght value. * @return {boolean} True if the attribute represents zero length. */ sre.SemanticUtil.isZeroLength = function(length) { if (!length) { return false; } var negativeNamedSpaces = [ 'negativeveryverythinmathspace', 'negativeverythinmathspace', 'negativethinmathspace', 'negativemediummathspace', 'negativethickmathspace', 'negativeverythickmathspace', 'negativeveryverythickmathspace']; if (negativeNamedSpaces.indexOf(length) !== -1) { return true; } var value = length.match(/[0-9\.]+/); if (!value) { return false; } return parseFloat(value) === 0 ? true : false; };
function Application (cb) { this._logger = function () {}; this._app = function () { return {}; }; cb.call(this); } Application.prototype.init = function () { this._app = this._app(); }; Application.prototype.setLogger = function (logger) { this._logger = logger || function () {}; }; Application.prototype.setApp = function (app) { this._app = app || function () {}; }; Application.prototype.log = function () { this._logger.apply(this._logger, arguments); }; Application.prototype.serve = function (port) { this._app.listen(port, function () { this.log('Server listening on port ' + port); }.bind(this)); }; module.exports = Application;
var Promise = require('../utils/promise'); var timing = require('../utils/timing'); var Book = require('../models/book'); var parseIgnore = require('./parseIgnore'); var parseConfig = require('./parseConfig'); var parseGlossary = require('./parseGlossary'); var parseSummary = require('./parseSummary'); var parseReadme = require('./parseReadme'); var parseLanguages = require('./parseLanguages'); /** Parse content of a book @param {Book} book @return {Promise<Book>} */ function parseBookContent(book) { return Promise(book) .then(parseReadme) .then(parseSummary) .then(parseGlossary); } /** Parse a multilingual book @param {Book} book @return {Promise<Book>} */ function parseMultilingualBook(book) { var languages = book.getLanguages(); var langList = languages.getList(); return Promise.reduce(langList, function(currentBook, lang) { var langID = lang.getID(); var child = Book.createFromParent(currentBook, langID); var ignore = currentBook.getIgnore(); return Promise(child) .then(parseConfig) .then(parseBookContent) .then(function(result) { // Ignore content of this book when generating parent book ignore = ignore.add(langID + '/**'); currentBook = currentBook.set('ignore', ignore); return currentBook.addLanguageBook(langID, result); }); }, book); } /** Parse a whole book from a filesystem @param {Book} book @return {Promise<Book>} */ function parseBook(book) { return timing.measure( 'parse.book', Promise(book) .then(parseIgnore) .then(parseConfig) .then(parseLanguages) .then(function(resultBook) { if (resultBook.isMultilingual()) { return parseMultilingualBook(resultBook); } else { return parseBookContent(resultBook); } }) ); } module.exports = parseBook;
//FOR for (var i = 0; i < 5; i++) { console.log(i); } //WHILE var ii = 0; while (ii < 5) { console.log(ii); ii++; } // DO...WHILE do { console.log(ii); ii--; } while (ii > 0) //BREAK while (ii < 5) { console.log(ii); break; } //CONTINUE while (ii < 5) { if (ii == 2) { ii++; continue; } console.log(ii); ii++; } // FOR...IN var arr = ['a', 'b', 'c']; var obj = { id: '1', name: 'test' } for (var item in obj) { console.log(item); console.log(obj[item]); } for (var item in arr) { console.log(item); console.log(arr[item]); } //For...of //just for iterables for (var item of arr) { console.log(item); } /* for(var item of obj){ console.log(item); console.log(obj[item]); } */
var util = require('../../utils/util.js') var app = getApp(); var like = []; var posreset = true; Page({ data: { datafetched: true, data: [], like: [], start: {} }, onLoad: function() { this.reload(); }, onShow: function() { if (JSON.stringify(this.data.like.sort()) !== JSON.stringify(app.globalData.like.sort())) { this.reload(); }; }, reload: function() { wx.showLoading({ title: '加载中', }) this.setData({ data: [] }) like = app.globalData.like; if (!like[0]) { wx.hideLoading() this.setData({ like: like, datafetched: false }) } else { var url = util.apibase + 'liked'; wx.request({ url: url, method: 'POST', data: like, success: (res) => { for (let i = 0; i < res.data.length; i++) { res.data[i].likeimgurl = util.bucketbase + res.data[i].wpimguri + '/jmf'; res.data[i].splitedd = res.data[i].day.split('-'); res.data[i].pos = 0; } this.setData({ like: like, datafetched: true, data: res.data }) wx.hideLoading(); }, fail: function() { wx.hideLoading(); wx.showModal({ title: '提示', content: '没能联系上服务器...一会再试吧.', showCancel: false, confirmText: '嗯', confirmColor: '#000000' }) } }) } }, Record: function(ev) { if (ev.touches.length == 1 && ev.target.dataset.day) { this.setData({ start: { point: ev.touches[0].clientX, day: ev.target.dataset.day, index: ev.target.dataset.index } }); } }, Moving: function(ev) { if (ev.touches.length == 1) { var offset = this.data.start.point - ev.touches[0].clientX, result; switch (true) { case offset <= 0: result = 0 break; case (offset > 0 && offset <= 115): result = -offset; break; case offset > 115: result = -115 break; } var data = this.data.data; if (!posreset) { for (var i = 0; i < data.length; i++) { data[i].pos = 0; } posreset = true; } data[this.data.start.index].pos = result; this.setData({ data: data }) } }, release: function(ev) { if (ev.changedTouches.length == 1) { var offset = this.data.start.point - ev.changedTouches[0].clientX, result; switch (true) { case offset <= 53: result = 0 break; case (offset > 53): result = -115; posreset = false; break; } var data = this.data.data; data[this.data.start.index].pos = result; this.setData({ data: data }) } }, goto: function(ev) { if (ev.target.dataset.day) { wx.navigateTo({ url: '/pages/day/day?date=' + ev.target.dataset.day }) } }, delcard: function() { var data = this.data.data; var like = this.data.like; data.splice(this.data.start.index, 1); like.splice(this.data.start.index, 1); for (var i = 0; i < data.length; i++) { data[i].pos = 0; } posreset = true; wx.setStorageSync('like',like); app.globalData.like = like; var datafetched = (like[0])?true:false; this.setData({ data: data, like: like, datafetched:datafetched }) }, onShareAppMessage: function(opt) { var info = {}; if (opt.from == 'button') { var day = opt.target.dataset.date; info.title = '今日' + day; info.path = '/pages/day/day' + '?date=' + day; } else { info.title = '今日'; info.path = 'pages/index/index' } return info; } })
var express = require("express"); var router = express.Router(); var mail = require("../nodemailer"); /* Post to mailer 3 @params required (receiver, subject, body) The information being sent from the front end must be specifically be JSON with 3 key value pairs for email, subject of email and message being sent otherwise a 400 code bad request will be sent back */ router.post("/", function (req, res, next) { //If any of the required information is missing it will go to code 400 or 404 console.log(req.body); if (req.body.email !== undefined && req.body.subject !== undefined && req.body.message !== undefined) { mail(req.body.email, req.body.subject, req.body.message) .then(res.send("Mail Sent")) .catch(console.error); } else { res.sendStatus(400); } }); module.exports = router;
import React from "react"; import propType from "prop-types"; import Box from "@material-ui/core/Box"; import Popper from "@material-ui/core/Popper"; import Button from "@material-ui/core/Button"; import Autocomplete from "@material-ui/lab/Autocomplete"; import InputBase from "@material-ui/core/InputBase"; import useStyles from "./AutoCompletePopper.scss"; const LoadMoreList = React.forwardRef((props, ref) => { // eslint-disable-next-line react/prop-types const { children, hasMore, onLoadMore, ...other } = props; return ( <ul ref={ref} {...other}> {children} {hasMore && ( <Button style={{ width: "100%" }} onClick={onLoadMore}> load more </Button> )} </ul> ); }); function AutoCompletePopper(props) { const { open, anchorEl, onChange, onClose, renderOption, pendingValues, selectedValues, allValues, loading, noOptionsText, multiple, hasMore, fetchMore, title } = props; const classes = useStyles(); return ( <Popper open={open} anchorEl={anchorEl} placement="bottom-end" className={classes.popper} > <Box className={classes.header}>{title}</Box> <Autocomplete open loading={loading} onClose={onClose} multiple={multiple} classes={{ paper: classes.paper, option: classes.option, popperDisablePortal: classes.popperDisablePortal }} value={pendingValues} onChange={onChange} disableCloseOnSelect disablePortal renderTags={() => null} includeInputInList ListboxComponent={React.forwardRef((allProps, ref) => ( <LoadMoreList ref={ref} hasMore={hasMore} onLoadMore={fetchMore} {...allProps} /> ))} noOptionsText={noOptionsText} renderOption={renderOption} options={allValues.sort((a, b) => { // Display the selected labels first. let ai = selectedValues.indexOf(a); ai = ai === -1 ? selectedValues.length + selectedValues.indexOf(a) : ai; let bi = selectedValues.indexOf(b); bi = bi === -1 ? selectedValues.length + selectedValues.indexOf(b) : bi; return ai - bi; })} getOptionLabel={option => option.name} renderInput={params => ( <InputBase ref={params.InputProps.ref} inputProps={params.inputProps} autoFocus className={classes.inputBase} /> )} /> </Popper> ); } AutoCompletePopper.defaultProps = { // Popper Props anchorEl: null, // AutoComplete Props multiple: false, open: false, loading: false }; AutoCompletePopper.propTypes = { selectedValues: propType.array.isRequired, pendingValues: propType.array.isRequired, allValues: propType.array.isRequired, hasMore: propType.bool.isRequired, fetchMore: propType.func.isRequired, title: propType.string.isRequired, // Popper Props onClose: propType.func.isRequired, anchorEl: propType.object, // AutoComplete Props onChange: propType.func.isRequired, multiple: propType.bool, open: propType.bool, loading: propType.bool, renderOption: propType.func.isRequired, noOptionsText: propType.string.isRequired }; export default AutoCompletePopper;
export default /* @ngInject */ ( $scope, $translate, $rootScope, License, Alerter, ) => { $scope.license = $scope.currentActionData.license; /** * Toggle delete at expiration serviceInfos. * @return {Promise} */ $scope.toggleDeleteAtExpiration = () => License.deleteLicenseAtExpiration($scope.license) .then(() => { Alerter.alertFromSWS( $translate.instant('license_details_update_success'), ); $rootScope.$broadcast('License.Details.Refresh'); }) .catch((err) => Alerter.alertFromSWS( $translate.instant('license_details_update_fail'), err, ), ) .finally(() => { $scope.resetAction(); }); };
import {Subscription} from "~/src/services/Observable"; const {subscribe, trigger} = Subscription(); if (typeof document !== 'undefined') { document.addEventListener("keyup", trigger); } export const KeyboardListener = { listen: subscribe };
import React, {Component} from "react"; import Header from "./Header"; import {connect} from "react-redux"; import {createSelector} from "reselect"; import {Card, CardActions} from "material-ui/Card"; import RaisedButton from "material-ui/RaisedButton"; import TextField from "material-ui/TextField"; import {Link} from "react-router"; import Divider from "material-ui/Divider"; import {articleActions} from "~/article"; import dateformat from "dateformat"; import { Table, TableBody, TableFooter, TableHeader, TableHeaderColumn, TableRow, TableRowColumn } from "material-ui/Table"; class ArticleList extends Component { constructor(){ super(); this.search = this.search.bind(this); } componentWillMount() { this.props.loadArticles(function () { }, (() => { this.props.filterArticles({ title: this.refs.title.getValue() }); }).bind(this) ); } componentWillUnmount() { this.props.unloadArticles(); } search(){ this.props.filterArticles({ title: this.refs.title.getValue() }); } render() { return ( <div> <Header/> <div style={{margin: 10}}> <Card> <CardActions> <TextField hintText="제목, 내용 , 이름으로 검색" floatingLabelText="검색어" ref="title" /> <RaisedButton label="검색" onTouchTap={this.search}/> <RaisedButton label="추가" primary={true} containerElement={<Link to="/articles/form"/>} /> <RaisedButton label="삭제" secondary={true}/> </CardActions> <Divider /> <List articles={this.props.articles} /> <Pagination/> </Card> </div> </div> ); } } class Search extends Component { render() { return (<div></div>); } } class List extends Component { render() { return ( <div> <Table> <TableHeader> <TableRow> <TableHeaderColumn> No </TableHeaderColumn> <TableHeaderColumn> title </TableHeaderColumn> <TableHeaderColumn> date </TableHeaderColumn> <TableHeaderColumn> hit </TableHeaderColumn> <TableHeaderColumn> author </TableHeaderColumn> </TableRow> </TableHeader> <TableBody> { this.props.articles.map((row, index) => { const formattedDate = (_date) => (dateformat(new Date(_date), "yyyy-mm-dd")); const date = ((row) => { if (row.updateDate) return formattedDate(row.updateDate); return formattedDate(row.createDate); })(row); return ( <TableRow key={row.id}> <TableRowColumn>{row.no}</TableRowColumn> <TableRowColumn> <Link to={`/articles/${row.id}`}>{row.title}</Link> </TableRowColumn> <TableRowColumn>{date}</TableRowColumn> <TableRowColumn>{row.hit}</TableRowColumn> <TableRowColumn>{row.author}</TableRowColumn> </TableRow> ) }) } </TableBody> <TableFooter/> </Table> </div> ); } } class Pagination extends Component { render() { return (<div></div>); } } const mapStateToProps = createSelector( (state) => state.articles, (articles) => ({ articles }) ); const mapDispatchToProps = Object.assign( {}, articleActions ); export default connect( mapStateToProps, mapDispatchToProps )(ArticleList);
//// [inferentialTypingWithFunctionTypeZip.ts] var pair: <T, S>(x: T) => (y: S) => { x: T; y: S; } var zipWith: <T, S, U>(a: T[], b: S[], f: (x: T) => (y: S) => U) => U[]; var result = zipWith([1, 2], ['a', 'b'], pair); var i = result[0].x; // number //// [inferentialTypingWithFunctionTypeZip.js] var pair; var zipWith; var result = zipWith([1, 2], ['a', 'b'], pair); var i = result[0].x;
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import $ from 'jquery'; import ApiHelper from 'api/apiHelper'; import { EXECUTION_STATUS } from './executable'; import Executor from './executor'; describe('executor.js', () => { /** * @param statement * @return {Executor} */ const createSubject = statement => new Executor({ compute: { id: 'compute' }, namespace: { id: 'namespace' }, database: 'default', sourceType: 'impala', statement: statement, isSqlEngine: true }); xit('should set the correct status after successful execute', done => { const subject = createSubject('SELECT * FROM customers;'); const simplePostDeferred = $.Deferred(); jest.spyOn(ApiHelper, 'simplePost').mockImplementation(url => { expect(url).toEqual('/notebook/api/execute/impala'); return simplePostDeferred; }); subject .executeNext() .then(() => { expect(subject.status).toEqual(EXECUTION_STATUS.available); done(); }) .catch(fail); expect(subject.status).toEqual(EXECUTION_STATUS.running); simplePostDeferred.resolve({ handle: {} }); }); });
import path from 'path' import fs from 'fs' import { spawn, execSync } from 'child_process' import webpack from 'webpack' import chalk from 'chalk' import merge from 'webpack-merge' import baseConfig from './webpack.config.base' const port = process.env.PORT || 1212 const publicPath = `http://localhost:${port}/dist` const dll = path.resolve(process.cwd(), 'dll') const manifest = path.resolve(dll, 'vendor.json') /** * Warn if the DLL is not built */ if (!(fs.existsSync(dll) && fs.existsSync(manifest))) { console.log( chalk.black.bgYellow.bold( 'The DLL files are missing. Sit back while we build them for you with "npm run build-dll"' ) ) execSync('npm run build-dll') } export default merge.smart(baseConfig, { devtool: 'inline-source-map', target: 'electron-renderer', entry: [ 'react-hot-loader/patch', `webpack-dev-server/client?http://localhost:${port}/`, 'webpack/hot/only-dev-server', path.resolve(process.cwd(), 'app/index.js'), ], output: { publicPath: `http://localhost:${port}/dist/`, }, module: { rules: [ { test: /\.yml$/, use: [{ loader: 'json-loader' }, { loader: 'yaml-flat-loader' }], }, // WOFF Font { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, use: { loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff', }, }, }, // WOFF2 Font { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, use: { loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff', }, }, }, // TTF Font { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, use: { loader: 'url-loader', options: { limit: 10000, mimetype: 'application/octet-stream', }, }, }, // EOT Font { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, use: 'file-loader', }, // SVG Font { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, use: { loader: 'url-loader', options: { limit: 10000, mimetype: 'image/svg+xml', }, }, }, // Common Image Formats { test: /\.(?:ico|gif|png|jpg|jpeg|webp)$/, use: 'url-loader', }, ], }, plugins: [ new webpack.DllReferencePlugin({ context: process.cwd(), manifest: require(manifest), // eslint-disable-line import/no-dynamic-require sourceType: 'var', }), /** * https://webpack.js.org/concepts/hot-module-replacement/ */ new webpack.HotModuleReplacementPlugin({ // @TODO: Waiting on https://github.com/jantimon/html-webpack-plugin/issues/533 // multiStep: true }), new webpack.NoEmitOnErrorsPlugin(), /** * Create global constants which can be configured at compile time. * * Useful for allowing different behaviour between development builds and * release builds * * NODE_ENV should be production so that modules do not perform certain * development checks * * By default, use 'development' as NODE_ENV. This can be overriden with * 'staging', for example, by changing the ENV variables in the npm scripts */ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify( process.env.NODE_ENV || 'development' ), }), new webpack.LoaderOptionsPlugin({ debug: true, }), ], devServer: { port, publicPath, compress: true, noInfo: true, stats: 'errors-only', inline: true, lazy: false, hot: true, headers: { 'Access-Control-Allow-Origin': '*' }, contentBase: path.resolve(process.cwd(), 'dist'), watchOptions: { aggregateTimeout: 300, poll: 100, }, historyApiFallback: { verbose: true, disableDotRule: false, }, setup() { if (process.env.START_HOT) { spawn('npm', ['run', 'start-hot-renderer'], { shell: true, env: process.env, stdio: 'inherit', }) .on('close', code => process.exit(code)) .on('error', spawnError => console.error(spawnError)) } }, }, })
import * as _logging from './logging.js'; export const logging = _logging; import * as _basic from './basic.js'; export const basic = _basic; import * as _strings from './strings.js'; export const strings = _strings; import * as _arrays from './arrays.js'; export const arrays = _arrays; import * as _objects from './objects.js'; export const objects = _objects; import * as _random from './random.js'; export const random = _random; import * as _timers from './timers.js'; export const timers = _timers; import * as _functions from './functions.js'; export const functions = _functions; import * as _context from './context.js'; export const context = _context; import * as _polling from './polling.js'; export const polling = _polling; import * as _elements from './elements.js'; export const elements = _elements; import * as _animation from './animation.js'; export const animation = _animation; import * as _viewport from './viewport.js'; export const viewport = _viewport; import * as _navigation from './navigation.js'; export const navigation = _navigation; import * as _dynamicLoading from './dynamic-loading.js'; export const dynamicLoading = _dynamicLoading;
import React, {useState, useEffect} from 'react'; const ProgressBar = ({background, completed, title}) => { const [loading, setLoading] = useState(1); useEffect(() => { setLoading(completed); }, []); return ( <div className="container max-w-screen-lg mx-auto wrapper"> <div className="flex items-center"> <p className="title">{title}</p> </div> <div className="pbcontainer"> <div className="shadow filler"> <span className="label">{`${completed}%`}</span> </div> </div> <style jsx> {` .wrapper { margin-top: -4px; padding-bottom: 9px; } .title { color: #b5babd; font-size: 14px; } .pbcontainer { height: 23px; width: 100%; background: linear-gradient( to right, #49505200, #49505260 50%, #495052 100% ); border-radius: 7px; } .filler { transition: width 1s ease-in-out; height: 100%; width: ${loading}%; background: ${background}; border-radius: inherit; text-align: right; } .label { padding-right: 5px; font-size: 13px; color: white; font-weight: 500; } `} </style> </div> ); }; export default ProgressBar;
# Copyright (c) 2012-2013 LiuYC https://github.com/liuyichen/ # Copyright 2012-2014 ksyun.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. import sys import logging import select import functools import socket import inspect from kscore.compat import six from kscore.compat import HTTPHeaders, HTTPResponse, urlunsplit, urlsplit from kscore.exceptions import UnseekableStreamError from kscore.utils import percent_encode_sequence from kscore.vendored.requests import models from kscore.vendored.requests.sessions import REDIRECT_STATI from kscore.vendored.requests.packages.urllib3.connection import \ VerifiedHTTPSConnection from kscore.vendored.requests.packages.urllib3.connection import \ HTTPConnection from kscore.vendored.requests.packages.urllib3.connectionpool import \ HTTPConnectionPool from kscore.vendored.requests.packages.urllib3.connectionpool import \ HTTPSConnectionPool logger = logging.getLogger(__name__) class KSHTTPResponse(HTTPResponse): # The *args, **kwargs is used because the args are slightly # different in py2.6 than in py2.7/py3. def __init__(self, *args, **kwargs): self._status_tuple = kwargs.pop('status_tuple') HTTPResponse.__init__(self, *args, **kwargs) def _read_status(self): if self._status_tuple is not None: status_tuple = self._status_tuple self._status_tuple = None return status_tuple else: return HTTPResponse._read_status(self) class KSHTTPConnection(HTTPConnection): """HTTPConnection that supports Expect 100-continue. This is conceptually a subclass of httplib.HTTPConnection (though technically we subclass from urllib3, which subclasses httplib.HTTPConnection) and we only override this class to support Expect 100-continue, which we need for S3. As far as I can tell, this is general purpose enough to not be specific to S3, but I'm being tentative and keeping it in kscore because I've only tested this against KSYUN services. """ def __init__(self, *args, **kwargs): HTTPConnection.__init__(self, *args, **kwargs) self._original_response_cls = self.response_class # We'd ideally hook into httplib's states, but they're all # __mangled_vars so we use our own state var. This variable is set # when we receive an early response from the server. If this value is # set to True, any calls to send() are noops. This value is reset to # false every time _send_request is called. This is to workaround the # fact that py2.6 (and only py2.6) has a separate send() call for the # body in _send_request, as opposed to endheaders(), which is where the # body is sent in all versions > 2.6. self._response_received = False self._expect_header_set = False def close(self): HTTPConnection.close(self) # Reset all of our instance state we were tracking. self._response_received = False self._expect_header_set = False self.response_class = self._original_response_cls def _tunnel(self): # Works around a bug in py26 which is fixed in later versions of # python. Bug involves hitting an infinite loop if readline() returns # nothing as opposed to just ``\r\n``. # As much as I don't like having if py2: <foo> code blocks, this seems # the cleanest way to handle this workaround. Fortunately, the # difference from py26 to py3 is very minimal. We're essentially # just overriding the while loop. if sys.version_info[:2] != (2, 6): return HTTPConnection._tunnel(self) # Otherwise we workaround the issue. self._set_hostport(self._tunnel_host, self._tunnel_port) self.send("CONNECT %s:%d HTTP/1.0\r\n" % (self.host, self.port)) for header, value in self._tunnel_headers.iteritems(): self.send("%s: %s\r\n" % (header, value)) self.send("\r\n") response = self.response_class(self.sock, strict=self.strict, method=self._method) (version, code, message) = response._read_status() if code != 200: self.close() raise socket.error("Tunnel connection failed: %d %s" % (code, message.strip())) while True: line = response.fp.readline() if not line: break if line in (b'\r\n', b'\n', b''): break def _send_request(self, method, url, body, headers, *py36_up_extra): self._response_received = False if headers.get('Expect', b'') == b'100-continue': self._expect_header_set = True else: self._expect_header_set = False self.response_class = self._original_response_cls rval = HTTPConnection._send_request( self, method, url, body, headers, *py36_up_extra) self._expect_header_set = False return rval def _convert_to_bytes(self, mixed_buffer): # Take a list of mixed str/bytes and convert it # all into a single bytestring. # Any six.text_types will be encoded as utf-8. bytes_buffer = [] for chunk in mixed_buffer: if isinstance(chunk, six.text_type): bytes_buffer.append(chunk.encode('utf-8')) else: bytes_buffer.append(chunk) msg = b"\r\n".join(bytes_buffer) return msg def _send_output(self, message_body=None, **py36_up_extra): self._buffer.extend((b"", b"")) msg = self._convert_to_bytes(self._buffer) del self._buffer[:] # If msg and message_body are sent in a single send() call, # it will avoid performance problems caused by the interaction # between delayed ack and the Nagle algorithm. if isinstance(message_body, bytes): msg += message_body message_body = None self.send(msg) if self._expect_header_set: # This is our custom behavior. If the Expect header was # set, it will trigger this custom behavior. logger.debug("Waiting for 100 Continue response.") # Wait for 1 second for the server to send a response. read, write, exc = select.select([self.sock], [], [self.sock], 1) if read: self._handle_expect_response(message_body) return else: # From the RFC: # Because of the presence of older implementations, the # protocol allows ambiguous situations in which a client may # send "Expect: 100-continue" without receiving either a 417 # (Expectation Failed) status or a 100 (Continue) status. # Therefore, when a client sends this header field to an origin # server (possibly via a proxy) from which it has never seen a # 100 (Continue) status, the client SHOULD NOT wait for an # indefinite period before sending the request body. logger.debug("No response seen from server, continuing to " "send the response body.") if message_body is not None: # message_body was not a string (i.e. it is a file), and # we must run the risk of Nagle. self.send(message_body) def _consume_headers(self, fp): # Most servers (including S3) will just return # the CLRF after the 100 continue response. However, # some servers (I've specifically seen this for squid when # used as a straight HTTP proxy) will also inject a # Connection: keep-alive header. To account for this # we'll read until we read '\r\n', and ignore any headers # that come immediately after the 100 continue response. current = None while current != b'\r\n': current = fp.readline() def _handle_expect_response(self, message_body): # This is called when we sent the request headers containing # an Expect: 100-continue header and received a response. # We now need to figure out what to do. fp = self.sock.makefile('rb', 0) try: maybe_status_line = fp.readline() parts = maybe_status_line.split(None, 2) if self._is_100_continue_status(maybe_status_line): self._consume_headers(fp) logger.debug("100 Continue response seen, " "now sending request body.") self._send_message_body(message_body) elif len(parts) == 3 and parts[0].startswith(b'HTTP/'): # From the RFC: # Requirements for HTTP/1.1 origin servers: # # - Upon receiving a request which includes an Expect # request-header field with the "100-continue" # expectation, an origin server MUST either respond with # 100 (Continue) status and continue to read from the # input stream, or respond with a final status code. # # So if we don't get a 100 Continue response, then # whatever the server has sent back is the final response # and don't send the message_body. logger.debug("Received a non 100 Continue response " "from the server, NOT sending request body.") status_tuple = (parts[0].decode('ascii'), int(parts[1]), parts[2].decode('ascii')) response_class = functools.partial( KSHTTPResponse, status_tuple=status_tuple) self.response_class = response_class self._response_received = True finally: fp.close() def _send_message_body(self, message_body): if message_body is not None: self.send(message_body) def send(self, str): if self._response_received: logger.debug("send() called, but reseponse already received. " "Not sending data.") return return HTTPConnection.send(self, str) def _is_100_continue_status(self, maybe_status_line): parts = maybe_status_line.split(None, 2) # Check for HTTP/<version> 100 Continue\r\n return ( len(parts) >= 3 and parts[0].startswith(b'HTTP/') and parts[1] == b'100') class KSHTTPSConnection(VerifiedHTTPSConnection): pass # Now we need to set the methods we overrode from KSHTTPConnection # onto KSHTTPSConnection. This is just a shortcut to avoid # copy/pasting the same code into KSHTTPSConnection. for name, function in KSHTTPConnection.__dict__.items(): if inspect.isfunction(function): setattr(KSHTTPSConnection, name, function) def prepare_request_dict(request_dict, endpoint_url, user_agent=None): """ This method prepares a request dict to be created into an KSRequestObject. This prepares the request dict by adding the url and the user agent to the request dict. :type request_dict: dict :param request_dict: The request dict (created from the ``serialize`` module). :type user_agent: string :param user_agent: The user agent to use for this request. :type endpoint_url: string :param endpoint_url: The full endpoint url, which contains at least the scheme, the hostname, and optionally any path components. """ r = request_dict if user_agent is not None: headers = r['headers'] headers['User-Agent'] = user_agent url = _urljoin(endpoint_url, r['url_path']) if r['query_string']: encoded_query_string = percent_encode_sequence(r['query_string']) if '?' not in url: url += '?%s' % encoded_query_string else: url += '&%s' % encoded_query_string r['url'] = url def create_request_object(request_dict): """ This method takes a request dict and creates an KSRequest object from it. :type request_dict: dict :param request_dict: The request dict (created from the ``prepare_request_dict`` method). :rtype: ``kscore.ksrequest.KSRequest`` :return: An KSRequest object based on the request_dict. """ r = request_dict return KSRequest(method=r['method'], url=r['url'], data=r['body'], headers=r['headers']) def _urljoin(endpoint_url, url_path): p = urlsplit(endpoint_url) # <part> - <index> # scheme - p[0] # netloc - p[1] # path - p[2] # query - p[3] # fragment - p[4] if not url_path or url_path == '/': # If there's no path component, ensure the URL ends with # a '/' for backwards compatibility. if not p[2]: return endpoint_url + '/' return endpoint_url if p[2].endswith('/') and url_path.startswith('/'): new_path = p[2][:-1] + url_path else: new_path = p[2] + url_path reconstructed = urlunsplit((p[0], p[1], new_path, p[3], p[4])) return reconstructed class KSRequest(models.RequestEncodingMixin, models.Request): def __init__(self, *args, **kwargs): self.auth_path = None if 'auth_path' in kwargs: self.auth_path = kwargs['auth_path'] del kwargs['auth_path'] models.Request.__init__(self, *args, **kwargs) headers = HTTPHeaders() if self.headers is not None: for key, value in self.headers.items(): headers[key] = value self.headers = headers # This is a dictionary to hold information that is used when # processing the request. What is inside of ``context`` is open-ended. # For example, it may have a timestamp key that is used for holding # what the timestamp is when signing the request. Note that none # of the information that is inside of ``context`` is directly # sent over the wire; the information is only used to assist in # creating what is sent over the wire. self.context = {} def prepare(self): """Constructs a :class:`KSPreparedRequest <KSPreparedRequest>`.""" # Eventually I think it would be nice to add hooks into this process. p = KSPreparedRequest(self) p.prepare_method(self.method) p.prepare_url(self.url, self.params) p.prepare_headers(self.headers) p.prepare_cookies(self.cookies) p.prepare_body(self.data, self.files) p.prepare_auth(self.auth) return p @property def body(self): p = models.PreparedRequest() p.prepare_headers({}) p.prepare_body(self.data, self.files) if isinstance(p.body, six.text_type): p.body = p.body.encode('utf-8') return p.body class KSPreparedRequest(models.PreparedRequest): """Represents a prepared request. :ivar method: HTTP Method :ivar url: The full url :ivar headers: The HTTP headers to send. :ivar body: The HTTP body. :ivar hooks: The set of callback hooks. In addition to the above attributes, the following attributes are available: :ivar query_params: The original query parameters. :ivar post_param: The original POST params (dict). """ def __init__(self, original_request): self.original = original_request super(KSPreparedRequest, self).__init__() self.hooks.setdefault('response', []).append( self.reset_stream_on_redirect) def reset_stream_on_redirect(self, response, **kwargs): if response.status_code in REDIRECT_STATI and \ self._looks_like_file(self.body): logger.debug("Redirect received, rewinding stream: %s", self.body) self.reset_stream() def _looks_like_file(self, body): return hasattr(body, 'read') and hasattr(body, 'seek') def reset_stream(self): # Trying to reset a stream when there is a no stream will # just immediately return. It's not an error, it will produce # the same result as if we had actually reset the stream (we'll send # the entire body contents again if we need to). # Same case if the body is a string/bytes type. if self.body is None or isinstance(self.body, six.text_type) or \ isinstance(self.body, six.binary_type): return try: logger.debug("Rewinding stream: %s", self.body) self.body.seek(0) except Exception as e: logger.debug("Unable to rewind stream: %s", e) raise UnseekableStreamError(stream_object=self.body) def prepare_body(self, data, files, json=None): """Prepares the given HTTP body data.""" super(KSPreparedRequest, self).prepare_body(data, files, json) # Calculate the Content-Length by trying to seek the file as # requests cannot determine content length for some seekable file-like # objects. if 'Content-Length' not in self.headers: if hasattr(data, 'seek') and hasattr(data, 'tell'): orig_pos = data.tell() data.seek(0, 2) end_file_pos = data.tell() self.headers['Content-Length'] = str(end_file_pos - orig_pos) data.seek(orig_pos) # If the Content-Length was added this way, a # Transfer-Encoding was added by requests because it did # not add a Content-Length header. However, the # Transfer-Encoding header is not supported for # KSYUN Services so remove it if it is added. if 'Transfer-Encoding' in self.headers: self.headers.pop('Transfer-Encoding') HTTPSConnectionPool.ConnectionCls = KSHTTPSConnection HTTPConnectionPool.ConnectionCls = KSHTTPConnection
var pem = require("pem"), async = require("async"), NodeRSA = require("node-rsa"), crypto = require('crypto'), publicKeyMacaroons = require("public-key-macaroons"), macaroons = require('node-macaroons'), _ = require("lodash"); var CHARACTERS_ON_CERTIFICATE_LINE = 64; function base64WithSplitCharLines(string){ return _.chain(string) .chunk(CHARACTERS_ON_CERTIFICATE_LINE) .map(function (str) {return str.join(""); } ) .value(); } function condenseCertificate(certVar){ return certVar .replace("-----BEGIN CERTIFICATE-----", "") .replace("-----END CERTIFICATE-----", "") .replace(/\n/g, ""); } function expandPem(string){ return _.flatten([ ["-----BEGIN CERTIFICATE-----"], base64WithSplitCharLines(string), ["-----END CERTIFICATE-----"] ], true).join("\n"); } function getMacPartsFn(delimiter) { return function (element) { var initialLoc = element.indexOf(delimiter) + delimiter.length; var key = element.substring(0, element.indexOf(delimiter)); var value = element.substring(initialLoc); return [key, value]; } } function macStringToPairs(mac, splitterFn) { return _.chain(mac.split("\n")) .filter(_.identity) .map(splitterFn) .value(); } function macaroonPairsToObj(mac, splitterFn) { return _.object(macStringToPairs(mac, splitterFn)); } //this needs to be separated into own library separate from 3rd party macaroons. function find3rdPartyCaveatParts(macaroonWithCaveat, secretPem) { var macaroonSerialized = macaroonWithCaveat.macaroon; var discharge = macaroonWithCaveat.discharge; var key = new NodeRSA(); key.importKey(secretPem); var getDischargeParts = getMacPartsFn(" = "); var macObj = macaroonPairsToObj(key.decrypt(discharge).toString('utf8'), getDischargeParts); var caveatKey = macObj.caveat_key; var message = macObj.message; var macaroon = macaroons.deserialize(macaroonSerialized); var getMacaroonParts = getMacPartsFn(" "); var stringMacPairs = macStringToPairs(macaroons.details(macaroon), getMacaroonParts); var identifierLoc = _.findIndex(stringMacPairs, function (pair) { return pair[0] === "cid" && pair[1] === "enc = " + discharge; }); var caveatIdentifier = stringMacPairs[identifierLoc][1]; var caveatLocation = stringMacPairs[identifierLoc + 2][1];//kind of a hack return { caveatKey: caveatKey, macRaw: macaroonSerialized, thirdParty: { messageObj: macaroonPairsToObj(macObj.message, getDischargeParts), identifier: caveatIdentifier, location: caveatLocation } }; } function handleCertFound(jsonData, serverCertString, privKey, returnCallback){ function resolveMacs(jsonData, serverCertString, resultCallback) { function resolveMac(mac, iterCallback) { var macObj = find3rdPartyCaveatParts(mac, privKey); var rootMac = macaroons.deserialize(mac.macaroon); var messageObj = macObj.thirdParty.messageObj; var caveatKey = macObj.caveatKey; var caveatIdentifier = macObj.thirdParty.identifier; var caveatLocation = macObj.thirdParty.location; var caveatKey2 = crypto.createHash('md5').digest('hex'); var serverPemCert = expandPem(serverCertString); // console.log(pem.getPublicKey.toString()); debugger pem.getPublicKey(serverPemCert, function (err, data) { var publicKey = data.publicKey; function getDischarge(loc, thirdPartyLoc, cond, onOK, onErr) { onOK(macaroons.newMacaroon(caveatKey, caveatIdentifier, caveatLocation)); } macaroons.discharge(rootMac, getDischarge, function(discharges) { var lastDischarge = discharges[discharges.length - 1]; var macWithDischarge2 = publicKeyMacaroons.addPublicKey3rdPartyCaveat(lastDischarge, "Macattack", caveatKey2, "cert = " + condenseCertificate(serverPemCert), publicKey); iterCallback(null, [mac.macaroon, macWithDischarge2.macaroon, macWithDischarge2.discharge]); }, iterCallback); }); } function dataIsMac(data) { return data.isMac; } async.mapSeries( jsonData.data, function (data, iterCallback) { return dataIsMac(data) ? resolveMac(data.mac, iterCallback) : iterCallback(null, data); }, resultCallback); } //what was i thinking here???? hmmmm resolveMacs(jsonData, serverCertString, function (err, processedJsonData) { jsonData.data = processedJsonData; returnCallback(err, jsonData); }); } exports.handleCertFound = handleCertFound;
YUI.add("lang/inputex-timerange_fr",function(e){e.Intl.add("inputex-timerange","fr",{incorrectOrder:"La fin de la plage horaire doit \u00eatre sup\u00e9rieure \u00e0 l'heure de d\u00e9but",minTimeError:"L'heure de d\u00e9but doit \u00eatre sup\u00e9rieure \u00e0 {minTime}",separators:[!1,"H","&nbsp; \u00e0 &nbsp;","H",!1]})},"@VERSION@");
/* * This file is part of the nivo project. * * Copyright 2016-present, Raphaël Benitte. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import { memo } from 'react' import PropTypes from 'prop-types' import { BasicTooltip } from '@nivo/tooltip' const PartTooltip = memo(({ part }) => { return ( <BasicTooltip id={part.data.label} value={part.formattedValue} color={part.color} enableChip={true} /> ) }) PartTooltip.displayName = 'ChordArcTooltip' PartTooltip.propTypes = { part: PropTypes.object.isRequired, } export default PartTooltip
# Parses derivatives.yaml into autograd functions # # Each autograd function is represented by `DifferentiabilityInfo` containing # a list of `Derivative`. See `tools.codegen.api.autograd` for the data models. from collections import defaultdict, Counter import re from typing import Sequence, Any, Tuple, List, Set, Dict, Match, Optional import yaml from tools.codegen.api.autograd import (Derivative, DifferentiabilityInfo, SavedAttribute, ForwardDerivative) from tools.codegen.api.types import (Binding, CppSignatureGroup, NamedCType, BaseCType, VectorCType, intArrayRefT, tensorOptionsT, typeAndSizeT, intT, tensorGeometryT, scalarTypeT, SpecialArgName, OptionalCType, stringT) from tools.codegen.api import cpp from tools.codegen.gen import parse_native_yaml from tools.codegen.context import with_native_function from tools.codegen.model import FunctionSchema, NativeFunction, Variant, Type, SchemaKind from tools.codegen.utils import IDENT_REGEX, split_name_params try: # use faster C loader if available from yaml import CSafeLoader as Loader except ImportError: from yaml import SafeLoader as Loader # type: ignore[misc] def load_derivatives(derivatives_yaml_path: str, native_yaml_path: str) -> Sequence[DifferentiabilityInfo]: with open(derivatives_yaml_path, 'r') as f: definitions = yaml.load(f, Loader=Loader) functions = parse_native_yaml(native_yaml_path).native_functions # What's the difference between function schema v.s. signature? # function schema is the complete declaration including mutability annotation / default value and etc. # signature is the canonical schema for a group of functions (in-place/out/functional variants) # that are semantically related. functions_by_signature: Dict[FunctionSchema, List[NativeFunction]] = defaultdict(list) functions_by_schema: Dict[str, NativeFunction] = dict() for function in functions: functions_by_signature[function.func.signature()].append(function) assert str(function.func) not in functions_by_schema functions_by_schema[str(function.func)] = function infos = [ create_differentiability_info(defn, functions_by_signature, functions_by_schema) for defn in definitions] # To keep it byte-for-byte compatible with the old codegen, we assign op names as a separate # step. We only assign op names to those with differentiable args, and only append suffix to # duplicated op names. This can be simplified if the first of the duplicates can be named # 'XyzBackward' instead of 'XyzBackward0' or unconditionally append '0' to singletons. op_names = create_op_names(infos) return [ DifferentiabilityInfo( name=info.name, func=info.func, op=op_name, derivatives=info.derivatives, forward_derivatives=info.forward_derivatives, all_saved_inputs=info.all_saved_inputs, all_saved_outputs=info.all_saved_outputs, args_with_derivatives=info.args_with_derivatives, non_differentiable_arg_names=info.non_differentiable_arg_names, output_differentiability=info.output_differentiability, ) for info, op_name in zip(infos, op_names)] @with_native_function def cpp_arguments(f: NativeFunction) -> Sequence[Binding]: return CppSignatureGroup.from_native_function(f, method=False).signature.arguments() def create_derivative(f: NativeFunction, formula: str, var_names: Tuple[str, ...]) -> Derivative: original_formula = formula arguments: List[NamedCType] = [a.nctype.remove_const_ref() for a in cpp_arguments(f)] return_names = tuple(n if n != 'self' else 'result' for n in cpp.return_names(f)) return_types = tuple(cpp.return_type(r).remove_const_ref() for r in f.func.returns) named_returns = [NamedCType(name, type) for name, type in zip(return_names, return_types)] formula, saved_inputs = saved_variables(formula, arguments, var_names) formula, saved_outputs = saved_variables(formula, named_returns, var_names) # Check that the referenced derivatives in the formula are in bounds for i in used_gradient_indices(formula): if i >= len(f.func.returns): raise RuntimeError( f'Out of bounds grads access: derivative formula for {cpp.name(f.func)} ' f'used grads[{i}], but the forward only returns {len(f.func.returns)} outputs.' ) return Derivative( formula=formula, original_formula=original_formula, var_names=var_names, saved_inputs=saved_inputs, saved_outputs=saved_outputs, ) def create_forward_derivative(f: NativeFunction, formula: str, names: Tuple[str, ...]) -> ForwardDerivative: assert len(names) == 1, "Forward derivatives can define gradients for only one output at a time" var_name = names[0] var_type: Optional[Type] = None for r in f.func.returns: if r.name == var_name: var_type = r.type break # Handle default return names if var_type is None: if var_name == "result": assert len(f.func.returns) == 1 var_type = f.func.returns[0].type else: res = re.findall(r"^result(\d+)$", var_name) if len(res) == 1: arg_idx = int(res[0]) var_type = f.func.returns[arg_idx].type assert var_type is not None, "No matching output for forward derivative definition" return ForwardDerivative( formula=formula, var_name=var_name, var_type=var_type, required_inputs_fw_grad=None, required_inputs_primal=None) def postprocess_forward_derivatives( f: NativeFunction, defn_name: str, all_arg_names: List[str], derivatives: List[Derivative], forward_derivatives: List[ForwardDerivative], args_with_derivatives: Sequence[Binding] ) -> List[ForwardDerivative]: def find_required_inputs(formula: str, postfix: str) -> Tuple[str, ...]: required_inputs = set() for arg in args_with_derivatives: if arg.type == 'at::TensorList': # The functions taking TensorList handle everything internally continue arg_name = arg.name found = re.search(IDENT_REGEX.format(arg_name), formula) if found: raise RuntimeError(f"The forward formula for {defn_name} is using the base name of the {arg_name} " f"argument which is ambiguous. You should use {arg_name}_p to access the primal " f"value and {arg_name}_t to access the tangent.") found = re.search(IDENT_REGEX.format(arg_name + postfix), formula) if found: required_inputs.add(arg_name) return tuple(required_inputs) updated_derivatives: List[ForwardDerivative] = [] for defn in forward_derivatives: formula = defn.formula required_inputs_tangent = find_required_inputs(formula, "_t") if formula == "auto_element_wise": if (not len(args_with_derivatives) == 1) or len(forward_derivatives) > 1: raise RuntimeError(f"Derivative definition of {defn_name} in derivatives.yaml defines the " "forward definition of gradient as element_wise but this only " "works for functions with a single differentiable input and a " "single differentiable output.") if not len(derivatives) == 1: raise RuntimeError(f"Derivative definition of {defn_name} in derivatives.yaml defines the " "forward definition of gradient as element_wise but it does not " "defines the gradient formula for its argument which is required.") # This transformation is based on the observation that for element-wise functions, the Jacobian # matrix is diagonal and thus doing J * v is the same as (v^T J)^T (in practice, we ignore the transpositions) # For the complex case, we use hermitian transpose and get (v.conj() J).conj() # So here we are going to re-use the backward formula and replace two things: # 1) all occurrences of "grad" with "foo_t.conj()", where foo is the name of the unique differentiable input. # 2) all usage of an original input "foo" with its primal value "foo_p". # 3) conjugate the final result # For example, for abs, the backward formula is: # grad * self.sgn() # And this function generates a forward formula that is: # (self_t.conj() * self_p.sgn()).conj() backward_formula = derivatives[0].original_formula input_name = args_with_derivatives[0].name # Do replacement 1) of the grad def repl(m: Any) -> str: return f"{m.group(1)}{input_name}_t.conj(){m.group(2)}" fw_formula = re.sub(IDENT_REGEX.format("grad"), repl, backward_formula) # Do replacement 2) of the input variables for arg in args_with_derivatives: arg_name = arg.name def repl(m: Any) -> str: return f"{m.group(1)}{arg_name}_p{m.group(2)}" fw_formula = re.sub(IDENT_REGEX.format(arg_name), repl, fw_formula) # Do the final conjugate 3) fw_formula = f"({fw_formula}).conj()" # Since there is a single differentiable inputs and we necessarily need its tangent we can # simply require all differentiable input's tangent. required_inputs_tangent = tuple(all_arg_names) formula = fw_formula elif formula == "auto_linear": if len(forward_derivatives) > 1: raise RuntimeError(f"Derivative definition of {defn_name} in derivatives.yaml defines the " "forward definition of gradient as linear but this only works " "for functions with a single differentiable output.") # This transformation is based on the observation that linear functions can be written as: # y = f(x) = A * x # For some matrix A and the Jacobian of the function f is also A. # So doing J * v = A * v = f(v). # Hence to do the jvp, we simply need to evaluate the function at the point v instead of x. # We do this by calling the forward again by replacing any occurrence of the differentiable # input "foo" by it's tangent "foo_t". # Note that multiple inputs are not a problem as long as the function is truly linear wrt to # the vector where all the differentiable inputs are stacked. diff_arg_names = [arg.name for arg in args_with_derivatives] assert len(diff_arg_names) > 0 # Do replacement of input variables new_args = [] for arg_name in all_arg_names: if arg_name in diff_arg_names: arg_name = arg_name + "_t" new_args.append(arg_name) # Call into the forward again. We need two cases here to handle both Tensor methods and at:: functions. if Variant.function in f.variants: fw_formula = "at::{}({})".format(defn_name, ", ".join(new_args)) else: assert f.func.kind() is not SchemaKind.inplace assert Variant.method in f.variants fw_formula = "{}.{}({})".format(new_args[0], defn_name, ", ".join(new_args[1:])) # All of the input tangents are always used so all of them are required here. required_inputs_tangent = tuple(diff_arg_names) formula = fw_formula # At this point, the formula is final and is not modified anymore. # During forward formula, we use the primal instead of the input Tensors. # This call inspects the formula to find for which input's primal are used. required_inputs_primal = find_required_inputs(formula, "_p") updated_derivatives.append(ForwardDerivative( formula=formula, var_name=defn.var_name, var_type=defn.var_type, required_inputs_fw_grad=required_inputs_tangent, required_inputs_primal=required_inputs_primal)) return updated_derivatives def is_forward_derivative_definition(all_arg_names: List[str], names: Tuple[str, ...]) -> bool: if len(names) > 1: # Forward definition are always for a single output at a time return False name = names[0] if name not in all_arg_names: return True else: return False def create_differentiability_info( defn: Dict[Any, Any], functions_by_signature: Dict[FunctionSchema, List[NativeFunction]], functions_by_schema: Dict[str, NativeFunction], ) -> DifferentiabilityInfo: """Processes a single entry `defn` in derivatives.yaml""" def canonical_function(functions: Sequence[NativeFunction], name: str) -> NativeFunction: for f in functions: if cpp.name(f.func) == name: return f # some functions only have in-place variants assert name + '_' == cpp.name(functions[0].func) return functions[0] def split_names(raw_names: str) -> Tuple[str, ...]: """Given "foo, bar", return ["foo", "bar"].""" return tuple(x.strip() for x in raw_names.split(',')) def check_grad_usage(defn_name: str, derivatives: Sequence[Derivative]) -> None: """ Check for some subtle mistakes one might make when writing derivatives. These mistakes will compile, but will be latent until a function is used with double backwards. """ used_grad = 0 used_grads = 0 fully_implemented = True used_grads_indices: List[int] = [] for d in derivatives: formula = d.formula used_grad += len(re.findall(IDENT_REGEX.format('grad'), formula)) used_grads += len(re.findall(IDENT_REGEX.format('grads'), formula)) fully_implemented = \ fully_implemented and \ not re.search(IDENT_REGEX.format('not_implemented'), formula) used_grads_indices.extend(used_gradient_indices(formula)) assert used_grads >= len(used_grads_indices) only_used_grads_indices = used_grads == len(used_grads_indices) if used_grad and used_grads: raise RuntimeError(f"Derivative definition of {defn_name} in derivatives.yaml illegally " "mixes use of 'grad' and 'grads'. Consider replacing " "occurrences of 'grad' with 'grads[0]'") if only_used_grads_indices and set(used_grads_indices) == {0}: raise RuntimeError(f"Derivative definition of {defn_name} in derivatives.yaml solely " "refers to 'grads[0]'. If the first output is indeed the " "only differentiable output, replace 'grads[0]' with 'grad'; " "otherwise, there is a likely error in your derivatives " "declaration.") @with_native_function def set_up_derivatives(f: NativeFunction) -> Tuple[ Sequence[Derivative], Sequence[ForwardDerivative], Sequence[Binding], Sequence[str], ]: # Set up the derivative information derivatives: List[Derivative] = [] forward_derivatives: List[ForwardDerivative] = [] non_differentiable_arg_names: List[str] = [] args_with_derivatives_set: Set[str] = set() all_arg_names = [a.name for a in cpp_arguments(f)] for raw_names in sorted(defn.keys()): formula = defn[raw_names] names = split_names(raw_names) if is_forward_derivative_definition(all_arg_names, names): forward_derivatives.append(create_forward_derivative(f, formula, names)) else: if formula.lower().strip() == 'non_differentiable': non_differentiable_arg_names += names else: derivative = create_derivative(f, formula, names) derivatives.append(derivative) args_with_derivatives_set |= set(names) overlap = args_with_derivatives_set.intersection(non_differentiable_arg_names) if overlap: raise RuntimeError(f'derivatives definition for {defn} have overlapped non_differentiable ' f'and differentiable variables: {overlap}') # Next, let us determine the list of inputs in order. # TODO: do we need eagerly calculate and save it here? Can it be derived # from NativeFunction and `derivatives` on callsites instead? args_with_derivatives = [a for a in cpp_arguments(f) if a.name in args_with_derivatives_set] # Postprocess forward derivatives definitions now that we know the differentiable arguments forward_derivatives = postprocess_forward_derivatives(f, defn_name, all_arg_names, derivatives, forward_derivatives, args_with_derivatives) # Test to see if the use of 'grads' makes sense. check_grad_usage(defn_name, derivatives) return derivatives, forward_derivatives, args_with_derivatives, non_differentiable_arg_names # NB: Removes 'name' from defn dictionary specification = defn.pop('name') defn_name, _ = split_name_params(specification) # NB: Removes 'output_differentiability' from defn dictionary # `None` means all differentiable. output_differentiability = defn.pop('output_differentiability', None) schema_function = functions_by_schema.get(specification) if not schema_function: avail = '\n'.join(k for k, v in functions_by_schema.items() if cpp.name(v.func) == defn_name) raise RuntimeError(f'could not find ATen function for schema: {specification} ' f'. Available signatures:\n{avail}') # now map this to the legacy schema; this isn't technically necessary, but we'd need some logic here # to map in-place schemas to the out-of-place variants. # TODO: maybe the logic to handle the legacy schema is no longer necessary? signature = schema_function.func.signature() functions = functions_by_signature[signature] if len(functions) == 0: avail = '\n'.join(str(k) for k, v in functions_by_signature.items() if cpp.name(k) == defn_name) raise RuntimeError(f'could not find ATen function for legacy signature: {signature} ' f'corresponding to schema {specification}. Please report a bug to PyTorch. ' f'Available signatures:\n{avail}') canonical = canonical_function(functions, defn_name) if 'grad_input_mask' in (a.name for a in cpp_arguments(canonical)): raise RuntimeError(f"Schema for {defn_name} has an argument named grad_input_mask, " "but this name would be shadowed by our codegen. " "Please use a different name in native_functions.yaml.") if 'result' in (a.name for a in cpp_arguments(canonical)): raise RuntimeError(f"Schema for {defn_name} has an argument named result, " "but this is only allowed for outputs." "Please use a different name in native_functions.yaml.") derivatives, forward_derivatives, args_with_derivatives, non_differentiable_arg_names = set_up_derivatives(canonical) return DifferentiabilityInfo( name=defn_name, func=canonical, op=None, derivatives=derivatives, forward_derivatives=forward_derivatives, all_saved_inputs=dedup_vars([v for d in derivatives for v in d.saved_inputs]), all_saved_outputs=dedup_vars([v for d in derivatives for v in d.saved_outputs]), args_with_derivatives=args_with_derivatives, non_differentiable_arg_names=non_differentiable_arg_names, output_differentiability=output_differentiability, ) GRAD_INDEX_REGEX = r'(?:^|\W)grads\[(\d+)\]' def used_gradient_indices(formula: str) -> List[int]: """Determine a list of gradient indices (the i in grads[i]) that are used by the formula. >>> used_gradient_indices("foo(grads[0], grads[1])") [0, 1] """ return [int(i) for i in re.findall(GRAD_INDEX_REGEX, formula)] def saved_variables( formula: str, nctypes: List[NamedCType], var_names: Tuple[str, ...], ) -> Tuple[str, Tuple[SavedAttribute, ...]]: def stride_expr(name: str) -> str: assert var_names == (name,), ( 'Replacement for ".strides()" is currently only supported for single derivatives of the same tensor ' 'that ".strides()" is being called on.') return f'strides_or_error({name}, "{name}")' REPLACEMENTS: List[Tuple[str, Dict[str, Any]]] = [ # replace self.sizes() with self_sizes (r'{}.sizes\(\)', { 'suffix': '_sizes', 'nctype': lambda name: NamedCType(name, BaseCType(intArrayRefT)), }), # replace self.options() with self_options (r'{}.options\(\)', { 'suffix': '_options', 'nctype': lambda name: NamedCType(name, BaseCType(tensorOptionsT)), }), # replace zeros_like(self) with self_info (r'zeros_like\({}\)', { 'suffix': '_info', 'nctype': lambda name: NamedCType(name, BaseCType(typeAndSizeT)), 'expr': lambda name: name, # at save-time 'res': lambda name: name + '_info.zeros()', # at eval-time }), # replace self.size(2) with self_size_2 (r'{}.size\((\w+)\)', { 'suffix': lambda m: '_argsize_{}'.format(*m.groups()), 'nctype': lambda name: NamedCType(name, BaseCType(intT)), }), # replace self.numel() with self_numel (r'{}.numel\(\)', { 'suffix': '_numel', 'nctype': lambda name: NamedCType(name, BaseCType(intT)), }), # replace to_args_sizes(self) with self_args_sizes (r'to_args_sizes\({}\)', { 'suffix': '_args_sizes', 'nctype': lambda name: NamedCType(name, VectorCType(VectorCType(BaseCType(intT)))), }), # replace to_args_scalartypes(self) with self_args_scalartypes (r'to_args_scalartypes\({}\)', { 'suffix': '_args_scalartypes', 'nctype': lambda name: NamedCType(name, VectorCType(BaseCType(scalarTypeT))), }), # replace TensorGeometry(self) with self_geometry (r'TensorGeometry\({}\)', { 'suffix': '_geometry', 'nctype': lambda name: NamedCType(name, BaseCType(tensorGeometryT)), }), (r'{}.scalar_type\(\)', { 'suffix': '_scalar_type', 'nctype': lambda name: NamedCType(name, BaseCType(scalarTypeT)), }), # replace self.dim() with self_dim (r'{}.dim\(\)', { 'suffix': '_dim', 'nctype': lambda name: NamedCType(name, BaseCType(intT)), }), # replace self.strides() with self_strides (r'{}.strides\(\)', { 'suffix': '_strides', 'nctype': lambda name: NamedCType(name, BaseCType(intArrayRefT)), 'expr': stride_expr, }), ] # find which arguments need to be saved saved: List[SavedAttribute] = [] for nctype in nctypes: name = nctype.name.name if isinstance(nctype.name, SpecialArgName) else nctype.name # First search the formula for expressions which can be evaluated # when the autograd Function is created to avoid saving variables for regex, info in REPLACEMENTS: def repl(m: Match[str]) -> str: suffix: str = info['suffix'](m) if callable(info['suffix']) else info['suffix'] expr: str = info['expr'](name) if 'expr' in info else m.group(0) saved.append(SavedAttribute( nctype=info['nctype'](name + suffix), expr=expr, )) if 'res' in info: replacement: str = info['res'](name) return replacement return name + suffix formula = re.sub(regex.format(name), repl, formula) # c10::optional<std::string> types stored in Backward nodes must be # converted to c10::optional<c10::string_view> before being passed into # the backward function if nctype.type == OptionalCType(BaseCType(stringT)): formula = re.sub( rf'\b{name}\b', f'{name}.has_value() ? c10::optional<c10::string_view>({name}.value()) : c10::nullopt', formula) # Find any variables which remain in the formula and save them if re.search(IDENT_REGEX.format(name), formula): saved.append(SavedAttribute( nctype=nctype, expr=name, )) return formula, tuple(saved) def create_op_name(info: DifferentiabilityInfo) -> Optional[str]: # only assign an op name if we are actually going to calculate a derivative if not info.args_with_derivatives: return None name = info.name camel_case = ''.join([p.title() for p in name.split('_')]) return (camel_case + 'Backward').replace('ForwardBackward', 'Backward') def create_op_names(infos: Sequence[DifferentiabilityInfo]) -> Sequence[Optional[str]]: names = list(map(create_op_name, infos)) dups = set(item for item, count in Counter(names).items() if count > 1) # de-duplicate operation names # you end up with something like: # AddBackward0 # AddBackward1 # one for each overload counter: Dict[str, int] = Counter() dedup: List[Optional[str]] = [] for name in names: if name is None: # Keep a placeholder dedup.append(None) elif name in dups: dedup.append(f'{name}{counter[name]}') counter[name] += 1 else: dedup.append(name) return dedup def dedup_vars(vars: Sequence[SavedAttribute]) -> Sequence[SavedAttribute]: seen: Set[str] = set() saved: List[SavedAttribute] = [] for var in vars: name = var.nctype.name.name if isinstance(var.nctype.name, SpecialArgName) else var.nctype.name if name in seen: continue seen.add(name) saved.append(var) return saved
from pyramid_controllers import Controller, RestController, expose, index class ItemController(RestController): ''' @PUBLIC Provides RESTful access to the URL-specified item. ''' def not_exposed(self, *args, **kw): ''' @PUBLIC This should not be reachable. ''' @expose def subaction(self, request): ''' @PUBLIC Executes a sub-action. ''' @expose def chatter(self, request): ''' @PUBLIC Generates chatter. ''' class Root(Controller): ''' @PUBLIC Application root. ''' ITEM_ID = ItemController(expose=False) @index def index(self, request): ''' @PUBLIC Serves the homepage. ''' @expose def about(self, request): ''' @PUBLIC Serves the glorious "about us" page. '''
export const cidCastConnected = ["512 512"," <defs> <style> .cls-2{fill:currentColor} </style> </defs> <path fill='currentColor' d='M480,80H32A16,16,0,0,0,16,96v64a263.814,263.814,0,0,1,64,7.8842V143.5H432v217H272.2351A263.809,263.809,0,0,1,280,424H480a16,16,0,0,0,16-16V96A16,16,0,0,0,480,80Z' opacity='.25'/> <path d='M16,360v64H80A64,64,0,0,0,16,360Z' class='cls-2'/> <path d='M16.2539,280.6348v48a95.2187,95.2187,0,0,1,95.1113,95.1113h48C159.3652,344.8345,95.1655,280.6348,16.2539,280.6348Z' class='cls-2'/> <path d='M16.3936,197.5083v48c98.2036,0,178.0981,79.8945,178.0981,178.0981h48A224.6183,224.6183,0,0,0,176.269,263.731,224.6183,224.6183,0,0,0,16.3936,197.5083Z' class='cls-2'/>"]
# Copyright 2021 MosaicML. All Rights Reserved. import os from typing import List, Optional import pytest import torch import torch.nn as nn from composer.core.state import State from composer.core.types import Tensor from composer.trainer.ddp import DDP, FileStoreHparams from composer.trainer.devices.device_cpu import DeviceCPU class MinimalConditionalModel(nn.Module): def __init__(self): super().__init__() self.choice1 = nn.Linear(1, 1, bias=False) self.choice2 = nn.Linear(1, 1, bias=False) self.choice3 = nn.Linear(1, 1, bias=False) nn.init.constant_(self.choice1.weight, 0) nn.init.constant_(self.choice2.weight, 0) nn.init.constant_(self.choice3.weight, 0) def forward(self, input: int): if input == 1: return self.choice1(Tensor([1])) if input == 2: return self.choice2(Tensor([1])) if input == 3: return self.choice3(Tensor([1])) raise Exception("Invalid input:", input) def loss(self, output: Tensor, target: Tensor): return (output - target) * (output - target) @pytest.mark.timeout(90) @pytest.mark.parametrize("ddp_sync_strategy,expected_grads", [ pytest.param('single_auto_sync', ([-1, None, None], [-1, -1.5, None], [-1, -1.5, None]), id='single_auto_sync'), pytest.param('multi_auto_sync', ([-1.5, None, None], [-1.5, -1.5, None], [-1.5, -1.5, None]), id='multi_auto_sync'), pytest.param('forced_sync', ([-1, None, None], [-1, -1, None], [-1.5, -1.5, None]), id='forced_sync'), ]) def test_ddp_sync_strategy(ddp_sync_strategy: str, expected_grads: List[Optional[float]], ddp_tmpdir: str): original_model = MinimalConditionalModel() device = DeviceCPU(num_cpus=2) ddp = DDP(nproc_per_node=device.nproc_per_node, store_hparams=FileStoreHparams(os.path.join(ddp_tmpdir, "store")), node_rank=0, num_nodes=1, backend=device.ddp_backend, fork_rank_0=True, find_unused_parameters=True, ddp_sync_strategy=ddp_sync_strategy) optimizer = torch.optim.SGD(original_model.parameters(), 0.1) state = State(model=original_model, optimizers=optimizer, train_batch_size=1, eval_batch_size=1, grad_accum=2, max_epochs=1, precision='fp32', world_size=2, nproc_per_node=2) batches = [[(1, Tensor([1])), (1, Tensor([2]))], [(2, Tensor([1])), (2, Tensor([2]))]] def basic_train_loop(): state.model = ddp.prepare_module(state.model) optimizer.zero_grad() for microbatch_idx in range(2): with ddp.ddp_sync_context(state, microbatch_idx == 1): input, target = batches[microbatch_idx][state.local_rank] output = state.model.forward(input) loss = original_model.loss(output, target) loss.mul_(1 / 2) loss.backward() if state.is_rank_zero: grads = [p.grad.item() if p.grad else None for p in original_model.parameters()] for expected, actual in zip(expected_grads[microbatch_idx], grads): # type: ignore assert expected == actual if state.is_rank_zero: grads = [p.grad.item() if p.grad else None for p in original_model.parameters()] for expected, actual in zip(expected_grads[-1], grads): # type: ignore assert expected == actual ddp.launch(state, basic_train_loop)
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import YTSearch from 'youtube-api-search'; import _ from 'lodash'; import SearchBar from './components/search_bar'; import VideoList from './components/video_list'; import VideoDetail from './components/video_detail'; // Create a new component. // This component should produce some HTML // const App = () => { // return (<div> // <SearchBar /> // </div>); // } class App extends Component { constructor(props) { super(props); this.state = { videos: [], selectedVideo: null }; this.videoSearch('react js'); }; videoSearch(term){ YTSearch({ key: API_KEY, term: term }, (videos) => { this.setState({ videos: videos, selectedVideo: videos[0] }); }); }; render() { const videoSearch = _.debounce((term) => {this.videoSearch(term)}, 300); return ( <div> <SearchBar onSearchTermChange={videoSearch}/> <VideoDetail video={this.state.selectedVideo}/> <VideoList onVideoSelect={selectedVideo => this.setState({selectedVideo})} videos={this.state.videos}/> </div> ); } }; // Take this component's generated HTML and put it on DOM ReactDOM.render(<App />, document.querySelector('.container'));
/* * ! ${copyright} */ // Provides control sap.m.P13nSortItem. sap.ui.define([ 'jquery.sap.global', './library', 'sap/ui/core/Item' ], function(jQuery, library, Item) { "use strict"; /** * Constructor for a new P13nSortItem. * * @param {string} [sId] id for the new control, generated automatically if no id is given * @param {object} [mSettings] initial settings for the new control * @class Type for <code>sortItems</code> aggregation in P13nSortPanel control. * @extends sap.ui.core.Item * @version ${version} * @constructor * @public * @alias sap.m.P13nSortItem * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel */ var P13nSortItem = Item.extend("sap.m.P13nSortItem", /** @lends sap.m.P13nSortItem.prototype */ { metadata: { library: "sap.m", properties: { /** * sap.m.P13nConditionOperation * @since 1.26.0 */ operation: { type: "string", group: "Misc", defaultValue: null }, /** * key of the column * @since 1.26.0 */ columnKey: { type: "string", group: "Misc", defaultValue: null } } } }); return P13nSortItem; }, /* bExport= */true);
# coding: utf-8 # Note: Use conda env py2 import os import sys from dateutil.parser import parse from pytz import timezone from tqdm import tqdm from glob import glob from hdmf.data_utils import DataChunkIterator from hdmf.backends.hdf5.h5_utils import H5DataIO import h5py import numpy as np from pynwb import NWBFile, NWBHDF5IO from pynwb.behavior import Position, BehavioralTimeSeries, BehavioralEvents from pynwb.ecephys import ElectricalSeries, LFP from pynwb.ophys import OpticalChannel, TwoPhotonSeries, Fluorescence, DfOverF, ImageSegmentation, CorrectedImageStack from to_nwb.neuroscope import get_channel_groups # Losonczy Imports from lab.misc import lfp_helpers as lfph from lab.misc.auto_helpers import get_element_size_um, get_prairieview_version from lab.classes.dbclasses import dbExperiment from .sima_helper import get_motion_correction def add_motion_correction(nwbfile, expt): data = get_motion_correction(expt) cis = CorrectedImageStack( corrected=np.zeros((1, 1, 1)), xy_translation=data) imaging_mod = nwbfile.create_processing_module('imaging', 'imaging processing') imaging_mod.add_container(cis) def add_transients(nwbfile, expt): trans = expt.transientsData() trial_num = 0 nwbfile.add_unit_column('intervals', description='start and end of transient in seconds', index=True) nwbfile.add_unit_column('sigma', description='standard deviation of noise for this ROI') for roi in trans: data = roi[trial_num] intervals = np.vstack((data['start_indices'], data['start_indices'])).T * expt.frame_period() nwbfile.add_unit( spike_times=data['max_amplitudes'], intervals=intervals, sigma=float(data['sigma']) ) def get_position(region): if region == 'CA1': return [2.1, 1.5, 1.2] else: return [np.nan, np.nan, np.nan] # Add LFP (to acquisitions, though this is already downsampled and converted from rhd we for now treat this as raw) def add_LFP(nwbfile, expt, count=1, region='CA1'): eeg_local = [x for x in os.listdir(expt.LFPFilePath()) if x.endswith('.eeg')][0] eeg_file = os.path.join(expt.LFPFilePath(), eeg_local) eeg_base = eeg_file.replace('.eeg', '') eeg_dict = lfph.loadEEG(eeg_base) lfp_xml_fpath = eeg_base + '.xml' channel_groups = get_channel_groups(lfp_xml_fpath) lfp_channels = channel_groups[0] lfp_fs = eeg_dict['sampeFreq'] nchannels = eeg_dict['nChannels'] lfp_signal = eeg_dict['EEG'][lfp_channels].T device_name = 'LFP_Device_{}'.format(count) device = nwbfile.create_device(device_name) electrode_group = nwbfile.create_electrode_group( name=device_name + '_electrodes', description=device_name, device=device, location=region) x, y, z = get_position(region) for channel in channel_groups[0]: nwbfile.add_electrode(float(x), float(y), float(z), # position? imp=np.nan, location=region, filtering='See lab.misc.lfp_helpers.ConvertFromRHD', group=electrode_group, id=channel) lfp_table_region = nwbfile.create_electrode_table_region( list(range(len(lfp_channels))), 'lfp electrodes') # TODO add conversion field for moving to V # TODO figure out how to link lfp data (zipping seems kludgey) lfp_elec_series = ElectricalSeries(name='LFP', data=H5DataIO(lfp_signal, compression='gzip'), electrodes=lfp_table_region, conversion=np.nan, rate=lfp_fs, resolution=np.nan) nwbfile.add_acquisition(LFP(electrical_series=lfp_elec_series)) def add_imaging(nwbfile, expt, z_spacing=25., device_name='2P Microscope', location='CA1', indicator='GCaMP6f', excitation_lambda=920., data_root=None, stub=False): color_dict = {'Ch1': 'Red', 'Ch2': 'Green'} # Emissions for mCherry and GCaMP # TODO make this more flexible emission = {'Ch1': 640., 'Ch2': 530.} ch_names = ['Ch1', 'Ch2'] optical_channels = [] for ch_name in ch_names: optical_channel = OpticalChannel( name=ch_name, description=color_dict[ch_name], emission_lambda=emission[ch_name]) optical_channels.append(optical_channel) h5_path = glob(os.path.join(data_root, '*.h5'))[0] pv_xml = os.path.join(data_root, os.path.basename(data_root) + '.xml') pv_version = get_prairieview_version(pv_xml) [y_um, x_um] = get_element_size_um(pv_xml, pv_version)[-2:] elem_size_um = [z_spacing, y_um, x_um] # TODO allow for flexibility in setting device, excitation, indicator, location # TODO nwb-schema issue #151 needs to be resolved so we can actually use imaging data size device = nwbfile.create_device(device_name) imaging_plane = nwbfile.create_imaging_plane( name='Imaging Data', optical_channel=optical_channels, description='imaging data for both channels', device=device, excitation_lambda=excitation_lambda, imaging_rate=1 / expt.frame_period(), indicator=indicator, location=location, conversion=1.0, # Should actually be elem_size_um manifold=np.ones((2, 2, 2, 3)), reference_frame='reference_frame', unit='um') f = h5py.File(h5_path, 'r') imaging_data = f['imaging'] channel_names = f['imaging'].attrs['channel_names'] for c, channel_name in enumerate(channel_names): if not stub: data_in = H5DataIO( DataChunkIterator( tqdm( (np.swapaxes(data[..., c], 0, 2) for data in imaging_data), total=imaging_data.shape[0] ), buffer_size=5000 ), compression='gzip' ) else: data_in = np.ones((10, 10, 10)) # use for dev testing for speed # TODO parse env file to add power and pmt gain? image_series = TwoPhotonSeries(name='2p_Series_' + channel_name, dimension=expt.frame_shape()[:-1], data=data_in, imaging_plane=imaging_plane, rate=1 / expt.frame_period(), starting_time=0., description=channel_name) nwbfile.add_acquisition(image_series) # Load in Behavior Data, store position, licking, and water reward delivery times # TODO Include non-image synced data and check if there is imaging data before trying to add synced def add_behavior(nwbfile, expt): bd = expt.behaviorData(imageSync=True) fs = 1 / expt.frame_period() behavior_module = nwbfile.create_processing_module(name='Behavior', description='Data relevant to behavior') # Add Normalized Position pos = Position(name='Normalized Position') pos.create_spatial_series(name='Normalized Position', rate=fs, data=bd['treadmillPosition'][:, np.newaxis], reference_frame='0 is belt start', conversion=0.001 * bd['trackLength']) behavior_module.add_container(pos) # Add Licking licking = BehavioralTimeSeries(name='Licking') licking.create_timeseries(name='Licking', data=bd['licking'], rate=fs, unit='na', description='1 if mouse licked during this imaging frame') behavior_module.add_container(licking) # Add Water Reward Delivery water = BehavioralTimeSeries(name='Water') water.create_timeseries(name='Water', data=bd['water'], rate=fs, unit='na', description='1 if water was delivered during this imaging frame') behavior_module.add_container(water) # Add Lap Times laps = BehavioralEvents(name='Lap Starts') # TODO probably not best to have laps as data and timestamps here laps.create_timeseries(name='Lap Starts', data=bd['lap'], timestamps=bd['lap'], description='Frames at which laps began', unit='na') behavior_module.add_container(laps) # ROI Utilities def get_pixel_mask(roi): image_mask = get_image_mask(roi) inds = zip(*np.where(image_mask)) out = [list(ind) + [1.] for ind in inds] return out def get_image_mask(roi): return np.dstack([mask.toarray().T for mask in roi.mask]) def add_rois(nwbfile, module, expt): img_seg = ImageSegmentation() module.add_data_interface(img_seg) ps = img_seg.create_plane_segmentation(name='Plane Segmentation', description='ROIs', imaging_plane=nwbfile.get_imaging_plane('Imaging Data')) rois = expt.rois() for roi in rois: ps.add_roi(image_mask=get_image_mask(roi)) return ps # TODO finish this! def add_signals(module, expt, rt_region): fs = 1 / expt.frame_period() fluor = Fluorescence() sigs = expt.imagingData(dFOverF=None) fluor.create_roi_response_series(name='Fluorescence', data=sigs.squeeze(), rate=fs, unit='NA', rois=rt_region) module.add_data_interface(fluor) def add_dff(module, expt, rt_region): fs = 1 / expt.frame_period() fluor = DfOverF(name='DFF') sigs = expt.imagingData(dFOverF=None) fluor.create_roi_response_series(name='DFF', data=sigs.squeeze(), rate=fs, unit='NA', rois=rt_region) module.add_data_interface(fluor) def main(argv): data_root = '/Volumes/side_drive/data/Losonczy/from_sebi/TSeries-05042017-001' # Lab-side read expts expt = dbExperiment(10304) expt.set_sima_path('/Volumes/side_drive/data/Losonczy/from_sebi/TSeries-05042017-001/TSeries-05042017-001.sima') expt.tSeriesDirectory = data_root expt.behavior_file = os.path.join(data_root, 'svr009_20170509113637.pkl') # Initialize NWBFile directly from experiment object metadata session_start_time = timezone('US/Eastern').localize(parse(expt.get('startTime'))) nwbfile = NWBFile(session_description='{} experiment for mouse {}'.format( expt.experimentType, expt.parent.mouse_name), # required identifier='{}'.format(expt.trial_id), # required session_start_time=session_start_time, # required experimenter=expt.project_name, # optional session_id='{}-{}-{}'.format( expt.get('condition'), expt.get('day'), expt.get('session')), # optional institution='Columbia University', # optional lab='Losonczy Lab') # optional add_imaging(nwbfile, expt, data_root=data_root, stub=True) add_LFP(nwbfile, expt) add_behavior(nwbfile, expt) imaging_module = nwbfile.create_processing_module(name='ophys', description='Data relevant to imaging') ps = add_rois(nwbfile, imaging_module, expt) rt_region = ps.create_roi_table_region('all ROIs', region=list(range(len(expt.rois())))) add_signals(imaging_module, expt, rt_region) add_dff(imaging_module, expt, rt_region) add_transients(nwbfile, expt) add_motion_correction(nwbfile, expt) fout = os.path.join(data_root, 'test_file.nwb') print('writing...') with NWBHDF5IO(fout, 'w') as io: io.write(nwbfile) with NWBHDF5IO(fout) as io: io.read() """ TODO: Motion Corrections (just displacements?) for each frame, rigid body ROIs (finish) # Transients, Spikes start frame, end frame, like Unit_Times, but with start and end frame a couple hundred ROIs Place Fields skip this for now SWRs start time, end time, electrode bad time segments apply to specific TimeSeries """ if __name__ == "__main__": main(sys.argv[1:])
import React, { Component } from "react"; import { Button, Form, FormGroup, Input, } from "reactstrap"; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { notify } from "../helpers/Helper" export default class CustomModal extends Component { constructor(props) { super(props); this.state = { activeItem: this.props.activeItem, todoList: this.props.todoList, }; } handleReset = () => { Array.from(document.querySelectorAll("input")).forEach( input => (input.value = "") ); // clear input and active state this.setState({ activeItem: { title: '', description: '', priority: 1, is_completed: false, flag: 0, is_updated: false } }); }; handleSubmit = (saveMethod) => { if (this.state.activeItem.title.length > 0) { saveMethod(this.state.activeItem) // clear form and active state this.handleReset() } else { notify("Please enter a task name", "error"); } } handleChange = (e) => { let { name, value } = e.target; if (e.target.type === "checkbox") { value = e.target.checked; } const activeItem = { ...this.state.activeItem, [name]: value }; this.setState({ activeItem }); }; render() { const { onSave } = this.props; return ( <Form id="task-form"> <FormGroup> <div className="row"> <div className="col-lg-10 col-md-10 col-sm-10 col-6"> <Input type="text" id="todo-title" name="title" value={this.state.activeItem.title} onChange={this.handleChange} placeholder="Task name" className="p-3" required={true} /> </div> <div className="col-lg-2 col-md-2 col-sm-2 col-6"> <div> <Button className="bg-bluish border-0 rounded" onClick={() => this.handleSubmit(onSave)} > <FontAwesomeIcon icon="plus" className="display-6 text-primary" /> </Button> </div> </div> </div> </FormGroup> </Form> ); } }
import React from "react" import Header from "../components/header" import Footer from "../components/footer" import "@fontsource/noto-sans-jp" export default ({ children }) => ( <div> <Header /> {children} <Footer /> </div> )
import _ from 'lodash'; import { INFERENCE_CONFIG_SET, INFERENCE_CONFIG_CLEAR, INFERENCE_SUBMIT, INFERENCE_PREDICTION_CLEAR, INFERENCE_CLEAR, INFERENCE_DOWNLOAD_SET_PYTORCH, INFERENCE_DOWNLOAD_CLEAR_PYTORCH, INFERENCE_DOWNLOAD_SET_ONNX, INFERENCE_DOWNLOAD_CLEAR_ONNX, } from '../actions/types'; const inferenceReducer = (state = {}, action) => { switch (action.type) { case INFERENCE_CONFIG_SET: return { ...state, ...action.payload }; case INFERENCE_CONFIG_CLEAR: return _.omit(state, 'token', 'prediction', 'accuracy', 'accuracyPlot'); case INFERENCE_SUBMIT: return { ...state, prediction: action.payload }; case INFERENCE_PREDICTION_CLEAR: return _.omit(state, 'prediction'); case INFERENCE_DOWNLOAD_SET_PYTORCH: return { ...state, downloadUrlPytorch: action.payload.downloadUrl }; case INFERENCE_DOWNLOAD_CLEAR_PYTORCH: return _.omit(state, 'downloadUrlPytorch'); case INFERENCE_DOWNLOAD_SET_ONNX: return { ...state, downloadUrlOnnx: action.payload.downloadUrl }; case INFERENCE_DOWNLOAD_CLEAR_ONNX: return _.omit(state, 'downloadUrlOnnx'); case INFERENCE_CLEAR: return {}; default: return state; } }; export default inferenceReducer;
def matrixElementsSum(matrix): sum = 0 for l in range(len(matrix[0])): for c in range(len(matrix)): if (matrix[c][l] != 0): sum += matrix[c][l] else: break return sum
var structlldpd__frame = [ [ "frame", "structlldpd__frame.html#a202b1b267366706cc82d210a2e48f718", null ], [ "size", "structlldpd__frame.html#a87da9c25e896cb2fe4b0bfcd8c152fef", null ] ];
/******/ (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; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = 35); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports) { module.exports = jQuery; /***/ }), /* 1 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return rtl; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return GetYoDigits; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return transitionend; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); // Core Foundation Utilities, utilized in a number of places. /** * Returns a boolean for RTL support */ function rtl() { return __WEBPACK_IMPORTED_MODULE_0_jquery___default()('html').attr('dir') === 'rtl'; } /** * returns a random base-36 uid with namespacing * @function * @param {Number} length - number of random base-36 digits desired. Increase for more random strings. * @param {String} namespace - name of plugin to be incorporated in uid, optional. * @default {String} '' - if no plugin name is provided, nothing is appended to the uid. * @returns {String} - unique id */ function GetYoDigits(length, namespace) { length = length || 6; return Math.round(Math.pow(36, length + 1) - Math.random() * Math.pow(36, length)).toString(36).slice(1) + (namespace ? '-' + namespace : ''); } function transitionend($elem) { var transitions = { 'transition': 'transitionend', 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'transitionend', 'OTransition': 'otransitionend' }; var elem = document.createElement('div'), end; for (var t in transitions) { if (typeof elem.style[t] !== 'undefined') { end = transitions[t]; } } if (end) { return end; } else { end = setTimeout(function () { $elem.triggerHandler('transitionend', [$elem]); }, 1); return 'transitionend'; } } /***/ }), /* 2 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Plugin; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_core__ = __webpack_require__(1); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // Abstract class for providing lifecycle hooks. Expect plugins to define AT LEAST // {function} _setup (replaces previous constructor), // {function} _destroy (replaces previous destroy) var Plugin = function () { function Plugin(element, options) { _classCallCheck(this, Plugin); this._setup(element, options); var pluginName = getPluginName(this); this.uuid = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__foundation_util_core__["a" /* GetYoDigits */])(6, pluginName); if (!this.$element.attr('data-' + pluginName)) { this.$element.attr('data-' + pluginName, this.uuid); } if (!this.$element.data('zfPlugin')) { this.$element.data('zfPlugin', this); } /** * Fires when the plugin has initialized. * @event Plugin#init */ this.$element.trigger('init.zf.' + pluginName); } _createClass(Plugin, [{ key: 'destroy', value: function destroy() { this._destroy(); var pluginName = getPluginName(this); this.$element.removeAttr('data-' + pluginName).removeData('zfPlugin') /** * Fires when the plugin has been destroyed. * @event Plugin#destroyed */ .trigger('destroyed.zf.' + pluginName); for (var prop in this) { this[prop] = null; //clean up script to prep for garbage collection. } } }]); return Plugin; }(); // Convert PascalCase to kebab-case // Thank you: http://stackoverflow.com/a/8955580 function hyphenate(str) { return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); } function getPluginName(obj) { if (typeof obj.constructor.name !== 'undefined') { return hyphenate(obj.constructor.name); } else { return hyphenate(obj.className); } } /***/ }), /* 3 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Keyboard; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_core__ = __webpack_require__(1); /******************************************* * * * This util was created by Marius Olbertz * * Please thank Marius on GitHub /owlbertz * * or the web http://www.mariusolbertz.de/ * * * ******************************************/ var keyCodes = { 9: 'TAB', 13: 'ENTER', 27: 'ESCAPE', 32: 'SPACE', 35: 'END', 36: 'HOME', 37: 'ARROW_LEFT', 38: 'ARROW_UP', 39: 'ARROW_RIGHT', 40: 'ARROW_DOWN' }; var commands = {}; // Functions pulled out to be referenceable from internals function findFocusable($element) { if (!$element) { return false; } return $element.find('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]').filter(function () { if (!__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).is(':visible') || __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).attr('tabindex') < 0) { return false; } //only have visible elements and those that have a tabindex greater or equal 0 return true; }); } function parseKey(event) { var key = keyCodes[event.which || event.keyCode] || String.fromCharCode(event.which).toUpperCase(); // Remove un-printable characters, e.g. for `fromCharCode` calls for CTRL only events key = key.replace(/\W+/, ''); if (event.shiftKey) key = 'SHIFT_' + key; if (event.ctrlKey) key = 'CTRL_' + key; if (event.altKey) key = 'ALT_' + key; // Remove trailing underscore, in case only modifiers were used (e.g. only `CTRL_ALT`) key = key.replace(/_$/, ''); return key; } var Keyboard = { keys: getKeyCodes(keyCodes), /** * Parses the (keyboard) event and returns a String that represents its key * Can be used like Foundation.parseKey(event) === Foundation.keys.SPACE * @param {Event} event - the event generated by the event handler * @return String key - String that represents the key pressed */ parseKey: parseKey, /** * Handles the given (keyboard) event * @param {Event} event - the event generated by the event handler * @param {String} component - Foundation component's name, e.g. Slider or Reveal * @param {Objects} functions - collection of functions that are to be executed */ handleKey: function (event, component, functions) { var commandList = commands[component], keyCode = this.parseKey(event), cmds, command, fn; if (!commandList) return console.warn('Component not defined!'); if (typeof commandList.ltr === 'undefined') { // this component does not differentiate between ltr and rtl cmds = commandList; // use plain list } else { // merge ltr and rtl: if document is rtl, rtl overwrites ltr and vice versa if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__foundation_util_core__["b" /* rtl */])()) cmds = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, commandList.ltr, commandList.rtl);else cmds = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, commandList.rtl, commandList.ltr); } command = cmds[keyCode]; fn = functions[command]; if (fn && typeof fn === 'function') { // execute function if exists var returnValue = fn.apply(); if (functions.handled || typeof functions.handled === 'function') { // execute function when event was handled functions.handled(returnValue); } } else { if (functions.unhandled || typeof functions.unhandled === 'function') { // execute function when event was not handled functions.unhandled(); } } }, /** * Finds all focusable elements within the given `$element` * @param {jQuery} $element - jQuery object to search within * @return {jQuery} $focusable - all focusable elements within `$element` */ findFocusable: findFocusable, /** * Returns the component name name * @param {Object} component - Foundation component, e.g. Slider or Reveal * @return String componentName */ register: function (componentName, cmds) { commands[componentName] = cmds; }, // TODO9438: These references to Keyboard need to not require global. Will 'this' work in this context? // /** * Traps the focus in the given element. * @param {jQuery} $element jQuery object to trap the foucs into. */ trapFocus: function ($element) { var $focusable = findFocusable($element), $firstFocusable = $focusable.eq(0), $lastFocusable = $focusable.eq(-1); $element.on('keydown.zf.trapfocus', function (event) { if (event.target === $lastFocusable[0] && parseKey(event) === 'TAB') { event.preventDefault(); $firstFocusable.focus(); } else if (event.target === $firstFocusable[0] && parseKey(event) === 'SHIFT_TAB') { event.preventDefault(); $lastFocusable.focus(); } }); }, /** * Releases the trapped focus from the given element. * @param {jQuery} $element jQuery object to release the focus for. */ releaseFocus: function ($element) { $element.off('keydown.zf.trapfocus'); } }; /* * Constants for easier comparing. * Can be used like Foundation.parseKey(event) === Foundation.keys.SPACE */ function getKeyCodes(kcs) { var k = {}; for (var kc in kcs) { k[kcs[kc]] = kcs[kc]; }return k; } /***/ }), /* 4 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return MediaQuery; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); // Default set of media queries var defaultQueries = { 'default': 'only screen', landscape: 'only screen and (orientation: landscape)', portrait: 'only screen and (orientation: portrait)', retina: 'only screen and (-webkit-min-device-pixel-ratio: 2),' + 'only screen and (min--moz-device-pixel-ratio: 2),' + 'only screen and (-o-min-device-pixel-ratio: 2/1),' + 'only screen and (min-device-pixel-ratio: 2),' + 'only screen and (min-resolution: 192dpi),' + 'only screen and (min-resolution: 2dppx)' }; // 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 var 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 && script.parentNode && 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' }; }; }(); var MediaQuery = { queries: [], current: '', /** * Initializes the media query helper, by extracting the breakpoint list from the CSS and activating the breakpoint watcher. * @function * @private */ _init: function () { var self = this; var $meta = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('meta.foundation-mq'); if (!$meta.length) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()('<meta class="foundation-mq">').appendTo(document.head); } var extractedStyles = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('.foundation-mq').css('font-family'); var namedQueries; namedQueries = parseStyleToObject(extractedStyles); for (var key in namedQueries) { if (namedQueries.hasOwnProperty(key)) { self.queries.push({ name: key, value: 'only screen and (min-width: ' + namedQueries[key] + ')' }); } } this.current = this._getCurrentSize(); this._watcher(); }, /** * Checks if the screen is at least as wide as a breakpoint. * @function * @param {String} size - Name of the breakpoint to check. * @returns {Boolean} `true` if the breakpoint matches, `false` if it's smaller. */ atLeast: function (size) { var query = this.get(size); if (query) { return matchMedia(query).matches; } return false; }, /** * Checks if the screen matches to a breakpoint. * @function * @param {String} size - Name of the breakpoint to check, either 'small only' or 'small'. Omitting 'only' falls back to using atLeast() method. * @returns {Boolean} `true` if the breakpoint matches, `false` if it does not. */ is: function (size) { size = size.trim().split(' '); if (size.length > 1 && size[1] === 'only') { if (size[0] === this._getCurrentSize()) return true; } else { return this.atLeast(size[0]); } return false; }, /** * Gets the media query of a breakpoint. * @function * @param {String} size - Name of the breakpoint to get. * @returns {String|null} - The media query of the breakpoint, or `null` if the breakpoint doesn't exist. */ get: function (size) { for (var i in this.queries) { if (this.queries.hasOwnProperty(i)) { var query = this.queries[i]; if (size === query.name) return query.value; } } return null; }, /** * Gets the current breakpoint name by testing every breakpoint and returning the last one to match (the biggest one). * @function * @private * @returns {String} Name of the current breakpoint. */ _getCurrentSize: function () { var matched; for (var i = 0; i < this.queries.length; i++) { var query = this.queries[i]; if (matchMedia(query.value).matches) { matched = query; } } if (typeof matched === 'object') { return matched.name; } else { return matched; } }, /** * Activates the breakpoint watcher, which fires an event on the window whenever the breakpoint changes. * @function * @private */ _watcher: function () { var _this = this; __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off('resize.zf.mediaquery').on('resize.zf.mediaquery', function () { var newSize = _this._getCurrentSize(), currentSize = _this.current; if (newSize !== currentSize) { // Change the current media query _this.current = newSize; // Broadcast the media query change on the window __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).trigger('changed.zf.mediaquery', [newSize, currentSize]); } }); } }; // Thank you: https://github.com/sindresorhus/query-string function parseStyleToObject(str) { var styleObject = {}; if (typeof str !== 'string') { return styleObject; } str = str.trim().slice(1, -1); // browsers re-quote string style values if (!str) { return styleObject; } styleObject = str.split('&').reduce(function (ret, param) { var parts = param.replace(/\+/g, ' ').split('='); var key = parts[0]; var val = parts[1]; key = decodeURIComponent(key); // missing `=` should be `null`: // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters val = val === undefined ? null : decodeURIComponent(val); if (!ret.hasOwnProperty(key)) { ret[key] = val; } else if (Array.isArray(ret[key])) { ret[key].push(val); } else { ret[key] = [ret[key], val]; } return ret; }, {}); return styleObject; } /***/ }), /* 5 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Triggers; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__ = __webpack_require__(6); var MutationObserver = function () { var prefixes = ['WebKit', 'Moz', 'O', 'Ms', '']; for (var i = 0; i < prefixes.length; i++) { if (prefixes[i] + 'MutationObserver' in window) { return window[prefixes[i] + 'MutationObserver']; } } return false; }(); var triggers = function (el, type) { el.data(type).split(' ').forEach(function (id) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + id)[type === 'close' ? 'trigger' : 'triggerHandler'](type + '.zf.trigger', [el]); }); }; var Triggers = { Listeners: { Basic: {}, Global: {} }, Initializers: {} }; Triggers.Listeners.Basic = { openListener: function () { triggers(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), 'open'); }, closeListener: function () { var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('close'); if (id) { triggers(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), 'close'); } else { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('close.zf.trigger'); } }, toggleListener: function () { var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('toggle'); if (id) { triggers(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), 'toggle'); } else { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('toggle.zf.trigger'); } }, closeableListener: function (e) { e.stopPropagation(); var animation = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('closable'); if (animation !== '') { __WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__["a" /* Motion */].animateOut(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), animation, function () { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('closed.zf'); }); } else { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).fadeOut().trigger('closed.zf'); } }, toggleFocusListener: function () { var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('toggle-focus'); __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + id).triggerHandler('toggle.zf.trigger', [__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this)]); } }; // Elements with [data-open] will reveal a plugin that supports it when clicked. Triggers.Initializers.addOpenListener = function ($elem) { $elem.off('click.zf.trigger', Triggers.Listeners.Basic.openListener); $elem.on('click.zf.trigger', '[data-open]', Triggers.Listeners.Basic.openListener); }; // Elements with [data-close] will close a plugin that supports it when clicked. // If used without a value on [data-close], the event will bubble, allowing it to close a parent component. Triggers.Initializers.addCloseListener = function ($elem) { $elem.off('click.zf.trigger', Triggers.Listeners.Basic.closeListener); $elem.on('click.zf.trigger', '[data-close]', Triggers.Listeners.Basic.closeListener); }; // Elements with [data-toggle] will toggle a plugin that supports it when clicked. Triggers.Initializers.addToggleListener = function ($elem) { $elem.off('click.zf.trigger', Triggers.Listeners.Basic.toggleListener); $elem.on('click.zf.trigger', '[data-toggle]', Triggers.Listeners.Basic.toggleListener); }; // Elements with [data-closable] will respond to close.zf.trigger events. Triggers.Initializers.addCloseableListener = function ($elem) { $elem.off('close.zf.trigger', Triggers.Listeners.Basic.closeableListener); $elem.on('close.zf.trigger', '[data-closeable], [data-closable]', Triggers.Listeners.Basic.closeableListener); }; // Elements with [data-toggle-focus] will respond to coming in and out of focus Triggers.Initializers.addToggleFocusListener = function ($elem) { $elem.off('focus.zf.trigger blur.zf.trigger', Triggers.Listeners.Basic.toggleFocusListener); $elem.on('focus.zf.trigger blur.zf.trigger', '[data-toggle-focus]', Triggers.Listeners.Basic.toggleFocusListener); }; // More Global/complex listeners and triggers Triggers.Listeners.Global = { resizeListener: function ($nodes) { if (!MutationObserver) { //fallback for IE 9 $nodes.each(function () { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).triggerHandler('resizeme.zf.trigger'); }); } //trigger all listening elements and signal a resize event $nodes.attr('data-events', "resize"); }, scrollListener: function ($nodes) { if (!MutationObserver) { //fallback for IE 9 $nodes.each(function () { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).triggerHandler('scrollme.zf.trigger'); }); } //trigger all listening elements and signal a scroll event $nodes.attr('data-events', "scroll"); }, closeMeListener: function (e, pluginId) { var plugin = e.namespace.split('.')[0]; var plugins = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-' + plugin + ']').not('[data-yeti-box="' + pluginId + '"]'); plugins.each(function () { var _this = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this); _this.triggerHandler('close.zf.trigger', [_this]); }); } }; // Global, parses whole document. Triggers.Initializers.addClosemeListener = function (pluginName) { var yetiBoxes = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-yeti-box]'), plugNames = ['dropdown', 'tooltip', 'reveal']; if (pluginName) { if (typeof pluginName === 'string') { plugNames.push(pluginName); } else if (typeof pluginName === 'object' && typeof pluginName[0] === 'string') { plugNames.concat(pluginName); } else { console.error('Plugin names must be strings'); } } if (yetiBoxes.length) { var listeners = plugNames.map(function (name) { return 'closeme.zf.' + name; }).join(' '); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(listeners).on(listeners, Triggers.Listeners.Global.closeMeListener); } }; function debounceGlobalListener(debounce, trigger, listener) { var timer = void 0, args = Array.prototype.slice.call(arguments, 3); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(trigger).on(trigger, function (e) { if (timer) { clearTimeout(timer); } timer = setTimeout(function () { listener.apply(null, args); }, debounce || 10); //default time to emit scroll event }); } Triggers.Initializers.addResizeListener = function (debounce) { var $nodes = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-resize]'); if ($nodes.length) { debounceGlobalListener(debounce, 'resize.zf.trigger', Triggers.Listeners.Global.resizeListener, $nodes); } }; Triggers.Initializers.addScrollListener = function (debounce) { var $nodes = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-scroll]'); if ($nodes.length) { debounceGlobalListener(debounce, 'scroll.zf.trigger', Triggers.Listeners.Global.scrollListener, $nodes); } }; Triggers.Initializers.addMutationEventsListener = function ($elem) { if (!MutationObserver) { return false; } var $nodes = $elem.find('[data-resize], [data-scroll], [data-mutate]'); //element callback var listeningElementsMutation = function (mutationRecordsList) { var $target = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(mutationRecordsList[0].target); //trigger the event handler for the element depending on type switch (mutationRecordsList[0].type) { case "attributes": if ($target.attr("data-events") === "scroll" && mutationRecordsList[0].attributeName === "data-events") { $target.triggerHandler('scrollme.zf.trigger', [$target, window.pageYOffset]); } if ($target.attr("data-events") === "resize" && mutationRecordsList[0].attributeName === "data-events") { $target.triggerHandler('resizeme.zf.trigger', [$target]); } if (mutationRecordsList[0].attributeName === "style") { $target.closest("[data-mutate]").attr("data-events", "mutate"); $target.closest("[data-mutate]").triggerHandler('mutateme.zf.trigger', [$target.closest("[data-mutate]")]); } break; case "childList": $target.closest("[data-mutate]").attr("data-events", "mutate"); $target.closest("[data-mutate]").triggerHandler('mutateme.zf.trigger', [$target.closest("[data-mutate]")]); break; default: return false; //nothing } }; if ($nodes.length) { //for each element that needs to listen for resizing, scrolling, or mutation add a single observer for (var i = 0; i <= $nodes.length - 1; i++) { var elementObserver = new MutationObserver(listeningElementsMutation); elementObserver.observe($nodes[i], { attributes: true, childList: true, characterData: false, subtree: true, attributeFilter: ["data-events", "style"] }); } } }; Triggers.Initializers.addSimpleListeners = function () { var $document = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(document); Triggers.Initializers.addOpenListener($document); Triggers.Initializers.addCloseListener($document); Triggers.Initializers.addToggleListener($document); Triggers.Initializers.addCloseableListener($document); Triggers.Initializers.addToggleFocusListener($document); }; Triggers.Initializers.addGlobalListeners = function () { var $document = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(document); Triggers.Initializers.addMutationEventsListener($document); Triggers.Initializers.addResizeListener(); Triggers.Initializers.addScrollListener(); Triggers.Initializers.addClosemeListener(); }; Triggers.init = function ($, Foundation) { if (typeof $.triggersInitialized === 'undefined') { var $document = $(document); if (document.readyState === "complete") { Triggers.Initializers.addSimpleListeners(); Triggers.Initializers.addGlobalListeners(); } else { $(window).on('load', function () { Triggers.Initializers.addSimpleListeners(); Triggers.Initializers.addGlobalListeners(); }); } $.triggersInitialized = true; } if (Foundation) { Foundation.Triggers = Triggers; // Legacy included to be backwards compatible for now. Foundation.IHearYou = Triggers.Initializers.addGlobalListeners; } }; /***/ }), /* 6 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Move; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Motion; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_core__ = __webpack_require__(1); /** * Motion module. * @module foundation.motion */ var initClasses = ['mui-enter', 'mui-leave']; var activeClasses = ['mui-enter-active', 'mui-leave-active']; var Motion = { animateIn: function (element, animation, cb) { animate(true, element, animation, cb); }, animateOut: function (element, animation, cb) { animate(false, element, animation, cb); } }; function Move(duration, elem, fn) { var anim, prog, start = null; // console.log('called'); if (duration === 0) { fn.apply(elem); elem.trigger('finished.zf.animate', [elem]).triggerHandler('finished.zf.animate', [elem]); return; } function move(ts) { if (!start) start = ts; // console.log(start, ts); prog = ts - start; fn.apply(elem); if (prog < duration) { anim = window.requestAnimationFrame(move, elem); } else { window.cancelAnimationFrame(anim); elem.trigger('finished.zf.animate', [elem]).triggerHandler('finished.zf.animate', [elem]); } } anim = window.requestAnimationFrame(move); } /** * Animates an element in or out using a CSS transition class. * @function * @private * @param {Boolean} isIn - Defines if the animation is in or out. * @param {Object} element - jQuery or HTML object to animate. * @param {String} animation - CSS class to use. * @param {Function} cb - Callback to run when animation is finished. */ function animate(isIn, element, animation, cb) { element = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(element).eq(0); if (!element.length) return; var initClass = isIn ? initClasses[0] : initClasses[1]; var activeClass = isIn ? activeClasses[0] : activeClasses[1]; // Set up the animation reset(); element.addClass(animation).css('transition', 'none'); requestAnimationFrame(function () { element.addClass(initClass); if (isIn) element.show(); }); // Start the animation requestAnimationFrame(function () { element[0].offsetWidth; element.css('transition', '').addClass(activeClass); }); // Clean up the animation when it finishes element.one(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__foundation_util_core__["c" /* transitionend */])(element), finish); // Hides the element (for out animations), resets the element, and runs a callback function finish() { if (!isIn) element.hide(); reset(); if (cb) cb.apply(element); } // Resets transitions and removes motion-specific classes function reset() { element[0].style.transitionDuration = 0; element.removeClass(initClass + ' ' + activeClass + ' ' + animation); } } /***/ }), /* 7 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Box; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foundation_util_core__ = __webpack_require__(1); var Box = { ImNotTouchingYou: ImNotTouchingYou, OverlapArea: OverlapArea, GetDimensions: GetDimensions, GetOffsets: GetOffsets, GetExplicitOffsets: GetExplicitOffsets }; /** * Compares the dimensions of an element to a container and determines collision events with container. * @function * @param {jQuery} element - jQuery object to test for collisions. * @param {jQuery} parent - jQuery object to use as bounding container. * @param {Boolean} lrOnly - set to true to check left and right values only. * @param {Boolean} tbOnly - set to true to check top and bottom values only. * @default if no parent object passed, detects collisions with `window`. * @returns {Boolean} - true if collision free, false if a collision in any direction. */ function ImNotTouchingYou(element, parent, lrOnly, tbOnly, ignoreBottom) { return OverlapArea(element, parent, lrOnly, tbOnly, ignoreBottom) === 0; }; function OverlapArea(element, parent, lrOnly, tbOnly, ignoreBottom) { var eleDims = GetDimensions(element), topOver, bottomOver, leftOver, rightOver; if (parent) { var parDims = GetDimensions(parent); bottomOver = parDims.height + parDims.offset.top - (eleDims.offset.top + eleDims.height); topOver = eleDims.offset.top - parDims.offset.top; leftOver = eleDims.offset.left - parDims.offset.left; rightOver = parDims.width + parDims.offset.left - (eleDims.offset.left + eleDims.width); } else { bottomOver = eleDims.windowDims.height + eleDims.windowDims.offset.top - (eleDims.offset.top + eleDims.height); topOver = eleDims.offset.top - eleDims.windowDims.offset.top; leftOver = eleDims.offset.left - eleDims.windowDims.offset.left; rightOver = eleDims.windowDims.width - (eleDims.offset.left + eleDims.width); } bottomOver = ignoreBottom ? 0 : Math.min(bottomOver, 0); topOver = Math.min(topOver, 0); leftOver = Math.min(leftOver, 0); rightOver = Math.min(rightOver, 0); if (lrOnly) { return leftOver + rightOver; } if (tbOnly) { return topOver + bottomOver; } // use sum of squares b/c we care about overlap area. return Math.sqrt(topOver * topOver + bottomOver * bottomOver + leftOver * leftOver + rightOver * rightOver); } /** * Uses native methods to return an object of dimension values. * @function * @param {jQuery || HTML} element - jQuery object or DOM element for which to get the dimensions. Can be any element other that document or window. * @returns {Object} - nested object of integer pixel values * TODO - if element is window, return only those values. */ function GetDimensions(elem, test) { elem = elem.length ? elem[0] : elem; if (elem === window || elem === document) { throw new Error("I'm sorry, Dave. I'm afraid I can't do that."); } var rect = elem.getBoundingClientRect(), parRect = elem.parentNode.getBoundingClientRect(), winRect = document.body.getBoundingClientRect(), winY = window.pageYOffset, winX = window.pageXOffset; return { width: rect.width, height: rect.height, offset: { top: rect.top + winY, left: rect.left + winX }, parentDims: { width: parRect.width, height: parRect.height, offset: { top: parRect.top + winY, left: parRect.left + winX } }, windowDims: { width: winRect.width, height: winRect.height, offset: { top: winY, left: winX } } }; } /** * Returns an object of top and left integer pixel values for dynamically rendered elements, * such as: Tooltip, Reveal, and Dropdown. Maintained for backwards compatibility, and where * you don't know alignment, but generally from * 6.4 forward you should use GetExplicitOffsets, as GetOffsets conflates position and alignment. * @function * @param {jQuery} element - jQuery object for the element being positioned. * @param {jQuery} anchor - jQuery object for the element's anchor point. * @param {String} position - a string relating to the desired position of the element, relative to it's anchor * @param {Number} vOffset - integer pixel value of desired vertical separation between anchor and element. * @param {Number} hOffset - integer pixel value of desired horizontal separation between anchor and element. * @param {Boolean} isOverflow - if a collision event is detected, sets to true to default the element to full width - any desired offset. * TODO alter/rewrite to work with `em` values as well/instead of pixels */ function GetOffsets(element, anchor, position, vOffset, hOffset, isOverflow) { console.log("NOTE: GetOffsets is deprecated in favor of GetExplicitOffsets and will be removed in 6.5"); switch (position) { case 'top': return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__foundation_util_core__["b" /* rtl */])() ? GetExplicitOffsets(element, anchor, 'top', 'left', vOffset, hOffset, isOverflow) : GetExplicitOffsets(element, anchor, 'top', 'right', vOffset, hOffset, isOverflow); case 'bottom': return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__foundation_util_core__["b" /* rtl */])() ? GetExplicitOffsets(element, anchor, 'bottom', 'left', vOffset, hOffset, isOverflow) : GetExplicitOffsets(element, anchor, 'bottom', 'right', vOffset, hOffset, isOverflow); case 'center top': return GetExplicitOffsets(element, anchor, 'top', 'center', vOffset, hOffset, isOverflow); case 'center bottom': return GetExplicitOffsets(element, anchor, 'bottom', 'center', vOffset, hOffset, isOverflow); case 'center left': return GetExplicitOffsets(element, anchor, 'left', 'center', vOffset, hOffset, isOverflow); case 'center right': return GetExplicitOffsets(element, anchor, 'right', 'center', vOffset, hOffset, isOverflow); case 'left bottom': return GetExplicitOffsets(element, anchor, 'bottom', 'left', vOffset, hOffset, isOverflow); case 'right bottom': return GetExplicitOffsets(element, anchor, 'bottom', 'right', vOffset, hOffset, isOverflow); // Backwards compatibility... this along with the reveal and reveal full // classes are the only ones that didn't reference anchor case 'center': return { left: $eleDims.windowDims.offset.left + $eleDims.windowDims.width / 2 - $eleDims.width / 2 + hOffset, top: $eleDims.windowDims.offset.top + $eleDims.windowDims.height / 2 - ($eleDims.height / 2 + vOffset) }; case 'reveal': return { left: ($eleDims.windowDims.width - $eleDims.width) / 2 + hOffset, top: $eleDims.windowDims.offset.top + vOffset }; case 'reveal full': return { left: $eleDims.windowDims.offset.left, top: $eleDims.windowDims.offset.top }; break; default: return { left: __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_0__foundation_util_core__["b" /* rtl */])() ? $anchorDims.offset.left - $eleDims.width + $anchorDims.width - hOffset : $anchorDims.offset.left + hOffset, top: $anchorDims.offset.top + $anchorDims.height + vOffset }; } } function GetExplicitOffsets(element, anchor, position, alignment, vOffset, hOffset, isOverflow) { var $eleDims = GetDimensions(element), $anchorDims = anchor ? GetDimensions(anchor) : null; var topVal, leftVal; // set position related attribute switch (position) { case 'top': topVal = $anchorDims.offset.top - ($eleDims.height + vOffset); break; case 'bottom': topVal = $anchorDims.offset.top + $anchorDims.height + vOffset; break; case 'left': leftVal = $anchorDims.offset.left - ($eleDims.width + hOffset); break; case 'right': leftVal = $anchorDims.offset.left + $anchorDims.width + hOffset; break; } // set alignment related attribute switch (position) { case 'top': case 'bottom': switch (alignment) { case 'left': leftVal = $anchorDims.offset.left + hOffset; break; case 'right': leftVal = $anchorDims.offset.left - $eleDims.width + $anchorDims.width - hOffset; break; case 'center': leftVal = isOverflow ? hOffset : $anchorDims.offset.left + $anchorDims.width / 2 - $eleDims.width / 2 + hOffset; break; } break; case 'right': case 'left': switch (alignment) { case 'bottom': topVal = $anchorDims.offset.top - vOffset + $anchorDims.height - $eleDims.height; break; case 'top': topVal = $anchorDims.offset.top + vOffset; break; case 'center': topVal = $anchorDims.offset.top + vOffset + $anchorDims.height / 2 - $eleDims.height / 2; break; } break; } return { top: topVal, left: leftVal }; } /***/ }), /* 8 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return onImagesLoaded; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /** * Runs a callback function when images are fully loaded. * @param {Object} images - Image(s) to check if loaded. * @param {Func} callback - Function to execute when image is fully loaded. */ function onImagesLoaded(images, callback) { var self = this, unloaded = images.length; if (unloaded === 0) { callback(); } images.each(function () { // Check if image is loaded if (this.complete && this.naturalWidth !== undefined) { singleImageLoaded(); } else { // If the above check failed, simulate loading on detached element. var image = new Image(); // Still count image as loaded if it finalizes with an error. var events = "load.zf.images error.zf.images"; __WEBPACK_IMPORTED_MODULE_0_jquery___default()(image).one(events, function me(event) { // Unbind the event listeners. We're using 'one' but only one of the two events will have fired. __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).off(events, me); singleImageLoaded(); }); image.src = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).attr('src'); } }); function singleImageLoaded() { unloaded--; if (unloaded === 0) { callback(); } } } /***/ }), /* 9 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Nest; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); var Nest = { Feather: function (menu) { var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'zf'; menu.attr('role', 'menubar'); var items = menu.find('li').attr({ 'role': 'menuitem' }), subMenuClass = 'is-' + type + '-submenu', subItemClass = subMenuClass + '-item', hasSubClass = 'is-' + type + '-submenu-parent', applyAria = type !== 'accordion'; // Accordions handle their own ARIA attriutes. items.each(function () { var $item = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), $sub = $item.children('ul'); if ($sub.length) { $item.addClass(hasSubClass); $sub.addClass('submenu ' + subMenuClass).attr({ 'data-submenu': '' }); if (applyAria) { $item.attr({ 'aria-haspopup': true, 'aria-label': $item.children('a:first').text() }); // Note: Drilldowns behave differently in how they hide, and so need // additional attributes. We should look if this possibly over-generalized // utility (Nest) is appropriate when we rework menus in 6.4 if (type === 'drilldown') { $item.attr({ 'aria-expanded': false }); } } $sub.addClass('submenu ' + subMenuClass).attr({ 'data-submenu': '', 'role': 'menu' }); if (type === 'drilldown') { $sub.attr({ 'aria-hidden': true }); } } if ($item.parent('[data-submenu]').length) { $item.addClass('is-submenu-item ' + subItemClass); } }); return; }, Burn: function (menu, type) { var //items = menu.find('li'), subMenuClass = 'is-' + type + '-submenu', subItemClass = subMenuClass + '-item', hasSubClass = 'is-' + type + '-submenu-parent'; menu.find('>li, .menu, .menu > li').removeClass(subMenuClass + ' ' + subItemClass + ' ' + hasSubClass + ' is-submenu-item submenu is-active').removeAttr('data-submenu').css('display', ''); } }; /***/ }), /* 10 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Accordion; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_plugin__ = __webpack_require__(2); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Accordion module. * @module foundation.accordion * @requires foundation.util.keyboard */ var Accordion = function (_Plugin) { _inherits(Accordion, _Plugin); function Accordion() { _classCallCheck(this, Accordion); return _possibleConstructorReturn(this, (Accordion.__proto__ || Object.getPrototypeOf(Accordion)).apply(this, arguments)); } _createClass(Accordion, [{ key: '_setup', /** * Creates a new instance of an accordion. * @class * @fires Accordion#init * @param {jQuery} element - jQuery object to make into an accordion. * @param {Object} options - a plain object with settings to override the default options. */ value: function _setup(element, options) { this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Accordion.defaults, this.$element.data(), options); this.className = 'Accordion'; // ie9 back compat this._init(); __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].register('Accordion', { 'ENTER': 'toggle', 'SPACE': 'toggle', 'ARROW_DOWN': 'next', 'ARROW_UP': 'previous' }); } /** * Initializes the accordion by animating the preset active pane(s). * @private */ }, { key: '_init', value: function _init() { var _this3 = this; this.$element.attr('role', 'tablist'); this.$tabs = this.$element.children('[data-accordion-item]'); this.$tabs.each(function (idx, el) { var $el = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(el), $content = $el.children('[data-tab-content]'), id = $content[0].id || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__foundation_util_core__["a" /* GetYoDigits */])(6, 'accordion'), linkId = el.id || id + '-label'; $el.find('a:first').attr({ 'aria-controls': id, 'role': 'tab', 'id': linkId, 'aria-expanded': false, 'aria-selected': false }); $content.attr({ 'role': 'tabpanel', 'aria-labelledby': linkId, 'aria-hidden': true, 'id': id }); }); var $initActive = this.$element.find('.is-active').children('[data-tab-content]'); this.firstTimeInit = true; if ($initActive.length) { this.down($initActive, this.firstTimeInit); this.firstTimeInit = false; } this._checkDeepLink = function () { var anchor = window.location.hash; //need a hash and a relevant anchor in this tabset if (anchor.length) { var $link = _this3.$element.find('[href$="' + anchor + '"]'), $anchor = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(anchor); if ($link.length && $anchor) { if (!$link.parent('[data-accordion-item]').hasClass('is-active')) { _this3.down($anchor, _this3.firstTimeInit); _this3.firstTimeInit = false; }; //roll up a little to show the titles if (_this3.options.deepLinkSmudge) { var _this = _this3; __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).load(function () { var offset = _this.$element.offset(); __WEBPACK_IMPORTED_MODULE_0_jquery___default()('html, body').animate({ scrollTop: offset.top }, _this.options.deepLinkSmudgeDelay); }); } /** * Fires when the zplugin has deeplinked at pageload * @event Accordion#deeplink */ _this3.$element.trigger('deeplink.zf.accordion', [$link, $anchor]); } } }; //use browser to open a tab, if it exists in this tabset if (this.options.deepLink) { this._checkDeepLink(); } this._events(); } /** * Adds event handlers for items within the accordion. * @private */ }, { key: '_events', value: function _events() { var _this = this; this.$tabs.each(function () { var $elem = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this); var $tabContent = $elem.children('[data-tab-content]'); if ($tabContent.length) { $elem.children('a').off('click.zf.accordion keydown.zf.accordion').on('click.zf.accordion', function (e) { e.preventDefault(); _this.toggle($tabContent); }).on('keydown.zf.accordion', function (e) { __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].handleKey(e, 'Accordion', { toggle: function () { _this.toggle($tabContent); }, next: function () { var $a = $elem.next().find('a').focus(); if (!_this.options.multiExpand) { $a.trigger('click.zf.accordion'); } }, previous: function () { var $a = $elem.prev().find('a').focus(); if (!_this.options.multiExpand) { $a.trigger('click.zf.accordion'); } }, handled: function () { e.preventDefault(); e.stopPropagation(); } }); }); } }); if (this.options.deepLink) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).on('popstate', this._checkDeepLink); } } /** * Toggles the selected content pane's open/close state. * @param {jQuery} $target - jQuery object of the pane to toggle (`.accordion-content`). * @function */ }, { key: 'toggle', value: function toggle($target) { if ($target.closest('[data-accordion]').is('[disabled]')) { console.info('Cannot toggle an accordion that is disabled.'); return; } if ($target.parent().hasClass('is-active')) { this.up($target); } else { this.down($target); } //either replace or update browser history if (this.options.deepLink) { var anchor = $target.prev('a').attr('href'); if (this.options.updateHistory) { history.pushState({}, '', anchor); } else { history.replaceState({}, '', anchor); } } } /** * Opens the accordion tab defined by `$target`. * @param {jQuery} $target - Accordion pane to open (`.accordion-content`). * @param {Boolean} firstTime - flag to determine if reflow should happen. * @fires Accordion#down * @function */ }, { key: 'down', value: function down($target, firstTime) { var _this4 = this; /** * checking firstTime allows for initial render of the accordion * to render preset is-active panes. */ if ($target.closest('[data-accordion]').is('[disabled]') && !firstTime) { console.info('Cannot call down on an accordion that is disabled.'); return; } $target.attr('aria-hidden', false).parent('[data-tab-content]').addBack().parent().addClass('is-active'); if (!this.options.multiExpand && !firstTime) { var $currentActive = this.$element.children('.is-active').children('[data-tab-content]'); if ($currentActive.length) { this.up($currentActive.not($target)); } } $target.slideDown(this.options.slideSpeed, function () { /** * Fires when the tab is done opening. * @event Accordion#down */ _this4.$element.trigger('down.zf.accordion', [$target]); }); __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + $target.attr('aria-labelledby')).attr({ 'aria-expanded': true, 'aria-selected': true }); } /** * Closes the tab defined by `$target`. * @param {jQuery} $target - Accordion tab to close (`.accordion-content`). * @fires Accordion#up * @function */ }, { key: 'up', value: function up($target) { if ($target.closest('[data-accordion]').is('[disabled]')) { console.info('Cannot call up on an accordion that is disabled.'); return; } var $aunts = $target.parent().siblings(), _this = this; if (!this.options.allowAllClosed && !$aunts.hasClass('is-active') || !$target.parent().hasClass('is-active')) { return; } $target.slideUp(_this.options.slideSpeed, function () { /** * Fires when the tab is done collapsing up. * @event Accordion#up */ _this.$element.trigger('up.zf.accordion', [$target]); }); $target.attr('aria-hidden', true).parent().removeClass('is-active'); __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + $target.attr('aria-labelledby')).attr({ 'aria-expanded': false, 'aria-selected': false }); } /** * Destroys an instance of an accordion. * @fires Accordion#destroyed * @function */ }, { key: '_destroy', value: function _destroy() { this.$element.find('[data-tab-content]').stop(true).slideUp(0).css('display', ''); this.$element.find('a').off('.zf.accordion'); if (this.options.deepLink) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off('popstate', this._checkDeepLink); } } }]); return Accordion; }(__WEBPACK_IMPORTED_MODULE_3__foundation_plugin__["a" /* Plugin */]); Accordion.defaults = { /** * Amount of time to animate the opening of an accordion pane. * @option * @type {number} * @default 250 */ slideSpeed: 250, /** * Allow the accordion to have multiple open panes. * @option * @type {boolean} * @default false */ multiExpand: false, /** * Allow the accordion to close all panes. * @option * @type {boolean} * @default false */ allowAllClosed: false, /** * Allows the window to scroll to content of pane specified by hash anchor * @option * @type {boolean} * @default false */ deepLink: false, /** * Adjust the deep link scroll to make sure the top of the accordion panel is visible * @option * @type {boolean} * @default false */ deepLinkSmudge: false, /** * Animation time (ms) for the deep link adjustment * @option * @type {number} * @default 300 */ deepLinkSmudgeDelay: 300, /** * Update the browser history with the open accordion * @option * @type {boolean} * @default false */ updateHistory: false }; /***/ }), /* 11 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AccordionMenu; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_nest__ = __webpack_require__(9); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_util_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__foundation_plugin__ = __webpack_require__(2); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * AccordionMenu module. * @module foundation.accordionMenu * @requires foundation.util.keyboard * @requires foundation.util.nest */ var AccordionMenu = function (_Plugin) { _inherits(AccordionMenu, _Plugin); function AccordionMenu() { _classCallCheck(this, AccordionMenu); return _possibleConstructorReturn(this, (AccordionMenu.__proto__ || Object.getPrototypeOf(AccordionMenu)).apply(this, arguments)); } _createClass(AccordionMenu, [{ key: '_setup', /** * Creates a new instance of an accordion menu. * @class * @fires AccordionMenu#init * @param {jQuery} element - jQuery object to make into an accordion menu. * @param {Object} options - Overrides to the default plugin settings. */ value: function _setup(element, options) { this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, AccordionMenu.defaults, this.$element.data(), options); this.className = 'AccordionMenu'; // ie9 back compat __WEBPACK_IMPORTED_MODULE_2__foundation_util_nest__["a" /* Nest */].Feather(this.$element, 'accordion'); this._init(); __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].register('AccordionMenu', { 'ENTER': 'toggle', 'SPACE': 'toggle', 'ARROW_RIGHT': 'open', 'ARROW_UP': 'up', 'ARROW_DOWN': 'down', 'ARROW_LEFT': 'close', 'ESCAPE': 'closeAll' }); } /** * Initializes the accordion menu by hiding all nested menus. * @private */ }, { key: '_init', value: function _init() { var _this = this; this.$element.find('[data-submenu]').not('.is-active').slideUp(0); //.find('a').css('padding-left', '1rem'); this.$element.attr({ 'role': 'tree', 'aria-multiselectable': this.options.multiOpen }); this.$menuLinks = this.$element.find('.is-accordion-submenu-parent'); this.$menuLinks.each(function () { var linkId = this.id || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__["a" /* GetYoDigits */])(6, 'acc-menu-link'), $elem = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), $sub = $elem.children('[data-submenu]'), subId = $sub[0].id || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__["a" /* GetYoDigits */])(6, 'acc-menu'), isActive = $sub.hasClass('is-active'); if (_this.options.submenuToggle) { $elem.addClass('has-submenu-toggle'); $elem.children('a').after('<button id="' + linkId + '" class="submenu-toggle" aria-controls="' + subId + '" aria-expanded="' + isActive + '" title="' + _this.options.submenuToggleText + '"><span class="submenu-toggle-text">' + _this.options.submenuToggleText + '</span></button>'); } else { $elem.attr({ 'aria-controls': subId, 'aria-expanded': isActive, 'id': linkId }); } $sub.attr({ 'aria-labelledby': linkId, 'aria-hidden': !isActive, 'role': 'group', 'id': subId }); }); this.$element.find('li').attr({ 'role': 'treeitem' }); var initPanes = this.$element.find('.is-active'); if (initPanes.length) { var _this = this; initPanes.each(function () { _this.down(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this)); }); } this._events(); } /** * Adds event handlers for items within the menu. * @private */ }, { key: '_events', value: function _events() { var _this = this; this.$element.find('li').each(function () { var $submenu = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).children('[data-submenu]'); if ($submenu.length) { if (_this.options.submenuToggle) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).children('.submenu-toggle').off('click.zf.accordionMenu').on('click.zf.accordionMenu', function (e) { _this.toggle($submenu); }); } else { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).children('a').off('click.zf.accordionMenu').on('click.zf.accordionMenu', function (e) { e.preventDefault(); _this.toggle($submenu); }); } } }).on('keydown.zf.accordionmenu', function (e) { var $element = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), $elements = $element.parent('ul').children('li'), $prevElement, $nextElement, $target = $element.children('[data-submenu]'); $elements.each(function (i) { if (__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).is($element)) { $prevElement = $elements.eq(Math.max(0, i - 1)).find('a').first(); $nextElement = $elements.eq(Math.min(i + 1, $elements.length - 1)).find('a').first(); if (__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).children('[data-submenu]:visible').length) { // has open sub menu $nextElement = $element.find('li:first-child').find('a').first(); } if (__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).is(':first-child')) { // is first element of sub menu $prevElement = $element.parents('li').first().find('a').first(); } else if ($prevElement.parents('li').first().children('[data-submenu]:visible').length) { // if previous element has open sub menu $prevElement = $prevElement.parents('li').find('li:last-child').find('a').first(); } if (__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).is(':last-child')) { // is last element of sub menu $nextElement = $element.parents('li').first().next('li').find('a').first(); } return; } }); __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].handleKey(e, 'AccordionMenu', { open: function () { if ($target.is(':hidden')) { _this.down($target); $target.find('li').first().find('a').first().focus(); } }, close: function () { if ($target.length && !$target.is(':hidden')) { // close active sub of this item _this.up($target); } else if ($element.parent('[data-submenu]').length) { // close currently open sub _this.up($element.parent('[data-submenu]')); $element.parents('li').first().find('a').first().focus(); } }, up: function () { $prevElement.focus(); return true; }, down: function () { $nextElement.focus(); return true; }, toggle: function () { if (_this.options.submenuToggle) { return false; } if ($element.children('[data-submenu]').length) { _this.toggle($element.children('[data-submenu]')); return true; } }, closeAll: function () { _this.hideAll(); }, handled: function (preventDefault) { if (preventDefault) { e.preventDefault(); } e.stopImmediatePropagation(); } }); }); //.attr('tabindex', 0); } /** * Closes all panes of the menu. * @function */ }, { key: 'hideAll', value: function hideAll() { this.up(this.$element.find('[data-submenu]')); } /** * Opens all panes of the menu. * @function */ }, { key: 'showAll', value: function showAll() { this.down(this.$element.find('[data-submenu]')); } /** * Toggles the open/close state of a submenu. * @function * @param {jQuery} $target - the submenu to toggle */ }, { key: 'toggle', value: function toggle($target) { if (!$target.is(':animated')) { if (!$target.is(':hidden')) { this.up($target); } else { this.down($target); } } } /** * Opens the sub-menu defined by `$target`. * @param {jQuery} $target - Sub-menu to open. * @fires AccordionMenu#down */ }, { key: 'down', value: function down($target) { var _this = this; if (!this.options.multiOpen) { this.up(this.$element.find('.is-active').not($target.parentsUntil(this.$element).add($target))); } $target.addClass('is-active').attr({ 'aria-hidden': false }); if (this.options.submenuToggle) { $target.prev('.submenu-toggle').attr({ 'aria-expanded': true }); } else { $target.parent('.is-accordion-submenu-parent').attr({ 'aria-expanded': true }); } $target.slideDown(_this.options.slideSpeed, function () { /** * Fires when the menu is done opening. * @event AccordionMenu#down */ _this.$element.trigger('down.zf.accordionMenu', [$target]); }); } /** * Closes the sub-menu defined by `$target`. All sub-menus inside the target will be closed as well. * @param {jQuery} $target - Sub-menu to close. * @fires AccordionMenu#up */ }, { key: 'up', value: function up($target) { var _this = this; $target.slideUp(_this.options.slideSpeed, function () { /** * Fires when the menu is done collapsing up. * @event AccordionMenu#up */ _this.$element.trigger('up.zf.accordionMenu', [$target]); }); var $menus = $target.find('[data-submenu]').slideUp(0).addBack().attr('aria-hidden', true); if (this.options.submenuToggle) { $menus.prev('.submenu-toggle').attr('aria-expanded', false); } else { $menus.parent('.is-accordion-submenu-parent').attr('aria-expanded', false); } } /** * Destroys an instance of accordion menu. * @fires AccordionMenu#destroyed */ }, { key: '_destroy', value: function _destroy() { this.$element.find('[data-submenu]').slideDown(0).css('display', ''); this.$element.find('a').off('click.zf.accordionMenu'); if (this.options.submenuToggle) { this.$element.find('.has-submenu-toggle').removeClass('has-submenu-toggle'); this.$element.find('.submenu-toggle').remove(); } __WEBPACK_IMPORTED_MODULE_2__foundation_util_nest__["a" /* Nest */].Burn(this.$element, 'accordion'); } }]); return AccordionMenu; }(__WEBPACK_IMPORTED_MODULE_4__foundation_plugin__["a" /* Plugin */]); AccordionMenu.defaults = { /** * Amount of time to animate the opening of a submenu in ms. * @option * @type {number} * @default 250 */ slideSpeed: 250, /** * Adds a separate submenu toggle button. This allows the parent item to have a link. * @option * @example true */ submenuToggle: false, /** * The text used for the submenu toggle if enabled. This is used for screen readers only. * @option * @example true */ submenuToggleText: 'Toggle menu', /** * Allow the menu to have multiple open panes. * @option * @type {boolean} * @default true */ multiOpen: true }; /***/ }), /* 12 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Drilldown; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_nest__ = __webpack_require__(9); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_util_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__foundation_util_box__ = __webpack_require__(7); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__foundation_plugin__ = __webpack_require__(2); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Drilldown module. * @module foundation.drilldown * @requires foundation.util.keyboard * @requires foundation.util.nest * @requires foundation.util.box */ var Drilldown = function (_Plugin) { _inherits(Drilldown, _Plugin); function Drilldown() { _classCallCheck(this, Drilldown); return _possibleConstructorReturn(this, (Drilldown.__proto__ || Object.getPrototypeOf(Drilldown)).apply(this, arguments)); } _createClass(Drilldown, [{ key: '_setup', /** * Creates a new instance of a drilldown menu. * @class * @param {jQuery} element - jQuery object to make into an accordion menu. * @param {Object} options - Overrides to the default plugin settings. */ value: function _setup(element, options) { this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Drilldown.defaults, this.$element.data(), options); this.className = 'Drilldown'; // ie9 back compat __WEBPACK_IMPORTED_MODULE_2__foundation_util_nest__["a" /* Nest */].Feather(this.$element, 'drilldown'); this._init(); __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].register('Drilldown', { 'ENTER': 'open', 'SPACE': 'open', 'ARROW_RIGHT': 'next', 'ARROW_UP': 'up', 'ARROW_DOWN': 'down', 'ARROW_LEFT': 'previous', 'ESCAPE': 'close', 'TAB': 'down', 'SHIFT_TAB': 'up' }); } /** * Initializes the drilldown by creating jQuery collections of elements * @private */ }, { key: '_init', value: function _init() { if (this.options.autoApplyClass) { this.$element.addClass('drilldown'); } this.$element.attr({ 'role': 'tree', 'aria-multiselectable': false }); this.$submenuAnchors = this.$element.find('li.is-drilldown-submenu-parent').children('a'); this.$submenus = this.$submenuAnchors.parent('li').children('[data-submenu]').attr('role', 'group'); this.$menuItems = this.$element.find('li').not('.js-drilldown-back').attr('role', 'treeitem').find('a'); this.$element.attr('data-mutate', this.$element.attr('data-drilldown') || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__["a" /* GetYoDigits */])(6, 'drilldown')); this._prepareMenu(); this._registerEvents(); this._keyboardEvents(); } /** * prepares drilldown menu by setting attributes to links and elements * sets a min height to prevent content jumping * wraps the element if not already wrapped * @private * @function */ }, { key: '_prepareMenu', value: function _prepareMenu() { var _this = this; // if(!this.options.holdOpen){ // this._menuLinkEvents(); // } this.$submenuAnchors.each(function () { var $link = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this); var $sub = $link.parent(); if (_this.options.parentLink) { $link.clone().prependTo($sub.children('[data-submenu]')).wrap('<li class="is-submenu-parent-item is-submenu-item is-drilldown-submenu-item" role="menu-item"></li>'); } $link.data('savedHref', $link.attr('href')).removeAttr('href').attr('tabindex', 0); $link.children('[data-submenu]').attr({ 'aria-hidden': true, 'tabindex': 0, 'role': 'group' }); _this._events($link); }); this.$submenus.each(function () { var $menu = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), $back = $menu.find('.js-drilldown-back'); if (!$back.length) { switch (_this.options.backButtonPosition) { case "bottom": $menu.append(_this.options.backButton); break; case "top": $menu.prepend(_this.options.backButton); break; default: console.error("Unsupported backButtonPosition value '" + _this.options.backButtonPosition + "'"); } } _this._back($menu); }); this.$submenus.addClass('invisible'); if (!this.options.autoHeight) { this.$submenus.addClass('drilldown-submenu-cover-previous'); } // create a wrapper on element if it doesn't exist. if (!this.$element.parent().hasClass('is-drilldown')) { this.$wrapper = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this.options.wrapper).addClass('is-drilldown'); if (this.options.animateHeight) this.$wrapper.addClass('animate-height'); this.$element.wrap(this.$wrapper); } // set wrapper this.$wrapper = this.$element.parent(); this.$wrapper.css(this._getMaxDims()); } }, { key: '_resize', value: function _resize() { this.$wrapper.css({ 'max-width': 'none', 'min-height': 'none' }); // _getMaxDims has side effects (boo) but calling it should update all other necessary heights & widths this.$wrapper.css(this._getMaxDims()); } /** * Adds event handlers to elements in the menu. * @function * @private * @param {jQuery} $elem - the current menu item to add handlers to. */ }, { key: '_events', value: function _events($elem) { var _this = this; $elem.off('click.zf.drilldown').on('click.zf.drilldown', function (e) { if (__WEBPACK_IMPORTED_MODULE_0_jquery___default()(e.target).parentsUntil('ul', 'li').hasClass('is-drilldown-submenu-parent')) { e.stopImmediatePropagation(); e.preventDefault(); } // if(e.target !== e.currentTarget.firstElementChild){ // return false; // } _this._show($elem.parent('li')); if (_this.options.closeOnClick) { var $body = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('body'); $body.off('.zf.drilldown').on('click.zf.drilldown', function (e) { if (e.target === _this.$element[0] || __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.contains(_this.$element[0], e.target)) { return; } e.preventDefault(); _this._hideAll(); $body.off('.zf.drilldown'); }); } }); } /** * Adds event handlers to the menu element. * @function * @private */ }, { key: '_registerEvents', value: function _registerEvents() { if (this.options.scrollTop) { this._bindHandler = this._scrollTop.bind(this); this.$element.on('open.zf.drilldown hide.zf.drilldown closed.zf.drilldown', this._bindHandler); } this.$element.on('mutateme.zf.trigger', this._resize.bind(this)); } /** * Scroll to Top of Element or data-scroll-top-element * @function * @fires Drilldown#scrollme */ }, { key: '_scrollTop', value: function _scrollTop() { var _this = this; var $scrollTopElement = _this.options.scrollTopElement != '' ? __WEBPACK_IMPORTED_MODULE_0_jquery___default()(_this.options.scrollTopElement) : _this.$element, scrollPos = parseInt($scrollTopElement.offset().top + _this.options.scrollTopOffset, 10); __WEBPACK_IMPORTED_MODULE_0_jquery___default()('html, body').stop(true).animate({ scrollTop: scrollPos }, _this.options.animationDuration, _this.options.animationEasing, function () { /** * Fires after the menu has scrolled * @event Drilldown#scrollme */ if (this === __WEBPACK_IMPORTED_MODULE_0_jquery___default()('html')[0]) _this.$element.trigger('scrollme.zf.drilldown'); }); } /** * Adds keydown event listener to `li`'s in the menu. * @private */ }, { key: '_keyboardEvents', value: function _keyboardEvents() { var _this = this; this.$menuItems.add(this.$element.find('.js-drilldown-back > a, .is-submenu-parent-item > a')).on('keydown.zf.drilldown', function (e) { var $element = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), $elements = $element.parent('li').parent('ul').children('li').children('a'), $prevElement, $nextElement; $elements.each(function (i) { if (__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).is($element)) { $prevElement = $elements.eq(Math.max(0, i - 1)); $nextElement = $elements.eq(Math.min(i + 1, $elements.length - 1)); return; } }); __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].handleKey(e, 'Drilldown', { next: function () { if ($element.is(_this.$submenuAnchors)) { _this._show($element.parent('li')); $element.parent('li').one(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__["c" /* transitionend */])($element), function () { $element.parent('li').find('ul li a').filter(_this.$menuItems).first().focus(); }); return true; } }, previous: function () { _this._hide($element.parent('li').parent('ul')); $element.parent('li').parent('ul').one(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__["c" /* transitionend */])($element), function () { setTimeout(function () { $element.parent('li').parent('ul').parent('li').children('a').first().focus(); }, 1); }); return true; }, up: function () { $prevElement.focus(); // Don't tap focus on first element in root ul return !$element.is(_this.$element.find('> li:first-child > a')); }, down: function () { $nextElement.focus(); // Don't tap focus on last element in root ul return !$element.is(_this.$element.find('> li:last-child > a')); }, close: function () { // Don't close on element in root ul if (!$element.is(_this.$element.find('> li > a'))) { _this._hide($element.parent().parent()); $element.parent().parent().siblings('a').focus(); } }, open: function () { if (!$element.is(_this.$menuItems)) { // not menu item means back button _this._hide($element.parent('li').parent('ul')); $element.parent('li').parent('ul').one(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__["c" /* transitionend */])($element), function () { setTimeout(function () { $element.parent('li').parent('ul').parent('li').children('a').first().focus(); }, 1); }); return true; } else if ($element.is(_this.$submenuAnchors)) { _this._show($element.parent('li')); $element.parent('li').one(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__["c" /* transitionend */])($element), function () { $element.parent('li').find('ul li a').filter(_this.$menuItems).first().focus(); }); return true; } }, handled: function (preventDefault) { if (preventDefault) { e.preventDefault(); } e.stopImmediatePropagation(); } }); }); // end keyboardAccess } /** * Closes all open elements, and returns to root menu. * @function * @fires Drilldown#closed */ }, { key: '_hideAll', value: function _hideAll() { var $elem = this.$element.find('.is-drilldown-submenu.is-active').addClass('is-closing'); if (this.options.autoHeight) this.$wrapper.css({ height: $elem.parent().closest('ul').data('calcHeight') }); $elem.one(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__["c" /* transitionend */])($elem), function (e) { $elem.removeClass('is-active is-closing'); }); /** * Fires when the menu is fully closed. * @event Drilldown#closed */ this.$element.trigger('closed.zf.drilldown'); } /** * Adds event listener for each `back` button, and closes open menus. * @function * @fires Drilldown#back * @param {jQuery} $elem - the current sub-menu to add `back` event. */ }, { key: '_back', value: function _back($elem) { var _this = this; $elem.off('click.zf.drilldown'); $elem.children('.js-drilldown-back').on('click.zf.drilldown', function (e) { e.stopImmediatePropagation(); // console.log('mouseup on back'); _this._hide($elem); // If there is a parent submenu, call show var parentSubMenu = $elem.parent('li').parent('ul').parent('li'); if (parentSubMenu.length) { _this._show(parentSubMenu); } }); } /** * Adds event listener to menu items w/o submenus to close open menus on click. * @function * @private */ }, { key: '_menuLinkEvents', value: function _menuLinkEvents() { var _this = this; this.$menuItems.not('.is-drilldown-submenu-parent').off('click.zf.drilldown').on('click.zf.drilldown', function (e) { // e.stopImmediatePropagation(); setTimeout(function () { _this._hideAll(); }, 0); }); } /** * Opens a submenu. * @function * @fires Drilldown#open * @param {jQuery} $elem - the current element with a submenu to open, i.e. the `li` tag. */ }, { key: '_show', value: function _show($elem) { if (this.options.autoHeight) this.$wrapper.css({ height: $elem.children('[data-submenu]').data('calcHeight') }); $elem.attr('aria-expanded', true); $elem.children('[data-submenu]').addClass('is-active').removeClass('invisible').attr('aria-hidden', false); /** * Fires when the submenu has opened. * @event Drilldown#open */ this.$element.trigger('open.zf.drilldown', [$elem]); } }, { key: '_hide', /** * Hides a submenu * @function * @fires Drilldown#hide * @param {jQuery} $elem - the current sub-menu to hide, i.e. the `ul` tag. */ value: function _hide($elem) { if (this.options.autoHeight) this.$wrapper.css({ height: $elem.parent().closest('ul').data('calcHeight') }); var _this = this; $elem.parent('li').attr('aria-expanded', false); $elem.attr('aria-hidden', true).addClass('is-closing'); $elem.addClass('is-closing').one(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__["c" /* transitionend */])($elem), function () { $elem.removeClass('is-active is-closing'); $elem.blur().addClass('invisible'); }); /** * Fires when the submenu has closed. * @event Drilldown#hide */ $elem.trigger('hide.zf.drilldown', [$elem]); } /** * Iterates through the nested menus to calculate the min-height, and max-width for the menu. * Prevents content jumping. * @function * @private */ }, { key: '_getMaxDims', value: function _getMaxDims() { var maxHeight = 0, result = {}, _this = this; this.$submenus.add(this.$element).each(function () { var numOfElems = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).children('li').length; var height = __WEBPACK_IMPORTED_MODULE_4__foundation_util_box__["a" /* Box */].GetDimensions(this).height; maxHeight = height > maxHeight ? height : maxHeight; if (_this.options.autoHeight) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('calcHeight', height); if (!__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).hasClass('is-drilldown-submenu')) result['height'] = height; } }); if (!this.options.autoHeight) result['min-height'] = maxHeight + 'px'; result['max-width'] = this.$element[0].getBoundingClientRect().width + 'px'; return result; } /** * Destroys the Drilldown Menu * @function */ }, { key: '_destroy', value: function _destroy() { if (this.options.scrollTop) this.$element.off('.zf.drilldown', this._bindHandler); this._hideAll(); this.$element.off('mutateme.zf.trigger'); __WEBPACK_IMPORTED_MODULE_2__foundation_util_nest__["a" /* Nest */].Burn(this.$element, 'drilldown'); this.$element.unwrap().find('.js-drilldown-back, .is-submenu-parent-item').remove().end().find('.is-active, .is-closing, .is-drilldown-submenu').removeClass('is-active is-closing is-drilldown-submenu').end().find('[data-submenu]').removeAttr('aria-hidden tabindex role'); this.$submenuAnchors.each(function () { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).off('.zf.drilldown'); }); this.$submenus.removeClass('drilldown-submenu-cover-previous invisible'); this.$element.find('a').each(function () { var $link = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this); $link.removeAttr('tabindex'); if ($link.data('savedHref')) { $link.attr('href', $link.data('savedHref')).removeData('savedHref'); } else { return; } }); } }]); return Drilldown; }(__WEBPACK_IMPORTED_MODULE_5__foundation_plugin__["a" /* Plugin */]); Drilldown.defaults = { /** * Drilldowns depend on styles in order to function properly; in the default build of Foundation these are * on the `drilldown` class. This option auto-applies this class to the drilldown upon initialization. * @option * @type {boolian} * @default true */ autoApplyClass: true, /** * Markup used for JS generated back button. Prepended or appended (see backButtonPosition) to submenu lists and deleted on `destroy` method, 'js-drilldown-back' class required. Remove the backslash (`\`) if copy and pasting. * @option * @type {string} * @default '<li class="js-drilldown-back"><a tabindex="0">Back</a></li>' */ backButton: '<li class="js-drilldown-back"><a tabindex="0">Back</a></li>', /** * Position the back button either at the top or bottom of drilldown submenus. Can be `'left'` or `'bottom'`. * @option * @type {string} * @default top */ backButtonPosition: 'top', /** * Markup used to wrap drilldown menu. Use a class name for independent styling; the JS applied class: `is-drilldown` is required. Remove the backslash (`\`) if copy and pasting. * @option * @type {string} * @default '<div></div>' */ wrapper: '<div></div>', /** * Adds the parent link to the submenu. * @option * @type {boolean} * @default false */ parentLink: false, /** * Allow the menu to return to root list on body click. * @option * @type {boolean} * @default false */ closeOnClick: false, /** * Allow the menu to auto adjust height. * @option * @type {boolean} * @default false */ autoHeight: false, /** * Animate the auto adjust height. * @option * @type {boolean} * @default false */ animateHeight: false, /** * Scroll to the top of the menu after opening a submenu or navigating back using the menu back button * @option * @type {boolean} * @default false */ scrollTop: false, /** * String jquery selector (for example 'body') of element to take offset().top from, if empty string the drilldown menu offset().top is taken * @option * @type {string} * @default '' */ scrollTopElement: '', /** * ScrollTop offset * @option * @type {number} * @default 0 */ scrollTopOffset: 0, /** * Scroll animation duration * @option * @type {number} * @default 500 */ animationDuration: 500, /** * Scroll animation easing. Can be `'swing'` or `'linear'`. * @option * @type {string} * @see {@link https://api.jquery.com/animate|JQuery animate} * @default 'swing' */ animationEasing: 'swing' // holdOpen: false }; /***/ }), /* 13 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DropdownMenu; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_nest__ = __webpack_require__(9); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_util_box__ = __webpack_require__(7); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__foundation_util_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__foundation_plugin__ = __webpack_require__(2); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * DropdownMenu module. * @module foundation.dropdown-menu * @requires foundation.util.keyboard * @requires foundation.util.box * @requires foundation.util.nest */ var DropdownMenu = function (_Plugin) { _inherits(DropdownMenu, _Plugin); function DropdownMenu() { _classCallCheck(this, DropdownMenu); return _possibleConstructorReturn(this, (DropdownMenu.__proto__ || Object.getPrototypeOf(DropdownMenu)).apply(this, arguments)); } _createClass(DropdownMenu, [{ key: '_setup', /** * Creates a new instance of DropdownMenu. * @class * @fires DropdownMenu#init * @param {jQuery} element - jQuery object to make into a dropdown menu. * @param {Object} options - Overrides to the default plugin settings. */ value: function _setup(element, options) { this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, DropdownMenu.defaults, this.$element.data(), options); this.className = 'DropdownMenu'; // ie9 back compat __WEBPACK_IMPORTED_MODULE_2__foundation_util_nest__["a" /* Nest */].Feather(this.$element, 'dropdown'); this._init(); __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].register('DropdownMenu', { 'ENTER': 'open', 'SPACE': 'open', 'ARROW_RIGHT': 'next', 'ARROW_UP': 'up', 'ARROW_DOWN': 'down', 'ARROW_LEFT': 'previous', 'ESCAPE': 'close' }); } /** * Initializes the plugin, and calls _prepareMenu * @private * @function */ }, { key: '_init', value: function _init() { var subs = this.$element.find('li.is-dropdown-submenu-parent'); this.$element.children('.is-dropdown-submenu-parent').children('.is-dropdown-submenu').addClass('first-sub'); this.$menuItems = this.$element.find('[role="menuitem"]'); this.$tabs = this.$element.children('[role="menuitem"]'); this.$tabs.find('ul.is-dropdown-submenu').addClass(this.options.verticalClass); if (this.options.alignment === 'auto') { if (this.$element.hasClass(this.options.rightClass) || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__foundation_util_core__["b" /* rtl */])() || this.$element.parents('.top-bar-right').is('*')) { this.options.alignment = 'right'; subs.addClass('opens-left'); } else { this.options.alignment = 'left'; subs.addClass('opens-right'); } } else { if (this.options.alignment === 'right') { subs.addClass('opens-left'); } else { subs.addClass('opens-right'); } } this.changed = false; this._events(); } }, { key: '_isVertical', value: function _isVertical() { return this.$tabs.css('display') === 'block' || this.$element.css('flex-direction') === 'column'; } }, { key: '_isRtl', value: function _isRtl() { return this.$element.hasClass('align-right') || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__foundation_util_core__["b" /* rtl */])() && !this.$element.hasClass('align-left'); } /** * Adds event listeners to elements within the menu * @private * @function */ }, { key: '_events', value: function _events() { var _this = this, hasTouch = 'ontouchstart' in window || typeof window.ontouchstart !== 'undefined', parClass = 'is-dropdown-submenu-parent'; // used for onClick and in the keyboard handlers var handleClickFn = function (e) { var $elem = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(e.target).parentsUntil('ul', '.' + parClass), hasSub = $elem.hasClass(parClass), hasClicked = $elem.attr('data-is-click') === 'true', $sub = $elem.children('.is-dropdown-submenu'); if (hasSub) { if (hasClicked) { if (!_this.options.closeOnClick || !_this.options.clickOpen && !hasTouch || _this.options.forceFollow && hasTouch) { return; } else { e.stopImmediatePropagation(); e.preventDefault(); _this._hide($elem); } } else { e.preventDefault(); e.stopImmediatePropagation(); _this._show($sub); $elem.add($elem.parentsUntil(_this.$element, '.' + parClass)).attr('data-is-click', true); } } }; if (this.options.clickOpen || hasTouch) { this.$menuItems.on('click.zf.dropdownmenu touchstart.zf.dropdownmenu', handleClickFn); } // Handle Leaf element Clicks if (_this.options.closeOnClickInside) { this.$menuItems.on('click.zf.dropdownmenu', function (e) { var $elem = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), hasSub = $elem.hasClass(parClass); if (!hasSub) { _this._hide(); } }); } if (!this.options.disableHover) { this.$menuItems.on('mouseenter.zf.dropdownmenu', function (e) { var $elem = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), hasSub = $elem.hasClass(parClass); if (hasSub) { clearTimeout($elem.data('_delay')); $elem.data('_delay', setTimeout(function () { _this._show($elem.children('.is-dropdown-submenu')); }, _this.options.hoverDelay)); } }).on('mouseleave.zf.dropdownmenu', function (e) { var $elem = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), hasSub = $elem.hasClass(parClass); if (hasSub && _this.options.autoclose) { if ($elem.attr('data-is-click') === 'true' && _this.options.clickOpen) { return false; } clearTimeout($elem.data('_delay')); $elem.data('_delay', setTimeout(function () { _this._hide($elem); }, _this.options.closingTime)); } }); } this.$menuItems.on('keydown.zf.dropdownmenu', function (e) { var $element = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(e.target).parentsUntil('ul', '[role="menuitem"]'), isTab = _this.$tabs.index($element) > -1, $elements = isTab ? _this.$tabs : $element.siblings('li').add($element), $prevElement, $nextElement; $elements.each(function (i) { if (__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).is($element)) { $prevElement = $elements.eq(i - 1); $nextElement = $elements.eq(i + 1); return; } }); var nextSibling = function () { if (!$element.is(':last-child')) { $nextElement.children('a:first').focus(); e.preventDefault(); } }, prevSibling = function () { $prevElement.children('a:first').focus(); e.preventDefault(); }, openSub = function () { var $sub = $element.children('ul.is-dropdown-submenu'); if ($sub.length) { _this._show($sub); $element.find('li > a:first').focus(); e.preventDefault(); } else { return; } }, closeSub = function () { //if ($element.is(':first-child')) { var close = $element.parent('ul').parent('li'); close.children('a:first').focus(); _this._hide(close); e.preventDefault(); //} }; var functions = { open: openSub, close: function () { _this._hide(_this.$element); _this.$menuItems.eq(0).children('a').focus(); // focus to first element e.preventDefault(); }, handled: function () { e.stopImmediatePropagation(); } }; if (isTab) { if (_this._isVertical()) { // vertical menu if (_this._isRtl()) { // right aligned __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend(functions, { down: nextSibling, up: prevSibling, next: closeSub, previous: openSub }); } else { // left aligned __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend(functions, { down: nextSibling, up: prevSibling, next: openSub, previous: closeSub }); } } else { // horizontal menu if (_this._isRtl()) { // right aligned __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend(functions, { next: prevSibling, previous: nextSibling, down: openSub, up: closeSub }); } else { // left aligned __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend(functions, { next: nextSibling, previous: prevSibling, down: openSub, up: closeSub }); } } } else { // not tabs -> one sub if (_this._isRtl()) { // right aligned __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend(functions, { next: closeSub, previous: openSub, down: nextSibling, up: prevSibling }); } else { // left aligned __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend(functions, { next: openSub, previous: closeSub, down: nextSibling, up: prevSibling }); } } __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].handleKey(e, 'DropdownMenu', functions); }); } /** * Adds an event handler to the body to close any dropdowns on a click. * @function * @private */ }, { key: '_addBodyHandler', value: function _addBodyHandler() { var $body = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(document.body), _this = this; $body.off('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu').on('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu', function (e) { var $link = _this.$element.find(e.target); if ($link.length) { return; } _this._hide(); $body.off('mouseup.zf.dropdownmenu touchend.zf.dropdownmenu'); }); } /** * Opens a dropdown pane, and checks for collisions first. * @param {jQuery} $sub - ul element that is a submenu to show * @function * @private * @fires DropdownMenu#show */ }, { key: '_show', value: function _show($sub) { var idx = this.$tabs.index(this.$tabs.filter(function (i, el) { return __WEBPACK_IMPORTED_MODULE_0_jquery___default()(el).find($sub).length > 0; })); var $sibs = $sub.parent('li.is-dropdown-submenu-parent').siblings('li.is-dropdown-submenu-parent'); this._hide($sibs, idx); $sub.css('visibility', 'hidden').addClass('js-dropdown-active').parent('li.is-dropdown-submenu-parent').addClass('is-active'); var clear = __WEBPACK_IMPORTED_MODULE_3__foundation_util_box__["a" /* Box */].ImNotTouchingYou($sub, null, true); if (!clear) { var oldClass = this.options.alignment === 'left' ? '-right' : '-left', $parentLi = $sub.parent('.is-dropdown-submenu-parent'); $parentLi.removeClass('opens' + oldClass).addClass('opens-' + this.options.alignment); clear = __WEBPACK_IMPORTED_MODULE_3__foundation_util_box__["a" /* Box */].ImNotTouchingYou($sub, null, true); if (!clear) { $parentLi.removeClass('opens-' + this.options.alignment).addClass('opens-inner'); } this.changed = true; } $sub.css('visibility', ''); if (this.options.closeOnClick) { this._addBodyHandler(); } /** * Fires when the new dropdown pane is visible. * @event DropdownMenu#show */ this.$element.trigger('show.zf.dropdownmenu', [$sub]); } /** * Hides a single, currently open dropdown pane, if passed a parameter, otherwise, hides everything. * @function * @param {jQuery} $elem - element with a submenu to hide * @param {Number} idx - index of the $tabs collection to hide * @private */ }, { key: '_hide', value: function _hide($elem, idx) { var $toClose; if ($elem && $elem.length) { $toClose = $elem; } else if (idx !== undefined) { $toClose = this.$tabs.not(function (i, el) { return i === idx; }); } else { $toClose = this.$element; } var somethingToClose = $toClose.hasClass('is-active') || $toClose.find('.is-active').length > 0; if (somethingToClose) { $toClose.find('li.is-active').add($toClose).attr({ 'data-is-click': false }).removeClass('is-active'); $toClose.find('ul.js-dropdown-active').removeClass('js-dropdown-active'); if (this.changed || $toClose.find('opens-inner').length) { var oldClass = this.options.alignment === 'left' ? 'right' : 'left'; $toClose.find('li.is-dropdown-submenu-parent').add($toClose).removeClass('opens-inner opens-' + this.options.alignment).addClass('opens-' + oldClass); this.changed = false; } /** * Fires when the open menus are closed. * @event DropdownMenu#hide */ this.$element.trigger('hide.zf.dropdownmenu', [$toClose]); } } /** * Destroys the plugin. * @function */ }, { key: '_destroy', value: function _destroy() { this.$menuItems.off('.zf.dropdownmenu').removeAttr('data-is-click').removeClass('is-right-arrow is-left-arrow is-down-arrow opens-right opens-left opens-inner'); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(document.body).off('.zf.dropdownmenu'); __WEBPACK_IMPORTED_MODULE_2__foundation_util_nest__["a" /* Nest */].Burn(this.$element, 'dropdown'); } }]); return DropdownMenu; }(__WEBPACK_IMPORTED_MODULE_5__foundation_plugin__["a" /* Plugin */]); /** * Default settings for plugin */ DropdownMenu.defaults = { /** * Disallows hover events from opening submenus * @option * @type {boolean} * @default false */ disableHover: false, /** * Allow a submenu to automatically close on a mouseleave event, if not clicked open. * @option * @type {boolean} * @default true */ autoclose: true, /** * Amount of time to delay opening a submenu on hover event. * @option * @type {number} * @default 50 */ hoverDelay: 50, /** * Allow a submenu to open/remain open on parent click event. Allows cursor to move away from menu. * @option * @type {boolean} * @default false */ clickOpen: false, /** * Amount of time to delay closing a submenu on a mouseleave event. * @option * @type {number} * @default 500 */ closingTime: 500, /** * Position of the menu relative to what direction the submenus should open. Handled by JS. Can be `'auto'`, `'left'` or `'right'`. * @option * @type {string} * @default 'auto' */ alignment: 'auto', /** * Allow clicks on the body to close any open submenus. * @option * @type {boolean} * @default true */ closeOnClick: true, /** * Allow clicks on leaf anchor links to close any open submenus. * @option * @type {boolean} * @default true */ closeOnClickInside: true, /** * Class applied to vertical oriented menus, Foundation default is `vertical`. Update this if using your own class. * @option * @type {string} * @default 'vertical' */ verticalClass: 'vertical', /** * Class applied to right-side oriented menus, Foundation default is `align-right`. Update this if using your own class. * @option * @type {string} * @default 'align-right' */ rightClass: 'align-right', /** * Boolean to force overide the clicking of links to perform default action, on second touch event for mobile. * @option * @type {boolean} * @default true */ forceFollow: true }; /***/ }), /* 14 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Tabs; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_imageLoader__ = __webpack_require__(8); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_plugin__ = __webpack_require__(2); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Tabs module. * @module foundation.tabs * @requires foundation.util.keyboard * @requires foundation.util.imageLoader if tabs contain images */ var Tabs = function (_Plugin) { _inherits(Tabs, _Plugin); function Tabs() { _classCallCheck(this, Tabs); return _possibleConstructorReturn(this, (Tabs.__proto__ || Object.getPrototypeOf(Tabs)).apply(this, arguments)); } _createClass(Tabs, [{ key: '_setup', /** * Creates a new instance of tabs. * @class * @fires Tabs#init * @param {jQuery} element - jQuery object to make into tabs. * @param {Object} options - Overrides to the default plugin settings. */ value: function _setup(element, options) { this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Tabs.defaults, this.$element.data(), options); this.className = 'Tabs'; // ie9 back compat this._init(); __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].register('Tabs', { 'ENTER': 'open', 'SPACE': 'open', 'ARROW_RIGHT': 'next', 'ARROW_UP': 'previous', 'ARROW_DOWN': 'next', 'ARROW_LEFT': 'previous' // 'TAB': 'next', // 'SHIFT_TAB': 'previous' }); } /** * Initializes the tabs by showing and focusing (if autoFocus=true) the preset active tab. * @private */ }, { key: '_init', value: function _init() { var _this3 = this; var _this = this; this.$element.attr({ 'role': 'tablist' }); this.$tabTitles = this.$element.find('.' + this.options.linkClass); this.$tabContent = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-tabs-content="' + this.$element[0].id + '"]'); this.$tabTitles.each(function () { var $elem = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), $link = $elem.find('a'), isActive = $elem.hasClass('' + _this.options.linkActiveClass), hash = $link.attr('data-tabs-target') || $link[0].hash.slice(1), linkId = $link[0].id ? $link[0].id : hash + '-label', $tabContent = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + hash); $elem.attr({ 'role': 'presentation' }); $link.attr({ 'role': 'tab', 'aria-controls': hash, 'aria-selected': isActive, 'id': linkId, 'tabindex': isActive ? '0' : '-1' }); $tabContent.attr({ 'role': 'tabpanel', 'aria-labelledby': linkId }); if (!isActive) { $tabContent.attr('aria-hidden', 'true'); } if (isActive && _this.options.autoFocus) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).load(function () { __WEBPACK_IMPORTED_MODULE_0_jquery___default()('html, body').animate({ scrollTop: $elem.offset().top }, _this.options.deepLinkSmudgeDelay, function () { $link.focus(); }); }); } }); if (this.options.matchHeight) { var $images = this.$tabContent.find('img'); if ($images.length) { __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__foundation_util_imageLoader__["a" /* onImagesLoaded */])($images, this._setHeight.bind(this)); } else { this._setHeight(); } } //current context-bound function to open tabs on page load or history popstate this._checkDeepLink = function () { var anchor = window.location.hash; //need a hash and a relevant anchor in this tabset if (anchor.length) { var $link = _this3.$element.find('[href$="' + anchor + '"]'); if ($link.length) { _this3.selectTab(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(anchor), true); //roll up a little to show the titles if (_this3.options.deepLinkSmudge) { var offset = _this3.$element.offset(); __WEBPACK_IMPORTED_MODULE_0_jquery___default()('html, body').animate({ scrollTop: offset.top }, _this3.options.deepLinkSmudgeDelay); } /** * Fires when the zplugin has deeplinked at pageload * @event Tabs#deeplink */ _this3.$element.trigger('deeplink.zf.tabs', [$link, __WEBPACK_IMPORTED_MODULE_0_jquery___default()(anchor)]); } } }; //use browser to open a tab, if it exists in this tabset if (this.options.deepLink) { this._checkDeepLink(); } this._events(); } /** * Adds event handlers for items within the tabs. * @private */ }, { key: '_events', value: function _events() { this._addKeyHandler(); this._addClickHandler(); this._setHeightMqHandler = null; if (this.options.matchHeight) { this._setHeightMqHandler = this._setHeight.bind(this); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).on('changed.zf.mediaquery', this._setHeightMqHandler); } if (this.options.deepLink) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).on('popstate', this._checkDeepLink); } } /** * Adds click handlers for items within the tabs. * @private */ }, { key: '_addClickHandler', value: function _addClickHandler() { var _this = this; this.$element.off('click.zf.tabs').on('click.zf.tabs', '.' + this.options.linkClass, function (e) { e.preventDefault(); e.stopPropagation(); _this._handleTabChange(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this)); }); } /** * Adds keyboard event handlers for items within the tabs. * @private */ }, { key: '_addKeyHandler', value: function _addKeyHandler() { var _this = this; this.$tabTitles.off('keydown.zf.tabs').on('keydown.zf.tabs', function (e) { if (e.which === 9) return; var $element = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), $elements = $element.parent('ul').children('li'), $prevElement, $nextElement; $elements.each(function (i) { if (__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).is($element)) { if (_this.options.wrapOnKeys) { $prevElement = i === 0 ? $elements.last() : $elements.eq(i - 1); $nextElement = i === $elements.length - 1 ? $elements.first() : $elements.eq(i + 1); } else { $prevElement = $elements.eq(Math.max(0, i - 1)); $nextElement = $elements.eq(Math.min(i + 1, $elements.length - 1)); } return; } }); // handle keyboard event with keyboard util __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].handleKey(e, 'Tabs', { open: function () { $element.find('[role="tab"]').focus(); _this._handleTabChange($element); }, previous: function () { $prevElement.find('[role="tab"]').focus(); _this._handleTabChange($prevElement); }, next: function () { $nextElement.find('[role="tab"]').focus(); _this._handleTabChange($nextElement); }, handled: function () { e.stopPropagation(); e.preventDefault(); } }); }); } /** * Opens the tab `$targetContent` defined by `$target`. Collapses active tab. * @param {jQuery} $target - Tab to open. * @param {boolean} historyHandled - browser has already handled a history update * @fires Tabs#change * @function */ }, { key: '_handleTabChange', value: function _handleTabChange($target, historyHandled) { /** * Check for active class on target. Collapse if exists. */ if ($target.hasClass('' + this.options.linkActiveClass)) { if (this.options.activeCollapse) { this._collapseTab($target); /** * Fires when the zplugin has successfully collapsed tabs. * @event Tabs#collapse */ this.$element.trigger('collapse.zf.tabs', [$target]); } return; } var $oldTab = this.$element.find('.' + this.options.linkClass + '.' + this.options.linkActiveClass), $tabLink = $target.find('[role="tab"]'), hash = $tabLink.attr('data-tabs-target') || $tabLink[0].hash.slice(1), $targetContent = this.$tabContent.find('#' + hash); //close old tab this._collapseTab($oldTab); //open new tab this._openTab($target); //either replace or update browser history if (this.options.deepLink && !historyHandled) { var anchor = $target.find('a').attr('href'); if (this.options.updateHistory) { history.pushState({}, '', anchor); } else { history.replaceState({}, '', anchor); } } /** * Fires when the plugin has successfully changed tabs. * @event Tabs#change */ this.$element.trigger('change.zf.tabs', [$target, $targetContent]); //fire to children a mutation event $targetContent.find("[data-mutate]").trigger("mutateme.zf.trigger"); } /** * Opens the tab `$targetContent` defined by `$target`. * @param {jQuery} $target - Tab to Open. * @function */ }, { key: '_openTab', value: function _openTab($target) { var $tabLink = $target.find('[role="tab"]'), hash = $tabLink.attr('data-tabs-target') || $tabLink[0].hash.slice(1), $targetContent = this.$tabContent.find('#' + hash); $target.addClass('' + this.options.linkActiveClass); $tabLink.attr({ 'aria-selected': 'true', 'tabindex': '0' }); $targetContent.addClass('' + this.options.panelActiveClass).removeAttr('aria-hidden'); } /** * Collapses `$targetContent` defined by `$target`. * @param {jQuery} $target - Tab to Open. * @function */ }, { key: '_collapseTab', value: function _collapseTab($target) { var $target_anchor = $target.removeClass('' + this.options.linkActiveClass).find('[role="tab"]').attr({ 'aria-selected': 'false', 'tabindex': -1 }); __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + $target_anchor.attr('aria-controls')).removeClass('' + this.options.panelActiveClass).attr({ 'aria-hidden': 'true' }); } /** * Public method for selecting a content pane to display. * @param {jQuery | String} elem - jQuery object or string of the id of the pane to display. * @param {boolean} historyHandled - browser has already handled a history update * @function */ }, { key: 'selectTab', value: function selectTab(elem, historyHandled) { var idStr; if (typeof elem === 'object') { idStr = elem[0].id; } else { idStr = elem; } if (idStr.indexOf('#') < 0) { idStr = '#' + idStr; } var $target = this.$tabTitles.find('[href$="' + idStr + '"]').parent('.' + this.options.linkClass); this._handleTabChange($target, historyHandled); } }, { key: '_setHeight', /** * Sets the height of each panel to the height of the tallest panel. * If enabled in options, gets called on media query change. * If loading content via external source, can be called directly or with _reflow. * If enabled with `data-match-height="true"`, tabs sets to equal height * @function * @private */ value: function _setHeight() { var max = 0, _this = this; // Lock down the `this` value for the root tabs object this.$tabContent.find('.' + this.options.panelClass).css('height', '').each(function () { var panel = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), isActive = panel.hasClass('' + _this.options.panelActiveClass); // get the options from the parent instead of trying to get them from the child if (!isActive) { panel.css({ 'visibility': 'hidden', 'display': 'block' }); } var temp = this.getBoundingClientRect().height; if (!isActive) { panel.css({ 'visibility': '', 'display': '' }); } max = temp > max ? temp : max; }).css('height', max + 'px'); } /** * Destroys an instance of an tabs. * @fires Tabs#destroyed */ }, { key: '_destroy', value: function _destroy() { this.$element.find('.' + this.options.linkClass).off('.zf.tabs').hide().end().find('.' + this.options.panelClass).hide(); if (this.options.matchHeight) { if (this._setHeightMqHandler != null) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off('changed.zf.mediaquery', this._setHeightMqHandler); } } if (this.options.deepLink) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off('popstate', this._checkDeepLink); } } }]); return Tabs; }(__WEBPACK_IMPORTED_MODULE_3__foundation_plugin__["a" /* Plugin */]); Tabs.defaults = { /** * Allows the window to scroll to content of pane specified by hash anchor * @option * @type {boolean} * @default false */ deepLink: false, /** * Adjust the deep link scroll to make sure the top of the tab panel is visible * @option * @type {boolean} * @default false */ deepLinkSmudge: false, /** * Animation time (ms) for the deep link adjustment * @option * @type {number} * @default 300 */ deepLinkSmudgeDelay: 300, /** * Update the browser history with the open tab * @option * @type {boolean} * @default false */ updateHistory: false, /** * Allows the window to scroll to content of active pane on load if set to true. * Not recommended if more than one tab panel per page. * @option * @type {boolean} * @default false */ autoFocus: false, /** * Allows keyboard input to 'wrap' around the tab links. * @option * @type {boolean} * @default true */ wrapOnKeys: true, /** * Allows the tab content panes to match heights if set to true. * @option * @type {boolean} * @default false */ matchHeight: false, /** * Allows active tabs to collapse when clicked. * @option * @type {boolean} * @default false */ activeCollapse: false, /** * Class applied to `li`'s in tab link list. * @option * @type {string} * @default 'tabs-title' */ linkClass: 'tabs-title', /** * Class applied to the active `li` in tab link list. * @option * @type {string} * @default 'is-active' */ linkActiveClass: 'is-active', /** * Class applied to the content containers. * @option * @type {string} * @default 'tabs-panel' */ panelClass: 'tabs-panel', /** * Class applied to the active content container. * @option * @type {string} * @default 'is-active' */ panelActiveClass: 'is-active' }; /***/ }), /* 15 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Positionable; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__foundation_util_box__ = __webpack_require__(7); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_plugin__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_core__ = __webpack_require__(1); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var POSITIONS = ['left', 'right', 'top', 'bottom']; var VERTICAL_ALIGNMENTS = ['top', 'bottom', 'center']; var HORIZONTAL_ALIGNMENTS = ['left', 'right', 'center']; var ALIGNMENTS = { 'left': VERTICAL_ALIGNMENTS, 'right': VERTICAL_ALIGNMENTS, 'top': HORIZONTAL_ALIGNMENTS, 'bottom': HORIZONTAL_ALIGNMENTS }; function nextItem(item, array) { var currentIdx = array.indexOf(item); if (currentIdx === array.length - 1) { return array[0]; } else { return array[currentIdx + 1]; } } var Positionable = function (_Plugin) { _inherits(Positionable, _Plugin); function Positionable() { _classCallCheck(this, Positionable); return _possibleConstructorReturn(this, (Positionable.__proto__ || Object.getPrototypeOf(Positionable)).apply(this, arguments)); } _createClass(Positionable, [{ key: '_init', /** * Abstract class encapsulating the tether-like explicit positioning logic * including repositioning based on overlap. * Expects classes to define defaults for vOffset, hOffset, position, * alignment, allowOverlap, and allowBottomOverlap. They can do this by * extending the defaults, or (for now recommended due to the way docs are * generated) by explicitly declaring them. * **/ value: function _init() { this.triedPositions = {}; this.position = this.options.position === 'auto' ? this._getDefaultPosition() : this.options.position; this.alignment = this.options.alignment === 'auto' ? this._getDefaultAlignment() : this.options.alignment; } }, { key: '_getDefaultPosition', value: function _getDefaultPosition() { return 'bottom'; } }, { key: '_getDefaultAlignment', value: function _getDefaultAlignment() { switch (this.position) { case 'bottom': case 'top': return __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__foundation_util_core__["b" /* rtl */])() ? 'right' : 'left'; case 'left': case 'right': return 'bottom'; } } /** * Adjusts the positionable possible positions by iterating through alignments * and positions. * @function * @private */ }, { key: '_reposition', value: function _reposition() { if (this._alignmentsExhausted(this.position)) { this.position = nextItem(this.position, POSITIONS); this.alignment = ALIGNMENTS[this.position][0]; } else { this._realign(); } } /** * Adjusts the dropdown pane possible positions by iterating through alignments * on the current position. * @function * @private */ }, { key: '_realign', value: function _realign() { this._addTriedPosition(this.position, this.alignment); this.alignment = nextItem(this.alignment, ALIGNMENTS[this.position]); } }, { key: '_addTriedPosition', value: function _addTriedPosition(position, alignment) { this.triedPositions[position] = this.triedPositions[position] || []; this.triedPositions[position].push(alignment); } }, { key: '_positionsExhausted', value: function _positionsExhausted() { var isExhausted = true; for (var i = 0; i < POSITIONS.length; i++) { isExhausted = isExhausted && this._alignmentsExhausted(POSITIONS[i]); } return isExhausted; } }, { key: '_alignmentsExhausted', value: function _alignmentsExhausted(position) { return this.triedPositions[position] && this.triedPositions[position].length == ALIGNMENTS[position].length; } // When we're trying to center, we don't want to apply offset that's going to // take us just off center, so wrap around to return 0 for the appropriate // offset in those alignments. TODO: Figure out if we want to make this // configurable behavior... it feels more intuitive, especially for tooltips, but // it's possible someone might actually want to start from center and then nudge // slightly off. }, { key: '_getVOffset', value: function _getVOffset() { return this.options.vOffset; } }, { key: '_getHOffset', value: function _getHOffset() { return this.options.hOffset; } }, { key: '_setPosition', value: function _setPosition($anchor, $element, $parent) { if ($anchor.attr('aria-expanded') === 'false') { return false; } var $eleDims = __WEBPACK_IMPORTED_MODULE_0__foundation_util_box__["a" /* Box */].GetDimensions($element), $anchorDims = __WEBPACK_IMPORTED_MODULE_0__foundation_util_box__["a" /* Box */].GetDimensions($anchor); $element.offset(__WEBPACK_IMPORTED_MODULE_0__foundation_util_box__["a" /* Box */].GetExplicitOffsets($element, $anchor, this.position, this.alignment, this._getVOffset(), this._getHOffset())); if (!this.options.allowOverlap) { var overlaps = {}; var minOverlap = 100000000; // default coordinates to how we start, in case we can't figure out better var minCoordinates = { position: this.position, alignment: this.alignment }; while (!this._positionsExhausted()) { var overlap = __WEBPACK_IMPORTED_MODULE_0__foundation_util_box__["a" /* Box */].OverlapArea($element, $parent, false, false, this.options.allowBottomOverlap); if (overlap === 0) { return; } if (overlap < minOverlap) { minOverlap = overlap; minCoordinates = { position: this.position, alignment: this.alignment }; } this._reposition(); $element.offset(__WEBPACK_IMPORTED_MODULE_0__foundation_util_box__["a" /* Box */].GetExplicitOffsets($element, $anchor, this.position, this.alignment, this._getVOffset(), this._getHOffset())); } // If we get through the entire loop, there was no non-overlapping // position available. Pick the version with least overlap. this.position = minCoordinates.position; this.alignment = minCoordinates.alignment; $element.offset(__WEBPACK_IMPORTED_MODULE_0__foundation_util_box__["a" /* Box */].GetExplicitOffsets($element, $anchor, this.position, this.alignment, this._getVOffset(), this._getHOffset())); } } }]); return Positionable; }(__WEBPACK_IMPORTED_MODULE_1__foundation_plugin__["a" /* Plugin */]); Positionable.defaults = { /** * Position of positionable relative to anchor. Can be left, right, bottom, top, or auto. * @option * @type {string} * @default 'auto' */ position: 'auto', /** * Alignment of positionable relative to anchor. Can be left, right, bottom, top, center, or auto. * @option * @type {string} * @default 'auto' */ alignment: 'auto', /** * Allow overlap of container/window. If false, dropdown positionable first * try to position as defined by data-position and data-alignment, but * reposition if it would cause an overflow. * @option * @type {boolean} * @default false */ allowOverlap: false, /** * Allow overlap of only the bottom of the container. This is the most common * behavior for dropdowns, allowing the dropdown to extend the bottom of the * screen but not otherwise influence or break out of the container. * @option * @type {boolean} * @default true */ allowBottomOverlap: true, /** * Number of pixels the positionable should be separated vertically from anchor * @option * @type {number} * @default 0 */ vOffset: 0, /** * Number of pixels the positionable should be separated horizontally from anchor * @option * @type {number} * @default 0 */ hOffset: 0 }; /***/ }), /* 16 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Touch; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } //************************************************** //**Work inspired by multiple jquery swipe plugins** //**Done by Yohai Ararat *************************** //************************************************** var Touch = {}; var startPosX, startPosY, startTime, elapsedTime, isMoving = false; function onTouchEnd() { // alert(this); this.removeEventListener('touchmove', onTouchMove); this.removeEventListener('touchend', onTouchEnd); isMoving = false; } function onTouchMove(e) { if (__WEBPACK_IMPORTED_MODULE_0_jquery___default.a.spotSwipe.preventDefault) { e.preventDefault(); } if (isMoving) { var x = e.touches[0].pageX; var y = e.touches[0].pageY; var dx = startPosX - x; var dy = startPosY - y; var dir; elapsedTime = new Date().getTime() - startTime; if (Math.abs(dx) >= __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.spotSwipe.moveThreshold && elapsedTime <= __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.spotSwipe.timeThreshold) { dir = dx > 0 ? 'left' : 'right'; } // else if(Math.abs(dy) >= $.spotSwipe.moveThreshold && elapsedTime <= $.spotSwipe.timeThreshold) { // dir = dy > 0 ? 'down' : 'up'; // } if (dir) { e.preventDefault(); onTouchEnd.call(this); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).trigger('swipe', dir).trigger('swipe' + dir); } } } function onTouchStart(e) { if (e.touches.length == 1) { startPosX = e.touches[0].pageX; startPosY = e.touches[0].pageY; isMoving = true; startTime = new Date().getTime(); this.addEventListener('touchmove', onTouchMove, false); this.addEventListener('touchend', onTouchEnd, false); } } function init() { this.addEventListener && this.addEventListener('touchstart', onTouchStart, false); } function teardown() { this.removeEventListener('touchstart', onTouchStart); } var SpotSwipe = function () { function SpotSwipe($) { _classCallCheck(this, SpotSwipe); this.version = '1.0.0'; this.enabled = 'ontouchstart' in document.documentElement; this.preventDefault = false; this.moveThreshold = 75; this.timeThreshold = 200; this.$ = $; this._init(); } _createClass(SpotSwipe, [{ key: '_init', value: function _init() { var $ = this.$; $.event.special.swipe = { setup: init }; $.each(['left', 'up', 'down', 'right'], function () { $.event.special['swipe' + this] = { setup: function () { $(this).on('swipe', $.noop); } }; }); } }]); return SpotSwipe; }(); /**************************************************** * As far as I can tell, both setupSpotSwipe and * * setupTouchHandler should be idempotent, * * because they directly replace functions & * * values, and do not add event handlers directly. * ****************************************************/ Touch.setupSpotSwipe = function ($) { $.spotSwipe = new SpotSwipe($); }; /**************************************************** * Method for adding pseudo drag events to elements * ***************************************************/ Touch.setupTouchHandler = function ($) { $.fn.addTouch = function () { this.each(function (i, el) { $(el).bind('touchstart touchmove touchend touchcancel', function () { //we pass the original event object because the jQuery event //object is normalized to w3c specs and does not provide the TouchList handleTouch(event); }); }); var handleTouch = function (event) { var touches = event.changedTouches, first = touches[0], eventTypes = { touchstart: 'mousedown', touchmove: 'mousemove', touchend: 'mouseup' }, type = eventTypes[event.type], simulatedEvent; if ('MouseEvent' in window && typeof window.MouseEvent === 'function') { simulatedEvent = new window.MouseEvent(type, { 'bubbles': true, 'cancelable': true, 'screenX': first.screenX, 'screenY': first.screenY, 'clientX': first.clientX, 'clientY': first.clientY }); } else { simulatedEvent = document.createEvent('MouseEvent'); simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, first.clientX, first.clientY, false, false, false, false, 0 /*left*/, null); } first.target.dispatchEvent(simulatedEvent); }; }; }; Touch.init = function ($) { if (typeof $.spotSwipe === 'undefined') { Touch.setupSpotSwipe($); Touch.setupTouchHandler($); } }; /***/ }), /* 17 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Abide; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_plugin__ = __webpack_require__(2); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Abide module. * @module foundation.abide */ var Abide = function (_Plugin) { _inherits(Abide, _Plugin); function Abide() { _classCallCheck(this, Abide); return _possibleConstructorReturn(this, (Abide.__proto__ || Object.getPrototypeOf(Abide)).apply(this, arguments)); } _createClass(Abide, [{ key: '_setup', /** * Creates a new instance of Abide. * @class * @fires Abide#init * @param {Object} element - jQuery object to add the trigger to. * @param {Object} options - Overrides to the default plugin settings. */ value: function _setup(element) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Abide.defaults, this.$element.data(), options); this.className = 'Abide'; // ie9 back compat this._init(); } /** * Initializes the Abide plugin and calls functions to get Abide functioning on load. * @private */ }, { key: '_init', value: function _init() { this.$inputs = this.$element.find('input, textarea, select'); this._events(); } /** * Initializes events for Abide. * @private */ }, { key: '_events', value: function _events() { var _this3 = this; this.$element.off('.abide').on('reset.zf.abide', function () { _this3.resetForm(); }).on('submit.zf.abide', function () { return _this3.validateForm(); }); if (this.options.validateOn === 'fieldChange') { this.$inputs.off('change.zf.abide').on('change.zf.abide', function (e) { _this3.validateInput(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(e.target)); }); } if (this.options.liveValidate) { this.$inputs.off('input.zf.abide').on('input.zf.abide', function (e) { _this3.validateInput(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(e.target)); }); } if (this.options.validateOnBlur) { this.$inputs.off('blur.zf.abide').on('blur.zf.abide', function (e) { _this3.validateInput(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(e.target)); }); } } /** * Calls necessary functions to update Abide upon DOM change * @private */ }, { key: '_reflow', value: function _reflow() { this._init(); } /** * Checks whether or not a form element has the required attribute and if it's checked or not * @param {Object} element - jQuery object to check for required attribute * @returns {Boolean} Boolean value depends on whether or not attribute is checked or empty */ }, { key: 'requiredCheck', value: function requiredCheck($el) { if (!$el.attr('required')) return true; var isGood = true; switch ($el[0].type) { case 'checkbox': isGood = $el[0].checked; break; case 'select': case 'select-one': case 'select-multiple': var opt = $el.find('option:selected'); if (!opt.length || !opt.val()) isGood = false; break; default: if (!$el.val() || !$el.val().length) isGood = false; } return isGood; } /** * Get: * - Based on $el, the first element(s) corresponding to `formErrorSelector` in this order: * 1. The element's direct sibling('s). * 2. The element's parent's children. * - Element(s) with the attribute `[data-form-error-for]` set with the element's id. * * This allows for multiple form errors per input, though if none are found, no form errors will be shown. * * @param {Object} $el - jQuery object to use as reference to find the form error selector. * @returns {Object} jQuery object with the selector. */ }, { key: 'findFormError', value: function findFormError($el) { var id = $el[0].id; var $error = $el.siblings(this.options.formErrorSelector); if (!$error.length) { $error = $el.parent().find(this.options.formErrorSelector); } $error = $error.add(this.$element.find('[data-form-error-for="' + id + '"]')); return $error; } /** * Get the first element in this order: * 2. The <label> with the attribute `[for="someInputId"]` * 3. The `.closest()` <label> * * @param {Object} $el - jQuery object to check for required attribute * @returns {Boolean} Boolean value depends on whether or not attribute is checked or empty */ }, { key: 'findLabel', value: function findLabel($el) { var id = $el[0].id; var $label = this.$element.find('label[for="' + id + '"]'); if (!$label.length) { return $el.closest('label'); } return $label; } /** * Get the set of labels associated with a set of radio els in this order * 2. The <label> with the attribute `[for="someInputId"]` * 3. The `.closest()` <label> * * @param {Object} $el - jQuery object to check for required attribute * @returns {Boolean} Boolean value depends on whether or not attribute is checked or empty */ }, { key: 'findRadioLabels', value: function findRadioLabels($els) { var _this4 = this; var labels = $els.map(function (i, el) { var id = el.id; var $label = _this4.$element.find('label[for="' + id + '"]'); if (!$label.length) { $label = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(el).closest('label'); } return $label[0]; }); return __WEBPACK_IMPORTED_MODULE_0_jquery___default()(labels); } /** * Adds the CSS error class as specified by the Abide settings to the label, input, and the form * @param {Object} $el - jQuery object to add the class to */ }, { key: 'addErrorClasses', value: function addErrorClasses($el) { var $label = this.findLabel($el); var $formError = this.findFormError($el); if ($label.length) { $label.addClass(this.options.labelErrorClass); } if ($formError.length) { $formError.addClass(this.options.formErrorClass); } $el.addClass(this.options.inputErrorClass).attr('data-invalid', ''); } /** * Remove CSS error classes etc from an entire radio button group * @param {String} groupName - A string that specifies the name of a radio button group * */ }, { key: 'removeRadioErrorClasses', value: function removeRadioErrorClasses(groupName) { var $els = this.$element.find(':radio[name="' + groupName + '"]'); var $labels = this.findRadioLabels($els); var $formErrors = this.findFormError($els); if ($labels.length) { $labels.removeClass(this.options.labelErrorClass); } if ($formErrors.length) { $formErrors.removeClass(this.options.formErrorClass); } $els.removeClass(this.options.inputErrorClass).removeAttr('data-invalid'); } /** * Removes CSS error class as specified by the Abide settings from the label, input, and the form * @param {Object} $el - jQuery object to remove the class from */ }, { key: 'removeErrorClasses', value: function removeErrorClasses($el) { // radios need to clear all of the els if ($el[0].type == 'radio') { return this.removeRadioErrorClasses($el.attr('name')); } var $label = this.findLabel($el); var $formError = this.findFormError($el); if ($label.length) { $label.removeClass(this.options.labelErrorClass); } if ($formError.length) { $formError.removeClass(this.options.formErrorClass); } $el.removeClass(this.options.inputErrorClass).removeAttr('data-invalid'); } /** * Goes through a form to find inputs and proceeds to validate them in ways specific to their type. * Ignores inputs with data-abide-ignore, type="hidden" or disabled attributes set * @fires Abide#invalid * @fires Abide#valid * @param {Object} element - jQuery object to validate, should be an HTML input * @returns {Boolean} goodToGo - If the input is valid or not. */ }, { key: 'validateInput', value: function validateInput($el) { var _this5 = this; var clearRequire = this.requiredCheck($el), validated = false, customValidator = true, validator = $el.attr('data-validator'), equalTo = true; // don't validate ignored inputs or hidden inputs or disabled inputs if ($el.is('[data-abide-ignore]') || $el.is('[type="hidden"]') || $el.is('[disabled]')) { return true; } switch ($el[0].type) { case 'radio': validated = this.validateRadio($el.attr('name')); break; case 'checkbox': validated = clearRequire; break; case 'select': case 'select-one': case 'select-multiple': validated = clearRequire; break; default: validated = this.validateText($el); } if (validator) { customValidator = this.matchValidation($el, validator, $el.attr('required')); } if ($el.attr('data-equalto')) { equalTo = this.options.validators.equalTo($el); } var goodToGo = [clearRequire, validated, customValidator, equalTo].indexOf(false) === -1; var message = (goodToGo ? 'valid' : 'invalid') + '.zf.abide'; if (goodToGo) { // Re-validate inputs that depend on this one with equalto var dependentElements = this.$element.find('[data-equalto="' + $el.attr('id') + '"]'); if (dependentElements.length) { (function () { var _this = _this5; dependentElements.each(function () { if (__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).val()) { _this.validateInput(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this)); } }); })(); } } this[goodToGo ? 'removeErrorClasses' : 'addErrorClasses']($el); /** * Fires when the input is done checking for validation. Event trigger is either `valid.zf.abide` or `invalid.zf.abide` * Trigger includes the DOM element of the input. * @event Abide#valid * @event Abide#invalid */ $el.trigger(message, [$el]); return goodToGo; } /** * Goes through a form and if there are any invalid inputs, it will display the form error element * @returns {Boolean} noError - true if no errors were detected... * @fires Abide#formvalid * @fires Abide#forminvalid */ }, { key: 'validateForm', value: function validateForm() { var acc = []; var _this = this; this.$inputs.each(function () { acc.push(_this.validateInput(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this))); }); var noError = acc.indexOf(false) === -1; this.$element.find('[data-abide-error]').css('display', noError ? 'none' : 'block'); /** * Fires when the form is finished validating. Event trigger is either `formvalid.zf.abide` or `forminvalid.zf.abide`. * Trigger includes the element of the form. * @event Abide#formvalid * @event Abide#forminvalid */ this.$element.trigger((noError ? 'formvalid' : 'forminvalid') + '.zf.abide', [this.$element]); return noError; } /** * Determines whether or a not a text input is valid based on the pattern specified in the attribute. If no matching pattern is found, returns true. * @param {Object} $el - jQuery object to validate, should be a text input HTML element * @param {String} pattern - string value of one of the RegEx patterns in Abide.options.patterns * @returns {Boolean} Boolean value depends on whether or not the input value matches the pattern specified */ }, { key: 'validateText', value: function validateText($el, pattern) { // A pattern can be passed to this function, or it will be infered from the input's "pattern" attribute, or it's "type" attribute pattern = pattern || $el.attr('pattern') || $el.attr('type'); var inputText = $el.val(); var valid = false; if (inputText.length) { // If the pattern attribute on the element is in Abide's list of patterns, then test that regexp if (this.options.patterns.hasOwnProperty(pattern)) { valid = this.options.patterns[pattern].test(inputText); } // If the pattern name isn't also the type attribute of the field, then test it as a regexp else if (pattern !== $el.attr('type')) { valid = new RegExp(pattern).test(inputText); } else { valid = true; } } // An empty field is valid if it's not required else if (!$el.prop('required')) { valid = true; } return valid; } /** * Determines whether or a not a radio input is valid based on whether or not it is required and selected. Although the function targets a single `<input>`, it validates by checking the `required` and `checked` properties of all radio buttons in its group. * @param {String} groupName - A string that specifies the name of a radio button group * @returns {Boolean} Boolean value depends on whether or not at least one radio input has been selected (if it's required) */ }, { key: 'validateRadio', value: function validateRadio(groupName) { // If at least one radio in the group has the `required` attribute, the group is considered required // Per W3C spec, all radio buttons in a group should have `required`, but we're being nice var $group = this.$element.find(':radio[name="' + groupName + '"]'); var valid = false, required = false; // For the group to be required, at least one radio needs to be required $group.each(function (i, e) { if (__WEBPACK_IMPORTED_MODULE_0_jquery___default()(e).attr('required')) { required = true; } }); if (!required) valid = true; if (!valid) { // For the group to be valid, at least one radio needs to be checked $group.each(function (i, e) { if (__WEBPACK_IMPORTED_MODULE_0_jquery___default()(e).prop('checked')) { valid = true; } }); }; return valid; } /** * Determines if a selected input passes a custom validation function. Multiple validations can be used, if passed to the element with `data-validator="foo bar baz"` in a space separated listed. * @param {Object} $el - jQuery input element. * @param {String} validators - a string of function names matching functions in the Abide.options.validators object. * @param {Boolean} required - self explanatory? * @returns {Boolean} - true if validations passed. */ }, { key: 'matchValidation', value: function matchValidation($el, validators, required) { var _this6 = this; required = required ? true : false; var clear = validators.split(' ').map(function (v) { return _this6.options.validators[v]($el, required, $el.parent()); }); return clear.indexOf(false) === -1; } /** * Resets form inputs and styles * @fires Abide#formreset */ }, { key: 'resetForm', value: function resetForm() { var $form = this.$element, opts = this.options; __WEBPACK_IMPORTED_MODULE_0_jquery___default()('.' + opts.labelErrorClass, $form).not('small').removeClass(opts.labelErrorClass); __WEBPACK_IMPORTED_MODULE_0_jquery___default()('.' + opts.inputErrorClass, $form).not('small').removeClass(opts.inputErrorClass); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(opts.formErrorSelector + '.' + opts.formErrorClass).removeClass(opts.formErrorClass); $form.find('[data-abide-error]').css('display', 'none'); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(':input', $form).not(':button, :submit, :reset, :hidden, :radio, :checkbox, [data-abide-ignore]').val('').removeAttr('data-invalid'); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(':input:radio', $form).not('[data-abide-ignore]').prop('checked', false).removeAttr('data-invalid'); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(':input:checkbox', $form).not('[data-abide-ignore]').prop('checked', false).removeAttr('data-invalid'); /** * Fires when the form has been reset. * @event Abide#formreset */ $form.trigger('formreset.zf.abide', [$form]); } /** * Destroys an instance of Abide. * Removes error styles and classes from elements, without resetting their values. */ }, { key: '_destroy', value: function _destroy() { var _this = this; this.$element.off('.abide').find('[data-abide-error]').css('display', 'none'); this.$inputs.off('.abide').each(function () { _this.removeErrorClasses(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this)); }); } }]); return Abide; }(__WEBPACK_IMPORTED_MODULE_1__foundation_plugin__["a" /* Plugin */]); /** * Default settings for plugin */ Abide.defaults = { /** * The default event to validate inputs. Checkboxes and radios validate immediately. * Remove or change this value for manual validation. * @option * @type {?string} * @default 'fieldChange' */ validateOn: 'fieldChange', /** * Class to be applied to input labels on failed validation. * @option * @type {string} * @default 'is-invalid-label' */ labelErrorClass: 'is-invalid-label', /** * Class to be applied to inputs on failed validation. * @option * @type {string} * @default 'is-invalid-input' */ inputErrorClass: 'is-invalid-input', /** * Class selector to use to target Form Errors for show/hide. * @option * @type {string} * @default '.form-error' */ formErrorSelector: '.form-error', /** * Class added to Form Errors on failed validation. * @option * @type {string} * @default 'is-visible' */ formErrorClass: 'is-visible', /** * Set to true to validate text inputs on any value change. * @option * @type {boolean} * @default false */ liveValidate: false, /** * Set to true to validate inputs on blur. * @option * @type {boolean} * @default false */ validateOnBlur: false, patterns: { alpha: /^[a-zA-Z]+$/, alpha_numeric: /^[a-zA-Z0-9]+$/, integer: /^[-+]?\d+$/, number: /^[-+]?\d*(?:[\.\,]\d+)?$/, // amex, visa, diners card: /^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/, cvv: /^([0-9]){3,4}$/, // http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address email: /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/, url: /^(https?|ftp|file|ssh):\/\/(((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-zA-Z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-zA-Z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/, // abc.de domain: /^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,8}$/, datetime: /^([0-2][0-9]{3})\-([0-1][0-9])\-([0-3][0-9])T([0-5][0-9])\:([0-5][0-9])\:([0-5][0-9])(Z|([\-\+]([0-1][0-9])\:00))$/, // YYYY-MM-DD date: /(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))$/, // HH:MM:SS time: /^(0[0-9]|1[0-9]|2[0-3])(:[0-5][0-9]){2}$/, dateISO: /^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}$/, // MM/DD/YYYY month_day_year: /^(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.]\d{4}$/, // DD/MM/YYYY day_month_year: /^(0[1-9]|[12][0-9]|3[01])[- \/.](0[1-9]|1[012])[- \/.]\d{4}$/, // #FFF or #FFFFFF color: /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/, // Domain || URL website: { test: function (text) { return Abide.defaults.patterns['domain'].test(text) || Abide.defaults.patterns['url'].test(text); } } }, /** * Optional validation functions to be used. `equalTo` being the only default included function. * Functions should return only a boolean if the input is valid or not. Functions are given the following arguments: * el : The jQuery element to validate. * required : Boolean value of the required attribute be present or not. * parent : The direct parent of the input. * @option */ validators: { equalTo: function (el, required, parent) { return __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + el.attr('data-equalto')).val() === el.val(); } } }; /***/ }), /* 18 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Foundation; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_core__ = __webpack_require__(1); var FOUNDATION_VERSION = '6.4.0'; // Global Foundation object // This is attached to the window, or used as a module for AMD/Browserify var Foundation = { version: FOUNDATION_VERSION, /** * Stores initialized plugins. */ _plugins: {}, /** * Stores generated unique ids for plugin instances */ _uuids: [], /** * Defines a Foundation plugin, adding it to the `Foundation` namespace and the list of plugins to initialize when reflowing. * @param {Object} plugin - The constructor of the plugin. */ plugin: function (plugin, name) { // Object key to use when adding to global Foundation object // Examples: Foundation.Reveal, Foundation.OffCanvas var className = name || functionName(plugin); // Object key to use when storing the plugin, also used to create the identifying data attribute for the plugin // Examples: data-reveal, data-off-canvas var attrName = hyphenate(className); // Add to the Foundation object and the plugins list (for reflowing) this._plugins[attrName] = this[className] = plugin; }, /** * @function * Populates the _uuids array with pointers to each individual plugin instance. * Adds the `zfPlugin` data-attribute to programmatically created plugins to allow use of $(selector).foundation(method) calls. * Also fires the initialization event for each plugin, consolidating repetitive code. * @param {Object} plugin - an instance of a plugin, usually `this` in context. * @param {String} name - the name of the plugin, passed as a camelCased string. * @fires Plugin#init */ registerPlugin: function (plugin, name) { var pluginName = name ? hyphenate(name) : functionName(plugin.constructor).toLowerCase(); plugin.uuid = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__foundation_util_core__["a" /* GetYoDigits */])(6, pluginName); if (!plugin.$element.attr('data-' + pluginName)) { plugin.$element.attr('data-' + pluginName, plugin.uuid); } if (!plugin.$element.data('zfPlugin')) { plugin.$element.data('zfPlugin', plugin); } /** * Fires when the plugin has initialized. * @event Plugin#init */ plugin.$element.trigger('init.zf.' + pluginName); this._uuids.push(plugin.uuid); return; }, /** * @function * Removes the plugins uuid from the _uuids array. * Removes the zfPlugin data attribute, as well as the data-plugin-name attribute. * Also fires the destroyed event for the plugin, consolidating repetitive code. * @param {Object} plugin - an instance of a plugin, usually `this` in context. * @fires Plugin#destroyed */ unregisterPlugin: function (plugin) { var pluginName = hyphenate(functionName(plugin.$element.data('zfPlugin').constructor)); this._uuids.splice(this._uuids.indexOf(plugin.uuid), 1); plugin.$element.removeAttr('data-' + pluginName).removeData('zfPlugin') /** * Fires when the plugin has been destroyed. * @event Plugin#destroyed */ .trigger('destroyed.zf.' + pluginName); for (var prop in plugin) { plugin[prop] = null; //clean up script to prep for garbage collection. } return; }, /** * @function * Causes one or more active plugins to re-initialize, resetting event listeners, recalculating positions, etc. * @param {String} plugins - optional string of an individual plugin key, attained by calling `$(element).data('pluginName')`, or string of a plugin class i.e. `'dropdown'` * @default If no argument is passed, reflow all currently active plugins. */ reInit: function (plugins) { var isJQ = plugins instanceof __WEBPACK_IMPORTED_MODULE_0_jquery___default.a; try { if (isJQ) { plugins.each(function () { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('zfPlugin')._init(); }); } else { var type = typeof plugins, _this = this, fns = { 'object': function (plgs) { plgs.forEach(function (p) { p = hyphenate(p); __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-' + p + ']').foundation('_init'); }); }, 'string': function () { plugins = hyphenate(plugins); __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-' + plugins + ']').foundation('_init'); }, 'undefined': function () { this['object'](Object.keys(_this._plugins)); } }; fns[type](plugins); } } catch (err) { console.error(err); } finally { return plugins; } }, /** * Initialize plugins on any elements within `elem` (and `elem` itself) that aren't already initialized. * @param {Object} elem - jQuery object containing the element to check inside. Also checks the element itself, unless it's the `document` object. * @param {String|Array} plugins - A list of plugins to initialize. Leave this out to initialize everything. */ reflow: function (elem, plugins) { // If plugins is undefined, just grab everything if (typeof plugins === 'undefined') { plugins = Object.keys(this._plugins); } // If plugins is a string, convert it to an array with one item else if (typeof plugins === 'string') { plugins = [plugins]; } var _this = this; // Iterate through each plugin __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.each(plugins, function (i, name) { // Get the current plugin var plugin = _this._plugins[name]; // Localize the search to all elements inside elem, as well as elem itself, unless elem === document var $elem = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(elem).find('[data-' + name + ']').addBack('[data-' + name + ']'); // For each plugin found, initialize it $elem.each(function () { var $el = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), opts = {}; // Don't double-dip on plugins if ($el.data('zfPlugin')) { console.warn("Tried to initialize " + name + " on an element that already has a Foundation plugin."); return; } if ($el.attr('data-options')) { var thing = $el.attr('data-options').split(';').forEach(function (e, i) { var opt = e.split(':').map(function (el) { return el.trim(); }); if (opt[0]) opts[opt[0]] = parseValue(opt[1]); }); } try { $el.data('zfPlugin', new plugin(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), opts)); } catch (er) { console.error(er); } finally { return; } }); }); }, getFnName: functionName, addToJquery: function ($) { // TODO: consider not making this a jQuery function // TODO: need way to reflow vs. re-initialize /** * The Foundation jQuery method. * @param {String|Array} method - An action to perform on the current jQuery object. */ var foundation = function (method) { var type = typeof method, $noJS = $('.no-js'); if ($noJS.length) { $noJS.removeClass('no-js'); } if (type === 'undefined') { //needs to initialize the Foundation object, or an individual plugin. Foundation.MediaQuery._init(); Foundation.reflow(this); } else if (type === 'string') { //an individual method to invoke on a plugin or group of plugins var args = Array.prototype.slice.call(arguments, 1); //collect all the arguments, if necessary var plugClass = this.data('zfPlugin'); //determine the class of plugin if (plugClass !== undefined && plugClass[method] !== undefined) { //make sure both the class and method exist if (this.length === 1) { //if there's only one, call it directly. plugClass[method].apply(plugClass, args); } else { this.each(function (i, el) { //otherwise loop through the jQuery collection and invoke the method on each plugClass[method].apply($(el).data('zfPlugin'), args); }); } } else { //error for no class or no method throw new ReferenceError("We're sorry, '" + method + "' is not an available method for " + (plugClass ? functionName(plugClass) : 'this element') + '.'); } } else { //error for invalid argument type throw new TypeError('We\'re sorry, ' + type + ' is not a valid parameter. You must use a string representing the method you wish to invoke.'); } return this; }; $.fn.foundation = foundation; return $; } }; Foundation.util = { /** * Function for applying a debounce effect to a function call. * @function * @param {Function} func - Function to be called at end of timeout. * @param {Number} delay - Time in ms to delay the call of `func`. * @returns function */ throttle: function (func, delay) { var timer = null; return function () { var context = this, args = arguments; if (timer === null) { timer = setTimeout(function () { func.apply(context, args); timer = null; }, delay); } }; } }; window.Foundation = Foundation; // Polyfill for requestAnimationFrame (function () { if (!Date.now || !window.Date.now) window.Date.now = Date.now = function () { return new Date().getTime(); }; var vendors = ['webkit', 'moz']; for (var i = 0; i < vendors.length && !window.requestAnimationFrame; ++i) { var vp = vendors[i]; window.requestAnimationFrame = window[vp + 'RequestAnimationFrame']; window.cancelAnimationFrame = window[vp + 'CancelAnimationFrame'] || window[vp + 'CancelRequestAnimationFrame']; } if (/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent) || !window.requestAnimationFrame || !window.cancelAnimationFrame) { var lastTime = 0; window.requestAnimationFrame = function (callback) { var now = Date.now(); var nextTime = Math.max(lastTime + 16, now); return setTimeout(function () { callback(lastTime = nextTime); }, nextTime - now); }; window.cancelAnimationFrame = clearTimeout; } /** * Polyfill for performance.now, required by rAF */ if (!window.performance || !window.performance.now) { window.performance = { start: Date.now(), now: function () { return Date.now() - this.start; } }; } })(); if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== 'function') { // closest thing possible to the ECMAScript 5 // internal IsCallable function throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () {}, fBound = function () { return fToBind.apply(this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; if (this.prototype) { // native functions don't have a prototype fNOP.prototype = this.prototype; } fBound.prototype = new fNOP(); return fBound; }; } // Polyfill to get the name of a function in IE9 function functionName(fn) { if (Function.prototype.name === undefined) { var funcNameRegex = /function\s([^(]{1,})\(/; var results = funcNameRegex.exec(fn.toString()); return results && results.length > 1 ? results[1].trim() : ""; } else if (fn.prototype === undefined) { return fn.constructor.name; } else { return fn.prototype.constructor.name; } } function parseValue(str) { if ('true' === str) return true;else if ('false' === str) return false;else if (!isNaN(str * 1)) return parseFloat(str); return str; } // Convert PascalCase to kebab-case // Thank you: http://stackoverflow.com/a/8955580 function hyphenate(str) { return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); } /***/ }), /* 19 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Dropdown; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_positionable__ = __webpack_require__(15); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__foundation_util_triggers__ = __webpack_require__(5); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Dropdown module. * @module foundation.dropdown * @requires foundation.util.keyboard * @requires foundation.util.box * @requires foundation.util.triggers */ var Dropdown = function (_Positionable) { _inherits(Dropdown, _Positionable); function Dropdown() { _classCallCheck(this, Dropdown); return _possibleConstructorReturn(this, (Dropdown.__proto__ || Object.getPrototypeOf(Dropdown)).apply(this, arguments)); } _createClass(Dropdown, [{ key: '_setup', /** * Creates a new instance of a dropdown. * @class * @param {jQuery} element - jQuery object to make into a dropdown. * Object should be of the dropdown panel, rather than its anchor. * @param {Object} options - Overrides to the default plugin settings. */ value: function _setup(element, options) { this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Dropdown.defaults, this.$element.data(), options); this.className = 'Dropdown'; // ie9 back compat // Triggers init is idempotent, just need to make sure it is initialized __WEBPACK_IMPORTED_MODULE_4__foundation_util_triggers__["a" /* Triggers */].init(__WEBPACK_IMPORTED_MODULE_0_jquery___default.a); this._init(); __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].register('Dropdown', { 'ENTER': 'open', 'SPACE': 'open', 'ESCAPE': 'close' }); } /** * Initializes the plugin by setting/checking options and attributes, adding helper variables, and saving the anchor. * @function * @private */ }, { key: '_init', value: function _init() { var $id = this.$element.attr('id'); this.$anchor = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-toggle="' + $id + '"]').length ? __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-toggle="' + $id + '"]') : __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-open="' + $id + '"]'); this.$anchor.attr({ 'aria-controls': $id, 'data-is-focus': false, 'data-yeti-box': $id, 'aria-haspopup': true, 'aria-expanded': false }); if (this.options.parentClass) { this.$parent = this.$element.parents('.' + this.options.parentClass); } else { this.$parent = null; } this.$element.attr({ 'aria-hidden': 'true', 'data-yeti-box': $id, 'data-resize': $id, 'aria-labelledby': this.$anchor[0].id || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__foundation_util_core__["a" /* GetYoDigits */])(6, 'dd-anchor') }); _get(Dropdown.prototype.__proto__ || Object.getPrototypeOf(Dropdown.prototype), '_init', this).call(this); this._events(); } }, { key: '_getDefaultPosition', value: function _getDefaultPosition() { // handle legacy classnames var position = this.$element[0].className.match(/(top|left|right|bottom)/g); if (position) { return position[0]; } else { return 'bottom'; } } }, { key: '_getDefaultAlignment', value: function _getDefaultAlignment() { // handle legacy float approach var horizontalPosition = /float-(\S+)/.exec(this.$anchor[0].className); if (horizontalPosition) { return horizontalPosition[1]; } return _get(Dropdown.prototype.__proto__ || Object.getPrototypeOf(Dropdown.prototype), '_getDefaultAlignment', this).call(this); } /** * Sets the position and orientation of the dropdown pane, checks for collisions if allow-overlap is not true. * Recursively calls itself if a collision is detected, with a new position class. * @function * @private */ }, { key: '_setPosition', value: function _setPosition() { _get(Dropdown.prototype.__proto__ || Object.getPrototypeOf(Dropdown.prototype), '_setPosition', this).call(this, this.$anchor, this.$element, this.$parent); } /** * Adds event listeners to the element utilizing the triggers utility library. * @function * @private */ }, { key: '_events', value: function _events() { var _this = this; this.$element.on({ 'open.zf.trigger': this.open.bind(this), 'close.zf.trigger': this.close.bind(this), 'toggle.zf.trigger': this.toggle.bind(this), 'resizeme.zf.trigger': this._setPosition.bind(this) }); if (this.options.hover) { this.$anchor.off('mouseenter.zf.dropdown mouseleave.zf.dropdown').on('mouseenter.zf.dropdown', function () { var bodyData = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('body').data(); if (typeof bodyData.whatinput === 'undefined' || bodyData.whatinput === 'mouse') { clearTimeout(_this.timeout); _this.timeout = setTimeout(function () { _this.open(); _this.$anchor.data('hover', true); }, _this.options.hoverDelay); } }).on('mouseleave.zf.dropdown', function () { clearTimeout(_this.timeout); _this.timeout = setTimeout(function () { _this.close(); _this.$anchor.data('hover', false); }, _this.options.hoverDelay); }); if (this.options.hoverPane) { this.$element.off('mouseenter.zf.dropdown mouseleave.zf.dropdown').on('mouseenter.zf.dropdown', function () { clearTimeout(_this.timeout); }).on('mouseleave.zf.dropdown', function () { clearTimeout(_this.timeout); _this.timeout = setTimeout(function () { _this.close(); _this.$anchor.data('hover', false); }, _this.options.hoverDelay); }); } } this.$anchor.add(this.$element).on('keydown.zf.dropdown', function (e) { var $target = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), visibleFocusableElements = __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].findFocusable(_this.$element); __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].handleKey(e, 'Dropdown', { open: function () { if ($target.is(_this.$anchor)) { _this.open(); _this.$element.attr('tabindex', -1).focus(); e.preventDefault(); } }, close: function () { _this.close(); _this.$anchor.focus(); } }); }); } /** * Adds an event handler to the body to close any dropdowns on a click. * @function * @private */ }, { key: '_addBodyHandler', value: function _addBodyHandler() { var $body = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(document.body).not(this.$element), _this = this; $body.off('click.zf.dropdown').on('click.zf.dropdown', function (e) { if (_this.$anchor.is(e.target) || _this.$anchor.find(e.target).length) { return; } if (_this.$element.find(e.target).length) { return; } _this.close(); $body.off('click.zf.dropdown'); }); } /** * Opens the dropdown pane, and fires a bubbling event to close other dropdowns. * @function * @fires Dropdown#closeme * @fires Dropdown#show */ }, { key: 'open', value: function open() { // var _this = this; /** * Fires to close other open dropdowns, typically when dropdown is opening * @event Dropdown#closeme */ this.$element.trigger('closeme.zf.dropdown', this.$element.attr('id')); this.$anchor.addClass('hover').attr({ 'aria-expanded': true }); // this.$element/*.show()*/; this.$element.addClass('is-opening'); this._setPosition(); this.$element.removeClass('is-opening').addClass('is-open').attr({ 'aria-hidden': false }); if (this.options.autoFocus) { var $focusable = __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].findFocusable(this.$element); if ($focusable.length) { $focusable.eq(0).focus(); } } if (this.options.closeOnClick) { this._addBodyHandler(); } if (this.options.trapFocus) { __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].trapFocus(this.$element); } /** * Fires once the dropdown is visible. * @event Dropdown#show */ this.$element.trigger('show.zf.dropdown', [this.$element]); } /** * Closes the open dropdown pane. * @function * @fires Dropdown#hide */ }, { key: 'close', value: function close() { if (!this.$element.hasClass('is-open')) { return false; } this.$element.removeClass('is-open').attr({ 'aria-hidden': true }); this.$anchor.removeClass('hover').attr('aria-expanded', false); /** * Fires once the dropdown is no longer visible. * @event Dropdown#hide */ this.$element.trigger('hide.zf.dropdown', [this.$element]); if (this.options.trapFocus) { __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].releaseFocus(this.$element); } } /** * Toggles the dropdown pane's visibility. * @function */ }, { key: 'toggle', value: function toggle() { if (this.$element.hasClass('is-open')) { if (this.$anchor.data('hover')) return; this.close(); } else { this.open(); } } /** * Destroys the dropdown. * @function */ }, { key: '_destroy', value: function _destroy() { this.$element.off('.zf.trigger').hide(); this.$anchor.off('.zf.dropdown'); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(document.body).off('click.zf.dropdown'); } }]); return Dropdown; }(__WEBPACK_IMPORTED_MODULE_3__foundation_positionable__["a" /* Positionable */]); Dropdown.defaults = { /** * Class that designates bounding container of Dropdown (default: window) * @option * @type {?string} * @default null */ parentClass: null, /** * Amount of time to delay opening a submenu on hover event. * @option * @type {number} * @default 250 */ hoverDelay: 250, /** * Allow submenus to open on hover events * @option * @type {boolean} * @default false */ hover: false, /** * Don't close dropdown when hovering over dropdown pane * @option * @type {boolean} * @default false */ hoverPane: false, /** * Number of pixels between the dropdown pane and the triggering element on open. * @option * @type {number} * @default 0 */ vOffset: 0, /** * Number of pixels between the dropdown pane and the triggering element on open. * @option * @type {number} * @default 0 */ hOffset: 0, /** * DEPRECATED: Class applied to adjust open position. * @option * @type {string} * @default '' */ positionClass: '', /** * Position of dropdown. Can be left, right, bottom, top, or auto. * @option * @type {string} * @default 'auto' */ position: 'auto', /** * Alignment of dropdown relative to anchor. Can be left, right, bottom, top, center, or auto. * @option * @type {string} * @default 'auto' */ alignment: 'auto', /** * Allow overlap of container/window. If false, dropdown will first try to position as defined by data-position and data-alignment, but reposition if it would cause an overflow. * @option * @type {boolean} * @default false */ allowOverlap: false, /** * Allow overlap of only the bottom of the container. This is the most common * behavior for dropdowns, allowing the dropdown to extend the bottom of the * screen but not otherwise influence or break out of the container. * @option * @type {boolean} * @default true */ allowBottomOverlap: true, /** * Allow the plugin to trap focus to the dropdown pane if opened with keyboard commands. * @option * @type {boolean} * @default false */ trapFocus: false, /** * Allow the plugin to set focus to the first focusable element within the pane, regardless of method of opening. * @option * @type {boolean} * @default false */ autoFocus: false, /** * Allows a click on the body to close the dropdown. * @option * @type {boolean} * @default false */ closeOnClick: false }; /***/ }), /* 20 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Equalizer; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_mediaQuery__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_imageLoader__ = __webpack_require__(8); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_util_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__foundation_plugin__ = __webpack_require__(2); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Equalizer module. * @module foundation.equalizer * @requires foundation.util.mediaQuery * @requires foundation.util.imageLoader if equalizer contains images */ var Equalizer = function (_Plugin) { _inherits(Equalizer, _Plugin); function Equalizer() { _classCallCheck(this, Equalizer); return _possibleConstructorReturn(this, (Equalizer.__proto__ || Object.getPrototypeOf(Equalizer)).apply(this, arguments)); } _createClass(Equalizer, [{ key: '_setup', /** * Creates a new instance of Equalizer. * @class * @fires Equalizer#init * @param {Object} element - jQuery object to add the trigger to. * @param {Object} options - Overrides to the default plugin settings. */ value: function _setup(element, options) { this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Equalizer.defaults, this.$element.data(), options); this.className = 'Equalizer'; // ie9 back compat this._init(); } /** * Initializes the Equalizer plugin and calls functions to get equalizer functioning on load. * @private */ }, { key: '_init', value: function _init() { var eqId = this.$element.attr('data-equalizer') || ''; var $watched = this.$element.find('[data-equalizer-watch="' + eqId + '"]'); __WEBPACK_IMPORTED_MODULE_1__foundation_util_mediaQuery__["a" /* MediaQuery */]._init(); this.$watched = $watched.length ? $watched : this.$element.find('[data-equalizer-watch]'); this.$element.attr('data-resize', eqId || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__["a" /* GetYoDigits */])(6, 'eq')); this.$element.attr('data-mutate', eqId || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__["a" /* GetYoDigits */])(6, 'eq')); this.hasNested = this.$element.find('[data-equalizer]').length > 0; this.isNested = this.$element.parentsUntil(document.body, '[data-equalizer]').length > 0; this.isOn = false; this._bindHandler = { onResizeMeBound: this._onResizeMe.bind(this), onPostEqualizedBound: this._onPostEqualized.bind(this) }; var imgs = this.$element.find('img'); var tooSmall; if (this.options.equalizeOn) { tooSmall = this._checkMQ(); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).on('changed.zf.mediaquery', this._checkMQ.bind(this)); } else { this._events(); } if (tooSmall !== undefined && tooSmall === false || tooSmall === undefined) { if (imgs.length) { __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__foundation_util_imageLoader__["a" /* onImagesLoaded */])(imgs, this._reflow.bind(this)); } else { this._reflow(); } } } /** * Removes event listeners if the breakpoint is too small. * @private */ }, { key: '_pauseEvents', value: function _pauseEvents() { this.isOn = false; this.$element.off({ '.zf.equalizer': this._bindHandler.onPostEqualizedBound, 'resizeme.zf.trigger': this._bindHandler.onResizeMeBound, 'mutateme.zf.trigger': this._bindHandler.onResizeMeBound }); } /** * function to handle $elements resizeme.zf.trigger, with bound this on _bindHandler.onResizeMeBound * @private */ }, { key: '_onResizeMe', value: function _onResizeMe(e) { this._reflow(); } /** * function to handle $elements postequalized.zf.equalizer, with bound this on _bindHandler.onPostEqualizedBound * @private */ }, { key: '_onPostEqualized', value: function _onPostEqualized(e) { if (e.target !== this.$element[0]) { this._reflow(); } } /** * Initializes events for Equalizer. * @private */ }, { key: '_events', value: function _events() { var _this = this; this._pauseEvents(); if (this.hasNested) { this.$element.on('postequalized.zf.equalizer', this._bindHandler.onPostEqualizedBound); } else { this.$element.on('resizeme.zf.trigger', this._bindHandler.onResizeMeBound); this.$element.on('mutateme.zf.trigger', this._bindHandler.onResizeMeBound); } this.isOn = true; } /** * Checks the current breakpoint to the minimum required size. * @private */ }, { key: '_checkMQ', value: function _checkMQ() { var tooSmall = !__WEBPACK_IMPORTED_MODULE_1__foundation_util_mediaQuery__["a" /* MediaQuery */].is(this.options.equalizeOn); if (tooSmall) { if (this.isOn) { this._pauseEvents(); this.$watched.css('height', 'auto'); } } else { if (!this.isOn) { this._events(); } } return tooSmall; } /** * A noop version for the plugin * @private */ }, { key: '_killswitch', value: function _killswitch() { return; } /** * Calls necessary functions to update Equalizer upon DOM change * @private */ }, { key: '_reflow', value: function _reflow() { if (!this.options.equalizeOnStack) { if (this._isStacked()) { this.$watched.css('height', 'auto'); return false; } } if (this.options.equalizeByRow) { this.getHeightsByRow(this.applyHeightByRow.bind(this)); } else { this.getHeights(this.applyHeight.bind(this)); } } /** * Manually determines if the first 2 elements are *NOT* stacked. * @private */ }, { key: '_isStacked', value: function _isStacked() { if (!this.$watched[0] || !this.$watched[1]) { return true; } return this.$watched[0].getBoundingClientRect().top !== this.$watched[1].getBoundingClientRect().top; } /** * Finds the outer heights of children contained within an Equalizer parent and returns them in an array * @param {Function} cb - A non-optional callback to return the heights array to. * @returns {Array} heights - An array of heights of children within Equalizer container */ }, { key: 'getHeights', value: function getHeights(cb) { var heights = []; for (var i = 0, len = this.$watched.length; i < len; i++) { this.$watched[i].style.height = 'auto'; heights.push(this.$watched[i].offsetHeight); } cb(heights); } /** * Finds the outer heights of children contained within an Equalizer parent and returns them in an array * @param {Function} cb - A non-optional callback to return the heights array to. * @returns {Array} groups - An array of heights of children within Equalizer container grouped by row with element,height and max as last child */ }, { key: 'getHeightsByRow', value: function getHeightsByRow(cb) { var lastElTopOffset = this.$watched.length ? this.$watched.first().offset().top : 0, groups = [], group = 0; //group by Row groups[group] = []; for (var i = 0, len = this.$watched.length; i < len; i++) { this.$watched[i].style.height = 'auto'; //maybe could use this.$watched[i].offsetTop var elOffsetTop = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this.$watched[i]).offset().top; if (elOffsetTop != lastElTopOffset) { group++; groups[group] = []; lastElTopOffset = elOffsetTop; } groups[group].push([this.$watched[i], this.$watched[i].offsetHeight]); } for (var j = 0, ln = groups.length; j < ln; j++) { var heights = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(groups[j]).map(function () { return this[1]; }).get(); var max = Math.max.apply(null, heights); groups[j].push(max); } cb(groups); } /** * Changes the CSS height property of each child in an Equalizer parent to match the tallest * @param {array} heights - An array of heights of children within Equalizer container * @fires Equalizer#preequalized * @fires Equalizer#postequalized */ }, { key: 'applyHeight', value: function applyHeight(heights) { var max = Math.max.apply(null, heights); /** * Fires before the heights are applied * @event Equalizer#preequalized */ this.$element.trigger('preequalized.zf.equalizer'); this.$watched.css('height', max); /** * Fires when the heights have been applied * @event Equalizer#postequalized */ this.$element.trigger('postequalized.zf.equalizer'); } /** * Changes the CSS height property of each child in an Equalizer parent to match the tallest by row * @param {array} groups - An array of heights of children within Equalizer container grouped by row with element,height and max as last child * @fires Equalizer#preequalized * @fires Equalizer#preequalizedrow * @fires Equalizer#postequalizedrow * @fires Equalizer#postequalized */ }, { key: 'applyHeightByRow', value: function applyHeightByRow(groups) { /** * Fires before the heights are applied */ this.$element.trigger('preequalized.zf.equalizer'); for (var i = 0, len = groups.length; i < len; i++) { var groupsILength = groups[i].length, max = groups[i][groupsILength - 1]; if (groupsILength <= 2) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(groups[i][0][0]).css({ 'height': 'auto' }); continue; } /** * Fires before the heights per row are applied * @event Equalizer#preequalizedrow */ this.$element.trigger('preequalizedrow.zf.equalizer'); for (var j = 0, lenJ = groupsILength - 1; j < lenJ; j++) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(groups[i][j][0]).css({ 'height': max }); } /** * Fires when the heights per row have been applied * @event Equalizer#postequalizedrow */ this.$element.trigger('postequalizedrow.zf.equalizer'); } /** * Fires when the heights have been applied */ this.$element.trigger('postequalized.zf.equalizer'); } /** * Destroys an instance of Equalizer. * @function */ }, { key: '_destroy', value: function _destroy() { this._pauseEvents(); this.$watched.css('height', 'auto'); } }]); return Equalizer; }(__WEBPACK_IMPORTED_MODULE_4__foundation_plugin__["a" /* Plugin */]); /** * Default settings for plugin */ Equalizer.defaults = { /** * Enable height equalization when stacked on smaller screens. * @option * @type {boolean} * @default false */ equalizeOnStack: false, /** * Enable height equalization row by row. * @option * @type {boolean} * @default false */ equalizeByRow: false, /** * String representing the minimum breakpoint size the plugin should equalize heights on. * @option * @type {string} * @default '' */ equalizeOn: '' }; /***/ }), /* 21 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Interchange; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_mediaQuery__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_plugin__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_util_core__ = __webpack_require__(1); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Interchange module. * @module foundation.interchange * @requires foundation.util.mediaQuery */ var Interchange = function (_Plugin) { _inherits(Interchange, _Plugin); function Interchange() { _classCallCheck(this, Interchange); return _possibleConstructorReturn(this, (Interchange.__proto__ || Object.getPrototypeOf(Interchange)).apply(this, arguments)); } _createClass(Interchange, [{ key: '_setup', /** * Creates a new instance of Interchange. * @class * @fires Interchange#init * @param {Object} element - jQuery object to add the trigger to. * @param {Object} options - Overrides to the default plugin settings. */ value: function _setup(element, options) { this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Interchange.defaults, options); this.rules = []; this.currentPath = ''; this.className = 'Interchange'; // ie9 back compat this._init(); this._events(); } /** * Initializes the Interchange plugin and calls functions to get interchange functioning on load. * @function * @private */ }, { key: '_init', value: function _init() { __WEBPACK_IMPORTED_MODULE_1__foundation_util_mediaQuery__["a" /* MediaQuery */]._init(); var id = this.$element[0].id || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__["a" /* GetYoDigits */])(6, 'interchange'); this.$element.attr({ 'data-resize': id, 'id': id }); this._addBreakpoints(); this._generateRules(); this._reflow(); } /** * Initializes events for Interchange. * @function * @private */ }, { key: '_events', value: function _events() { var _this3 = this; this.$element.off('resizeme.zf.trigger').on('resizeme.zf.trigger', function () { return _this3._reflow(); }); } /** * Calls necessary functions to update Interchange upon DOM change * @function * @private */ }, { key: '_reflow', value: function _reflow() { var match; // Iterate through each rule, but only save the last match for (var i in this.rules) { if (this.rules.hasOwnProperty(i)) { var rule = this.rules[i]; if (window.matchMedia(rule.query).matches) { match = rule; } } } if (match) { this.replace(match.path); } } /** * Gets the Foundation breakpoints and adds them to the Interchange.SPECIAL_QUERIES object. * @function * @private */ }, { key: '_addBreakpoints', value: function _addBreakpoints() { for (var i in __WEBPACK_IMPORTED_MODULE_1__foundation_util_mediaQuery__["a" /* MediaQuery */].queries) { if (__WEBPACK_IMPORTED_MODULE_1__foundation_util_mediaQuery__["a" /* MediaQuery */].queries.hasOwnProperty(i)) { var query = __WEBPACK_IMPORTED_MODULE_1__foundation_util_mediaQuery__["a" /* MediaQuery */].queries[i]; Interchange.SPECIAL_QUERIES[query.name] = query.value; } } } /** * Checks the Interchange element for the provided media query + content pairings * @function * @private * @param {Object} element - jQuery object that is an Interchange instance * @returns {Array} scenarios - Array of objects that have 'mq' and 'path' keys with corresponding keys */ }, { key: '_generateRules', value: function _generateRules(element) { var rulesList = []; var rules; if (this.options.rules) { rules = this.options.rules; } else { rules = this.$element.data('interchange'); } rules = typeof rules === 'string' ? rules.match(/\[.*?\]/g) : rules; for (var i in rules) { if (rules.hasOwnProperty(i)) { var rule = rules[i].slice(1, -1).split(', '); var path = rule.slice(0, -1).join(''); var query = rule[rule.length - 1]; if (Interchange.SPECIAL_QUERIES[query]) { query = Interchange.SPECIAL_QUERIES[query]; } rulesList.push({ path: path, query: query }); } } this.rules = rulesList; } /** * Update the `src` property of an image, or change the HTML of a container, to the specified path. * @function * @param {String} path - Path to the image or HTML partial. * @fires Interchange#replaced */ }, { key: 'replace', value: function replace(path) { if (this.currentPath === path) return; var _this = this, trigger = 'replaced.zf.interchange'; // Replacing images if (this.$element[0].nodeName === 'IMG') { this.$element.attr('src', path).on('load', function () { _this.currentPath = path; }).trigger(trigger); } // Replacing background images else if (path.match(/\.(gif|jpg|jpeg|png|svg|tiff)([?#].*)?/i)) { this.$element.css({ 'background-image': 'url(' + path + ')' }).trigger(trigger); } // Replacing HTML else { __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.get(path, function (response) { _this.$element.html(response).trigger(trigger); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(response).foundation(); _this.currentPath = path; }); } /** * Fires when content in an Interchange element is done being loaded. * @event Interchange#replaced */ // this.$element.trigger('replaced.zf.interchange'); } /** * Destroys an instance of interchange. * @function */ }, { key: '_destroy', value: function _destroy() { this.$element.off('resizeme.zf.trigger'); } }]); return Interchange; }(__WEBPACK_IMPORTED_MODULE_2__foundation_plugin__["a" /* Plugin */]); /** * Default settings for plugin */ Interchange.defaults = { /** * Rules to be applied to Interchange elements. Set with the `data-interchange` array notation. * @option * @type {?array} * @default null */ rules: null }; Interchange.SPECIAL_QUERIES = { 'landscape': 'screen and (orientation: landscape)', 'portrait': 'screen and (orientation: portrait)', 'retina': 'only screen and (-webkit-min-device-pixel-ratio: 2), only screen and (min--moz-device-pixel-ratio: 2), only screen and (-o-min-device-pixel-ratio: 2/1), only screen and (min-device-pixel-ratio: 2), only screen and (min-resolution: 192dpi), only screen and (min-resolution: 2dppx)' }; /***/ }), /* 22 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Magellan; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_plugin__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_smoothScroll__ = __webpack_require__(33); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Magellan module. * @module foundation.magellan * @requires foundation.smoothScroll */ var Magellan = function (_Plugin) { _inherits(Magellan, _Plugin); function Magellan() { _classCallCheck(this, Magellan); return _possibleConstructorReturn(this, (Magellan.__proto__ || Object.getPrototypeOf(Magellan)).apply(this, arguments)); } _createClass(Magellan, [{ key: '_setup', /** * Creates a new instance of Magellan. * @class * @fires Magellan#init * @param {Object} element - jQuery object to add the trigger to. * @param {Object} options - Overrides to the default plugin settings. */ value: function _setup(element, options) { this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Magellan.defaults, this.$element.data(), options); this.className = 'Magellan'; // ie9 back compat this._init(); this.calcPoints(); } /** * Initializes the Magellan plugin and calls functions to get equalizer functioning on load. * @private */ }, { key: '_init', value: function _init() { var id = this.$element[0].id || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__foundation_util_core__["a" /* GetYoDigits */])(6, 'magellan'); var _this = this; this.$targets = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-magellan-target]'); this.$links = this.$element.find('a'); this.$element.attr({ 'data-resize': id, 'data-scroll': id, 'id': id }); this.$active = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(); this.scrollPos = parseInt(window.pageYOffset, 10); this._events(); } /** * Calculates an array of pixel values that are the demarcation lines between locations on the page. * Can be invoked if new elements are added or the size of a location changes. * @function */ }, { key: 'calcPoints', value: function calcPoints() { var _this = this, body = document.body, html = document.documentElement; this.points = []; this.winHeight = Math.round(Math.max(window.innerHeight, html.clientHeight)); this.docHeight = Math.round(Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight)); this.$targets.each(function () { var $tar = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), pt = Math.round($tar.offset().top - _this.options.threshold); $tar.targetPoint = pt; _this.points.push(pt); }); } /** * Initializes events for Magellan. * @private */ }, { key: '_events', value: function _events() { var _this = this, $body = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('html, body'), opts = { duration: _this.options.animationDuration, easing: _this.options.animationEasing }; __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).one('load', function () { if (_this.options.deepLinking) { if (location.hash) { _this.scrollToLoc(location.hash); } } _this.calcPoints(); _this._updateActive(); }); this.$element.on({ 'resizeme.zf.trigger': this.reflow.bind(this), 'scrollme.zf.trigger': this._updateActive.bind(this) }).on('click.zf.magellan', 'a[href^="#"]', function (e) { e.preventDefault(); var arrival = this.getAttribute('href'); _this.scrollToLoc(arrival); }); this._deepLinkScroll = function (e) { if (_this.options.deepLinking) { _this.scrollToLoc(window.location.hash); } }; __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).on('popstate', this._deepLinkScroll); } /** * Function to scroll to a given location on the page. * @param {String} loc - a properly formatted jQuery id selector. Example: '#foo' * @function */ }, { key: 'scrollToLoc', value: function scrollToLoc(loc) { this._inTransition = true; var _this = this; var options = { animationEasing: this.options.animationEasing, animationDuration: this.options.animationDuration, threshold: this.options.threshold, offset: this.options.offset }; __WEBPACK_IMPORTED_MODULE_3__foundation_smoothScroll__["a" /* SmoothScroll */].scrollToLoc(loc, options, function () { _this._inTransition = false; _this._updateActive(); }); } /** * Calls necessary functions to update Magellan upon DOM change * @function */ }, { key: 'reflow', value: function reflow() { this.calcPoints(); this._updateActive(); } /** * Updates the visibility of an active location link, and updates the url hash for the page, if deepLinking enabled. * @private * @function * @fires Magellan#update */ }, { key: '_updateActive', value: function _updateActive() /*evt, elem, scrollPos*/{ if (this._inTransition) { return; } var winPos = /*scrollPos ||*/parseInt(window.pageYOffset, 10), curIdx; if (winPos + this.winHeight === this.docHeight) { curIdx = this.points.length - 1; } else if (winPos < this.points[0]) { curIdx = undefined; } else { var isDown = this.scrollPos < winPos, _this = this, curVisible = this.points.filter(function (p, i) { return isDown ? p - _this.options.offset <= winPos : p - _this.options.offset - _this.options.threshold <= winPos; }); curIdx = curVisible.length ? curVisible.length - 1 : 0; } this.$active.removeClass(this.options.activeClass); this.$active = this.$links.filter('[href="#' + this.$targets.eq(curIdx).data('magellan-target') + '"]').addClass(this.options.activeClass); if (this.options.deepLinking) { var hash = ""; if (curIdx != undefined) { hash = this.$active[0].getAttribute('href'); } if (hash !== window.location.hash) { if (window.history.pushState) { window.history.pushState(null, null, hash); } else { window.location.hash = hash; } } } this.scrollPos = winPos; /** * Fires when magellan is finished updating to the new active element. * @event Magellan#update */ this.$element.trigger('update.zf.magellan', [this.$active]); } /** * Destroys an instance of Magellan and resets the url of the window. * @function */ }, { key: '_destroy', value: function _destroy() { this.$element.off('.zf.trigger .zf.magellan').find('.' + this.options.activeClass).removeClass(this.options.activeClass); if (this.options.deepLinking) { var hash = this.$active[0].getAttribute('href'); window.location.hash.replace(hash, ''); } __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off('popstate', this._deepLinkScroll); } }]); return Magellan; }(__WEBPACK_IMPORTED_MODULE_2__foundation_plugin__["a" /* Plugin */]); /** * Default settings for plugin */ Magellan.defaults = { /** * Amount of time, in ms, the animated scrolling should take between locations. * @option * @type {number} * @default 500 */ animationDuration: 500, /** * Animation style to use when scrolling between locations. Can be `'swing'` or `'linear'`. * @option * @type {string} * @default 'linear' * @see {@link https://api.jquery.com/animate|Jquery animate} */ animationEasing: 'linear', /** * Number of pixels to use as a marker for location changes. * @option * @type {number} * @default 50 */ threshold: 50, /** * Class applied to the active locations link on the magellan container. * @option * @type {string} * @default 'is-active' */ activeClass: 'is-active', /** * Allows the script to manipulate the url of the current page, and if supported, alter the history. * @option * @type {boolean} * @default false */ deepLinking: false, /** * Number of pixels to offset the scroll of the page on item click if using a sticky nav bar. * @option * @type {number} * @default 0 */ offset: 0 }; /***/ }), /* 23 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return OffCanvas; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_util_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__foundation_plugin__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__foundation_util_triggers__ = __webpack_require__(5); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * OffCanvas module. * @module foundation.offcanvas * @requires foundation.util.keyboard * @requires foundation.util.mediaQuery * @requires foundation.util.triggers */ var OffCanvas = function (_Plugin) { _inherits(OffCanvas, _Plugin); function OffCanvas() { _classCallCheck(this, OffCanvas); return _possibleConstructorReturn(this, (OffCanvas.__proto__ || Object.getPrototypeOf(OffCanvas)).apply(this, arguments)); } _createClass(OffCanvas, [{ key: '_setup', /** * Creates a new instance of an off-canvas wrapper. * @class * @fires OffCanvas#init * @param {Object} element - jQuery object to initialize. * @param {Object} options - Overrides to the default plugin settings. */ value: function _setup(element, options) { var _this3 = this; this.className = 'OffCanvas'; // ie9 back compat this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, OffCanvas.defaults, this.$element.data(), options); this.contentClasses = { base: [], reveal: [] }; this.$lastTrigger = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(); this.$triggers = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(); this.position = 'left'; this.$content = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(); this.nested = !!this.options.nested; // Defines the CSS transition/position classes of the off-canvas content container. __WEBPACK_IMPORTED_MODULE_0_jquery___default()(['push', 'overlap']).each(function (index, val) { _this3.contentClasses.base.push('has-transition-' + val); }); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(['left', 'right', 'top', 'bottom']).each(function (index, val) { _this3.contentClasses.base.push('has-position-' + val); _this3.contentClasses.reveal.push('has-reveal-' + val); }); // Triggers init is idempotent, just need to make sure it is initialized __WEBPACK_IMPORTED_MODULE_5__foundation_util_triggers__["a" /* Triggers */].init(__WEBPACK_IMPORTED_MODULE_0_jquery___default.a); __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__["a" /* MediaQuery */]._init(); this._init(); this._events(); __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].register('OffCanvas', { 'ESCAPE': 'close' }); } /** * Initializes the off-canvas wrapper by adding the exit overlay (if needed). * @function * @private */ }, { key: '_init', value: function _init() { var id = this.$element.attr('id'); this.$element.attr('aria-hidden', 'true'); // Find off-canvas content, either by ID (if specified), by siblings or by closest selector (fallback) if (this.options.contentId) { this.$content = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + this.options.contentId); } else if (this.$element.siblings('[data-off-canvas-content]').length) { this.$content = this.$element.siblings('[data-off-canvas-content]').first(); } else { this.$content = this.$element.closest('[data-off-canvas-content]').first(); } if (!this.options.contentId) { // Assume that the off-canvas element is nested if it isn't a sibling of the content this.nested = this.$element.siblings('[data-off-canvas-content]').length === 0; } else if (this.options.contentId && this.options.nested === null) { // Warning if using content ID without setting the nested option // Once the element is nested it is required to work properly in this case console.warn('Remember to use the nested option if using the content ID option!'); } if (this.nested === true) { // Force transition overlap if nested this.options.transition = 'overlap'; // Remove appropriate classes if already assigned in markup this.$element.removeClass('is-transition-push'); } this.$element.addClass('is-transition-' + this.options.transition + ' is-closed'); // Find triggers that affect this element and add aria-expanded to them this.$triggers = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(document).find('[data-open="' + id + '"], [data-close="' + id + '"], [data-toggle="' + id + '"]').attr('aria-expanded', 'false').attr('aria-controls', id); // Get position by checking for related CSS class this.position = this.$element.is('.position-left, .position-top, .position-right, .position-bottom') ? this.$element.attr('class').match(/position\-(left|top|right|bottom)/)[1] : this.position; // Add an overlay over the content if necessary if (this.options.contentOverlay === true) { var overlay = document.createElement('div'); var overlayPosition = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this.$element).css("position") === 'fixed' ? 'is-overlay-fixed' : 'is-overlay-absolute'; overlay.setAttribute('class', 'js-off-canvas-overlay ' + overlayPosition); this.$overlay = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(overlay); if (overlayPosition === 'is-overlay-fixed') { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this.$overlay).insertAfter(this.$element); } else { this.$content.append(this.$overlay); } } this.options.isRevealed = this.options.isRevealed || new RegExp(this.options.revealClass, 'g').test(this.$element[0].className); if (this.options.isRevealed === true) { this.options.revealOn = this.options.revealOn || this.$element[0].className.match(/(reveal-for-medium|reveal-for-large)/g)[0].split('-')[2]; this._setMQChecker(); } if (this.options.transitionTime) { this.$element.css('transition-duration', this.options.transitionTime); } // Initally remove all transition/position CSS classes from off-canvas content container. this._removeContentClasses(); } /** * Adds event handlers to the off-canvas wrapper and the exit overlay. * @function * @private */ }, { key: '_events', value: function _events() { this.$element.off('.zf.trigger .zf.offcanvas').on({ 'open.zf.trigger': this.open.bind(this), 'close.zf.trigger': this.close.bind(this), 'toggle.zf.trigger': this.toggle.bind(this), 'keydown.zf.offcanvas': this._handleKeyboard.bind(this) }); if (this.options.closeOnClick === true) { var $target = this.options.contentOverlay ? this.$overlay : this.$content; $target.on({ 'click.zf.offcanvas': this.close.bind(this) }); } } /** * Applies event listener for elements that will reveal at certain breakpoints. * @private */ }, { key: '_setMQChecker', value: function _setMQChecker() { var _this = this; __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).on('changed.zf.mediaquery', function () { if (__WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__["a" /* MediaQuery */].atLeast(_this.options.revealOn)) { _this.reveal(true); } else { _this.reveal(false); } }).one('load.zf.offcanvas', function () { if (__WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__["a" /* MediaQuery */].atLeast(_this.options.revealOn)) { _this.reveal(true); } }); } /** * Removes the CSS transition/position classes of the off-canvas content container. * Removing the classes is important when another off-canvas gets opened that uses the same content container. * @private */ }, { key: '_removeContentClasses', value: function _removeContentClasses(hasReveal) { this.$content.removeClass(this.contentClasses.base.join(' ')); if (hasReveal === true) { this.$content.removeClass(this.contentClasses.reveal.join(' ')); } } /** * Adds the CSS transition/position classes of the off-canvas content container, based on the opening off-canvas element. * Beforehand any transition/position class gets removed. * @param {Boolean} hasReveal - true if related off-canvas element is revealed. * @private */ }, { key: '_addContentClasses', value: function _addContentClasses(hasReveal) { this._removeContentClasses(); this.$content.addClass('has-transition-' + this.options.transition + ' has-position-' + this.position); if (hasReveal === true) { this.$content.addClass('has-reveal-' + this.position); } } /** * Handles the revealing/hiding the off-canvas at breakpoints, not the same as open. * @param {Boolean} isRevealed - true if element should be revealed. * @function */ }, { key: 'reveal', value: function reveal(isRevealed) { if (isRevealed) { this.close(); this.isRevealed = true; this.$element.attr('aria-hidden', 'false'); this.$element.off('open.zf.trigger toggle.zf.trigger'); this.$element.removeClass('is-closed'); } else { this.isRevealed = false; this.$element.attr('aria-hidden', 'true'); this.$element.off('open.zf.trigger toggle.zf.trigger').on({ 'open.zf.trigger': this.open.bind(this), 'toggle.zf.trigger': this.toggle.bind(this) }); this.$element.addClass('is-closed'); } this._addContentClasses(isRevealed); } /** * Stops scrolling of the body when offcanvas is open on mobile Safari and other troublesome browsers. * @private */ }, { key: '_stopScrolling', value: function _stopScrolling(event) { return false; } // Taken and adapted from http://stackoverflow.com/questions/16889447/prevent-full-page-scrolling-ios // Only really works for y, not sure how to extend to x or if we need to. }, { key: '_recordScrollable', value: function _recordScrollable(event) { var elem = this; // called from event handler context with this as elem // If the element is scrollable (content overflows), then... if (elem.scrollHeight !== elem.clientHeight) { // If we're at the top, scroll down one pixel to allow scrolling up if (elem.scrollTop === 0) { elem.scrollTop = 1; } // If we're at the bottom, scroll up one pixel to allow scrolling down if (elem.scrollTop === elem.scrollHeight - elem.clientHeight) { elem.scrollTop = elem.scrollHeight - elem.clientHeight - 1; } } elem.allowUp = elem.scrollTop > 0; elem.allowDown = elem.scrollTop < elem.scrollHeight - elem.clientHeight; elem.lastY = event.originalEvent.pageY; } }, { key: '_stopScrollPropagation', value: function _stopScrollPropagation(event) { var elem = this; // called from event handler context with this as elem var up = event.pageY < elem.lastY; var down = !up; elem.lastY = event.pageY; if (up && elem.allowUp || down && elem.allowDown) { event.stopPropagation(); } else { event.preventDefault(); } } /** * Opens the off-canvas menu. * @function * @param {Object} event - Event object passed from listener. * @param {jQuery} trigger - element that triggered the off-canvas to open. * @fires OffCanvas#opened */ }, { key: 'open', value: function open(event, trigger) { if (this.$element.hasClass('is-open') || this.isRevealed) { return; } var _this = this; if (trigger) { this.$lastTrigger = trigger; } if (this.options.forceTo === 'top') { window.scrollTo(0, 0); } else if (this.options.forceTo === 'bottom') { window.scrollTo(0, document.body.scrollHeight); } if (this.options.transitionTime && this.options.transition !== 'overlap') { this.$element.siblings('[data-off-canvas-content]').css('transition-duration', this.options.transitionTime); } else { this.$element.siblings('[data-off-canvas-content]').css('transition-duration', ''); } /** * Fires when the off-canvas menu opens. * @event OffCanvas#opened */ this.$element.addClass('is-open').removeClass('is-closed'); this.$triggers.attr('aria-expanded', 'true'); this.$element.attr('aria-hidden', 'false').trigger('opened.zf.offcanvas'); this.$content.addClass('is-open-' + this.position); // If `contentScroll` is set to false, add class and disable scrolling on touch devices. if (this.options.contentScroll === false) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()('body').addClass('is-off-canvas-open').on('touchmove', this._stopScrolling); this.$element.on('touchstart', this._recordScrollable); this.$element.on('touchmove', this._stopScrollPropagation); } if (this.options.contentOverlay === true) { this.$overlay.addClass('is-visible'); } if (this.options.closeOnClick === true && this.options.contentOverlay === true) { this.$overlay.addClass('is-closable'); } if (this.options.autoFocus === true) { this.$element.one(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__["c" /* transitionend */])(this.$element), function () { if (!_this.$element.hasClass('is-open')) { return; // exit if prematurely closed } var canvasFocus = _this.$element.find('[data-autofocus]'); if (canvasFocus.length) { canvasFocus.eq(0).focus(); } else { _this.$element.find('a, button').eq(0).focus(); } }); } if (this.options.trapFocus === true) { this.$content.attr('tabindex', '-1'); __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].trapFocus(this.$element); } this._addContentClasses(); } /** * Closes the off-canvas menu. * @function * @param {Function} cb - optional cb to fire after closure. * @fires OffCanvas#closed */ }, { key: 'close', value: function close(cb) { if (!this.$element.hasClass('is-open') || this.isRevealed) { return; } var _this = this; this.$element.removeClass('is-open'); this.$element.attr('aria-hidden', 'true') /** * Fires when the off-canvas menu opens. * @event OffCanvas#closed */ .trigger('closed.zf.offcanvas'); this.$content.removeClass('is-open-left is-open-top is-open-right is-open-bottom'); // If `contentScroll` is set to false, remove class and re-enable scrolling on touch devices. if (this.options.contentScroll === false) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()('body').removeClass('is-off-canvas-open').off('touchmove', this._stopScrolling); this.$element.off('touchstart', this._recordScrollable); this.$element.off('touchmove', this._stopScrollPropagation); } if (this.options.contentOverlay === true) { this.$overlay.removeClass('is-visible'); } if (this.options.closeOnClick === true && this.options.contentOverlay === true) { this.$overlay.removeClass('is-closable'); } this.$triggers.attr('aria-expanded', 'false'); if (this.options.trapFocus === true) { this.$content.removeAttr('tabindex'); __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].releaseFocus(this.$element); } // Listen to transitionEnd and add class when done. this.$element.one(__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__["c" /* transitionend */])(this.$element), function (e) { _this.$element.addClass('is-closed'); _this._removeContentClasses(); }); } /** * Toggles the off-canvas menu open or closed. * @function * @param {Object} event - Event object passed from listener. * @param {jQuery} trigger - element that triggered the off-canvas to open. */ }, { key: 'toggle', value: function toggle(event, trigger) { if (this.$element.hasClass('is-open')) { this.close(event, trigger); } else { this.open(event, trigger); } } /** * Handles keyboard input when detected. When the escape key is pressed, the off-canvas menu closes, and focus is restored to the element that opened the menu. * @function * @private */ }, { key: '_handleKeyboard', value: function _handleKeyboard(e) { var _this4 = this; __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].handleKey(e, 'OffCanvas', { close: function () { _this4.close(); _this4.$lastTrigger.focus(); return true; }, handled: function () { e.stopPropagation(); e.preventDefault(); } }); } /** * Destroys the offcanvas plugin. * @function */ }, { key: '_destroy', value: function _destroy() { this.close(); this.$element.off('.zf.trigger .zf.offcanvas'); this.$overlay.off('.zf.offcanvas'); } }]); return OffCanvas; }(__WEBPACK_IMPORTED_MODULE_4__foundation_plugin__["a" /* Plugin */]); OffCanvas.defaults = { /** * Allow the user to click outside of the menu to close it. * @option * @type {boolean} * @default true */ closeOnClick: true, /** * Adds an overlay on top of `[data-off-canvas-content]`. * @option * @type {boolean} * @default true */ contentOverlay: true, /** * Target an off-canvas content container by ID that may be placed anywhere. If null the closest content container will be taken. * @option * @type {?string} * @default null */ contentId: null, /** * Define the off-canvas element is nested in an off-canvas content. This is required when using the contentId option for a nested element. * @option * @type {boolean} * @default null */ nested: null, /** * Enable/disable scrolling of the main content when an off canvas panel is open. * @option * @type {boolean} * @default true */ contentScroll: true, /** * Amount of time in ms the open and close transition requires. If none selected, pulls from body style. * @option * @type {number} * @default null */ transitionTime: null, /** * Type of transition for the offcanvas menu. Options are 'push', 'detached' or 'slide'. * @option * @type {string} * @default push */ transition: 'push', /** * Force the page to scroll to top or bottom on open. * @option * @type {?string} * @default null */ forceTo: null, /** * Allow the offcanvas to remain open for certain breakpoints. * @option * @type {boolean} * @default false */ isRevealed: false, /** * Breakpoint at which to reveal. JS will use a RegExp to target standard classes, if changing classnames, pass your class with the `revealClass` option. * @option * @type {?string} * @default null */ revealOn: null, /** * Force focus to the offcanvas on open. If true, will focus the opening trigger on close. * @option * @type {boolean} * @default true */ autoFocus: true, /** * Class used to force an offcanvas to remain open. Foundation defaults for this are `reveal-for-large` & `reveal-for-medium`. * @option * @type {string} * @default reveal-for- * @todo improve the regex testing for this. */ revealClass: 'reveal-for-', /** * Triggers optional focus trapping when opening an offcanvas. Sets tabindex of [data-off-canvas-content] to -1 for accessibility purposes. * @option * @type {boolean} * @default false */ trapFocus: false }; /***/ }), /* 24 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Orbit; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_motion__ = __webpack_require__(6); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_util_timer__ = __webpack_require__(34); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__foundation_util_imageLoader__ = __webpack_require__(8); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__foundation_util_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__foundation_plugin__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__foundation_util_touch__ = __webpack_require__(16); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Orbit module. * @module foundation.orbit * @requires foundation.util.keyboard * @requires foundation.util.motion * @requires foundation.util.timer * @requires foundation.util.imageLoader * @requires foundation.util.touch */ var Orbit = function (_Plugin) { _inherits(Orbit, _Plugin); function Orbit() { _classCallCheck(this, Orbit); return _possibleConstructorReturn(this, (Orbit.__proto__ || Object.getPrototypeOf(Orbit)).apply(this, arguments)); } _createClass(Orbit, [{ key: '_setup', /** * Creates a new instance of an orbit carousel. * @class * @param {jQuery} element - jQuery object to make into an Orbit Carousel. * @param {Object} options - Overrides to the default plugin settings. */ value: function _setup(element, options) { this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Orbit.defaults, this.$element.data(), options); this.className = 'Orbit'; // ie9 back compat __WEBPACK_IMPORTED_MODULE_7__foundation_util_touch__["a" /* Touch */].init(__WEBPACK_IMPORTED_MODULE_0_jquery___default.a); // Touch init is idempotent, we just need to make sure it's initialied. this._init(); __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].register('Orbit', { 'ltr': { 'ARROW_RIGHT': 'next', 'ARROW_LEFT': 'previous' }, 'rtl': { 'ARROW_LEFT': 'next', 'ARROW_RIGHT': 'previous' } }); } /** * Initializes the plugin by creating jQuery collections, setting attributes, and starting the animation. * @function * @private */ }, { key: '_init', value: function _init() { // @TODO: consider discussion on PR #9278 about DOM pollution by changeSlide this._reset(); this.$wrapper = this.$element.find('.' + this.options.containerClass); this.$slides = this.$element.find('.' + this.options.slideClass); var $images = this.$element.find('img'), initActive = this.$slides.filter('.is-active'), id = this.$element[0].id || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_5__foundation_util_core__["a" /* GetYoDigits */])(6, 'orbit'); this.$element.attr({ 'data-resize': id, 'id': id }); if (!initActive.length) { this.$slides.eq(0).addClass('is-active'); } if (!this.options.useMUI) { this.$slides.addClass('no-motionui'); } if ($images.length) { __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_4__foundation_util_imageLoader__["a" /* onImagesLoaded */])($images, this._prepareForOrbit.bind(this)); } else { this._prepareForOrbit(); //hehe } if (this.options.bullets) { this._loadBullets(); } this._events(); if (this.options.autoPlay && this.$slides.length > 1) { this.geoSync(); } if (this.options.accessible) { // allow wrapper to be focusable to enable arrow navigation this.$wrapper.attr('tabindex', 0); } } /** * Creates a jQuery collection of bullets, if they are being used. * @function * @private */ }, { key: '_loadBullets', value: function _loadBullets() { this.$bullets = this.$element.find('.' + this.options.boxOfBullets).find('button'); } /** * Sets a `timer` object on the orbit, and starts the counter for the next slide. * @function */ }, { key: 'geoSync', value: function geoSync() { var _this = this; this.timer = new __WEBPACK_IMPORTED_MODULE_3__foundation_util_timer__["a" /* Timer */](this.$element, { duration: this.options.timerDelay, infinite: false }, function () { _this.changeSlide(true); }); this.timer.start(); } /** * Sets wrapper and slide heights for the orbit. * @function * @private */ }, { key: '_prepareForOrbit', value: function _prepareForOrbit() { var _this = this; this._setWrapperHeight(); } /** * Calulates the height of each slide in the collection, and uses the tallest one for the wrapper height. * @function * @private * @param {Function} cb - a callback function to fire when complete. */ }, { key: '_setWrapperHeight', value: function _setWrapperHeight(cb) { //rewrite this to `for` loop var max = 0, temp, counter = 0, _this = this; this.$slides.each(function () { temp = this.getBoundingClientRect().height; __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).attr('data-slide', counter); if (_this.$slides.filter('.is-active')[0] !== _this.$slides.eq(counter)[0]) { //if not the active slide, set css position and display property __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).css({ 'position': 'relative', 'display': 'none' }); } max = temp > max ? temp : max; counter++; }); if (counter === this.$slides.length) { this.$wrapper.css({ 'height': max }); //only change the wrapper height property once. if (cb) { cb(max); } //fire callback with max height dimension. } } /** * Sets the max-height of each slide. * @function * @private */ }, { key: '_setSlideHeight', value: function _setSlideHeight(height) { this.$slides.each(function () { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).css('max-height', height); }); } /** * Adds event listeners to basically everything within the element. * @function * @private */ }, { key: '_events', value: function _events() { var _this = this; //*************************************** //**Now using custom event - thanks to:** //** Yohai Ararat of Toronto ** //*************************************** // this.$element.off('.resizeme.zf.trigger').on({ 'resizeme.zf.trigger': this._prepareForOrbit.bind(this) }); if (this.$slides.length > 1) { if (this.options.swipe) { this.$slides.off('swipeleft.zf.orbit swiperight.zf.orbit').on('swipeleft.zf.orbit', function (e) { e.preventDefault(); _this.changeSlide(true); }).on('swiperight.zf.orbit', function (e) { e.preventDefault(); _this.changeSlide(false); }); } //*************************************** if (this.options.autoPlay) { this.$slides.on('click.zf.orbit', function () { _this.$element.data('clickedOn', _this.$element.data('clickedOn') ? false : true); _this.timer[_this.$element.data('clickedOn') ? 'pause' : 'start'](); }); if (this.options.pauseOnHover) { this.$element.on('mouseenter.zf.orbit', function () { _this.timer.pause(); }).on('mouseleave.zf.orbit', function () { if (!_this.$element.data('clickedOn')) { _this.timer.start(); } }); } } if (this.options.navButtons) { var $controls = this.$element.find('.' + this.options.nextClass + ', .' + this.options.prevClass); $controls.attr('tabindex', 0) //also need to handle enter/return and spacebar key presses .on('click.zf.orbit touchend.zf.orbit', function (e) { e.preventDefault(); _this.changeSlide(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).hasClass(_this.options.nextClass)); }); } if (this.options.bullets) { this.$bullets.on('click.zf.orbit touchend.zf.orbit', function () { if (/is-active/g.test(this.className)) { return false; } //if this is active, kick out of function. var idx = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('slide'), ltr = idx > _this.$slides.filter('.is-active').data('slide'), $slide = _this.$slides.eq(idx); _this.changeSlide(ltr, $slide, idx); }); } if (this.options.accessible) { this.$wrapper.add(this.$bullets).on('keydown.zf.orbit', function (e) { // handle keyboard event with keyboard util __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].handleKey(e, 'Orbit', { next: function () { _this.changeSlide(true); }, previous: function () { _this.changeSlide(false); }, handled: function () { // if bullet is focused, make sure focus moves if (__WEBPACK_IMPORTED_MODULE_0_jquery___default()(e.target).is(_this.$bullets)) { _this.$bullets.filter('.is-active').focus(); } } }); }); } } } /** * Resets Orbit so it can be reinitialized */ }, { key: '_reset', value: function _reset() { // Don't do anything if there are no slides (first run) if (typeof this.$slides == 'undefined') { return; } if (this.$slides.length > 1) { // Remove old events this.$element.off('.zf.orbit').find('*').off('.zf.orbit'); // Restart timer if autoPlay is enabled if (this.options.autoPlay) { this.timer.restart(); } // Reset all sliddes this.$slides.each(function (el) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(el).removeClass('is-active is-active is-in').removeAttr('aria-live').hide(); }); // Show the first slide this.$slides.first().addClass('is-active').show(); // Triggers when the slide has finished animating this.$element.trigger('slidechange.zf.orbit', [this.$slides.first()]); // Select first bullet if bullets are present if (this.options.bullets) { this._updateBullets(0); } } } /** * Changes the current slide to a new one. * @function * @param {Boolean} isLTR - flag if the slide should move left to right. * @param {jQuery} chosenSlide - the jQuery element of the slide to show next, if one is selected. * @param {Number} idx - the index of the new slide in its collection, if one chosen. * @fires Orbit#slidechange */ }, { key: 'changeSlide', value: function changeSlide(isLTR, chosenSlide, idx) { if (!this.$slides) { return; } // Don't freak out if we're in the middle of cleanup var $curSlide = this.$slides.filter('.is-active').eq(0); if (/mui/g.test($curSlide[0].className)) { return false; } //if the slide is currently animating, kick out of the function var $firstSlide = this.$slides.first(), $lastSlide = this.$slides.last(), dirIn = isLTR ? 'Right' : 'Left', dirOut = isLTR ? 'Left' : 'Right', _this = this, $newSlide; if (!chosenSlide) { //most of the time, this will be auto played or clicked from the navButtons. $newSlide = isLTR ? //if wrapping enabled, check to see if there is a `next` or `prev` sibling, if not, select the first or last slide to fill in. if wrapping not enabled, attempt to select `next` or `prev`, if there's nothing there, the function will kick out on next step. CRAZY NESTED TERNARIES!!!!! this.options.infiniteWrap ? $curSlide.next('.' + this.options.slideClass).length ? $curSlide.next('.' + this.options.slideClass) : $firstSlide : $curSlide.next('.' + this.options.slideClass) : //pick next slide if moving left to right this.options.infiniteWrap ? $curSlide.prev('.' + this.options.slideClass).length ? $curSlide.prev('.' + this.options.slideClass) : $lastSlide : $curSlide.prev('.' + this.options.slideClass); //pick prev slide if moving right to left } else { $newSlide = chosenSlide; } if ($newSlide.length) { /** * Triggers before the next slide starts animating in and only if a next slide has been found. * @event Orbit#beforeslidechange */ this.$element.trigger('beforeslidechange.zf.orbit', [$curSlide, $newSlide]); if (this.options.bullets) { idx = idx || this.$slides.index($newSlide); //grab index to update bullets this._updateBullets(idx); } if (this.options.useMUI && !this.$element.is(':hidden')) { __WEBPACK_IMPORTED_MODULE_2__foundation_util_motion__["a" /* Motion */].animateIn($newSlide.addClass('is-active').css({ 'position': 'absolute', 'top': 0 }), this.options['animInFrom' + dirIn], function () { $newSlide.css({ 'position': 'relative', 'display': 'block' }).attr('aria-live', 'polite'); }); __WEBPACK_IMPORTED_MODULE_2__foundation_util_motion__["a" /* Motion */].animateOut($curSlide.removeClass('is-active'), this.options['animOutTo' + dirOut], function () { $curSlide.removeAttr('aria-live'); if (_this.options.autoPlay && !_this.timer.isPaused) { _this.timer.restart(); } //do stuff? }); } else { $curSlide.removeClass('is-active is-in').removeAttr('aria-live').hide(); $newSlide.addClass('is-active is-in').attr('aria-live', 'polite').show(); if (this.options.autoPlay && !this.timer.isPaused) { this.timer.restart(); } } /** * Triggers when the slide has finished animating in. * @event Orbit#slidechange */ this.$element.trigger('slidechange.zf.orbit', [$newSlide]); } } /** * Updates the active state of the bullets, if displayed. * @function * @private * @param {Number} idx - the index of the current slide. */ }, { key: '_updateBullets', value: function _updateBullets(idx) { var $oldBullet = this.$element.find('.' + this.options.boxOfBullets).find('.is-active').removeClass('is-active').blur(), span = $oldBullet.find('span:last').detach(), $newBullet = this.$bullets.eq(idx).addClass('is-active').append(span); } /** * Destroys the carousel and hides the element. * @function */ }, { key: '_destroy', value: function _destroy() { this.$element.off('.zf.orbit').find('*').off('.zf.orbit').end().hide(); } }]); return Orbit; }(__WEBPACK_IMPORTED_MODULE_6__foundation_plugin__["a" /* Plugin */]); Orbit.defaults = { /** * Tells the JS to look for and loadBullets. * @option * @type {boolean} * @default true */ bullets: true, /** * Tells the JS to apply event listeners to nav buttons * @option * @type {boolean} * @default true */ navButtons: true, /** * motion-ui animation class to apply * @option * @type {string} * @default 'slide-in-right' */ animInFromRight: 'slide-in-right', /** * motion-ui animation class to apply * @option * @type {string} * @default 'slide-out-right' */ animOutToRight: 'slide-out-right', /** * motion-ui animation class to apply * @option * @type {string} * @default 'slide-in-left' * */ animInFromLeft: 'slide-in-left', /** * motion-ui animation class to apply * @option * @type {string} * @default 'slide-out-left' */ animOutToLeft: 'slide-out-left', /** * Allows Orbit to automatically animate on page load. * @option * @type {boolean} * @default true */ autoPlay: true, /** * Amount of time, in ms, between slide transitions * @option * @type {number} * @default 5000 */ timerDelay: 5000, /** * Allows Orbit to infinitely loop through the slides * @option * @type {boolean} * @default true */ infiniteWrap: true, /** * Allows the Orbit slides to bind to swipe events for mobile, requires an additional util library * @option * @type {boolean} * @default true */ swipe: true, /** * Allows the timing function to pause animation on hover. * @option * @type {boolean} * @default true */ pauseOnHover: true, /** * Allows Orbit to bind keyboard events to the slider, to animate frames with arrow keys * @option * @type {boolean} * @default true */ accessible: true, /** * Class applied to the container of Orbit * @option * @type {string} * @default 'orbit-container' */ containerClass: 'orbit-container', /** * Class applied to individual slides. * @option * @type {string} * @default 'orbit-slide' */ slideClass: 'orbit-slide', /** * Class applied to the bullet container. You're welcome. * @option * @type {string} * @default 'orbit-bullets' */ boxOfBullets: 'orbit-bullets', /** * Class applied to the `next` navigation button. * @option * @type {string} * @default 'orbit-next' */ nextClass: 'orbit-next', /** * Class applied to the `previous` navigation button. * @option * @type {string} * @default 'orbit-previous' */ prevClass: 'orbit-previous', /** * Boolean to flag the js to use motion ui classes or not. Default to true for backwards compatability. * @option * @type {boolean} * @default true */ useMUI: true }; /***/ }), /* 25 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ResponsiveAccordionTabs; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_mediaQuery__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_plugin__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__foundation_accordion__ = __webpack_require__(10); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__foundation_tabs__ = __webpack_require__(14); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } // The plugin matches the plugin classes with these plugin instances. var MenuPlugins = { tabs: { cssClass: 'tabs', plugin: __WEBPACK_IMPORTED_MODULE_5__foundation_tabs__["a" /* Tabs */] }, accordion: { cssClass: 'accordion', plugin: __WEBPACK_IMPORTED_MODULE_4__foundation_accordion__["a" /* Accordion */] } }; /** * ResponsiveAccordionTabs module. * @module foundation.responsiveAccordionTabs * @requires foundation.util.motion * @requires foundation.accordion * @requires foundation.tabs */ var ResponsiveAccordionTabs = function (_Plugin) { _inherits(ResponsiveAccordionTabs, _Plugin); function ResponsiveAccordionTabs() { _classCallCheck(this, ResponsiveAccordionTabs); return _possibleConstructorReturn(this, (ResponsiveAccordionTabs.__proto__ || Object.getPrototypeOf(ResponsiveAccordionTabs)).apply(this, arguments)); } _createClass(ResponsiveAccordionTabs, [{ key: '_setup', /** * Creates a new instance of a responsive accordion tabs. * @class * @fires ResponsiveAccordionTabs#init * @param {jQuery} element - jQuery object to make into Responsive Accordion Tabs. * @param {Object} options - Overrides to the default plugin settings. */ value: function _setup(element, options) { this.$element = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(element); this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, this.$element.data(), options); this.rules = this.$element.data('responsive-accordion-tabs'); this.currentMq = null; this.currentPlugin = null; this.className = 'ResponsiveAccordionTabs'; // ie9 back compat if (!this.$element.attr('id')) { this.$element.attr('id', __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__foundation_util_core__["a" /* GetYoDigits */])(6, 'responsiveaccordiontabs')); }; this._init(); this._events(); } /** * Initializes the Menu by parsing the classes from the 'data-responsive-accordion-tabs' attribute on the element. * @function * @private */ }, { key: '_init', value: function _init() { __WEBPACK_IMPORTED_MODULE_1__foundation_util_mediaQuery__["a" /* MediaQuery */]._init(); // The first time an Interchange plugin is initialized, this.rules is converted from a string of "classes" to an object of rules if (typeof this.rules === 'string') { var rulesTree = {}; // Parse rules from "classes" pulled from data attribute var rules = this.rules.split(' '); // Iterate through every rule found for (var i = 0; i < rules.length; i++) { var rule = rules[i].split('-'); var ruleSize = rule.length > 1 ? rule[0] : 'small'; var rulePlugin = rule.length > 1 ? rule[1] : rule[0]; if (MenuPlugins[rulePlugin] !== null) { rulesTree[ruleSize] = MenuPlugins[rulePlugin]; } } this.rules = rulesTree; } this._getAllOptions(); if (!__WEBPACK_IMPORTED_MODULE_0_jquery___default.a.isEmptyObject(this.rules)) { this._checkMediaQueries(); } } }, { key: '_getAllOptions', value: function _getAllOptions() { //get all defaults and options var _this = this; _this.allOptions = {}; for (var key in MenuPlugins) { if (MenuPlugins.hasOwnProperty(key)) { var obj = MenuPlugins[key]; try { var dummyPlugin = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('<ul></ul>'); var tmpPlugin = new obj.plugin(dummyPlugin, _this.options); for (var keyKey in tmpPlugin.options) { if (tmpPlugin.options.hasOwnProperty(keyKey) && keyKey !== 'zfPlugin') { var objObj = tmpPlugin.options[keyKey]; _this.allOptions[keyKey] = objObj; } } tmpPlugin.destroy(); } catch (e) {} } } } /** * Initializes events for the Menu. * @function * @private */ }, { key: '_events', value: function _events() { var _this = this; __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).on('changed.zf.mediaquery', function () { _this._checkMediaQueries(); }); } /** * Checks the current screen width against available media queries. If the media query has changed, and the plugin needed has changed, the plugins will swap out. * @function * @private */ }, { key: '_checkMediaQueries', value: function _checkMediaQueries() { var matchedMq, _this = this; // Iterate through each rule and find the last matching rule __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.each(this.rules, function (key) { if (__WEBPACK_IMPORTED_MODULE_1__foundation_util_mediaQuery__["a" /* MediaQuery */].atLeast(key)) { matchedMq = key; } }); // No match? No dice if (!matchedMq) return; // Plugin already initialized? We good if (this.currentPlugin instanceof this.rules[matchedMq].plugin) return; // Remove existing plugin-specific CSS classes __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.each(MenuPlugins, function (key, value) { _this.$element.removeClass(value.cssClass); }); // Add the CSS class for the new plugin this.$element.addClass(this.rules[matchedMq].cssClass); // Create an instance of the new plugin if (this.currentPlugin) { //don't know why but on nested elements data zfPlugin get's lost if (!this.currentPlugin.$element.data('zfPlugin') && this.storezfData) this.currentPlugin.$element.data('zfPlugin', this.storezfData); this.currentPlugin.destroy(); } this._handleMarkup(this.rules[matchedMq].cssClass); this.currentPlugin = new this.rules[matchedMq].plugin(this.$element, {}); this.storezfData = this.currentPlugin.$element.data('zfPlugin'); } }, { key: '_handleMarkup', value: function _handleMarkup(toSet) { var _this = this, fromString = 'accordion'; var $panels = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-tabs-content=' + this.$element.attr('id') + ']'); if ($panels.length) fromString = 'tabs'; if (fromString === toSet) { return; }; var tabsTitle = _this.allOptions.linkClass ? _this.allOptions.linkClass : 'tabs-title'; var tabsPanel = _this.allOptions.panelClass ? _this.allOptions.panelClass : 'tabs-panel'; this.$element.removeAttr('role'); var $liHeads = this.$element.children('.' + tabsTitle + ',[data-accordion-item]').removeClass(tabsTitle).removeClass('accordion-item').removeAttr('data-accordion-item'); var $liHeadsA = $liHeads.children('a').removeClass('accordion-title'); if (fromString === 'tabs') { $panels = $panels.children('.' + tabsPanel).removeClass(tabsPanel).removeAttr('role').removeAttr('aria-hidden').removeAttr('aria-labelledby'); $panels.children('a').removeAttr('role').removeAttr('aria-controls').removeAttr('aria-selected'); } else { $panels = $liHeads.children('[data-tab-content]').removeClass('accordion-content'); }; $panels.css({ display: '', visibility: '' }); $liHeads.css({ display: '', visibility: '' }); if (toSet === 'accordion') { $panels.each(function (key, value) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(value).appendTo($liHeads.get(key)).addClass('accordion-content').attr('data-tab-content', '').removeClass('is-active').css({ height: '' }); __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-tabs-content=' + _this.$element.attr('id') + ']').after('<div id="tabs-placeholder-' + _this.$element.attr('id') + '"></div>').detach(); $liHeads.addClass('accordion-item').attr('data-accordion-item', ''); $liHeadsA.addClass('accordion-title'); }); } else if (toSet === 'tabs') { var $tabsContent = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-tabs-content=' + _this.$element.attr('id') + ']'); var $placeholder = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#tabs-placeholder-' + _this.$element.attr('id')); if ($placeholder.length) { $tabsContent = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('<div class="tabs-content"></div>').insertAfter($placeholder).attr('data-tabs-content', _this.$element.attr('id')); $placeholder.remove(); } else { $tabsContent = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('<div class="tabs-content"></div>').insertAfter(_this.$element).attr('data-tabs-content', _this.$element.attr('id')); }; $panels.each(function (key, value) { var tempValue = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(value).appendTo($tabsContent).addClass(tabsPanel); var hash = $liHeadsA.get(key).hash.slice(1); var id = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(value).attr('id') || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__foundation_util_core__["a" /* GetYoDigits */])(6, 'accordion'); if (hash !== id) { if (hash !== '') { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(value).attr('id', hash); } else { hash = id; __WEBPACK_IMPORTED_MODULE_0_jquery___default()(value).attr('id', hash); __WEBPACK_IMPORTED_MODULE_0_jquery___default()($liHeadsA.get(key)).attr('href', __WEBPACK_IMPORTED_MODULE_0_jquery___default()($liHeadsA.get(key)).attr('href').replace('#', '') + '#' + hash); }; }; var isActive = __WEBPACK_IMPORTED_MODULE_0_jquery___default()($liHeads.get(key)).hasClass('is-active'); if (isActive) { tempValue.addClass('is-active'); }; }); $liHeads.addClass(tabsTitle); }; } /** * Destroys the instance of the current plugin on this element, as well as the window resize handler that switches the plugins out. * @function */ }, { key: '_destroy', value: function _destroy() { if (this.currentPlugin) this.currentPlugin.destroy(); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off('.zf.ResponsiveAccordionTabs'); } }]); return ResponsiveAccordionTabs; }(__WEBPACK_IMPORTED_MODULE_3__foundation_plugin__["a" /* Plugin */]); ResponsiveAccordionTabs.defaults = {}; /***/ }), /* 26 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ResponsiveMenu; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_mediaQuery__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_plugin__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__foundation_dropdownMenu__ = __webpack_require__(13); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__foundation_drilldown__ = __webpack_require__(12); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__foundation_accordionMenu__ = __webpack_require__(11); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var MenuPlugins = { dropdown: { cssClass: 'dropdown', plugin: __WEBPACK_IMPORTED_MODULE_4__foundation_dropdownMenu__["a" /* DropdownMenu */] }, drilldown: { cssClass: 'drilldown', plugin: __WEBPACK_IMPORTED_MODULE_5__foundation_drilldown__["a" /* Drilldown */] }, accordion: { cssClass: 'accordion-menu', plugin: __WEBPACK_IMPORTED_MODULE_6__foundation_accordionMenu__["a" /* AccordionMenu */] } }; // import "foundation.util.triggers.js"; /** * ResponsiveMenu module. * @module foundation.responsiveMenu * @requires foundation.util.triggers * @requires foundation.util.mediaQuery */ var ResponsiveMenu = function (_Plugin) { _inherits(ResponsiveMenu, _Plugin); function ResponsiveMenu() { _classCallCheck(this, ResponsiveMenu); return _possibleConstructorReturn(this, (ResponsiveMenu.__proto__ || Object.getPrototypeOf(ResponsiveMenu)).apply(this, arguments)); } _createClass(ResponsiveMenu, [{ key: '_setup', /** * Creates a new instance of a responsive menu. * @class * @fires ResponsiveMenu#init * @param {jQuery} element - jQuery object to make into a dropdown menu. * @param {Object} options - Overrides to the default plugin settings. */ value: function _setup(element, options) { this.$element = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(element); this.rules = this.$element.data('responsive-menu'); this.currentMq = null; this.currentPlugin = null; this.className = 'ResponsiveMenu'; // ie9 back compat this._init(); this._events(); } /** * Initializes the Menu by parsing the classes from the 'data-ResponsiveMenu' attribute on the element. * @function * @private */ }, { key: '_init', value: function _init() { __WEBPACK_IMPORTED_MODULE_1__foundation_util_mediaQuery__["a" /* MediaQuery */]._init(); // The first time an Interchange plugin is initialized, this.rules is converted from a string of "classes" to an object of rules if (typeof this.rules === 'string') { var rulesTree = {}; // Parse rules from "classes" pulled from data attribute var rules = this.rules.split(' '); // Iterate through every rule found for (var i = 0; i < rules.length; i++) { var rule = rules[i].split('-'); var ruleSize = rule.length > 1 ? rule[0] : 'small'; var rulePlugin = rule.length > 1 ? rule[1] : rule[0]; if (MenuPlugins[rulePlugin] !== null) { rulesTree[ruleSize] = MenuPlugins[rulePlugin]; } } this.rules = rulesTree; } if (!__WEBPACK_IMPORTED_MODULE_0_jquery___default.a.isEmptyObject(this.rules)) { this._checkMediaQueries(); } // Add data-mutate since children may need it. this.$element.attr('data-mutate', this.$element.attr('data-mutate') || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__foundation_util_core__["a" /* GetYoDigits */])(6, 'responsive-menu')); } /** * Initializes events for the Menu. * @function * @private */ }, { key: '_events', value: function _events() { var _this = this; __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).on('changed.zf.mediaquery', function () { _this._checkMediaQueries(); }); // $(window).on('resize.zf.ResponsiveMenu', function() { // _this._checkMediaQueries(); // }); } /** * Checks the current screen width against available media queries. If the media query has changed, and the plugin needed has changed, the plugins will swap out. * @function * @private */ }, { key: '_checkMediaQueries', value: function _checkMediaQueries() { var matchedMq, _this = this; // Iterate through each rule and find the last matching rule __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.each(this.rules, function (key) { if (__WEBPACK_IMPORTED_MODULE_1__foundation_util_mediaQuery__["a" /* MediaQuery */].atLeast(key)) { matchedMq = key; } }); // No match? No dice if (!matchedMq) return; // Plugin already initialized? We good if (this.currentPlugin instanceof this.rules[matchedMq].plugin) return; // Remove existing plugin-specific CSS classes __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.each(MenuPlugins, function (key, value) { _this.$element.removeClass(value.cssClass); }); // Add the CSS class for the new plugin this.$element.addClass(this.rules[matchedMq].cssClass); // Create an instance of the new plugin if (this.currentPlugin) this.currentPlugin.destroy(); this.currentPlugin = new this.rules[matchedMq].plugin(this.$element, {}); } /** * Destroys the instance of the current plugin on this element, as well as the window resize handler that switches the plugins out. * @function */ }, { key: '_destroy', value: function _destroy() { this.currentPlugin.destroy(); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off('.zf.ResponsiveMenu'); } }]); return ResponsiveMenu; }(__WEBPACK_IMPORTED_MODULE_3__foundation_plugin__["a" /* Plugin */]); ResponsiveMenu.defaults = {}; /***/ }), /* 27 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ResponsiveToggle; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_mediaQuery__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_motion__ = __webpack_require__(6); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_plugin__ = __webpack_require__(2); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * ResponsiveToggle module. * @module foundation.responsiveToggle * @requires foundation.util.mediaQuery * @requires foundation.util.motion */ var ResponsiveToggle = function (_Plugin) { _inherits(ResponsiveToggle, _Plugin); function ResponsiveToggle() { _classCallCheck(this, ResponsiveToggle); return _possibleConstructorReturn(this, (ResponsiveToggle.__proto__ || Object.getPrototypeOf(ResponsiveToggle)).apply(this, arguments)); } _createClass(ResponsiveToggle, [{ key: '_setup', /** * Creates a new instance of Tab Bar. * @class * @fires ResponsiveToggle#init * @param {jQuery} element - jQuery object to attach tab bar functionality to. * @param {Object} options - Overrides to the default plugin settings. */ value: function _setup(element, options) { this.$element = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(element); this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, ResponsiveToggle.defaults, this.$element.data(), options); this.className = 'ResponsiveToggle'; // ie9 back compat this._init(); this._events(); } /** * Initializes the tab bar by finding the target element, toggling element, and running update(). * @function * @private */ }, { key: '_init', value: function _init() { __WEBPACK_IMPORTED_MODULE_1__foundation_util_mediaQuery__["a" /* MediaQuery */]._init(); var targetID = this.$element.data('responsive-toggle'); if (!targetID) { console.error('Your tab bar needs an ID of a Menu as the value of data-tab-bar.'); } this.$targetMenu = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + targetID); this.$toggler = this.$element.find('[data-toggle]').filter(function () { var target = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).data('toggle'); return target === targetID || target === ""; }); this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, this.options, this.$targetMenu.data()); // If they were set, parse the animation classes if (this.options.animate) { var input = this.options.animate.split(' '); this.animationIn = input[0]; this.animationOut = input[1] || null; } this._update(); } /** * Adds necessary event handlers for the tab bar to work. * @function * @private */ }, { key: '_events', value: function _events() { var _this = this; this._updateMqHandler = this._update.bind(this); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).on('changed.zf.mediaquery', this._updateMqHandler); this.$toggler.on('click.zf.responsiveToggle', this.toggleMenu.bind(this)); } /** * Checks the current media query to determine if the tab bar should be visible or hidden. * @function * @private */ }, { key: '_update', value: function _update() { // Mobile if (!__WEBPACK_IMPORTED_MODULE_1__foundation_util_mediaQuery__["a" /* MediaQuery */].atLeast(this.options.hideFor)) { this.$element.show(); this.$targetMenu.hide(); } // Desktop else { this.$element.hide(); this.$targetMenu.show(); } } /** * Toggles the element attached to the tab bar. The toggle only happens if the screen is small enough to allow it. * @function * @fires ResponsiveToggle#toggled */ }, { key: 'toggleMenu', value: function toggleMenu() { var _this3 = this; if (!__WEBPACK_IMPORTED_MODULE_1__foundation_util_mediaQuery__["a" /* MediaQuery */].atLeast(this.options.hideFor)) { /** * Fires when the element attached to the tab bar toggles. * @event ResponsiveToggle#toggled */ if (this.options.animate) { if (this.$targetMenu.is(':hidden')) { __WEBPACK_IMPORTED_MODULE_2__foundation_util_motion__["a" /* Motion */].animateIn(this.$targetMenu, this.animationIn, function () { _this3.$element.trigger('toggled.zf.responsiveToggle'); _this3.$targetMenu.find('[data-mutate]').triggerHandler('mutateme.zf.trigger'); }); } else { __WEBPACK_IMPORTED_MODULE_2__foundation_util_motion__["a" /* Motion */].animateOut(this.$targetMenu, this.animationOut, function () { _this3.$element.trigger('toggled.zf.responsiveToggle'); }); } } else { this.$targetMenu.toggle(0); this.$targetMenu.find('[data-mutate]').trigger('mutateme.zf.trigger'); this.$element.trigger('toggled.zf.responsiveToggle'); } } } }, { key: '_destroy', value: function _destroy() { this.$element.off('.zf.responsiveToggle'); this.$toggler.off('.zf.responsiveToggle'); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off('changed.zf.mediaquery', this._updateMqHandler); } }]); return ResponsiveToggle; }(__WEBPACK_IMPORTED_MODULE_3__foundation_plugin__["a" /* Plugin */]); ResponsiveToggle.defaults = { /** * The breakpoint after which the menu is always shown, and the tab bar is hidden. * @option * @type {string} * @default 'medium' */ hideFor: 'medium', /** * To decide if the toggle should be animated or not. * @option * @type {boolean} * @default false */ animate: false }; /***/ }), /* 28 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Reveal; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_util_motion__ = __webpack_require__(6); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__foundation_plugin__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__foundation_util_triggers__ = __webpack_require__(5); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Reveal module. * @module foundation.reveal * @requires foundation.util.keyboard * @requires foundation.util.triggers * @requires foundation.util.mediaQuery * @requires foundation.util.motion if using animations */ var Reveal = function (_Plugin) { _inherits(Reveal, _Plugin); function Reveal() { _classCallCheck(this, Reveal); return _possibleConstructorReturn(this, (Reveal.__proto__ || Object.getPrototypeOf(Reveal)).apply(this, arguments)); } _createClass(Reveal, [{ key: '_setup', /** * Creates a new instance of Reveal. * @class * @param {jQuery} element - jQuery object to use for the modal. * @param {Object} options - optional parameters. */ value: function _setup(element, options) { this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Reveal.defaults, this.$element.data(), options); this.className = 'Reveal'; // ie9 back compat this._init(); // Triggers init is idempotent, just need to make sure it is initialized __WEBPACK_IMPORTED_MODULE_5__foundation_util_triggers__["a" /* Triggers */].init(__WEBPACK_IMPORTED_MODULE_0_jquery___default.a); __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].register('Reveal', { 'ESCAPE': 'close' }); } /** * Initializes the modal by adding the overlay and close buttons, (if selected). * @private */ }, { key: '_init', value: function _init() { __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__["a" /* MediaQuery */]._init(); this.id = this.$element.attr('id'); this.isActive = false; this.cached = { mq: __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__["a" /* MediaQuery */].current }; this.isMobile = mobileSniff(); this.$anchor = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-open="' + this.id + '"]').length ? __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-open="' + this.id + '"]') : __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-toggle="' + this.id + '"]'); this.$anchor.attr({ 'aria-controls': this.id, 'aria-haspopup': true, 'tabindex': 0 }); if (this.options.fullScreen || this.$element.hasClass('full')) { this.options.fullScreen = true; this.options.overlay = false; } if (this.options.overlay && !this.$overlay) { this.$overlay = this._makeOverlay(this.id); } this.$element.attr({ 'role': 'dialog', 'aria-hidden': true, 'data-yeti-box': this.id, 'data-resize': this.id }); if (this.$overlay) { this.$element.detach().appendTo(this.$overlay); } else { this.$element.detach().appendTo(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this.options.appendTo)); this.$element.addClass('without-overlay'); } this._events(); if (this.options.deepLink && window.location.hash === '#' + this.id) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).one('load.zf.reveal', this.open.bind(this)); } } /** * Creates an overlay div to display behind the modal. * @private */ }, { key: '_makeOverlay', value: function _makeOverlay() { var additionalOverlayClasses = ''; if (this.options.additionalOverlayClasses) { additionalOverlayClasses = ' ' + this.options.additionalOverlayClasses; } return __WEBPACK_IMPORTED_MODULE_0_jquery___default()('<div></div>').addClass('reveal-overlay' + additionalOverlayClasses).appendTo(this.options.appendTo); } /** * Updates position of modal * TODO: Figure out if we actually need to cache these values or if it doesn't matter * @private */ }, { key: '_updatePosition', value: function _updatePosition() { var width = this.$element.outerWidth(); var outerWidth = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).width(); var height = this.$element.outerHeight(); var outerHeight = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).height(); var left, top; if (this.options.hOffset === 'auto') { left = parseInt((outerWidth - width) / 2, 10); } else { left = parseInt(this.options.hOffset, 10); } if (this.options.vOffset === 'auto') { if (height > outerHeight) { top = parseInt(Math.min(100, outerHeight / 10), 10); } else { top = parseInt((outerHeight - height) / 4, 10); } } else { top = parseInt(this.options.vOffset, 10); } this.$element.css({ top: top + 'px' }); // only worry about left if we don't have an overlay or we havea horizontal offset, // otherwise we're perfectly in the middle if (!this.$overlay || this.options.hOffset !== 'auto') { this.$element.css({ left: left + 'px' }); this.$element.css({ margin: '0px' }); } } /** * Adds event handlers for the modal. * @private */ }, { key: '_events', value: function _events() { var _this3 = this; var _this = this; this.$element.on({ 'open.zf.trigger': this.open.bind(this), 'close.zf.trigger': function (event, $element) { if (event.target === _this.$element[0] || __WEBPACK_IMPORTED_MODULE_0_jquery___default()(event.target).parents('[data-closable]')[0] === $element) { // only close reveal when it's explicitly called return _this3.close.apply(_this3); } }, 'toggle.zf.trigger': this.toggle.bind(this), 'resizeme.zf.trigger': function () { _this._updatePosition(); } }); if (this.options.closeOnClick && this.options.overlay) { this.$overlay.off('.zf.reveal').on('click.zf.reveal', function (e) { if (e.target === _this.$element[0] || __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.contains(_this.$element[0], e.target) || !__WEBPACK_IMPORTED_MODULE_0_jquery___default.a.contains(document, e.target)) { return; } _this.close(); }); } if (this.options.deepLink) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).on('popstate.zf.reveal:' + this.id, this._handleState.bind(this)); } } /** * Handles modal methods on back/forward button clicks or any other event that triggers popstate. * @private */ }, { key: '_handleState', value: function _handleState(e) { if (window.location.hash === '#' + this.id && !this.isActive) { this.open(); } else { this.close(); } } /** * Opens the modal controlled by `this.$anchor`, and closes all others by default. * @function * @fires Reveal#closeme * @fires Reveal#open */ }, { key: 'open', value: function open() { var _this4 = this; // either update or replace browser history if (this.options.deepLink) { var hash = '#' + this.id; if (window.history.pushState) { if (this.options.updateHistory) { window.history.pushState({}, '', hash); } else { window.history.replaceState({}, '', hash); } } else { window.location.hash = hash; } } this.isActive = true; // Make elements invisible, but remove display: none so we can get size and positioning this.$element.css({ 'visibility': 'hidden' }).show().scrollTop(0); if (this.options.overlay) { this.$overlay.css({ 'visibility': 'hidden' }).show(); } this._updatePosition(); this.$element.hide().css({ 'visibility': '' }); if (this.$overlay) { this.$overlay.css({ 'visibility': '' }).hide(); if (this.$element.hasClass('fast')) { this.$overlay.addClass('fast'); } else if (this.$element.hasClass('slow')) { this.$overlay.addClass('slow'); } } if (!this.options.multipleOpened) { /** * Fires immediately before the modal opens. * Closes any other modals that are currently open * @event Reveal#closeme */ this.$element.trigger('closeme.zf.reveal', this.id); } var _this = this; function addRevealOpenClasses() { if (_this.isMobile) { if (!_this.originalScrollPos) { _this.originalScrollPos = window.pageYOffset; } __WEBPACK_IMPORTED_MODULE_0_jquery___default()('html, body').addClass('is-reveal-open'); } else { __WEBPACK_IMPORTED_MODULE_0_jquery___default()('body').addClass('is-reveal-open'); } } // Motion UI method of reveal if (this.options.animationIn) { (function () { var afterAnimation = function () { _this.$element.attr({ 'aria-hidden': false, 'tabindex': -1 }).focus(); addRevealOpenClasses(); __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].trapFocus(_this.$element); }; if (_this4.options.overlay) { __WEBPACK_IMPORTED_MODULE_3__foundation_util_motion__["a" /* Motion */].animateIn(_this4.$overlay, 'fade-in'); } __WEBPACK_IMPORTED_MODULE_3__foundation_util_motion__["a" /* Motion */].animateIn(_this4.$element, _this4.options.animationIn, function () { if (_this4.$element) { // protect against object having been removed _this4.focusableElements = __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].findFocusable(_this4.$element); afterAnimation(); } }); })(); } // jQuery method of reveal else { if (this.options.overlay) { this.$overlay.show(0); } this.$element.show(this.options.showDelay); } // handle accessibility this.$element.attr({ 'aria-hidden': false, 'tabindex': -1 }).focus(); __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].trapFocus(this.$element); addRevealOpenClasses(); this._extraHandlers(); /** * Fires when the modal has successfully opened. * @event Reveal#open */ this.$element.trigger('open.zf.reveal'); } /** * Adds extra event handlers for the body and window if necessary. * @private */ }, { key: '_extraHandlers', value: function _extraHandlers() { var _this = this; if (!this.$element) { return; } // If we're in the middle of cleanup, don't freak out this.focusableElements = __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].findFocusable(this.$element); if (!this.options.overlay && this.options.closeOnClick && !this.options.fullScreen) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()('body').on('click.zf.reveal', function (e) { if (e.target === _this.$element[0] || __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.contains(_this.$element[0], e.target) || !__WEBPACK_IMPORTED_MODULE_0_jquery___default.a.contains(document, e.target)) { return; } _this.close(); }); } if (this.options.closeOnEsc) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).on('keydown.zf.reveal', function (e) { __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].handleKey(e, 'Reveal', { close: function () { if (_this.options.closeOnEsc) { _this.close(); } } }); }); } } /** * Closes the modal. * @function * @fires Reveal#closed */ }, { key: 'close', value: function close() { if (!this.isActive || !this.$element.is(':visible')) { return false; } var _this = this; // Motion UI method of hiding if (this.options.animationOut) { if (this.options.overlay) { __WEBPACK_IMPORTED_MODULE_3__foundation_util_motion__["a" /* Motion */].animateOut(this.$overlay, 'fade-out'); } __WEBPACK_IMPORTED_MODULE_3__foundation_util_motion__["a" /* Motion */].animateOut(this.$element, this.options.animationOut, finishUp); } // jQuery method of hiding else { this.$element.hide(this.options.hideDelay); if (this.options.overlay) { this.$overlay.hide(0, finishUp); } else { finishUp(); } } // Conditionals to remove extra event listeners added on open if (this.options.closeOnEsc) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off('keydown.zf.reveal'); } if (!this.options.overlay && this.options.closeOnClick) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()('body').off('click.zf.reveal'); } this.$element.off('keydown.zf.reveal'); function finishUp() { if (_this.isMobile) { if (__WEBPACK_IMPORTED_MODULE_0_jquery___default()('.reveal:visible').length === 0) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()('html, body').removeClass('is-reveal-open'); } if (_this.originalScrollPos) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()('body').scrollTop(_this.originalScrollPos); _this.originalScrollPos = null; } } else { if (__WEBPACK_IMPORTED_MODULE_0_jquery___default()('.reveal:visible').length === 0) { __WEBPACK_IMPORTED_MODULE_0_jquery___default()('body').removeClass('is-reveal-open'); } } __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].releaseFocus(_this.$element); _this.$element.attr('aria-hidden', true); /** * Fires when the modal is done closing. * @event Reveal#closed */ _this.$element.trigger('closed.zf.reveal'); } /** * Resets the modal content * This prevents a running video to keep going in the background */ if (this.options.resetOnClose) { this.$element.html(this.$element.html()); } this.isActive = false; if (_this.options.deepLink) { if (window.history.replaceState) { window.history.replaceState('', document.title, window.location.href.replace('#' + this.id, '')); } else { window.location.hash = ''; } } this.$anchor.focus(); } /** * Toggles the open/closed state of a modal. * @function */ }, { key: 'toggle', value: function toggle() { if (this.isActive) { this.close(); } else { this.open(); } } }, { key: '_destroy', /** * Destroys an instance of a modal. * @function */ value: function _destroy() { if (this.options.overlay) { this.$element.appendTo(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this.options.appendTo)); // move $element outside of $overlay to prevent error unregisterPlugin() this.$overlay.hide().off().remove(); } this.$element.hide().off(); this.$anchor.off('.zf'); __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off('.zf.reveal:' + this.id); } }]); return Reveal; }(__WEBPACK_IMPORTED_MODULE_4__foundation_plugin__["a" /* Plugin */]); Reveal.defaults = { /** * Motion-UI class to use for animated elements. If none used, defaults to simple show/hide. * @option * @type {string} * @default '' */ animationIn: '', /** * Motion-UI class to use for animated elements. If none used, defaults to simple show/hide. * @option * @type {string} * @default '' */ animationOut: '', /** * Time, in ms, to delay the opening of a modal after a click if no animation used. * @option * @type {number} * @default 0 */ showDelay: 0, /** * Time, in ms, to delay the closing of a modal after a click if no animation used. * @option * @type {number} * @default 0 */ hideDelay: 0, /** * Allows a click on the body/overlay to close the modal. * @option * @type {boolean} * @default true */ closeOnClick: true, /** * Allows the modal to close if the user presses the `ESCAPE` key. * @option * @type {boolean} * @default true */ closeOnEsc: true, /** * If true, allows multiple modals to be displayed at once. * @option * @type {boolean} * @default false */ multipleOpened: false, /** * Distance, in pixels, the modal should push down from the top of the screen. * @option * @type {number|string} * @default auto */ vOffset: 'auto', /** * Distance, in pixels, the modal should push in from the side of the screen. * @option * @type {number|string} * @default auto */ hOffset: 'auto', /** * Allows the modal to be fullscreen, completely blocking out the rest of the view. JS checks for this as well. * @option * @type {boolean} * @default false */ fullScreen: false, /** * Percentage of screen height the modal should push up from the bottom of the view. * @option * @type {number} * @default 10 */ btmOffsetPct: 10, /** * Allows the modal to generate an overlay div, which will cover the view when modal opens. * @option * @type {boolean} * @default true */ overlay: true, /** * Allows the modal to remove and reinject markup on close. Should be true if using video elements w/o using provider's api, otherwise, videos will continue to play in the background. * @option * @type {boolean} * @default false */ resetOnClose: false, /** * Allows the modal to alter the url on open/close, and allows the use of the `back` button to close modals. ALSO, allows a modal to auto-maniacally open on page load IF the hash === the modal's user-set id. * @option * @type {boolean} * @default false */ deepLink: false, /** * Update the browser history with the open modal * @option * @default false */ updateHistory: false, /** * Allows the modal to append to custom div. * @option * @type {string} * @default "body" */ appendTo: "body", /** * Allows adding additional class names to the reveal overlay. * @option * @type {string} * @default '' */ additionalOverlayClasses: '' }; function iPhoneSniff() { return (/iP(ad|hone|od).*OS/.test(window.navigator.userAgent) ); } function androidSniff() { return (/Android/.test(window.navigator.userAgent) ); } function mobileSniff() { return iPhoneSniff() || androidSniff(); } /***/ }), /* 29 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Slider; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_motion__ = __webpack_require__(6); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_util_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__foundation_plugin__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__foundation_util_touch__ = __webpack_require__(16); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__foundation_util_triggers__ = __webpack_require__(5); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Slider module. * @module foundation.slider * @requires foundation.util.motion * @requires foundation.util.triggers * @requires foundation.util.keyboard * @requires foundation.util.touch */ var Slider = function (_Plugin) { _inherits(Slider, _Plugin); function Slider() { _classCallCheck(this, Slider); return _possibleConstructorReturn(this, (Slider.__proto__ || Object.getPrototypeOf(Slider)).apply(this, arguments)); } _createClass(Slider, [{ key: '_setup', /** * Creates a new instance of a slider control. * @class * @param {jQuery} element - jQuery object to make into a slider control. * @param {Object} options - Overrides to the default plugin settings. */ value: function _setup(element, options) { this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Slider.defaults, this.$element.data(), options); this.className = 'Slider'; // ie9 back compat // Touch and Triggers inits are idempotent, we just need to make sure it's initialied. __WEBPACK_IMPORTED_MODULE_5__foundation_util_touch__["a" /* Touch */].init(__WEBPACK_IMPORTED_MODULE_0_jquery___default.a); __WEBPACK_IMPORTED_MODULE_6__foundation_util_triggers__["a" /* Triggers */].init(__WEBPACK_IMPORTED_MODULE_0_jquery___default.a); this._init(); __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].register('Slider', { 'ltr': { 'ARROW_RIGHT': 'increase', 'ARROW_UP': 'increase', 'ARROW_DOWN': 'decrease', 'ARROW_LEFT': 'decrease', 'SHIFT_ARROW_RIGHT': 'increase_fast', 'SHIFT_ARROW_UP': 'increase_fast', 'SHIFT_ARROW_DOWN': 'decrease_fast', 'SHIFT_ARROW_LEFT': 'decrease_fast', 'HOME': 'min', 'END': 'max' }, 'rtl': { 'ARROW_LEFT': 'increase', 'ARROW_RIGHT': 'decrease', 'SHIFT_ARROW_LEFT': 'increase_fast', 'SHIFT_ARROW_RIGHT': 'decrease_fast' } }); } /** * Initilizes the plugin by reading/setting attributes, creating collections and setting the initial position of the handle(s). * @function * @private */ }, { key: '_init', value: function _init() { this.inputs = this.$element.find('input'); this.handles = this.$element.find('[data-slider-handle]'); this.$handle = this.handles.eq(0); this.$input = this.inputs.length ? this.inputs.eq(0) : __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + this.$handle.attr('aria-controls')); this.$fill = this.$element.find('[data-slider-fill]').css(this.options.vertical ? 'height' : 'width', 0); var isDbl = false, _this = this; if (this.options.disabled || this.$element.hasClass(this.options.disabledClass)) { this.options.disabled = true; this.$element.addClass(this.options.disabledClass); } if (!this.inputs.length) { this.inputs = __WEBPACK_IMPORTED_MODULE_0_jquery___default()().add(this.$input); this.options.binding = true; } this._setInitAttr(0); if (this.handles[1]) { this.options.doubleSided = true; this.$handle2 = this.handles.eq(1); this.$input2 = this.inputs.length > 1 ? this.inputs.eq(1) : __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + this.$handle2.attr('aria-controls')); if (!this.inputs[1]) { this.inputs = this.inputs.add(this.$input2); } isDbl = true; // this.$handle.triggerHandler('click.zf.slider'); this._setInitAttr(1); } // Set handle positions this.setHandles(); this._events(); } }, { key: 'setHandles', value: function setHandles() { var _this3 = this; if (this.handles[1]) { this._setHandlePos(this.$handle, this.inputs.eq(0).val(), true, function () { _this3._setHandlePos(_this3.$handle2, _this3.inputs.eq(1).val(), true); }); } else { this._setHandlePos(this.$handle, this.inputs.eq(0).val(), true); } } }, { key: '_reflow', value: function _reflow() { this.setHandles(); } /** * @function * @private * @param {Number} value - floating point (the value) to be transformed using to a relative position on the slider (the inverse of _value) */ }, { key: '_pctOfBar', value: function _pctOfBar(value) { var pctOfBar = percent(value - this.options.start, this.options.end - this.options.start); switch (this.options.positionValueFunction) { case "pow": pctOfBar = this._logTransform(pctOfBar); break; case "log": pctOfBar = this._powTransform(pctOfBar); break; } return pctOfBar.toFixed(2); } /** * @function * @private * @param {Number} pctOfBar - floating point, the relative position of the slider (typically between 0-1) to be transformed to a value */ }, { key: '_value', value: function _value(pctOfBar) { switch (this.options.positionValueFunction) { case "pow": pctOfBar = this._powTransform(pctOfBar); break; case "log": pctOfBar = this._logTransform(pctOfBar); break; } var value = (this.options.end - this.options.start) * pctOfBar + this.options.start; return value; } /** * @function * @private * @param {Number} value - floating point (typically between 0-1) to be transformed using the log function */ }, { key: '_logTransform', value: function _logTransform(value) { return baseLog(this.options.nonLinearBase, value * (this.options.nonLinearBase - 1) + 1); } /** * @function * @private * @param {Number} value - floating point (typically between 0-1) to be transformed using the power function */ }, { key: '_powTransform', value: function _powTransform(value) { return (Math.pow(this.options.nonLinearBase, value) - 1) / (this.options.nonLinearBase - 1); } /** * Sets the position of the selected handle and fill bar. * @function * @private * @param {jQuery} $hndl - the selected handle to move. * @param {Number} location - floating point between the start and end values of the slider bar. * @param {Function} cb - callback function to fire on completion. * @fires Slider#moved * @fires Slider#changed */ }, { key: '_setHandlePos', value: function _setHandlePos($hndl, location, noInvert, cb) { // don't move if the slider has been disabled since its initialization if (this.$element.hasClass(this.options.disabledClass)) { return; } //might need to alter that slightly for bars that will have odd number selections. location = parseFloat(location); //on input change events, convert string to number...grumble. // prevent slider from running out of bounds, if value exceeds the limits set through options, override the value to min/max if (location < this.options.start) { location = this.options.start; } else if (location > this.options.end) { location = this.options.end; } var isDbl = this.options.doubleSided; if (isDbl) { //this block is to prevent 2 handles from crossing eachother. Could/should be improved. if (this.handles.index($hndl) === 0) { var h2Val = parseFloat(this.$handle2.attr('aria-valuenow')); location = location >= h2Val ? h2Val - this.options.step : location; } else { var h1Val = parseFloat(this.$handle.attr('aria-valuenow')); location = location <= h1Val ? h1Val + this.options.step : location; } } //this is for single-handled vertical sliders, it adjusts the value to account for the slider being "upside-down" //for click and drag events, it's weird due to the scale(-1, 1) css property if (this.options.vertical && !noInvert) { location = this.options.end - location; } var _this = this, vert = this.options.vertical, hOrW = vert ? 'height' : 'width', lOrT = vert ? 'top' : 'left', handleDim = $hndl[0].getBoundingClientRect()[hOrW], elemDim = this.$element[0].getBoundingClientRect()[hOrW], //percentage of bar min/max value based on click or drag point pctOfBar = this._pctOfBar(location), //number of actual pixels to shift the handle, based on the percentage obtained above pxToMove = (elemDim - handleDim) * pctOfBar, //percentage of bar to shift the handle movement = (percent(pxToMove, elemDim) * 100).toFixed(this.options.decimal); //fixing the decimal value for the location number, is passed to other methods as a fixed floating-point value location = parseFloat(location.toFixed(this.options.decimal)); // declare empty object for css adjustments, only used with 2 handled-sliders var css = {}; this._setValues($hndl, location); // TODO update to calculate based on values set to respective inputs?? if (isDbl) { var isLeftHndl = this.handles.index($hndl) === 0, //empty variable, will be used for min-height/width for fill bar dim, //percentage w/h of the handle compared to the slider bar handlePct = ~~(percent(handleDim, elemDim) * 100); //if left handle, the math is slightly different than if it's the right handle, and the left/top property needs to be changed for the fill bar if (isLeftHndl) { //left or top percentage value to apply to the fill bar. css[lOrT] = movement + '%'; //calculate the new min-height/width for the fill bar. dim = parseFloat(this.$handle2[0].style[lOrT]) - movement + handlePct; //this callback is necessary to prevent errors and allow the proper placement and initialization of a 2-handled slider //plus, it means we don't care if 'dim' isNaN on init, it won't be in the future. if (cb && typeof cb === 'function') { cb(); } //this is only needed for the initialization of 2 handled sliders } else { //just caching the value of the left/bottom handle's left/top property var handlePos = parseFloat(this.$handle[0].style[lOrT]); //calculate the new min-height/width for the fill bar. Use isNaN to prevent false positives for numbers <= 0 //based on the percentage of movement of the handle being manipulated, less the opposing handle's left/top position, plus the percentage w/h of the handle itself dim = movement - (isNaN(handlePos) ? (this.options.initialStart - this.options.start) / ((this.options.end - this.options.start) / 100) : handlePos) + handlePct; } // assign the min-height/width to our css object css['min-' + hOrW] = dim + '%'; } this.$element.one('finished.zf.animate', function () { /** * Fires when the handle is done moving. * @event Slider#moved */ _this.$element.trigger('moved.zf.slider', [$hndl]); }); //because we don't know exactly how the handle will be moved, check the amount of time it should take to move. var moveTime = this.$element.data('dragging') ? 1000 / 60 : this.options.moveTime; __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_2__foundation_util_motion__["b" /* Move */])(moveTime, $hndl, function () { // adjusting the left/top property of the handle, based on the percentage calculated above // if movement isNaN, that is because the slider is hidden and we cannot determine handle width, // fall back to next best guess. if (isNaN(movement)) { $hndl.css(lOrT, pctOfBar * 100 + '%'); } else { $hndl.css(lOrT, movement + '%'); } if (!_this.options.doubleSided) { //if single-handled, a simple method to expand the fill bar _this.$fill.css(hOrW, pctOfBar * 100 + '%'); } else { //otherwise, use the css object we created above _this.$fill.css(css); } }); /** * Fires when the value has not been change for a given time. * @event Slider#changed */ clearTimeout(_this.timeout); _this.timeout = setTimeout(function () { _this.$element.trigger('changed.zf.slider', [$hndl]); }, _this.options.changedDelay); } /** * Sets the initial attribute for the slider element. * @function * @private * @param {Number} idx - index of the current handle/input to use. */ }, { key: '_setInitAttr', value: function _setInitAttr(idx) { var initVal = idx === 0 ? this.options.initialStart : this.options.initialEnd; var id = this.inputs.eq(idx).attr('id') || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__["a" /* GetYoDigits */])(6, 'slider'); this.inputs.eq(idx).attr({ 'id': id, 'max': this.options.end, 'min': this.options.start, 'step': this.options.step }); this.inputs.eq(idx).val(initVal); this.handles.eq(idx).attr({ 'role': 'slider', 'aria-controls': id, 'aria-valuemax': this.options.end, 'aria-valuemin': this.options.start, 'aria-valuenow': initVal, 'aria-orientation': this.options.vertical ? 'vertical' : 'horizontal', 'tabindex': 0 }); } /** * Sets the input and `aria-valuenow` values for the slider element. * @function * @private * @param {jQuery} $handle - the currently selected handle. * @param {Number} val - floating point of the new value. */ }, { key: '_setValues', value: function _setValues($handle, val) { var idx = this.options.doubleSided ? this.handles.index($handle) : 0; this.inputs.eq(idx).val(val); $handle.attr('aria-valuenow', val); } /** * Handles events on the slider element. * Calculates the new location of the current handle. * If there are two handles and the bar was clicked, it determines which handle to move. * @function * @private * @param {Object} e - the `event` object passed from the listener. * @param {jQuery} $handle - the current handle to calculate for, if selected. * @param {Number} val - floating point number for the new value of the slider. * TODO clean this up, there's a lot of repeated code between this and the _setHandlePos fn. */ }, { key: '_handleEvent', value: function _handleEvent(e, $handle, val) { var value, hasVal; if (!val) { //click or drag events e.preventDefault(); var _this = this, vertical = this.options.vertical, param = vertical ? 'height' : 'width', direction = vertical ? 'top' : 'left', eventOffset = vertical ? e.pageY : e.pageX, halfOfHandle = this.$handle[0].getBoundingClientRect()[param] / 2, barDim = this.$element[0].getBoundingClientRect()[param], windowScroll = vertical ? __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).scrollTop() : __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).scrollLeft(); var elemOffset = this.$element.offset()[direction]; // touch events emulated by the touch util give position relative to screen, add window.scroll to event coordinates... // best way to guess this is simulated is if clientY == pageY if (e.clientY === e.pageY) { eventOffset = eventOffset + windowScroll; } var eventFromBar = eventOffset - elemOffset; var barXY; if (eventFromBar < 0) { barXY = 0; } else if (eventFromBar > barDim) { barXY = barDim; } else { barXY = eventFromBar; } var offsetPct = percent(barXY, barDim); value = this._value(offsetPct); // turn everything around for RTL, yay math! if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_3__foundation_util_core__["b" /* rtl */])() && !this.options.vertical) { value = this.options.end - value; } value = _this._adjustValue(null, value); //boolean flag for the setHandlePos fn, specifically for vertical sliders hasVal = false; if (!$handle) { //figure out which handle it is, pass it to the next function. var firstHndlPos = absPosition(this.$handle, direction, barXY, param), secndHndlPos = absPosition(this.$handle2, direction, barXY, param); $handle = firstHndlPos <= secndHndlPos ? this.$handle : this.$handle2; } } else { //change event on input value = this._adjustValue(null, val); hasVal = true; } this._setHandlePos($handle, value, hasVal); } /** * Adjustes value for handle in regard to step value. returns adjusted value * @function * @private * @param {jQuery} $handle - the selected handle. * @param {Number} value - value to adjust. used if $handle is falsy */ }, { key: '_adjustValue', value: function _adjustValue($handle, value) { var val, step = this.options.step, div = parseFloat(step / 2), left, prev_val, next_val; if (!!$handle) { val = parseFloat($handle.attr('aria-valuenow')); } else { val = value; } left = val % step; prev_val = val - left; next_val = prev_val + step; if (left === 0) { return val; } val = val >= prev_val + div ? next_val : prev_val; return val; } /** * Adds event listeners to the slider elements. * @function * @private */ }, { key: '_events', value: function _events() { this._eventsForHandle(this.$handle); if (this.handles[1]) { this._eventsForHandle(this.$handle2); } } /** * Adds event listeners a particular handle * @function * @private * @param {jQuery} $handle - the current handle to apply listeners to. */ }, { key: '_eventsForHandle', value: function _eventsForHandle($handle) { var _this = this, curHandle, timer; this.inputs.off('change.zf.slider').on('change.zf.slider', function (e) { var idx = _this.inputs.index(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this)); _this._handleEvent(e, _this.handles.eq(idx), __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).val()); }); if (this.options.clickSelect) { this.$element.off('click.zf.slider').on('click.zf.slider', function (e) { if (_this.$element.data('dragging')) { return false; } if (!__WEBPACK_IMPORTED_MODULE_0_jquery___default()(e.target).is('[data-slider-handle]')) { if (_this.options.doubleSided) { _this._handleEvent(e); } else { _this._handleEvent(e, _this.$handle); } } }); } if (this.options.draggable) { this.handles.addTouch(); var $body = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('body'); $handle.off('mousedown.zf.slider').on('mousedown.zf.slider', function (e) { $handle.addClass('is-dragging'); _this.$fill.addClass('is-dragging'); // _this.$element.data('dragging', true); curHandle = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(e.currentTarget); $body.on('mousemove.zf.slider', function (e) { e.preventDefault(); _this._handleEvent(e, curHandle); }).on('mouseup.zf.slider', function (e) { _this._handleEvent(e, curHandle); $handle.removeClass('is-dragging'); _this.$fill.removeClass('is-dragging'); _this.$element.data('dragging', false); $body.off('mousemove.zf.slider mouseup.zf.slider'); }); }) // prevent events triggered by touch .on('selectstart.zf.slider touchmove.zf.slider', function (e) { e.preventDefault(); }); } $handle.off('keydown.zf.slider').on('keydown.zf.slider', function (e) { var _$handle = __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this), idx = _this.options.doubleSided ? _this.handles.index(_$handle) : 0, oldValue = parseFloat(_this.inputs.eq(idx).val()), newValue; // handle keyboard event with keyboard util __WEBPACK_IMPORTED_MODULE_1__foundation_util_keyboard__["a" /* Keyboard */].handleKey(e, 'Slider', { decrease: function () { newValue = oldValue - _this.options.step; }, increase: function () { newValue = oldValue + _this.options.step; }, decrease_fast: function () { newValue = oldValue - _this.options.step * 10; }, increase_fast: function () { newValue = oldValue + _this.options.step * 10; }, min: function () { newValue = _this.options.start; }, max: function () { newValue = _this.options.end; }, handled: function () { // only set handle pos when event was handled specially e.preventDefault(); _this._setHandlePos(_$handle, newValue, true); } }); /*if (newValue) { // if pressed key has special function, update value e.preventDefault(); _this._setHandlePos(_$handle, newValue); }*/ }); } /** * Destroys the slider plugin. */ }, { key: '_destroy', value: function _destroy() { this.handles.off('.zf.slider'); this.inputs.off('.zf.slider'); this.$element.off('.zf.slider'); clearTimeout(this.timeout); } }]); return Slider; }(__WEBPACK_IMPORTED_MODULE_4__foundation_plugin__["a" /* Plugin */]); Slider.defaults = { /** * Minimum value for the slider scale. * @option * @type {number} * @default 0 */ start: 0, /** * Maximum value for the slider scale. * @option * @type {number} * @default 100 */ end: 100, /** * Minimum value change per change event. * @option * @type {number} * @default 1 */ step: 1, /** * Value at which the handle/input *(left handle/first input)* should be set to on initialization. * @option * @type {number} * @default 0 */ initialStart: 0, /** * Value at which the right handle/second input should be set to on initialization. * @option * @type {number} * @default 100 */ initialEnd: 100, /** * Allows the input to be located outside the container and visible. Set to by the JS * @option * @type {boolean} * @default false */ binding: false, /** * Allows the user to click/tap on the slider bar to select a value. * @option * @type {boolean} * @default true */ clickSelect: true, /** * Set to true and use the `vertical` class to change alignment to vertical. * @option * @type {boolean} * @default false */ vertical: false, /** * Allows the user to drag the slider handle(s) to select a value. * @option * @type {boolean} * @default true */ draggable: true, /** * Disables the slider and prevents event listeners from being applied. Double checked by JS with `disabledClass`. * @option * @type {boolean} * @default false */ disabled: false, /** * Allows the use of two handles. Double checked by the JS. Changes some logic handling. * @option * @type {boolean} * @default false */ doubleSided: false, /** * Potential future feature. */ // steps: 100, /** * Number of decimal places the plugin should go to for floating point precision. * @option * @type {number} * @default 2 */ decimal: 2, /** * Time delay for dragged elements. */ // dragDelay: 0, /** * Time, in ms, to animate the movement of a slider handle if user clicks/taps on the bar. Needs to be manually set if updating the transition time in the Sass settings. * @option * @type {number} * @default 200 */ moveTime: 200, //update this if changing the transition time in the sass /** * Class applied to disabled sliders. * @option * @type {string} * @default 'disabled' */ disabledClass: 'disabled', /** * Will invert the default layout for a vertical<span data-tooltip title="who would do this???"> </span>slider. * @option * @type {boolean} * @default false */ invertVertical: false, /** * Milliseconds before the `changed.zf-slider` event is triggered after value change. * @option * @type {number} * @default 500 */ changedDelay: 500, /** * Basevalue for non-linear sliders * @option * @type {number} * @default 5 */ nonLinearBase: 5, /** * Basevalue for non-linear sliders, possible values are: `'linear'`, `'pow'` & `'log'`. Pow and Log use the nonLinearBase setting. * @option * @type {string} * @default 'linear' */ positionValueFunction: 'linear' }; function percent(frac, num) { return frac / num; } function absPosition($handle, dir, clickPos, param) { return Math.abs($handle.position()[dir] + $handle[param]() / 2 - clickPos); } function baseLog(base, value) { return Math.log(value) / Math.log(base); } /***/ }), /* 30 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Sticky; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_plugin__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__foundation_util_triggers__ = __webpack_require__(5); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Sticky module. * @module foundation.sticky * @requires foundation.util.triggers * @requires foundation.util.mediaQuery */ var Sticky = function (_Plugin) { _inherits(Sticky, _Plugin); function Sticky() { _classCallCheck(this, Sticky); return _possibleConstructorReturn(this, (Sticky.__proto__ || Object.getPrototypeOf(Sticky)).apply(this, arguments)); } _createClass(Sticky, [{ key: '_setup', /** * Creates a new instance of a sticky thing. * @class * @param {jQuery} element - jQuery object to make sticky. * @param {Object} options - options object passed when creating the element programmatically. */ value: function _setup(element, options) { this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Sticky.defaults, this.$element.data(), options); this.className = 'Sticky'; // ie9 back compat // Triggers init is idempotent, just need to make sure it is initialized __WEBPACK_IMPORTED_MODULE_4__foundation_util_triggers__["a" /* Triggers */].init(__WEBPACK_IMPORTED_MODULE_0_jquery___default.a); this._init(); } /** * Initializes the sticky element by adding classes, getting/setting dimensions, breakpoints and attributes * @function * @private */ }, { key: '_init', value: function _init() { __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__["a" /* MediaQuery */]._init(); var $parent = this.$element.parent('[data-sticky-container]'), id = this.$element[0].id || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__foundation_util_core__["a" /* GetYoDigits */])(6, 'sticky'), _this = this; if ($parent.length) { this.$container = $parent; } else { this.wasWrapped = true; this.$element.wrap(this.options.container); this.$container = this.$element.parent(); } this.$container.addClass(this.options.containerClass); this.$element.addClass(this.options.stickyClass).attr({ 'data-resize': id, 'data-mutate': id }); if (this.options.anchor !== '') { __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + _this.options.anchor).attr({ 'data-mutate': id }); } this.scrollCount = this.options.checkEvery; this.isStuck = false; __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).one('load.zf.sticky', function () { //We calculate the container height to have correct values for anchor points offset calculation. _this.containerHeight = _this.$element.css("display") == "none" ? 0 : _this.$element[0].getBoundingClientRect().height; _this.$container.css('height', _this.containerHeight); _this.elemHeight = _this.containerHeight; if (_this.options.anchor !== '') { _this.$anchor = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + _this.options.anchor); } else { _this._parsePoints(); } _this._setSizes(function () { var scroll = window.pageYOffset; _this._calc(false, scroll); //Unstick the element will ensure that proper classes are set. if (!_this.isStuck) { _this._removeSticky(scroll >= _this.topPoint ? false : true); } }); _this._events(id.split('-').reverse().join('-')); }); } /** * If using multiple elements as anchors, calculates the top and bottom pixel values the sticky thing should stick and unstick on. * @function * @private */ }, { key: '_parsePoints', value: function _parsePoints() { var top = this.options.topAnchor == "" ? 1 : this.options.topAnchor, btm = this.options.btmAnchor == "" ? document.documentElement.scrollHeight : this.options.btmAnchor, pts = [top, btm], breaks = {}; for (var i = 0, len = pts.length; i < len && pts[i]; i++) { var pt; if (typeof pts[i] === 'number') { pt = pts[i]; } else { var place = pts[i].split(':'), anchor = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('#' + place[0]); pt = anchor.offset().top; if (place[1] && place[1].toLowerCase() === 'bottom') { pt += anchor[0].getBoundingClientRect().height; } } breaks[i] = pt; } this.points = breaks; return; } /** * Adds event handlers for the scrolling element. * @private * @param {String} id - pseudo-random id for unique scroll event listener. */ }, { key: '_events', value: function _events(id) { var _this = this, scrollListener = this.scrollListener = 'scroll.zf.' + id; if (this.isOn) { return; } if (this.canStick) { this.isOn = true; __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(scrollListener).on(scrollListener, function (e) { if (_this.scrollCount === 0) { _this.scrollCount = _this.options.checkEvery; _this._setSizes(function () { _this._calc(false, window.pageYOffset); }); } else { _this.scrollCount--; _this._calc(false, window.pageYOffset); } }); } this.$element.off('resizeme.zf.trigger').on('resizeme.zf.trigger', function (e, el) { _this._eventsHandler(id); }); this.$element.on('mutateme.zf.trigger', function (e, el) { _this._eventsHandler(id); }); if (this.$anchor) { this.$anchor.on('mutateme.zf.trigger', function (e, el) { _this._eventsHandler(id); }); } } /** * Handler for events. * @private * @param {String} id - pseudo-random id for unique scroll event listener. */ }, { key: '_eventsHandler', value: function _eventsHandler(id) { var _this = this, scrollListener = this.scrollListener = 'scroll.zf.' + id; _this._setSizes(function () { _this._calc(false); if (_this.canStick) { if (!_this.isOn) { _this._events(id); } } else if (_this.isOn) { _this._pauseListeners(scrollListener); } }); } /** * Removes event handlers for scroll and change events on anchor. * @fires Sticky#pause * @param {String} scrollListener - unique, namespaced scroll listener attached to `window` */ }, { key: '_pauseListeners', value: function _pauseListeners(scrollListener) { this.isOn = false; __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(scrollListener); /** * Fires when the plugin is paused due to resize event shrinking the view. * @event Sticky#pause * @private */ this.$element.trigger('pause.zf.sticky'); } /** * Called on every `scroll` event and on `_init` * fires functions based on booleans and cached values * @param {Boolean} checkSizes - true if plugin should recalculate sizes and breakpoints. * @param {Number} scroll - current scroll position passed from scroll event cb function. If not passed, defaults to `window.pageYOffset`. */ }, { key: '_calc', value: function _calc(checkSizes, scroll) { if (checkSizes) { this._setSizes(); } if (!this.canStick) { if (this.isStuck) { this._removeSticky(true); } return false; } if (!scroll) { scroll = window.pageYOffset; } if (scroll >= this.topPoint) { if (scroll <= this.bottomPoint) { if (!this.isStuck) { this._setSticky(); } } else { if (this.isStuck) { this._removeSticky(false); } } } else { if (this.isStuck) { this._removeSticky(true); } } } /** * Causes the $element to become stuck. * Adds `position: fixed;`, and helper classes. * @fires Sticky#stuckto * @function * @private */ }, { key: '_setSticky', value: function _setSticky() { var _this = this, stickTo = this.options.stickTo, mrgn = stickTo === 'top' ? 'marginTop' : 'marginBottom', notStuckTo = stickTo === 'top' ? 'bottom' : 'top', css = {}; css[mrgn] = this.options[mrgn] + 'em'; css[stickTo] = 0; css[notStuckTo] = 'auto'; this.isStuck = true; this.$element.removeClass('is-anchored is-at-' + notStuckTo).addClass('is-stuck is-at-' + stickTo).css(css) /** * Fires when the $element has become `position: fixed;` * Namespaced to `top` or `bottom`, e.g. `sticky.zf.stuckto:top` * @event Sticky#stuckto */ .trigger('sticky.zf.stuckto:' + stickTo); this.$element.on("transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd", function () { _this._setSizes(); }); } /** * Causes the $element to become unstuck. * Removes `position: fixed;`, and helper classes. * Adds other helper classes. * @param {Boolean} isTop - tells the function if the $element should anchor to the top or bottom of its $anchor element. * @fires Sticky#unstuckfrom * @private */ }, { key: '_removeSticky', value: function _removeSticky(isTop) { var stickTo = this.options.stickTo, stickToTop = stickTo === 'top', css = {}, anchorPt = (this.points ? this.points[1] - this.points[0] : this.anchorHeight) - this.elemHeight, mrgn = stickToTop ? 'marginTop' : 'marginBottom', notStuckTo = stickToTop ? 'bottom' : 'top', topOrBottom = isTop ? 'top' : 'bottom'; css[mrgn] = 0; css['bottom'] = 'auto'; if (isTop) { css['top'] = 0; } else { css['top'] = anchorPt; } this.isStuck = false; this.$element.removeClass('is-stuck is-at-' + stickTo).addClass('is-anchored is-at-' + topOrBottom).css(css) /** * Fires when the $element has become anchored. * Namespaced to `top` or `bottom`, e.g. `sticky.zf.unstuckfrom:bottom` * @event Sticky#unstuckfrom */ .trigger('sticky.zf.unstuckfrom:' + topOrBottom); } /** * Sets the $element and $container sizes for plugin. * Calls `_setBreakPoints`. * @param {Function} cb - optional callback function to fire on completion of `_setBreakPoints`. * @private */ }, { key: '_setSizes', value: function _setSizes(cb) { this.canStick = __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__["a" /* MediaQuery */].is(this.options.stickyOn); if (!this.canStick) { if (cb && typeof cb === 'function') { cb(); } } var _this = this, newElemWidth = this.$container[0].getBoundingClientRect().width, comp = window.getComputedStyle(this.$container[0]), pdngl = parseInt(comp['padding-left'], 10), pdngr = parseInt(comp['padding-right'], 10); if (this.$anchor && this.$anchor.length) { this.anchorHeight = this.$anchor[0].getBoundingClientRect().height; } else { this._parsePoints(); } this.$element.css({ 'max-width': newElemWidth - pdngl - pdngr + 'px' }); var newContainerHeight = this.$element[0].getBoundingClientRect().height || this.containerHeight; if (this.$element.css("display") == "none") { newContainerHeight = 0; } this.containerHeight = newContainerHeight; this.$container.css({ height: newContainerHeight }); this.elemHeight = newContainerHeight; if (!this.isStuck) { if (this.$element.hasClass('is-at-bottom')) { var anchorPt = (this.points ? this.points[1] - this.$container.offset().top : this.anchorHeight) - this.elemHeight; this.$element.css('top', anchorPt); } } this._setBreakPoints(newContainerHeight, function () { if (cb && typeof cb === 'function') { cb(); } }); } /** * Sets the upper and lower breakpoints for the element to become sticky/unsticky. * @param {Number} elemHeight - px value for sticky.$element height, calculated by `_setSizes`. * @param {Function} cb - optional callback function to be called on completion. * @private */ }, { key: '_setBreakPoints', value: function _setBreakPoints(elemHeight, cb) { if (!this.canStick) { if (cb && typeof cb === 'function') { cb(); } else { return false; } } var mTop = emCalc(this.options.marginTop), mBtm = emCalc(this.options.marginBottom), topPoint = this.points ? this.points[0] : this.$anchor.offset().top, bottomPoint = this.points ? this.points[1] : topPoint + this.anchorHeight, // topPoint = this.$anchor.offset().top || this.points[0], // bottomPoint = topPoint + this.anchorHeight || this.points[1], winHeight = window.innerHeight; if (this.options.stickTo === 'top') { topPoint -= mTop; bottomPoint -= elemHeight + mTop; } else if (this.options.stickTo === 'bottom') { topPoint -= winHeight - (elemHeight + mBtm); bottomPoint -= winHeight - mBtm; } else { //this would be the stickTo: both option... tricky } this.topPoint = topPoint; this.bottomPoint = bottomPoint; if (cb && typeof cb === 'function') { cb(); } } /** * Destroys the current sticky element. * Resets the element to the top position first. * Removes event listeners, JS-added css properties and classes, and unwraps the $element if the JS added the $container. * @function */ }, { key: '_destroy', value: function _destroy() { this._removeSticky(true); this.$element.removeClass(this.options.stickyClass + ' is-anchored is-at-top').css({ height: '', top: '', bottom: '', 'max-width': '' }).off('resizeme.zf.trigger').off('mutateme.zf.trigger'); if (this.$anchor && this.$anchor.length) { this.$anchor.off('change.zf.sticky'); } __WEBPACK_IMPORTED_MODULE_0_jquery___default()(window).off(this.scrollListener); if (this.wasWrapped) { this.$element.unwrap(); } else { this.$container.removeClass(this.options.containerClass).css({ height: '' }); } } }]); return Sticky; }(__WEBPACK_IMPORTED_MODULE_3__foundation_plugin__["a" /* Plugin */]); Sticky.defaults = { /** * Customizable container template. Add your own classes for styling and sizing. * @option * @type {string} * @default '&lt;div data-sticky-container&gt;&lt;/div&gt;' */ container: '<div data-sticky-container></div>', /** * Location in the view the element sticks to. Can be `'top'` or `'bottom'`. * @option * @type {string} * @default 'top' */ stickTo: 'top', /** * If anchored to a single element, the id of that element. * @option * @type {string} * @default '' */ anchor: '', /** * If using more than one element as anchor points, the id of the top anchor. * @option * @type {string} * @default '' */ topAnchor: '', /** * If using more than one element as anchor points, the id of the bottom anchor. * @option * @type {string} * @default '' */ btmAnchor: '', /** * Margin, in `em`'s to apply to the top of the element when it becomes sticky. * @option * @type {number} * @default 1 */ marginTop: 1, /** * Margin, in `em`'s to apply to the bottom of the element when it becomes sticky. * @option * @type {number} * @default 1 */ marginBottom: 1, /** * Breakpoint string that is the minimum screen size an element should become sticky. * @option * @type {string} * @default 'medium' */ stickyOn: 'medium', /** * Class applied to sticky element, and removed on destruction. Foundation defaults to `sticky`. * @option * @type {string} * @default 'sticky' */ stickyClass: 'sticky', /** * Class applied to sticky container. Foundation defaults to `sticky-container`. * @option * @type {string} * @default 'sticky-container' */ containerClass: 'sticky-container', /** * Number of scroll events between the plugin's recalculating sticky points. Setting it to `0` will cause it to recalc every scroll event, setting it to `-1` will prevent recalc on scroll. * @option * @type {number} * @default -1 */ checkEvery: -1 }; /** * Helper function to calculate em values * @param Number {em} - number of em's to calculate into pixels */ function emCalc(em) { return parseInt(window.getComputedStyle(document.body, null).fontSize, 10) * em; } /***/ }), /* 31 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Toggler; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__ = __webpack_require__(6); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_plugin__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_util_triggers__ = __webpack_require__(5); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Toggler module. * @module foundation.toggler * @requires foundation.util.motion * @requires foundation.util.triggers */ var Toggler = function (_Plugin) { _inherits(Toggler, _Plugin); function Toggler() { _classCallCheck(this, Toggler); return _possibleConstructorReturn(this, (Toggler.__proto__ || Object.getPrototypeOf(Toggler)).apply(this, arguments)); } _createClass(Toggler, [{ key: '_setup', /** * Creates a new instance of Toggler. * @class * @fires Toggler#init * @param {Object} element - jQuery object to add the trigger to. * @param {Object} options - Overrides to the default plugin settings. */ value: function _setup(element, options) { this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Toggler.defaults, element.data(), options); this.className = ''; this.className = 'Toggler'; // ie9 back compat // Triggers init is idempotent, just need to make sure it is initialized __WEBPACK_IMPORTED_MODULE_3__foundation_util_triggers__["a" /* Triggers */].init(__WEBPACK_IMPORTED_MODULE_0_jquery___default.a); this._init(); this._events(); } /** * Initializes the Toggler plugin by parsing the toggle class from data-toggler, or animation classes from data-animate. * @function * @private */ }, { key: '_init', value: function _init() { var input; // Parse animation classes if they were set if (this.options.animate) { input = this.options.animate.split(' '); this.animationIn = input[0]; this.animationOut = input[1] || null; } // Otherwise, parse toggle class else { input = this.$element.data('toggler'); // Allow for a . at the beginning of the string this.className = input[0] === '.' ? input.slice(1) : input; } // Add ARIA attributes to triggers var id = this.$element[0].id; __WEBPACK_IMPORTED_MODULE_0_jquery___default()('[data-open="' + id + '"], [data-close="' + id + '"], [data-toggle="' + id + '"]').attr('aria-controls', id); // If the target is hidden, add aria-hidden this.$element.attr('aria-expanded', this.$element.is(':hidden') ? false : true); } /** * Initializes events for the toggle trigger. * @function * @private */ }, { key: '_events', value: function _events() { this.$element.off('toggle.zf.trigger').on('toggle.zf.trigger', this.toggle.bind(this)); } /** * Toggles the target class on the target element. An event is fired from the original trigger depending on if the resultant state was "on" or "off". * @function * @fires Toggler#on * @fires Toggler#off */ }, { key: 'toggle', value: function toggle() { this[this.options.animate ? '_toggleAnimate' : '_toggleClass'](); } }, { key: '_toggleClass', value: function _toggleClass() { this.$element.toggleClass(this.className); var isOn = this.$element.hasClass(this.className); if (isOn) { /** * Fires if the target element has the class after a toggle. * @event Toggler#on */ this.$element.trigger('on.zf.toggler'); } else { /** * Fires if the target element does not have the class after a toggle. * @event Toggler#off */ this.$element.trigger('off.zf.toggler'); } this._updateARIA(isOn); this.$element.find('[data-mutate]').trigger('mutateme.zf.trigger'); } }, { key: '_toggleAnimate', value: function _toggleAnimate() { var _this = this; if (this.$element.is(':hidden')) { __WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__["a" /* Motion */].animateIn(this.$element, this.animationIn, function () { _this._updateARIA(true); this.trigger('on.zf.toggler'); this.find('[data-mutate]').trigger('mutateme.zf.trigger'); }); } else { __WEBPACK_IMPORTED_MODULE_1__foundation_util_motion__["a" /* Motion */].animateOut(this.$element, this.animationOut, function () { _this._updateARIA(false); this.trigger('off.zf.toggler'); this.find('[data-mutate]').trigger('mutateme.zf.trigger'); }); } } }, { key: '_updateARIA', value: function _updateARIA(isOn) { this.$element.attr('aria-expanded', isOn ? true : false); } /** * Destroys the instance of Toggler on the element. * @function */ }, { key: '_destroy', value: function _destroy() { this.$element.off('.zf.toggler'); } }]); return Toggler; }(__WEBPACK_IMPORTED_MODULE_2__foundation_plugin__["a" /* Plugin */]); Toggler.defaults = { /** * Tells the plugin if the element should animated when toggled. * @option * @type {boolean} * @default false */ animate: false }; /***/ }), /* 32 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Tooltip; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__ = __webpack_require__(4); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__foundation_util_triggers__ = __webpack_require__(5); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__foundation_positionable__ = __webpack_require__(15); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * Tooltip module. * @module foundation.tooltip * @requires foundation.util.box * @requires foundation.util.mediaQuery * @requires foundation.util.triggers */ var Tooltip = function (_Positionable) { _inherits(Tooltip, _Positionable); function Tooltip() { _classCallCheck(this, Tooltip); return _possibleConstructorReturn(this, (Tooltip.__proto__ || Object.getPrototypeOf(Tooltip)).apply(this, arguments)); } _createClass(Tooltip, [{ key: '_setup', /** * Creates a new instance of a Tooltip. * @class * @fires Tooltip#init * @param {jQuery} element - jQuery object to attach a tooltip to. * @param {Object} options - object to extend the default configuration. */ value: function _setup(element, options) { this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, Tooltip.defaults, this.$element.data(), options); this.className = 'Tooltip'; // ie9 back compat this.isActive = false; this.isClick = false; // Triggers init is idempotent, just need to make sure it is initialized __WEBPACK_IMPORTED_MODULE_3__foundation_util_triggers__["a" /* Triggers */].init(__WEBPACK_IMPORTED_MODULE_0_jquery___default.a); this._init(); } /** * Initializes the tooltip by setting the creating the tip element, adding it's text, setting private variables and setting attributes on the anchor. * @private */ }, { key: '_init', value: function _init() { __WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__["a" /* MediaQuery */]._init(); var elemId = this.$element.attr('aria-describedby') || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__foundation_util_core__["a" /* GetYoDigits */])(6, 'tooltip'); this.options.tipText = this.options.tipText || this.$element.attr('title'); this.template = this.options.template ? __WEBPACK_IMPORTED_MODULE_0_jquery___default()(this.options.template) : this._buildTemplate(elemId); if (this.options.allowHtml) { this.template.appendTo(document.body).html(this.options.tipText).hide(); } else { this.template.appendTo(document.body).text(this.options.tipText).hide(); } this.$element.attr({ 'title': '', 'aria-describedby': elemId, 'data-yeti-box': elemId, 'data-toggle': elemId, 'data-resize': elemId }).addClass(this.options.triggerClass); _get(Tooltip.prototype.__proto__ || Object.getPrototypeOf(Tooltip.prototype), '_init', this).call(this); this._events(); } }, { key: '_getDefaultPosition', value: function _getDefaultPosition() { // handle legacy classnames var position = this.$element[0].className.match(/\b(top|left|right|bottom)\b/g); return position ? position[0] : 'top'; } }, { key: '_getDefaultAlignment', value: function _getDefaultAlignment() { return 'center'; } }, { key: '_getHOffset', value: function _getHOffset() { if (this.position === 'left' || this.position === 'right') { return this.options.hOffset + this.options.tooltipWidth; } else { return this.options.hOffset; } } }, { key: '_getVOffset', value: function _getVOffset() { if (this.position === 'top' || this.position === 'bottom') { return this.options.vOffset + this.options.tooltipHeight; } else { return this.options.vOffset; } } /** * builds the tooltip element, adds attributes, and returns the template. * @private */ }, { key: '_buildTemplate', value: function _buildTemplate(id) { var templateClasses = (this.options.tooltipClass + ' ' + this.options.positionClass + ' ' + this.options.templateClasses).trim(); var $template = __WEBPACK_IMPORTED_MODULE_0_jquery___default()('<div></div>').addClass(templateClasses).attr({ 'role': 'tooltip', 'aria-hidden': true, 'data-is-active': false, 'data-is-focus': false, 'id': id }); return $template; } /** * sets the position class of an element and recursively calls itself until there are no more possible positions to attempt, or the tooltip element is no longer colliding. * if the tooltip is larger than the screen width, default to full width - any user selected margin * @private */ }, { key: '_setPosition', value: function _setPosition() { _get(Tooltip.prototype.__proto__ || Object.getPrototypeOf(Tooltip.prototype), '_setPosition', this).call(this, this.$element, this.template); } /** * reveals the tooltip, and fires an event to close any other open tooltips on the page * @fires Tooltip#closeme * @fires Tooltip#show * @function */ }, { key: 'show', value: function show() { if (this.options.showOn !== 'all' && !__WEBPACK_IMPORTED_MODULE_2__foundation_util_mediaQuery__["a" /* MediaQuery */].is(this.options.showOn)) { // console.error('The screen is too small to display this tooltip'); return false; } var _this = this; this.template.css('visibility', 'hidden').show(); this._setPosition(); this.template.removeClass('top bottom left right').addClass(this.position); this.template.removeClass('align-top align-bottom align-left align-right align-center').addClass('align-' + this.alignment); /** * Fires to close all other open tooltips on the page * @event Closeme#tooltip */ this.$element.trigger('closeme.zf.tooltip', this.template.attr('id')); this.template.attr({ 'data-is-active': true, 'aria-hidden': false }); _this.isActive = true; // console.log(this.template); this.template.stop().hide().css('visibility', '').fadeIn(this.options.fadeInDuration, function () { //maybe do stuff? }); /** * Fires when the tooltip is shown * @event Tooltip#show */ this.$element.trigger('show.zf.tooltip'); } /** * Hides the current tooltip, and resets the positioning class if it was changed due to collision * @fires Tooltip#hide * @function */ }, { key: 'hide', value: function hide() { // console.log('hiding', this.$element.data('yeti-box')); var _this = this; this.template.stop().attr({ 'aria-hidden': true, 'data-is-active': false }).fadeOut(this.options.fadeOutDuration, function () { _this.isActive = false; _this.isClick = false; }); /** * fires when the tooltip is hidden * @event Tooltip#hide */ this.$element.trigger('hide.zf.tooltip'); } /** * adds event listeners for the tooltip and its anchor * TODO combine some of the listeners like focus and mouseenter, etc. * @private */ }, { key: '_events', value: function _events() { var _this = this; var $template = this.template; var isFocus = false; if (!this.options.disableHover) { this.$element.on('mouseenter.zf.tooltip', function (e) { if (!_this.isActive) { _this.timeout = setTimeout(function () { _this.show(); }, _this.options.hoverDelay); } }).on('mouseleave.zf.tooltip', function (e) { clearTimeout(_this.timeout); if (!isFocus || _this.isClick && !_this.options.clickOpen) { _this.hide(); } }); } if (this.options.clickOpen) { this.$element.on('mousedown.zf.tooltip', function (e) { e.stopImmediatePropagation(); if (_this.isClick) { //_this.hide(); // _this.isClick = false; } else { _this.isClick = true; if ((_this.options.disableHover || !_this.$element.attr('tabindex')) && !_this.isActive) { _this.show(); } } }); } else { this.$element.on('mousedown.zf.tooltip', function (e) { e.stopImmediatePropagation(); _this.isClick = true; }); } if (!this.options.disableForTouch) { this.$element.on('tap.zf.tooltip touchend.zf.tooltip', function (e) { _this.isActive ? _this.hide() : _this.show(); }); } this.$element.on({ // 'toggle.zf.trigger': this.toggle.bind(this), // 'close.zf.trigger': this.hide.bind(this) 'close.zf.trigger': this.hide.bind(this) }); this.$element.on('focus.zf.tooltip', function (e) { isFocus = true; if (_this.isClick) { // If we're not showing open on clicks, we need to pretend a click-launched focus isn't // a real focus, otherwise on hover and come back we get bad behavior if (!_this.options.clickOpen) { isFocus = false; } return false; } else { _this.show(); } }).on('focusout.zf.tooltip', function (e) { isFocus = false; _this.isClick = false; _this.hide(); }).on('resizeme.zf.trigger', function () { if (_this.isActive) { _this._setPosition(); } }); } /** * adds a toggle method, in addition to the static show() & hide() functions * @function */ }, { key: 'toggle', value: function toggle() { if (this.isActive) { this.hide(); } else { this.show(); } } /** * Destroys an instance of tooltip, removes template element from the view. * @function */ }, { key: '_destroy', value: function _destroy() { this.$element.attr('title', this.template.text()).off('.zf.trigger .zf.tooltip').removeClass('has-tip top right left').removeAttr('aria-describedby aria-haspopup data-disable-hover data-resize data-toggle data-tooltip data-yeti-box'); this.template.remove(); } }]); return Tooltip; }(__WEBPACK_IMPORTED_MODULE_4__foundation_positionable__["a" /* Positionable */]); Tooltip.defaults = { disableForTouch: false, /** * Time, in ms, before a tooltip should open on hover. * @option * @type {number} * @default 200 */ hoverDelay: 200, /** * Time, in ms, a tooltip should take to fade into view. * @option * @type {number} * @default 150 */ fadeInDuration: 150, /** * Time, in ms, a tooltip should take to fade out of view. * @option * @type {number} * @default 150 */ fadeOutDuration: 150, /** * Disables hover events from opening the tooltip if set to true * @option * @type {boolean} * @default false */ disableHover: false, /** * Optional addtional classes to apply to the tooltip template on init. * @option * @type {string} * @default '' */ templateClasses: '', /** * Non-optional class added to tooltip templates. Foundation default is 'tooltip'. * @option * @type {string} * @default 'tooltip' */ tooltipClass: 'tooltip', /** * Class applied to the tooltip anchor element. * @option * @type {string} * @default 'has-tip' */ triggerClass: 'has-tip', /** * Minimum breakpoint size at which to open the tooltip. * @option * @type {string} * @default 'small' */ showOn: 'small', /** * Custom template to be used to generate markup for tooltip. * @option * @type {string} * @default '' */ template: '', /** * Text displayed in the tooltip template on open. * @option * @type {string} * @default '' */ tipText: '', touchCloseText: 'Tap to close.', /** * Allows the tooltip to remain open if triggered with a click or touch event. * @option * @type {boolean} * @default true */ clickOpen: true, /** * DEPRECATED Additional positioning classes, set by the JS * @option * @type {string} * @default '' */ positionClass: '', /** * Position of tooltip. Can be left, right, bottom, top, or auto. * @option * @type {string} * @default 'auto' */ position: 'auto', /** * Alignment of tooltip relative to anchor. Can be left, right, bottom, top, center, or auto. * @option * @type {string} * @default 'auto' */ alignment: 'auto', /** * Allow overlap of container/window. If false, tooltip will first try to * position as defined by data-position and data-alignment, but reposition if * it would cause an overflow. @option * @type {boolean} * @default false */ allowOverlap: false, /** * Allow overlap of only the bottom of the container. This is the most common * behavior for dropdowns, allowing the dropdown to extend the bottom of the * screen but not otherwise influence or break out of the container. * Less common for tooltips. * @option * @type {boolean} * @default false */ allowBottomOverlap: false, /** * Distance, in pixels, the template should push away from the anchor on the Y axis. * @option * @type {number} * @default 0 */ vOffset: 0, /** * Distance, in pixels, the template should push away from the anchor on the X axis * @option * @type {number} * @default 0 */ hOffset: 0, /** * Distance, in pixels, the template spacing auto-adjust for a vertical tooltip * @option * @type {number} * @default 14 */ tooltipHeight: 14, /** * Distance, in pixels, the template spacing auto-adjust for a horizontal tooltip * @option * @type {number} * @default 12 */ tooltipWidth: 12, /** * Allow HTML in tooltip. Warning: If you are loading user-generated content into tooltips, * allowing HTML may open yourself up to XSS attacks. * @option * @type {boolean} * @default false */ allowHtml: false }; /** * TODO utilize resize event trigger */ /***/ }), /* 33 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return SmoothScroll; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__foundation_util_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__foundation_plugin__ = __webpack_require__(2); var _createClass = function () { 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; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * SmoothScroll module. * @module foundation.smooth-scroll */ var SmoothScroll = function (_Plugin) { _inherits(SmoothScroll, _Plugin); function SmoothScroll() { _classCallCheck(this, SmoothScroll); return _possibleConstructorReturn(this, (SmoothScroll.__proto__ || Object.getPrototypeOf(SmoothScroll)).apply(this, arguments)); } _createClass(SmoothScroll, [{ key: '_setup', value: function _setup(element, options) { this.$element = element; this.options = __WEBPACK_IMPORTED_MODULE_0_jquery___default.a.extend({}, SmoothScroll.defaults, this.$element.data(), options); this.className = 'SmoothScroll'; // ie9 back compat this._init(); } /** * Initialize the SmoothScroll plugin * @private */ }, { key: '_init', value: function _init() { var id = this.$element[0].id || __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__foundation_util_core__["a" /* GetYoDigits */])(6, 'smooth-scroll'); var _this = this; this.$element.attr({ 'id': id }); this._events(); } /** * Initializes events for SmoothScroll. * @private */ }, { key: '_events', value: function _events() { var _this = this; // click handler function. var handleLinkClick = function (e) { // exit function if the event source isn't coming from an anchor with href attribute starts with '#' if (!__WEBPACK_IMPORTED_MODULE_0_jquery___default()(this).is('a[href^="#"]')) { return false; } var arrival = this.getAttribute('href'); _this._inTransition = true; SmoothScroll.scrollToLoc(arrival, _this.options, function () { _this._inTransition = false; }); e.preventDefault(); }; this.$element.on('click.zf.smoothScroll', handleLinkClick); this.$element.on('click.zf.smoothScroll', 'a[href^="#"]', handleLinkClick); } /** * Function to scroll to a given location on the page. * @param {String} loc - A properly formatted jQuery id selector. Example: '#foo' * @param {Object} options - The options to use. * @param {Function} callback - The callback function. * @static * @function */ }], [{ key: 'scrollToLoc', value: function scrollToLoc(loc) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : SmoothScroll.defaults; var callback = arguments[2]; // Do nothing if target does not exist to prevent errors if (!__WEBPACK_IMPORTED_MODULE_0_jquery___default()(loc).length) { return false; } var scrollPos = Math.round(__WEBPACK_IMPORTED_MODULE_0_jquery___default()(loc).offset().top - options.threshold / 2 - options.offset); __WEBPACK_IMPORTED_MODULE_0_jquery___default()('html, body').stop(true).animate({ scrollTop: scrollPos }, options.animationDuration, options.animationEasing, function () { if (callback && typeof callback == "function") { callback(); } }); } }]); return SmoothScroll; }(__WEBPACK_IMPORTED_MODULE_2__foundation_plugin__["a" /* Plugin */]); /** * Default settings for plugin. */ SmoothScroll.defaults = { /** * Amount of time, in ms, the animated scrolling should take between locations. * @option * @type {number} * @default 500 */ animationDuration: 500, /** * Animation style to use when scrolling between locations. Can be `'swing'` or `'linear'`. * @option * @type {string} * @default 'linear' * @see {@link https://api.jquery.com/animate|Jquery animate} */ animationEasing: 'linear', /** * Number of pixels to use as a marker for location changes. * @option * @type {number} * @default 50 */ threshold: 50, /** * Number of pixels to offset the scroll of the page on item click if using a sticky nav bar. * @option * @type {number} * @default 0 */ offset: 0 }; /***/ }), /* 34 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Timer; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); function Timer(elem, options, cb) { var _this = this, duration = options.duration, //options is an object for easily adding features later. nameSpace = Object.keys(elem.data())[0] || 'timer', remain = -1, start, timer; this.isPaused = false; this.restart = function () { remain = -1; clearTimeout(timer); this.start(); }; this.start = function () { this.isPaused = false; // if(!elem.data('paused')){ return false; }//maybe implement this sanity check if used for other things. clearTimeout(timer); remain = remain <= 0 ? duration : remain; elem.data('paused', false); start = Date.now(); timer = setTimeout(function () { if (options.infinite) { _this.restart(); //rerun the timer. } if (cb && typeof cb === 'function') { cb(); } }, remain); elem.trigger('timerstart.zf.' + nameSpace); }; this.pause = function () { this.isPaused = true; //if(elem.data('paused')){ return false; }//maybe implement this sanity check if used for other things. clearTimeout(timer); elem.data('paused', true); var end = Date.now(); remain = remain - (end - start); elem.trigger('timerpaused.zf.' + nameSpace); }; } /***/ }), /* 35 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_jquery___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_jquery__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__ = __webpack_require__(18); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_abide__ = __webpack_require__(17); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_accordion__ = __webpack_require__(10); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_accordionMenu__ = __webpack_require__(11); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_drilldown__ = __webpack_require__(12); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_dropdown__ = __webpack_require__(19); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_dropdownMenu__ = __webpack_require__(13); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_equalizer__ = __webpack_require__(20); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_interchange__ = __webpack_require__(21); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_magellan__ = __webpack_require__(22); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_offcanvas__ = __webpack_require__(23); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_orbit__ = __webpack_require__(24); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_responsiveMenu__ = __webpack_require__(26); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_responsiveToggle__ = __webpack_require__(27); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_reveal__ = __webpack_require__(28); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_slider__ = __webpack_require__(29); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_17__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_sticky__ = __webpack_require__(30); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_18__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_tabs__ = __webpack_require__(14); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_19__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_toggler__ = __webpack_require__(31); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_20__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_tooltip__ = __webpack_require__(32); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_21__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_responsiveAccordionTabs__ = __webpack_require__(25); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].addToJQuery(__WEBPACK_IMPORTED_MODULE_0_jquery___default.a); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_2__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_abide__["a" /* Abide */], 'Abide'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_3__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_accordion__["a" /* Accordion */], 'Accordion'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_4__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_accordionMenu__["a" /* AccordionMenu */], 'AccordionMenu'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_5__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_drilldown__["a" /* Drilldown */], 'Drilldown'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_6__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_dropdown__["a" /* Dropdown */], 'Dropdown'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_7__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_dropdownMenu__["a" /* DropdownMenu */], 'DropdownMenu'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_8__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_equalizer__["a" /* Equalizer */], 'Equalizer'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_9__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_interchange__["a" /* Interchange */], 'Interchange'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_10__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_magellan__["a" /* Magellan */], 'Magellan'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_11__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_offcanvas__["a" /* OffCanvas */], 'OffCanvas'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_12__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_orbit__["a" /* Orbit */], 'Orbit'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_13__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_responsiveMenu__["a" /* ResponsiveMenu */], 'ResponsiveMenu'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_14__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_responsiveToggle__["a" /* ResponsiveToggle */], 'ResponsiveToggle'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_15__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_reveal__["a" /* Reveal */], 'Reveal'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_16__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_slider__["a" /* Slider */], 'Slider'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_17__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_sticky__["a" /* Sticky */], 'Sticky'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_18__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_tabs__["a" /* Tabs */], 'Tabs'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_19__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_toggler__["a" /* Toggler */], 'Toggler'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_20__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_tooltip__["a" /* Tooltip */], 'Tooltip'); __WEBPACK_IMPORTED_MODULE_1__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_core__["a" /* Foundation */].plugin(__WEBPACK_IMPORTED_MODULE_21__home_deployer_sites_node_foundation_customizer_node_foundation_customizer_foundation_sites_js_foundation_responsiveAccordionTabs__["a" /* ResponsiveAccordionTabs */], 'ResponsiveAccordionTabs'); /***/ }) /******/ ]);
'use strict'; var _slicedToArray2 = require('babel-runtime/helpers/slicedToArray'); var _slicedToArray3 = _interopRequireDefault(_slicedToArray2); var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of'); var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf); var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck'); var _classCallCheck3 = _interopRequireDefault(_classCallCheck2); var _createClass2 = require('babel-runtime/helpers/createClass'); var _createClass3 = _interopRequireDefault(_createClass2); var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn'); var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2); var _inherits2 = require('babel-runtime/helpers/inherits'); var _inherits3 = _interopRequireDefault(_inherits2); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _require = require('../../errors'), CramUnimplementedError = _require.CramUnimplementedError, CramMalformedError = _require.CramMalformedError, CramBufferOverrunError = _require.CramBufferOverrunError; var CramCodec = require('./_base'); var _require2 = require('../util'), parseItf8 = _require2.parseItf8; var ExternalCodec = function (_CramCodec) { (0, _inherits3.default)(ExternalCodec, _CramCodec); function ExternalCodec() { var parameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var dataType = arguments[1]; (0, _classCallCheck3.default)(this, ExternalCodec); var _this = (0, _possibleConstructorReturn3.default)(this, (ExternalCodec.__proto__ || (0, _getPrototypeOf2.default)(ExternalCodec)).call(this, parameters, dataType)); if (_this.dataType === 'int') { _this._decodeData = _this._decodeInt; } else if (_this.dataType === 'byte') { _this._decodeData = _this._decodeByte; } else { throw new CramUnimplementedError(_this.dataType + ' decoding not yet implemented by EXTERNAL codec'); } return _this; } (0, _createClass3.default)(ExternalCodec, [{ key: 'decode', value: function decode(slice, coreDataBlock, blocksByContentId, cursors) { var blockContentId = this.parameters.blockContentId; var contentBlock = blocksByContentId[blockContentId]; if (!contentBlock) throw new CramMalformedError('no block found with content ID ' + blockContentId); var cursor = cursors.externalBlocks.getCursor(blockContentId); return this._decodeData(contentBlock, cursor); } }, { key: '_decodeInt', value: function _decodeInt(contentBlock, cursor) { var _parseItf = parseItf8(contentBlock.content, cursor.bytePosition), _parseItf2 = (0, _slicedToArray3.default)(_parseItf, 2), result = _parseItf2[0], bytesRead = _parseItf2[1]; cursor.bytePosition += bytesRead; return result; } }, { key: '_decodeByte', value: function _decodeByte(contentBlock, cursor) { if (cursor.bytePosition >= contentBlock.content.length) throw new CramBufferOverrunError('attempted to read beyond end of block. this file seems truncated.'); var result = contentBlock.content[cursor.bytePosition]; cursor.bytePosition += 1; return result; } }]); return ExternalCodec; }(CramCodec); module.exports = ExternalCodec;
function Testimonial({ testimonialText }) { return ( <figure> <blockquote className='blockquote'> <p> {testimonialText}</p> </blockquote> <figcaption className='blockquote-footer'>Firstbane Lastname</figcaption> </figure> ) } export default Testimonial
'use strict'; describe('Directive: navigationMenu', function () { // load the directive's module beforeEach(module('jedd')); var element, scope; beforeEach(inject(function ($rootScope) { scope = $rootScope.$new(); })); it('should make hidden element visible', inject(function ($compile) { element = angular.element('<navigation-menu></navigation-menu>'); element = $compile(element)(scope); expect(element.text()).toBe('this is the navigationMenu directive'); })); });
/** * echarts图表类:K线图 * * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。 * @author Kener (@Kener-林峰, [email protected]) * */ define(function (require) { var ComponentBase = require('../component/base'); var ChartBase = require('./base'); // 图形依赖 var CandleShape = require('../util/shape/Candle'); // 组件依赖 require('../component/axis'); require('../component/grid'); require('../component/dataZoom'); var ecConfig = require('../config'); var ecData = require('../util/ecData'); var zrUtil = require('zrender/tool/util'); /** * 构造函数 * @param {Object} messageCenter echart消息中心 * @param {ZRender} zr zrender实例 * @param {Object} series 数据 * @param {Object} component 组件 */ function K(ecTheme, messageCenter, zr, option, myChart){ // 基类 ComponentBase.call(this, ecTheme, messageCenter, zr, option, myChart); // 图表基类 ChartBase.call(this); this.refresh(option); } K.prototype = { type: ecConfig.CHART_TYPE_K, /** * 绘制图形 */ _buildShape: function () { var series = this.series; this.selectedMap = {}; // 水平垂直双向series索引 ,position索引到seriesIndex var _position2sIndexMap = { top: [], bottom: [] }; var xAxis; for (var i = 0, l = series.length; i < l; i++) { if (series[i].type === ecConfig.CHART_TYPE_K) { series[i] = this.reformOption(series[i]); this.legendHoverLink = series[i].legendHoverLink || this.legendHoverLink; xAxis = this.component.xAxis.getAxis(series[i].xAxisIndex); if (xAxis.type === ecConfig.COMPONENT_TYPE_AXIS_CATEGORY ) { _position2sIndexMap[xAxis.getPosition()].push(i); } } } //console.log(_position2sIndexMap) for (var position in _position2sIndexMap) { if (_position2sIndexMap[position].length > 0) { this._buildSinglePosition( position, _position2sIndexMap[position] ); } } this.addShapeList(); }, /** * 构建单个方向上的K线图 * * @param {number} seriesIndex 系列索引 */ _buildSinglePosition: function (position, seriesArray) { var mapData = this._mapData(seriesArray); var locationMap = mapData.locationMap; var maxDataLength = mapData.maxDataLength; if (maxDataLength === 0 || locationMap.length === 0) { return; } this._buildHorizontal(seriesArray, maxDataLength, locationMap); for (var i = 0, l = seriesArray.length; i < l; i++) { this.buildMark(seriesArray[i]); } }, /** * 数据整形 * 数组位置映射到系列索引 */ _mapData: function (seriesArray) { var series = this.series; var serie; // 临时映射变量 var serieName; // 临时映射变量 var legend = this.component.legend; var locationMap = []; // 需要返回的东西:数组位置映射到系列索引 var maxDataLength = 0; // 需要返回的东西:最大数据长度 // 计算需要显示的个数和分配位置并记在下面这个结构里 for (var i = 0, l = seriesArray.length; i < l; i++) { serie = series[seriesArray[i]]; serieName = serie.name; if (legend){ this.selectedMap[serieName] = legend.isSelected(serieName); } else { this.selectedMap[serieName] = true; } if (this.selectedMap[serieName]) { locationMap.push(seriesArray[i]); } // 兼职帮算一下最大长度 maxDataLength = Math.max(maxDataLength, serie.data.length); } return { locationMap: locationMap, maxDataLength: maxDataLength }; }, /** * 构建类目轴为水平方向的K线图系列 */ _buildHorizontal: function (seriesArray, maxDataLength, locationMap) { var series = this.series; // 确定类目轴和数值轴,同一方向随便找一个即可 var seriesIndex; var serie; var xAxisIndex; var categoryAxis; var yAxisIndex; // 数值轴各异 var valueAxis; // 数值轴各异 var pointList = {}; var candleWidth; var data; var value; var barMaxWidth; for (var j = 0, k = locationMap.length; j < k; j++) { seriesIndex = locationMap[j]; serie = series[seriesIndex]; xAxisIndex = serie.xAxisIndex || 0; categoryAxis = this.component.xAxis.getAxis(xAxisIndex); candleWidth = serie.barWidth || Math.floor(categoryAxis.getGap() / 2); barMaxWidth = serie.barMaxWidth; if (barMaxWidth && barMaxWidth < candleWidth) { candleWidth = barMaxWidth; } yAxisIndex = serie.yAxisIndex || 0; valueAxis = this.component.yAxis.getAxis(yAxisIndex); pointList[seriesIndex] = []; for (var i = 0, l = maxDataLength; i < l; i++) { if (categoryAxis.getNameByIndex(i) == null) { // 系列数据超出类目轴长度 break; } data = serie.data[i]; value = data != null ? (data.value != null ? data.value : data) : '-'; if (value === '-' || value.length != 4) { // 数据格式不符 continue; } pointList[seriesIndex].push([ categoryAxis.getCoordByIndex(i), // 横坐标 candleWidth, valueAxis.getCoord(value[0]), // 纵坐标:开盘 valueAxis.getCoord(value[1]), // 纵坐标:收盘 valueAxis.getCoord(value[2]), // 纵坐标:最低 valueAxis.getCoord(value[3]), // 纵坐标:最高 i, // 数据index categoryAxis.getNameByIndex(i) // 类目名称 ]); } } // console.log(pointList) this._buildKLine(seriesArray, pointList); }, /** * 生成K线 */ _buildKLine: function (seriesArray, pointList) { var series = this.series; // normal: var nLineWidth; var nLineColor; var nLineColor0; // 阴线 var nColor; var nColor0; // 阴线 // emphasis: var eLineWidth; var eLineColor; var eLineColor0; var eColor; var eColor0; var serie; var queryTarget; var data; var seriesPL; var singlePoint; var candleType; var seriesIndex; for (var sIdx = 0, len = seriesArray.length; sIdx < len; sIdx++) { seriesIndex = seriesArray[sIdx]; serie = series[seriesIndex]; seriesPL = pointList[seriesIndex]; if (this._isLarge(seriesPL)) { seriesPL = this._getLargePointList(seriesPL); } if (serie.type === ecConfig.CHART_TYPE_K && seriesPL != null) { // 多级控制 queryTarget = serie; nLineWidth = this.query( queryTarget, 'itemStyle.normal.lineStyle.width' ); nLineColor = this.query( queryTarget, 'itemStyle.normal.lineStyle.color' ); nLineColor0 = this.query( queryTarget, 'itemStyle.normal.lineStyle.color0' ); nColor = this.query( queryTarget, 'itemStyle.normal.color' ); nColor0 = this.query( queryTarget, 'itemStyle.normal.color0' ); eLineWidth = this.query( queryTarget, 'itemStyle.emphasis.lineStyle.width' ); eLineColor = this.query( queryTarget, 'itemStyle.emphasis.lineStyle.color' ); eLineColor0 = this.query( queryTarget, 'itemStyle.emphasis.lineStyle.color0' ); eColor = this.query( queryTarget, 'itemStyle.emphasis.color' ); eColor0 = this.query( queryTarget, 'itemStyle.emphasis.color0' ); /* * pointlist=[ * 0 x, * 1 width, * 2 y0, * 3 y1, * 4 y2, * 5 y3, * 6 dataIndex, * 7 categoryName * ] */ for (var i = 0, l = seriesPL.length; i < l; i++) { singlePoint = seriesPL[i]; data = serie.data[singlePoint[6]]; queryTarget = data; candleType = singlePoint[3] < singlePoint[2]; this.shapeList.push(this._getCandle( seriesIndex, // seriesIndex singlePoint[6], // dataIndex singlePoint[7], // name singlePoint[0], // x singlePoint[1], // width singlePoint[2], // y开盘 singlePoint[3], // y收盘 singlePoint[4], // y最低 singlePoint[5], // y最高 // 填充颜色 candleType ? (this.query( // 阳 queryTarget, 'itemStyle.normal.color' ) || nColor) : (this.query( // 阴 queryTarget, 'itemStyle.normal.color0' ) || nColor0), // 线宽 this.query( queryTarget, 'itemStyle.normal.lineStyle.width' ) || nLineWidth, // 线色 candleType ? (this.query( // 阳 queryTarget, 'itemStyle.normal.lineStyle.color' ) || nLineColor) : (this.query( // 阴 queryTarget, 'itemStyle.normal.lineStyle.color0' ) || nLineColor0), //------------高亮 // 填充颜色 candleType ? (this.query( // 阳 queryTarget, 'itemStyle.emphasis.color' ) || eColor || nColor) : (this.query( // 阴 queryTarget, 'itemStyle.emphasis.color0' ) || eColor0 || nColor0), // 线宽 this.query( queryTarget, 'itemStyle.emphasis.lineStyle.width' ) || eLineWidth || nLineWidth, // 线色 candleType ? (this.query( // 阳 queryTarget, 'itemStyle.emphasis.lineStyle.color' ) || eLineColor || nLineColor) : (this.query( // 阴 queryTarget, 'itemStyle.emphasis.lineStyle.color0' ) || eLineColor0 || nLineColor0) )); } } } // console.log(this.shapeList) }, _isLarge: function(singlePL) { return singlePL[0][1] < 0.5; }, /** * 大规模pointList优化 */ _getLargePointList: function(singlePL) { var total = this.component.grid.getWidth(); var len = singlePL.length; var newList = []; for (var i = 0; i < total; i++) { newList[i] = singlePL[Math.floor(len / total * i)]; } return newList; }, /** * 生成K线图上的图形 */ _getCandle: function ( seriesIndex, dataIndex, name, x, width, y0, y1, y2, y3, nColor, nLinewidth, nLineColor, eColor, eLinewidth, eLineColor ) { var series = this.series; var itemShape = { zlevel: this._zlevelBase, clickable: this.deepQuery( [series[seriesIndex].data[dataIndex], series[seriesIndex]], 'clickable' ), style: { x: x, y: [y0, y1, y2, y3], width: width, color: nColor, strokeColor: nLineColor, lineWidth: nLinewidth, brushType: 'both' }, highlightStyle: { color: eColor, strokeColor: eLineColor, lineWidth: eLinewidth }, _seriesIndex: seriesIndex }; ecData.pack( itemShape, series[seriesIndex], seriesIndex, series[seriesIndex].data[dataIndex], dataIndex, name ); itemShape = new CandleShape(itemShape); return itemShape; }, // 位置转换 getMarkCoord: function (seriesIndex, mpData) { var serie = this.series[seriesIndex]; var xAxis = this.component.xAxis.getAxis(serie.xAxisIndex); var yAxis = this.component.yAxis.getAxis(serie.yAxisIndex); return [ typeof mpData.xAxis != 'string' && xAxis.getCoordByIndex ? xAxis.getCoordByIndex(mpData.xAxis || 0) : xAxis.getCoord(mpData.xAxis || 0), typeof mpData.yAxis != 'string' && yAxis.getCoordByIndex ? yAxis.getCoordByIndex(mpData.yAxis || 0) : yAxis.getCoord(mpData.yAxis || 0) ]; }, /** * 刷新 */ refresh: function (newOption) { if (newOption) { this.option = newOption; this.series = newOption.series; } this.backupShapeList(); this._buildShape(); }, /** * 动画设定 */ addDataAnimation: function (params) { var series = this.series; var aniMap = {}; // seriesIndex索引参数 for (var i = 0, l = params.length; i < l; i++) { aniMap[params[i][0]] = params[i]; } var x; var dx; var y; var serie; var seriesIndex; var dataIndex; for (var i = 0, l = this.shapeList.length; i < l; i++) { seriesIndex = this.shapeList[i]._seriesIndex; if (aniMap[seriesIndex] && !aniMap[seriesIndex][3]) { // 有数据删除才有移动的动画 if (this.shapeList[i].type === 'candle') { dataIndex = ecData.get(this.shapeList[i], 'dataIndex'); serie = series[seriesIndex]; if (aniMap[seriesIndex][2] && dataIndex === serie.data.length - 1 ) { // 队头加入删除末尾 this.zr.delShape(this.shapeList[i].id); continue; } else if (!aniMap[seriesIndex][2] && dataIndex === 0) { // 队尾加入删除头部 this.zr.delShape(this.shapeList[i].id); continue; } dx = this.component.xAxis.getAxis( serie.xAxisIndex || 0 ).getGap(); x = aniMap[seriesIndex][2] ? dx : -dx; y = 0; this.zr.animate(this.shapeList[i].id, '') .when( 500, { position: [ x, y ] } ) .start(); } } } } }; zrUtil.inherits(K, ChartBase); zrUtil.inherits(K, ComponentBase); // 图表注册 require('../chart').define('k', K); return K; });
'use strict' const utils = require('./utils.js') module.exports = function(context) { return { CallExpression: function(node) { if (node.callee.type !== 'MemberExpression') return if (node.callee.property.name !== 'show') return if (utils.isjQuery(node)) { context.report({ node: node, message: '$.show is not allowed' }) } } } } module.exports.schema = []
//Business Logic function Game (player1, player2, board) { this.player1 = player1; this.player2 = player2; this.turnsArray = [0, 1]; this.currentTurn = turnsArray[0] this.board = board; } Game.prototype.nextTurn = function() { if (this.currentTurn === turnsArray[0]) { this.currentTurn = turnsArray[1] } else { this.currentTurn = turnsArray[0] } } Game.prototype.whoseTurn = function() { if (this.currentTurn === turnsArray[0]) { return this.player1 } else if (this.currentTurn === turnsArray[1]) { return this.player2 } } Game.prototype.currentMark = function() { if (this.currentTurn === turnsArray[0]) { return 'X' } else { return 'O' } } Game.prototpe.checkWin(board, player) { //use reduce method. It'll go through every thing in the array. A is what is returned. I is the index let plays = board.reduce((accumulator, element, index) => //If the element is equal to the player, then we'll push that index to the array. (element === player) ? accumulator.concat(index) :accumulator, []); let gameWon = null; for (let [index, win] of board.winCombos.entries()) { //has the player played in every spot that counts as a win for that win array entry? if(win.every(elem => plays.indexOf(elem) > -1)) { gameWon = {index: index, player: player}; break; } } return gameWon; } //add method for checking for winner after other objects have been defined. function Player(mark) { this.mark = mark; } Player.prototype.whichMark = function() { console.log(this.mark); } Player.prototype.turnClick = function() { turn(square.target.id, this.mark) } function Spaces() { const cells = document.querySelectorAll('.cell'); for (let currentCell = 0; currentCell <cells.length; currentCell++) { cells[currentCell].innerText = ''; cells[currentCell].addEventListener('click', turnClick, false); } } Spaces.prototype.beenMarked = function(spaceNumber) { if((cells.item(spaceNumber).innerText) != '') { console.log((cells.item(spaceNumber).innerText)) } else if (cells.item(spaceNumber).innerText === '') { return } } function Board(spaces, winningcombos) { this.spaces = spaces; this.winCombos = [ [0, 1, 2], [0, 3, 6], [0, 4, 8], [1, 4, 7], [2, 5, 8], [3, 4, 5], [6, 7, 8], [6, 4, 2] ] } Board.prototype.markSpace = function(spaceNumber, currentMark) { } } function turn(squareID, mark) { origBoard[squareID] = mark; document.getElementById(squareId).innerText = mark; } //User Logic $(document).ready(function() { let origBoard; $('form#play_style_form').submit(function(event) { event.preventDefault(); $('#player_select').slideUp(); $('#game_board').slideDown(); const playerX = 'X'; const playerO = '0'; const winCombos = [ [0, 1, 2], [0, 3, 6], [0, 4, 8], [1, 4, 7], [2, 5, 8], [3, 4, 5], [6, 7, 8], [6, 4, 2] ] const cells = document.querySelectorAll('.cell'); startGame(); function startGame() { origBoard = Array.from(Array(9).keys()); for (let currentCell = 0; currentCell <cells.length; currentCell++) { cells[currentCell].innerText = ''; cells[currentCell].addEventListener('click', turnClick, false); } } function turnClick(square) { turn(square.target.id, player) } function turn(squareID, player) { origBoard[squareID] = player; document.getElementById(squareId).innerText = player; let gameWon = checkWin(origBoard, player) if (gameWon) gameOver(gameWon) } function checkWin(board, player) { //use reduce method. It'll go through every thing in the array. A is what is returned. I is the index let plays = board.reduce((accumulator, element, index) => //If the element is equal to the player, then we'll push that index to the array. (element === player) ? accumulator.concat(index) :accumulator, []); let gameWon = null; for (let [index, win] of winCombos.entries()) { //has the player played in every spot that counts as a win for that win array entry? if(win.every(elem => plays.indexOf(elem) > -1)) { gameWon = {index: index, player: player}; break; } } return gameWon; } function gameOver(gameWon) { for (let index of winCombos[gomeWon.index]) { document.getElementById(index).style.backgroundColor = gameWon.player === playerX ? "blue" : "red" } for (let index = 0; index <cells.length; index++) { cells[i].removeEventListener('click', turnclick, false) } } }); });
import React from "react"; export const ButtonViewListings = props => ( <div className='holder'> <button className="btn viewListings"> {props.children}</button> </div> );
'use strict'; describe('PractitionerListApp.practitioner', function() { var $httpBackend; var Practitioner; var practitionerData = { "resourceType": "Bundle", "id": "ceba7a08-4ffb-43bd-8cd4-0edb255c1a", "meta": {"lastUpdated": "2017-01-15T16:19:38Z"}, "type": "searchset", "total": 89, "link": [{ "relation": "self", "url": "http://fhir3.healthintersections.com.au/open/Practitioner?_format=application/json+fhir&search-id=aee79655-3189-44ca-91aa-b8007258eb" }, { "relation": "first", "url": "http://fhir3.healthintersections.com.au/open/Practitioner?_format=application/json+fhir&search-id=aee79655-3189-44ca-91aa-b8007258eb&search-offset=0&_count=50" }, { "relation": "next", "url": "http://fhir3.healthintersections.com.au/open/Practitioner?_format=application/json+fhir&search-id=aee79655-3189-44ca-91aa-b8007258eb&search-offset=50&_count=50" }, { "relation": "last", "url": "http://fhir3.healthintersections.com.au/open/Practitioner?_format=application/json+fhir&search-id=aee79655-3189-44ca-91aa-b8007258eb&search-offset=50&_count=50" }], "entry": [ { "fullUrl": "http://fhir3.healthintersections.com.au/open/Practitioner/1", "resource": { "resourceType": 'Practitioner', "id": "1", "meta": {"versionId": "1", "lastUpdated": "2017-01-14T11:36:29Z"}, "text": { "status": "generated", "div": "<div xmlns=\"http://www.w3.org/1999/xhtml\">&#10;&#9;&#9;&#9;&#9;&#9;&#9;&#10; <p>Dr Adam Careful is a Referring Practitioner for Acme Hospital from 1-Jan 2012 to 31-Mar&#10; 2012</p>&#10;&#9;&#9;&#9;&#9;&#9;&#10; </div>" }, "identifier": [{"system": "http://www.acme.org/practitioners", "value": "23"}], "name": [{"family": "Careful", "given": ["Adam"], "prefix": ["Dr"]}] } }, { "fullUrl": "http://fhir3.healthintersections.com.au/open/Practitioner/13", "resource": { "resourceType": "Practitioner", "id": "13", "meta": {"versionId": "1", "lastUpdated": "2017-01-14T12:05:11Z"}, "text": { "status": "generated", "div": "<div xmlns=\"http://www.w3.org/1999/xhtml\">Seven, Henry. SSN:&#10; 333333333</div>" }, "identifier": [{ "type": {"coding": [{"system": "http://hl7.org/fhir/v2/0203", "code": "SS"}]}, "system": "http://hl7.org/fhir/sid/us-ssn", "value": "333333333" }], "name": [{"use": "official", "family": "Seven", "given": ["Henry"]}] } } ] }; // Add a custom equality tester before each test beforeEach(function() { }); // Load the module that contains the `Practitioner` service before each test beforeEach(module('PractitionerListApp.practitioner')); // Instantiate the service and "train" `$httpBackend` before each test beforeEach(inject(function(_$httpBackend_, _Practitioner_) { $httpBackend = _$httpBackend_; $httpBackend.expectGET('http://fhir3.healthintersections.com.au/open/Practitioner?_format=json&_id=&_sort=_id').respond(practitionerData); Practitioner = _Practitioner_; })); // Verify that there are no outstanding expectations or requests after each test afterEach(function () { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); // unit test it('should fetch the practitioners data from STU3 FHIR server `practitioner`', function() { var practitioners = Practitioner.query(); expect(angular.equals(practitioners, {})).to.be.true; $httpBackend.flush(); expect(angular.equals(practitioners, practitionerData)).to.be.true; }); it('should have a total result number of 89', function() { var practitioners = Practitioner.query(); expect(angular.equals(practitioners, {})).to.be.true; $httpBackend.flush(); expect(practitioners.total).to.equal(89); }); });
import utilities as u from wallaby import * import constants as c def clear_ticks_button(): print ("Waiting for motor to be placed in zero position") u.wait_for_button() clear_motor_position_counter(c.electric_line_motor) def clear_ticks(speed): count = 0 motor_power(c.electric_line_motor, speed) while count < 10: x = get_motor_position_counter(c.electric_line_motor) msleep(5) if get_motor_position_counter(c.electric_line_motor) == x: count = count + 1 motor(c.electric_line_motor, 0) clear_motor_position_counter(c.electric_line_motor) def electric_line_motor(speed, endPos, n = 10): count = 0 if get_motor_position_counter(c.electric_line_motor) > endPos: speed = -speed motor_power(c.electric_line_motor, speed) while get_motor_position_counter(c.electric_line_motor) > endPos: x = get_motor_position_counter(c.electric_line_motor) msleep(5) if count == n: break elif x == get_motor_position_counter(c.electric_line_motor): count = count + 1 else: count = 0 else: motor_power(c.electric_line_motor, speed) while get_motor_position_counter(c.electric_line_motor) < endPos: x = get_motor_position_counter(c.electric_line_motor) msleep(5) if count == n: break elif x == get_motor_position_counter(c.electric_line_motor): count = count + 1 else: count = 0 motor(c.electric_line_motor, 0)
""" Created on 22. apr. 2015 @author: pab References ---------- A METHODOLOGY FOR ROBUST OPTIMIZATION OF LOW-THRUST TRAJECTORIES IN MULTI-BODY ENVIRONMENTS Gregory Lantoine (2010) Phd thesis, Georgia Institute of Technology USING MULTICOMPLEX VARIABLES FOR AUTOMATIC COMPUTATION OF HIGH-ORDER DERIVATIVES Gregory Lantoine, Ryan P. Russell , and Thierry Dargent ACM Transactions on Mathematical Software, Vol. 38, No. 3, Article 16, April 2012, 21 pages, http://doi.acm.org/10.1145/2168773.2168774 M.E. Luna-Elizarraras, M. Shapiro, D.C. Struppa1, A. Vajiac (2012) CUBO A Mathematical Journal Vol. 14, No 2, (61-80). June 2012. Computation of higher-order derivatives using the multi-complex step method Adriaen Verheyleweghen, (2014) Project report, NTNU """ from __future__ import division import numpy as np _TINY = np.finfo(float).machar.tiny def c_atan2(x, y): a, b = np.real(x), np.imag(x) c, d = np.real(y), np.imag(y) return np.arctan2(a, c) + 1j * (c * b - a * d) / (a**2 + c**2) def c_max(x, y): return np.where(x.real < y.real, y, x) def c_min(x, y): return np.where(x.real > y.real, y, x) def c_abs(z): if np.all(np.iscomplex(z)): return np.where(np.real(z) >= 0, z, -z) return np.abs(z) class Bicomplex(object): """ BICOMPLEX(z1, z2) Creates an instance of a Bicomplex object. zeta = z1 + j*z2, where z1 and z2 are complex numbers. """ def __init__(self, z1, z2): z1, z2 = np.broadcast_arrays(z1, z2) self.z1 = np.asanyarray(z1, dtype=np.complex128) self.z2 = np.asanyarray(z2, dtype=np.complex128) @property def shape(self): return self.z1.shape @property def size(self): return self.z1.size def mod_c(self): """Complex modulus""" r12, r22 = self.z1*self.z1, self.z2*self.z2 r = np.sqrt(r12 + r22) return r def norm(self): z1, z2 = self.z1, self.z2 return np.sqrt(z1.real**2 + z2.real**2 + z1.imag**2 + z2.imag**2) @property def real(self): return self.z1.real @property def imag(self): return self.z1.imag @property def imag1(self): return self.z1.imag @property def imag2(self): return self.z2.real @property def imag12(self): return self.z2.imag @staticmethod def asarray(other): z1, z2 = other.z1, other.z2 return np.vstack((np.hstack((z1, -z2)), np.hstack((z2, z1)))) @staticmethod def _coerce(other): if not isinstance(other, Bicomplex): return Bicomplex(other, np.zeros(np.shape(other))) return other @staticmethod def mat2bicomp(arr): shape = np.array(arr.shape) shape[:2] = shape[:2] // 2 z1 = arr[:shape[0]] z2 = arr[shape[0]:] slices = tuple([slice(None, None, 1)] + [slice(n) for n in shape[1:]]) return Bicomplex(z1[slices], z2[slices]) @staticmethod def __array_wrap__(result): if isinstance(result, Bicomplex): return result shape = result.shape result = np.atleast_1d(result) z1 = np.array([cls.z1 for cls in result.ravel()]) z2 = np.array([cls.z2 for cls in result.ravel()]) return Bicomplex(z1.reshape(shape), z2.reshape(shape)) def __repr__(self): name = self.__class__.__name__ return """{0!s}(z1={1!s}, z2={2!s})""".format(name, str(self.z1), str(self.z2)) def __lt__(self, other): other = self._coerce(other) return self.z1.real < other.z1.real def __le__(self, other): other = self._coerce(other) return self.z1.real <= other.z1.real def __gt__(self, other): other = self._coerce(other) return self.z1.real > other.z1.real def __ge__(self, other): other = self._coerce(other) return self.z1.real >= other.z1.real def __eq__(self, other): other = self._coerce(other) return (self.z1 == other.z1) * (self.z2 == other.z2) def __getitem__(self, index): return Bicomplex(self.z1[index], self.z2[index]) def __setitem__(self, index, value): value = self._coerce(value) if index in ['z1', 'z2']: setattr(self, index, value) else: self.z1[index] = value.z1 self.z2[index] = value.z2 def __abs__(self): z1, z2 = self.z1, self.z2 mask = self >= 0 return Bicomplex(np.where(mask, z1, -z1), np.where(mask, z2, -z2)) def __neg__(self): return Bicomplex(-self.z1, -self.z2) def __add__(self, other): other = self._coerce(other) return Bicomplex(self.z1 + other.z1, self.z2 + other.z2) def __sub__(self, other): other = self._coerce(other) return Bicomplex(self.z1 - other.z1, self.z2 - other.z2) def __rsub__(self, other): return - self.__sub__(other) def __div__(self, other): """elementwise division""" return self * other ** -1 # np.exp(-np.log(other)) __truediv__ = __div__ def __rdiv__(self, other): """elementwise division""" return other * self ** -1 def __mul__(self, other): """elementwise multiplication""" other = self._coerce(other) return Bicomplex(self.z1 * other.z1 - self.z2 * other.z2, self.z1 * other.z2 + self.z2 * other.z1) def _pow_singular(self, other): z1, z2 = self.z1, self.z2 z01 = 0.5 * (z1 - 1j * z2) ** other z02 = 0.5 * (z1 + 1j * z2) ** other return Bicomplex(z01 + z02, (z01 - z02) * 1j) def __pow__(self, other): # TODO: Check correctness out = (self.log()*other).exp() non_invertible = np.abs(self.mod_c()) < 1e-15 if non_invertible.any(): out[non_invertible] = self[non_invertible]._pow_singular(other) return out def __rpow__(self, other): return (np.log(other) * self).exp() __radd__ = __add__ __rmul__ = __mul__ def __len__(self): return len(self.z1) def conjugate(self): return Bicomplex(self.z1, -self.z2) def flat(self, index): return Bicomplex(self.z1.flat[index], self.z2.flat[index]) def dot(self, other): other = self._coerce(other) if self.size == 1 or other.size == 1: return self * other return self.mat2bicomp(self.asarray(self).dot(self.asarray(other).T)) def logaddexp(self, other): other = self._coerce(other) return self + np.log1p(np.exp(other-self)) def logaddexp2(self, other): other = self._coerce(other) return self + np.log2(1+np.exp2(other-self)) def sin(self): z1 = np.cosh(self.z2) * np.sin(self.z1) z2 = np.sinh(self.z2) * np.cos(self.z1) return Bicomplex(z1, z2) def cos(self): z1 = np.cosh(self.z2) * np.cos(self.z1) z2 = -np.sinh(self.z2) * np.sin(self.z1) return Bicomplex(z1, z2) def tan(self): return self.sin() / self.cos() def cot(self): return self.cos() / self.sin() def sec(self): return 1. / self.cos() def csc(self): return 1. / self.sin() def cosh(self): z1 = np.cosh(self.z1) * np.cos(self.z2) z2 = np.sinh(self.z1) * np.sin(self.z2) return Bicomplex(z1, z2) def sinh(self): z1 = np.sinh(self.z1) * np.cos(self.z2) z2 = np.cosh(self.z1) * np.sin(self.z2) return Bicomplex(z1, z2) def tanh(self): return self.sinh() / self.cosh() def coth(self): return self.cosh() / self.sinh() def sech(self): return 1. / self.cosh() def csch(self): return 1. / self.sinh() def exp2(self): return np.exp(self * np.log(2)) def sqrt(self): return self.__pow__(0.5) def log10(self): return self.log()/np.log(10) def log2(self): return self.log()/np.log(2) def log1p(self): return Bicomplex(np.log1p(self.mod_c()), self.arg_c1p()) def expm1(self): expz1 = np.expm1(self.z1) return Bicomplex(expz1 * np.cos(self.z2), expz1 * np.sin(self.z2)) def exp(self): expz1 = np.exp(self.z1) return Bicomplex(expz1 * np.cos(self.z2), expz1 * np.sin(self.z2)) def log(self): mod_c = self.mod_c() # if (mod_c == 0).any(): # raise ValueError('mod_c is zero -> number not invertable!') return Bicomplex(np.log(mod_c + _TINY), self.arg_c()) # def _log_m(self, m=0): # return np.log(self.mod_c() + _TINY) + 1j * \ # (self.arg_c() + 2 * m * np.pi) # # def _log_mn(self, m=0, n=0): # arg_c = self.arg_c() # log_m = np.log(self.mod_c() + _TINY) + 1j * (2 * m * np.pi) # return Bicomplex(log_m, arg_c + 2 * n * np.pi) def arcsin(self): J = Bicomplex(0, 1) return -J * ((J*self + (1-self**2)**0.5).log()) def arccos(self): return np.pi/2 - self.arcsin() def arctan(self): J = Bicomplex(0, 1) arg1, arg2 = 1 - J * self, 1 + J * self tmp = J * (arg1.log() - arg2.log()) * 0.5 return Bicomplex(tmp.z1, tmp.z2) def arccosh(self): return (self + (self**2-1)**0.5).log() def arcsinh(self): return (self + (self**2+1)**0.5).log() def arctanh(self): return 0.5 * (((1+self)/(1-self)).log()) @staticmethod def _arg_c(z1, z2): sign = np.where((z1.real == 0) * (z2.real == 0), 0, np.where(0 <= z2.real, 1, -1)) # clip to avoid nans for complex args arg = z2 / (z1 + _TINY).clip(min=-1e150, max=1e150) arg_c = np.arctan(arg) + sign * np.pi * (z1.real <= 0) return arg_c def arg_c1p(self): z1, z2 = 1+self.z1, self.z2 return self._arg_c(z1, z2) def arg_c(self): return self._arg_c(self.z1, self.z2)
from dcos import (marathon, mesos, http) from shakedown.dcos.command import * from shakedown.dcos.spinner import * from shakedown.dcos import dcos_service_url, dcos_agents_state, master_url from shakedown.dcos.master import get_all_masters from shakedown.dcos.zookeeper import delete_zk_node from dcos.errors import DCOSException, DCOSConnectionError, DCOSHTTPException from urllib.parse import urljoin import json def get_service( service_name, inactive=False, completed=False ): """ Get a dictionary describing a service :param service_name: the service name :type service_name: str :param inactive: whether to include inactive services :type inactive: bool :param completed: whether to include completed services :type completed: bool :return: a dict describing a service :rtype: dict, or None """ services = mesos.get_master().frameworks(inactive=inactive, completed=completed) for service in services: if service['name'] == service_name: return service return None def get_service_framework_id( service_name, inactive=False, completed=False ): """ Get the framework ID for a service :param service_name: the service name :type service_name: str :param inactive: whether to include inactive services :type inactive: bool :param completed: whether to include completed services :type completed: bool :return: a framework id :rtype: str, or None """ service = get_service(service_name, inactive, completed) if service is not None and service['id']: return service['id'] return None def get_service_tasks( service_name, inactive=False, completed=False ): """ Get a list of tasks associated with a service :param service_name: the service name :type service_name: str :param inactive: whether to include inactive services :type inactive: bool :param completed: whether to include completed services :type completed: bool :return: a list of task objects :rtye: [dict], or None """ service = get_service(service_name, inactive, completed) if service is not None and service['tasks']: return service['tasks'] return [] def get_service_task_ids( service_name, task_predicate=None, inactive=False, completed=False ): """ Get a list of task IDs associated with a service :param service_name: the service name :type service_name: str :param task_predicate: filter function which accepts a task object and returns a boolean :type task_predicate: function, or None :param inactive: whether to include inactive services :type inactive: bool :param completed: whether to include completed services :type completed: bool :return: a list of task ids :rtye: [str], or None """ tasks = get_service_tasks(service_name, inactive, completed) if task_predicate: return [t['id'] for t in tasks if task_predicate(t)] else: return [t['id'] for t in tasks] def get_marathon_tasks( inactive=False, completed=False ): """ Get a list of marathon tasks """ return get_service_tasks('marathon', inactive, completed) def get_mesos_tasks(): """ Get a list of mesos tasks """ return mesos.get_master().tasks() def get_service_task( service_name, task_name, inactive=False, completed=False ): """ Get a dictionary describing a service task, or None :param service_name: the service name :type service_name: str :param task_name: the task name :type task_name: str :param inactive: whether to include inactive services :type inactive: bool :param completed: whether to include completed services :type completed: bool :return: a dictionary describing the service :rtye: dict, or None """ service = get_service_tasks(service_name, inactive, completed) if service is not None: for task in service: if task['name'] == task_name: return task return None def get_marathon_task( task_name, inactive=False, completed=False ): """ Get a dictionary describing a named marathon task """ return get_service_task('marathon', task_name, inactive, completed) def get_mesos_task(task_name): """ Get a mesos task with a specific task name """ tasks = get_mesos_tasks() if tasks is not None: for task in tasks: if task['name'] == task_name: return task return None def get_service_ips( service_name, task_name=None, inactive=False, completed=False ): """ Get a set of the IPs associated with a service :param service_name: the service name :type service_name: str :param task_name: the task name :type task_name: str :param inactive: wehther to include inactive services :type inactive: bool :param completed: whether to include completed services :type completed: bool :return: a list of IP addresses :rtype: [str] """ service_tasks = get_service_tasks(service_name, inactive, completed) ips = set([]) for task in service_tasks: if task_name is None or task['name'] == task_name: for status in task['statuses']: # Only the TASK_RUNNING status will have correct IP information. if status["state"] != "TASK_RUNNING": continue for ip in status['container_status']['network_infos'][0]['ip_addresses']: ips.add(ip['ip_address']) return ips def service_healthy(service_name, app_id=None): """ Check whether a named service is healthy :param service_name: the service name :type service_name: str :param app_id: app_id to filter :type app_id: str :return: True if healthy, False otherwise :rtype: bool """ marathon_client = marathon.create_client() apps = marathon_client.get_apps_for_framework(service_name) if apps: for app in apps: if (app_id is not None) and (app['id'] != "/{}".format(str(app_id))): continue if (app['tasksHealthy']) \ and (app['tasksRunning']) \ and (not app['tasksStaged']) \ and (not app['tasksUnhealthy']): return True return False def mesos_task_present_predicate(task_name): return get_mesos_task(task_name) is not None def mesos_task_not_present_predicate(task_name): return get_mesos_task(task_name) is None def wait_for_mesos_task(task_name, timeout_sec=120): return time_wait(lambda: mesos_task_present_predicate(task_name), timeout_seconds=timeout_sec) def wait_for_mesos_task_removal(task_name, timeout_sec=120): return time_wait(lambda: mesos_task_not_present_predicate(task_name), timeout_seconds=timeout_sec) def delete_persistent_data(role, zk_node): """ Deletes any persistent data associated with the specified role, and zk node. :param role: the mesos role to delete, or None to omit this :type role: str :param zk_node: the zookeeper node to be deleted, or None to skip this deletion :type zk_node: str """ if role: destroy_volumes(role) unreserve_resources(role) if zk_node: delete_zk_node(zk_node) def destroy_volumes(role): """ Destroys all volumes on all the slaves in the cluster for the role. """ state = dcos_agents_state() if not state or 'slaves' not in state.keys(): return False all_success = True for agent in state['slaves']: if not destroy_volume(agent, role): all_success = False return all_success def destroy_volume(agent, role): """ Deletes the volumes on the specific agent for the role """ volumes = [] agent_id = agent['id'] reserved_resources_full = agent.get('reserved_resources_full', None) if not reserved_resources_full: # doesn't exist return True reserved_resources = reserved_resources_full.get(role, None) if not reserved_resources: # doesn't exist return True for reserved_resource in reserved_resources: name = reserved_resource.get('name', None) disk = reserved_resource.get('disk', None) if name == 'disk' and disk is not None and 'persistence' in disk: volumes.append(reserved_resource) req_url = urljoin(master_url(), 'destroy-volumes') data = { 'slaveId': agent_id, 'volumes': json.dumps(volumes) } success = False try: response = http.post(req_url, data=data) success = 200 <= response.status_code < 300 if response.status_code == 409: # thoughts on what to do here? throw exception # i would rather not print print('''###\nIs a framework using these resources still installed?\n###''') except DCOSHTTPException as e: print("HTTP {}: Unabled to delete volume based on: {}".format( e.response.status_code, e.response.text)) return success def unreserve_resources(role): """ Unreserves all the resources for all the slaves for the role. """ state = dcos_agents_state() if not state or 'slaves' not in state.keys(): return False all_success = True for agent in state['slaves']: if not unreserve_resource(agent, role): all_success = False return all_success def unreserve_resource(agent, role): """ Unreserves all the resources for the role on the agent. """ resources = [] agent_id = agent['id'] reserved_resources_full = agent.get('reserved_resources_full', None) if not reserved_resources_full: # doesn't exist return True reserved_resources = reserved_resources_full.get(role, None) if not reserved_resources: # doesn't exist return True for reserved_resource in reserved_resources: resources.append(reserved_resource) req_url = urljoin(master_url(), 'unreserve') data = { 'slaveId': agent_id, 'resources': json.dumps(resources) } success = False try: response = http.post(req_url, data=data) success = 200 <= response.status_code < 300 except DCOSHTTPException as e: print("HTTP {}: Unabled to unreserve resources based on: {}".format( e.response.status_code, e.response.text)) return success def service_available_predicate(service_name): url = dcos_service_url(service_name) try: response = http.get(url) return response.status_code == 200 except Exception as e: return False def service_unavailable_predicate(service_name): url = dcos_service_url(service_name) try: response = http.get(url) except DCOSHTTPException as e: if e.response.status_code == 500: return True else: return False def wait_for_service_endpoint(service_name, timeout_sec=120): """Checks the service url if available it returns true, on expiration it returns false""" master_count = len(get_all_masters()) return time_wait(lambda: service_available_predicate(service_name), timeout_seconds=timeout_sec, required_consecutive_success_count=master_count) def wait_for_service_endpoint_removal(service_name, timeout_sec=120): """Checks the service url if it is removed it returns true, on expiration it returns false""" return time_wait(lambda: service_unavailable_predicate(service_name), timeout_seconds=timeout_sec) def task_states_predicate(service_name, expected_task_count, expected_task_states): """ Returns whether the provided service_names's tasks have expected_task_count tasks in any of expected_task_states. For example, if service 'foo' has 5 tasks which are TASK_STAGING or TASK_RUNNING. :param service_name: the service name :type service_name: str :param expected_task_count: the number of tasks which should have an expected state :type expected_task_count: int :param expected_task_states: the list states to search for among the service's tasks :type expected_task_states: [str] :return: True if expected_task_count tasks have any of expected_task_states, False otherwise :rtype: bool """ try: tasks = get_service_tasks(service_name) except (DCOSConnectionError, DCOSHTTPException): tasks = [] matching_tasks = [] other_tasks = [] for t in tasks: name = t.get('name', 'UNKNOWN_NAME') state = t.get('state', None) if state and state in expected_task_states: matching_tasks.append(name) else: other_tasks.append('{}={}'.format(name, state)) print('expected {} tasks in {}:\n- {} in expected {}: {}\n- {} in other states: {}'.format( expected_task_count, ', '.join(expected_task_states), len(matching_tasks), ', '.join(expected_task_states), ', '.join(matching_tasks), len(other_tasks), ', '.join(other_tasks))) return len(matching_tasks) >= expected_task_count def wait_for_service_tasks_state( service_name, expected_task_count, expected_task_states, timeout_sec=120 ): """ Returns once the service has at least N tasks in one of the specified state(s) :param service_name: the service name :type service_name: str :param expected_task_count: the expected number of tasks in the specified state(s) :type expected_task_count: int :param expected_task_states: the expected state(s) for tasks to be in, e.g. 'TASK_RUNNING' :type expected_task_states: [str] :param timeout_sec: duration to wait :type timeout_sec: int :return: the duration waited in seconds :rtype: int """ return time_wait( lambda: task_states_predicate(service_name, expected_task_count, expected_task_states), timeout_seconds=timeout_sec) def wait_for_service_tasks_running( service_name, expected_task_count, timeout_sec=120 ): """ Returns once the service has at least N running tasks :param service_name: the service name :type service_name: str :param expected_task_count: the expected number of running tasks :type expected_task_count: int :param timeout_sec: duration to wait :type timeout_sec: int :return: the duration waited in seconds :rtype: int """ return wait_for_service_tasks_state(service_name, expected_task_count, ['TASK_RUNNING'], timeout_sec) def tasks_all_replaced_predicate( service_name, old_task_ids, task_predicate=None ): """ Returns whether ALL of old_task_ids have been replaced with new tasks :param service_name: the service name :type service_name: str :param old_task_ids: list of original task ids as returned by get_service_task_ids :type old_task_ids: [str] :param task_predicate: filter to use when searching for tasks :type task_predicate: func :return: True if none of old_task_ids are still present in the service :rtype: bool """ try: task_ids = get_service_task_ids(service_name, task_predicate) except DCOSHTTPException: print('failed to get task ids for service {}'.format(service_name)) task_ids = [] print('waiting for all task ids in "{}" to change:\n- old tasks: {}\n- current tasks: {}'.format( service_name, old_task_ids, task_ids)) for id in task_ids: if id in old_task_ids: return False # old task still present if len(task_ids) < len(old_task_ids): # new tasks haven't fully replaced old tasks return False return True def tasks_missing_predicate( service_name, old_task_ids, task_predicate=None ): """ Returns whether any of old_task_ids are no longer present :param service_name: the service name :type service_name: str :param old_task_ids: list of original task ids as returned by get_service_task_ids :type old_task_ids: [str] :param task_predicate: filter to use when searching for tasks :type task_predicate: func :return: True if any of old_task_ids are no longer present in the service :rtype: bool """ try: task_ids = get_service_task_ids(service_name, task_predicate) except DCOSHTTPException: print('failed to get task ids for service {}'.format(service_name)) task_ids = [] print('checking whether old tasks in "{}" are missing:\n- old tasks: {}\n- current tasks: {}'.format( service_name, old_task_ids, task_ids)) for id in old_task_ids: if id not in task_ids: return True # an old task was not present return False def wait_for_service_tasks_all_changed( service_name, old_task_ids, task_predicate=None, timeout_sec=120 ): """ Returns once ALL of old_task_ids have been replaced with new tasks :param service_name: the service name :type service_name: str :param old_task_ids: list of original task ids as returned by get_service_task_ids :type old_task_ids: [str] :param task_predicate: filter to use when searching for tasks :type task_predicate: func :param timeout_sec: duration to wait :type timeout_sec: int :return: the duration waited in seconds :rtype: int """ return time_wait( lambda: tasks_all_replaced_predicate(service_name, old_task_ids, task_predicate), timeout_seconds=timeout_sec) def wait_for_service_tasks_all_unchanged( service_name, old_task_ids, task_predicate=None, timeout_sec=30 ): """ Returns after verifying that NONE of old_task_ids have been removed or replaced from the service :param service_name: the service name :type service_name: str :param old_task_ids: list of original task ids as returned by get_service_task_ids :type old_task_ids: [str] :param task_predicate: filter to use when searching for tasks :type task_predicate: func :param timeout_sec: duration to wait until assuming tasks are unchanged :type timeout_sec: int :return: the duration waited in seconds (the timeout value) :rtype: int """ try: time_wait( lambda: tasks_missing_predicate(service_name, old_task_ids, task_predicate), timeout_seconds=timeout_sec) # shouldn't have exited successfully: raise below except TimeoutExpired: return timeout_sec # no changes occurred within timeout, as expected raise DCOSException("One or more of the following tasks were no longer found: {}".format(old_task_ids))
import React, { Component } from 'react'; import TextField from 'material-ui/TextField'; import fav from '../../assets/fav.png'; import favAdd from '../../assets/favAdd.png'; import RaisedButton from 'material-ui/RaisedButton'; import { getRoom, getPath, getAuthInfo, checkFavorites, addFavorite, removeFavorite } from '../../utils/communication-manager'; import { getCookie } from '../../utils/cookie-handler'; import { SESSION_COOKIE_NAME } from '../../constants/configuration'; import { updateAuthInfo } from '../../utils/authentication'; class Search extends Component { constructor(props) { super(props); this.state = { currentLocation: "", searchInput: "", inputErrorText: "", currentInputErrorText: "", errorMessage: "", showSecond: false, showFav: false, showFavAdd: false, label: "+" } } componentWillReceiveProps(nextProps) { console.log("favoriteButton"); if (nextProps.authentication.isLoggedIn) { this.setState({ showFav: true }); } else { this.setState({ showFav: false }); } } handleInputChange = (event) => { this.setState({ [event.target.name]: event.target.value, inputErrorText: event.target.name === "searchInput" ? "" : this.state.inputErrorText, currentInputErrorText: event.target.name === "currentLocation" ? "" : this.state.currentInputErrorText }); } handleSubmit = (e) => { e.preventDefault(); this.props.removeAllLines(); this.props.clearMarker(); if (this.state.searchInput === "") { this.setState({ inputErrorText: "This field is required." }); } else { if (!this.state.showSecond) { getRoom(this.state.searchInput).then((roomData) => { this.setState({ errorData: undefined }); let coordinates = roomData.coordinates.split(','); this.props.updateMarker(coordinates[0], coordinates[1]); checkFavorites(getCookie(SESSION_COOKIE_NAME)).then((response) => { console.log(response); if (!response.length) { return; } console.log(roomData); if (response.map(f => f.code).indexOf(roomData.name) >= 0) { this.setState({ showFavAdd: true }); } }).catch((error) => { this.setState({ errorData: error.message }); }); }).catch((error) => { this.setState({ errorData: error.message }); }); } else if (this.state.currentLocation === "") { this.setState({ currentInputErrorText: "This field is required." }); } else { getPath(this.state.currentLocation, this.state.searchInput, getCookie(SESSION_COOKIE_NAME)).then((pathData) => { let new_coord = pathData.path.map(path => path.coordinate); for (let i = 1; i < new_coord.length; i++) { let ori_coord = new_coord[i - 1].split(','); let dest_coord = new_coord[i].split(','); this.props.createLine( ori_coord[0], ori_coord[1], dest_coord[0], dest_coord[1] ); } }).catch((error) => { this.setState({ errorData: error.message }); }); } } } showSecond = (e) => { e.preventDefault(); if (this.state.label === '-') { this.setState({ label: "+", currentLocation: "", showSecond: !this.state.showSecond, showFav: true }); } else { this.setState({ label: "-", showSecond: !this.state.showSecond, showFav: false }); } } addFav = (e) => { e.preventDefault(); addFavorite(this.state.searchInput, getCookie(SESSION_COOKIE_NAME)) .then((response) => { this.setState({ showFavAdd: true }); }).catch((error) => { this.setState({ errorData: error.message }); }); } removeFav = (e) => { e.preventDefault(); removeFavorite(this.state.searchInput, getCookie(SESSION_COOKIE_NAME)) .then((response) => { this.setState({ showFavAdd: false }); }).catch((error) => { this.setState({ errorData: error.message }); }); } render() { return ( <div id="searchBar"> { this.state.showSecond && <TextField name="currentLocation" value={this.state.currentLocation.toUpperCase()} hintText="current location" errorText={this.state.currentInputErrorText} onChange={this.handleInputChange} className="searchInput" /> } <TextField name="searchInput" value={this.state.searchInput.toUpperCase()} hintText="Search for a POI" errorText={this.state.inputErrorText} onChange={this.handleInputChange} className="searchInput" /> <RaisedButton label={this.state.label} primary={true} className="navigationButton" onClick={this.showSecond} /> { this.state.showFav && <img className="fav" alt="fav" src={this.state.showFav ? this.state.showFavAdd ? favAdd : fav : ''} onClick={this.state.showFav ? this.state.showFavAdd ? this.removeFav : this.addFav : ''} /> } <RaisedButton label="GO" primary={true} className="searchButton" onClick={this.handleSubmit} /> { this.state.errorData !== undefined && <div> {this.state.errorData} </div> } </div> ); } } export default Search;
define(["@jupyter-widgets/base"], function(__WEBPACK_EXTERNAL_MODULE_3__) { return /******/ (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, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = 1); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports) { module.exports = {"name":"tensorflow_model_analysis","version":"0.22.0dev","homepage":"https://github.com/tensorflow/model-analysis","bugs":"https://github.com/tensorflow/model-analysis/issues","license":"Apache-2.0","repository":{"type":"git","url":"https://github.com/tensorflow/model-analysis.git"},"main":"lib/index.js","files":["lib/**/*.js","dist/*.js","README.md","LICENSE"],"scripts":{"clean":"rimraf dist/","prepare":"webpack && ./collect-files-before-publish.sh","test":"echo \"Error: no test specified\" && exit 1"},"devDependencies":{"webpack":"^3.5.5","rimraf":"^2.6.1"},"dependencies":{"@jupyter-widgets/base":"^1.0.0","lodash":"^4.17.4"}} /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Entry point for the notebook bundle containing custom model definitions. // // Setup notebook base URL // // Some static assets may be required by the custom widget javascript. The base // url for the notebook is not known at build time and is therefore computed // dynamically. __webpack_require__.p = document.querySelector('body').getAttribute('data-base-url') + 'nbextensions/tensorflow_model_analysis/'; // Export widget models and views, and the npm package version number. module.exports = __webpack_require__(2); module.exports['version'] = __webpack_require__(0).version; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { /** * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const widgets = __webpack_require__(3); const _ = __webpack_require__(4); const version = __webpack_require__(0).version; /** * Helper method to load the vulcanized templates. */ function loadVulcanizedTemplate() { const templateLocation = __webpack_require__.p + 'vulcanized_tfma.js'; // If the vulcanizes tempalets are not loaded yet, load it now. if (!document.querySelector('script[src="' + templateLocation + '"]')) { const script = document.createElement('script'); script.setAttribute('src', templateLocation); document.head.appendChild(script); } } /** * HACK: Calls the render callback in a setTimeout. This delay avoids some * rendering artifacts. * @param {!Function} cb */ function delayedRender(cb) { setTimeout(cb, 0); } const MODULE_NAME = 'tensorflow_model_analysis'; const MODEL_VERSION = version; const VIEW_VERSION = version; const SLICING_METRICS_MODEL_NAME = 'SlicingMetricsModel'; const SLICING_METRICS_VIEW_NAME = 'SlicingMetricsView'; const SLICING_METRICS_ELEMENT_NAME = 'tfma-nb-slicing-metrics'; const TIME_SERIES_MODEL_NAME = 'TimeSeriesModel'; const TIME_SERIES_VIEW_NAME = 'TimeSeriesView'; const TIME_SERIES_ELEMENT_NAME = 'tfma-nb-time-series'; const PLOT_MODEL_NAME = 'PlotModel'; const PLOT_VIEW_NAME = 'PlotView'; const PLOT_ELEMENT_NAME = 'tfma-nb-plot'; const FAIRNESS_INDICATOR_MODEL_NAME = 'FairnessIndicatorModel'; const FAIRNESS_INDICATOR_VIEW_NAME = 'FairnessIndicatorView'; const FAIRNESS_INDICATOR_ELEMENT_NAME = 'fairness-nb-container'; const SlicingMetricsModel = widgets.DOMWidgetModel.extend({ defaults: _.extend(widgets.DOMWidgetModel.prototype.defaults(), { _model_name: SLICING_METRICS_MODEL_NAME, _view_name: SLICING_METRICS_VIEW_NAME, _model_module: MODULE_NAME, _view_module: MODULE_NAME, _model_module_version: MODEL_VERSION, _view_module_version: VIEW_VERSION, config: {}, data: [], js_events: [], }) }); const SlicingMetricsView = widgets.DOMWidgetView.extend({ render: function() { loadVulcanizedTemplate(); this.view_ = document.createElement(SLICING_METRICS_ELEMENT_NAME); this.el.appendChild(this.view_); this.view_.addEventListener('tfma-event', (e) => { handleTfmaEvent(e, this); }); delayedRender(() => { this.configChanged_(); this.dataChanged_(); this.model.on('change:config', this.configChanged_, this); this.model.on('change:data', this.dataChanged_, this); }); }, dataChanged_: function() { this.view_.data = this.model.get('data'); }, configChanged_: function() { this.view_.config = this.model.get('config'); }, }); const TimeSeriesModel = widgets.DOMWidgetModel.extend({ defaults: _.extend(widgets.DOMWidgetModel.prototype.defaults(), { _model_name: TIME_SERIES_MODEL_NAME, _view_name: TIME_SERIES_VIEW_NAME, _model_module: MODULE_NAME, _view_module: MODULE_NAME, _model_module_version: MODEL_VERSION, _view_module_version: VIEW_VERSION, config: {}, data: [], }) }); const TimeSeriesView = widgets.DOMWidgetView.extend({ render: function() { loadVulcanizedTemplate(); this.view_ = document.createElement(TIME_SERIES_ELEMENT_NAME); this.el.appendChild(this.view_); delayedRender(() => { this.configChanged_(); this.dataChanged_(); this.model.on('change:config', this.configChanged_, this); this.model.on('change:data', this.dataChanged_, this); }); }, dataChanged_: function() { this.view_.data = this.model.get('data'); }, configChanged_: function() { this.view_.config = this.model.get('config'); }, }); const PlotModel = widgets.DOMWidgetModel.extend({ defaults: _.extend(widgets.DOMWidgetModel.prototype.defaults(), { _model_name: PLOT_MODEL_NAME, _view_name: PLOT_VIEW_NAME, _model_module: MODULE_NAME, _view_module: MODULE_NAME, _model_module_version: MODEL_VERSION, _view_module_version: VIEW_VERSION, config: {}, data: [], }) }); const PlotView = widgets.DOMWidgetView.extend({ render: function() { loadVulcanizedTemplate(); this.view_ = document.createElement(PLOT_ELEMENT_NAME); this.el.appendChild(this.view_); delayedRender(() => { this.configChanged_(); this.dataChanged_(); this.model.on('change:config', this.configChanged_, this); this.model.on('change:data', this.dataChanged_, this); }); }, dataChanged_: function() { this.view_.data = this.model.get('data'); }, configChanged_: function() { this.view_.config = this.model.get('config'); }, }); const FairnessIndicatorModel = widgets.DOMWidgetModel.extend({ defaults: _.extend(widgets.DOMWidgetModel.prototype.defaults(), { _model_name: FAIRNESS_INDICATOR_MODEL_NAME, _view_name: FAIRNESS_INDICATOR_VIEW_NAME, _model_module: MODULE_NAME, _view_module: MODULE_NAME, _model_module_version: MODEL_VERSION, _view_module_version: VIEW_VERSION, slicingMetrics: [], slicingMetricsCompare: [], evalName: '', evalNameCompare: '', js_events: [], }) }); const FairnessIndicatorView = widgets.DOMWidgetView.extend({ render: function() { loadVulcanizedTemplate(); this.view_ = document.createElement(FAIRNESS_INDICATOR_ELEMENT_NAME); this.el.appendChild(this.view_); this.view_.addEventListener('tfma-event', (e) => { handleTfmaEvent(e, this); }); delayedRender(() => { this.slicingMetricsChanged_(); this.slicingMetricsCompareChanged_(); this.evalNameChanged_(); this.evalNameCompareChanged_(); this.model.on('change:slicingMetrics', this.slicingMetricsChanged_, this); this.model.on( 'change:slicingMetricsCompare', this.slicingMetricsCompareChanged_, this); this.model.on('change:evalName', this.evalNameChanged_, this); this.model.on( 'change:evalNameCompare', this.evalNameCompareChanged_, this); }); }, slicingMetricsChanged_: function() { this.view_.slicingMetrics = this.model.get('slicingMetrics'); }, slicingMetricsCompareChanged_: function() { this.view_.slicingMetricsCompare = this.model.get('slicingMetricsCompare'); }, evalNameChanged_: function() { this.view_.evalName = this.model.get('evalName'); }, evalNameCompareChanged_: function() { this.view_.evalNameCompare = this.model.get('evalNameCompare'); }, }); /** * Handler for events of type "tfma-event" for the given view element. * @param {!Event} tfmaEvent * @param {!Element} view */ const handleTfmaEvent = (tfmaEvent, view) => { const model = view.model; const jsEvents = model.get('js_events').slice(); const detail = tfmaEvent.detail; jsEvents.push({'name': detail.type, 'detail': detail.detail}); model.set('js_events', jsEvents); view.touch(); }; module.exports = { [PLOT_MODEL_NAME]: PlotModel, [PLOT_VIEW_NAME]: PlotView, [SLICING_METRICS_MODEL_NAME]: SlicingMetricsModel, [SLICING_METRICS_VIEW_NAME]: SlicingMetricsView, [TIME_SERIES_MODEL_NAME]: TimeSeriesModel, [TIME_SERIES_VIEW_NAME]: TimeSeriesView, [FAIRNESS_INDICATOR_MODEL_NAME]: FairnessIndicatorModel, [FAIRNESS_INDICATOR_VIEW_NAME]: FairnessIndicatorView, }; /***/ }), /* 3 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_3__; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, module) {var __WEBPACK_AMD_DEFINE_RESULT__;/** * @license * Lodash <https://lodash.com/> * Copyright OpenJS Foundation and other contributors <https://openjsf.org/> * Released under MIT license <https://lodash.com/license> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ ;(function() { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** Used as the semantic version number. */ var VERSION = '4.17.15'; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Error message constants. */ var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', FUNC_ERROR_TEXT = 'Expected a function'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used as default options for `_.truncate`. */ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = '...'; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /** Used to indicate the type of lazy iteratees. */ var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e+308, NAN = 0 / 0; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', asyncTag = '[object AsyncFunction]', boolTag = '[object Boolean]', dateTag = '[object Date]', domExcTag = '[object DOMException]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', nullTag = '[object Null]', objectTag = '[object Object]', promiseTag = '[object Promise]', proxyTag = '[object Proxy]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', undefinedTag = '[object Undefined]', weakMapTag = '[object WeakMap]', weakSetTag = '[object WeakSet]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to match empty string literals in compiled template source. */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** Used to match HTML entities and HTML characters. */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); /** Used to match template delimiters. */ var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g, reTrimStart = /^\s+/, reTrimEnd = /\s+$/; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** Used to match words composed of alphanumeric characters. */ var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Used to match * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to match Latin Unicode letters (excluding mathematical operators). */ var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; /** Used to ensure capturing order of template delimiters. */ var reNoMatch = /($^)/; /** Used to match unescaped characters in compiled string literals. */ var reUnescapedString = /['\n\r\u2028\u2029\\]/g; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = '\\u2700-\\u27bf', rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', rsPunctuationRange = '\\u2000-\\u206f', rsSpaceRange = ' \\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', rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', rsVarRange = '\\ufe0e\\ufe0f', rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; /** Used to compose unicode capture groups. */ var rsApos = "['\u2019]", rsAstral = '[' + rsAstralRange + ']', rsBreak = '[' + rsBreakRange + ']', rsCombo = '[' + rsComboRange + ']', rsDigits = '\\d+', rsDingbat = '[' + rsDingbatRange + ']', rsLower = '[' + rsLowerRange + ']', rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsUpper = '[' + rsUpperRange + ']', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match apostrophes. */ var reApos = RegExp(rsApos, 'g'); /** * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). */ var reComboMark = RegExp(rsCombo, 'g'); /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** Used to match complex or compound words. */ var reUnicodeWord = RegExp([ rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, rsUpper + '+' + rsOptContrUpper, rsOrdUpper, rsOrdLower, rsDigits, rsEmoji ].join('|'), 'g'); /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** Used to detect strings that need a more robust regexp to match words. */ var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; /** Used to assign default `context` object properties. */ var contextProps = [ 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' ]; /** Used to make template sourceURLs easier to identify. */ var templateCounter = -1; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** Used to map Latin Unicode letters to basic Latin letters. */ var deburredLetters = { // Latin-1 Supplement block. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', '\xc7': 'C', '\xe7': 'c', '\xd0': 'D', '\xf0': 'd', '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', '\xd1': 'N', '\xf1': 'n', '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', '\xc6': 'Ae', '\xe6': 'ae', '\xde': 'Th', '\xfe': 'th', '\xdf': 'ss', // Latin Extended-A block. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', '\u0134': 'J', '\u0135': 'j', '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', '\u0163': 't', '\u0165': 't', '\u0167': 't', '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', '\u0174': 'W', '\u0175': 'w', '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', '\u0132': 'IJ', '\u0133': 'ij', '\u0152': 'Oe', '\u0153': 'oe', '\u0149': "'n", '\u017f': 's' }; /** Used to map characters to HTML entities. */ var htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }; /** Used to map HTML entities to characters. */ var htmlUnescapes = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'" }; /** Used to escape characters for inclusion in compiled string literals. */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Built-in method references without a dependency on `root`. */ var freeParseFloat = parseFloat, freeParseInt = parseInt; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { // Use `util.types` for Node.js 10+. var types = freeModule && freeModule.require && freeModule.require('util').types; if (types) { return types; } // Legacy `process.binding('util')` for Node.js < 10. return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /*--------------------------------------------------------------------------*/ /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } /** * A specialized version of `baseAggregator` for arrays. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array); } return accumulator; } /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * A specialized version of `_.forEachRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEachRight(array, iteratee) { var length = array == null ? 0 : array.length; while (length--) { if (iteratee(array[length], length, array) === false) { break; } } return array; } /** * A specialized version of `_.every` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. */ function arrayEvery(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (!predicate(array[index], index, array)) { return false; } } return true; } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * A specialized version of `_.reduceRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the last element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduceRight(array, iteratee, accumulator, initAccum) { var length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[--length]; } while (length--) { accumulator = iteratee(accumulator, array[length], length, array); } return accumulator; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * Gets the size of an ASCII `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ var asciiSize = baseProperty('length'); /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } /** * Splits an ASCII `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function asciiWords(string) { return string.match(reAsciiWord) || []; } /** * The base implementation of methods like `_.findKey` and `_.findLastKey`, * without support for iteratee shorthands, which iterates over `collection` * using `eachFunc`. * * @private * @param {Array|Object} collection The collection to inspect. * @param {Function} predicate The function invoked per iteration. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the found element or its key, else `undefined`. */ function baseFindKey(collection, predicate, eachFunc) { var result; eachFunc(collection, function(value, key, collection) { if (predicate(value, key, collection)) { result = key; return false; } }); return result; } /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } /** * This function is like `baseIndexOf` except that it accepts a comparator. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @param {Function} comparator The comparator invoked per element. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOfWith(array, value, fromIndex, comparator) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (comparator(array[index], value)) { return index; } } return -1; } /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } /** * The base implementation of `_.mean` and `_.meanBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the mean. */ function baseMean(array, iteratee) { var length = array == null ? 0 : array.length; return length ? (baseSum(array, iteratee) / length) : NAN; } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.propertyOf` without support for deep paths. * * @private * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. */ function basePropertyOf(object) { return function(key) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array * of key-value pairs for `object` corresponding to the property names of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the key-value pairs. */ function baseToPairs(object, props) { return arrayMap(props, function(key) { return [key, object[key]]; }); } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } /** * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A * letters to basic Latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. */ var deburrLetter = basePropertyOf(deburredLetters); /** * Used by `_.escape` to convert characters to HTML entities. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ var escapeHtmlChar = basePropertyOf(htmlEscapes); /** * Used by `_.template` to escape characters for inclusion in compiled string literals. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(chr) { return '\\' + stringEscapes[chr]; } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } /** * Checks if `string` contains a word composed of Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a word is found, else `false`. */ function hasUnicodeWord(string) { return reHasUnicodeWord.test(string); } /** * Converts `iterator` to an array. * * @private * @param {Object} iterator The iterator to convert. * @returns {Array} Returns the converted array. */ function iteratorToArray(iterator) { var data, result = []; while (!(data = iterator.next()).done) { result.push(data.value); } return result; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** * Converts `set` to its value-value pairs. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the value-value pairs. */ function setToPairs(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = [value, value]; }); return result; } /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * A specialized version of `_.lastIndexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictLastIndexOf(array, value, fromIndex) { var index = fromIndex + 1; while (index--) { if (array[index] === value) { return index; } } return index; } /** * Gets the number of symbols in `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the string size. */ function stringSize(string) { return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); } /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } /** * Used by `_.unescape` to convert HTML entities to characters. * * @private * @param {string} chr The matched character to unescape. * @returns {string} Returns the unescaped character. */ var unescapeHtmlChar = basePropertyOf(htmlUnescapes); /** * Gets the size of a Unicode `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ function unicodeSize(string) { var result = reUnicode.lastIndex = 0; while (reUnicode.test(string)) { ++result; } return result; } /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } /** * Splits a Unicode `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function unicodeWords(string) { return string.match(reUnicodeWord) || []; } /*--------------------------------------------------------------------------*/ /** * Create a new pristine `lodash` function using the `context` object. * * @static * @memberOf _ * @since 1.1.0 * @category Util * @param {Object} [context=root] The context object. * @returns {Function} Returns a new `lodash` function. * @example * * _.mixin({ 'foo': _.constant('foo') }); * * var lodash = _.runInContext(); * lodash.mixin({ 'bar': lodash.constant('bar') }); * * _.isFunction(_.foo); * // => true * _.isFunction(_.bar); * // => false * * lodash.isFunction(lodash.foo); * // => false * lodash.isFunction(lodash.bar); * // => true * * // Create a suped-up `defer` in Node.js. * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; */ var runInContext = (function runInContext(context) { context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); /** Built-in constructor references. */ var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = context['__core-js_shared__']; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to generate unique IDs. */ var idCounter = 0; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** Used to restore the original `_` reference in `_.noConflict`. */ var oldDash = root._; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? context.Buffer : undefined, Symbol = context.Symbol, Uint8Array = context.Uint8Array, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, getPrototype = overArg(Object.getPrototypeOf, Object), objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, symIterator = Symbol ? Symbol.iterator : undefined, symToStringTag = Symbol ? Symbol.toStringTag : undefined; var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); /** Mocked built-ins. */ var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date && Date.now !== root.Date.now && Date.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max, nativeMin = Math.min, nativeNow = Date.now, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReverse = arrayProto.reverse; /* Built-in method references that are verified to be native. */ var DataView = getNative(context, 'DataView'), Map = getNative(context, 'Map'), Promise = getNative(context, 'Promise'), Set = getNative(context, 'Set'), WeakMap = getNative(context, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; /** Used to lookup unminified function names. */ var realNames = {}; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /*------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } /** * By default, the template delimiters used by lodash are like those in * embedded Ruby (ERB) as well as ES2015 template strings. Change the * following template settings to use alternative delimiters. * * @static * @memberOf _ * @type {Object} */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type {RegExp} */ 'escape': reEscape, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type {RegExp} */ 'evaluate': reEvaluate, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type {RegExp} */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type {string} */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type {Object} */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type {Function} */ '_': lodash } }; // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; /*------------------------------------------------------------------------*/ /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } /** * Creates a clone of the lazy wrapper object. * * @private * @name clone * @memberOf LazyWrapper * @returns {Object} Returns the cloned `LazyWrapper` object. */ function lazyClone() { var result = new LazyWrapper(this.__wrapped__); result.__actions__ = copyArray(this.__actions__); result.__dir__ = this.__dir__; result.__filtered__ = this.__filtered__; result.__iteratees__ = copyArray(this.__iteratees__); result.__takeCount__ = this.__takeCount__; result.__views__ = copyArray(this.__views__); return result; } /** * Reverses the direction of lazy iteration. * * @private * @name reverse * @memberOf LazyWrapper * @returns {Object} Returns the new reversed `LazyWrapper` object. */ function lazyReverse() { if (this.__filtered__) { var result = new LazyWrapper(this); result.__dir__ = -1; result.__filtered__ = true; } else { result = this.clone(); result.__dir__ *= -1; } return result; } /** * Extracts the unwrapped value from its lazy wrapper. * * @private * @name value * @memberOf LazyWrapper * @returns {*} Returns the unwrapped value. */ function lazyValue() { var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : (start - 1), iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); if (!isArr || (!isRight && arrLength == length && takeCount == length)) { return baseWrapperValue(array, this.__actions__); } var result = []; outer: while (length-- && resIndex < takeCount) { index += dir; var iterIndex = -1, value = array[index]; while (++iterIndex < iterLength) { var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type, computed = iteratee(value); if (type == LAZY_MAP_FLAG) { value = computed; } else if (!computed) { if (type == LAZY_FILTER_FLAG) { continue outer; } else { break outer; } } } result[resIndex++] = value; } return result; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; /*------------------------------------------------------------------------*/ /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /*------------------------------------------------------------------------*/ /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /*------------------------------------------------------------------------*/ /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /*------------------------------------------------------------------------*/ /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /*------------------------------------------------------------------------*/ /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /*------------------------------------------------------------------------*/ /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } /** * A specialized version of `_.sample` for arrays. * * @private * @param {Array} array The array to sample. * @returns {*} Returns the random element. */ function arraySample(array) { var length = array.length; return length ? array[baseRandom(0, length - 1)] : undefined; } /** * A specialized version of `_.sampleSize` for arrays. * * @private * @param {Array} array The array to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function arraySampleSize(array, n) { return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); } /** * A specialized version of `_.shuffle` for arrays. * * @private * @param {Array} array The array to shuffle. * @returns {Array} Returns the new shuffled array. */ function arrayShuffle(array) { return shuffleSelf(copyArray(array)); } /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq(object[key], value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * Aggregates elements of `collection` on `accumulator` with keys transformed * by `iteratee` and values set by `setter`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function baseAggregator(collection, setter, iteratee, accumulator) { baseEach(collection, function(value, key, collection) { setter(accumulator, value, iteratee(value), collection); }); return accumulator; } /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } /** * The base implementation of `_.at` without support for individual paths. * * @private * @param {Object} object The object to iterate over. * @param {string[]} paths The property paths to pick. * @returns {Array} Returns the picked elements. */ function baseAt(object, paths) { var index = -1, length = paths.length, result = Array(length), skip = object == null; while (++index < length) { result[index] = skip ? undefined : get(object, paths[index]); } return result; } /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet(value)) { value.forEach(function(subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); } else if (isMap(value)) { value.forEach(function(subValue, key) { result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); } var keysFunc = isFull ? (isFlat ? getAllKeysIn : getAllKeys) : (isFlat ? keysIn : keys); var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } /** * The base implementation of `_.conforms` which doesn't clone `source`. * * @private * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. */ function baseConforms(source) { var props = keys(source); return function(object) { return baseConformsTo(object, source, props); }; } /** * The base implementation of `_.conformsTo` which accepts `props` to check. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. */ function baseConformsTo(object, source, props) { var length = props.length; if (object == null) { return !length; } object = Object(object); while (length--) { var key = props[length], predicate = source[key], value = object[key]; if ((value === undefined && !(key in object)) || !predicate(value)) { return false; } } return true; } /** * The base implementation of `_.delay` and `_.defer` which accepts `args` * to provide to `func`. * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {Array} args The arguments to provide to `func`. * @returns {number|Object} Returns the timer id or timeout object. */ function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * The base implementation of `_.forEachRight` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEachRight = createBaseEach(baseForOwnRight, true); /** * The base implementation of `_.every` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false` */ function baseEvery(collection, predicate) { var result = true; baseEach(collection, function(value, index, collection) { result = !!predicate(value, index, collection); return result; }); return result; } /** * The base implementation of methods like `_.max` and `_.min` which accepts a * `comparator` to determine the extremum value. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The iteratee invoked per iteration. * @param {Function} comparator The comparator used to compare values. * @returns {*} Returns the extremum value. */ function baseExtremum(array, iteratee, comparator) { var index = -1, length = array.length; while (++index < length) { var value = array[index], current = iteratee(value); if (current != null && (computed === undefined ? (current === current && !isSymbol(current)) : comparator(current, computed) )) { var computed = current, result = value; } } return result; } /** * The base implementation of `_.fill` without an iteratee call guard. * * @private * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. */ function baseFill(array, value, start, end) { var length = array.length; start = toInteger(start); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : toInteger(end); if (end < 0) { end += length; } end = start > end ? 0 : toLength(end); while (start < end) { array[start++] = value; } return array; } /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * This function is like `baseFor` except that it iterates over properties * in the opposite order. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseForRight = createBaseFor(true); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } /** * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwnRight(object, iteratee) { return object && baseForRight(object, iteratee, keys); } /** * The base implementation of `_.functions` which creates an array of * `object` function property names filtered from `props`. * * @private * @param {Object} object The object to inspect. * @param {Array} props The property names to filter. * @returns {Array} Returns the function names. */ function baseFunctions(object, props) { return arrayFilter(props, function(key) { return isFunction(object[key]); }); } /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } /** * The base implementation of `_.gt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. */ function baseGt(value, other) { return value > other; } /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key); } /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } /** * The base implementation of `_.inRange` which doesn't coerce arguments. * * @private * @param {number} number The number to check. * @param {number} start The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. */ function baseInRange(number, start, end) { return number >= nativeMin(start, end) && number < nativeMax(start, end); } /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } /** * The base implementation of `_.invoke` without support for individual * method arguments. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {Array} args The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. */ function baseInvoke(object, path, args) { path = castPath(path, object); object = parent(object, path); var func = object == null ? object : object[toKey(last(path))]; return func == null ? undefined : apply(func, object, args); } /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** * The base implementation of `_.isArrayBuffer` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. */ function baseIsArrayBuffer(value) { return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; } /** * The base implementation of `_.isDate` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. */ function baseIsDate(value) { return isObjectLike(value) && baseGetTag(value) == dateTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike(value) && getTag(value) == mapTag; } /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isRegExp` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ function baseIsRegExp(value) { return isObjectLike(value) && baseGetTag(value) == regexpTag; } /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike(value) && getTag(value) == setTag; } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } /** * The base implementation of `_.lt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. */ function baseLt(value, other) { return value < other; } /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function(srcValue, key) { stack || (stack = new Stack); if (isObject(srcValue)) { baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); } /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = safeGet(object, key), srcValue = safeGet(source, key), stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || isFunction(objValue)) { newValue = initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } assignMergeValue(object, key, newValue); } /** * The base implementation of `_.nth` which doesn't coerce arguments. * * @private * @param {Array} array The array to query. * @param {number} n The index of the element to return. * @returns {*} Returns the nth element of `array`. */ function baseNth(array, n) { var length = array.length; if (!length) { return; } n += n < 0 ? length : 0; return isIndex(n, length) ? array[n] : undefined; } /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); var result = baseMap(collection, function(value, key, collection) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return basePickBy(object, paths, function(value, path) { return hasIn(object, path); }); } /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = baseGet(object, path); if (predicate(value, path)) { baseSet(result, castPath(path, object), value); } } return result; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } /** * The base implementation of `_.pullAllBy` without support for iteratee * shorthands. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. */ function basePullAll(array, values, iteratee, comparator) { var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; if (array === values) { values = copyArray(values); } if (iteratee) { seen = arrayMap(array, baseUnary(iteratee)); } while (++index < length) { var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { if (seen !== array) { splice.call(seen, fromIndex, 1); } splice.call(array, fromIndex, 1); } } return array; } /** * The base implementation of `_.pullAt` without support for individual * indexes or capturing the removed elements. * * @private * @param {Array} array The array to modify. * @param {number[]} indexes The indexes of elements to remove. * @returns {Array} Returns `array`. */ function basePullAt(array, indexes) { var length = array ? indexes.length : 0, lastIndex = length - 1; while (length--) { var index = indexes[length]; if (length == lastIndex || index !== previous) { var previous = index; if (isIndex(index)) { splice.call(array, index, 1); } else { baseUnset(array, index); } } } return array; } /** * The base implementation of `_.random` without support for returning * floating-point numbers. * * @private * @param {number} lower The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the random number. */ function baseRandom(lower, upper) { return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } /** * The base implementation of `_.repeat` which doesn't coerce arguments. * * @private * @param {string} string The string to repeat. * @param {number} n The number of times to repeat the string. * @returns {string} Returns the repeated string. */ function baseRepeat(string, n) { var result = ''; if (!string || n < 1 || n > MAX_SAFE_INTEGER) { return result; } // Leverage the exponentiation by squaring algorithm for a faster repeat. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. do { if (n % 2) { result += string; } n = nativeFloor(n / 2); if (n) { string += string; } } while (n); return result; } /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } /** * The base implementation of `_.sample`. * * @private * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. */ function baseSample(collection) { return arraySample(values(collection)); } /** * The base implementation of `_.sampleSize` without param guards. * * @private * @param {Array|Object} collection The collection to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function baseSampleSize(collection, n) { var array = values(collection); return shuffleSelf(array, baseClamp(n, 0, array.length)); } /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; } path = castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject(objValue) ? objValue : (isIndex(path[index + 1]) ? [] : {}); } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; /** * The base implementation of `_.shuffle`. * * @private * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. */ function baseShuffle(collection) { return shuffleSelf(values(collection)); } /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * The base implementation of `_.some` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function baseSome(collection, predicate) { var result; baseEach(collection, function(value, index, collection) { result = predicate(value, index, collection); return !result; }); return !!result; } /** * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which * performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndex(array, value, retHighest) { var low = 0, high = array == null ? low : array.length; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (computed !== null && !isSymbol(computed) && (retHighest ? (computed <= value) : (computed < value))) { low = mid + 1; } else { high = mid; } } return high; } return baseSortedIndexBy(array, value, identity, retHighest); } /** * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` * which invokes `iteratee` for `value` and each element of `array` to compute * their sort ranking. The iteratee is invoked with one argument; (value). * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} iteratee The iteratee invoked per element. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndexBy(array, value, iteratee, retHighest) { value = iteratee(value); var low = 0, high = array == null ? 0 : array.length, valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined; while (low < high) { var mid = nativeFloor((low + high) / 2), computed = iteratee(array[mid]), othIsDefined = computed !== undefined, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); if (valIsNaN) { var setLow = retHighest || othIsReflexive; } else if (valIsUndefined) { setLow = othIsReflexive && (retHighest || othIsDefined); } else if (valIsNull) { setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); } else if (valIsSymbol) { setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); } else if (othIsNull || othIsSymbol) { setLow = false; } else { setLow = retHighest ? (computed <= value) : (computed < value); } if (setLow) { low = mid + 1; } else { high = mid; } } return nativeMin(high, MAX_ARRAY_INDEX); } /** * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseSortedUniq(array, iteratee) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (!index || !eq(computed, seen)) { var seen = computed; result[resIndex++] = value === 0 ? 0 : value; } } return result; } /** * The base implementation of `_.toNumber` which doesn't ensure correct * conversions of binary, hexadecimal, or octal string values. * * @private * @param {*} value The value to process. * @returns {number} Returns the number. */ function baseToNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } return +value; } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = castPath(path, object); object = parent(object, path); return object == null || delete object[toKey(last(path))]; } /** * The base implementation of `_.update`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to update. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseUpdate(object, path, updater, customizer) { return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** * The base implementation of methods like `_.dropWhile` and `_.takeWhile` * without support for iteratee shorthands. * * @private * @param {Array} array The array to query. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [isDrop] Specify dropping elements instead of taking them. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the slice of `array`. */ function baseWhile(array, predicate, isDrop, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} return isDrop ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); } /** * The base implementation of `wrapperValue` which returns the result of * performing a sequence of actions on the unwrapped `value`, where each * successive action is supplied the return value of the previous. * * @private * @param {*} value The unwrapped value. * @param {Array} actions Actions to perform to resolve the unwrapped value. * @returns {*} Returns the resolved value. */ function baseWrapperValue(value, actions) { var result = value; if (result instanceof LazyWrapper) { result = result.value(); } return arrayReduce(actions, function(result, action) { return action.func.apply(action.thisArg, arrayPush([result], action.args)); }, result); } /** * The base implementation of methods like `_.xor`, without support for * iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of values. */ function baseXor(arrays, iteratee, comparator) { var length = arrays.length; if (length < 2) { return length ? baseUniq(arrays[0]) : []; } var index = -1, result = Array(length); while (++index < length) { var array = arrays[index], othIndex = -1; while (++othIndex < length) { if (othIndex != index) { result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); } } } return baseUniq(baseFlatten(result, 1), iteratee, comparator); } /** * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * * @private * @param {Array} props The property identifiers. * @param {Array} values The property values. * @param {Function} assignFunc The function to assign values. * @returns {Object} Returns the new object. */ function baseZipObject(props, values, assignFunc) { var index = -1, length = props.length, valsLength = values.length, result = {}; while (++index < length) { var value = index < valsLength ? values[index] : undefined; assignFunc(result, props[index], value); } return result; } /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity; } /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } /** * A `baseRest` alias which can be replaced with `identity` by module * replacement plugins. * * @private * @type {Function} * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ var castRest = baseRest; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } /** * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * * @private * @param {number|Object} id The timer id or timeout object of the timer to clear. */ var clearTimeout = ctxClearTimeout || function(id) { return root.clearTimeout(id); }; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } /** * Creates a function like `_.groupBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} [initializer] The accumulator object initializer. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, getIteratee(iteratee, 2), accumulator); }; } /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } /** * Creates a function like `_.lowerFirst`. * * @private * @param {string} methodName The name of the `String` case method to use. * @returns {Function} Returns the new case function. */ function createCaseFirst(methodName) { return function(string) { string = toString(string); var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined; var chr = strSymbols ? strSymbols[0] : string.charAt(0); var trailing = strSymbols ? castSlice(strSymbols, 1).join('') : string.slice(1); return chr[methodName]() + trailing; }; } /** * Creates a function like `_.camelCase`. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function(string) { return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); }; } /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; } /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = getIteratee(predicate, 3); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } /** * Creates a `_.flow` or `_.flowRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new flow function. */ function createFlow(fromRight) { return flatRest(function(funcs) { var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; if (fromRight) { funcs.reverse(); } while (index--) { var func = funcs[index]; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (prereq && !wrapper && getFuncName(func) == 'wrapper') { var wrapper = new LodashWrapper([], true); } } index = wrapper ? index : length; while (++index < length) { func = funcs[index]; var funcName = getFuncName(func), data = funcName == 'wrapper' ? getData(func) : undefined; if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1 ) { wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); } else { wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); } } return function() { var args = arguments, value = args[0]; if (wrapper && args.length == 1 && isArray(value)) { return wrapper.plant(value).value(); } var index = 0, result = length ? funcs[index].apply(this, args) : value; while (++index < length) { result = funcs[index].call(this, result); } return result; }; }); } /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } /** * Creates a function that performs a mathematical operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @param {number} [defaultValue] The value used for `undefined` arguments. * @returns {Function} Returns the new mathematical operation function. */ function createMathOperation(operator, defaultValue) { return function(value, other) { var result; if (value === undefined && other === undefined) { return defaultValue; } if (value !== undefined) { result = value; } if (other !== undefined) { if (result === undefined) { return other; } if (typeof value == 'string' || typeof other == 'string') { value = baseToString(value); other = baseToString(other); } else { value = baseToNumber(value); other = baseToNumber(other); } result = operator(value, other); } return result; }; } /** * Creates a function like `_.over`. * * @private * @param {Function} arrayFunc The function to iterate over iteratees. * @returns {Function} Returns the new over function. */ function createOver(arrayFunc) { return flatRest(function(iteratees) { iteratees = arrayMap(iteratees, baseUnary(getIteratee())); return baseRest(function(args) { var thisArg = this; return arrayFunc(iteratees, function(iteratee) { return apply(iteratee, thisArg, args); }); }); }); } /** * Creates the padding for `string` based on `length`. The `chars` string * is truncated if the number of characters exceeds `length`. * * @private * @param {number} length The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padding for `string`. */ function createPadding(length, chars) { chars = chars === undefined ? ' ' : baseToString(chars); var charsLength = chars.length; if (charsLength < 2) { return charsLength ? baseRepeat(chars, length) : chars; } var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); return hasUnicode(chars) ? castSlice(stringToArray(result), 0, length).join('') : result.slice(0, length); } /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; } /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); return baseRange(start, end, step, fromRight); }; } /** * Creates a function that performs a relational operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @returns {Function} Returns the new relational operation function. */ function createRelationalOperation(operator) { return function(value, other) { if (!(typeof value == 'string' && typeof other == 'string')) { value = toNumber(value); other = toNumber(other); } return operator(value, other); }; } /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } /** * Creates a function like `_.round`. * * @private * @param {string} methodName The name of the `Math` method to use when rounding. * @returns {Function} Returns the new round function. */ function createRound(methodName) { var func = Math[methodName]; return function(number, precision) { number = toNumber(number); precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); if (precision && nativeIsFinite(number)) { // Shift with exponential notation to avoid floating-point issues. // See [MDN](https://mdn.io/round#Examples) for more details. var pair = (toString(number) + 'e').split('e'), value = func(pair[0] + 'e' + (+pair[1] + precision)); pair = (toString(value) + 'e').split('e'); return +(pair[0] + 'e' + (+pair[1] - precision)); } return func(number); }; } /** * Creates a set object of `values`. * * @private * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { return new Set(values); }; /** * Creates a `_.toPairs` or `_.toPairsIn` function. * * @private * @param {Function} keysFunc The function to get the keys of a given object. * @returns {Function} Returns the new pairs function. */ function createToPairs(keysFunc) { return function(object) { var tag = getTag(object); if (tag == mapTag) { return mapToArray(object); } if (tag == setTag) { return setToPairs(object); } return baseToPairs(object, keysFunc(object)); }; } /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == WRAP_BIND_FLAG) { var result = createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials); } else { result = createHybrid.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); } /** * Used by `_.defaults` to customize its `_.assignIn` use to assign properties * of source objects to the destination object for all destination properties * that resolve to `undefined`. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function customDefaultsAssignIn(objValue, srcValue, key, object) { if (objValue === undefined || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } /** * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source * objects into destination objects that are passed thru. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to merge. * @param {Object} object The parent object of `objValue`. * @param {Object} source The parent object of `srcValue`. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. * @returns {*} Returns the value to assign. */ function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { if (isObject(objValue) && isObject(srcValue)) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, objValue); baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); stack['delete'](srcValue); } return objValue; } /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject(value) ? undefined : value; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return setToString(overRest(func, undefined, flatten), func + ''); } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; return object.placeholder; } /** * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, * this function returns the custom method, otherwise it returns `baseIteratee`. * If arguments are provided, the chosen function is invoked with them and * its result is returned. * * @private * @param {*} [value] The value to convert to an iteratee. * @param {number} [arity] The arity of the created iteratee. * @returns {Function} Returns the chosen function or its result. */ function getIteratee() { var result = lodash.iteratee || iteratee; result = result === iteratee ? baseIteratee : result; return arguments.length ? result(arguments[0], arguments[1]) : result; } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Gets the view, applying any `transforms` to the `start` and `end` positions. * * @private * @param {number} start The start of the view. * @param {number} end The end of the view. * @param {Array} transforms The transformations to apply to the view. * @returns {Object} Returns an object containing the `start` and `end` * positions of the view. */ function getView(start, end, transforms) { var index = -1, length = transforms.length; while (++index < length) { var data = transforms[index], size = data.size; switch (data.type) { case 'drop': start += size; break; case 'dropRight': end -= size; break; case 'take': end = nativeMin(end, start + size); break; case 'takeRight': start = nativeMax(start, end - size); break; } } return { 'start': start, 'end': end }; } /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return new Ctor; case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return new Ctor; case symbolTag: return cloneSymbol(object); } } /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `func` is capable of being masked. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `func` is maskable, else `false`. */ var isMaskable = coreJsData ? isFunction : stubFalse; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); var isCombo = ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } /** * Gets the value at `key`, unless `key` is "__proto__" or "constructor". * * @private * @param {Object} object The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function safeGet(object, key) { if (key === 'constructor' && typeof object[key] === 'function') { return; } if (key == '__proto__') { return; } return object[key]; } /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = shortOut(baseSetData); /** * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @returns {number|Object} Returns the timer id or timeout object. */ var setTimeout = ctxSetTimeout || function(func, wait) { return root.setTimeout(func, wait); }; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } /** * A specialized version of `_.shuffle` which mutates and sets the size of `array`. * * @private * @param {Array} array The array to shuffle. * @param {number} [size=array.length] The size of `array`. * @returns {Array} Returns `array`. */ function shuffleSelf(array, size) { var index = -1, length = array.length, lastIndex = length - 1; size = size === undefined ? length : size; while (++index < size) { var rand = baseRandom(index, lastIndex), value = array[rand]; array[rand] = array[index]; array[index] = value; } array.length = size; return array; } /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (string.charCodeAt(0) === 46 /* . */) { result.push(''); } string.replace(rePropName, function(match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } /*------------------------------------------------------------------------*/ /** * Creates an array of elements split into groups the length of `size`. * If `array` can't be split evenly, the final chunk will be the remaining * elements. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the new array of chunks. * @example * * _.chunk(['a', 'b', 'c', 'd'], 2); * // => [['a', 'b'], ['c', 'd']] * * _.chunk(['a', 'b', 'c', 'd'], 3); * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size, guard) { if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { size = 1; } else { size = nativeMax(toInteger(size), 0); } var length = array == null ? 0 : array.length; if (!length || size < 1) { return []; } var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); while (index < length) { result[resIndex++] = baseSlice(array, index, (index += size)); } return result; } /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } /** * Creates a new array concatenating `array` with any additional arrays * and/or values. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to concatenate. * @param {...*} [values] The values to concatenate. * @returns {Array} Returns the new concatenated array. * @example * * var array = [1]; * var other = _.concat(array, 2, [3], [[4]]); * * console.log(other); * // => [1, 2, 3, [4]] * * console.log(array); * // => [1] */ function concat() { var length = arguments.length; if (!length) { return []; } var args = Array(length - 1), array = arguments[0], index = length; while (index--) { args[index - 1] = arguments[index]; } return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); } /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); /** * This method is like `_.difference` except that it accepts `iteratee` which * is invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * **Note:** Unlike `_.pullAllBy`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2] * * // The `_.property` iteratee shorthand. * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var differenceBy = baseRest(function(array, values) { var iteratee = last(values); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.difference` except that it accepts `comparator` * which is invoked to compare elements of `array` to `values`. The order and * references of result values are determined by the first array. The comparator * is invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.pullAllWith`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); * // => [{ 'x': 2, 'y': 1 }] */ var differenceWith = baseRest(function(array, values) { var comparator = last(values); if (isArrayLikeObject(comparator)) { comparator = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) : []; }); /** * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ * @since 0.5.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.drop([1, 2, 3]); * // => [2, 3] * * _.drop([1, 2, 3], 2); * // => [3] * * _.drop([1, 2, 3], 5); * // => [] * * _.drop([1, 2, 3], 0); * // => [1, 2, 3] */ function drop(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropRight([1, 2, 3]); * // => [1, 2] * * _.dropRight([1, 2, 3], 2); * // => [1] * * _.dropRight([1, 2, 3], 5); * // => [] * * _.dropRight([1, 2, 3], 0); * // => [1, 2, 3] */ function dropRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` excluding elements dropped from the end. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.dropRightWhile(users, function(o) { return !o.active; }); * // => objects for ['barney'] * * // The `_.matches` iteratee shorthand. * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['barney', 'fred'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropRightWhile(users, ['active', false]); * // => objects for ['barney'] * * // The `_.property` iteratee shorthand. * _.dropRightWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; } /** * Creates a slice of `array` excluding elements dropped from the beginning. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.dropWhile(users, function(o) { return !o.active; }); * // => objects for ['pebbles'] * * // The `_.matches` iteratee shorthand. * _.dropWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['fred', 'pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropWhile(users, ['active', false]); * // => objects for ['pebbles'] * * // The `_.property` iteratee shorthand. * _.dropWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true) : []; } /** * Fills elements of `array` with `value` from `start` up to, but not * including, `end`. * * **Note:** This method mutates `array`. * * @static * @memberOf _ * @since 3.2.0 * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.fill(array, 'a'); * console.log(array); * // => ['a', 'a', 'a'] * * _.fill(Array(3), 2); * // => [2, 2, 2] * * _.fill([4, 6, 8, 10], '*', 1, 3); * // => [4, '*', '*', 10] */ function fill(array, value, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { start = 0; end = length; } return baseFill(array, value, start, end); } /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, getIteratee(predicate, 3), index); } /** * This method is like `_.findIndex` except that it iterates over elements * of `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); * // => 2 * * // The `_.matches` iteratee shorthand. * _.findLastIndex(users, { 'user': 'barney', 'active': true }); * // => 0 * * // The `_.matchesProperty` iteratee shorthand. * _.findLastIndex(users, ['active', false]); * // => 2 * * // The `_.property` iteratee shorthand. * _.findLastIndex(users, 'active'); * // => 0 */ function findLastIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length - 1; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return baseFindIndex(array, getIteratee(predicate, 3), index, true); } /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : []; } /** * Recursively flattens `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flattenDeep([1, [2, [3, [4]], 5]]); * // => [1, 2, 3, 4, 5] */ function flattenDeep(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, INFINITY) : []; } /** * Recursively flatten `array` up to `depth` times. * * @static * @memberOf _ * @since 4.4.0 * @category Array * @param {Array} array The array to flatten. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * var array = [1, [2, [3, [4]], 5]]; * * _.flattenDepth(array, 1); * // => [1, 2, [3, [4]], 5] * * _.flattenDepth(array, 2); * // => [1, 2, 3, [4], 5] */ function flattenDepth(array, depth) { var length = array == null ? 0 : array.length; if (!length) { return []; } depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(array, depth); } /** * The inverse of `_.toPairs`; this method returns an object composed * from key-value `pairs`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} pairs The key-value pairs. * @returns {Object} Returns the new object. * @example * * _.fromPairs([['a', 1], ['b', 2]]); * // => { 'a': 1, 'b': 2 } */ function fromPairs(pairs) { var index = -1, length = pairs == null ? 0 : pairs.length, result = {}; while (++index < length) { var pair = pairs[index]; result[pair[0]] = pair[1]; } return result; } /** * Gets the first element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @alias first * @category Array * @param {Array} array The array to query. * @returns {*} Returns the first element of `array`. * @example * * _.head([1, 2, 3]); * // => 1 * * _.head([]); * // => undefined */ function head(array) { return (array && array.length) ? array[0] : undefined; } /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseIndexOf(array, value, index); } /** * Gets all but the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] */ function initial(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 0, -1) : []; } /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); /** * This method is like `_.intersection` except that it accepts `iteratee` * which is invoked for each element of each `arrays` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [2.1] * * // The `_.property` iteratee shorthand. * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }] */ var intersectionBy = baseRest(function(arrays) { var iteratee = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (iteratee === last(mapped)) { iteratee = undefined; } else { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.intersection` except that it accepts `comparator` * which is invoked to compare elements of `arrays`. The order and references * of result values are determined by the first array. The comparator is * invoked with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.intersectionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }] */ var intersectionWith = baseRest(function(arrays) { var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); comparator = typeof comparator == 'function' ? comparator : undefined; if (comparator) { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, undefined, comparator) : []; }); /** * Converts all elements in `array` into a string separated by `separator`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to convert. * @param {string} [separator=','] The element separator. * @returns {string} Returns the joined string. * @example * * _.join(['a', 'b', 'c'], '~'); * // => 'a~b~c' */ function join(array, separator) { return array == null ? '' : nativeJoin.call(array, separator); } /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } /** * This method is like `_.indexOf` except that it iterates over elements of * `array` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.lastIndexOf([1, 2, 1, 2], 2); * // => 3 * * // Search from the `fromIndex`. * _.lastIndexOf([1, 2, 1, 2], 2, 2); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return value === value ? strictLastIndexOf(array, value, index) : baseFindIndex(array, baseIsNaN, index, true); } /** * Gets the element at index `n` of `array`. If `n` is negative, the nth * element from the end is returned. * * @static * @memberOf _ * @since 4.11.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=0] The index of the element to return. * @returns {*} Returns the nth element of `array`. * @example * * var array = ['a', 'b', 'c', 'd']; * * _.nth(array, 1); * // => 'b' * * _.nth(array, -2); * // => 'c'; */ function nth(array, n) { return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; } /** * Removes all given values from `array` using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` * to remove elements from an array by predicate. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {...*} [values] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pull(array, 'a', 'c'); * console.log(array); * // => ['b', 'b'] */ var pull = baseRest(pullAll); /** * This method is like `_.pull` except that it accepts an array of values to remove. * * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pullAll(array, ['a', 'c']); * console.log(array); * // => ['b', 'b'] */ function pullAll(array, values) { return (array && array.length && values && values.length) ? basePullAll(array, values) : array; } /** * This method is like `_.pullAll` except that it accepts `iteratee` which is * invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The iteratee is invoked with one argument: (value). * * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); * console.log(array); * // => [{ 'x': 2 }] */ function pullAllBy(array, values, iteratee) { return (array && array.length && values && values.length) ? basePullAll(array, values, getIteratee(iteratee, 2)) : array; } /** * This method is like `_.pullAll` except that it accepts `comparator` which * is invoked to compare elements of `array` to `values`. The comparator is * invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.differenceWith`, this method mutates `array`. * * @static * @memberOf _ * @since 4.6.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); * console.log(array); * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ function pullAllWith(array, values, comparator) { return (array && array.length && values && values.length) ? basePullAll(array, values, undefined, comparator) : array; } /** * Removes elements from `array` corresponding to `indexes` and returns an * array of removed elements. * * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to modify. * @param {...(number|number[])} [indexes] The indexes of elements to remove. * @returns {Array} Returns the new array of removed elements. * @example * * var array = ['a', 'b', 'c', 'd']; * var pulled = _.pullAt(array, [1, 3]); * * console.log(array); * // => ['a', 'c'] * * console.log(pulled); * // => ['b', 'd'] */ var pullAt = flatRest(function(array, indexes) { var length = array == null ? 0 : array.length, result = baseAt(array, indexes); basePullAt(array, arrayMap(indexes, function(index) { return isIndex(index, length) ? +index : index; }).sort(compareAscending)); return result; }); /** * Removes all elements from `array` that `predicate` returns truthy for * and returns an array of the removed elements. The predicate is invoked * with three arguments: (value, index, array). * * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` * to pull elements from an array by value. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [1, 2, 3, 4]; * var evens = _.remove(array, function(n) { * return n % 2 == 0; * }); * * console.log(array); * // => [1, 3] * * console.log(evens); * // => [2, 4] */ function remove(array, predicate) { var result = []; if (!(array && array.length)) { return result; } var index = -1, indexes = [], length = array.length; predicate = getIteratee(predicate, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); indexes.push(index); } } basePullAt(array, indexes); return result; } /** * Reverses `array` so that the first element becomes the last, the second * element becomes the second to last, and so on. * * **Note:** This method mutates `array` and is based on * [`Array#reverse`](https://mdn.io/Array/reverse). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.reverse(array); * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function reverse(array) { return array == null ? array : nativeReverse.call(array); } /** * Creates a slice of `array` from `start` up to, but not including, `end`. * * **Note:** This method is used instead of * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are * returned. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function slice(array, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { start = 0; end = length; } else { start = start == null ? 0 : toInteger(start); end = end === undefined ? length : toInteger(end); } return baseSlice(array, start, end); } /** * Uses a binary search to determine the lowest index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([30, 50], 40); * // => 1 */ function sortedIndex(array, value) { return baseSortedIndex(array, value); } /** * This method is like `_.sortedIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 0 * * // The `_.property` iteratee shorthand. * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); * // => 0 */ function sortedIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); } /** * This method is like `_.indexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedIndexOf([4, 5, 5, 5, 6], 5); * // => 1 */ function sortedIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value); if (index < length && eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedLastIndex([4, 5, 5, 5, 6], 5); * // => 4 */ function sortedLastIndex(array, value) { return baseSortedIndex(array, value, true); } /** * This method is like `_.sortedLastIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 1 * * // The `_.property` iteratee shorthand. * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); * // => 1 */ function sortedLastIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); } /** * This method is like `_.lastIndexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); * // => 3 */ function sortedLastIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value, true) - 1; if (eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.uniq` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniq([1, 1, 2]); * // => [1, 2] */ function sortedUniq(array) { return (array && array.length) ? baseSortedUniq(array) : []; } /** * This method is like `_.uniqBy` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); * // => [1.1, 2.3] */ function sortedUniqBy(array, iteratee) { return (array && array.length) ? baseSortedUniq(array, getIteratee(iteratee, 2)) : []; } /** * Gets all but the first element of `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.tail([1, 2, 3]); * // => [2, 3] */ function tail(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 1, length) : []; } /** * Creates a slice of `array` with `n` elements taken from the beginning. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.take([1, 2, 3]); * // => [1] * * _.take([1, 2, 3], 2); * // => [1, 2] * * _.take([1, 2, 3], 5); * // => [1, 2, 3] * * _.take([1, 2, 3], 0); * // => [] */ function take(array, n, guard) { if (!(array && array.length)) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeRight([1, 2, 3]); * // => [3] * * _.takeRight([1, 2, 3], 2); * // => [2, 3] * * _.takeRight([1, 2, 3], 5); * // => [1, 2, 3] * * _.takeRight([1, 2, 3], 0); * // => [] */ function takeRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with elements taken from the end. Elements are * taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.takeRightWhile(users, function(o) { return !o.active; }); * // => objects for ['fred', 'pebbles'] * * // The `_.matches` iteratee shorthand. * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeRightWhile(users, ['active', false]); * // => objects for ['fred', 'pebbles'] * * // The `_.property` iteratee shorthand. * _.takeRightWhile(users, 'active'); * // => [] */ function takeRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; } /** * Creates a slice of `array` with elements taken from the beginning. Elements * are taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.takeWhile(users, function(o) { return !o.active; }); * // => objects for ['barney', 'fred'] * * // The `_.matches` iteratee shorthand. * _.takeWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeWhile(users, ['active', false]); * // => objects for ['barney', 'fred'] * * // The `_.property` iteratee shorthand. * _.takeWhile(users, 'active'); * // => [] */ function takeWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3)) : []; } /** * Creates an array of unique values, in order, from all given arrays using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([2], [1, 2]); * // => [2, 1] */ var union = baseRest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); /** * This method is like `_.union` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which uniqueness is computed. Result values are chosen from the first * array in which the value occurs. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * _.unionBy([2.1], [1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ var unionBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); }); /** * This method is like `_.union` except that it accepts `comparator` which * is invoked to compare elements of `arrays`. Result values are chosen from * the first array in which the value occurs. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.unionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var unionWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); }); /** * Creates a duplicate-free version of an array, using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons, in which only the first occurrence of each element * is kept. The order of result values is determined by the order they occur * in the array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniq([2, 1, 2]); * // => [2, 1] */ function uniq(array) { return (array && array.length) ? baseUniq(array) : []; } /** * This method is like `_.uniq` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * uniqueness is computed. The order of result values is determined by the * order they occur in the array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniqBy([2.1, 1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniqBy(array, iteratee) { return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; } /** * This method is like `_.uniq` except that it accepts `comparator` which * is invoked to compare elements of `array`. The order of result values is * determined by the order they occur in the array.The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.uniqWith(objects, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ function uniqWith(array, comparator) { comparator = typeof comparator == 'function' ? comparator : undefined; return (array && array.length) ? baseUniq(array, undefined, comparator) : []; } /** * This method is like `_.zip` except that it accepts an array of grouped * elements and creates an array regrouping the elements to their pre-zip * configuration. * * @static * @memberOf _ * @since 1.2.0 * @category Array * @param {Array} array The array of grouped elements to process. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] * * _.unzip(zipped); * // => [['a', 'b'], [1, 2], [true, false]] */ function unzip(array) { if (!(array && array.length)) { return []; } var length = 0; array = arrayFilter(array, function(group) { if (isArrayLikeObject(group)) { length = nativeMax(group.length, length); return true; } }); return baseTimes(length, function(index) { return arrayMap(array, baseProperty(index)); }); } /** * This method is like `_.unzip` except that it accepts `iteratee` to specify * how regrouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {Array} array The array of grouped elements to process. * @param {Function} [iteratee=_.identity] The function to combine * regrouped values. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip([1, 2], [10, 20], [100, 200]); * // => [[1, 10, 100], [2, 20, 200]] * * _.unzipWith(zipped, _.add); * // => [3, 30, 300] */ function unzipWith(array, iteratee) { if (!(array && array.length)) { return []; } var result = unzip(array); if (iteratee == null) { return result; } return arrayMap(result, function(group) { return apply(iteratee, undefined, group); }); } /** * Creates an array excluding all given values using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.pull`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...*} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.xor * @example * * _.without([2, 1, 2, 3], 1, 2); * // => [3] */ var without = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : []; }); /** * Creates an array of unique values that is the * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the given arrays. The order of result values is determined by the order * they occur in the arrays. * * @static * @memberOf _ * @since 2.4.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.without * @example * * _.xor([2, 1], [2, 3]); * // => [1, 3] */ var xor = baseRest(function(arrays) { return baseXor(arrayFilter(arrays, isArrayLikeObject)); }); /** * This method is like `_.xor` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which by which they're compared. The order of result values is determined * by the order they occur in the arrays. The iteratee is invoked with one * argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2, 3.4] * * // The `_.property` iteratee shorthand. * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var xorBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); }); /** * This method is like `_.xor` except that it accepts `comparator` which is * invoked to compare elements of `arrays`. The order of result values is * determined by the order they occur in the arrays. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.xorWith(objects, others, _.isEqual); * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var xorWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); }); /** * Creates an array of grouped elements, the first of which contains the * first elements of the given arrays, the second of which contains the * second elements of the given arrays, and so on. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] */ var zip = baseRest(unzip); /** * This method is like `_.fromPairs` except that it accepts two arrays, * one of property identifiers and one of corresponding values. * * @static * @memberOf _ * @since 0.4.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObject(['a', 'b'], [1, 2]); * // => { 'a': 1, 'b': 2 } */ function zipObject(props, values) { return baseZipObject(props || [], values || [], assignValue); } /** * This method is like `_.zipObject` except that it supports property paths. * * @static * @memberOf _ * @since 4.1.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } */ function zipObjectDeep(props, values) { return baseZipObject(props || [], values || [], baseSet); } /** * This method is like `_.zip` except that it accepts `iteratee` to specify * how grouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @param {Function} [iteratee=_.identity] The function to combine * grouped values. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { * return a + b + c; * }); * // => [111, 222] */ var zipWith = baseRest(function(arrays) { var length = arrays.length, iteratee = length > 1 ? arrays[length - 1] : undefined; iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; return unzipWith(arrays, iteratee); }); /*------------------------------------------------------------------------*/ /** * Creates a `lodash` wrapper instance that wraps `value` with explicit method * chain sequences enabled. The result of such sequences must be unwrapped * with `_#value`. * * @static * @memberOf _ * @since 1.3.0 * @category Seq * @param {*} value The value to wrap. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'pebbles', 'age': 1 } * ]; * * var youngest = _ * .chain(users) * .sortBy('age') * .map(function(o) { * return o.user + ' is ' + o.age; * }) * .head() * .value(); * // => 'pebbles is 1' */ function chain(value) { var result = lodash(value); result.__chain__ = true; return result; } /** * This method invokes `interceptor` and returns `value`. The interceptor * is invoked with one argument; (value). The purpose of this method is to * "tap into" a method chain sequence in order to modify intermediate results. * * @static * @memberOf _ * @since 0.1.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns `value`. * @example * * _([1, 2, 3]) * .tap(function(array) { * // Mutate input array. * array.pop(); * }) * .reverse() * .value(); * // => [2, 1] */ function tap(value, interceptor) { interceptor(value); return value; } /** * This method is like `_.tap` except that it returns the result of `interceptor`. * The purpose of this method is to "pass thru" values replacing intermediate * results in a method chain sequence. * * @static * @memberOf _ * @since 3.0.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns the result of `interceptor`. * @example * * _(' abc ') * .chain() * .trim() * .thru(function(value) { * return [value]; * }) * .value(); * // => ['abc'] */ function thru(value, interceptor) { return interceptor(value); } /** * This method is the wrapper version of `_.at`. * * @name at * @memberOf _ * @since 1.0.0 * @category Seq * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _(object).at(['a[0].b.c', 'a[1]']).value(); * // => [3, 4] */ var wrapperAt = flatRest(function(paths) { var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { return baseAt(object, paths); }; if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { return this.thru(interceptor); } value = value.slice(start, +start + (length ? 1 : 0)); value.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(value, this.__chain__).thru(function(array) { if (length && !array.length) { array.push(undefined); } return array; }); }); /** * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. * * @name chain * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // A sequence without explicit chaining. * _(users).head(); * // => { 'user': 'barney', 'age': 36 } * * // A sequence with explicit chaining. * _(users) * .chain() * .head() * .pick('user') * .value(); * // => { 'user': 'barney' } */ function wrapperChain() { return chain(this); } /** * Executes the chain sequence and returns the wrapped result. * * @name commit * @memberOf _ * @since 3.2.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2]; * var wrapped = _(array).push(3); * * console.log(array); * // => [1, 2] * * wrapped = wrapped.commit(); * console.log(array); * // => [1, 2, 3] * * wrapped.last(); * // => 3 * * console.log(array); * // => [1, 2, 3] */ function wrapperCommit() { return new LodashWrapper(this.value(), this.__chain__); } /** * Gets the next value on a wrapped object following the * [iterator protocol](https://mdn.io/iteration_protocols#iterator). * * @name next * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the next iterator value. * @example * * var wrapped = _([1, 2]); * * wrapped.next(); * // => { 'done': false, 'value': 1 } * * wrapped.next(); * // => { 'done': false, 'value': 2 } * * wrapped.next(); * // => { 'done': true, 'value': undefined } */ function wrapperNext() { if (this.__values__ === undefined) { this.__values__ = toArray(this.value()); } var done = this.__index__ >= this.__values__.length, value = done ? undefined : this.__values__[this.__index__++]; return { 'done': done, 'value': value }; } /** * Enables the wrapper to be iterable. * * @name Symbol.iterator * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the wrapper object. * @example * * var wrapped = _([1, 2]); * * wrapped[Symbol.iterator]() === wrapped; * // => true * * Array.from(wrapped); * // => [1, 2] */ function wrapperToIterator() { return this; } /** * Creates a clone of the chain sequence planting `value` as the wrapped value. * * @name plant * @memberOf _ * @since 3.2.0 * @category Seq * @param {*} value The value to plant. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2]).map(square); * var other = wrapped.plant([3, 4]); * * other.value(); * // => [9, 16] * * wrapped.value(); * // => [1, 4] */ function wrapperPlant(value) { var result, parent = this; while (parent instanceof baseLodash) { var clone = wrapperClone(parent); clone.__index__ = 0; clone.__values__ = undefined; if (result) { previous.__wrapped__ = clone; } else { result = clone; } var previous = clone; parent = parent.__wrapped__; } previous.__wrapped__ = value; return result; } /** * This method is the wrapper version of `_.reverse`. * * **Note:** This method mutates the wrapped array. * * @name reverse * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2, 3]; * * _(array).reverse().value() * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function wrapperReverse() { var value = this.__wrapped__; if (value instanceof LazyWrapper) { var wrapped = value; if (this.__actions__.length) { wrapped = new LazyWrapper(this); } wrapped = wrapped.reverse(); wrapped.__actions__.push({ 'func': thru, 'args': [reverse], 'thisArg': undefined }); return new LodashWrapper(wrapped, this.__chain__); } return this.thru(reverse); } /** * Executes the chain sequence to resolve the unwrapped value. * * @name value * @memberOf _ * @since 0.1.0 * @alias toJSON, valueOf * @category Seq * @returns {*} Returns the resolved unwrapped value. * @example * * _([1, 2, 3]).value(); * // => [1, 2, 3] */ function wrapperValue() { return baseWrapperValue(this.__wrapped__, this.__actions__); } /*------------------------------------------------------------------------*/ /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the number of times the key was returned by `iteratee`. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.5.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': 1, '6': 2 } * * // The `_.property` iteratee shorthand. * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { ++result[key]; } else { baseAssignValue(result, key, 1); } }); /** * Checks if `predicate` returns truthy for **all** elements of `collection`. * Iteration is stopped once `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index|key, collection). * * **Note:** This method returns `true` for * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of * elements of empty collections. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.every(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.every(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.every(users, 'active'); * // => false */ function every(collection, predicate, guard) { var func = isArray(collection) ? arrayEvery : baseEvery; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] */ function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = createFind(findIndex); /** * This method is like `_.find` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=collection.length-1] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(n) { * return n % 2 == 1; * }); * // => 3 */ var findLast = createFind(findLastIndex); /** * Creates a flattened array of values by running each element in `collection` * thru `iteratee` and flattening the mapped results. The iteratee is invoked * with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [n, n]; * } * * _.flatMap([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMap(collection, iteratee) { return baseFlatten(map(collection, iteratee), 1); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDeep([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMapDeep(collection, iteratee) { return baseFlatten(map(collection, iteratee), INFINITY); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results up to `depth` times. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDepth([1, 2], duplicate, 2); * // => [[1, 1], [2, 2]] */ function flatMapDepth(collection, iteratee, depth) { depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(map(collection, iteratee), depth); } /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.forEach` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @alias eachRight * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEach * @example * * _.forEachRight([1, 2], function(value) { * console.log(value); * }); * // => Logs `2` then `1`. */ function forEachRight(collection, iteratee) { var func = isArray(collection) ? arrayEachRight : baseEachRight; return func(collection, getIteratee(iteratee, 3)); } /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The order of grouped values * is determined by the order they occur in `collection`. The corresponding * value of each key is an array of elements responsible for generating the * key. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': [4.2], '6': [6.1, 6.3] } * * // The `_.property` iteratee shorthand. * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { baseAssignValue(result, key, [value]); } }); /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } /** * Invokes the method at `path` of each element in `collection`, returning * an array of the results of each invoked method. Any additional arguments * are provided to each invoked method. If `path` is a function, it's invoked * for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|string} path The path of the method to invoke or * the function invoked per iteration. * @param {...*} [args] The arguments to invoke each method with. * @returns {Array} Returns the array of results. * @example * * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invokeMap([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ var invokeMap = baseRest(function(collection, path, args) { var index = -1, isFunc = typeof path == 'function', result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value) { result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); }); return result; }); /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the last element responsible for generating the key. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * var array = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.keyBy(array, function(o) { * return String.fromCharCode(o.code); * }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.keyBy(array, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } */ var keyBy = createAggregator(function(result, value, key) { baseAssignValue(result, key, value); }); /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseOrderBy(collection, iteratees, orders); } /** * Creates an array of elements split into two groups, the first of which * contains elements `predicate` returns truthy for, the second of which * contains elements `predicate` returns falsey for. The predicate is * invoked with one argument: (value). * * @static * @memberOf _ * @since 3.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of grouped elements. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true }, * { 'user': 'pebbles', 'age': 1, 'active': false } * ]; * * _.partition(users, function(o) { return o.active; }); * // => objects for [['fred'], ['barney', 'pebbles']] * * // The `_.matches` iteratee shorthand. * _.partition(users, { 'age': 1, 'active': false }); * // => objects for [['pebbles'], ['barney', 'fred']] * * // The `_.matchesProperty` iteratee shorthand. * _.partition(users, ['active', false]); * // => objects for [['barney', 'pebbles'], ['fred']] * * // The `_.property` iteratee shorthand. * _.partition(users, 'active'); * // => objects for [['fred'], ['barney', 'pebbles']] */ var partition = createAggregator(function(result, value, key) { result[key ? 0 : 1].push(value); }, function() { return [[], []]; }); /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); } /** * This method is like `_.reduce` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduce * @example * * var array = [[0, 1], [2, 3], [4, 5]]; * * _.reduceRight(array, function(flattened, other) { * return flattened.concat(other); * }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); } /** * The opposite of `_.filter`; this method returns the elements of `collection` * that `predicate` does **not** return truthy for. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.filter * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true } * ]; * * _.reject(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.reject(users, { 'age': 40, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.reject(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.reject(users, 'active'); * // => objects for ['barney'] */ function reject(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, negate(getIteratee(predicate, 3))); } /** * Gets a random element from `collection`. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. * @example * * _.sample([1, 2, 3, 4]); * // => 2 */ function sample(collection) { var func = isArray(collection) ? arraySample : baseSample; return func(collection); } /** * Gets `n` random elements at unique keys from `collection` up to the * size of `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @param {number} [n=1] The number of elements to sample. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the random elements. * @example * * _.sampleSize([1, 2, 3], 2); * // => [3, 1] * * _.sampleSize([1, 2, 3], 4); * // => [2, 3, 1] */ function sampleSize(collection, n, guard) { if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } var func = isArray(collection) ? arraySampleSize : baseSampleSize; return func(collection, n); } /** * Creates an array of shuffled values, using a version of the * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. * @example * * _.shuffle([1, 2, 3, 4]); * // => [4, 1, 3, 2] */ function shuffle(collection) { var func = isArray(collection) ? arrayShuffle : baseShuffle; return func(collection); } /** * Gets the size of `collection` by returning its length for array-like * values or the number of own enumerable string keyed properties for objects. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns the collection size. * @example * * _.size([1, 2, 3]); * // => 3 * * _.size({ 'a': 1, 'b': 2 }); * // => 2 * * _.size('pebbles'); * // => 7 */ function size(collection) { if (collection == null) { return 0; } if (isArrayLike(collection)) { return isString(collection) ? stringSize(collection) : collection.length; } var tag = getTag(collection); if (tag == mapTag || tag == setTag) { return collection.size; } return baseKeys(collection).length; } /** * Checks if `predicate` returns truthy for **any** element of `collection`. * Iteration is stopped once `predicate` returns truthy. The predicate is * invoked with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.some(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.some(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.some(users, 'active'); * // => true */ function some(collection, predicate, guard) { var func = isArray(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection thru each iteratee. This method * performs a stable sort, that is, it preserves the original sort order of * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to sort by. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.sortBy(users, [function(o) { return o.user; }]); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] * * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] */ var sortBy = baseRest(function(collection, iteratees) { if (collection == null) { return []; } var length = iteratees.length; if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { iteratees = []; } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]]; } return baseOrderBy(collection, baseFlatten(iteratees, 1), []); }); /*------------------------------------------------------------------------*/ /** * Gets the timestamp of the number of milliseconds that have elapsed since * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @since 2.4.0 * @category Date * @returns {number} Returns the timestamp. * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => Logs the number of milliseconds it took for the deferred invocation. */ var now = ctxNow || function() { return root.Date.now(); }; /*------------------------------------------------------------------------*/ /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it's called `n` or more times. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => Logs 'done saving!' after the two async saves have completed. */ function after(n, func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that invokes `func`, with up to `n` arguments, * ignoring any additional arguments. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @param {number} [n=func.length] The arity cap. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.ary(parseInt, 1)); * // => [6, 8, 10] */ function ary(func, n, guard) { n = guard ? undefined : n; n = (func && n == null) ? func.length : n; return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); } /** * Creates a function that invokes `func`, with the `this` binding and arguments * of the created function, while it's called less than `n` times. Subsequent * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {number} n The number of calls at which `func` is no longer invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * jQuery(element).on('click', _.before(5, addContactToList)); * // => Allows adding up to 4 contacts to the list. */ function before(n, func) { var result; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n > 0) { result = func.apply(this, arguments); } if (n <= 1) { func = undefined; } return result; }; } /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(func, bitmask, thisArg, partials, holders); }); /** * Creates a function that invokes the method at `object[key]` with `partials` * prepended to the arguments it receives. * * This method differs from `_.bind` by allowing bound functions to reference * methods that may be redefined or don't yet exist. See * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) * for more details. * * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * @static * @memberOf _ * @since 0.10.0 * @category Function * @param {Object} object The object to invoke the method on. * @param {string} key The key of the method. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'user': 'fred', * 'greet': function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * }; * * var bound = _.bindKey(object, 'greet', 'hi'); * bound('!'); * // => 'hi fred!' * * object.greet = function(greeting, punctuation) { * return greeting + 'ya ' + this.user + punctuation; * }; * * bound('!'); * // => 'hiya fred!' * * // Bound with placeholders. * var bound = _.bindKey(object, 'greet', _, '!'); * bound('hi'); * // => 'hiya fred!' */ var bindKey = baseRest(function(object, key, partials) { var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bindKey)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(key, bitmask, object, partials, holders); }); /** * Creates a function that accepts arguments of `func` and either invokes * `func` returning its result, if at least `arity` number of arguments have * been provided, or returns a function that accepts the remaining `func` * arguments, and so on. The arity of `func` may be specified if `func.length` * is not sufficient. * * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 2.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curry(abc); * * curried(1)(2)(3); * // => [1, 2, 3] * * curried(1, 2)(3); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(1)(_, 3)(2); * // => [1, 2, 3] */ function curry(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curry.placeholder; return result; } /** * This method is like `_.curry` except that arguments are applied to `func` * in the manner of `_.partialRight` instead of `_.partial`. * * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curryRight(abc); * * curried(3)(2)(1); * // => [1, 2, 3] * * curried(2, 3)(1); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(3)(1, _)(2); * // => [1, 2, 3] */ function curryRight(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curryRight.placeholder; return result; } /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide `options` to indicate whether `func` should be invoked on the * leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent * calls to the debounced function return the result of the last `func` * invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the debounced function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return (lastCallTime === undefined || (timeSinceLastCall >= wait) || (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined; return result; } function cancel() { if (timerId !== undefined) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined; } function flush() { return timerId === undefined ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. clearTimeout(timerId); timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } /** * Defers invoking the `func` until the current call stack has cleared. Any * additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to defer. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.defer(function(text) { * console.log(text); * }, 'deferred'); * // => Logs 'deferred' after one millisecond. */ var defer = baseRest(function(func, args) { return baseDelay(func, 1, args); }); /** * Invokes `func` after `wait` milliseconds. Any additional arguments are * provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { * console.log(text); * }, 1000, 'later'); * // => Logs 'later' after one second. */ var delay = baseRest(function(func, wait, args) { return baseDelay(func, toNumber(wait) || 0, args); }); /** * Creates a function that invokes `func` with arguments reversed. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to flip arguments for. * @returns {Function} Returns the new flipped function. * @example * * var flipped = _.flip(function() { * return _.toArray(arguments); * }); * * flipped('a', 'b', 'c', 'd'); * // => ['d', 'c', 'b', 'a'] */ function flip(func) { return createWrap(func, WRAP_FLIP_FLAG); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; /** * Creates a function that negates the result of the predicate `func`. The * `func` predicate is invoked with the `this` binding and arguments of the * created function. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} predicate The predicate to negate. * @returns {Function} Returns the new negated function. * @example * * function isEven(n) { * return n % 2 == 0; * } * * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); * // => [1, 3, 5] */ function negate(predicate) { if (typeof predicate != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function() { var args = arguments; switch (args.length) { case 0: return !predicate.call(this); case 1: return !predicate.call(this, args[0]); case 2: return !predicate.call(this, args[0], args[1]); case 3: return !predicate.call(this, args[0], args[1], args[2]); } return !predicate.apply(this, args); }; } /** * Creates a function that is restricted to invoking `func` once. Repeat calls * to the function return the value of the first invocation. The `func` is * invoked with the `this` binding and arguments of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // => `createApplication` is invoked once */ function once(func) { return before(2, func); } /** * Creates a function that invokes `func` with its arguments transformed. * * @static * @since 4.0.0 * @memberOf _ * @category Function * @param {Function} func The function to wrap. * @param {...(Function|Function[])} [transforms=[_.identity]] * The argument transforms. * @returns {Function} Returns the new function. * @example * * function doubled(n) { * return n * 2; * } * * function square(n) { * return n * n; * } * * var func = _.overArgs(function(x, y) { * return [x, y]; * }, [square, doubled]); * * func(9, 3); * // => [81, 6] * * func(10, 5); * // => [100, 10] */ var overArgs = castRest(function(func, transforms) { transforms = (transforms.length == 1 && isArray(transforms[0])) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); var funcsLength = transforms.length; return baseRest(function(args) { var index = -1, length = nativeMin(args.length, funcsLength); while (++index < length) { args[index] = transforms[index].call(this, args[index]); } return apply(func, this, args); }); }); /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); }); /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); }); /** * Creates a function that invokes `func` with arguments arranged according * to the specified `indexes` where the argument value at the first index is * provided as the first argument, the argument value at the second index is * provided as the second argument, and so on. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to rearrange arguments for. * @param {...(number|number[])} indexes The arranged argument indexes. * @returns {Function} Returns the new function. * @example * * var rearged = _.rearg(function(a, b, c) { * return [a, b, c]; * }, [2, 0, 1]); * * rearged('b', 'c', 'a') * // => ['a', 'b', 'c'] */ var rearg = flatRest(function(func, indexes) { return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); }); /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as * an array. * * **Note:** This method is based on the * [rest parameter](https://mdn.io/rest_parameters). * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.rest(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function rest(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start === undefined ? start : toInteger(start); return baseRest(func, start); } /** * Creates a function that invokes `func` with the `this` binding of the * create function and an array of arguments much like * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). * * **Note:** This method is based on the * [spread operator](https://mdn.io/spread_operator). * * @static * @memberOf _ * @since 3.2.0 * @category Function * @param {Function} func The function to spread arguments over. * @param {number} [start=0] The start position of the spread. * @returns {Function} Returns the new function. * @example * * var say = _.spread(function(who, what) { * return who + ' says ' + what; * }); * * say(['fred', 'hello']); * // => 'fred says hello' * * var numbers = Promise.all([ * Promise.resolve(40), * Promise.resolve(36) * ]); * * numbers.then(_.spread(function(x, y) { * return x + y; * })); * // => a Promise of 76 */ function spread(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start == null ? 0 : nativeMax(toInteger(start), 0); return baseRest(function(args) { var array = args[start], otherArgs = castSlice(args, 0, start); if (array) { arrayPush(otherArgs, array); } return apply(func, this, otherArgs); }); } /** * Creates a throttled function that only invokes `func` at most once per * every `wait` milliseconds. The throttled function comes with a `cancel` * method to cancel delayed `func` invocations and a `flush` method to * immediately invoke them. Provide `options` to indicate whether `func` * should be invoked on the leading and/or trailing edge of the `wait` * timeout. The `func` is invoked with the last arguments provided to the * throttled function. Subsequent calls to the throttled function return the * result of the last `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the throttled function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=true] * Specify invoking on the leading edge of the timeout. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // Avoid excessively updating the position while scrolling. * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); * jQuery(element).on('click', throttled); * * // Cancel the trailing throttled invocation. * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } return debounce(func, wait, { 'leading': leading, 'maxWait': wait, 'trailing': trailing }); } /** * Creates a function that accepts up to one argument, ignoring any * additional arguments. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.unary(parseInt)); * // => [6, 8, 10] */ function unary(func) { return ary(func, 1); } /** * Creates a function that provides `value` to `wrapper` as its first * argument. Any additional arguments provided to the function are appended * to those provided to the `wrapper`. The wrapper is invoked with the `this` * binding of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {*} value The value to wrap. * @param {Function} [wrapper=identity] The wrapper function. * @returns {Function} Returns the new function. * @example * * var p = _.wrap(_.escape, function(func, text) { * return '<p>' + func(text) + '</p>'; * }); * * p('fred, barney, & pebbles'); * // => '<p>fred, barney, &amp; pebbles</p>' */ function wrap(value, wrapper) { return partial(castFunction(wrapper), value); } /*------------------------------------------------------------------------*/ /** * Casts `value` as an array if it's not one. * * @static * @memberOf _ * @since 4.4.0 * @category Lang * @param {*} value The value to inspect. * @returns {Array} Returns the cast array. * @example * * _.castArray(1); * // => [1] * * _.castArray({ 'a': 1 }); * // => [{ 'a': 1 }] * * _.castArray('abc'); * // => ['abc'] * * _.castArray(null); * // => [null] * * _.castArray(undefined); * // => [undefined] * * _.castArray(); * // => [] * * var array = [1, 2, 3]; * console.log(_.castArray(array) === array); * // => true */ function castArray() { if (!arguments.length) { return []; } var value = arguments[0]; return isArray(value) ? value : [value]; } /** * Creates a shallow clone of `value`. * * **Note:** This method is loosely based on the * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) * and supports cloning arrays, array buffers, booleans, date objects, maps, * numbers, `Object` objects, regexes, sets, strings, symbols, and typed * arrays. The own enumerable properties of `arguments` objects are cloned * as plain objects. An empty object is returned for uncloneable values such * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to clone. * @returns {*} Returns the cloned value. * @see _.cloneDeep * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var shallow = _.clone(objects); * console.log(shallow[0] === objects[0]); * // => true */ function clone(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); } /** * This method is like `_.clone` except that it accepts `customizer` which * is invoked to produce the cloned value. If `customizer` returns `undefined`, * cloning is handled by the method instead. The `customizer` is invoked with * up to four arguments; (value [, index|key, object, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the cloned value. * @see _.cloneDeepWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * } * * var el = _.cloneWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 0 */ function cloneWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); } /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); } /** * This method is like `_.cloneWith` except that it recursively clones `value`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to recursively clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the deep cloned value. * @see _.cloneWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(true); * } * } * * var el = _.cloneDeepWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 20 */ function cloneDeepWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); } /** * Checks if `object` conforms to `source` by invoking the predicate * properties of `source` with the corresponding property values of `object`. * * **Note:** This method is equivalent to `_.conforms` when `source` is * partially applied. * * @static * @memberOf _ * @since 4.14.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); * // => true * * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); * // => false */ function conformsTo(object, source) { return source == null || baseConformsTo(object, source, keys(source)); } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is greater than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. * @see _.lt * @example * * _.gt(3, 1); * // => true * * _.gt(3, 3); * // => false * * _.gt(1, 3); * // => false */ var gt = createRelationalOperation(baseGt); /** * Checks if `value` is greater than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than or equal to * `other`, else `false`. * @see _.lte * @example * * _.gte(3, 1); * // => true * * _.gte(3, 3); * // => true * * _.gte(1, 3); * // => false */ var gte = createRelationalOperation(function(value, other) { return value >= other; }); /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is classified as an `ArrayBuffer` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. * @example * * _.isArrayBuffer(new ArrayBuffer(2)); * // => true * * _.isArrayBuffer(new Array(2)); * // => false */ var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. * @example * * _.isBoolean(false); * // => true * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || (isObjectLike(value) && baseGetTag(value) == boolTag); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Checks if `value` is classified as a `Date` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. * @example * * _.isDate(new Date); * // => true * * _.isDate('Mon April 23 2012'); * // => false */ var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; /** * Checks if `value` is likely a DOM element. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true * * _.isElement('<body>'); * // => false */ function isElement(value) { return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); } /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (isPrototype(value)) { return !baseKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * This method is like `_.isEqual` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with up to * six arguments: (objValue, othValue [, index|key, object, other, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, othValue) { * if (isGreeting(objValue) && isGreeting(othValue)) { * return true; * } * } * * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqualWith(array, other, customizer); * // => true */ function isEqualWith(value, other, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; var result = customizer ? customizer(value, other) : undefined; return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; } /** * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, * `SyntaxError`, `TypeError`, or `URIError` object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an error object, else `false`. * @example * * _.isError(new Error); * // => true * * _.isError(Error); * // => false */ function isError(value) { if (!isObjectLike(value)) { return false; } var tag = baseGetTag(value); return tag == errorTag || tag == domExcTag || (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); } /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite(value) { return typeof value == 'number' && nativeIsFinite(value); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** * Checks if `value` is an integer. * * **Note:** This method is based on * [`Number.isInteger`](https://mdn.io/Number/isInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an integer, else `false`. * @example * * _.isInteger(3); * // => true * * _.isInteger(Number.MIN_VALUE); * // => false * * _.isInteger(Infinity); * // => false * * _.isInteger('3'); * // => false */ function isInteger(value) { return typeof value == 'number' && value == toInteger(value); } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; /** * Performs a partial deep comparison between `object` and `source` to * determine if `object` contains equivalent property values. * * **Note:** This method is equivalent to `_.matches` when `source` is * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.isMatch(object, { 'b': 2 }); * // => true * * _.isMatch(object, { 'b': 1 }); * // => false */ function isMatch(object, source) { return object === source || baseIsMatch(object, source, getMatchData(source)); } /** * This method is like `_.isMatch` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with five * arguments: (objValue, srcValue, index|key, object, source). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, srcValue) { * if (isGreeting(objValue) && isGreeting(srcValue)) { * return true; * } * } * * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatchWith(object, source, customizer); * // => true */ function isMatchWith(object, source, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseIsMatch(object, source, getMatchData(source), customizer); } /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber(value) && value != +value; } /** * Checks if `value` is a pristine native function. * * **Note:** This method can't reliably detect native functions in the presence * of the core-js package because core-js circumvents this kind of detection. * Despite multiple requests, the core-js maintainer has made it clear: any * attempt to fix the detection will be obstructed. As a result, we're left * with little choice but to throw an error. Unfortunately, this also affects * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), * which rely on core-js. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (isMaskable(value)) { throw new Error(CORE_ERROR_TEXT); } return baseIsNative(value); } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(void 0); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * * _.isNil(null); * // => true * * _.isNil(void 0); * // => true * * _.isNil(NaN); * // => false */ function isNil(value) { return value == null; } /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && baseGetTag(value) == numberTag); } /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } /** * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. * @example * * _.isRegExp(/abc/); * // => true * * _.isRegExp('/abc/'); * // => false */ var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; /** * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 * double precision number which isn't the result of a rounded unsafe integer. * * **Note:** This method is based on * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. * @example * * _.isSafeInteger(3); * // => true * * _.isSafeInteger(Number.MIN_VALUE); * // => false * * _.isSafeInteger(Infinity); * // => false * * _.isSafeInteger('3'); * // => false */ function isSafeInteger(value) { return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } /** * Checks if `value` is classified as a `WeakMap` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. * @example * * _.isWeakMap(new WeakMap); * // => true * * _.isWeakMap(new Map); * // => false */ function isWeakMap(value) { return isObjectLike(value) && getTag(value) == weakMapTag; } /** * Checks if `value` is classified as a `WeakSet` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. * @example * * _.isWeakSet(new WeakSet); * // => true * * _.isWeakSet(new Set); * // => false */ function isWeakSet(value) { return isObjectLike(value) && baseGetTag(value) == weakSetTag; } /** * Checks if `value` is less than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. * @see _.gt * @example * * _.lt(1, 3); * // => true * * _.lt(3, 3); * // => false * * _.lt(3, 1); * // => false */ var lt = createRelationalOperation(baseLt); /** * Checks if `value` is less than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than or equal to * `other`, else `false`. * @see _.gte * @example * * _.lte(1, 3); * // => true * * _.lte(3, 3); * // => true * * _.lte(3, 1); * // => false */ var lte = createRelationalOperation(function(value, other) { return value <= other; }); /** * Converts `value` to an array. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Array} Returns the converted array. * @example * * _.toArray({ 'a': 1, 'b': 2 }); * // => [1, 2] * * _.toArray('abc'); * // => ['a', 'b', 'c'] * * _.toArray(1); * // => [] * * _.toArray(null); * // => [] */ function toArray(value) { if (!value) { return []; } if (isArrayLike(value)) { return isString(value) ? stringToArray(value) : copyArray(value); } if (symIterator && value[symIterator]) { return iteratorToArray(value[symIterator]()); } var tag = getTag(value), func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); return func(value); } /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * **Note:** This method is based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toLength(3.2); * // => 3 * * _.toLength(Number.MIN_VALUE); * // => 0 * * _.toLength(Infinity); * // => 4294967295 * * _.toLength('3.2'); * // => 3 */ function toLength(value) { return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; } /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } /** * Converts `value` to a safe integer. A safe integer can be compared and * represented correctly. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toSafeInteger(3.2); * // => 3 * * _.toSafeInteger(Number.MIN_VALUE); * // => 0 * * _.toSafeInteger(Infinity); * // => 9007199254740991 * * _.toSafeInteger('3.2'); * // => 3 */ function toSafeInteger(value) { return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) : (value === 0 ? value : 0); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /*------------------------------------------------------------------------*/ /** * Assigns own enumerable string keyed properties of source objects to the * destination object. Source objects are applied from left to right. * Subsequent sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object` and is loosely based on * [`Object.assign`](https://mdn.io/Object/assign). * * @static * @memberOf _ * @since 0.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assignIn * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assign({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3 } */ var assign = createAssigner(function(object, source) { if (isPrototype(source) || isArrayLike(source)) { copyObject(source, keys(source), object); return; } for (var key in source) { if (hasOwnProperty.call(source, key)) { assignValue(object, key, source[key]); } } }); /** * This method is like `_.assign` except that it iterates over own and * inherited source properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assign * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assignIn({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } */ var assignIn = createAssigner(function(object, source) { copyObject(source, keysIn(source), object); }); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); /** * This method is like `_.assign` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignInWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keys(source), object, customizer); }); /** * Creates an array of values corresponding to `paths` of `object`. * * @static * @memberOf _ * @since 1.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Array} Returns the picked values. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _.at(object, ['a[0].b.c', 'a[1]']); * // => [3, 4] */ var at = flatRest(baseAt); /** * Creates an object that inherits from the `prototype` object. If a * `properties` object is given, its own enumerable string keyed properties * are assigned to the created object. * * @static * @memberOf _ * @since 2.3.0 * @category Object * @param {Object} prototype The object to inherit from. * @param {Object} [properties] The properties to assign to the object. * @returns {Object} Returns the new object. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * function Circle() { * Shape.call(this); * } * * Circle.prototype = _.create(Shape.prototype, { * 'constructor': Circle * }); * * var circle = new Circle; * circle instanceof Circle; * // => true * * circle instanceof Shape; * // => true */ function create(prototype, properties) { var result = baseCreate(prototype); return properties == null ? result : baseAssign(result, properties); } /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = baseRest(function(object, sources) { object = Object(object); var index = -1; var length = sources.length; var guard = length > 2 ? sources[2] : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { length = 1; } while (++index < length) { var source = sources[index]; var props = keysIn(source); var propsIndex = -1; var propsLength = props.length; while (++propsIndex < propsLength) { var key = props[propsIndex]; var value = object[key]; if (value === undefined || (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { object[key] = source[key]; } } } return object; }); /** * This method is like `_.defaults` except that it recursively assigns * default properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaults * @example * * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); * // => { 'a': { 'b': 2, 'c': 3 } } */ var defaultsDeep = baseRest(function(args) { args.push(undefined, customDefaultsMerge); return apply(mergeWith, undefined, args); }); /** * This method is like `_.find` except that it returns the key of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findKey(users, function(o) { return o.age < 40; }); * // => 'barney' (iteration order is not guaranteed) * * // The `_.matches` iteratee shorthand. * _.findKey(users, { 'age': 1, 'active': true }); * // => 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.findKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findKey(users, 'active'); * // => 'barney' */ function findKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); } /** * This method is like `_.findKey` except that it iterates over elements of * a collection in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findLastKey(users, function(o) { return o.age < 40; }); * // => returns 'pebbles' assuming `_.findKey` returns 'barney' * * // The `_.matches` iteratee shorthand. * _.findLastKey(users, { 'age': 36, 'active': true }); * // => 'barney' * * // The `_.matchesProperty` iteratee shorthand. * _.findLastKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findLastKey(users, 'active'); * // => 'pebbles' */ function findLastKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); } /** * Iterates over own and inherited enumerable string keyed properties of an * object and invokes `iteratee` for each property. The iteratee is invoked * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forInRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forIn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). */ function forIn(object, iteratee) { return object == null ? object : baseFor(object, getIteratee(iteratee, 3), keysIn); } /** * This method is like `_.forIn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forIn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forInRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. */ function forInRight(object, iteratee) { return object == null ? object : baseForRight(object, getIteratee(iteratee, 3), keysIn); } /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && baseForOwn(object, getIteratee(iteratee, 3)); } /** * This method is like `_.forOwn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwnRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. */ function forOwnRight(object, iteratee) { return object && baseForOwnRight(object, getIteratee(iteratee, 3)); } /** * Creates an array of function property names from own enumerable properties * of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functionsIn * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functions(new Foo); * // => ['a', 'b'] */ function functions(object) { return object == null ? [] : baseFunctions(object, keys(object)); } /** * Creates an array of function property names from own and inherited * enumerable properties of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functions * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functionsIn(new Foo); * // => ['a', 'b', 'c'] */ function functionsIn(object) { return object == null ? [] : baseFunctions(object, keysIn(object)); } /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } result[value] = key; }, constant(identity)); /** * This method is like `_.invert` except that the inverted object is generated * from the results of running each element of `object` thru `iteratee`. The * corresponding inverted value of each inverted key is an array of keys * responsible for generating the inverted value. The iteratee is invoked * with one argument: (value). * * @static * @memberOf _ * @since 4.1.0 * @category Object * @param {Object} object The object to invert. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invertBy(object); * // => { '1': ['a', 'c'], '2': ['b'] } * * _.invertBy(object, function(value) { * return 'group' + value; * }); * // => { 'group1': ['a', 'c'], 'group2': ['b'] } */ var invertBy = createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } }, getIteratee); /** * Invokes the method at `path` of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. * @example * * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; * * _.invoke(object, 'a[0].b.c.slice', 1, 3); * // => [2, 3] */ var invoke = baseRest(baseInvoke); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, iteratee(value, key, object), value); }); return result; } /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); /** * This method is like `_.merge` except that it accepts `customizer` which * is invoked to produce the merged values of the destination and source * properties. If `customizer` returns `undefined`, merging is handled by the * method instead. The `customizer` is invoked with six arguments: * (objValue, srcValue, key, object, source, stack). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * if (_.isArray(objValue)) { * return objValue.concat(srcValue); * } * } * * var object = { 'a': [1], 'b': [2] }; * var other = { 'a': [3], 'b': [4] }; * * _.mergeWith(object, other, customizer); * // => { 'a': [1, 3], 'b': [2, 4] } */ var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { baseMerge(object, source, srcIndex, customizer); }); /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = arrayMap(paths, function(path) { path = castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); copyObject(object, getAllKeysIn(object), result); if (isDeep) { result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); } var length = paths.length; while (length--) { baseUnset(result, paths[length]); } return result; }); /** * The opposite of `_.pickBy`; this method creates an object composed of * the own and inherited enumerable string keyed properties of `object` that * `predicate` doesn't return truthy for. The predicate is invoked with two * arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omitBy(object, _.isNumber); * // => { 'b': '2' } */ function omitBy(object, predicate) { return pickBy(object, negate(getIteratee(predicate))); } /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = flatRest(function(object, paths) { return object == null ? {} : basePick(object, paths); }); /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = arrayMap(getAllKeysIn(object), function(prop) { return [prop]; }); predicate = getIteratee(predicate); return basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } /** * This method is like `_.get` except that if the resolved value is a * function it's invoked with the `this` binding of its parent object and * its result is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to resolve. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * * _.result(object, 'a[0].b.c1'); * // => 3 * * _.result(object, 'a[0].b.c2'); * // => 4 * * _.result(object, 'a[0].b.c3', 'default'); * // => 'default' * * _.result(object, 'a[0].b.c3', _.constant('default')); * // => 'default' */ function result(object, path, defaultValue) { path = castPath(path, object); var index = -1, length = path.length; // Ensure the loop is entered when path is empty. if (!length) { length = 1; object = undefined; } while (++index < length) { var value = object == null ? undefined : object[toKey(path[index])]; if (value === undefined) { index = length; value = defaultValue; } object = isFunction(value) ? value.call(object) : value; } return object; } /** * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, * it's created. Arrays are created for missing index properties while objects * are created for all other missing properties. Use `_.setWith` to customize * `path` creation. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.set(object, 'a[0].b.c', 4); * console.log(object.a[0].b.c); * // => 4 * * _.set(object, ['x', '0', 'y', 'z'], 5); * console.log(object.x[0].y.z); * // => 5 */ function set(object, path, value) { return object == null ? object : baseSet(object, path, value); } /** * This method is like `_.set` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.setWith(object, '[0][1]', 'a', Object); * // => { '0': { '1': 'a' } } */ function setWith(object, path, value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseSet(object, path, value, customizer); } /** * Creates an array of own enumerable string keyed-value pairs for `object` * which can be consumed by `_.fromPairs`. If `object` is a map or set, its * entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entries * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairs(new Foo); * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) */ var toPairs = createToPairs(keys); /** * Creates an array of own and inherited enumerable string keyed-value pairs * for `object` which can be consumed by `_.fromPairs`. If `object` is a map * or set, its entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entriesIn * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairsIn(new Foo); * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) */ var toPairsIn = createToPairs(keysIn); /** * An alternative to `_.reduce`; this method transforms `object` to a new * `accumulator` object which is the result of running each of its own * enumerable string keyed properties thru `iteratee`, with each invocation * potentially mutating the `accumulator` object. If `accumulator` is not * provided, a new object with the same `[[Prototype]]` will be used. The * iteratee is invoked with four arguments: (accumulator, value, key, object). * Iteratee functions may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 1.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The custom accumulator value. * @returns {*} Returns the accumulated value. * @example * * _.transform([2, 3, 4], function(result, n) { * result.push(n *= n); * return n % 2 == 0; * }, []); * // => [4, 9] * * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } */ function transform(object, iteratee, accumulator) { var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); iteratee = getIteratee(iteratee, 4); if (accumulator == null) { var Ctor = object && object.constructor; if (isArrLike) { accumulator = isArr ? new Ctor : []; } else if (isObject(object)) { accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; } else { accumulator = {}; } } (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { return iteratee(accumulator, value, index, object); }); return accumulator; } /** * Removes the property at `path` of `object`. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. * @example * * var object = { 'a': [{ 'b': { 'c': 7 } }] }; * _.unset(object, 'a[0].b.c'); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; * * _.unset(object, ['a', '0', 'b', 'c']); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; */ function unset(object, path) { return object == null ? true : baseUnset(object, path); } /** * This method is like `_.set` except that accepts `updater` to produce the * value to set. Use `_.updateWith` to customize `path` creation. The `updater` * is invoked with one argument: (value). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.update(object, 'a[0].b.c', function(n) { return n * n; }); * console.log(object.a[0].b.c); * // => 9 * * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); * console.log(object.x[0].y.z); * // => 0 */ function update(object, path, updater) { return object == null ? object : baseUpdate(object, path, castFunction(updater)); } /** * This method is like `_.update` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.updateWith(object, '[0][1]', _.constant('a'), Object); * // => { '0': { '1': 'a' } } */ function updateWith(object, path, updater, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); } /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : baseValues(object, keys(object)); } /** * Creates an array of the own and inherited enumerable string keyed property * values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.valuesIn(new Foo); * // => [1, 2, 3] (iteration order is not guaranteed) */ function valuesIn(object) { return object == null ? [] : baseValues(object, keysIn(object)); } /*------------------------------------------------------------------------*/ /** * Clamps `number` within the inclusive `lower` and `upper` bounds. * * @static * @memberOf _ * @since 4.0.0 * @category Number * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. * @example * * _.clamp(-10, -5, 5); * // => -5 * * _.clamp(10, -5, 5); * // => 5 */ function clamp(number, lower, upper) { if (upper === undefined) { upper = lower; lower = undefined; } if (upper !== undefined) { upper = toNumber(upper); upper = upper === upper ? upper : 0; } if (lower !== undefined) { lower = toNumber(lower); lower = lower === lower ? lower : 0; } return baseClamp(toNumber(number), lower, upper); } /** * Checks if `n` is between `start` and up to, but not including, `end`. If * `end` is not specified, it's set to `start` with `start` then set to `0`. * If `start` is greater than `end` the params are swapped to support * negative ranges. * * @static * @memberOf _ * @since 3.3.0 * @category Number * @param {number} number The number to check. * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. * @see _.range, _.rangeRight * @example * * _.inRange(3, 2, 4); * // => true * * _.inRange(4, 8); * // => true * * _.inRange(4, 2); * // => false * * _.inRange(2, 2); * // => false * * _.inRange(1.2, 2); * // => true * * _.inRange(5.2, 4); * // => false * * _.inRange(-3, -2, -6); * // => true */ function inRange(number, start, end) { start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } number = toNumber(number); return baseInRange(number, start, end); } /** * Produces a random number between the inclusive `lower` and `upper` bounds. * If only one argument is provided a number between `0` and the given number * is returned. If `floating` is `true`, or either `lower` or `upper` are * floats, a floating-point number is returned instead of an integer. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @memberOf _ * @since 0.7.0 * @category Number * @param {number} [lower=0] The lower bound. * @param {number} [upper=1] The upper bound. * @param {boolean} [floating] Specify returning a floating-point number. * @returns {number} Returns the random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(lower, upper, floating) { if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { upper = floating = undefined; } if (floating === undefined) { if (typeof upper == 'boolean') { floating = upper; upper = undefined; } else if (typeof lower == 'boolean') { floating = lower; lower = undefined; } } if (lower === undefined && upper === undefined) { lower = 0; upper = 1; } else { lower = toFinite(lower); if (upper === undefined) { upper = lower; lower = 0; } else { upper = toFinite(upper); } } if (lower > upper) { var temp = lower; lower = upper; upper = temp; } if (floating || lower % 1 || upper % 1) { var rand = nativeRandom(); return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); } return baseRandom(lower, upper); } /*------------------------------------------------------------------------*/ /** * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the camel cased string. * @example * * _.camelCase('Foo Bar'); * // => 'fooBar' * * _.camelCase('--foo-bar--'); * // => 'fooBar' * * _.camelCase('__FOO_BAR__'); * // => 'fooBar' */ var camelCase = createCompounder(function(result, word, index) { word = word.toLowerCase(); return result + (index ? capitalize(word) : word); }); /** * Converts the first character of `string` to upper case and the remaining * to lower case. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to capitalize. * @returns {string} Returns the capitalized string. * @example * * _.capitalize('FRED'); * // => 'Fred' */ function capitalize(string) { return upperFirst(toString(string).toLowerCase()); } /** * Deburrs `string` by converting * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) * letters to basic Latin letters and removing * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to deburr. * @returns {string} Returns the deburred string. * @example * * _.deburr('déjà vu'); * // => 'deja vu' */ function deburr(string) { string = toString(string); return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); } /** * Checks if `string` ends with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=string.length] The position to search up to. * @returns {boolean} Returns `true` if `string` ends with `target`, * else `false`. * @example * * _.endsWith('abc', 'c'); * // => true * * _.endsWith('abc', 'b'); * // => false * * _.endsWith('abc', 'b', 2); * // => true */ function endsWith(string, target, position) { string = toString(string); target = baseToString(target); var length = string.length; position = position === undefined ? length : baseClamp(toInteger(position), 0, length); var end = position; position -= target.length; return position >= 0 && string.slice(position, end) == target; } /** * Converts the characters "&", "<", ">", '"', and "'" in `string` to their * corresponding HTML entities. * * **Note:** No other characters are escaped. To escape additional * characters use a third-party library like [_he_](https://mths.be/he). * * Though the ">" character is escaped for symmetry, characters like * ">" and "/" don't need escaping in HTML and have no special meaning * unless they're part of a tag or unquoted attribute value. See * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) * (under "semi-related fun fact") for more details. * * When working with HTML you should always * [quote attribute values](http://wonko.com/post/html-escaping) to reduce * XSS vectors. * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('fred, barney, & pebbles'); * // => 'fred, barney, &amp; pebbles' */ function escape(string) { string = toString(string); return (string && reHasUnescapedHtml.test(string)) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } /** * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https://lodash\.com/\)' */ function escapeRegExp(string) { string = toString(string); return (string && reHasRegExpChar.test(string)) ? string.replace(reRegExpChar, '\\$&') : string; } /** * Converts `string` to * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the kebab cased string. * @example * * _.kebabCase('Foo Bar'); * // => 'foo-bar' * * _.kebabCase('fooBar'); * // => 'foo-bar' * * _.kebabCase('__FOO_BAR__'); * // => 'foo-bar' */ var kebabCase = createCompounder(function(result, word, index) { return result + (index ? '-' : '') + word.toLowerCase(); }); /** * Converts `string`, as space separated words, to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.lowerCase('--Foo-Bar--'); * // => 'foo bar' * * _.lowerCase('fooBar'); * // => 'foo bar' * * _.lowerCase('__FOO_BAR__'); * // => 'foo bar' */ var lowerCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toLowerCase(); }); /** * Converts the first character of `string` to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.lowerFirst('Fred'); * // => 'fred' * * _.lowerFirst('FRED'); * // => 'fRED' */ var lowerFirst = createCaseFirst('toLowerCase'); /** * Pads `string` on the left and right sides if it's shorter than `length`. * Padding characters are truncated if they can't be evenly divided by `length`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.pad('abc', 8); * // => ' abc ' * * _.pad('abc', 8, '_-'); * // => '_-abc_-_' * * _.pad('abc', 3); * // => 'abc' */ function pad(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; if (!length || strLength >= length) { return string; } var mid = (length - strLength) / 2; return ( createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars) ); } /** * Pads `string` on the right side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padEnd('abc', 6); * // => 'abc ' * * _.padEnd('abc', 6, '_-'); * // => 'abc_-_' * * _.padEnd('abc', 3); * // => 'abc' */ function padEnd(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (string + createPadding(length - strLength, chars)) : string; } /** * Pads `string` on the left side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padStart('abc', 6); * // => ' abc' * * _.padStart('abc', 6, '_-'); * // => '_-_abc' * * _.padStart('abc', 3); * // => 'abc' */ function padStart(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (createPadding(length - strLength, chars) + string) : string; } /** * Converts `string` to an integer of the specified radix. If `radix` is * `undefined` or `0`, a `radix` of `10` is used unless `value` is a * hexadecimal, in which case a `radix` of `16` is used. * * **Note:** This method aligns with the * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. * * @static * @memberOf _ * @since 1.1.0 * @category String * @param {string} string The string to convert. * @param {number} [radix=10] The radix to interpret `value` by. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {number} Returns the converted integer. * @example * * _.parseInt('08'); * // => 8 * * _.map(['6', '08', '10'], _.parseInt); * // => [6, 8, 10] */ function parseInt(string, radix, guard) { if (guard || radix == null) { radix = 0; } else if (radix) { radix = +radix; } return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); } /** * Repeats the given string `n` times. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to repeat. * @param {number} [n=1] The number of times to repeat the string. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the repeated string. * @example * * _.repeat('*', 3); * // => '***' * * _.repeat('abc', 2); * // => 'abcabc' * * _.repeat('abc', 0); * // => '' */ function repeat(string, n, guard) { if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } return baseRepeat(toString(string), n); } /** * Replaces matches for `pattern` in `string` with `replacement`. * * **Note:** This method is based on * [`String#replace`](https://mdn.io/String/replace). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to modify. * @param {RegExp|string} pattern The pattern to replace. * @param {Function|string} replacement The match replacement. * @returns {string} Returns the modified string. * @example * * _.replace('Hi Fred', 'Fred', 'Barney'); * // => 'Hi Barney' */ function replace() { var args = arguments, string = toString(args[0]); return args.length < 3 ? string : string.replace(args[1], args[2]); } /** * Converts `string` to * [snake case](https://en.wikipedia.org/wiki/Snake_case). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the snake cased string. * @example * * _.snakeCase('Foo Bar'); * // => 'foo_bar' * * _.snakeCase('fooBar'); * // => 'foo_bar' * * _.snakeCase('--FOO-BAR--'); * // => 'foo_bar' */ var snakeCase = createCompounder(function(result, word, index) { return result + (index ? '_' : '') + word.toLowerCase(); }); /** * Splits `string` by `separator`. * * **Note:** This method is based on * [`String#split`](https://mdn.io/String/split). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to split. * @param {RegExp|string} separator The separator pattern to split by. * @param {number} [limit] The length to truncate results to. * @returns {Array} Returns the string segments. * @example * * _.split('a-b-c', '-', 2); * // => ['a', 'b'] */ function split(string, separator, limit) { if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { separator = limit = undefined; } limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; if (!limit) { return []; } string = toString(string); if (string && ( typeof separator == 'string' || (separator != null && !isRegExp(separator)) )) { separator = baseToString(separator); if (!separator && hasUnicode(string)) { return castSlice(stringToArray(string), 0, limit); } } return string.split(separator, limit); } /** * Converts `string` to * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). * * @static * @memberOf _ * @since 3.1.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the start cased string. * @example * * _.startCase('--foo-bar--'); * // => 'Foo Bar' * * _.startCase('fooBar'); * // => 'Foo Bar' * * _.startCase('__FOO_BAR__'); * // => 'FOO BAR' */ var startCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + upperFirst(word); }); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } /** * Creates a compiled template function that can interpolate data properties * in "interpolate" delimiters, HTML-escape interpolated data properties in * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data * properties may be accessed as free variables in the template. If a setting * object is given, it takes precedence over `_.templateSettings` values. * * **Note:** In the development build `_.template` utilizes * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) * for easier debugging. * * For more information on precompiling templates see * [lodash's custom builds documentation](https://lodash.com/custom-builds). * * For more information on Chrome extension sandboxes see * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The template string. * @param {Object} [options={}] The options object. * @param {RegExp} [options.escape=_.templateSettings.escape] * The HTML "escape" delimiter. * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] * The "evaluate" delimiter. * @param {Object} [options.imports=_.templateSettings.imports] * An object to import into the template as free variables. * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] * The "interpolate" delimiter. * @param {string} [options.sourceURL='lodash.templateSources[n]'] * The sourceURL of the compiled template. * @param {string} [options.variable='obj'] * The data object variable name. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the compiled template function. * @example * * // Use the "interpolate" delimiter to create a compiled template. * var compiled = _.template('hello <%= user %>!'); * compiled({ 'user': 'fred' }); * // => 'hello fred!' * * // Use the HTML "escape" delimiter to escape data property values. * var compiled = _.template('<b><%- value %></b>'); * compiled({ 'value': '<script>' }); * // => '<b>&lt;script&gt;</b>' * * // Use the "evaluate" delimiter to execute JavaScript and generate HTML. * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the internal `print` function in "evaluate" delimiters. * var compiled = _.template('<% print("hello " + user); %>!'); * compiled({ 'user': 'barney' }); * // => 'hello barney!' * * // Use the ES template literal delimiter as an "interpolate" delimiter. * // Disable support by replacing the "interpolate" delimiter. * var compiled = _.template('hello ${ user }!'); * compiled({ 'user': 'pebbles' }); * // => 'hello pebbles!' * * // Use backslashes to treat delimiters as plain text. * var compiled = _.template('<%= "\\<%- value %\\>" %>'); * compiled({ 'value': 'ignored' }); * // => '<%- value %>' * * // Use the `imports` option to import `jQuery` as `jq`. * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>'; * var compiled = _.template(text, { 'imports': { 'jq': jQuery } }); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the `sourceURL` option to specify a custom sourceURL for the template. * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' }); * compiled(data); * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector. * * // Use the `variable` option to ensure a with-statement isn't used in the compiled template. * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' }); * compiled.source; * // => function(data) { * // var __t, __p = ''; * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!'; * // return __p; * // } * * // Use custom template delimiters. * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; * var compiled = _.template('hello {{ user }}!'); * compiled({ 'user': 'mustache' }); * // => 'hello mustache!' * * // Use the `source` property to inline compiled templates for meaningful * // line numbers in error messages and stack traces. * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\ * var JST = {\ * "main": ' + _.template(mainText).source + '\ * };\ * '); */ function template(string, options, guard) { // Based on John Resig's `tmpl` implementation // (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). var settings = lodash.templateSettings; if (guard && isIterateeCall(string, options, guard)) { options = undefined; } string = toString(string); options = assignInWith({}, options, settings, customDefaultsAssignIn); var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; // Compile the regexp to match each delimiter. var reDelimiters = RegExp( (options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$' , 'g'); // Use a sourceURL for easier debugging. // The sourceURL gets injected into the source that's eval-ed, so be careful // with lookup (in case of e.g. prototype pollution), and strip newlines if any. // A newline wouldn't be a valid sourceURL anyway, and it'd enable code injection. var sourceURL = '//# sourceURL=' + (hasOwnProperty.call(options, 'sourceURL') ? (options.sourceURL + '').replace(/[\r\n]/g, ' ') : ('lodash.templateSources[' + (++templateCounter) + ']') ) + '\n'; string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // Escape characters that can't be included in string literals. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source += "' +\n__e(" + escapeValue + ") +\n'"; } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; // The JS engine embedded in Adobe products needs `match` returned in // order to produce the correct `offset` value. return match; }); source += "';\n"; // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. // Like with sourceURL, we take care to not check the option's prototype, // as this configuration is a code injection vector. var variable = hasOwnProperty.call(options, 'variable') && options.variable; if (!variable) { source = 'with (obj) {\n' + source + '\n}\n'; } // Cleanup code by stripping empty strings. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) .replace(reEmptyStringMiddle, '$1') .replace(reEmptyStringTrailing, '$1;'); // Frame code as the function body. source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n' ) + "var __t, __p = ''" + (isEscaping ? ', __e = _.escape' : '' ) + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n' ) + source + 'return __p\n}'; var result = attempt(function() { return Function(importsKeys, sourceURL + 'return ' + source) .apply(undefined, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; } /** * Converts `string`, as a whole, to lower case just like * [String#toLowerCase](https://mdn.io/toLowerCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.toLower('--Foo-Bar--'); * // => '--foo-bar--' * * _.toLower('fooBar'); * // => 'foobar' * * _.toLower('__FOO_BAR__'); * // => '__foo_bar__' */ function toLower(value) { return toString(value).toLowerCase(); } /** * Converts `string`, as a whole, to upper case just like * [String#toUpperCase](https://mdn.io/toUpperCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.toUpper('--foo-bar--'); * // => '--FOO-BAR--' * * _.toUpper('fooBar'); * // => 'FOOBAR' * * _.toUpper('__foo_bar__'); * // => '__FOO_BAR__' */ function toUpper(value) { return toString(value).toUpperCase(); } /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; return castSlice(strSymbols, start, end).join(''); } /** * Removes trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimEnd(' abc '); * // => ' abc' * * _.trimEnd('-_-abc-_-', '_-'); * // => '-_-abc' */ function trimEnd(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimEnd, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; return castSlice(strSymbols, 0, end).join(''); } /** * Removes leading whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimStart(' abc '); * // => 'abc ' * * _.trimStart('-_-abc-_-', '_-'); * // => 'abc-_-' */ function trimStart(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimStart, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), start = charsStartIndex(strSymbols, stringToArray(chars)); return castSlice(strSymbols, start).join(''); } /** * Truncates `string` if it's longer than the given maximum string length. * The last characters of the truncated string are replaced with the omission * string which defaults to "...". * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to truncate. * @param {Object} [options={}] The options object. * @param {number} [options.length=30] The maximum string length. * @param {string} [options.omission='...'] The string to indicate text is omitted. * @param {RegExp|string} [options.separator] The separator pattern to truncate to. * @returns {string} Returns the truncated string. * @example * * _.truncate('hi-diddly-ho there, neighborino'); * // => 'hi-diddly-ho there, neighbo...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': ' ' * }); * // => 'hi-diddly-ho there,...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': /,? +/ * }); * // => 'hi-diddly-ho there...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'omission': ' [...]' * }); * // => 'hi-diddly-ho there, neig [...]' */ function truncate(string, options) { var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; if (isObject(options)) { var separator = 'separator' in options ? options.separator : separator; length = 'length' in options ? toInteger(options.length) : length; omission = 'omission' in options ? baseToString(options.omission) : omission; } string = toString(string); var strLength = string.length; if (hasUnicode(string)) { var strSymbols = stringToArray(string); strLength = strSymbols.length; } if (length >= strLength) { return string; } var end = length - stringSize(omission); if (end < 1) { return omission; } var result = strSymbols ? castSlice(strSymbols, 0, end).join('') : string.slice(0, end); if (separator === undefined) { return result + omission; } if (strSymbols) { end += (result.length - end); } if (isRegExp(separator)) { if (string.slice(end).search(separator)) { var match, substring = result; if (!separator.global) { separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g'); } separator.lastIndex = 0; while ((match = separator.exec(substring))) { var newEnd = match.index; } result = result.slice(0, newEnd === undefined ? end : newEnd); } } else if (string.indexOf(baseToString(separator), end) != end) { var index = result.lastIndexOf(separator); if (index > -1) { result = result.slice(0, index); } } return result + omission; } /** * The inverse of `_.escape`; this method converts the HTML entities * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to * their corresponding characters. * * **Note:** No other HTML entities are unescaped. To unescape additional * HTML entities use a third-party library like [_he_](https://mths.be/he). * * @static * @memberOf _ * @since 0.6.0 * @category String * @param {string} [string=''] The string to unescape. * @returns {string} Returns the unescaped string. * @example * * _.unescape('fred, barney, &amp; pebbles'); * // => 'fred, barney, & pebbles' */ function unescape(string) { string = toString(string); return (string && reHasEscapedHtml.test(string)) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string; } /** * Converts `string`, as space separated words, to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.upperCase('--foo-bar'); * // => 'FOO BAR' * * _.upperCase('fooBar'); * // => 'FOO BAR' * * _.upperCase('__foo_bar__'); * // => 'FOO BAR' */ var upperCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toUpperCase(); }); /** * Converts the first character of `string` to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.upperFirst('fred'); * // => 'Fred' * * _.upperFirst('FRED'); * // => 'FRED' */ var upperFirst = createCaseFirst('toUpperCase'); /** * Splits `string` into an array of its words. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {RegExp|string} [pattern] The pattern to match words. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the words of `string`. * @example * * _.words('fred, barney, & pebbles'); * // => ['fred', 'barney', 'pebbles'] * * _.words('fred, barney, & pebbles', /[^, ]+/g); * // => ['fred', 'barney', '&', 'pebbles'] */ function words(string, pattern, guard) { string = toString(string); pattern = guard ? undefined : pattern; if (pattern === undefined) { return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); } return string.match(pattern) || []; } /*------------------------------------------------------------------------*/ /** * Attempts to invoke `func`, returning either the result or the caught error * object. Any additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Function} func The function to attempt. * @param {...*} [args] The arguments to invoke `func` with. * @returns {*} Returns the `func` result or error object. * @example * * // Avoid throwing errors for invalid selectors. * var elements = _.attempt(function(selector) { * return document.querySelectorAll(selector); * }, '>_>'); * * if (_.isError(elements)) { * elements = []; * } */ var attempt = baseRest(function(func, args) { try { return apply(func, undefined, args); } catch (e) { return isError(e) ? e : new Error(e); } }); /** * Binds methods of an object to the object itself, overwriting the existing * method. * * **Note:** This method doesn't set the "length" property of bound functions. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Object} object The object to bind and assign the bound methods to. * @param {...(string|string[])} methodNames The object method names to bind. * @returns {Object} Returns `object`. * @example * * var view = { * 'label': 'docs', * 'click': function() { * console.log('clicked ' + this.label); * } * }; * * _.bindAll(view, ['click']); * jQuery(element).on('click', view.click); * // => Logs 'clicked docs' when clicked. */ var bindAll = flatRest(function(object, methodNames) { arrayEach(methodNames, function(key) { key = toKey(key); baseAssignValue(object, key, bind(object[key], object)); }); return object; }); /** * Creates a function that iterates over `pairs` and invokes the corresponding * function of the first predicate to return truthy. The predicate-function * pairs are invoked with the `this` binding and arguments of the created * function. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Array} pairs The predicate-function pairs. * @returns {Function} Returns the new composite function. * @example * * var func = _.cond([ * [_.matches({ 'a': 1 }), _.constant('matches A')], * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')], * [_.stubTrue, _.constant('no match')] * ]); * * func({ 'a': 1, 'b': 2 }); * // => 'matches A' * * func({ 'a': 0, 'b': 1 }); * // => 'matches B' * * func({ 'a': '1', 'b': '2' }); * // => 'no match' */ function cond(pairs) { var length = pairs == null ? 0 : pairs.length, toIteratee = getIteratee(); pairs = !length ? [] : arrayMap(pairs, function(pair) { if (typeof pair[1] != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return [toIteratee(pair[0]), pair[1]]; }); return baseRest(function(args) { var index = -1; while (++index < length) { var pair = pairs[index]; if (apply(pair[0], this, args)) { return apply(pair[1], this, args); } } }); } /** * Creates a function that invokes the predicate properties of `source` with * the corresponding property values of a given object, returning `true` if * all predicates return truthy, else `false`. * * **Note:** The created function is equivalent to `_.conformsTo` with * `source` partially applied. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 2, 'b': 1 }, * { 'a': 1, 'b': 2 } * ]; * * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } })); * // => [{ 'a': 1, 'b': 2 }] */ function conforms(source) { return baseConforms(baseClone(source, CLONE_DEEP_FLAG)); } /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } /** * Checks `value` to determine whether a default value should be returned in * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, * or `undefined`. * * @static * @memberOf _ * @since 4.14.0 * @category Util * @param {*} value The value to check. * @param {*} defaultValue The default value. * @returns {*} Returns the resolved value. * @example * * _.defaultTo(1, 10); * // => 1 * * _.defaultTo(undefined, 10); * // => 10 */ function defaultTo(value, defaultValue) { return (value == null || value !== value) ? defaultValue : value; } /** * Creates a function that returns the result of invoking the given functions * with the `this` binding of the created function, where each successive * invocation is supplied the return value of the previous. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {...(Function|Function[])} [funcs] The functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flowRight * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flow([_.add, square]); * addSquare(1, 2); * // => 9 */ var flow = createFlow(); /** * This method is like `_.flow` except that it creates a function that * invokes the given functions from right to left. * * @static * @since 3.0.0 * @memberOf _ * @category Util * @param {...(Function|Function[])} [funcs] The functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flow * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flowRight([square, _.add]); * addSquare(1, 2); * // => 9 */ var flowRight = createFlow(true); /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } /** * Creates a function that invokes `func` with the arguments of the created * function. If `func` is a property name, the created function returns the * property value for a given element. If `func` is an array or object, the * created function returns `true` for elements that contain the equivalent * source properties, otherwise it returns `false`. * * @static * @since 4.0.0 * @memberOf _ * @category Util * @param {*} [func=_.identity] The value to convert to a callback. * @returns {Function} Returns the callback. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); * // => [{ 'user': 'barney', 'age': 36, 'active': true }] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, _.iteratee(['user', 'fred'])); * // => [{ 'user': 'fred', 'age': 40 }] * * // The `_.property` iteratee shorthand. * _.map(users, _.iteratee('user')); * // => ['barney', 'fred'] * * // Create custom iteratee shorthands. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { * return !_.isRegExp(func) ? iteratee(func) : function(string) { * return func.test(string); * }; * }); * * _.filter(['abc', 'def'], /ef/); * // => ['def'] */ function iteratee(func) { return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG)); } /** * Creates a function that performs a partial deep comparison between a given * object and `source`, returning `true` if the given object has equivalent * property values, else `false`. * * **Note:** The created function is equivalent to `_.isMatch` with `source` * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 1, 'b': 2, 'c': 3 }, * { 'a': 4, 'b': 5, 'c': 6 } * ]; * * _.filter(objects, _.matches({ 'a': 4, 'c': 6 })); * // => [{ 'a': 4, 'b': 5, 'c': 6 }] */ function matches(source) { return baseMatches(baseClone(source, CLONE_DEEP_FLAG)); } /** * Creates a function that performs a partial deep comparison between the * value at `path` of a given object to `srcValue`, returning `true` if the * object value is equivalent, else `false`. * * **Note:** Partial comparisons will match empty array and empty object * `srcValue` values against any array or object value, respectively. See * `_.isEqual` for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.2.0 * @category Util * @param {Array|string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 1, 'b': 2, 'c': 3 }, * { 'a': 4, 'b': 5, 'c': 6 } * ]; * * _.find(objects, _.matchesProperty('a', 4)); * // => { 'a': 4, 'b': 5, 'c': 6 } */ function matchesProperty(path, srcValue) { return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG)); } /** * Creates a function that invokes the method at `path` of a given object. * Any additional arguments are provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var objects = [ * { 'a': { 'b': _.constant(2) } }, * { 'a': { 'b': _.constant(1) } } * ]; * * _.map(objects, _.method('a.b')); * // => [2, 1] * * _.map(objects, _.method(['a', 'b'])); * // => [2, 1] */ var method = baseRest(function(path, args) { return function(object) { return baseInvoke(object, path, args); }; }); /** * The opposite of `_.method`; this method creates a function that invokes * the method at a given path of `object`. Any additional arguments are * provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Object} object The object to query. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var array = _.times(3, _.constant), * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.methodOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.methodOf(object)); * // => [2, 0] */ var methodOf = baseRest(function(object, args) { return function(path) { return baseInvoke(object, path, args); }; }); /** * Adds all own enumerable string keyed function properties of a source * object to the destination object. If `object` is a function, then methods * are added to its prototype as well. * * **Note:** Use `_.runInContext` to create a pristine `lodash` function to * avoid conflicts caused by modifying the original. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Function|Object} [object=lodash] The destination object. * @param {Object} source The object of functions to add. * @param {Object} [options={}] The options object. * @param {boolean} [options.chain=true] Specify whether mixins are chainable. * @returns {Function|Object} Returns `object`. * @example * * function vowels(string) { * return _.filter(string, function(v) { * return /[aeiou]/i.test(v); * }); * } * * _.mixin({ 'vowels': vowels }); * _.vowels('fred'); * // => ['e'] * * _('fred').vowels().value(); * // => ['e'] * * _.mixin({ 'vowels': vowels }, { 'chain': false }); * _('fred').vowels(); * // => ['e'] */ function mixin(object, source, options) { var props = keys(source), methodNames = baseFunctions(source, props); if (options == null && !(isObject(source) && (methodNames.length || !props.length))) { options = source; source = object; object = this; methodNames = baseFunctions(source, keys(source)); } var chain = !(isObject(options) && 'chain' in options) || !!options.chain, isFunc = isFunction(object); arrayEach(methodNames, function(methodName) { var func = source[methodName]; object[methodName] = func; if (isFunc) { object.prototype[methodName] = function() { var chainAll = this.__chain__; if (chain || chainAll) { var result = object(this.__wrapped__), actions = result.__actions__ = copyArray(this.__actions__); actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); result.__chain__ = chainAll; return result; } return func.apply(object, arrayPush([this.value()], arguments)); }; } }); return object; } /** * Reverts the `_` variable to its previous value and returns a reference to * the `lodash` function. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @returns {Function} Returns the `lodash` function. * @example * * var lodash = _.noConflict(); */ function noConflict() { if (root._ === this) { root._ = oldDash; } return this; } /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() { // No operation performed. } /** * Creates a function that gets the argument at index `n`. If `n` is negative, * the nth argument from the end is returned. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [n=0] The index of the argument to return. * @returns {Function} Returns the new pass-thru function. * @example * * var func = _.nthArg(1); * func('a', 'b', 'c', 'd'); * // => 'b' * * var func = _.nthArg(-2); * func('a', 'b', 'c', 'd'); * // => 'c' */ function nthArg(n) { n = toInteger(n); return baseRest(function(args) { return baseNth(args, n); }); } /** * Creates a function that invokes `iteratees` with the arguments it receives * and returns their results. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to invoke. * @returns {Function} Returns the new function. * @example * * var func = _.over([Math.max, Math.min]); * * func(1, 2, 3, 4); * // => [4, 1] */ var over = createOver(arrayMap); /** * Creates a function that checks if **all** of the `predicates` return * truthy when invoked with the arguments it receives. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [predicates=[_.identity]] * The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overEvery([Boolean, isFinite]); * * func('1'); * // => true * * func(null); * // => false * * func(NaN); * // => false */ var overEvery = createOver(arrayEvery); /** * Creates a function that checks if **any** of the `predicates` return * truthy when invoked with the arguments it receives. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [predicates=[_.identity]] * The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overSome([Boolean, isFinite]); * * func('1'); * // => true * * func(null); * // => true * * func(NaN); * // => false */ var overSome = createOver(arraySome); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } /** * The opposite of `_.property`; this method creates a function that returns * the value at a given path of `object`. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. * @example * * var array = [0, 1, 2], * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); * // => [2, 0] */ function propertyOf(object) { return function(path) { return object == null ? undefined : baseGet(object, path); }; } /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. A step of `-1` is used if a negative * `start` is specified without an `end` or `step`. If `end` is not specified, * it's set to `start` with `start` then set to `0`. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.rangeRight * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(-4); * // => [0, -1, -2, -3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ var range = createRange(); /** * This method is like `_.range` except that it populates values in * descending order. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.range * @example * * _.rangeRight(4); * // => [3, 2, 1, 0] * * _.rangeRight(-4); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 5); * // => [4, 3, 2, 1] * * _.rangeRight(0, 20, 5); * // => [15, 10, 5, 0] * * _.rangeRight(0, -4, -1); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 4, 0); * // => [1, 1, 1] * * _.rangeRight(0); * // => [] */ var rangeRight = createRange(true); /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } /** * This method returns a new empty object. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Object} Returns the new empty object. * @example * * var objects = _.times(2, _.stubObject); * * console.log(objects); * // => [{}, {}] * * console.log(objects[0] === objects[1]); * // => false */ function stubObject() { return {}; } /** * This method returns an empty string. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {string} Returns the empty string. * @example * * _.times(2, _.stubString); * // => ['', ''] */ function stubString() { return ''; } /** * This method returns `true`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `true`. * @example * * _.times(2, _.stubTrue); * // => [true, true] */ function stubTrue() { return true; } /** * Invokes the iteratee `n` times, returning an array of the results of * each invocation. The iteratee is invoked with one argument; (index). * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} n The number of times to invoke `iteratee`. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of results. * @example * * _.times(3, String); * // => ['0', '1', '2'] * * _.times(4, _.constant(0)); * // => [0, 0, 0, 0] */ function times(n, iteratee) { n = toInteger(n); if (n < 1 || n > MAX_SAFE_INTEGER) { return []; } var index = MAX_ARRAY_LENGTH, length = nativeMin(n, MAX_ARRAY_LENGTH); iteratee = getIteratee(iteratee); n -= MAX_ARRAY_LENGTH; var result = baseTimes(length, iteratee); while (++index < n) { iteratee(index); } return result; } /** * Converts `value` to a property path array. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {*} value The value to convert. * @returns {Array} Returns the new property path array. * @example * * _.toPath('a.b.c'); * // => ['a', 'b', 'c'] * * _.toPath('a[0].b.c'); * // => ['a', '0', 'b', 'c'] */ function toPath(value) { if (isArray(value)) { return arrayMap(value, toKey); } return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value))); } /** * Generates a unique ID. If `prefix` is given, the ID is appended to it. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {string} [prefix=''] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return toString(prefix) + id; } /*------------------------------------------------------------------------*/ /** * Adds two numbers. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {number} augend The first number in an addition. * @param {number} addend The second number in an addition. * @returns {number} Returns the total. * @example * * _.add(6, 4); * // => 10 */ var add = createMathOperation(function(augend, addend) { return augend + addend; }, 0); /** * Computes `number` rounded up to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round up. * @param {number} [precision=0] The precision to round up to. * @returns {number} Returns the rounded up number. * @example * * _.ceil(4.006); * // => 5 * * _.ceil(6.004, 2); * // => 6.01 * * _.ceil(6040, -2); * // => 6100 */ var ceil = createRound('ceil'); /** * Divide two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} dividend The first number in a division. * @param {number} divisor The second number in a division. * @returns {number} Returns the quotient. * @example * * _.divide(6, 4); * // => 1.5 */ var divide = createMathOperation(function(dividend, divisor) { return dividend / divisor; }, 1); /** * Computes `number` rounded down to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round down. * @param {number} [precision=0] The precision to round down to. * @returns {number} Returns the rounded down number. * @example * * _.floor(4.006); * // => 4 * * _.floor(0.046, 2); * // => 0.04 * * _.floor(4060, -2); * // => 4000 */ var floor = createRound('floor'); /** * Computes the maximum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the maximum value. * @example * * _.max([4, 2, 8, 6]); * // => 8 * * _.max([]); * // => undefined */ function max(array) { return (array && array.length) ? baseExtremum(array, identity, baseGt) : undefined; } /** * This method is like `_.max` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the maximum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.maxBy(objects, function(o) { return o.n; }); * // => { 'n': 2 } * * // The `_.property` iteratee shorthand. * _.maxBy(objects, 'n'); * // => { 'n': 2 } */ function maxBy(array, iteratee) { return (array && array.length) ? baseExtremum(array, getIteratee(iteratee, 2), baseGt) : undefined; } /** * Computes the mean of the values in `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the mean. * @example * * _.mean([4, 2, 8, 6]); * // => 5 */ function mean(array) { return baseMean(array, identity); } /** * This method is like `_.mean` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be averaged. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the mean. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.meanBy(objects, function(o) { return o.n; }); * // => 5 * * // The `_.property` iteratee shorthand. * _.meanBy(objects, 'n'); * // => 5 */ function meanBy(array, iteratee) { return baseMean(array, getIteratee(iteratee, 2)); } /** * Computes the minimum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the minimum value. * @example * * _.min([4, 2, 8, 6]); * // => 2 * * _.min([]); * // => undefined */ function min(array) { return (array && array.length) ? baseExtremum(array, identity, baseLt) : undefined; } /** * This method is like `_.min` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the minimum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.minBy(objects, function(o) { return o.n; }); * // => { 'n': 1 } * * // The `_.property` iteratee shorthand. * _.minBy(objects, 'n'); * // => { 'n': 1 } */ function minBy(array, iteratee) { return (array && array.length) ? baseExtremum(array, getIteratee(iteratee, 2), baseLt) : undefined; } /** * Multiply two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} multiplier The first number in a multiplication. * @param {number} multiplicand The second number in a multiplication. * @returns {number} Returns the product. * @example * * _.multiply(6, 4); * // => 24 */ var multiply = createMathOperation(function(multiplier, multiplicand) { return multiplier * multiplicand; }, 1); /** * Computes `number` rounded to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round. * @param {number} [precision=0] The precision to round to. * @returns {number} Returns the rounded number. * @example * * _.round(4.006); * // => 4 * * _.round(4.006, 2); * // => 4.01 * * _.round(4060, -2); * // => 4100 */ var round = createRound('round'); /** * Subtract two numbers. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {number} minuend The first number in a subtraction. * @param {number} subtrahend The second number in a subtraction. * @returns {number} Returns the difference. * @example * * _.subtract(6, 4); * // => 2 */ var subtract = createMathOperation(function(minuend, subtrahend) { return minuend - subtrahend; }, 0); /** * Computes the sum of the values in `array`. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the sum. * @example * * _.sum([4, 2, 8, 6]); * // => 20 */ function sum(array) { return (array && array.length) ? baseSum(array, identity) : 0; } /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? baseSum(array, getIteratee(iteratee, 2)) : 0; } /*------------------------------------------------------------------------*/ // Add methods that return wrapped values in chain sequences. lodash.after = after; lodash.ary = ary; lodash.assign = assign; lodash.assignIn = assignIn; lodash.assignInWith = assignInWith; lodash.assignWith = assignWith; lodash.at = at; lodash.before = before; lodash.bind = bind; lodash.bindAll = bindAll; lodash.bindKey = bindKey; lodash.castArray = castArray; lodash.chain = chain; lodash.chunk = chunk; lodash.compact = compact; lodash.concat = concat; lodash.cond = cond; lodash.conforms = conforms; lodash.constant = constant; lodash.countBy = countBy; lodash.create = create; lodash.curry = curry; lodash.curryRight = curryRight; lodash.debounce = debounce; lodash.defaults = defaults; lodash.defaultsDeep = defaultsDeep; lodash.defer = defer; lodash.delay = delay; lodash.difference = difference; lodash.differenceBy = differenceBy; lodash.differenceWith = differenceWith; lodash.drop = drop; lodash.dropRight = dropRight; lodash.dropRightWhile = dropRightWhile; lodash.dropWhile = dropWhile; lodash.fill = fill; lodash.filter = filter; lodash.flatMap = flatMap; lodash.flatMapDeep = flatMapDeep; lodash.flatMapDepth = flatMapDepth; lodash.flatten = flatten; lodash.flattenDeep = flattenDeep; lodash.flattenDepth = flattenDepth; lodash.flip = flip; lodash.flow = flow; lodash.flowRight = flowRight; lodash.fromPairs = fromPairs; lodash.functions = functions; lodash.functionsIn = functionsIn; lodash.groupBy = groupBy; lodash.initial = initial; lodash.intersection = intersection; lodash.intersectionBy = intersectionBy; lodash.intersectionWith = intersectionWith; lodash.invert = invert; lodash.invertBy = invertBy; lodash.invokeMap = invokeMap; lodash.iteratee = iteratee; lodash.keyBy = keyBy; lodash.keys = keys; lodash.keysIn = keysIn; lodash.map = map; lodash.mapKeys = mapKeys; lodash.mapValues = mapValues; lodash.matches = matches; lodash.matchesProperty = matchesProperty; lodash.memoize = memoize; lodash.merge = merge; lodash.mergeWith = mergeWith; lodash.method = method; lodash.methodOf = methodOf; lodash.mixin = mixin; lodash.negate = negate; lodash.nthArg = nthArg; lodash.omit = omit; lodash.omitBy = omitBy; lodash.once = once; lodash.orderBy = orderBy; lodash.over = over; lodash.overArgs = overArgs; lodash.overEvery = overEvery; lodash.overSome = overSome; lodash.partial = partial; lodash.partialRight = partialRight; lodash.partition = partition; lodash.pick = pick; lodash.pickBy = pickBy; lodash.property = property; lodash.propertyOf = propertyOf; lodash.pull = pull; lodash.pullAll = pullAll; lodash.pullAllBy = pullAllBy; lodash.pullAllWith = pullAllWith; lodash.pullAt = pullAt; lodash.range = range; lodash.rangeRight = rangeRight; lodash.rearg = rearg; lodash.reject = reject; lodash.remove = remove; lodash.rest = rest; lodash.reverse = reverse; lodash.sampleSize = sampleSize; lodash.set = set; lodash.setWith = setWith; lodash.shuffle = shuffle; lodash.slice = slice; lodash.sortBy = sortBy; lodash.sortedUniq = sortedUniq; lodash.sortedUniqBy = sortedUniqBy; lodash.split = split; lodash.spread = spread; lodash.tail = tail; lodash.take = take; lodash.takeRight = takeRight; lodash.takeRightWhile = takeRightWhile; lodash.takeWhile = takeWhile; lodash.tap = tap; lodash.throttle = throttle; lodash.thru = thru; lodash.toArray = toArray; lodash.toPairs = toPairs; lodash.toPairsIn = toPairsIn; lodash.toPath = toPath; lodash.toPlainObject = toPlainObject; lodash.transform = transform; lodash.unary = unary; lodash.union = union; lodash.unionBy = unionBy; lodash.unionWith = unionWith; lodash.uniq = uniq; lodash.uniqBy = uniqBy; lodash.uniqWith = uniqWith; lodash.unset = unset; lodash.unzip = unzip; lodash.unzipWith = unzipWith; lodash.update = update; lodash.updateWith = updateWith; lodash.values = values; lodash.valuesIn = valuesIn; lodash.without = without; lodash.words = words; lodash.wrap = wrap; lodash.xor = xor; lodash.xorBy = xorBy; lodash.xorWith = xorWith; lodash.zip = zip; lodash.zipObject = zipObject; lodash.zipObjectDeep = zipObjectDeep; lodash.zipWith = zipWith; // Add aliases. lodash.entries = toPairs; lodash.entriesIn = toPairsIn; lodash.extend = assignIn; lodash.extendWith = assignInWith; // Add methods to `lodash.prototype`. mixin(lodash, lodash); /*------------------------------------------------------------------------*/ // Add methods that return unwrapped values in chain sequences. lodash.add = add; lodash.attempt = attempt; lodash.camelCase = camelCase; lodash.capitalize = capitalize; lodash.ceil = ceil; lodash.clamp = clamp; lodash.clone = clone; lodash.cloneDeep = cloneDeep; lodash.cloneDeepWith = cloneDeepWith; lodash.cloneWith = cloneWith; lodash.conformsTo = conformsTo; lodash.deburr = deburr; lodash.defaultTo = defaultTo; lodash.divide = divide; lodash.endsWith = endsWith; lodash.eq = eq; lodash.escape = escape; lodash.escapeRegExp = escapeRegExp; lodash.every = every; lodash.find = find; lodash.findIndex = findIndex; lodash.findKey = findKey; lodash.findLast = findLast; lodash.findLastIndex = findLastIndex; lodash.findLastKey = findLastKey; lodash.floor = floor; lodash.forEach = forEach; lodash.forEachRight = forEachRight; lodash.forIn = forIn; lodash.forInRight = forInRight; lodash.forOwn = forOwn; lodash.forOwnRight = forOwnRight; lodash.get = get; lodash.gt = gt; lodash.gte = gte; lodash.has = has; lodash.hasIn = hasIn; lodash.head = head; lodash.identity = identity; lodash.includes = includes; lodash.indexOf = indexOf; lodash.inRange = inRange; lodash.invoke = invoke; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isArrayBuffer = isArrayBuffer; lodash.isArrayLike = isArrayLike; lodash.isArrayLikeObject = isArrayLikeObject; lodash.isBoolean = isBoolean; lodash.isBuffer = isBuffer; lodash.isDate = isDate; lodash.isElement = isElement; lodash.isEmpty = isEmpty; lodash.isEqual = isEqual; lodash.isEqualWith = isEqualWith; lodash.isError = isError; lodash.isFinite = isFinite; lodash.isFunction = isFunction; lodash.isInteger = isInteger; lodash.isLength = isLength; lodash.isMap = isMap; lodash.isMatch = isMatch; lodash.isMatchWith = isMatchWith; lodash.isNaN = isNaN; lodash.isNative = isNative; lodash.isNil = isNil; lodash.isNull = isNull; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isObjectLike = isObjectLike; lodash.isPlainObject = isPlainObject; lodash.isRegExp = isRegExp; lodash.isSafeInteger = isSafeInteger; lodash.isSet = isSet; lodash.isString = isString; lodash.isSymbol = isSymbol; lodash.isTypedArray = isTypedArray; lodash.isUndefined = isUndefined; lodash.isWeakMap = isWeakMap; lodash.isWeakSet = isWeakSet; lodash.join = join; lodash.kebabCase = kebabCase; lodash.last = last; lodash.lastIndexOf = lastIndexOf; lodash.lowerCase = lowerCase; lodash.lowerFirst = lowerFirst; lodash.lt = lt; lodash.lte = lte; lodash.max = max; lodash.maxBy = maxBy; lodash.mean = mean; lodash.meanBy = meanBy; lodash.min = min; lodash.minBy = minBy; lodash.stubArray = stubArray; lodash.stubFalse = stubFalse; lodash.stubObject = stubObject; lodash.stubString = stubString; lodash.stubTrue = stubTrue; lodash.multiply = multiply; lodash.nth = nth; lodash.noConflict = noConflict; lodash.noop = noop; lodash.now = now; lodash.pad = pad; lodash.padEnd = padEnd; lodash.padStart = padStart; lodash.parseInt = parseInt; lodash.random = random; lodash.reduce = reduce; lodash.reduceRight = reduceRight; lodash.repeat = repeat; lodash.replace = replace; lodash.result = result; lodash.round = round; lodash.runInContext = runInContext; lodash.sample = sample; lodash.size = size; lodash.snakeCase = snakeCase; lodash.some = some; lodash.sortedIndex = sortedIndex; lodash.sortedIndexBy = sortedIndexBy; lodash.sortedIndexOf = sortedIndexOf; lodash.sortedLastIndex = sortedLastIndex; lodash.sortedLastIndexBy = sortedLastIndexBy; lodash.sortedLastIndexOf = sortedLastIndexOf; lodash.startCase = startCase; lodash.startsWith = startsWith; lodash.subtract = subtract; lodash.sum = sum; lodash.sumBy = sumBy; lodash.template = template; lodash.times = times; lodash.toFinite = toFinite; lodash.toInteger = toInteger; lodash.toLength = toLength; lodash.toLower = toLower; lodash.toNumber = toNumber; lodash.toSafeInteger = toSafeInteger; lodash.toString = toString; lodash.toUpper = toUpper; lodash.trim = trim; lodash.trimEnd = trimEnd; lodash.trimStart = trimStart; lodash.truncate = truncate; lodash.unescape = unescape; lodash.uniqueId = uniqueId; lodash.upperCase = upperCase; lodash.upperFirst = upperFirst; // Add aliases. lodash.each = forEach; lodash.eachRight = forEachRight; lodash.first = head; mixin(lodash, (function() { var source = {}; baseForOwn(lodash, function(func, methodName) { if (!hasOwnProperty.call(lodash.prototype, methodName)) { source[methodName] = func; } }); return source; }()), { 'chain': false }); /*------------------------------------------------------------------------*/ /** * The semantic version number. * * @static * @memberOf _ * @type {string} */ lodash.VERSION = VERSION; // Assign default placeholders. arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) { lodash[methodName].placeholder = lodash; }); // Add `LazyWrapper` methods for `_.drop` and `_.take` variants. arrayEach(['drop', 'take'], function(methodName, index) { LazyWrapper.prototype[methodName] = function(n) { n = n === undefined ? 1 : nativeMax(toInteger(n), 0); var result = (this.__filtered__ && !index) ? new LazyWrapper(this) : this.clone(); if (result.__filtered__) { result.__takeCount__ = nativeMin(n, result.__takeCount__); } else { result.__views__.push({ 'size': nativeMin(n, MAX_ARRAY_LENGTH), 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') }); } return result; }; LazyWrapper.prototype[methodName + 'Right'] = function(n) { return this.reverse()[methodName](n).reverse(); }; }); // Add `LazyWrapper` methods that accept an `iteratee` value. arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) { var type = index + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; LazyWrapper.prototype[methodName] = function(iteratee) { var result = this.clone(); result.__iteratees__.push({ 'iteratee': getIteratee(iteratee, 3), 'type': type }); result.__filtered__ = result.__filtered__ || isFilter; return result; }; }); // Add `LazyWrapper` methods for `_.head` and `_.last`. arrayEach(['head', 'last'], function(methodName, index) { var takeName = 'take' + (index ? 'Right' : ''); LazyWrapper.prototype[methodName] = function() { return this[takeName](1).value()[0]; }; }); // Add `LazyWrapper` methods for `_.initial` and `_.tail`. arrayEach(['initial', 'tail'], function(methodName, index) { var dropName = 'drop' + (index ? '' : 'Right'); LazyWrapper.prototype[methodName] = function() { return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); }; }); LazyWrapper.prototype.compact = function() { return this.filter(identity); }; LazyWrapper.prototype.find = function(predicate) { return this.filter(predicate).head(); }; LazyWrapper.prototype.findLast = function(predicate) { return this.reverse().find(predicate); }; LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { if (typeof path == 'function') { return new LazyWrapper(this); } return this.map(function(value) { return baseInvoke(value, path, args); }); }); LazyWrapper.prototype.reject = function(predicate) { return this.filter(negate(getIteratee(predicate))); }; LazyWrapper.prototype.slice = function(start, end) { start = toInteger(start); var result = this; if (result.__filtered__ && (start > 0 || end < 0)) { return new LazyWrapper(result); } if (start < 0) { result = result.takeRight(-start); } else if (start) { result = result.drop(start); } if (end !== undefined) { end = toInteger(end); result = end < 0 ? result.dropRight(-end) : result.take(end - start); } return result; }; LazyWrapper.prototype.takeRightWhile = function(predicate) { return this.reverse().takeWhile(predicate).reverse(); }; LazyWrapper.prototype.toArray = function() { return this.take(MAX_ARRAY_LENGTH); }; // Add `LazyWrapper` methods to `lodash.prototype`. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName], retUnwrapped = isTaker || /^find/.test(methodName); if (!lodashFunc) { return; } lodash.prototype[methodName] = function() { var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee = args[0], useLazy = isLazy || isArray(value); var interceptor = function(value) { var result = lodashFunc.apply(lodash, arrayPush([value], args)); return (isTaker && chainAll) ? result[0] : result; }; if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) { // Avoid lazy use if the iteratee has a "length" value other than `1`. isLazy = useLazy = false; } var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid; if (!retUnwrapped && useLazy) { value = onlyLazy ? value : new LazyWrapper(this); var result = func.apply(value, args); result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(result, chainAll); } if (isUnwrapped && onlyLazy) { return func.apply(this, args); } result = this.thru(interceptor); return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result; }; }); // Add `Array` methods to `lodash.prototype`. arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', retUnwrapped = /^(?:pop|shift)$/.test(methodName); lodash.prototype[methodName] = function() { var args = arguments; if (retUnwrapped && !this.__chain__) { var value = this.value(); return func.apply(isArray(value) ? value : [], args); } return this[chainName](function(value) { return func.apply(isArray(value) ? value : [], args); }); }; }); // Map minified method names to their real names. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var lodashFunc = lodash[methodName]; if (lodashFunc) { var key = lodashFunc.name + ''; if (!hasOwnProperty.call(realNames, key)) { realNames[key] = []; } realNames[key].push({ 'name': methodName, 'func': lodashFunc }); } }); realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': undefined }]; // Add methods to `LazyWrapper`. LazyWrapper.prototype.clone = lazyClone; LazyWrapper.prototype.reverse = lazyReverse; LazyWrapper.prototype.value = lazyValue; // Add chain sequence methods to the `lodash` wrapper. lodash.prototype.at = wrapperAt; lodash.prototype.chain = wrapperChain; lodash.prototype.commit = wrapperCommit; lodash.prototype.next = wrapperNext; lodash.prototype.plant = wrapperPlant; lodash.prototype.reverse = wrapperReverse; lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; // Add lazy aliases. lodash.prototype.first = lodash.prototype.head; if (symIterator) { lodash.prototype[symIterator] = wrapperToIterator; } return lodash; }); /*--------------------------------------------------------------------------*/ // Export lodash. var _ = runInContext(); // Some AMD build optimizers, like r.js, check for condition patterns like: if (true) { // Expose Lodash on the global object to prevent errors when Lodash is // loaded by a script tag in the presence of an AMD loader. // See http://requirejs.org/docs/errors.html#mismatch for more details. // Use `_.noConflict` to remove Lodash from the global object. root._ = _; // Define as an anonymous module so, through path mapping, it can be // referenced as the "underscore" module. !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return _; }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } // Check for `exports` after `define` in case a build optimizer adds it. else if (freeModule) { // Export for Node.js. (freeModule.exports = _)._ = _; // Export for CommonJS support. freeExports._ = _; } else { // Export to the global object. root._ = _; } }.call(this)); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5), __webpack_require__(6)(module))) /***/ }), /* 5 */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || Function("return this")() || (1,eval)("this"); } catch(e) { // This works if the window reference is available if(typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /* 6 */ /***/ (function(module, exports) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default if(!module.children) module.children = []; Object.defineProperty(module, "loaded", { enumerable: true, get: function() { return module.l; } }); Object.defineProperty(module, "id", { enumerable: true, get: function() { return module.i; } }); module.webpackPolyfill = 1; } return module; }; /***/ }) /******/ ])});; //# sourceMappingURL=index.js.map
/** * Created by Jian Ping Xu on 5/22/2017. */ var mongo = require('mongodb'); var Server = mongo.Server, Db = mongo.Db, BSON = mongo.BSONPure; var server = new Server('localhost', 27017, {auto_reconnect: true}); db = new Db('TradeQ', server); db.open(function(err, db) { if(!err) { console.log("Connected to 'TradeQ' database"); db.collection('users', {strict:true}, function(err, collection) { if (err) { console.log("The 'users' collection doesn't exist. Creating it with sample data..."); //populateDB(); } }); } }); exports.findAll = function(req, res) { db.collection('users', function(err, collection) { collection.find().toArray(function(err, items) { res.send(items); }); }); }; exports.findById = function(req, res) { var id = require('mongodb').ObjectID(req.params.id); console.log('Retrieving user: ' + id); db.collection('users', function(err, collection) { collection.findOne(id, function(err, item) { res.send(item); }); }); }; exports.findByUserName = function(req, res) { var uName = req.params.id; console.log('Retrieving user: ' + uName); db.collection('users', function(err, collection) { collection.findOne({username: uName}, function(err, item) { res.send(item); }); }); }; exports.addUsers = function(req, res) { var user = req.body; console.log('Adding user: ' + JSON.stringify(user)); db.collection('users', function(err, collection) { collection.insert(user, {safe:true}, function(err, result) { if (err) { res.send({'error':'An error has occurred'}); } else { console.log('Success: ' + JSON.stringify(result[0])); res.send(result[0]); } }); }); };
import { Component, Host, h, Prop } from "@stencil/core"; export class CalciteRadio { constructor() { //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- /** The checked state of the radio. */ this.checked = false; /** The disabled state of the radio. */ this.disabled = false; /** The focused state of the radio. */ this.focused = false; /** The radio's hidden status. */ this.hidden = false; /** The hovered state of the radio. */ this.hovered = false; /** The scale (size) of the radio. */ this.scale = "m"; /** The color theme of the radio, */ this.theme = "light"; } // -------------------------------------------------------------------------- // // Render Methods // // -------------------------------------------------------------------------- render() { return (h(Host, null, h("div", { class: "radio" }))); } static get is() { return "calcite-radio"; } static get encapsulation() { return "shadow"; } static get originalStyleUrls() { return { "$": ["calcite-radio.scss"] }; } static get styleUrls() { return { "$": ["calcite-radio.css"] }; } static get properties() { return { "checked": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "The checked state of the radio." }, "attribute": "checked", "reflect": true, "defaultValue": "false" }, "disabled": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": true, "docs": { "tags": [], "text": "The disabled state of the radio." }, "attribute": "disabled", "reflect": true, "defaultValue": "false" }, "focused": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "The focused state of the radio." }, "attribute": "focused", "reflect": true, "defaultValue": "false" }, "hidden": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "The radio's hidden status." }, "attribute": "hidden", "reflect": true, "defaultValue": "false" }, "hovered": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "The hovered state of the radio." }, "attribute": "hovered", "reflect": true, "defaultValue": "false" }, "scale": { "type": "string", "mutable": false, "complexType": { "original": "\"s\" | \"m\" | \"l\"", "resolved": "\"l\" | \"m\" | \"s\"", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "The scale (size) of the radio." }, "attribute": "scale", "reflect": true, "defaultValue": "\"m\"" }, "theme": { "type": "string", "mutable": false, "complexType": { "original": "\"light\" | \"dark\"", "resolved": "\"dark\" | \"light\"", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "The color theme of the radio," }, "attribute": "theme", "reflect": true, "defaultValue": "\"light\"" } }; } }
from . import fiber_bundles
'use strict' module.exports = ini ini.displayName = 'ini' ini.aliases = [] function ini(Prism) { Prism.languages.ini = { /** * The component mimics the behavior of the Win32 API parser. * * @see {@link https://github.com/PrismJS/prism/issues/2775#issuecomment-787477723} */ comment: { pattern: /(^[ \f\t\v]*)[#;][^\n\r]*/m, lookbehind: true }, section: { pattern: /(^[ \f\t\v]*)\[[^\n\r\]]*\]?/m, lookbehind: true, inside: { 'section-name': { pattern: /(^\[[ \f\t\v]*)[^ \f\t\v\]]+(?:[ \f\t\v]+[^ \f\t\v\]]+)*/, lookbehind: true, alias: 'selector' }, punctuation: /\[|\]/ } }, key: { pattern: /(^[ \f\t\v]*)[^ \f\n\r\t\v=]+(?:[ \f\t\v]+[^ \f\n\r\t\v=]+)*(?=[ \f\t\v]*=)/m, lookbehind: true, alias: 'attr-name' }, value: { pattern: /(=[ \f\t\v]*)[^ \f\n\r\t\v]+(?:[ \f\t\v]+[^ \f\n\r\t\v]+)*/, lookbehind: true, alias: 'attr-value', inside: { 'inner-value': { pattern: /^("|').+(?=\1$)/, lookbehind: true } } }, punctuation: /=/ } }
import hashlib from math import cos, sin, radians, atan2 import threading import time class BoardThread(threading.Thread): def __init__(self, tick, deltatime, sleep_time=None): threading.Thread.__init__(self) self._tick = tick self._deltatime = deltatime self._sleep_time = sleep_time if sleep_time is not None else deltatime def run(self): while 1: self._tick(self._deltatime) time.sleep(self._sleep_time) def get_sleep_time(self): return self._sleep_time class Missile: def __init__(self, board, xy, degree, distance, speed, damage, owner=None): assert isinstance(board, Board) self._board = board self._owner = owner self._x, self._y = xy self._degree = degree self._distance = distance self._speed = speed self._damage = damage self._space = 0.0 def tick(self, deltatime): dx = self._speed * cos(radians(self._degree)) * deltatime dy = self._speed * sin(radians(self._degree)) * deltatime self._distance -= self._speed * deltatime if self._distance < 1: self._board.spawn_explosion((self._x + dx + self._distance * cos(radians(self._degree)), self._y + dy + self._distance * sin(radians(self._degree))), self._damage, self._owner) self._board.remove_missile(self) self._x += dx self._y += dy def get_status(self): return dict( x=self._x, y=self._y, degree=self._degree, distance=self._distance, speed=self._speed, damage=self._damage ) class Explosion: def __init__(self, board, xy, damage, owner=None): assert isinstance(board, Board) self._owner = owner self._board = board self._x, self._y = xy self._damage = damage self._step = 0 self._explosion_time = 1.0 # sec def tick(self, deltatime): self._step += 1 if 1 == self._step: # do damage for robot in self._board.robots.values(): if robot.is_dead(): continue d, a = robot.distance((self._x, self._y)) total_damage = 0 for distance, hp_damage in self._damage: if d <= distance: total_damage += hp_damage if total_damage: robot.take_damage(total_damage) if robot.is_dead(): if robot.get_name() not in self._board.kdr: self._board.kdr[robot.get_name()] = {'kill': 0, 'death': 0} self._board.kdr[robot.get_name()]['death'] += 1 if self._owner and self._owner.get_name() not in self._board.kdr: self._board.kdr[self._owner.get_name()] = {'kill': 0, 'death': 0} self._board.kdr[self._owner.get_name()]['kill'] += 1 elif self._step > 1: self._explosion_time -= deltatime if self._explosion_time <= 0.0: self._board.remove_explosion(self) def get_status(self): return dict( x=self._x, y=self._y, step=self._step, damage=self._damage, time=self._explosion_time ) class RobotAlreadyExistsException(Exception): pass class Board: def __init__(self, size=(1000, 1000)): self._size = size self.robots = {} self._missiles = {} self._explosions = {} self._radar = {} self._wall_hit_damage = 2 self._join_status = None self.kdr = {} def add_robot(self, robot): if robot.get_name() not in self.robots: self.robots[robot.get_name()] = robot return True return False def remove_robot(self, robot): if robot.get_name() in self.robots: del self.robots[robot.get_name()] return True return False def reinit(self, size=(1000, 1000)): self.__init__(size) def get_status(self): ret = dict( size=self._size, robots=[v.get_status() for v in self.robots.values()], missiles=dict([(k, v.get_status()) for k, v in self._missiles.items()]), explosions=dict([(k, v.get_status()) for k, v in self._explosions.items()]), radar=dict(self._radar), kdr=self.kdr ) self._radar = dict([(k, v) for k, v in self._radar.items() if v['spawntime'] + 1.0 > time.time()]) return ret def radar(self, scanning_robot, xy, max_scan_distance, degree, resolution): key = hashlib.md5(repr(dict(time=time.time(), xy=xy, degree=degree, resolution=resolution, distance=max_scan_distance))).hexdigest() self._radar[key] = dict(xy=xy, degree=degree, resolution=resolution, distance=max_scan_distance, spawntime=time.time()) ret = [] degree %= 360 for robot in [x for x in self.robots.values() if x != scanning_robot]: if robot.is_dead(): continue distance, angle = robot.distance(xy) angle = (180 + angle) % 360 if self.angle_distance(angle, degree) > resolution: continue if distance > max_scan_distance: continue ret.append(distance) return min(ret) if ret else 0 def detect_collision(self, robot, xy, dxy): x, y = xy dx, dy = dxy # collision with other robots step = max(abs(dx), abs(dy)) if step: # the robot is moving x0, y0 = x - dx, y - dy stepx = float(dx) / float(step) stepy = float(dy) / float(step) for other_robot in [j for j in self.robots.values() if j != robot]: xp, yp = x0, y0 for i in xrange(int(step) + 1): dist, angle = other_robot.distance((xp, yp)) if dist < 2: # 1 per ogni robot other_robot.take_damage(self._wall_hit_damage) other_robot.block() teta = atan2(dy, dx) xp, yp = other_robot.get_xy() xp -= 2 * cos(teta) yp -= 2 * sin(teta) return xp, yp, self._wall_hit_damage xp += stepx yp += stepy # COLLISION WITH WALLS if x < 0: y = y - dy * x / dx x = 0 return x, y, self._wall_hit_damage if x > self._size[0]: y = y - dy * (x - self._size[0]) / dx x = self._size[0] return x, y, self._wall_hit_damage if y < 0: x = x - dx * y / dy y = 0 return x, y, self._wall_hit_damage if y > self._size[1]: x = x - dx * (y - self._size[1]) / dy y = self._size[1] return x, y, self._wall_hit_damage return None def spawn_missile(self, xy, degree, distance, bullet_speed, bullet_damage, owner=None): key = hashlib.md5(repr( dict(time=time.time(), xy=xy, degree=degree, distance=distance, bullet_speed=bullet_speed, bullet_damage=bullet_damage))).hexdigest() missile = Missile(self, xy, degree, distance, bullet_speed, bullet_damage, owner) self._missiles[key] = missile def remove_missile(self, missile): self._missiles = dict([(k, x) for k, x in self._missiles.items() if x != missile]) # del self._missiles[self._missiles.index(missile)] def spawn_explosion(self, xy, damage, owner=None): key = hashlib.md5(repr(dict(time=time.time(), xy=xy, damage=damage))).hexdigest() self._explosions[key] = Explosion(self, xy, damage, owner) def remove_explosion(self, explosion): self._explosions = dict([(k, x) for k, x in self._explosions.items() if x != explosion]) def tick(self, deltatime=0.125): # manage missiles for m in self._missiles.values(): assert isinstance(m, Missile) m.tick(deltatime) # manage explosions for e in self._explosions.values(): assert isinstance(e, Explosion) e.tick(deltatime) # manage robots for r in self.robots.values(): r.tick(deltatime) def new_robot(self, clazz, name): return clazz(self, name, len(self.robots)) @staticmethod def angle_distance(angle, degree): ret = (angle - degree) if angle > degree else (degree - angle) if ret > 180: ret = 360 - ret return ret
'use strict'; const {assert} = require('chai'); const dataDriven = require('data-driven'); const Errors = require('src/Errors'); const {correctPath, correctUrl, StreamsInfo} = require('./Helpers/'); const {incorrectConfigData, incorrectUrlData, incorrectConfig} = require('./constructor.data'); describe('StreamsInfo::constructor', () => { dataDriven(incorrectConfigData, function () { it('config param has invalid ({type}) type', function (ctx) { assert.throws(() => { new StreamsInfo(ctx.config, undefined); }, TypeError, 'Config param should be an object, bastard.'); }); }); dataDriven(incorrectUrlData, function () { it('url param has invalid ({type}) type', function (ctx) { assert.throws(() => { new StreamsInfo({}, ctx.url); }, TypeError, 'You should provide a correct url, bastard.'); }); }); dataDriven(incorrectConfig, function () { it('{description}', function (ctx) { assert.throws(() => { new StreamsInfo(ctx.config, correctUrl); }, Errors.ConfigError, ctx.errorMsg); }); }); it('config.ffprobePath points to incorrect path', () => { assert.throws(() => { new StreamsInfo({ ffprobePath : `/incorrect/path/${correctUrl}`, timeoutInSec: 1 }, correctUrl); }, Errors.ExecutablePathError); }); it('all params are good', () => { assert.doesNotThrow(() => { new StreamsInfo({ ffprobePath : correctPath, timeoutInSec: 1 }, correctUrl); }); }); });
import { getMessageById } from '../../models/message'; export default async replies => { let newReplies = []; const replyPromises = replies.map( async reply => await getMessageById(reply.id) ); // get all the messages for this thread const messageRecords = await Promise.all(replyPromises).catch(err => console.log('error getting reply promises', err) ); // filter deleted ones and sort them by recency const filteredMessageRecords = messageRecords .filter(message => !message.deletedAt) .sort((a, b) => a.timestamp > b.timestamp); const filteredPromises = filteredMessageRecords.map((message, index) => { const reply = replies.filter(r => r.id === message.id)[0]; const body = message.messageType === 'media' ? `<p class='reply-img-container'><img class='reply-img' src='${reply .content.body}?w=600&dpr=2' /></p>` : `<p class='reply'>${reply.content.body}</p>`; const newGroup = { ...reply, content: { body, }, }; if (index === 0) return newReplies.push(newGroup); if ( newReplies[newReplies.length - 1] && newReplies[newReplies.length - 1].sender.id === message.senderId ) { newReplies[newReplies.length - 1].content.body += body; return; } else { newReplies.push(newGroup); return; } }); return await Promise.all([filteredPromises]) .then(() => newReplies) .catch(err => console.log('error getting filteredPromises', err)); };
// Copyright (c) 2020, Pedro Antonio Fernandez Gomez and contributors // For license information, please see license.txt frappe.ui.form.on('Pagina', { // refresh: function(frm) { // } });
"use strict"; var _uiTree_list = _interopRequireDefault(require("./ui.tree_list.core")); var _uiGrid_core = _interopRequireDefault(require("../grid_core/ui.grid_core.columns_resizing_reordering")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } _uiTree_list.default.registerModule('columnsResizingReordering', _uiGrid_core.default);