text
stringlengths
2
1.05M
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component, PropTypes } from 'react'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-trigger`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'trigger'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><polygon fill="none" stroke="#000" strokeWidth="2" points="4 14 10 14 7 23 9 23 20 9 14 9 18 1 7 1"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Trigger'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
import React from 'react'; import { Modal } from './Modal'; import { makeStyles } from '@material-ui/core/styles'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; const createData = (key, description) => ({ key, description }); const rows = [ createData('ctrl ↑', 'Rotate up'), createData('ctrl ↓', 'Rotate down'), createData('ctrl ←', 'Rotate left'), createData('ctrl →', 'Rotate right'), createData('+', 'Zoom in'), createData('-', 'Zoom out'), createData('l', 'Rotate to selected country'), createData('r', 'Select random country'), createData('w', 'Show/hide widgets'), createData('ctrl /', 'Show/hide shortcuts'), ]; const useStyles = makeStyles({ table: { minWidth: 300, }, cellKey: { fontFamily: 'monospace', fontSize: '1.1rem', }, }); const ShortcutsTable = () => { const classes = useStyles(); return ( <TableContainer component={Paper}> <Table className={classes.table} aria-label="Shortcuts table"> <TableHead> <TableRow> <TableCell>Key</TableCell> <TableCell>Description</TableCell> </TableRow> </TableHead> <TableBody> {rows.map(row => ( <TableRow key={row.key}> <TableCell align="center" className={classes.cellKey}> {row.key} </TableCell> <TableCell align="left">{row.description}</TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> ); }; export const Shortcuts = ({ show, onClose }) => { return ( <Modal show={show} onClose={onClose}> <ShortcutsTable /> </Modal> ); };
function WPATH(s) { var index = s.lastIndexOf("/"); var path = -1 === index ? "modalWindow/" + s : s.substring(0, index) + "/modalWindow/" + s.substring(index + 1); return path; } module.exports = [ { isApi: true, priority: 1000.0015, key: "Button", style: { backgroundRepeat: false, width: "100dip", height: "35dip", bottom: "5dip", borderRadius: "10dip", backgroundImage: "/modalWindow/button.png" } }, { isClass: true, priority: 10000.0019, key: "modalwindow-button-ok", style: { color: "#fff", backgroundColor: "#080" } }, { isClass: true, priority: 10000.002, key: "modalwindow-button-cancel", style: { color: "#fff", backgroundColor: "#800" } }, { isClass: true, priority: 10000.0021, key: "modalwindow-button-default", style: { color: "#000", backgroundColor: "#aaa" } }, { isId: true, priority: 100000.0016, key: "modalwindow_button_ok", style: { visible: true } }, { isId: true, priority: 100000.0017, key: "modalwindow_button_cancel", style: { visible: true } }, { isId: true, priority: 100000.0018, key: "modalwindow_button_default", style: { visible: true } } ];
'use strict'; const Service = require('egg').Service; const arrayToTree = require('array-to-tree'); const toc = require('markdown-toc'); const marked = require('marked'); const constant = require('../constant'); class AdminService extends Service { async users({ limit, page, name, email, status, sort_type }) { const Op = this.app.Sequelize.Op; const offset = (page - 1) * limit; const where = {}; if (name !== '') { where.name = { [Op.like]: `%${name}%`, }; } if (email !== '') { where.email = email; } if (status !== '') { where.status = status; } const order = []; if (sort_type !== '') { order.push([ sort_type, 'DESC' ]); } else { order.push([ 'id', 'DESC' ]); } const result = await this.ctx.model.User.unscoped().findAndCountAll({ where, limit, offset, order, }); result.last_page = Math.ceil(result.count / limit); result.page = page; return result; } async queueJobs({ limit, page, queue, sort_type }) { const offset = (page - 1) * limit; const where = {}; if (queue !== '') { where.queue = queue; } const order = []; if (sort_type !== '') { order.push([ sort_type, 'DESC' ]); } else { order.push([ 'id', 'DESC' ]); } const result = await this.ctx.model.QueueJob.unscoped().findAndCountAll({ where, limit, offset, order, }); result.last_page = Math.ceil(result.count / limit); result.page = page; return result; } async sites({ limit, page, title, url, status, sort_type }) { const Op = this.app.Sequelize.Op; const offset = (page - 1) * limit; const where = {}; if (title !== '') { where.title = { [Op.like]: `%${title}%`, }; } if (url !== '') { where.url = url; } if (status !== '') { where.status = status; } const order = []; if (sort_type !== '') { order.push([ sort_type, 'DESC' ]); } else { order.push([ 'id', 'DESC' ]); } const result = await this.ctx.model.Site.unscoped().findAndCountAll({ where, limit, offset, order, }); result.last_page = Math.ceil(result.count / limit); result.page = page; return result; } async links({ limit, page, title, url, status, sort_type }) { const Op = this.app.Sequelize.Op; const offset = (page - 1) * limit; const where = {}; if (title !== '') { where.title = { [Op.like]: `%${title}%`, }; } if (url !== '') { where.url = url; } if (status !== '') { where.status = status; } const order = []; if (sort_type !== '') { order.push([ sort_type, 'DESC' ]); } else { order.push([ 'id', 'DESC' ]); } const result = await this.ctx.model.Link.unscoped().findAndCountAll({ where, limit, offset, order, }); result.last_page = Math.ceil(result.count / limit); result.page = page; return result; } async wiki({ limit, page, title, url, status, sort_type }) { const Op = this.app.Sequelize.Op; const offset = (page - 1) * limit; const where = {}; if (title !== '') { where.title = { [Op.like]: `%${title}%`, }; } if (url !== '') { where.url = url; } if (status !== '') { where.status = status; } const order = []; if (sort_type !== '') { order.push([ sort_type, 'DESC' ]); } else { order.push([ 'id', 'DESC' ]); } const result = await this.ctx.model.Wiki.unscoped().findAndCountAll({ where, limit, offset, order, }); result.last_page = Math.ceil(result.count / limit); result.page = page; return result; } async news({ limit, page, title, post_date, status, sort_type }) { const Op = this.app.Sequelize.Op; const offset = (page - 1) * limit; const where = {}; if (title !== '') { where.title = { [Op.like]: `%${title}%`, }; } if (post_date !== '') { where.post_date = post_date; } if (status !== '') { where.status = status; } const order = []; if (sort_type !== '') { order.push([ sort_type, 'DESC' ]); } else { order.push([ 'id', 'DESC' ]); } const result = await this.ctx.model.ReposNews.unscoped().findAndCountAll({ where, limit, offset, order, }); result.last_page = Math.ceil(result.count / limit); result.page = page; return result; } async articles({ limit, page, title, url, status, sort_type }) { const Op = this.app.Sequelize.Op; const offset = (page - 1) * limit; const where = {}; if (title !== '') { where.title = { [Op.like]: `%${title}%`, }; } if (url !== '') { where.url = url; } if (status !== '') { where.status = status; } const order = []; if (sort_type !== '') { order.push([ sort_type, 'DESC' ]); } else { order.push([ 'id', 'DESC' ]); } const result = await this.ctx.model.Article.unscoped().findAndCountAll({ where, limit, offset, order, }); result.last_page = Math.ceil(result.count / limit); result.page = page; return result; } async click({ limit, page, target, sort_type }) { const offset = (page - 1) * limit; const where = {}; if (target !== '') { where.target = target; } const order = []; if (sort_type !== '') { order.push([ sort_type, 'DESC' ]); } else { order.push([ 'clicked_at', 'DESC' ]); } const result = await this.ctx.model.LinkClick.unscoped().findAndCountAll({ where, limit, offset, order, }); result.last_page = Math.ceil(result.count / limit); result.page = page; return result; } async vote({ limit, page, repos_id, sort_type }) { const offset = (page - 1) * limit; const where = {}; if (repos_id !== '') { where.repos_id = repos_id; } const order = []; if (sort_type !== '') { order.push([ sort_type, 'DESC' ]); } else { order.push([ 'updated_at', 'DESC' ]); } const result = await this.ctx.model.ReposVote.unscoped().findAndCountAll({ where, limit, offset, order, }); result.last_page = Math.ceil(result.count / limit); result.page = page; return result; } async repos({ limit, page, slug, status, sort_type }) { const offset = (page - 1) * limit; const where = {}; if (slug !== '') { where.slug = slug; } if (status !== '') { where.status = status; } const order = []; if (sort_type !== '') { order.push([ sort_type, 'DESC' ]); } else { order.push([ 'id', 'DESC' ]); } const result = await this.ctx.model.Repos.unscoped().findAndCountAll({ where, limit, offset, order, }); result.last_page = Math.ceil(result.count / limit); result.page = page; return result; } async developers({ limit, page, login, status, sort_type, type }) { const offset = (page - 1) * limit; const where = {}; if (login !== '') { where.login = login; } if (type !== '') { where.type = type; } if (status !== '') { where.status = status; } const order = []; if (sort_type !== '') { order.push([ sort_type, 'DESC' ]); } else { order.push([ 'id', 'DESC' ]); } const result = await this.ctx.model.Developer.unscoped().findAndCountAll({ where, limit, offset, order, }); result.last_page = Math.ceil(result.count / limit); result.page = page; return result; } async reposSwitch({ id, status }) { const Op = this.app.Sequelize.Op; const res = await this.ctx.model.Repos.unscoped().update( { status, }, { where: { id: { [Op.in]: id, }, }, }); return { affected: res }; } async reposEdit({ id, status }) { const repos = await this.ctx.model.Repos.unscoped().findOne({ where: { id, }, }); repos.status = status; const res = await repos.save(); return { affected: res }; } async reposEnable() { const res = await this.ctx.model.Repos.unscoped().update( { status: constant.ENABLE, }, { where: { status: 0, }, }); return { affected: res }; } async developerSwitch({ id, status }) { const Op = this.app.Sequelize.Op; const res = await this.ctx.model.Developer.unscoped().update( { status, }, { where: { id: { [Op.in]: id, }, }, }); return { affected: res }; } async developerEdit({ id, status }) { const developer = await this.ctx.model.Developer.unscoped().findOne({ where: { id, }, }); developer.status = status; const res = await developer.save(); return { affected: res }; } async developerEnable() { const res = await this.ctx.model.Developer.unscoped().update( { status: constant.ENABLE, }, { where: { status: 0, }, }); return { affected: res }; } async ecosystems({ limit, page, slug, status, sort_type }) { const offset = (page - 1) * limit; const where = {}; if (slug !== '') { where.slug = slug; } if (status !== '') { where.status = status; } const order = []; if (sort_type !== '') { order.push([ sort_type, 'DESC' ]); } else { order.push([ 'sort', 'ASC' ]); } const result = await this.ctx.model.Topic.unscoped().findAndCountAll({ where, limit, offset, order, }); result.last_page = Math.ceil(result.count / limit); result.page = page; return result; } async ecosystemSwitch({ id, status }) { const Op = this.app.Sequelize.Op; const res = await this.ctx.model.Topic.unscoped().update( { status, }, { where: { id: { [Op.in]: id, }, }, }); return { affected: res }; } async ecosystemEdit(data) { const topic = await this.ctx.model.Topic.unscoped().findOne({ where: { id: data.id, }, }); // Link Sync if (data.wiki && data.wiki !== '') { this.ctx.service.queue.addJob({ queue: 'linkFetch', payload: { url: data.wiki } }); } if (data.homepage && data.homepage !== '') { this.ctx.service.queue.addJob({ queue: 'linkFetch', payload: { url: data.homepage } }); } if (data.github && data.github !== '') { this.ctx.service.queue.addJob({ queue: 'linkFetch', payload: { url: data.github } }); } const res = await topic.update(data, { fields: [ 'title', 'slug', 'description', 'homepage', 'github', 'wiki', 'sort', 'status' ], }); return { affected: res }; } async ecosystemCreate(data) { const title = data.title || ''; data.slug = this.ctx.helper.toSlug(title); return await this.ctx.model.Topic.create( data, { fields: [ 'title', 'slug', 'description', 'homepage', 'github', 'wiki', 'sort' ], }); } async ecosystemCollectionCreate(data) { const title = data.title || ''; data.slug = this.ctx.helper.toSlug(title); return await this.ctx.model.Collection.create( data, { fields: [ 'title', 'slug', 'parent_id', 'topic_id', 'sort' ], }); } async ecosystemCollectionEdit(data) { const collection = await this.ctx.model.Collection.unscoped().findOne({ where: { id: data.id, }, }); const res = await collection.update(data, { fields: [ 'title', 'slug', 'parent_id', 'topic_id', 'sort', 'status' ], }); return { affected: res }; } async ecosystemCollectionDelete({ id }) { const childCollection = await this.ctx.model.Collection.unscoped().findOne({ attributes: [ 'id' ], where: { parent_id: id, }, }); if (childCollection) { return false; } const items = await this.ctx.model.CollectionItem.unscoped().findOne({ attributes: [ 'id' ], where: { collection_id: id, }, }); if (items) { return false; } return await this.ctx.model.Collection.unscoped().destroy({ where: { id, }, limit: 1, }); } async ecosystemCollections({ id }) { let collections = await this.ctx.model.Collection.unscoped().findAll({ where: { topic_id: id, }, order: [ [ 'sort', 'ASC' ], ], }); collections = JSON.parse(JSON.stringify(collections)); collections = arrayToTree(collections); return collections; } async ecosystemCollectionItems({ id }) { const items = await this.ctx.model.CollectionItem.unscoped().findAll({ where: { collection_id: id, }, order: [ [ 'sort', 'ASC' ], ], }); return items; } async ecosystemCollectionItemSwitch(data) { const res = await this.ctx.model.CollectionItem.unscoped().update( { status: data.status, }, { where: { collection_id: data.collection_id, }, }); return { affected: res }; } async ecosystemCollectionItemCheck() { return await this.ecosystemCollectionItemsCheck(); } async ecosystemCollectionItemCreate(data) { if (data.type === 'repos') { const repos = await this.ctx.model.Repos.unscoped().findOne({ where: { id: data.foreign_id, }, }); if (!repos) { return false; } data.title = `${repos.owner}/${repos.repo}`; } if (data.type === 'developers') { const developer = await this.ctx.model.Developer.unscoped().findOne({ where: { id: data.foreign_id, }, }); if (!developer) { return false; } data.title = `${developer.login} (${developer.name})`; } if (data.type === 'sites') { const site = await this.ctx.model.Site.unscoped().findOne({ where: { id: data.foreign_id, }, }); if (!site) { return false; } data.title = site.title; } if (data.type === 'links') { const link = await this.ctx.model.Link.unscoped().findOne({ where: { url: data.url, }, }); if (!link) { const newLink = await this.ctx.model.Link.create({ title: data.title, url: data.url, }); data.foreign_id = newLink.id; } else { data.title = link.title; data.foreign_id = link.id; } } return await this.ctx.model.CollectionItem.create( data, { fields: [ 'collection_id', 'title', 'type', 'foreign_id', 'sort' ], }); } async ecosystemCollectionItemEdit(data) { const item = await this.ctx.model.CollectionItem.unscoped().findOne({ where: { id: data.id, }, }); const res = await item.update(data, { fields: [ 'title', 'sort', 'status' ], }); return { affected: res }; } async ecosystemCollectionItemDelete({ id }) { return await this.ctx.model.CollectionItem.unscoped().destroy({ where: { id, }, limit: 1, }); } async ecosystemCollectionImport({ topic_id, url, text }) { if (typeof url === 'string' && url.length > 0) { await this.ctx.model.TopicSource.create({ topic_id, source: 'Awesome List', url, }); this.ctx.service.queue.addJob({ queue: 'awesomeListFetch', payload: { title: '', url } }); } if (typeof text === 'string' && text.length > 0) { // Insert Collections const collectionTokens = this.lexerCollectionToken(text); await this.insertCollections(topic_id, collectionTokens); // Insert Items const itemTokens = this.lexerItemTokens(text); await this.insertCollectionItems(topic_id, itemTokens); } return { topic_id, url, text }; } lexerCollectionToken(md) { const collections = toc(md).json; let preLvl = 0; let curLvl = 0; for (let i = 0; i < collections.length; i++) { curLvl = collections[i].lvl; if (preLvl !== 0) { if (curLvl > preLvl) { collections[i].parent = collections[i - 1].slug; } else if (curLvl === preLvl) { collections[i].parent = collections[i - 1].parent; } else { for (let j = 1; j <= i - 1; j++) { if (curLvl === collections[i - j].lvl) { collections[i].parent = collections[i - j].parent; } } if (collections[i].parent === undefined) { collections[i].parent = collections[0].slug; } } } else { collections[i].parent = ''; } preLvl = curLvl; } return collections; } async insertCollections(topic_id, tokens) { for (let i = 0; i < tokens.length; i++) { if (tokens[i].parent !== '') { const parentCollection = await this.ctx.model.Collection.unscoped().findOne({ attributes: [ 'id' ], where: { topic_id, slug: tokens[i].parent, }, }); if (parentCollection) { const found = await this.ctx.model.Collection.unscoped().findOne({ attributes: [ 'id' ], where: { topic_id, parent_id: parentCollection.id, slug: tokens[i].slug, }, }); if (!found) { await this.ctx.model.Collection.create({ topic_id, parent_id: parentCollection.id, title: tokens[i].content, slug: tokens[i].slug, sort: tokens[i].i, }); } } } else { const found = await this.ctx.model.Collection.unscoped().findOne({ attributes: [ 'id' ], where: { topic_id, parent_id: 0, slug: tokens[i].slug, }, }); if (!found) { await this.ctx.model.Collection.create({ topic_id, parent_id: 0, title: tokens[i].content, slug: tokens[i].slug, sort: tokens[i].i, }); } } } } lexerItemTokens(md) { const tokens = marked.lexer(md); let list = []; const _tokens = []; for (let i = 0; i < tokens.length; i++) { if (tokens[i].type === 'heading') { _tokens.push(tokens[i]); } if ([ 'text', 'list_start', 'list_end', 'list_item_start', 'list_item_end' ].includes(tokens[i].type)) { list.push(tokens[i]); if (tokens[i].type === 'list_end') { list.forEach(listItem => { _tokens.push(listItem); }); list = []; } } } const __tokens = []; for (let i = 0; i < _tokens.length; i++) { if ([ 'heading', 'text' ].includes(_tokens[i].type)) { __tokens.push(_tokens[i]); } } for (let i = 0; i < __tokens.length; i++) { if (__tokens[i].type === 'text') { let slug = ''; for (let j = i - 1; j >= 0; j--) { if (__tokens[j].type === 'heading') { slug = __tokens[j].text; break; } } __tokens[i].collection = slug; } } return __tokens; } async insertCollectionItems(topic_id, tokens) { for (let i = 0; i < tokens.length; i++) { if (tokens[i].type === 'text') { const found = await this.ctx.model.Collection.unscoped().findOne({ attributes: [ 'id' ], where: { topic_id, title: tokens[i].collection, }, }); if (found) { const analyzeText = await this.analyzeItemText(tokens[i].text); const itemExists = await this.ctx.model.CollectionItem.unscoped().findOne({ where: { collection_id: found.id, title: (analyzeText.title || tokens[i].text).substring(0, 255), type: analyzeText.type || 'text', foreign_id: analyzeText.foreign_id || 0, }, }); if (!itemExists) { await this.ctx.model.CollectionItem.create({ collection_id: found.id, title: (analyzeText.title || tokens[i].text).substring(0, 255), type: analyzeText.type || 'text', sort: i, foreign_id: analyzeText.foreign_id || 0, }); } } } } } async analyzeItemText(text) { const found = text.match(/\[(.*)\]\((.*)\)( \- )?(.*)/i); const res = {}; if (found) { res.title = found[1]; if (this.ctx.helper.isUrl(found[2])) { // Repos const reposFound = this.ctx.helper.isGithubRepos(found[2]); if (reposFound) { const owner = reposFound[1]; const repo = reposFound[2]; const reposExist = await this.ctx.model.Repos.unscoped().findOne({ attributes: [ 'id' ], where: { slug: `${owner}-${repo}`, }, }); if (reposExist) { res.foreign_id = reposExist.id; res.type = 'repos'; res.title = `${owner}/${repo}`; } else { res.foreign_id = 0; res.type = 'repos'; res.title = text; // fetch job this.ctx.service.queue.addJob({ queue: 'reposFetch', payload: { url: found[2] } }); } } // Developer const developerFound = this.ctx.helper.isGithubDeveloper(found[2]); if (developerFound) { const login = developerFound[1]; const developerExist = await this.ctx.model.Developer.unscoped().findOne({ attributes: [ 'id' ], where: { login, }, }); if (developerExist) { res.foreign_id = developerExist.id; res.type = 'developers'; res.title = developerExist.login; } else { res.foreign_id = 0; res.type = 'developers'; res.title = text; // fetch job this.ctx.service.queue.addJob({ queue: 'developerFetch', payload: { url: found[2] } }); } } // Site const siteFound = this.ctx.helper.isSite(found[2]); if (siteFound) { const siteExist = await this.ctx.model.Site.unscoped().findOne({ where: { url: found[2], }, }); if (siteExist) { res.foreign_id = siteExist.id; res.type = 'sites'; res.title = siteExist.title !== '' ? siteExist.title : found[1]; } else { res.foreign_id = 0; res.type = 'sites'; res.title = text; } } if (!('type' in res)) { const linkExist = await this.ctx.model.Link.unscoped().findOne({ where: { url: found[2], }, }); if (linkExist) { res.foreign_id = linkExist.id; res.type = 'links'; res.title = linkExist.title !== '' ? linkExist.title : found[1]; } else { res.foreign_id = 0; res.type = 'links'; res.title = text; } } } } else { res.title = text; res.type = 'text'; } return res; } async queueReplay({ id }) { id.forEach(i => { this.ctx.service.queue.replayJob(i); }); return true; } async queueReplayAll() { const ctx = this.ctx; const Op = this.app.Sequelize.Op; const jobs = await ctx.model.QueueJob.findAll({ attributes: [ 'id' ], where: { attempts: { [Op.lte]: 2, }, }, }); for (let i = 0; i < jobs.length; i++) { await ctx.service.queue.replayJob(jobs[i].id); } return true; } async queueDelete({ id }) { return this.ctx.service.queue.finishJob(id); } async queueBullCounts() { return await this.app.queue.getJobCounts(); } async queueBullClean({ type }) { if (type === 'all') { await this.app.queue.clean(0, 'completed'); await this.app.queue.clean(0, 'wait'); await this.app.queue.clean(0, 'active'); await this.app.queue.clean(0, 'delayed'); await this.app.queue.clean(0, 'failed'); return true; } return await this.app.queue.clean(0, type); } async queueSystemClean({ type }) { if (type === 'failed') { return await this.ctx.service.queue.cleanFailJob(); } if (type === 'repeat') { return await this.ctx.service.queue.cleanRepeatJob(); } return false; } async fetch({ url }) { return this.ctx.service.queue.addJob({ queue: 'linkFetch', payload: { url } }); } async ecosystemCollectionSwitch({ id, status }) { const Op = this.app.Sequelize.Op; const res = await this.ctx.model.Collection.unscoped().update( { status, }, { where: { id: { [Op.in]: id, }, }, }); return { affected: res }; } async ecosystemCollectionMove({ parent_id, id }) { const Op = this.app.Sequelize.Op; const res = await this.ctx.model.Collection.unscoped().update( { parent_id, }, { where: { id: { [Op.in]: id, }, }, }); return { affected: res }; } async ecosystemSource({ id }) { return await this.ctx.model.TopicSource.findAll({ where: { topic_id: id, }, order: [ [ 'updated_at', 'DESC' ], ], }); } async ecosystemSourceCreate(data) { return await this.ctx.model.TopicSource.create( data, { fields: [ 'source', 'url', 'topic_id' ], }); } async ecosystemSourceDelete({ id }) { return await this.ctx.model.TopicSource.destroy({ where: { id, }, limit: 1, }); } async ecosystemSourceFetch({ id }) { const source = await this.ctx.model.TopicSource.findOne({ where: { id, }, }); if (source) { if (source.source === 'Awesome List') { this.ctx.service.queue.addJob({ queue: 'awesomeListFetch', payload: { title: '', url: source.url } }); return true; } } return false; } async ecosystemAttributes({ id }) { return await this.ctx.model.TopicAttribute.findAll({ where: { topic_id: id, }, order: [ [ 'sort', 'ASC' ], ], }); } async ecosystemAttributeCreate(data) { return await this.ctx.model.TopicAttribute.create( data, { fields: [ 'key', 'value', 'topic_id', 'sort' ], }); } async ecosystemAttributeEdit(data) { const attribute = await this.ctx.model.TopicAttribute.findOne({ where: { id: data.id, }, }); const res = await attribute.update(data, { fields: [ 'key', 'value', 'topic_id', 'sort' ], }); return { affected: res }; } async ecosystemAttributeDelete({ id }) { return await this.ctx.model.TopicAttribute.destroy({ where: { id, }, limit: 1, }); } async ecosystemCollectionCrawler(data) { const { app, ctx } = this; app.logger.debug(data); const readme = await ctx.helper.remember('awesome-repos:readme', 60 * 60, async function() { const res = await app.curl('https://raw.githubusercontent.com/bayandin/awesome-awesomeness/master/README.md', { dataType: 'text', }); if (res.status === 200) { return res.data; } throw Error('Download fail readme'); }); if (typeof readme === 'string') { const found = readme.match(/(?:\[(.*?)\]\((.*?)\))/ig); found.forEach(i => { const match = i.match(/(?:\[(.*?)\]\((.*?)\))/i); if (match) { ctx.service.queue.addJob({ queue: 'awesomeListFetch', payload: { title: match[1], url: match[2] } }); } }); } return true; } async ecosystemCollectionItemsCheck() { const Op = this.app.Sequelize.Op; const { ctx } = this; // repos const reposItems = await ctx.model.CollectionItem.unscoped().findAll({ attributes: [ 'id', 'title', 'foreign_id' ], where: { type: 'repos', foreign_id: 0, title: { [Op.ne]: '', }, }, }); for (let i = 0; i < reposItems.length; i++) { const found = reposItems[i].title.match(/(?:\[(.*?)\]\((.*?)\))/i); if (found) { const reposFound = ctx.helper.isGithubRepos(found[2]); if (reposFound) { const repos = await ctx.model.Repos.unscoped().findOne({ attributes: [ 'id', 'title' ], where: { slug: `${reposFound[1]}-${reposFound[2]}`, }, }); if (repos) { reposItems[i].foreign_id = repos.id; reposItems[i].title = repos.title; await reposItems[i].save(); } else { await ctx.service.queue.addJob({ queue: 'linkFetch', payload: { url: found[2] } }); } } } } // developers const developersItems = await ctx.model.CollectionItem.unscoped().findAll({ attributes: [ 'id', 'title', 'foreign_id' ], where: { type: 'developers', foreign_id: 0, title: { [Op.ne]: '', }, }, }); for (let i = 0; i < developersItems.length; i++) { const found = developersItems[i].title.match(/(?:\[(.*?)\]\((.*?)\))/i); if (found) { const developerFound = ctx.helper.isGithubDeveloper(found[2]); if (developerFound) { const developer = await ctx.model.Developer.unscoped().findOne({ attributes: [ 'id', 'login', 'name' ], where: { login: `${developerFound[1]}`, }, }); if (developer) { developersItems[i].foreign_id = developer.id; developersItems[i].title = `${developer.login} (${developer.name})`; await developersItems[i].save(); } else { await ctx.service.queue.addJob({ queue: 'linkFetch', payload: { url: found[2] } }); } } } } // sites const sitesItems = await ctx.model.CollectionItem.unscoped().findAll({ attributes: [ 'id', 'title', 'foreign_id' ], where: { type: 'sites', foreign_id: 0, title: { [Op.ne]: '', }, }, }); for (let i = 0; i < sitesItems.length; i++) { const found = sitesItems[i].title.match(/(?:\[(.*?)\]\((.*?)\))/i); if (found) { const siteFound = ctx.helper.isSite(found[2]); if (siteFound) { const site = await ctx.model.Site.unscoped().findOne({ attributes: [ 'id', 'title' ], where: { url: found[2], }, }); if (site) { sitesItems[i].foreign_id = site.id; sitesItems[i].title = typeof site.title === 'string' && site.title.length > 0 ? site.title : found[1]; await sitesItems[i].save(); } else { await ctx.service.queue.addJob({ queue: 'linkFetch', payload: { url: found[2] } }); } } } } // links const linksItems = await ctx.model.CollectionItem.unscoped().findAll({ attributes: [ 'id', 'title', 'foreign_id' ], where: { type: 'links', foreign_id: 0, title: { [Op.ne]: '', }, }, }); for (let i = 0; i < linksItems.length; i++) { const found = linksItems[i].title.match(/(?:\[(.*?)\]\((.*?)\))/i); if (found) { const linkFound = ctx.helper.isUrl(found[2]); if (linkFound) { const link = await ctx.model.Link.unscoped().findOne({ attributes: [ 'id', 'title' ], where: { url: found[2], }, }); if (link) { linksItems[i].foreign_id = link.id; linksItems[i].title = typeof link.title === 'string' && link.title.length > 0 ? link.title : found[1]; await linksItems[i].save(); } else { await ctx.service.queue.addJob({ queue: 'linkFetch', payload: { url: found[2] } }); } } } } return { reposItems, developersItems, sitesItems, linksItems }; } async userAnalytics() { const count = await this.ctx.model.User.count(); return { count }; } async ecosystemAnalytics() { const count = await this.ctx.model.Topic.count(); return { count }; } async feedback({ limit, page, tags, status, sort_type }) { const offset = (page - 1) * limit; const where = {}; if (tags !== '') { where.tags = tags; } if (status !== '') { where.status = status; } const order = []; if (sort_type !== '') { order.push([ sort_type, 'DESC' ]); } else { order.push([ 'status', 'ASC' ]); order.push([ 'updated_at', 'DESC' ]); } const result = await this.ctx.model.Feedback.unscoped().findAndCountAll({ where, limit, offset, order, }); result.last_page = Math.ceil(result.count / limit); result.page = page; return result; } async feedbackSwitch({ id, status }) { const Op = this.app.Sequelize.Op; const res = await this.ctx.model.Feedback.unscoped().update( { status, }, { where: { id: { [Op.in]: id, }, }, }); return { affected: res }; } async feedbackDelete({ id }) { return await this.ctx.model.Feedback.destroy({ where: { id, }, limit: 1, }); } } module.exports = AdminService;
import _isNil from 'lodash/isNil'; import BaseModel from '../../base/BaseModel'; import FixCollection from '../Fix/FixCollection'; import WaypointModel from '../../aircraft/FlightManagementSystem/WaypointModel'; import { REGEX } from '../../constants/globalConstants'; import { FLY_OVER_WAYPOINT_PREFIX, VECTOR_WAYPOINT_PREFIX } from '../../constants/navigation/routeConstants'; import { ALTITUDE_RESTRICTION_PREFIX, DECIMAL_RADIX, FL_TO_THOUSANDS_MULTIPLIER, NAME_INDEX, RESTRICTION_INDEX, RESTRICTION_SEPARATOR, SPEED_RESTRICTION_PREFIX } from '../../constants/navigation/waypointConstants'; /** * A route waypoint describes a `fixName` and any altitude or speed restrictions for that fix. * * @class StandardRouteWaypointModel * @extends BaseModel */ export default class StandardRouteWaypointModel extends BaseModel { /** * Expects `routeWaypoint` to be in one of these forms: * - ["FRAWG", "A80+|S210+"] * - ["FRAWG", "A80-|S210"] * - ["FRAWG", "A80"] * - ["FRAWG", "S210"] * - "FRAWG" * * @constructor * @param routeWaypoint {array|string} */ constructor(routeWaypoint) { super(); if (typeof routeWaypoint === 'undefined') { return this; } /** * Name of the fix * * @property name * @type {string} * @default '' * @private */ this.name = ''; /** * Any restrictions for a given fix * * ex: * - "A80+|S210" * - "A80-" * - "S230" * * using null here to match current api, if restrictions dont exist for a given waypoint * the consumers are expecting this to be null. * * @property _restrictions * @type {string|null} * @default null * @private */ this._restrictions = null; /** * Required altitude for a waypoint * * @property _altitude (optional) * @type {number} * @default null * @private */ this._altitude = -1; /** * Flag used to determine if the waypoint must be flown over before the * aircraft may proceed to the next fix on their route. * * @for StandardRouteWaypointModel * @property _isFlyOverWaypoint * @type {boolean} * @default false */ this._isFlyOverWaypoint = false; /** * Required speed for a waypoint * * @property _speed (optional) * @type {string} * @default null * @private */ this._speed = -1; // TODO: This will need to be implemented in the future as an emuneration. Something to the effect of: {BELOW|AT|ABOVE} /** * NOT IN USE * * Altitude constraint, if any, for a waypoint. * * @property _altitudeConstraint (options) * @type {string} * @default '' * @private */ this._altitudeConstraint = ''; /** * NOT IN USE * * Speed constraint, if any, for a waypoint. * * @property _speedConstraint (optional) * @type {string} * @default null * @private */ this._speedConstraint = ''; /** * Positon information for the current waypoint * * Specific bits of this property are exposed via public getters. * This property should never be modified by an exteral method. * * @property _positionModel * @type {StaticPositionModel} * @default null * @private */ this._positionModel = null; /** * Distance in nm from the previous waypoint. * * This property is set exterally by the `StandardRouteModel` and used only when called via * `ArrivalBase.preSpawn()`. * * This value is mutable and is not intended to be re-used after its initial use. * * @property distanceFromPreviousWaypoint * @type {number} * @default -1 */ this.distanceFromPreviousWaypoint = -1; /** * Name of the previous `StandardWaypointModel` object in a route * * This property is set exterally by the `StandardRouteModel` and used only when called via * `ArrivalBase.preSpawn()`. * * This value is mutable and is not intended to be re-used after its initial use. * * @property previousStandardWaypointName * @type {string} * @default '' */ this.previousStandardWaypointName = ''; return this._init(routeWaypoint) .clonePoisitonFromFix(); } /** * Return this waypoint's `gps` position property * * @property gps * @return {array} */ get gps() { return this._positionModel.gps; } /** * Return this waypoint's `gpsXY` position property * * @property gps * @return {array} */ get gpsXY() { return this._positionModel.gpsXY; } /** * This will return a normalized fix in the shape of `[FIXNAME, FIX_RESTRICTIONS]`. * * Fixes without restrictions are brought in to the application as a single string, however, all * fixes are consumed as an array. `_restrictions` are initialized as null, thus if there are * no restrictions for a fix this getter will return `[FIXNAME, null]` * * @for StandardRouteWaypointModel * @property fix * @return {array} */ get fix() { return [this.name, this._restrictions]; } /** * Provide read-only public access to this._positionModel * * @for SpawnPatternModel * @property positionModel * @type {StaticPositionModel} */ get positionModel() { return this._positionModel; } /** * Fascade to access relative position * * @for StandardRouteWaypointModel * @property relativePosition * @type {array<number>} [kilometersNorth, kilometersEast] */ get relativePosition() { return this._positionModel.relativePosition; } /** * Lifecycle method. Should be run only once on instantiation. * * @for StandardRouteWaypointModel * @method _init * @param routeWaypoint {array|string} * @chainable * @private */ _init(routeWaypoint) { // if we receive a string, this fix doesnt have any restrictions so we only need to set `name` if (typeof routeWaypoint === 'string') { this.name = routeWaypoint.replace(FLY_OVER_WAYPOINT_PREFIX, ''); this._isVector = routeWaypoint.indexOf(VECTOR_WAYPOINT_PREFIX) !== -1; this._isFlyOverWaypoint = routeWaypoint.indexOf(FLY_OVER_WAYPOINT_PREFIX) !== -1; return this; } this.name = routeWaypoint[NAME_INDEX].replace(FLY_OVER_WAYPOINT_PREFIX, ''); this._isVector = routeWaypoint[NAME_INDEX].indexOf(VECTOR_WAYPOINT_PREFIX) !== -1; this._isFlyOverWaypoint = routeWaypoint[NAME_INDEX].indexOf(FLY_OVER_WAYPOINT_PREFIX) !== -1; // temporary property. should end up as a getter that wraps private methods this._restrictions = routeWaypoint[RESTRICTION_INDEX]; this._parseWaypointRestrictions(routeWaypoint[RESTRICTION_INDEX]); return this; } /** * reset the current model instance * * @for StandardRouteWaypointModel * @method reset */ reset() { this.name = ''; this._restrictions = null; this._altitude = -1; this._altitudeConstraint = ''; this._speed = -1; this._speedConstraint = ''; return this; } /** * Find the matching fix from the `FixCollection` and clone its `StaticPositionModel` this `_positionModel` * * @for StandardRouteWaypointModel * @method _clonePoisitonFromFix * @param fixCollection {FixCollection} * @private */ clonePoisitonFromFix() { const fixModel = FixCollection.findFixByName(this.name); if (!fixModel) { console.warn(`The following fix was not found in the list of fixes for this Airport: ${this.name}`); return this; } this._positionModel = fixModel.clonePosition(); return this; } /** * Build a new `WaypointModel` from the current instance. * * This method provides a way to create a `WaypointModel` with the current * properties of a `StandardRouteWaypointModel` instance. * * This is used by `LegModel` when building a flight plan from a `routeString`. A `procedureRouteString` * will result in finding a list of `StandardRouteWaypointModel`s. From those `StandardRouteWaypointModel` * we need to be able to create `WaypointModel`s that the Fms can consume. * * There is a method of the same name in the `FixModel` that does this same thing * but will be used only for `directRouteStrings`. * * @for StandardRouteWaypointModel * @method toWaypointModel * @return {WaypointModel} */ toWaypointModel() { const waypointProps = { altitudeRestriction: this._altitude, isFlyOverWaypoint: this._isFlyOverWaypoint, isVector: this._isVector, name: this.name, positionModel: this.positionModel, speedRestriction: this._speed }; return new WaypointModel(waypointProps); } /** * Parse any waypoint restrictions * * Parse a single string into: * - `this._altitude` = expressed in feet * - `this._altitudeConstraint` = {BELOW|AT|ABOVE} * - `this._speed` = expressed in kts * * Exapmles: * - "A80+|S210" * - "A80-|S210" * - "A80" * - "S210" * * @for StandardRouteWaypointModel * @method _parseWaypointRestrictions * @param waypointRestrictions {string} * @private */ _parseWaypointRestrictions(waypointRestrictions) { if (_isNil(waypointRestrictions)) { return; } const restrictionPieces = this._extractRestrictionPieces(waypointRestrictions); for (let i = 0; i < restrictionPieces.length; i++) { const restriction = restrictionPieces[i]; // looking at the first letter of a restrictionPiece here. if (restriction[0] === ALTITUDE_RESTRICTION_PREFIX) { this._setAltitudeRestriction(restriction); } else if (restriction[0] === SPEED_RESTRICTION_PREFIX) { this._setSpeedRestriction(restriction); } } } /** * @for StandardRouteWaypointModel * @method _setAltitudeRestriction * @param altitudeRestriction {string} * @private */ _setAltitudeRestriction(rawAltitudeStr) { const altitudeRestriction = rawAltitudeStr.replace(REGEX.ALT_SPEED_RESTRICTION, ''); this._altitude = parseInt(altitudeRestriction, DECIMAL_RADIX) * FL_TO_THOUSANDS_MULTIPLIER; } /** * @for StandardRouteWaypointModel * @method _setSpeedRestriction * @param speedRestriction {string} * @private */ _setSpeedRestriction(rawSpeedRestrictionStr) { const speedRestriction = rawSpeedRestrictionStr.replace(REGEX.ALT_SPEED_RESTRICTION, ''); this._speed = parseInt(speedRestriction, DECIMAL_RADIX); } /** * @for StandardRouteWaypointModel * @method _extractRestrictionPieces * @param waypointRestrictions {array<string>} * @@return {string} * @private */ _extractRestrictionPieces(waypointRestrictions) { return waypointRestrictions.split(RESTRICTION_SEPARATOR); } }
load("bf4b12814bc95f34eeb130127d8438ab.js"); load("93fae755edd261212639eed30afa2ca4.js"); // This file was procedurally generated from the following sources: // - src/dstr-binding/obj-ptrn-id-trailing-comma.case // - src/dstr-binding/default/cls-decl-gen-meth-dflt.template /*--- description: Trailing comma is allowed following BindingPropertyList (class expression method (default parameters)) esid: sec-class-definitions-runtime-semantics-evaluation es6id: 14.5.16 features: [destructuring-binding, default-parameters] flags: [generated] info: | ClassDeclaration : class BindingIdentifier ClassTail 1. Let className be StringValue of BindingIdentifier. 2. Let value be the result of ClassDefinitionEvaluation of ClassTail with argument className. [...] 14.5.14 Runtime Semantics: ClassDefinitionEvaluation 21. For each ClassElement m in order from methods a. If IsStatic of m is false, then i. Let status be the result of performing PropertyDefinitionEvaluation for m with arguments proto and false. [...] 14.4.13 Runtime Semantics: PropertyDefinitionEvaluation GeneratorMethod : * PropertyName ( StrictFormalParameters ) { GeneratorBody } 1. Let propKey be the result of evaluating PropertyName. 2. ReturnIfAbrupt(propKey). 3. If the function code for this GeneratorMethod is strict mode code, let strict be true. Otherwise let strict be false. 4. Let scope be the running execution context's LexicalEnvironment. 5. Let closure be GeneratorFunctionCreate(Method, StrictFormalParameters, GeneratorBody, scope, strict). 9.2.1 [[Call]] ( thisArgument, argumentsList) [...] 7. Let result be OrdinaryCallEvaluateBody(F, argumentsList). [...] 9.2.1.3 OrdinaryCallEvaluateBody ( F, argumentsList ) 1. Let status be FunctionDeclarationInstantiation(F, argumentsList). [...] 9.2.12 FunctionDeclarationInstantiation(func, argumentsList) [...] 23. Let iteratorRecord be Record {[[iterator]]: CreateListIterator(argumentsList), [[done]]: false}. 24. If hasDuplicates is true, then [...] 25. Else, b. Let formalStatus be IteratorBindingInitialization for formals with iteratorRecord and env as arguments. [...] 13.3.3 Destructuring Binding Patterns ObjectBindingPattern[Yield] : { } { BindingPropertyList[?Yield] } { BindingPropertyList[?Yield] , } ---*/ var callCount = 0; class C { *method({ x, } = { x: 23 }) { assert.sameValue(x, 23); callCount = callCount + 1; } }; new C().method().next(); assert.sameValue(callCount, 1, 'method invoked exactly once');
/** * DB connection */ const mongoose = require('mongoose') const config = require('./index') const log4js = require('./../utils/log4j') mongoose.connect(config.URL,{ useNewUrlParser: true, useUnifiedTopology: true }) const db = mongoose.connection; // db.collections.song.createIndex({ songName: "text", songMimetype: "text", ipfsCID: "text" }) db.on('error',()=>{ log4js.error('*** MongoDB connect failed ***') }) db.on('open',()=>{ log4js.info('*** MongoDB successful connected ***') })
import activeComponentsById from 'reducers/app-state/active-components-by-id'; import activeCodeListsById from 'reducers/app-state/active-code-lists-by-id'; import activeCalculatedVariablesById from 'reducers/app-state/active-calculated-variables-by-id'; import collectedVariableByQuestion from 'reducers/app-state/collected-variable-by-question'; import activeExternalVariablesById from 'reducers/app-state/active-external-variables-by-id'; import invalidItemsByActiveQuestion from 'reducers/app-state/invalid-items-by-active-question'; import errorsByQuestionTab from 'reducers/app-state/errors-by-question-tab'; import formUtilsReducers from 'reducers/app-state/form-utils'; import { SET_ACTIVE_QUESTIONNAIRE, SET_SELECTED_COMPONENT, SET_EDITING_COMPONENT, UPDATE_ACTIVE_QUESTIONNAIRE, LOAD_STATISTICAL_CONTEXT_SUCCESS, SAVE_ACTIVE_QUESTIONNAIRE_SUCCESS, CREATE_PAGE_BREAK, REMOVE_PAGE_BREAK, } from 'actions/app-state'; import { CREATE_COMPONENT, DUPLICATE_COMPONENT, UPDATE_COMPONENT, REMOVE_COMPONENT, UPDATE_COMPONENT_PARENT, UPDATE_COMPONENT_ORDER, MOVE_COMPONENT, } from 'actions/component'; import { LOAD_USER_SUCCESS } from 'actions/user'; import { COMPONENT_TYPE } from 'constants/pogues-constants'; const { QUESTIONNAIRE } = COMPONENT_TYPE; const actionHandlers = { ...formUtilsReducers, }; const defaultState = { user: {}, activeQuestionnaire: {}, activeComponentsById: {}, activeCodeListsById: {}, activeCodesById: {}, activeCalculatedVariablesById: {}, activeExternalVariablesById: {}, collectedVariableByQuestion: {}, errorsByCode: {}, selectedComponentId: '', editingComponentId: '', errorsByQuestionTab: {}, isQuestionnaireModified: false, componentIdForPageBreak: '', focusedInput: '', }; export function loadUserSuccess(state, user) { return { ...state, user: user, }; } export function setActiveQuestionnaire(state, questionnaire) { const { components, codeLists, ...activeQuestionnaire } = questionnaire; return { ...state, activeQuestionnaire, }; } export function updateActiveQuestionnaire(state, updatedQuestionnaire) { return { ...state, isQuestionnaireModified: true, activeQuestionnaire: { ...state.activeQuestionnaire, ...updatedQuestionnaire, }, }; } export function getComponentIdForPageBreak(id, componentsStore, state) { const defaultReturn = { ...state, }; if (id && componentsStore[id]) { return { ...state, componentIdForPageBreak: componentsStore[id].pageBreak ? '' : id, }; } const questionnaire = Object.keys(componentsStore).find( key => componentsStore[key].type === QUESTIONNAIRE, ); if ( !questionnaire || !componentsStore[questionnaire].children || componentsStore[questionnaire].children.length === 0 ) return defaultReturn; const lastChildId = componentsStore[questionnaire].children .map(key => componentsStore[key]) .sort((c1, c2) => c1.weight < c2.weight)[0].id; return lastChildId ? getComponentIdForPageBreak(lastChildId, componentsStore, state) : defaultReturn; } export function setSelectedComponentId(state, id) { return { ...state, ...getComponentIdForPageBreak(id, state.activeComponentsById, { ...state, componentIdForPageBreak: '', }), selectedComponentId: id, }; } export function setEditingComponentId(state, id) { return { ...state, editingComponentId: id, }; } export function loadStatisticalContext(state, { serie, operation }) { return { ...state, activeQuestionnaire: { ...state.activeQuestionnaire, serie, operation, }, }; } export function setQuestionNotModified(state) { return { ...state, isQuestionnaireModified: false, }; } export function setQuestionModified(state) { return { ...state, isQuestionnaireModified: true, }; } export function setQuestionModifiedAndResetSelectedComponent(state) { return { ...setSelectedComponentId( { ...state, ...setQuestionModified(state), }, '', ), }; } actionHandlers[LOAD_USER_SUCCESS] = loadUserSuccess; actionHandlers[SET_ACTIVE_QUESTIONNAIRE] = setActiveQuestionnaire; actionHandlers[UPDATE_ACTIVE_QUESTIONNAIRE] = updateActiveQuestionnaire; actionHandlers[SET_SELECTED_COMPONENT] = setSelectedComponentId; actionHandlers[SET_EDITING_COMPONENT] = setEditingComponentId; actionHandlers[LOAD_STATISTICAL_CONTEXT_SUCCESS] = loadStatisticalContext; actionHandlers[SAVE_ACTIVE_QUESTIONNAIRE_SUCCESS] = setQuestionNotModified; actionHandlers[CREATE_COMPONENT] = setQuestionModified; actionHandlers[DUPLICATE_COMPONENT] = setQuestionModified; actionHandlers[UPDATE_COMPONENT] = setQuestionModified; actionHandlers[REMOVE_COMPONENT] = setQuestionModifiedAndResetSelectedComponent; actionHandlers[UPDATE_COMPONENT_PARENT] = setQuestionModified; actionHandlers[UPDATE_COMPONENT_ORDER] = setQuestionModified; actionHandlers[MOVE_COMPONENT] = setQuestionModified; actionHandlers[CREATE_PAGE_BREAK] = setQuestionModified; actionHandlers[REMOVE_PAGE_BREAK] = setQuestionModified; // @TODO: Add the combine functionality to the generic createActionHandler method export default function(state = defaultState, action) { if (!action) return state; const { type, payload, meta } = action; const hndlr = actionHandlers[type]; return { ...(hndlr ? hndlr(state, payload, meta) : state), activeComponentsById: activeComponentsById( state.activeComponentsById, action, ), activeCodeListsById: activeCodeListsById(state.activeCodeListsById, action), activeCalculatedVariablesById: activeCalculatedVariablesById( state.activeCalculatedVariablesById, action, ), collectedVariableByQuestion: collectedVariableByQuestion( state.collectedVariableByQuestion, action, ), activeExternalVariablesById: activeExternalVariablesById( state.activeExternalVariablesById, action, ), invalidItemsByActiveQuestion: invalidItemsByActiveQuestion( state.invalidItemsByActiveQuestion, action, ), errorsByQuestionTab: errorsByQuestionTab(state.errorsByQuestionTab, action), }; }
import * as tslib_1 from "tslib"; import * as React from 'react'; import { StyledIconBase } from '../../StyledIconBase'; export var Amilia = React.forwardRef(function (props, ref) { var attrs = { "fill": "currentColor", }; return (React.createElement(StyledIconBase, tslib_1.__assign({ iconAttrs: attrs, iconVerticalAlign: "-.125em", iconViewBox: "0 0 448 512" }, props, { ref: ref }), React.createElement("path", { fill: "currentColor", d: "M240.1 32c-61.9 0-131.5 16.9-184.2 55.4-5.1 3.1-9.1 9.2-7.2 19.4 1.1 5.1 5.1 27.4 10.2 39.6 4.1 10.2 14.2 10.2 20.3 6.1 32.5-22.3 96.5-47.7 152.3-47.7 57.9 0 58.9 28.4 58.9 73.1v38.5C203 227.7 78.2 251 46.7 264.2 11.2 280.5 16.3 357.7 16.3 376s15.2 104 124.9 104c47.8 0 113.7-20.7 153.3-42.1v25.4c0 3 2.1 8.2 6.1 9.1 3.1 1 50.7 2 59.9 2s62.5.3 66.5-.7c4.1-1 5.1-6.1 5.1-9.1V168c-.1-80.3-57.9-136-192-136zm50.2 348c-21.4 13.2-48.7 24.4-79.1 24.4-52.8 0-58.9-33.5-59-44.7 0-12.2-3-42.7 18.3-52.9 24.3-13.2 75.1-29.4 119.8-33.5z", key: "k0" }))); }); Amilia.displayName = 'Amilia'; export var AmiliaDimensions = { height: undefined, width: undefined };
import React from "react"; import { Button, Menu, MenuItem, Popover, Position } from "@blueprintjs/core"; import { IconNames } from "@blueprintjs/icons"; const InformationMenu = React.memo((props) => { const { libraryVersions, tosURL, privacyURL } = props; return ( <Popover content={ <Menu> <MenuItem href="https://chanzuckerberg.github.io/cellxgene/" target="_blank" icon="book" text="Documentation" rel="noopener" /> <MenuItem href="https://join-cellxgene-users.herokuapp.com/" target="_blank" icon="chat" text="Chat" rel="noopener" /> <MenuItem href="https://github.com/chanzuckerberg/cellxgene" target="_blank" icon="git-branch" text="Github" rel="noopener" /> <MenuItem target="_blank" text={libraryVersions?.cellxgene || null} /> <MenuItem text="MIT License" /> {tosURL && ( <MenuItem href={tosURL} target="_blank" text="Terms of Service" rel="noopener" /> )} {privacyURL && ( <MenuItem href={privacyURL} target="_blank" text="Privacy Policy" rel="noopener" /> )} </Menu> } position={Position.BOTTOM_RIGHT} modifiers={{ preventOverflow: { enabled: false }, hide: { enabled: false }, }} > <Button data-testid="menu" type="button" icon={IconNames.INFO_SIGN} style={{ cursor: "pointer", verticalAlign: "middle", }} /> </Popover> ); }); export default InformationMenu;
import React, { Fragment } from "react"; import Title from "accessories/Title"; import { InstallPWA } from "widgets"; export default { title: "Desing System/TemplatePWA/InstallPWA", }; export const INSTALLPWA = args => { return ( <Fragment> <Title variant="h2">Install PWA</Title> <InstallPWA {...args} /> </Fragment> ); }; INSTALLPWA.args = { text: "Agréganos a tu pantalla de inicio para visitarnos más fácil y rápido", btncancel: "No por ahora", btnadd: "Agregar", }; INSTALLPWA.argTypes = { texto: { control: "text" }, btncancel: { control: "text" }, btnadd: { control: "text" }, };
var ipp = require('../ipp.js'); var data = new Buffer( '0200' + //version 2.0 '000B' + //Get-Printer-Attributes '00000001'+ //reqid '01' + //operation-attributes-tag //blah blah the required bloat of this protocol '470012617474726962757465732d6368617273657400057574662d3848001b617474726962757465732d6e61747572616c2d6c616e67756167650002656e' + '03' //end-of-attributes-tag ,'hex'); var result = ipp.parse(data); console.log(JSON.stringify(result,null,2)); //ta-da! //{ // "version": "2.0", // "operation": 11, // "id": 1, // "operation-attributes-tag": { // "attributes-charset": "utf-8", // "attributes-natural-language": "en" // } //} return; var data = new Buffer( '0200' +//version '0000' +//status '00000001' +//reqid '01' +//operation-attributes-tag '470012617474726962757465732d6368617273657400057574662d3848001b617474726962757465732d6e61747572616c2d6c616e67756167650002656e' + // '044500157072696e7465722d7572692d737570706f7274656400166970703a2f2f435030312f6970702f7072696e7465724400167572692d73656375726974792d737570706f7274656400046e6f6e6544001c7572692d61757468656e7469636174696f6e2d737570706f72746564001472657175657374696e672d757365722d6e616d6542000c7072696e7465722d6e616d650004435030314100107072696e7465722d6c6f636174696f6e00004500117072696e7465722d6d6f72652d696e666f000b687474703a2f2f4350303141000c7072696e7465722d696e666f00164850204c617365724a657420343030204d343031646e4100167072696e7465722d6d616b652d616e642d6d6f64656c00164850204c617365724a657420343030204d343031646e23000d7072696e7465722d73746174650004000000' + '03' + // '4400157072696e7465722d73746174652d726561736f6e7300046e6f6e654400166970702d76657273696f6e732d737570706f727465640003312e304400000003312e314400000003322e302300146f7065726174696f6e732d737570706f7274656400040000000223000000040000000323000000040000000423000000040000000523000000040000000723000000040000000823000000040000000923000000040000000a23000000040000000b23000000040000003c2200206d756c7469706c652d646f63756d656e742d6a6f62732d737570706f72746564000101470012636861727365742d636f6e6669677572656400057574662d38470011636861727365742d737570706f7274656400057574662d38470000000875732d617363696948001b6e61747572616c2d6c616e67756167652d636f6e666967757265640002656e48002467656e6572617465642d6e61747572616c2d6c616e67756167652d737570706f727465640002656e490017646f63756d656e742d666f726d61742d64656661756c74000f6170706c69636174696f6e2f706466490019646f63756d656e742d666f726d61742d737570706f727465640009696d6167652f757266490000000f6170706c69636174696f6e2f70646649000000166170706c69636174696f6e2f706f737473637269707449000000166170706c69636174696f6e2f766e642e68702d50434c49000000186170706c69636174696f6e2f766e642e68702d50434c584c49000000106170706c69636174696f6e2f50434c6d49000000186170706c69636174696f6e2f6f637465742d73747265616d2200197072696e7465722d69732d616363657074696e672d6a6f62730001012100107175657565642d6a6f622d636f756e7400040000000044001670646c2d6f766572726964652d737570706f727465640009617474656d7074656421000f7072696e7465722d75702d74696d6500040004f0a4440015636f6d7072657373696f6e2d737570706f7274656400046e6f6e6522000f636f6c6f722d737570706f72746564000100220015706167652d72616e6765732d737570706f727465640001014400216a6f622d6372656174696f6e2d617474726962757465732d737570706f727465640006636f70696573440000000a66696e697368696e67734400000005736964657344000000156f7269656e746174696f6e2d72657175657374656444000000056d65646961440000000d7072696e742d7175616c69747944000000127072696e7465722d7265736f6c7574696f6e440000000a6f75747075742d62696e44000000096d656469612d636f6c440000000b6f75747075742d6d6f646544000000166970702d6174747269627574652d666964656c69747944000000086a6f622d6e616d65440000000b706167652d72616e676573440000001a6d756c7469706c652d646f63756d656e742d68616e646c696e67440000000f7064662d6669742d746f2d7061676544000000107072696e742d636f6c6f722d6d6f646544000000167072696e742d636f6e74656e742d6f7074696d697a6544000000196d616e75616c2d6475706c65782d73686565742d636f756e7444000000136d617267696e732d7072652d6170706c696564440000001670636c6d2d736f757263652d7265736f6c7574696f6e44000f6d656469612d737570706f7274656400126e615f6c65747465725f382e35783131696e44000000116e615f6c6567616c5f382e35783134696e44000000186e615f6578656375746976655f372e32357831302e35696e44000000146e615f666f6f6c736361705f382e35783133696e440000001069736f5f61345f323130783239376d6d440000001069736f5f61355f313438783231306d6d440000001069736f5f61365f313035783134386d6d44000000106a69735f62355f313832783235376d6d44000000117072635f31366b5f313935783237306d6d44000000117072635f31366b5f313834783236306d6d44000000117072635f31366b5f313937783237336d6d44000000146a706e5f686167616b695f313030783134386d6d44000000146a706e5f6f7566756b755f313438783230306d6d44000000186e615f6e756d6265722d31305f342e31323578392e35696e44000000166e615f6d6f6e617263685f332e38373578372e35696e440000001069736f5f62355f313736783235306d6d440000001069736f5f63355f313632783232396d6d440000001069736f5f646c5f313130783232306d6d44000d6d656469612d64656661756c7400126e615f6c65747465725f382e35783131696e4400136d656469612d636f6c2d737570706f72746564000a6d656469612d74797065440000000a6d656469612d73697a6544000000106d656469612d746f702d6d617267696e44000000116d656469612d6c6566742d6d617267696e44000000126d656469612d72696768742d6d617267696e44000000136d656469612d626f74746f6d2d6d617267696e440000000c6d656469612d736f7572636544000000106475706c65782d737570706f727465643400116d656469612d636f6c2d64656661756c7400004a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000054564a0000000b792d64696d656e73696f6e210000000400006d244a0000000f6d656469612d73697a652d6e616d6542000000126e615f6c65747465725f382e35783131696e37000000004a000000106d656469612d746f702d6d617267696e2100000004000001a74a000000136d656469612d626f74746f6d2d6d617267696e2100000004000001a74a000000116d656469612d6c6566742d6d617267696e2100000004000001a74a000000126d656469612d72696768742d6d617267696e2100000004000001a74a0000000c6d656469612d736f7572636544000000046175746f4a0000000a6d656469612d74797065420000000a73746174696f6e6572794a000000106475706c65782d737570706f72746564210000000400000001370000000021001b6d656469612d6c6566742d6d617267696e2d737570706f727465640004000001a721001c6d656469612d72696768742d6d617267696e2d737570706f727465640004000001a721001a6d656469612d746f702d6d617267696e2d737570706f727465640004000001a721001d6d656469612d626f74746f6d2d6d617267696e2d737570706f727465640004000001a74400166d656469612d736f757263652d737570706f7274656400046175746f44000000066d616e75616c4400000006747261792d314400000006747261792d324200146d656469612d747970652d737570706f72746564000a73746174696f6e657279420000001673746174696f6e6572792d6c69676874776569676874420000000a65787472614c6967687442000000096d6964776569676874420000001673746174696f6e6572792d6865617679776569676874420000000a657874726148656176794200000011636f6c6f725472616e73706172656e637942000000066c6162656c73420000001573746174696f6e6572792d6c6574746572686561644200000008656e76656c6f7065420000001573746174696f6e6572792d7072657072696e746564420000001573746174696f6e6572792d70726570756e636865644200000005636f6c6f724200000004626f6e64420000000872656379636c65644200000005726f7567683400196a6f622d636f6e73747261696e74732d737570706f7274656400004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001474776f2d73696465642d73686f72742d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000047ef4a0000000b792d64696d656e73696f6e21000000040000682e4a0000000f6d656469612d73697a652d6e616d6542000000186e615f6578656375746976655f372e32357831302e35696e3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001474776f2d73696465642d73686f72742d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000054564a0000000b792d64696d656e73696f6e2100000004000080fc4a0000000f6d656469612d73697a652d6e616d6542000000146e615f666f6f6c736361705f382e35783133696e3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001474776f2d73696465642d73686f72742d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000039d04a0000000b792d64696d656e73696f6e2100000004000052084a0000000f6d656469612d73697a652d6e616d65420000001069736f5f61355f313438783231306d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001474776f2d73696465642d73686f72742d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000029044a0000000b792d64696d656e73696f6e2100000004000039d04a0000000f6d656469612d73697a652d6e616d65420000001069736f5f61365f313035783134386d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001474776f2d73696465642d73686f72742d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000047184a0000000b792d64696d656e73696f6e2100000004000064644a0000000f6d656469612d73697a652d6e616d6542000000106a69735f62355f313832783235376d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001474776f2d73696465642d73686f72742d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e210000000400004c2c4a0000000b792d64696d656e73696f6e2100000004000069784a0000000f6d656469612d73697a652d6e616d6542000000117072635f31366b5f313935783237306d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001474776f2d73696465642d73686f72742d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000047e04a0000000b792d64696d656e73696f6e2100000004000065904a0000000f6d656469612d73697a652d6e616d6542000000117072635f31366b5f313834783236306d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001474776f2d73696465642d73686f72742d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e210000000400004ce04a0000000b792d64696d656e73696f6e210000000400006aa44a0000000f6d656469612d73697a652d6e616d6542000000117072635f31366b5f313937783237336d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001474776f2d73696465642d73686f72742d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000027104a0000000b792d64696d656e73696f6e2100000004000039d04a0000000f6d656469612d73697a652d6e616d6542000000146a706e5f686167616b695f313030783134386d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001474776f2d73696465642d73686f72742d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000039d04a0000000b792d64696d656e73696f6e210000000400004e204a0000000f6d656469612d73697a652d6e616d6542000000146a706e5f6f7566756b755f313438783230306d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001474776f2d73696465642d73686f72742d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000028f04a0000000b792d64696d656e73696f6e210000000400005e424a0000000f6d656469612d73697a652d6e616d6542000000186e615f6e756d6265722d31305f342e31323578392e35696e3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001474776f2d73696465642d73686f72742d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000026704a0000000b792d64696d656e73696f6e210000000400004a6a4a0000000f6d656469612d73697a652d6e616d6542000000166e615f6d6f6e617263685f332e38373578372e35696e3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001474776f2d73696465642d73686f72742d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000044c04a0000000b792d64696d656e73696f6e2100000004000061a84a0000000f6d656469612d73697a652d6e616d65420000001069736f5f62355f313736783235306d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001474776f2d73696465642d73686f72742d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e210000000400003f484a0000000b792d64696d656e73696f6e2100000004000059744a0000000f6d656469612d73697a652d6e616d65420000001069736f5f63355f313632783232396d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001474776f2d73696465642d73686f72742d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e210000000400002af84a0000000b792d64696d656e73696f6e2100000004000055f04a0000000f6d656469612d73697a652d6e616d65420000001069736f5f646c5f313130783232306d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001374776f2d73696465642d6c6f6e672d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000047ef4a0000000b792d64696d656e73696f6e21000000040000682e4a0000000f6d656469612d73697a652d6e616d6542000000186e615f6578656375746976655f372e32357831302e35696e3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001374776f2d73696465642d6c6f6e672d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000054564a0000000b792d64696d656e73696f6e2100000004000080fc4a0000000f6d656469612d73697a652d6e616d6542000000146e615f666f6f6c736361705f382e35783133696e3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001374776f2d73696465642d6c6f6e672d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000039d04a0000000b792d64696d656e73696f6e2100000004000052084a0000000f6d656469612d73697a652d6e616d65420000001069736f5f61355f313438783231306d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001374776f2d73696465642d6c6f6e672d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000029044a0000000b792d64696d656e73696f6e2100000004000039d04a0000000f6d656469612d73697a652d6e616d65420000001069736f5f61365f313035783134386d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001374776f2d73696465642d6c6f6e672d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000047184a0000000b792d64696d656e73696f6e2100000004000064644a0000000f6d656469612d73697a652d6e616d6542000000106a69735f62355f313832783235376d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001374776f2d73696465642d6c6f6e672d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e210000000400004c2c4a0000000b792d64696d656e73696f6e2100000004000069784a0000000f6d656469612d73697a652d6e616d6542000000117072635f31366b5f313935783237306d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001374776f2d73696465642d6c6f6e672d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000047e04a0000000b792d64696d656e73696f6e2100000004000065904a0000000f6d656469612d73697a652d6e616d6542000000117072635f31366b5f313834783236306d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001374776f2d73696465642d6c6f6e672d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e210000000400004ce04a0000000b792d64696d656e73696f6e210000000400006aa44a0000000f6d656469612d73697a652d6e616d6542000000117072635f31366b5f313937783237336d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001374776f2d73696465642d6c6f6e672d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000027104a0000000b792d64696d656e73696f6e2100000004000039d04a0000000f6d656469612d73697a652d6e616d6542000000146a706e5f686167616b695f313030783134386d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001374776f2d73696465642d6c6f6e672d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000039d04a0000000b792d64696d656e73696f6e210000000400004e204a0000000f6d656469612d73697a652d6e616d6542000000146a706e5f6f7566756b755f313438783230306d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001374776f2d73696465642d6c6f6e672d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000028f04a0000000b792d64696d656e73696f6e210000000400005e424a0000000f6d656469612d73697a652d6e616d6542000000186e615f6e756d6265722d31305f342e31323578392e35696e3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001374776f2d73696465642d6c6f6e672d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000026704a0000000b792d64696d656e73696f6e210000000400004a6a4a0000000f6d656469612d73697a652d6e616d6542000000166e615f6d6f6e617263685f332e38373578372e35696e3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001374776f2d73696465642d6c6f6e672d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000044c04a0000000b792d64696d656e73696f6e2100000004000061a84a0000000f6d656469612d73697a652d6e616d65420000001069736f5f62355f313736783235306d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001374776f2d73696465642d6c6f6e672d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e210000000400003f484a0000000b792d64696d656e73696f6e2100000004000059744a0000000f6d656469612d73697a652d6e616d65420000001069736f5f63355f313632783232396d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a000000057369646573440000001374776f2d73696465642d6c6f6e672d656467654a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e210000000400002af84a0000000b792d64696d656e73696f6e2100000004000055f04a0000000f6d656469612d73697a652d6e616d65420000001069736f5f646c5f313130783232306d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a000000057369646573440000001474776f2d73696465642d73686f72742d656467654a0000000a6d656469612d747970654200000011636f6c6f725472616e73706172656e6379370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a000000057369646573440000001474776f2d73696465642d73686f72742d656467654a0000000a6d656469612d7479706542000000066c6162656c73370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a000000057369646573440000001474776f2d73696465642d73686f72742d656467654a0000000a6d656469612d747970654200000008656e76656c6f7065370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a000000057369646573440000001374776f2d73696465642d6c6f6e672d656467654a0000000a6d656469612d747970654200000011636f6c6f725472616e73706172656e6379370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a000000057369646573440000001374776f2d73696465642d6c6f6e672d656467654a0000000a6d656469612d7479706542000000066c6162656c73370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a000000057369646573440000001374776f2d73696465642d6c6f6e672d656467654a0000000a6d656469612d747970654200000008656e76656c6f706537000000003400176a6f622d7265736f6c766572732d737570706f7274656400004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a00000005736964657344000000096f6e652d73696465644a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000054564a0000000b792d64696d656e73696f6e210000000400006d244a0000000f6d656469612d73697a652d6e616d6542000000126e615f6c65747465725f382e35783131696e3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a00000005736964657344000000096f6e652d73696465644a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000054564a0000000b792d64696d656e73696f6e210000000400008ae84a0000000f6d656469612d73697a652d6e616d6542000000116e615f6c6567616c5f382e35783134696e3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d73697a654a00000005736964657344000000096f6e652d73696465644a0000000a6d656469612d73697a6534000000004a0000000b782d64696d656e73696f6e2100000004000052084a0000000b792d64696d656e73696f6e2100000004000074044a0000000f6d656469612d73697a652d6e616d65420000001069736f5f61345f323130783239376d6d3700000000370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a00000005736964657344000000096f6e652d73696465644a0000000a6d656469612d74797065420000000a73746174696f6e657279370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a00000005736964657344000000096f6e652d73696465644a0000000a6d656469612d74797065420000001673746174696f6e6572792d6c69676874776569676874370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a00000005736964657344000000096f6e652d73696465644a0000000a6d656469612d74797065420000000a65787472614c69676874370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a00000005736964657344000000096f6e652d73696465644a0000000a6d656469612d7479706542000000096d6964776569676874370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a00000005736964657344000000096f6e652d73696465644a0000000a6d656469612d74797065420000001673746174696f6e6572792d6865617679776569676874370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a00000005736964657344000000096f6e652d73696465644a0000000a6d656469612d74797065420000000a65787472614865617679370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a00000005736964657344000000096f6e652d73696465644a0000000a6d656469612d74797065420000001573746174696f6e6572792d6c657474657268656164370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a00000005736964657344000000096f6e652d73696465644a0000000a6d656469612d74797065420000001573746174696f6e6572792d7072657072696e746564370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a00000005736964657344000000096f6e652d73696465644a0000000a6d656469612d74797065420000001573746174696f6e6572792d70726570756e63686564370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a00000005736964657344000000096f6e652d73696465644a0000000a6d656469612d747970654200000005636f6c6f72370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a00000005736964657344000000096f6e652d73696465644a0000000a6d656469612d747970654200000004626f6e64370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a00000005736964657344000000096f6e652d73696465644a0000000a6d656469612d74797065420000000872656379636c6564370000000034000000004a0000000d7265736f6c7665722d6e616d65420000001b6475706c65782d737570706f727465642d6d656469612d747970654a00000005736964657344000000096f6e652d73696465644a0000000a6d656469612d747970654200000005726f756768370000000021001070616765732d7065722d6d696e7574650004000000233300167064662d6b2d6f63746574732d737570706f72746564000800000000000124f84400167064662d76657273696f6e732d737570706f72746564000961646f62652d312e32440000000961646f62652d312e33440000000961646f62652d312e34440000000961646f62652d312e35440000000961646f62652d312e36440000000961646f62652d312e37440000001069736f2d31393030352d315f32303035440000001069736f2d33323030302d315f3230303844000d7572662d737570706f727465640004435039394400000002573844000000044f42313044000000075051332d342d354400000003444d3144000000074953312d322d3444000000094d54312d322d332d3544000000094d54312d322d332d35440000000a52533630302d3132303045000c7072696e7465722d75756964002d75726e3a757569643a35363465343233332d343833302d333433352d333033332d38306331366539373265353142000c6d61726b65722d6e616d65730019426c61636b204361727472696467652048502043463238305842000d6d61726b65722d636f6c6f727300072330303030303044000c6d61726b65722d74797065730005746f6e65722100116d61726b65722d6c6f772d6c6576656c730004000000062100126d61726b65722d686967682d6c6576656c7300040000006421000d6d61726b65722d6c6576656c7300040000004721000e636f706965732d64656661756c740004000000014400226d756c7469706c652d646f63756d656e742d68616e646c696e672d64656661756c74000f73696e676c652d646f63756d656e7423001266696e697368696e67732d64656661756c7400040000000323001d6f7269656e746174696f6e2d7265717565737465642d64656661756c740004000000032300157072696e742d7175616c6974792d64656661756c7400040000000432001a7072696e7465722d7265736f6c7574696f6e2d64656661756c74000900000258000002580344000d73696465732d64656661756c7400096f6e652d73696465644400126f75747075742d62696e2d64656661756c740009666163652d646f776e4400136f75747075742d6d6f64652d64656661756c7400046175746f440000000a6d6f6e6f6368726f6d65330010636f706965732d737570706f72746564000800000001000003e74400246d756c7469706c652d646f63756d656e742d68616e646c696e672d737570706f72746564000f73696e676c652d646f63756d656e74440000002473657061726174652d646f63756d656e74732d756e636f6c6c617465642d636f70696573440000002273657061726174652d646f63756d656e74732d636f6c6c617465642d636f70696573440000001973696e676c652d646f63756d656e742d6e65772d736865657423001466696e697368696e67732d737570706f7274656400040000000323001f6f7269656e746174696f6e2d7265717565737465642d737570706f727465640004000000032300000004000000042300000004000000052300000004000000062300177072696e742d7175616c6974792d737570706f7274656400040000000423000000040000000332001c7072696e7465722d7265736f6c7574696f6e2d737570706f7274656400090000025800000258033200000009000004b0000004b00344000f73696465732d737570706f7274656400096f6e652d7369646564440000001474776f2d73696465642d73686f72742d65646765440000001374776f2d73696465642d6c6f6e672d656467653300196a6f622d696d7072657373696f6e732d737570706f727465640008000000010001869f4400146f75747075742d62696e2d737570706f727465640009666163652d646f776e4400156f75747075742d6d6f64652d737570706f7274656400046175746f440000000a6d6f6e6f6368726f6d6545000d7072696e7465722d69636f6e730022687474703a2f2f435030312f6970702f696d616765732f7072696e7465722e706e674500000028687474703a2f2f435030312f6970702f696d616765732f7072696e7465722d6c617267652e706e674500177072696e7465722d737570706c792d696e666f2d7572690028687474703a2f2f435030312f68702f6465766963652f6d537570706c795374617475732e68746d6c4100117072696e7465722d6465766963652d696400d04d46473a4865776c6574742d5061636b6172643b434d443a504a4c2c504d4c2c50434c584c2c5552502c50434c2c5044462c504f53545343524950543b4d444c3a4850204c617365724a657420343030204d343031646e3b434c533a5052494e5445523b4445533a4865776c6574742d5061636b617264204c617365724a657420343030204d343031646e3b4d454d3a4d454d3d3233374d423b434f4d4d454e543a5245533d3132303078313b4c45444d4449533a5553422366662330342330313b4349443a48504c4a50444c56313b2300296c616e6473636170652d6f7269656e746174696f6e2d7265717565737465642d7072656665727265640004000000044400186964656e746966792d616374696f6e732d64656661756c740007646973706c617944001a6964656e746966792d616374696f6e732d737570706f727465640007646973706c61794400166570636c2d76657273696f6e2d737570706f7274656400086570636c2d312e3044001b696d6167652d656e68616e63656d656e742d737570706f72746564000e6f626a6563742d74616767696e6744000000136b2d706c616e652d656e68616e63656d656e742200176d616e75616c2d6475706c65782d737570706f7274656400010144001570636c6d2d7261737465722d6261636b2d7369646500066e6f726d616c44002170636c6d2d636f6d7072657373696f6e2d6d6574686f642d70726566657272656400046a70656732002070636c6d2d736f757263652d7265736f6c7574696f6e2d737570706f7274656400090000025800000258033200000009000004b0000004b00321001b70636c6d2d73747269702d6865696768742d70726566657272656400040000001021001b70636c6d2d73747269702d6865696768742d737570706f727465640004000000002100000004000000102100000004000000202100000004000000402100000004000000802100000004000001002100000004000002002200177064662d6669742d746f2d706167652d64656661756c740001002200197064662d6669742d746f2d706167652d737570706f727465640001012100147064662d73697a652d636f6e73747261696e74730004047868c04400187072696e742d636f6c6f722d6d6f64652d64656661756c74000a6d6f6e6f6368726f6d6544001a7072696e742d636f6c6f722d6d6f64652d737570706f72746564000a6d6f6e6f6368726f6d6544001e7072696e742d636f6e74656e742d6f7074696d697a652d64656661756c740011746578742d616e642d67726170686963734400207072696e742d636f6e74656e742d6f7074696d697a652d737570706f72746564000570686f746f440000000867726170686963734400000004746578744400000011746578742d616e642d677261706869637303' + '', 'hex'); var ipp = require('../ipp.js'); var result = ipp.parse(data); console.log(JSON.stringify(result,null,2)); var x = { "version": "2.0", "operation": 0, "id": 1, "operation-attributes-tag": { "attributes-charset": "utf-8", "attributes-natural-language": "en" }, "printer-attributes-tag": { "printer-uri-supported": "ipp://CP01/ipp/printer", "uri-security-supported": "none", "uri-authentication-supported": "requesting-user-name", "printer-name": "CP01", "printer-location": "", "printer-more-info": "http://CP01", "printer-info": "HP LaserJet 400 M401dn", "printer-make-and-model": "HP LaserJet 400 M401dn", "printer-state": "idle", "printer-state-reasons": "none", "ipp-versions-supported": [ "1.0", "1.1", "2.0" ], "operations-supported": [ "Print-Job", "Print-URI", "Validate-Job", "Create-Job", "Send-URI", "Cancel-Job", "Get-Job-Attributes", "Get-Jobs", "Get-Printer-Attributes", "Identify-Printer" ], "multiple-document-jobs-supported": true, "charset-configured": "utf-8", "charset-supported": [ "utf-8", "us-ascii" ], "natural-language-configured": "en", "generated-natural-language-supported": "en", "document-format-default": "application/pdf", "document-format-supported": [ "image/urf", "application/pdf", "application/postscript", "application/vnd.hp-PCL", "application/vnd.hp-PCLXL", "application/PCLm", "application/octet-stream" ], "printer-is-accepting-jobs": true, "queued-job-count": 0, "pdl-override-supported": "attempted", "printer-up-time": 323748, "compression-supported": "none", "color-supported": false, "page-ranges-supported": true, "job-creation-attributes-supported": [ "copies", "finishings", "sides", "orientation-requested", "media", "print-quality", "printer-resolution", "output-bin", "media-col", "output-mode", "ipp-attribute-fidelity", "job-name", "page-ranges", "multiple-document-handling", "pdf-fit-to-page", "print-color-mode", "print-content-optimize", "manual-duplex-sheet-count", "margins-pre-applied", "pclm-source-resolution" ], "media-supported": [ "na_letter_8.5x11in", "na_legal_8.5x14in", "na_executive_7.25x10.5in", "na_foolscap_8.5x13in", "iso_a4_210x297mm", "iso_a5_148x210mm", "iso_a6_105x148mm", "jis_b5_182x257mm", "prc_16k_195x270mm", "prc_16k_184x260mm", "prc_16k_197x273mm", "jpn_hagaki_100x148mm", "jpn_oufuku_148x200mm", "na_number-10_4.125x9.5in", "na_monarch_3.875x7.5in", "iso_b5_176x250mm", "iso_c5_162x229mm", "iso_dl_110x220mm" ], "media-default": "na_letter_8.5x11in", "media-col-supported": [ "media-type", "media-size", "media-top-margin", "media-left-margin", "media-right-margin", "media-bottom-margin", "media-source", "duplex-supported" ], "media-col-default": { "media-size": { "x-dimension": 21590, "y-dimension": 27940, "media-size-name": "na_letter_8.5x11in" }, "media-top-margin": 423, "media-bottom-margin": 423, "media-left-margin": 423, "media-right-margin": 423, "media-source": "auto", "media-type": "stationery", "duplex-supported": 1 }, "media-left-margin-supported": 423, "media-right-margin-supported": 423, "media-top-margin-supported": 423, "media-bottom-margin-supported": 423, "media-source-supported": [ "auto", "manual", "tray-1", "tray-2" ], "media-type-supported": [ "stationery", "stationery-lightweight", "extraLight", "midweight", "stationery-heavyweight", "extraHeavy", "colorTransparency", "labels", "stationery-letterhead", "envelope", "stationery-preprinted", "stationery-prepunched", "color", "bond", "recycled", "rough" ], "job-constraints-supported": [ { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-short-edge", "media-size": { "x-dimension": 18415, "y-dimension": 26670, "media-size-name": "na_executive_7.25x10.5in" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-short-edge", "media-size": { "x-dimension": 21590, "y-dimension": 33020, "media-size-name": "na_foolscap_8.5x13in" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-short-edge", "media-size": { "x-dimension": 14800, "y-dimension": 21000, "media-size-name": "iso_a5_148x210mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-short-edge", "media-size": { "x-dimension": 10500, "y-dimension": 14800, "media-size-name": "iso_a6_105x148mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-short-edge", "media-size": { "x-dimension": 18200, "y-dimension": 25700, "media-size-name": "jis_b5_182x257mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-short-edge", "media-size": { "x-dimension": 19500, "y-dimension": 27000, "media-size-name": "prc_16k_195x270mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-short-edge", "media-size": { "x-dimension": 18400, "y-dimension": 26000, "media-size-name": "prc_16k_184x260mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-short-edge", "media-size": { "x-dimension": 19680, "y-dimension": 27300, "media-size-name": "prc_16k_197x273mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-short-edge", "media-size": { "x-dimension": 10000, "y-dimension": 14800, "media-size-name": "jpn_hagaki_100x148mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-short-edge", "media-size": { "x-dimension": 14800, "y-dimension": 20000, "media-size-name": "jpn_oufuku_148x200mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-short-edge", "media-size": { "x-dimension": 10480, "y-dimension": 24130, "media-size-name": "na_number-10_4.125x9.5in" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-short-edge", "media-size": { "x-dimension": 9840, "y-dimension": 19050, "media-size-name": "na_monarch_3.875x7.5in" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-short-edge", "media-size": { "x-dimension": 17600, "y-dimension": 25000, "media-size-name": "iso_b5_176x250mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-short-edge", "media-size": { "x-dimension": 16200, "y-dimension": 22900, "media-size-name": "iso_c5_162x229mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-short-edge", "media-size": { "x-dimension": 11000, "y-dimension": 22000, "media-size-name": "iso_dl_110x220mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-long-edge", "media-size": { "x-dimension": 18415, "y-dimension": 26670, "media-size-name": "na_executive_7.25x10.5in" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-long-edge", "media-size": { "x-dimension": 21590, "y-dimension": 33020, "media-size-name": "na_foolscap_8.5x13in" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-long-edge", "media-size": { "x-dimension": 14800, "y-dimension": 21000, "media-size-name": "iso_a5_148x210mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-long-edge", "media-size": { "x-dimension": 10500, "y-dimension": 14800, "media-size-name": "iso_a6_105x148mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-long-edge", "media-size": { "x-dimension": 18200, "y-dimension": 25700, "media-size-name": "jis_b5_182x257mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-long-edge", "media-size": { "x-dimension": 19500, "y-dimension": 27000, "media-size-name": "prc_16k_195x270mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-long-edge", "media-size": { "x-dimension": 18400, "y-dimension": 26000, "media-size-name": "prc_16k_184x260mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-long-edge", "media-size": { "x-dimension": 19680, "y-dimension": 27300, "media-size-name": "prc_16k_197x273mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-long-edge", "media-size": { "x-dimension": 10000, "y-dimension": 14800, "media-size-name": "jpn_hagaki_100x148mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-long-edge", "media-size": { "x-dimension": 14800, "y-dimension": 20000, "media-size-name": "jpn_oufuku_148x200mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-long-edge", "media-size": { "x-dimension": 10480, "y-dimension": 24130, "media-size-name": "na_number-10_4.125x9.5in" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-long-edge", "media-size": { "x-dimension": 9840, "y-dimension": 19050, "media-size-name": "na_monarch_3.875x7.5in" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-long-edge", "media-size": { "x-dimension": 17600, "y-dimension": 25000, "media-size-name": "iso_b5_176x250mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-long-edge", "media-size": { "x-dimension": 16200, "y-dimension": 22900, "media-size-name": "iso_c5_162x229mm" } }, { "resolver-name": "duplex-supported-media-size", "sides": "two-sided-long-edge", "media-size": { "x-dimension": 11000, "y-dimension": 22000, "media-size-name": "iso_dl_110x220mm" } }, { "resolver-name": "duplex-supported-media-type", "sides": "two-sided-short-edge", "media-type": "colorTransparency" }, { "resolver-name": "duplex-supported-media-type", "sides": "two-sided-short-edge", "media-type": "labels" }, { "resolver-name": "duplex-supported-media-type", "sides": "two-sided-short-edge", "media-type": "envelope" }, { "resolver-name": "duplex-supported-media-type", "sides": "two-sided-long-edge", "media-type": "colorTransparency" }, { "resolver-name": "duplex-supported-media-type", "sides": "two-sided-long-edge", "media-type": "labels" }, { "resolver-name": "duplex-supported-media-type", "sides": "two-sided-long-edge", "media-type": "envelope" } ], "job-resolvers-supported": [ { "resolver-name": "duplex-supported-media-size", "sides": "one-sided", "media-size": { "x-dimension": 21590, "y-dimension": 27940, "media-size-name": "na_letter_8.5x11in" } }, { "resolver-name": "duplex-supported-media-size", "sides": "one-sided", "media-size": { "x-dimension": 21590, "y-dimension": 35560, "media-size-name": "na_legal_8.5x14in" } }, { "resolver-name": "duplex-supported-media-size", "sides": "one-sided", "media-size": { "x-dimension": 21000, "y-dimension": 29700, "media-size-name": "iso_a4_210x297mm" } }, { "resolver-name": "duplex-supported-media-type", "sides": "one-sided", "media-type": "stationery" }, { "resolver-name": "duplex-supported-media-type", "sides": "one-sided", "media-type": "stationery-lightweight" }, { "resolver-name": "duplex-supported-media-type", "sides": "one-sided", "media-type": "extraLight" }, { "resolver-name": "duplex-supported-media-type", "sides": "one-sided", "media-type": "midweight" }, { "resolver-name": "duplex-supported-media-type", "sides": "one-sided", "media-type": "stationery-heavyweight" }, { "resolver-name": "duplex-supported-media-type", "sides": "one-sided", "media-type": "extraHeavy" }, { "resolver-name": "duplex-supported-media-type", "sides": "one-sided", "media-type": "stationery-letterhead" }, { "resolver-name": "duplex-supported-media-type", "sides": "one-sided", "media-type": "stationery-preprinted" }, { "resolver-name": "duplex-supported-media-type", "sides": "one-sided", "media-type": "stationery-prepunched" }, { "resolver-name": "duplex-supported-media-type", "sides": "one-sided", "media-type": "color" }, { "resolver-name": "duplex-supported-media-type", "sides": "one-sided", "media-type": "bond" }, { "resolver-name": "duplex-supported-media-type", "sides": "one-sided", "media-type": "recycled" }, { "resolver-name": "duplex-supported-media-type", "sides": "one-sided", "media-type": "rough" } ], "pages-per-minute": 35, "pdf-k-octets-supported": [ 0, 75000 ], "pdf-versions-supported": [ "adobe-1.2", "adobe-1.3", "adobe-1.4", "adobe-1.5", "adobe-1.6", "adobe-1.7", "iso-19005-1_2005", "iso-32000-1_2008" ], "urf-supported": [ "CP99", "W8", "OB10", "PQ3-4-5", "DM1", "IS1-2-4", "MT1-2-3-5", "MT1-2-3-5", "RS600-1200" ], "printer-uuid": "urn:uuid:564e4233-4830-3435-3033-80c16e972e51", "marker-names": "Black Cartridge HP CF280X", "marker-colors": "#000000", "marker-types": "toner", "marker-low-levels": 6, "marker-high-levels": 100, "marker-levels": 71, "copies-default": 1, "multiple-document-handling-default": "single-document", "finishings-default": "none", "orientation-requested-default": "portrait", "print-quality-default": "normal", "printer-resolution-default": [ 600, 600, "dpi" ], "sides-default": "one-sided", "output-bin-default": "face-down", "output-mode-default": [ "auto", "monochrome" ], "copies-supported": [ 1, 999 ], "multiple-document-handling-supported": [ "single-document", "separate-documents-uncollated-copies", "separate-documents-collated-copies", "single-document-new-sheet" ], "finishings-supported": "none", "orientation-requested-supported": [ "portrait", "landscape", "reverse-landscape", "reverse-portrait" ], "print-quality-supported": [ "normal", "draft" ], "printer-resolution-supported": [ [ 600, 600, "dpi" ], [ 1200, 1200, "dpi" ] ], "sides-supported": [ "one-sided", "two-sided-short-edge", "two-sided-long-edge" ], "job-impressions-supported": [ 1, 99999 ], "output-bin-supported": "face-down", "output-mode-supported": [ "auto", "monochrome" ], "printer-icons": [ "http://CP01/ipp/images/printer.png", "http://CP01/ipp/images/printer-large.png" ], "printer-supply-info-uri": "http://CP01/hp/device/mSupplyStatus.html", "printer-device-id": "MFG:Hewlett-Packard;CMD:PJL,PML,PCLXL,URP,PCL,PDF,POSTSCRIPT;MDL:HP LaserJet 400 M401dn;CLS:PRINTER;DES:Hewlett-Packard LaserJet 400 M401dn;MEM:MEM=237MB;COMMENT:RES=1200x1;LEDMDIS:USB#ff#04#01;CID:HPLJPDLV1;", "landscape-orientation-requested-preferred": "landscape", "identify-actions-default": "display", "identify-actions-supported": "display", "epcl-version-supported": "epcl-1.0", "image-enhancement-supported": [ "object-tagging", "k-plane-enhancement" ], "manual-duplex-supported": true, "pclm-raster-back-side": "normal", "pclm-compression-method-preferred": "jpeg", "pclm-source-resolution-supported": [ [ 600, 600, "dpi" ], [ 1200, 1200, "dpi" ] ], "pclm-strip-height-preferred": 16, "pclm-strip-height-supported": [ 0, 16, 32, 64, 128, 256, 512 ], "pdf-fit-to-page-default": false, "pdf-fit-to-page-supported": true, "pdf-size-constraints": 75000000, "print-color-mode-default": "monochrome", "print-color-mode-supported": "monochrome", "print-content-optimize-default": "text-and-graphics", "print-content-optimize-supported": [ "photo", "graphics", "text", "text-and-graphics" ] } };
const logs = [ { _id: "5c37f4cbc0acb663ef64e330", _ability: "ability-id-1", type: "event", data: false, createdAt: "2019-01-11T01:43:39.493Z" }, { _id: "5c381289c0acb663ef64e331", _ability: "ability-id-1", type: "event", data: false, createdAt: "2019-01-11T03:50:33.160Z" }, { _id: "5c381297c0acb663ef64e332", _ability: "ability-id-1", type: "event", data: false, createdAt: "2019-01-11T03:50:47.062Z" }, { _id: "5c381298c0acb663ef64e333", _ability: "ability-id-1", type: "event", data: false, createdAt: "2019-01-11T03:50:48.079Z" }, { _id: "5c3812eac0acb663ef64e334", _ability: "ability-id-2", type: "event", data: false, createdAt: "2019-01-11T03:52:10.827Z" }, { _id: "5c5b2c4eb8f9f4a654776902", _ability: "ability-id-2", type: "action", createdAt: "2019-02-06T18:49:50.265Z" }, { _id: "5c5b2c4eb8f9f4a654776903", _ability: "ability-id-2", type: "event", createdAt: "2019-02-06T18:49:50.296Z" }, { _id: "5c3812eac0acb663efqweqwe", _ability: "ability-id-2", type: "event", data: false, createdAt: "2019-01-11T03:52:10.827Z" }, { _id: "5c5b2c4eb8f9f4a6547asd", _ability: "ability-id-2", type: "action", createdAt: "2019-02-06T18:49:50.265Z" }, { _id: "5c5b2c4eb8f9f4a65473ewre", _ability: "ability-id-2", type: "event", createdAt: "2019-02-06T18:49:50.296Z" } ]; const getLogsSuccess = { url: "/api/logs", method: "GET", response: { status: 200, body: logs } }; const getLogsError = { url: "/api/logs", method: "GET", response: { status: 500, body: { statusCode: 500, error: "Internal server error", message: "Internal server error" } } }; const countLogsSuccess = { url: "/api/logs/stats", method: "GET", response: { status: 200, body: { total: 100 } } }; module.exports = { getLogsSuccess, getLogsError, countLogsSuccess };
function remove_duplicates(arr) { var obj = {}; var ret_arr = []; for (var i = 0; i < arr.length; i++) { obj[arr[i]] = true; } for (var key in obj) { ret_arr.push(key); } return ret_arr; } var intersect = function (nums1, nums2) { var result = nums1.filter(x => nums2.includes(x)); return [...new Set(result)]; }; var recipes_top10 = [240619, 236805, 65671, 8673, 8763, 72311, 112206, 17311, 12825, 46813 ]; var recipes_user = [229277, 231233, 8855, 30007, 59303 ]; var top10_list = []; db.getCollection('recipes_without_reviews').find({ id: { $in: recipes_top10 } }).forEach( function (item) { for (i = 0; i < recipes_top10.length; i++) { if (recipes_top10[i] == item.id) { top10_list[i] = item; } } }) var ing_list_id_top10 = []; top10_list.forEach(function (item) { item.ingredients.forEach(function (element) { ing_list_id_top10.push(element.id); }); }); var recipes_user_list = []; db.getCollection('recipes_without_reviews').find({ id: { $in: recipes_user } }).forEach( function (item) { for (i = 0; i < recipes_user.length; i++) { if (recipes_user[i] == item.id) { recipes_user_list[i] = item; } } }) print(recipes_user_list) var i = 1; var ing_list_id_userprofile = []; recipes_user_list.forEach(function (item) { item.ingredients.forEach(function (element) { ing_list_id_userprofile.push(element.id); }); }); // remove duplicate ingredients from top 10 and user list var no_ing_dupes_top10 = remove_duplicates(ing_list_id_top10) var no_ing_dupes_user = remove_duplicates(ing_list_id_userprofile) var ing_intersect = intersect(no_ing_dupes_top10, no_ing_dupes_user) var test = intersect(recipes_top10, recipes_user) //convert string id into ints var no_ing_dupes_top10 = no_ing_dupes_top10.map(Number) var no_ing_dupes_user = no_ing_dupes_user.map(Number) var ing_intersect = ing_intersect.map(Number) var remove_ing_id = [16421, 4342, 4397, 16406, 16157, 6307, 6494, 2496, 16238, 16317] //remove not wanted ingredients using the remove_ing_id array var no_ing_dupes_user = no_ing_dupes_user.filter(function (el) { return remove_ing_id.indexOf(el) < 0; }); var no_ing_dupes_top10 = no_ing_dupes_top10.filter(function (el) { return remove_ing_id.indexOf(el) < 0; }); var ing_intersect = ing_intersect.filter(function (el) { return remove_ing_id.indexOf(el) < 0; }); var result_list = []; db.getCollection('recipes_without_reviews').find({ id: { $in: recipes_top10 } }).forEach( function (item) { for (i = 0; i < recipes_top10.length; i++) { if (recipes_top10[i] == item.id) { result_list[i] = item; } } }) var recipe_position = 1; var count_intersect_ings = 0; result_list.forEach(function (item) { var ing_counter = 0; var count_intersct_ings_per_recipe = 0; print("##################################################################### \n"+ "+Pos:" + recipe_position++) print(item.name + ", ID: " + item.id + "\n") item.nutritions.forEach(function (element) { if (element.name == 'Fat' || element.name == 'Carbohydrates') { print(element.name + ": " + element.display_value); } }); print("\nIngredientss: ") item.ingredients.forEach(function (element) { ing_counter++; for (i = 0; i < ing_intersect.length; i++) { if (ing_intersect[i] == element.id) { print("ing_id: " + element.id + " ing_name: " + element.name) count_intersect_ings++; count_intersct_ings_per_recipe++; } } }); print("\ning_number: " + count_intersct_ings_per_recipe + "/" + ing_counter + " item_rating: " + item.rating + ", made_it_count: " + item.made_it_count + ", review_count: " + item.review_count + ", rating_count: " + item.rating_count + "\n"); }); var a = ing_list_id_top10.length / top10_list.length var b = ing_intersect.length / a print("Einzigartige Ueberschneidungszutaten TOP10 VS Userprofil: " + ing_intersect.length + "\n" + "Aufsummiert Ueberschneidungszutaten: " + count_intersect_ings + "\n" + "Einzigartige Zutaten TOP10: " + no_ing_dupes_top10.length + "\n" + "Durchschnitt Anzahl Zutaten Top10: " + ing_list_id_top10.length / top10_list.length + "\n" + "Einzigartige Zutaten User: " + no_ing_dupes_user.length + "\n" + "Ueberschneidungszutaten/Durch.Zutaten Top10: " + b.toFixed(2).toString().replace(".", ",") + "\n" ) print(ing_intersect.length + "\n" + count_intersect_ings + "\n" + no_ing_dupes_top10.length + "\n" + a.toString().replace(".", ",") + "\n" + no_ing_dupes_user.length + "\n" + b.toFixed(2).toString().replace(".", ",") + "\n" ) var result_list = []; db.getCollection('recipes_without_reviews').find({ id: { $in: recipes_user } }).forEach( function (item) { for (i = 0; i < recipes_user.length; i++) { if (recipes_user[i] == item.id) { result_list[i] = item; } } }) var recipe_position = 1; var count_intersect_ings = 0; result_list.forEach(function (item) { var ing_counter = 0; var count_intersct_ings_per_recipe = 0; print("##################################################################### \n"+ "+Pos:" + recipe_position++) print(item.name + ", ID: " + item.id + "\n") item.nutritions.forEach(function (element) { if (element.name == 'Fat' || element.name == 'Carbohydrates') { print(element.name + ": " + element.display_value); } }); print("\nIngredientss: ") item.ingredients.forEach(function (element) { ing_counter++; for (i = 0; i < ing_intersect.length; i++) { if (ing_intersect[i] == element.id) { print("ing_id: " + element.id + " ing_name: " + element.name) count_intersect_ings++; count_intersct_ings_per_recipe++; } } }); print("\ning_number: " + count_intersct_ings_per_recipe + "/" + ing_counter + " item_rating: " + item.rating + ", made_it_count: " + item.made_it_count + ", review_count: " + item.review_count + ", rating_count: " + item.rating_count + "\n"); });
import React from 'react'; import Link from 'next/link'; import UserImage from '../UserImage'; import FollowButton from '../../containers/FollowButton'; import { FollowList } from './style'; const FollowListLayout = ({ value }) => { return ( <FollowList> <div className="imageContainer"> <div className="sideProfileImage"> <UserImage image={value.Image} nickname={value.nickname} size={32} /> </div> </div> <div className="followListContent"> <div className="sideFollowList"> <Link href={{ pathname: '/profile', query: { nickname: value.nickname }, }} as={`/profile/${value.nickname}`} > <a>{value.nickname}</a> </Link> </div> </div> <div className="followButtonContainer"> <FollowButton userId={value.id} /> </div> </FollowList> ); }; export default FollowListLayout;
const postcss = require('postcss') const { parse } = require('css-box-shadow') module.exports = postcss.plugin('postcss-css-shadow', opts => root => { root.walkRules(rule => { let shadow = null rule.walkDecls('shadow', decl => { const { offsetX, offsetY, blurRadius, color } = parse(decl.value)[0] shadow = { color, blur: parseFloat(blurRadius), offset: [parseFloat(offsetX), parseFloat(offsetY)] } decl.remove() }) if (shadow) { rule.append({ prop: '__shadow', value: JSON.stringify(shadow) }) } }) })
'use strict'; (function() { function PopulateZones(domPulldown, result) { this.domPulldown = domPulldown; this.result = result; } PopulateZones.prototype = { execute: function(parts) { var zoneNames = []; for (var i = 0; i < this.result.zones.length; i++) { var currentZone = this.result.zones[i]; zoneNames.push(currentZone.zoneName); } zoneNames.sort(function(a, b) { return a.localeCompare(b, 'en'); }); for (var j = 0; j < zoneNames.length; j++) { var opt = document.createElement('option'); opt.textContent = zoneNames[j]; opt.value = zoneNames[j]; this.domPulldown.appendChild(opt); } parts.resolve(); } }; // load modules....instantiate... require(['src/TroubleMaker', 'src/WorkQueue'], function(TroubleMaker, WorkQueue) { var requireScriptNode = document.querySelector('#require'); var requireScriptUrl = requireScriptNode.src; console.log(requireScriptUrl); // for the demo...baseUrl and appPath (where BaseThread is located) are the same thing... // when you import into your codebase and change defines ....they might be different. TroubleMaker.setup({ fullPathToRequire: requireScriptUrl, baseUrl: '/', appPath: '/' }); var addButton = document.querySelector('#simple_execButton'); var param1 = document.querySelector('#simple_param1'); var param2 = document.querySelector('#simple_param2'); var paramOp = document.querySelector('#simple_paramop'); var resultDom = document.querySelector('#simple_result'); addButton.addEventListener('click', function(e) { var prom = TroubleMaker.start({ jobPath: 'jobs/SimpleJob', jobParams: { param1: parseInt(param1.value), param2: parseInt(param2.value), op: paramOp.value } }); prom.then(function(result) { resultDom.innerHTML = result.toString(); }).catch(function(e) { console.error(e); }); }); var reExecButton = document.querySelector('#recurse_execButton'); var reParamOne = document.querySelector('#recurse_param1'); var reresultDom = document.querySelector('#recurse_result'); reExecButton.addEventListener('click', function(e) { var prom = TroubleMaker.start({ jobPath: 'jobs/RecursiveJob', jobParams: { n: parseInt(reParamOne.value), } }); prom.then(function(result) { reresultDom.innerHTML = result.toString(); }).catch(function(e) { console.error(e); }); }); var wsApiParam = document.querySelector('#timez_apiparam'); var wsExecButton = document.querySelector('#ws_execButton'); var wsresultDom = document.querySelector('#ws_result'); wsExecButton.addEventListener('click', function(e) { var url = 'http://api.timezonedb.com/v2.1/get-time-zone?key=' + wsApiParam.value + '&format=json&by=zone&zone=America/New_York'; var prom = TroubleMaker.start({ jobPath: 'jobs/GenericWebServiceJob', jobParams: { url: url, verb: 'GET' } }); prom.then(function(result) { wsresultDom.innerHTML = JSON.stringify(result, null, ' '); // result.toString(); }).catch(function(e) { console.error(e); }); }); var multiApiParam = document.querySelector('#multi_apiparam'); var multiExecButton = document.querySelector('#multi_listButton'); var multiZoneList = document.querySelector('#multi_paramlist'); var multiGetButton = document.querySelector('#multi_getButton'); var multiGetResult = document.querySelector('#multi_result'); var infoButton = document.querySelector('#wsinfo_execButton'); var infoResult = document.querySelector('#wsinfo_result'); var infoStatus = document.querySelector('#wsinfo_status'); // wsinfo_status // perform list then perrform get on selected from list. multiExecButton.addEventListener('click', function(e) { var url = 'http://api.timezonedb.com/v2.1/list-time-zone?key=' + multiApiParam.value + '&format=json'; var prom = TroubleMaker.start({ jobPath: 'jobs/GenericWebServiceJob', jobParams: { url: url, verb: 'GET' } }); prom.then(function(result) { console.log(result); WorkQueue.queue(new PopulateZones(multiZoneList, result)); // var zoneNames = []; // for (var i = 0; i < result.zones.length; i++) { // var currentZone = result.zones[i]; // zoneNames.push(currentZone.zoneName); // } // zoneNames.sort(function(a, b) { // return a.localeCompare(b, 'en'); // }); // // for (var j = 0; j < zoneNames.length; j++) { // var opt = document.createElement('option'); // opt.textContent = zoneNames[j]; // opt.value = zoneNames[j]; // multiZoneList.appendChild(opt); // } //wsresultDom.innerHTML = JSON.stringify(result, null, ' '); // result.toString(); }).catch(function(e) { console.error(e); }); }); multiGetButton.addEventListener('click', function(e) { var url = 'http://api.timezonedb.com/v2.1/get-time-zone?key=' + multiApiParam.value + '&format=json&by=zone&zone=' + multiZoneList.value; var prom = TroubleMaker.start({ jobPath: 'jobs/GenericWebServiceJob', jobParams: { url: url, verb: 'GET' } }); prom.then(function(result) { wsresultDom.innerHTML = JSON.stringify(result, null, ' '); // result.toString(); }).catch(function(e) { console.error(e); }); }); infoButton.addEventListener('click', function(e) { var url = 'http://api.timezonedb.com/v2.1/get-time-zone?key=' + wsApiParam.value + '&format=json&by=zone&zone=America/New_York'; var prom = TroubleMaker.start({ jobPath: 'jobs/WebServiceJobWithInfo', jobParams: { url: url, verb: 'GET' }, infoCallback: function(data) { infoStatus.innerHTML = JSON.stringify(data, null, ' '); } }); prom.then(function(result) { infoResult.innerHTML = JSON.stringify(result, null, ' '); // result.toString(); }).catch(function(e) { console.error(e); }); }); }); })();
import request from '@/utils/request' export function addGrade(params) { return request({ url: '/api/grade/addGrade', method: 'post', data: { major: params.major, // 专业 account: params.account, // 账号 fullname: params.fullname, // 姓名 subject: params.subject, // 科目 grade: params.grade, // 成绩 semester: params.semester, // 学期 year: params.year, // 学年 l_id: params.l_id, // 学年 classes: params.classes // 班级 } }) } export function updateGrade(params) { return request({ url: '/api/grade/updateGrade', method: 'post', data: { _id: params._id, // 登录id subject: params.subject, // 登录id grade: params.grade // 成绩 } }) } export function getGrade(params) { return request({ url: '/api/grade/getGrade', method: 'post', data: { l_id: params.l_id // 登录id } }) } export function delGrade(params) { return request({ url: '/api/grade/delGrade', method: 'post', data: { _id: params._id // 成绩id } }) }
//effectively links super-evos with their base forms var base = [ {base: 261, evo: 1413}, {base: 367, evo: 1619}, {base: 416, evo: 1445}, {base: 459, evo: 1847}, {base: 530, evo: 1707}, {base: 562, evo: 1816}, {base: 649, evo: 2868}, {base: 669, evo: 1492}, {base: 718, evo: 1881}, {base: 720, evo: 1927}, {base: 748, evo: 1663}, {base: 870, evo: 2444}, {base: 935, evo: 2066}, {base: 1001, evo: 2195}, {base: 1035, evo: 1928}, {base: 1045, evo: 2001}, {base: 1085, evo: 2954}, {base: 1123, evo: 2357}, {base: 1192, evo: 1764}, {base: 1240, evo: 2034}, {base: 1268, evo: 3154}, {base: 1314, evo: 2578}, {base: 1362, evo: 1921}, {base: 1391, evo: 2035}, {base: 1404, evo: 1593}, {base: 1434, evo: 1880}, {base: 1473, evo: 2631}, {base: 1532, evo: 1543}, {base: 1571, evo: 2372}, {base: 1588, evo: 2245}, {base: 1610, evo: 2232}, {base: 1652, evo: 2373}, {base: 1698, evo: 2159}, {base: 1747, evo: 2434}, {base: 1751, evo: 1922}, {base: 1763, evo: 2784}, {base: 1794, evo: 2814}, {base: 1832, evo: 2138}, {base: 1869, evo: 2505}, {base: 1883, evo: 3018}, {base: 1935, evo: 2300}, {base: 1951, evo: 2830}, {base: 2074, evo: 2363}, {base: 2076, evo: 2588}, {base: 2113, evo: 2739}, {base: 2234, evo: 2500}, {base: 2251, evo: 2991}, {base: 2265, evo: 3048}, {base: 2302, evo: 3079}, {base: 2433, evo: 3448}, {base: 2477, evo: 3202}, {base: 2651, evo: 2681}, {base: 2686, evo: 2909}, {base: 2148, evo: 3211}, {base: 2338, evo: 3417}, {base: 2441, evo: 3393}, {base: 2465, evo: 3298}, {base: 2475, evo: 3240}, {base: 2774, evo: 3275}, {base: 2776, evo: 3350}, {base: 2837, evo: 3469}, {base: 3071, evo: 3369}, {base: 3429, evo: 3430}, ]; function updateStorage(key, value, save) { if (save) { localStorage.setItem(key, value); } else { localStorage.removeItem(key); } } function readStorageValue(key) { return localStorage.getItem(key); } function readAllStorage() { const nbItem = localStorage.length; const store = []; let i; let storeKey; for (i = 0; i < nbItem; i += 1) { storeKey = localStorage.key(i); store.push({ "key" : storeKey, "value" : readStorageValue(storeKey) }); } return store; } function updatePage() { //check local storage const store = readAllStorage(); //restore the selected class $.each(store, function(index, elem) { if(elem['value'] == 'rainbow') $("#" + elem.key).addClass("rainbow selected"); else if(elem['value'] == 'srainbow') $("#" + elem.key).addClass("srainbow selected"); else if(elem['value'] == 'hidden') $("#" + elem.key).addClass("disabled"); else if (elem['value'] == 'true'){ $('.base').toggleClass('hidden'); $('#hide-base').css('display', 'none'); $('#show-base').css('display', 'inline-block'); } else $("#" + elem.key).addClass("selected"); }); } function selectPage() { var isChecked = document.getElementById('switch').checked; var isChecked2 = document.getElementById('switch2').checked; if (isChecked) { $("#special .flair:not(.disabled)").addClass("rainbow"); $("#special .flair:not(.disabled)").removeClass("srainbow"); } else if (isChecked2) { $("#special .flair:not(.disabled)").addClass("srainbow"); $("#special .flair:not(.disabled)").removeClass("rainbow"); } else { //adds selected class to every icon $("#special .flair:not(.disabled)").addClass("selected"); $("#special .flair:not(.disabled)").removeClass("rainbow"); $("#special .flair:not(.disabled)").removeClass("srainbow"); } var className = document.getElementsByClassName('selected'); var idStore = new Array(); //loops every ID and stores key into array for(var i = 0; i < className.length; i++) { idStore.push({"key" : className[i].id, "value" : className[i].className}); } //add IDs from array to local storage for(var j=0; j<idStore.length; j++) { if(idStore[j]['value'].includes('srainbow')) { updateStorage(idStore[j]['key'], "srainbow", true); } else if(idStore[j]['value'].includes('rainbow')) { updateStorage(idStore[j]['key'], "rainbow", true); } else { updateStorage(idStore[j]['key'], null, true); } } } function resetPage() { //check local storage const store = readAllStorage(); //delete the selected class $.each(store, function(index, elem) { $("#" + elem.key).removeClass("selected"); $("#" + elem.key).removeClass("rainbow"); $("#" + elem.key).removeClass("srainbow"); $("#" + elem.key).removeClass("disabled"); }); //clears local storage localStorage.clear(); $('#show-hidden').html('Unhide All Removed Legends (' + $('.disabled').length + ')'); } //unique legend tracker function countLegends() { var disabled = $('.disabled'); var unique = $('#special .flair:not(.base)'); var selected = $('.selected'); var pairs = []; var baseArray = []; var disabledArray = []; //maps evos with base var baseMap = base.reduce(function(map, obj) { map[obj.evo] = obj.base; return map; }, {}); //pushes IDs to new array for(var i = 0; i < selected.length; i++) { pairs.push(selected[i].id); } for(var k = 0; k < base.length; k++) { baseArray.push(base[k]['base']); baseArray.push(base[k]['evo']); } //push IDs to disabled array to pass as argument later for(var j = 0; j < disabled.length; j++) { if(baseArray.includes(parseInt(disabled[j].id))) disabledArray.push(disabled[j].id); } //creates new set and returns size function countUnique(arg) { return new Set(arg.map (x => baseMap.hasOwnProperty(x)? baseMap[x].toString() : x)).size; } $('#counter').html("<span class='cl'>Unique Legends - </span>" + countUnique(pairs) + "/" + (countUnique(unique) - (disabled.length - countUnique(disabledArray)))); countLegends2(); } //total legend tracker function countLegends2() { var amount = $(".selected").length; var total = $("#special .flair").length; var disabled = $('.disabled').length; $('#counter2').html("<span class='cl'>Total Legends - </span>" + amount + "/" + (total-disabled)); countRainbows(); countSrainbows(); } //rainbow tracker function countRainbows() { var amount = $(".rainbow").length; var amount2 = $(".srainbow").length; var total = $("#special .flair").length; var disabled = $('.disabled').length; $('#rainbow').html("<span class='cl'>Rainbowed - </span>" + (amount + amount2) + "/" + (total-disabled)); } //super rainbow tracker function countSrainbows() { var amount = $(".srainbow").length; var total = $("#special .flair").length; var disabled = $('.disabled').length; $('#srainbow').html("<span class='cl'>Super Rainbowed - </span>" + amount + "/" + (total-disabled)); } //un-hides all hidden legends function showHidden() { var disabled = $(".disabled"); for(var i = 0; i < disabled.length; i++) { localStorage.removeItem(disabled[i].id); } $(".disabled").toggleClass("disabled"); $('#show-hidden').html('Unhide All Removed Legends (' + $('.disabled').length + ')'); } //unhides specific Legends function listHidden() { toggleModal2(); $(".modal-content2").empty(); $("#switch").prop("checked", false); $("#switch2").prop("checked", false); $("#hide-legends").prop("checked", false); var disabled = $(".disabled"); var box = $('.modal-content2'); //creates new images for hidden legends for(var i = 0; i < disabled.length; i++) { var flair = document.createElement('img'); flair.setAttribute('class', 'flair'); flair.setAttribute('name', disabled[i].id); flair.setAttribute('src', 'images/icons/'+disabled[i].id+'.png'); box.append(flair); } //unhide legends in checklist when clicked $(".modal-content2 img").mousedown(function(e) { const $obj = $(this); var id = $obj[0].name; $("#"+id).removeClass('disabled'); //removes from modal display $obj.hide(); //removes from local storage localStorage.removeItem(id); //updates counters $('#show-hidden').html('Unhide All Removed Legends (' + $('.disabled').length + ')'); countLegends(); }); } //toggles popup window function toggleModal() { let modal = document.querySelector(".modal") let closeBtn = document.querySelector(".close-btn") modal.style.display = "block" closeBtn.onclick = function(){ modal.style.display = "none" } window.onclick = function(e){ if(e.target == modal){ modal.style.display = "none" } } } //toggles 2nd popup window function toggleModal2() { let modal = document.querySelector(".modal2") let closeBtn = document.querySelector(".close-btn2") modal.style.display = "block" closeBtn.onclick = function(){ modal.style.display = "none" } window.onclick = function(e){ if(e.target == modal){ modal.style.display = "none" } } } //toggles 3rd popup window function toggleModal3() { let modal = document.querySelector(".modal3") let closeBtn = document.querySelector(".close-btn3") modal.style.display = "block" closeBtn.onclick = function(){ modal.style.display = "none" } window.onclick = function(e){ if(e.target == modal){ modal.style.display = "none" } } } function windowOnClick(event) { var modal = document.querySelector(".modal"); if (event.target === modal) { toggleModal(); } } //export image function function generateImage() { toggleModal(); $(".modal-content").empty(); domtoimage.toSvg($('.icon-container')[0]).then(function (dataUrl) { var img = new Image(); img.src = dataUrl; $(".modal-content").append(img); }); } //download feature function download() { domtoimage.toBlob($('.icon-container')[0]).then(function (blob) { window.saveAs(blob, 'checklist.jpg'); }); } //export localStorage function exportSelection() { $('#import-text').attr("style", "opacity: 0; z-index: -1;"); $('#apply-import').attr("style", "opacity: 0; z-index: -1;"); $('#copy-export').attr("style", "opacity: 1; z-index: 1;"); var raw = JSON.stringify(localStorage); container = document.getElementById("export-text"); container.setAttribute("style", "transform: translateY(0); opacity: 1; z-index: 1;"); container.value = LZString.compressToEncodedURIComponent(raw); } //copy exported data function copySelection() { container = document.getElementById("export-text"); container.select(); document.execCommand("copy"); $('#display-copied').fadeIn().delay(1000).fadeOut(); } //import button function toggleImport() { $('#export-text').attr("style", "opacity: 0; z-index: -1;"); $('#copy-export').attr("style", "opacity: 0; z-index: -1;"); $('#apply-import').attr("style", "opacity: 1; z-index: 1;"); $("#import-text").attr("style", "transform: translateY(0); opacity: 1; z-index: 1;"); } //apply imported data function importSelection() { var text = document.getElementById("import-text").value; plaintext = LZString.decompressFromEncodedURIComponent(text); //clears local storage localStorage.clear(); try { // Convert to a JSON object data = JSON.parse(plaintext); console.log(data); // Iterate over the JSON object and save to localstorage Object.keys(data).map(function(key, index) { var value = data[key]; localStorage.setItem(key, value); }); $('#imported').fadeIn().delay(1000).fadeOut(); } //if error catch { $('#undefined').fadeIn().delay(1000).fadeOut(); } //restore previous state updatePage(); //legend counter countLegends(); } jQuery(document).ready(function($) { //adds base class to pre-defined elements for(var v in base) { var item = document.getElementById(base[v]['base']); $(item).addClass('base'); } //restore previous state updatePage(); //legend counter countLegends(); //restores hidden legend counter upon page load - must be placed under updatePage() $('#show-hidden').html('Unhide All Removed Legends (' + $('.disabled').length + ')'); //makes sure only one toggle can be flipped at a time $("#switch").on("change", function(){ $("#hide-legends").prop("checked", false); $("#switch2").prop("checked", false); }); $("#switch2").on("change", function(){ $("#hide-legends").prop("checked", false); $("#switch").prop("checked", false); }); $("#hide-legends").on("change", function(){ $("#switch").prop("checked", false); $("#switch2").prop("checked", false); }); //main function for selecting icons $("#special img").mousedown(function(e) { var isChecked = document.getElementById('switch').checked; var isChecked2 = document.getElementById('hide-legends').checked; var isChecked3 = document.getElementById('switch2').checked; const $obj = $(this); //rainbow toggle must be checked if(isChecked) { if($obj.hasClass("selected")) { $obj.toggleClass('rainbow'); $obj.removeClass('srainbow'); } else { $obj.toggleClass('rainbow selected'); } //creates object if selected class is present const save = $obj.hasClass("selected"); var rainbow = $obj.hasClass("rainbow"); //updates the storage value accordingly if(rainbow) { updateStorage($obj.attr("id"), "rainbow", save); } else { updateStorage($obj.attr("id"), null, save); } countLegends(); } //hide legends toggle else if(isChecked2){ $obj.toggleClass("disabled"); $obj.removeClass("rainbow"); $obj.removeClass("srainbow"); $obj.removeClass("selected"); const save = $obj.hasClass("disabled"); updateStorage($obj.attr("id"), "hidden", save); countLegends(); //shows counter of hidden legends $('#show-hidden').html('Unhide All Removed Legends (' + $('.disabled').length + ')'); } //super rainbow toggle else if(isChecked3){ if($obj.hasClass("selected")) { $obj.toggleClass('srainbow'); $obj.removeClass('rainbow'); } else { $obj.toggleClass('srainbow selected'); } //creates object if selected class is present const save = $obj.hasClass("selected"); var srainbow = $obj.hasClass("srainbow"); //updates the storage value accordingly if(srainbow) { updateStorage($obj.attr("id"), "srainbow", save); } else { updateStorage($obj.attr("id"), null, save); } countLegends(); } //if not checked else { //toggles selected classes $obj.toggleClass("selected"); $obj.removeClass("rainbow"); $obj.removeClass("srainbow"); //creates object if selected class is present const save = $obj.hasClass("selected"); //update the key updateStorage($obj.attr("id"), null, save); countLegends(); } }); //select all button $("#select-all").on("click", function() { selectPage(); countLegends(); }); //clear button $("#select-none").on("click", function() { resetPage(); countLegends(); }); //unhide all legends $("#show-hidden").on("click", function() { showHidden(); countLegends(); }); //unhide specific legends $("#list-hidden").on("click", function() { listHidden(); countLegends(); }); //hides base forms of legends with super-evos $("#show-base").on("click", function() { $('.base').toggleClass('hidden'); $('#show-base').css('display', 'none'); $('#hide-base').css('display', 'inline-block'); updateStorage("evohidden", null, false); }); //shows base forms of legends with super-evos $("#hide-base").on("click", function() { $('.base').toggleClass('hidden'); $('#hide-base').css('display', 'none'); $('#show-base').css('display', 'inline-block'); updateStorage("evohidden", 'true', true); }); });
/// <reference types="cypress" /> // TODO: // verify displayed content matches the fetched data: notes, address, offices, links, projects, past proejcts // comments -- listing, creating, deleting // history (patches) // correct links to individual pages for offices, [past] projects // correct links for external links // what loading indicator looks like when results are 'in flight' // what happens when server returns no results or is down const findOne = 'mongo --quiet mongodb://127.0.0.1:4005/meteor --eval ' + "'db.contacts.findOne({}, {updatedAt:0, createdAt:0})' " + '> tests/cypress/fixtures/contact.json' const clear = Cypress.LocalStorage.clear const doNotClearLocalStorage = () => { } describe('Contact Single', () => { before(() => { Cypress.LocalStorage.clear = doNotClearLocalStorage cy.resetTriad() cy.stubAlgolia() cy.login() cy.exec(findOne) .its('code').should('eq', 0) cy.visit('/') }) beforeEach(() => { Cypress.Cookies.preserveOnce('meteor_login_token') cy.fixture('contact.json').as('contact') }) // NB: keyword `function` not arrow function to access `this.contact` it('should display contact name in header', function () { const contact = this.contact cy.visit(`/contacts/${contact._id}`) cy.get('h2.card-header').contains(contact.displayName) }) it('should display contact title', function () { const contact = this.contact cy.visit(`/contacts/${contact._id}`) cy.get('div.card-text > :nth-child(2)').contains(contact.title) }) it('should display office name', function () { const contact = this.contact cy.visit(`/contacts/${contact._id}`) if (contact.offices) { cy.get('.card-accent-offices >.card-header > a').should('have.text', contact.offices[0].officeName) } }) it('should have a working edit button', function () { const contact = this.contact cy.visit(`/contacts/${contact._id}`) cy.get('h2.card-header .float-right > .btn').should('have.text', 'Edit') cy.get('h2.card-header .float-right > .btn').click() cy.url().should('eq', `${Cypress.config().baseUrl}/contacts/${contact._id}/edit`) .then(() => { cy.get('a.form-cancel').click() }) }) after(() => { Cypress.LocalStorage.clear = clear }) })
/* @flow */ import { type Transaction } from '@neo-one/client-common'; const TRANSACTION_LENGTH = 'Transaction'.length; export default (type: $PropertyType<Transaction, 'type'>) => type.substring(0, type.length - TRANSACTION_LENGTH);
// effects: redux-saga 미들웨어가 수행하도록 작업을 명령하는 거라고 이해할 수 있다 // delay: 대기하라는 명령 // put: 특정 액션을 dispatch하라는 명령 // takeEvery: generator 코드를 실행해야할 때 takeEvery effect를 사용 // takeLatest: 가장 마지막으로 들어온 것만 처리 import { delay, put, takeEvery, takeLatest, takeLeading, } from 'redux-saga/effects'; // action const INCREASE = 'INCREASE'; const DECREASE = 'DECREASE'; const INCREASE_ASYNC = 'INCREASE_ASYNC'; const DECREASE_ASYNC = 'DECREASE_ASYNC'; // action creator export const increase = () => ({ type: INCREASE }); export const decrease = () => ({ type: DECREASE }); // ! 기존에 thunk로 처리했던 것을 순수 객체로 바꿔줌 export const increaseAsync = () => ({ type: INCREASE_ASYNC }); export const decreaseAsync = () => ({ type: DECREASE_ASYNC }); // ! saga function* increaseSaga() { // yield delay(1000); // put은 dispatch랑 비슷 // increase를 호출해서 increase action 객체를 만들고 그 액션을 디스패치하도록 Redux-saga 미들웨어에게 명령 yield put(increase()); } function* decreaseSaga() { yield put(decrease()); yield delay(5000); yield put(increase()); } // rootreducer를 만드는 것처럼 rootsaga를 만들어야 하기 때문에 export해준다 export function* counterSaga() { // INCREASE_ASYNC action이 dispatch 되면 increaseSaga()의 코드를 실행해준다 yield takeEvery(INCREASE_ASYNC, increaseSaga); // delay(1000)에 의해서 1초를 기다리고 있는 도중에 새로운 것이 들어온다면 기존 것은 무시하고 가장 마지막으로 들어온 것만 처리하겠다 yield takeLatest(DECREASE_ASYNC, decreaseSaga); // 가장 먼저 들어온걸 처리하고 끝날때까지 기다렸다가 끝나고나면 다시 다른 걸 받는다 // yield takeLeading(DECREASE_ASYNC, decreaseSaga); } // ! thunk // ! 1.아래의 코드는 정확하게 얘기하면 전체가 thunk함수는 아니다 // ! getState가 필요할 경우에는 불러오지만 필요없으면 생략해도 된다 // ! 정확히는 2,3번으로 나누어 2번이 thunk함수이다 // export const increaseAsync = () => (dispatch, getState) => { // setTimeout(() => { // dispatch(increase()); // }, 1000); // }; // export const decreaseAsync = () => (dispatch, getState) => { // setTimeout(() => { // dispatch(decrease()); // }, 1000); // }; // // ! 2. thunk 함수 // // thunk function // const increaseThunk = (dispatch, getState) => { // setTimeout(() => { // dispatch(increase()); // }, 1000); // }; // const decreaseThunk = (dispatch, getState) => { // setTimeout(() => { // dispatch(decrease()); // }, 1000); // }; // // ! 3. thunk creator // // thunk creator // export const increaseAsync = () => increaseThunk; // export const decreaseAsync = () => decreaseThunk; // initial state const initialState = 0; // reducer const counter = (state = initialState, action) => { switch (action.type) { case INCREASE: return state + 1; case DECREASE: return state - 1; default: return state; } }; export default counter;
const ist = require('ist') const { EditorState } = require('prosemirror-state') const { table, tr, c11, c, doc } = require('./build') const { columnResizing, columnResizingPluginKey } = require('../dist') const columnResizingPlugin = columnResizing() describe('ColumnResizing', () => { // 无跨行跨列表格 3 * 3 // | 2 | 7 | 12 | // ---------------------- // | 19 | 24 | 29 | // ---------------------- // | 36 | 41 | 46 | const t = doc( table( tr(/* 2 */ c11, /* 7 */ c11, /* 12 */ c11), tr(/* 19 */ c11, /* 24 */ c11, /* 29 */ c11), tr(/* 36 */ c11, /* 41 */ c11, /* 46 */ c11) ) ) // 跨行表格 4 * 3 // ----------------------------- // | | 7 | 12 | 17 | // 2 ---------------------- // | | 24 | | 34 | // --------------- 29 -------- // | 41 | 46 | | 51 | // ----------------------------- const t1 = doc( table( tr(/* 2 */ c(1, 2), /* 7 */ c11, /* 12 */ c11, /* 17 */ c11), tr(/* 24 */ c(1, 1), /* 29 */ c(1, 2), /* 34 */ c11), tr(/* 41 */ c11, /* 46 */ c11, /* 51 */ c11) ) ) // 跨列表格 3 * 4 // ---------------------- // | 2 | 7 | // ---------------------- // | 14 | 19 | 24 | // ---------------------- // | 31 | 36 | // ---------------------- // | 43 | // ---------------------- const t2 = doc( table( tr(/* 2 */ c(2, 1), /* 7 */ c11), tr(/* 14 */ c11, /* 19 */ c11, /* 24 */ c11), tr(/* 31 */ c11, /* 36 */ c(2, 1)), tr(/* 43 */ c(3, 1)) ) ) // 跨行跨列表格 4 * 4 // ----------------------------- // | | 7 | 12 | 17 | // 2 ---------------------- // | | 24 | | // --------------- 29 // | 36 | | // ----------------------------- // | 43 | 48 | 53 | // ----------------------------- const t3 = doc( table( tr(/* 2 */ c(1, 2), /* 7 */ c11, /* 12 */ c11, /* 17 */ c11), tr(/* 24 */ c(1, 1), /* 29 */ c(2, 2)), tr(/* 36 */ c(2, 1)), tr(/* 43 */ c11, /* 48 */ c(2, 1), /* 53 */ c11) ) ) // 初始化 state function initState(doc) { return EditorState.create({ doc, plugins: [columnResizingPlugin], }) } // 更新 state function updateState( state, setHandle, isTableLeftBorder = false, isTableRightBorder = false ) { return state.apply( state.tr.setMeta(columnResizingPluginKey, { setHandle, isTableLeftBorder, isTableRightBorder, }) ) } // 获取 decorations pos 信息 function getDecorations(state) { return columnResizingPlugin.props .decorations(state) .find() .map((i) => i.from) } // 测试函数 function test(a, b) { ist(a.join(', '), b.join(', ')) } it('测试无跨行跨列表格', () => { const state = initState(t) // 表格左侧边框 const state1 = updateState(state, 2, true, false) test(getDecorations(state1), [6, 23, 40]) // 中间单元格 const state2 = updateState(state, 2) test(getDecorations(state2), [6, 23, 40]) const state3 = updateState(state, 7) test(getDecorations(state3), [11, 28, 45]) // 表格右侧边框 const state4 = updateState(state, 12, false, true) test(getDecorations(state4), [16, 33, 50]) }) it('测试跨行表格', () => { const state = initState(t1) // 第一行 // 表格左侧边框 const state1 = updateState(state, 2, true, false) test(getDecorations(state1), [6, 6, 45]) // 中间单元格 const state2 = updateState(state, 2) test(getDecorations(state2), [6, 6, 45]) const state3 = updateState(state, 7) test(getDecorations(state3), [11, 28, 50]) const state4 = updateState(state, 12) test(getDecorations(state4), [16, 33, 33]) // 表格右侧边框 const state5 = updateState(state, 17, false, true) test(getDecorations(state5), [21, 38, 55]) // 第二行 // 中间单元格 const state6 = updateState(state, 24) test(getDecorations(state6), [11, 28, 50]) const state7 = updateState(state, 29) test(getDecorations(state7), [16, 33, 33]) // 表格右侧边框 const state8 = updateState(state, 34, false, true) test(getDecorations(state8), [21, 38, 55]) // 第三行 // 表格左侧边框 const state9 = updateState(state, 41, true, false) test(getDecorations(state9), [6, 6, 45]) // 中间单元格 const state10 = updateState(state, 41) test(getDecorations(state10), [6, 6, 45]) const state11 = updateState(state, 46) test(getDecorations(state11), [11, 28, 50]) // 表格右侧边框 const state12 = updateState(state, 51, false, true) test(getDecorations(state12), [21, 38, 55]) }) it('测试跨列表格', () => { const state = initState(t2) // 第一行 // 表格左侧边框 const state1 = updateState(state, 2, true, false) test(getDecorations(state1), [6, 18, 35, 47]) // 中间单元格 const state2 = updateState(state, 2) test(getDecorations(state2), [6, 23]) // 表格右侧边框 const state3 = updateState(state, 7, false, true) test(getDecorations(state3), [11, 28, 40, 47]) // 第二行 // 表格左侧边框 const state4 = updateState(state, 14, true, false) // 中间单元格 test(getDecorations(state4), [6, 18, 35, 47]) const state5 = updateState(state, 14) test(getDecorations(state5), [18, 35]) const state6 = updateState(state, 19) test(getDecorations(state6), [6, 23]) // 表格右侧边框 const state7 = updateState(state, 24, false, true) test(getDecorations(state7), [11, 28, 40, 47]) // 第三行 // 表格左侧边框 const state8 = updateState(state, 31, true, false) test(getDecorations(state8), [6, 18, 35, 47]) // 中间单元格 const state9 = updateState(state, 31) test(getDecorations(state9), [18, 35]) // 表格右侧边框 const state10 = updateState(state, 36, false, true) test(getDecorations(state10), [11, 28, 40, 47]) // 第四行 // 表格左侧边框 const state11 = updateState(state, 43, true, false) test(getDecorations(state11), [6, 18, 35, 47]) // 表格右侧边框 const state12 = updateState(state, 43, false, true) test(getDecorations(state12), [11, 28, 40, 47]) }) it('测试跨行跨列表格', () => { const state = initState(t3) // 第一行 // 表格左侧边框 const state1 = updateState(state, 2, true, false) test(getDecorations(state1), [6, 6, 40, 47]) // 中间单元格 const state2 = updateState(state, 2) test(getDecorations(state2), [6, 6, 47]) const state3 = updateState(state, 7) test(getDecorations(state3), [11, 28, 40]) const state4 = updateState(state, 12) test(getDecorations(state4), [16, 52]) // 表格右侧边框 const state5 = updateState(state, 17, false, true) test(getDecorations(state5), [21, 33, 33, 57]) // 第二行 // 中间单元格 const state6 = updateState(state, 24) test(getDecorations(state6), [11, 28, 40]) // 表格右侧边框 const state7 = updateState(state, 29, false, true) test(getDecorations(state7), [21, 33, 33, 57]) // 第三行 // 表格左侧边框 const state8 = updateState(state, 36, true, false) // 中间单元格 test(getDecorations(state8), [6, 6, 40, 47]) const state9 = updateState(state, 36) test(getDecorations(state9), [11, 28, 40]) // 第四行 // 表格左侧边框 const state10 = updateState(state, 43, true, false) test(getDecorations(state10), [6, 6, 40, 47]) // 中间单元格 const state11 = updateState(state, 43) test(getDecorations(state11), [6, 6, 47]) const state12 = updateState(state, 48) test(getDecorations(state12), [16, 52]) // 表格右侧边框 const state13 = updateState(state, 53, false, true) test(getDecorations(state13), [21, 33, 33, 57]) }) })
version https://git-lfs.github.com/spec/v1 oid sha256:0f4b9f79a2084c4accd94d7b346a064e6552349622b4ee7451f875f915a1bd7d size 1821
'use strict'; const pkg = require('../../package'); const showUsage = (error = false) => { const usage = ` Usage: npx @mryhryki/markdown-preview [options] markdown-preview [options] Options: -f,--file [relative_file_path] Default: README.md -t,--template [template_name] Default: default -p,--port [port_number] Default: 34567 -v,--version -h,--help `; console.log(usage); process.exit(error ? 1 : 0); }; const showVersion = () => { console.log(pkg.version); process.exit(0); }; module.exports = { showUsage, showVersion, };
import { dolls } from 'girlsfrontline-core'; import Doll from 'girlsfrontline-core/lib/doll'; import gfextradata from 'girlsfrontline-extra-data'; import dollRank from './data/dollRank.json'; const { alias: { doll: dollAlias } } = gfextradata({ locale: 'ko' }); const buildData = (doll) => { const { id, skins } = doll; const rank = (parseInt((Number(id) / 1000), 10) === 1) ? 1 : doll.rank; return Object.assign( doll, { skins: skins.filter(skin => parseInt(skin.id / 1000, 10) !== 5), // 5000 번대 스킨 쓸모없는 것 같음 rank: dollRank[rank], alias: dollAlias[doll.id] || [], }, ); }; const dollMap = new Map(dolls.map(e => [e.id, e])); const getAll = () => { const dollDict = {}; dollMap.forEach((e, id) => { dollDict[id] = buildData(new Doll(e.toJSON())); }); return dollDict; }; const getNewById = (id) => { const doll = dollMap.get(id); if (!doll) { return null; } return buildData(new Doll(doll.toJSON())); }; export default { getAll, getNewById };
/* $This file is distributed under the terms of the license in LICENSE$ */ var EntityTablesWidget = Class.extend({ init: function(sciMapWidget) { this.sciMapWidget = sciMapWidget; this.keyToDataTable = {}; this.container = $('<div>'); $("#subEntityTableArea").append(this.container); $("#subEntityTableArea").show(); }, initView: function(key) { this.container.show(); }, cleanView: function(key) { this.container.hide(); }, loadJsonData: function(data) { }, loadEntity: function(data, color) { var key = data.label; var dataTable = this.getDataTable(key); if (dataTable == null) { dataTable = this._createDataTable(key, data, color); } dataTable.initView(); }, unloadEntity: function(key) { this._removeDataTable(key); }, getDataTable: function(key) { return this.keyToDataTable[key]; }, _removeDataTable: function(key) { var dataTable = this.getDataTable(key); if (dataTable) { dataTable.cleanView(); delete this.keyToDataTable[key]; } }, _createDataTable: function(key, data, color) { dataTable = new SimpleDataTableWidget({ sciMapWidget: this.sciMapWidget, container: this.container }); data.color = color; dataTable.loadJsonData(data); this.keyToDataTable[key] = dataTable; return dataTable; } });
/*! Bootstrap integration for DataTables' Buttons ©2016 SpryMedia Ltd - datatables.net/license */ (function(b){"function"===typeof define&&define.amd?define(["jquery","datatables.net-bs5","datatables.net-buttons"],function(a){return b(a,window,document)}):"object"===typeof exports?module.exports=function(a,c){a||(a=window);if(!c||!c.fn.dataTable)c=require("datatables.net-bs5")(a,c).$;c.fn.dataTable.Buttons||require("datatables.net-buttons")(a,c);return b(c,a,a.document)}:b(jQuery,window,document)})(function(b){var a=b.fn.dataTable;b.extend(!0,a.Buttons.defaults,{dom:{container:{className:"dt-buttons btn-group flex-wrap"}, button:{className:"btn btn-secondary"},collection:{tag:"div",className:"dropdown-menu",button:{tag:"a",className:"dt-button dropdown-item",active:"active",disabled:"disabled"}}},buttonCreated:function(a,d){return a.buttons?b('<div class="btn-group"/>').append(d):d}});a.ext.buttons.collection.className+=" dropdown-toggle";a.ext.buttons.collection.rightAlignClassName="dropdown-menu-right";return a.Buttons});
/* eslint-disable import/no-extraneous-dependencies, no-await-in-loop */ /* eslint-disable no-restricted-syntax, jest/no-export, jest/no-conditional-expect */ // import 'babel-polyfill'; const { toMatchImageSnapshot } = require('jest-image-snapshot'); const { joinObjects, writeImage, getReplacementsFolder } = require('./tools'); // const playwright = require('playwright'); // import { getReplacementsFolder } from '../../../tests/browser/common'; const sitePath = process.env.TIG_ADDRESS || 'http://host.docker.internal:5003'; expect.extend({ toMatchImageSnapshot }); function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } page.on('console', async (msg) => { const msgType = msg.type(); const args = await Promise.all(msg.args().map(jsHandle => jsHandle.jsonValue())); if (msgType === 'error') { // eslint-disable-next-line no-console console.log(...args); } }); async function removeRatings(p) { await p.evaluate(() => new Promise((resolve) => { (document.querySelectorAll( '.rating__container, .approach__links_table__small_screen__value', ) || []).forEach( (el) => { // eslint-disable-next-line no-param-reassign el.style.visibility = 'hidden'; }, ); resolve(); })); } async function removeTopicVariables(p) { await p.evaluate(() => new Promise((resolve) => { (document.querySelectorAll( '.topic__variable', ) || []).forEach( (el) => { // eslint-disable-next-line no-param-reassign el.style.display = 'none'; }, ); resolve(); })); } // eslint-disable no-await-in-loop export default function singlePageTester(optionsOrScenario, ...scenarios) { const fullPath = module.parent.filename.split('/').slice(0, -1).join('/'); const defEndpoint = fullPath.split('/').slice(3, -1).join('/'); let scenariosToUse = scenarios; const replacementsPath = getReplacementsFolder(fullPath); const defaultOptions = { viewHeight: 'auto', height: 'auto', includeQRs: false, prePath: '', threshold: 50, element: '#topic__content', prefix: '', endpoint: defEndpoint, }; let optionsToUse = defaultOptions; if (!('width' in optionsOrScenario)) { optionsToUse = joinObjects({}, defaultOptions, optionsOrScenario); } else { scenariosToUse = [optionsOrScenario, ...scenarios]; } const allTests = []; scenariosToUse.forEach((scenarioIn) => { const scenario = joinObjects({}, optionsToUse, scenarioIn); const scenarioOptions = { element: scenario.element, prefix: scenario.prefix, endpoint: scenario.endpoint, threshold: scenario.threshold, prePath: scenario.prePath, }; allTests.push([ scenario.width, scenario.height, scenario.viewHeight, scenario.includeQRs, scenario.endpoint, scenarioOptions, ]); }); // eslint-disable-next-line jest/valid-describe describe(`${fullPath}`, () => { test.each(allTests)( 'width: %i height: %p, viewHeight: %p, QRs: %p, endpoint: %s', async (width, height, viewHeight, includeQRs, endpoint, options) => { let errorFlag = false; jest.setTimeout(120000); const fullpath = `${sitePath}${options.prePath}/${options.endpoint}`; await page.goto(fullpath, { waitUntil: 'load' }); await sleep(500); // Open all hints on a page let hints = await page.$$('.simple__hint_label'); for (const hint of hints) { await hint.click(); } hints = await page.$$('.simple__hint_label_low'); for (const hint of hints) { await hint.click(); } await page.evaluate(() => { window.scrollTo(0, 0); }); // const contentBox = await (await page.$('#topic__content')) // .boundingBox(); // const pageBox = await (await page.$('body')) // .boundingBox(); // console.log(pageBox) // const bb = await (await page.$('#topic__content')).boundingBox(); // console.log(bb) if (viewHeight === 'auto') { await page.setViewportSize({ width, height: 1000 }); const pageBox = await (await page.$('body')) .boundingBox(); // const bb = await (await page.$('#topic__content')).boundingBox(); await page.setViewportSize({ width, height: Math.floor(pageBox.height) }); } else { await page.setViewportSize({ width, height: viewHeight }); } // await page.evaluate((y) => { // window.scrollTo(0, y); // }, Math.floor(pageBox.y)); await removeRatings(page); await removeTopicVariables(page); let clippingBox = await (await page.$(options.element)).boundingBox(); if (height !== 'auto') { clippingBox.height = height; } let image = await page.screenshot({ clip: clippingBox }); let fileName = `${options.prefix}${width}-${height}`; // expect(image).toMatchImageSnapshot({ // failureThreshold: options.threshold, // customSnapshotIdentifier: fileName, // }); try { expect(image).toMatchImageSnapshot({ failureThreshold: options.threshold, customSnapshotIdentifier: fileName, }); } catch (error) { // eslint-disable-next-line console.log(error); writeImage(image, `${replacementsPath}/${fileName}-snap.png`); errorFlag = true; } if (includeQRs) { // Find all links on page that go to QR popups // eslint-disable-next-line no-loop-func const qrLinks = await page.$$('.topic__qr_action_word'); let index = 0; // eslint-disable-next-line no-restricted-syntax for (const link of qrLinks) { await link.click(); await page.mouse.move(0, 0); await page.evaluate(() => { window.scrollTo(0, 0); }); await sleep(1000); clippingBox = await (await page.$('#id_topic__qr__static_container')).boundingBox(); if (clippingBox == null) { clippingBox = await (await page.$('#id_topic__qr__pres_container')).boundingBox(); } // const linkBox = await link.boundingBox(); // await page.evaluate((y) => { // window.scrollTo(0, y); // }, linkBox.y); image = await page.screenshot({ clip: clippingBox }); fileName = `${options.prefix}${width}-${height}-QR-${index}`; // expect(image).toMatchImageSnapshot({ // failureThreshold: options.threshold, // customSnapshotIdentifier: fileName, // }); try { expect(image).toMatchImageSnapshot({ failureThreshold: options.threshold, customSnapshotIdentifier: fileName, }); } catch (error) { // eslint-disable-next-line console.log(error); writeImage(image, `${replacementsPath}/${fileName}-snap.png`); errorFlag = true; } index += 1; const closeButtons = await page.$$('.topic__qr__title_close'); // eslint-disable-next-line no-restricted-syntax for (const closeButton of closeButtons) { const box = await closeButton.boundingBox(); if (box != null && box.x > 0) { await closeButton.click(); break; } } } } if (errorFlag) { expect(true).toBe(false); } }, 60000, ); }); }
module.exports = function (match) { match('', 'home#index'); match('repos', 'repos#index'); match('repos/:owner/:name', 'repos#show'); match('users' , 'users#index'); match('users/:login', 'users#show'); };
(window.webpackJsonp=window.webpackJsonp||[]).push([[132],{271:function(e){e.exports=JSON.parse('{"docsSidebars":{"docs":[{"collapsed":true,"type":"category","label":"Introduction","items":[{"type":"link","label":"Introduction","href":"/kratos/docs/next/"},{"type":"link","label":"Quickstart","href":"/kratos/docs/next/quickstart"},{"type":"link","label":"Installation","href":"/kratos/docs/next/install"}]},{"collapsed":true,"type":"category","label":"Concepts","items":[{"type":"link","label":"Overview","href":"/kratos/docs/next/concepts/index"},{"type":"link","label":"User Interface","href":"/kratos/docs/next/concepts/ui-user-interface"},{"type":"link","label":"Identity Data Model","href":"/kratos/docs/next/concepts/identity-user-model"},{"collapsed":true,"label":"Identity Credentials","type":"category","items":[{"type":"link","label":"Overview","href":"/kratos/docs/next/concepts/credentials"},{"type":"link","label":"Username / Email & Password","href":"/kratos/docs/next/concepts/credentials/username-email-password"},{"type":"link","label":"Social Sign In, OpenID Connect, and OAuth2","href":"/kratos/docs/next/concepts/credentials/openid-connect-oidc-oauth2"}]},{"type":"link","label":"HTTP Redirection Configuration","href":"/kratos/docs/next/concepts/browser-redirect-flow-completion"},{"type":"link","label":"Out-of-band communication via E-Mail and SMS","href":"/kratos/docs/next/concepts/email-sms"},{"type":"link","label":"REST API Design","href":"/kratos/docs/next/concepts/rest-api"},{"type":"link","label":"Federation","href":"/kratos/docs/next/concepts/federation"},{"type":"link","label":"Threat Models and Security Profiles","href":"/kratos/docs/next/concepts/security"}]},{"collapsed":true,"type":"category","label":"Self Service","items":[{"type":"link","label":"Before you start reading","href":"/kratos/docs/next/self-service"},{"collapsed":true,"type":"category","label":"User Login and User Registration","items":[{"type":"link","label":"Overview","href":"/kratos/docs/next/self-service/flows/user-login-user-registration"},{"type":"link","label":"Username or Email and Password","href":"/kratos/docs/next/self-service/flows/user-login-user-registration/username-email-password"},{"type":"link","label":"Social Sign In with OpenID Connect and OAuth2","href":"/kratos/docs/next/self-service/flows/user-login-user-registration/openid-connect-social-sign-in-oauth2"}]},{"collapsed":true,"type":"category","label":"User Settings","items":[{"type":"link","label":"Overview","href":"/kratos/docs/next/self-service/flows/user-settings"},{"type":"link","label":"User Profile Management","href":"/kratos/docs/next/self-service/flows/user-settings/user-profile-management"},{"type":"link","label":"Change Password","href":"/kratos/docs/next/self-service/flows/user-settings/change-password"},{"type":"link","label":"Link and Unlink OpenID Connect and OAuth2 Connections","href":"/kratos/docs/next/self-service/flows/user-settings/link-unlink-openid-connect-oauth2"}]},{"collapsed":true,"type":"category","label":"Account Recovery","items":[{"type":"link","label":"Account Recovery","href":"/kratos/docs/next/self-service/flows/account-recovery"},{"type":"link","label":"Recovery Link and Password Reset","href":"/kratos/docs/next/self-service/flows/account-recovery/password-reset-recovery-link"}]},{"type":"link","label":"User Logout","href":"/kratos/docs/next/self-service/flows/user-logout"},{"type":"link","label":"User-Facing Errors","href":"/kratos/docs/next/self-service/flows/user-facing-errors"},{"type":"link","label":"Email and Phone Verification and Account Activation","href":"/kratos/docs/next/self-service/flows/verify-email-account-activation"},{"type":"link","label":"MFA / 2FA","href":"/kratos/docs/next/self-service/flows/2fa-mfa-multi-factor-authentication"},{"type":"link","label":"Hooks","href":"/kratos/docs/next/self-service/hooks/index"}]},{"collapsed":true,"type":"category","label":"Guides","items":[{"type":"link","label":"Sign in with GitHub, Google, Facebook, LinkedIn, Microsoft ...","href":"/kratos/docs/next/guides/sign-in-with-github-google-facebook-linkedin"},{"type":"link","label":"Zero Trust with IAP Proxy","href":"/kratos/docs/next/guides/zero-trust-iap-proxy-identity-access-proxy"},{"type":"link","label":"Setting up Account Recovery and Password Reset","href":"/kratos/docs/next/guides/account-recovery-password-reset"},{"type":"link","label":"Setting up Account Activation and E-Mail Verification","href":"/kratos/docs/next/guides/account-activation-email-verification"},{"type":"link","label":"Multitenancy","href":"/kratos/docs/next/guides/multi-tenancy-multitenant"},{"type":"link","label":"Configuring Cookies","href":"/kratos/docs/next/guides/configuring-cookies"},{"type":"link","label":"Secret and Key Rotation","href":"/kratos/docs/next/guides/secret-key-rotation"},{"type":"link","label":"High Availability","href":"/kratos/docs/next/guides/high-availability-ha"},{"type":"link","label":"Docker Images","href":"/kratos/docs/next/guides/docker"}]},{"collapsed":true,"type":"category","label":"Reference","items":[{"type":"link","label":"Configuration","href":"/kratos/docs/next/reference/configuration"},{"type":"link","label":"JSON Schema and JSON Paths","href":"/kratos/docs/next/reference/json-schema-json-paths"},{"type":"link","label":"HTML Form Parser","href":"/kratos/docs/next/reference/html-forms"},{"type":"link","label":"REST API","href":"/kratos/docs/next/reference/api"}]},{"collapsed":true,"type":"category","label":"Debug & Help","items":[{"type":"link","label":"Common Cookie and CSRF Pitfalls","href":"/kratos/docs/next/debug/csrf"}]},{"collapsed":true,"type":"category","label":"SDKs","items":[{"type":"link","label":"Overview","href":"/kratos/docs/next/sdk"}]},{"collapsed":true,"type":"category","label":"Further Reading","items":[{"type":"link","label":"Comparison","href":"/kratos/docs/next/further-reading/comparison"}]},{"collapsed":true,"type":"category","label":"ORY Hydra","items":[{"type":"link","label":"Home","href":"https://www.ory.sh/hydra"},{"type":"link","label":"Docs","href":"https://www.ory.sh/hydra/docs"},{"type":"link","label":"GitHub","href":"https://github.com/ory/hydra"}]},{"collapsed":true,"type":"category","label":"ORY Oathkeeper","items":[{"type":"link","label":"Home","href":"https://www.ory.sh/oathkeeper"},{"type":"link","label":"Docs","href":"https://www.ory.sh/oathkeeper/docs"},{"type":"link","label":"GitHub","href":"https://github.com/ory/oathkeeper"}]},{"collapsed":true,"type":"category","label":"ORY Keto","items":[{"type":"link","label":"Home","href":"https://www.ory.sh/keto"},{"type":"link","label":"Docs","href":"https://www.ory.sh/keto/docs"},{"type":"link","label":"GitHub","href":"https://github.com/ory/keto"}]}]},"permalinkToSidebar":{"/kratos/docs/next/":"docs","/kratos/docs/next/concepts/browser-redirect-flow-completion":"docs","/kratos/docs/next/concepts/credentials":"docs","/kratos/docs/next/concepts/credentials/openid-connect-oidc-oauth2":"docs","/kratos/docs/next/concepts/credentials/username-email-password":"docs","/kratos/docs/next/concepts/email-sms":"docs","/kratos/docs/next/concepts/federation":"docs","/kratos/docs/next/concepts/identity-user-model":"docs","/kratos/docs/next/concepts/index":"docs","/kratos/docs/next/concepts/rest-api":"docs","/kratos/docs/next/concepts/security":"docs","/kratos/docs/next/concepts/ui-user-interface":"docs","/kratos/docs/next/debug/csrf":"docs","/kratos/docs/next/further-reading/comparison":"docs","/kratos/docs/next/guides/account-activation-email-verification":"docs","/kratos/docs/next/guides/account-recovery-password-reset":"docs","/kratos/docs/next/guides/configuring-cookies":"docs","/kratos/docs/next/guides/docker":"docs","/kratos/docs/next/guides/high-availability-ha":"docs","/kratos/docs/next/guides/multi-tenancy-multitenant":"docs","/kratos/docs/next/guides/secret-key-rotation":"docs","/kratos/docs/next/guides/sign-in-with-github-google-facebook-linkedin":"docs","/kratos/docs/next/guides/zero-trust-iap-proxy-identity-access-proxy":"docs","/kratos/docs/next/install":"docs","/kratos/docs/next/quickstart":"docs","/kratos/docs/next/reference/api":"docs","/kratos/docs/next/reference/configuration":"docs","/kratos/docs/next/reference/html-forms":"docs","/kratos/docs/next/reference/json-schema-json-paths":"docs","/kratos/docs/next/sdk":"docs","/kratos/docs/next/self-service":"docs","/kratos/docs/next/self-service/flows/2fa-mfa-multi-factor-authentication":"docs","/kratos/docs/next/self-service/flows/account-recovery":"docs","/kratos/docs/next/self-service/flows/account-recovery/password-reset-recovery-link":"docs","/kratos/docs/next/self-service/flows/user-facing-errors":"docs","/kratos/docs/next/self-service/flows/user-login-user-registration":"docs","/kratos/docs/next/self-service/flows/user-login-user-registration/openid-connect-social-sign-in-oauth2":"docs","/kratos/docs/next/self-service/flows/user-login-user-registration/username-email-password":"docs","/kratos/docs/next/self-service/flows/user-logout":"docs","/kratos/docs/next/self-service/flows/user-settings":"docs","/kratos/docs/next/self-service/flows/user-settings/change-password":"docs","/kratos/docs/next/self-service/flows/user-settings/link-unlink-openid-connect-oauth2":"docs","/kratos/docs/next/self-service/flows/user-settings/user-profile-management":"docs","/kratos/docs/next/self-service/flows/verify-email-account-activation":"docs","/kratos/docs/next/self-service/hooks/index":"docs"},"version":"next"}')}}]);
import { REG_START, REG_SUCCESS, REG_FAILED, LOGIN_START, LOGIN_SUCCESS, LOGIN_FAILED } from "../actions" const initialUser = {username: "", password: ""}; export const reducer = (state = initialUser, action) => { switch (action.type) { case REG_START: return{ ...state, inProgress: true, error: "" } case REG_SUCCESS: return{ ...state, inProgress: false, register: action.payload, error: "", username: action.payload } case REG_FAILED: return{ ...state, inProgress: false, error: action.payload } case LOGIN_START: return{ ...state, inProgress: true, success: false } case LOGIN_SUCCESS: return{ ...state, inProgress: false, success: true, username: action.payload, password: action.payload } case LOGIN_FAILED: return{ ...state, inProgress: false, success: false, username: "", password: "" } default: return state; } }
module.exports = { extends: ['standard', 'prettier', 'prettier/standard'], env: { es6: true, node: true }, parserOptions: { ecmaVersion: 6 }, plugins: ['prettier'], rules: { 'prettier/prettier': [ 'error', { singleQuote: true, semi: false } ] } }
mycallback( {"CONTRIBUTOR OCCUPATION": "VP MTI Research & Development", "CONTRIBUTION AMOUNT (F3L Bundled)": "150.00", "ELECTION CODE": "", "MEMO CODE": "", "CONTRIBUTOR EMPLOYER": "Mylan Technologies Inc.", "DONOR CANDIDATE STATE": "", "CONTRIBUTOR STREET 1": "346 Vitez Dr", "CONTRIBUTOR MIDDLE NAME": "E", "DONOR CANDIDATE FEC ID": "", "DONOR CANDIDATE MIDDLE NAME": "", "CONTRIBUTOR STATE": "WV", "DONOR CANDIDATE FIRST NAME": "", "CONTRIBUTOR FIRST NAME": "Michael", "BACK REFERENCE SCHED NAME": "", "DONOR CANDIDATE DISTRICT": "", "CONTRIBUTION DATE": "20100930", "DONOR COMMITTEE NAME": "", "MEMO TEXT/DESCRIPTION": "P/R Deduction ($0.00 )", "Reference to SI or SL system code that identifies the Account": "", "FILER COMMITTEE ID NUMBER": "C00332395", "DONOR CANDIDATE LAST NAME": "", "CONTRIBUTOR LAST NAME": "Houghton", "_record_type": "fec.version.v7_0.SA", "CONDUIT STREET2": "", "CONDUIT STREET1": "", "DONOR COMMITTEE FEC ID": "", "CONTRIBUTION PURPOSE DESCRIP": "", "CONTRIBUTOR ZIP": "26508", "CONTRIBUTOR STREET 2": "", "CONDUIT CITY": "", "ENTITY TYPE": "IND", "CONTRIBUTOR CITY": "Morgantown", "CONTRIBUTOR SUFFIX": "", "TRANSACTION ID": "PR1481904520383", "DONOR CANDIDATE SUFFIX": "", "DONOR CANDIDATE OFFICE": "", "CONTRIBUTION PURPOSE CODE": "15", "ELECTION OTHER DESCRIPTION": "", "_src_file": "2011/20110411/721688.fec_1.yml", "CONDUIT STATE": "", "CONTRIBUTOR ORGANIZATION NAME": "", "BACK REFERENCE TRAN ID NUMBER": "", "DONOR CANDIDATE PREFIX": "", "CONTRIBUTOR PREFIX": "", "CONDUIT ZIP": "", "CONDUIT NAME": "", "CONTRIBUTION AGGREGATE F3L Semi-annual Bundled": "450.00", "FORM TYPE": "SA11ai"});
import axios from 'axios' // import store from '@/store' // import { getToken } from '@/utils/auth' // create an axios instance const service = axios.create({ baseURL: process.env.BASE_API, // timeout: 8000 // request timeout }) // request interceptor service.interceptors.request.use(config => { // Do something before request is sent // if (store.getters.token) { // config.headers['X-Token'] = getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改 // } return config }, error => { // Do something with request error console.log(error) // for debug Promise.reject(error) }) // respone interceptor service.interceptors.response.use( response => { const res = response.data if (res.code !== '0') { if (!res.code) { // store.dispatch('FedLogOut').then(() => { // // location.reload()// 为了重新实例化vue-router对象 避免bug // }) } return Promise.reject(res) } else { return response.data } }, error => { console.log('err' + error) // for debug return Promise.reject(error) }) export default service
"use strict"; function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } define(['src/util/util', './printServerFactory', './printProcessors'], function (Util, printServerFactory, processors) { var Printer = /*#__PURE__*/ function () { function Printer(printer, printServer, opts) { _classCallCheck(this, Printer); this.url = String(printServer.url); this.id = String(printer.id); this.printServer = printServerFactory(printServer, opts); } _createClass(Printer, [{ key: "print", value: function () { var _print = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee(printFormat, data) { var printData; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return getPrintData(printFormat, data); case 2: printData = _context.sent; if (!(printData === null)) { _context.next = 5; break; } return _context.abrupt("return", null); case 5: return _context.abrupt("return", this.printServer.print(this.id, printData)); case 6: case "end": return _context.stop(); } } }, _callee, this); })); function print(_x, _x2) { return _print.apply(this, arguments); } return print; }() }]); return Printer; }(); function getPrintData(_x3, _x4) { return _getPrintData.apply(this, arguments); } function _getPrintData() { _getPrintData = _asyncToGenerator( /*#__PURE__*/ regeneratorRuntime.mark(function _callee2(printFormat, data) { var options, _args2 = arguments; return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: options = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : {}; if (processors[printFormat.processor]) { _context2.next = 3; break; } throw new Error('processor does not exist'); case 3: data = processData(printFormat, data); return _context2.abrupt("return", processors[String(printFormat.processor)].call(null, printFormat, data, options)); case 5: case "end": return _context2.stop(); } } }, _callee2); })); return _getPrintData.apply(this, arguments); } function processData(printFormat, data) { switch (printFormat.type) { case 'sample': { var result = JSON.parse(JSON.stringify(data)); if (result.$content) { result.entry = result.$content; if (result._id) { result.uuidShort = result._id.substring(0, 12); result.b64Short = Util.hexToBase64(result.uuidShort); } if (result.$id) { result.id = result.$id; } if (result.$content.general) { if (result.$content.general.description) { result.line1 = result.$content.general.description.substring(0, 60); result.line2 = result.$content.general.description.substring(60, 120); } else { result.line1 = ''; result.line2 = ''; } if (result.$content.general.molfile) { result.molfile = result.$content.general.molfile; } } } return result; } case 'location': return data; default: return data; } } Printer.processData = processData; Printer.getPrintData = getPrintData; return Printer; });
/******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ "./node_modules/alpinejs/dist/module.esm.js": /*!**************************************************!*\ !*** ./node_modules/alpinejs/dist/module.esm.js ***! \**************************************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => (/* binding */ module_default) /* harmony export */ }); var __create = Object.create; var __defProp = Object.defineProperty; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __getOwnPropNames = Object.getOwnPropertyNames; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __markAsModule = (target) => __defProp(target, "__esModule", {value: true}); var __commonJS = (callback, module) => () => { if (!module) { module = {exports: {}}; callback(module.exports, module); } return module.exports; }; var __exportStar = (target, module, desc) => { if (module && typeof module === "object" || typeof module === "function") { for (let key of __getOwnPropNames(module)) if (!__hasOwnProp.call(target, key) && key !== "default") __defProp(target, key, {get: () => module[key], enumerable: !(desc = __getOwnPropDesc(module, key)) || desc.enumerable}); } return target; }; var __toModule = (module) => { return __exportStar(__markAsModule(__defProp(module != null ? __create(__getProtoOf(module)) : {}, "default", module && module.__esModule && "default" in module ? {get: () => module.default, enumerable: true} : {value: module, enumerable: true})), module); }; // node_modules/@vue/shared/dist/shared.cjs.js var require_shared_cjs = __commonJS((exports) => { "use strict"; Object.defineProperty(exports, "__esModule", {value: true}); function makeMap(str, expectsLowerCase) { const map = Object.create(null); const list = str.split(","); for (let i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? (val) => !!map[val.toLowerCase()] : (val) => !!map[val]; } var PatchFlagNames = { [1]: `TEXT`, [2]: `CLASS`, [4]: `STYLE`, [8]: `PROPS`, [16]: `FULL_PROPS`, [32]: `HYDRATE_EVENTS`, [64]: `STABLE_FRAGMENT`, [128]: `KEYED_FRAGMENT`, [256]: `UNKEYED_FRAGMENT`, [512]: `NEED_PATCH`, [1024]: `DYNAMIC_SLOTS`, [2048]: `DEV_ROOT_FRAGMENT`, [-1]: `HOISTED`, [-2]: `BAIL` }; var slotFlagsText = { [1]: "STABLE", [2]: "DYNAMIC", [3]: "FORWARDED" }; var GLOBALS_WHITE_LISTED = "Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt"; var isGloballyWhitelisted = /* @__PURE__ */ makeMap(GLOBALS_WHITE_LISTED); var range = 2; function generateCodeFrame(source, start2 = 0, end = source.length) { const lines = source.split(/\r?\n/); let count = 0; const res = []; for (let i = 0; i < lines.length; i++) { count += lines[i].length + 1; if (count >= start2) { for (let j = i - range; j <= i + range || end > count; j++) { if (j < 0 || j >= lines.length) continue; const line = j + 1; res.push(`${line}${" ".repeat(Math.max(3 - String(line).length, 0))}| ${lines[j]}`); const lineLength = lines[j].length; if (j === i) { const pad = start2 - (count - lineLength) + 1; const length = Math.max(1, end > count ? lineLength - pad : end - start2); res.push(` | ` + " ".repeat(pad) + "^".repeat(length)); } else if (j > i) { if (end > count) { const length = Math.max(Math.min(end - count, lineLength), 1); res.push(` | ` + "^".repeat(length)); } count += lineLength + 1; } } break; } } return res.join("\n"); } var specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`; var isSpecialBooleanAttr = /* @__PURE__ */ makeMap(specialBooleanAttrs); var isBooleanAttr2 = /* @__PURE__ */ makeMap(specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected`); var unsafeAttrCharRE = /[>/="'\u0009\u000a\u000c\u0020]/; var attrValidationCache = {}; function isSSRSafeAttrName(name) { if (attrValidationCache.hasOwnProperty(name)) { return attrValidationCache[name]; } const isUnsafe = unsafeAttrCharRE.test(name); if (isUnsafe) { console.error(`unsafe attribute name: ${name}`); } return attrValidationCache[name] = !isUnsafe; } var propsToAttrMap = { acceptCharset: "accept-charset", className: "class", htmlFor: "for", httpEquiv: "http-equiv" }; var isNoUnitNumericStyleProp = /* @__PURE__ */ makeMap(`animation-iteration-count,border-image-outset,border-image-slice,border-image-width,box-flex,box-flex-group,box-ordinal-group,column-count,columns,flex,flex-grow,flex-positive,flex-shrink,flex-negative,flex-order,grid-row,grid-row-end,grid-row-span,grid-row-start,grid-column,grid-column-end,grid-column-span,grid-column-start,font-weight,line-clamp,line-height,opacity,order,orphans,tab-size,widows,z-index,zoom,fill-opacity,flood-opacity,stop-opacity,stroke-dasharray,stroke-dashoffset,stroke-miterlimit,stroke-opacity,stroke-width`); var isKnownAttr = /* @__PURE__ */ makeMap(`accept,accept-charset,accesskey,action,align,allow,alt,async,autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,border,buffered,capture,challenge,charset,checked,cite,class,code,codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,formaction,formenctype,formmethod,formnovalidate,formtarget,headers,height,hidden,high,href,hreflang,http-equiv,icon,id,importance,integrity,ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,target,title,translate,type,usemap,value,width,wrap`); function normalizeStyle(value) { if (isArray(value)) { const res = {}; for (let i = 0; i < value.length; i++) { const item = value[i]; const normalized = normalizeStyle(isString(item) ? parseStringStyle(item) : item); if (normalized) { for (const key in normalized) { res[key] = normalized[key]; } } } return res; } else if (isObject(value)) { return value; } } var listDelimiterRE = /;(?![^(]*\))/g; var propertyDelimiterRE = /:(.+)/; function parseStringStyle(cssText) { const ret = {}; cssText.split(listDelimiterRE).forEach((item) => { if (item) { const tmp = item.split(propertyDelimiterRE); tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim()); } }); return ret; } function stringifyStyle(styles) { let ret = ""; if (!styles) { return ret; } for (const key in styles) { const value = styles[key]; const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key); if (isString(value) || typeof value === "number" && isNoUnitNumericStyleProp(normalizedKey)) { ret += `${normalizedKey}:${value};`; } } return ret; } function normalizeClass(value) { let res = ""; if (isString(value)) { res = value; } else if (isArray(value)) { for (let i = 0; i < value.length; i++) { const normalized = normalizeClass(value[i]); if (normalized) { res += normalized + " "; } } } else if (isObject(value)) { for (const name in value) { if (value[name]) { res += name + " "; } } } return res.trim(); } var HTML_TAGS = "html,body,base,head,link,meta,style,title,address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot"; var SVG_TAGS = "svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistanceLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view"; var VOID_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr"; var isHTMLTag = /* @__PURE__ */ makeMap(HTML_TAGS); var isSVGTag = /* @__PURE__ */ makeMap(SVG_TAGS); var isVoidTag = /* @__PURE__ */ makeMap(VOID_TAGS); var escapeRE = /["'&<>]/; function escapeHtml(string) { const str = "" + string; const match = escapeRE.exec(str); if (!match) { return str; } let html = ""; let escaped; let index; let lastIndex = 0; for (index = match.index; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: escaped = "&quot;"; break; case 38: escaped = "&amp;"; break; case 39: escaped = "&#39;"; break; case 60: escaped = "&lt;"; break; case 62: escaped = "&gt;"; break; default: continue; } if (lastIndex !== index) { html += str.substring(lastIndex, index); } lastIndex = index + 1; html += escaped; } return lastIndex !== index ? html + str.substring(lastIndex, index) : html; } var commentStripRE = /^-?>|<!--|-->|--!>|<!-$/g; function escapeHtmlComment(src) { return src.replace(commentStripRE, ""); } function looseCompareArrays(a, b) { if (a.length !== b.length) return false; let equal = true; for (let i = 0; equal && i < a.length; i++) { equal = looseEqual(a[i], b[i]); } return equal; } function looseEqual(a, b) { if (a === b) return true; let aValidType = isDate(a); let bValidType = isDate(b); if (aValidType || bValidType) { return aValidType && bValidType ? a.getTime() === b.getTime() : false; } aValidType = isArray(a); bValidType = isArray(b); if (aValidType || bValidType) { return aValidType && bValidType ? looseCompareArrays(a, b) : false; } aValidType = isObject(a); bValidType = isObject(b); if (aValidType || bValidType) { if (!aValidType || !bValidType) { return false; } const aKeysCount = Object.keys(a).length; const bKeysCount = Object.keys(b).length; if (aKeysCount !== bKeysCount) { return false; } for (const key in a) { const aHasKey = a.hasOwnProperty(key); const bHasKey = b.hasOwnProperty(key); if (aHasKey && !bHasKey || !aHasKey && bHasKey || !looseEqual(a[key], b[key])) { return false; } } } return String(a) === String(b); } function looseIndexOf(arr, val) { return arr.findIndex((item) => looseEqual(item, val)); } var toDisplayString = (val) => { return val == null ? "" : isObject(val) ? JSON.stringify(val, replacer, 2) : String(val); }; var replacer = (_key, val) => { if (isMap(val)) { return { [`Map(${val.size})`]: [...val.entries()].reduce((entries, [key, val2]) => { entries[`${key} =>`] = val2; return entries; }, {}) }; } else if (isSet(val)) { return { [`Set(${val.size})`]: [...val.values()] }; } else if (isObject(val) && !isArray(val) && !isPlainObject(val)) { return String(val); } return val; }; var babelParserDefaultPlugins = [ "bigInt", "optionalChaining", "nullishCoalescingOperator" ]; var EMPTY_OBJ = Object.freeze({}); var EMPTY_ARR = Object.freeze([]); var NOOP = () => { }; var NO = () => false; var onRE = /^on[^a-z]/; var isOn = (key) => onRE.test(key); var isModelListener = (key) => key.startsWith("onUpdate:"); var extend = Object.assign; var remove = (arr, el) => { const i = arr.indexOf(el); if (i > -1) { arr.splice(i, 1); } }; var hasOwnProperty = Object.prototype.hasOwnProperty; var hasOwn = (val, key) => hasOwnProperty.call(val, key); var isArray = Array.isArray; var isMap = (val) => toTypeString(val) === "[object Map]"; var isSet = (val) => toTypeString(val) === "[object Set]"; var isDate = (val) => val instanceof Date; var isFunction = (val) => typeof val === "function"; var isString = (val) => typeof val === "string"; var isSymbol = (val) => typeof val === "symbol"; var isObject = (val) => val !== null && typeof val === "object"; var isPromise = (val) => { return isObject(val) && isFunction(val.then) && isFunction(val.catch); }; var objectToString = Object.prototype.toString; var toTypeString = (value) => objectToString.call(value); var toRawType = (value) => { return toTypeString(value).slice(8, -1); }; var isPlainObject = (val) => toTypeString(val) === "[object Object]"; var isIntegerKey = (key) => isString(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key; var isReservedProp = /* @__PURE__ */ makeMap(",key,ref,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"); var cacheStringFunction = (fn) => { const cache = Object.create(null); return (str) => { const hit = cache[str]; return hit || (cache[str] = fn(str)); }; }; var camelizeRE = /-(\w)/g; var camelize = cacheStringFunction((str) => { return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : ""); }); var hyphenateRE = /\B([A-Z])/g; var hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, "-$1").toLowerCase()); var capitalize = cacheStringFunction((str) => str.charAt(0).toUpperCase() + str.slice(1)); var toHandlerKey = cacheStringFunction((str) => str ? `on${capitalize(str)}` : ``); var hasChanged = (value, oldValue) => value !== oldValue && (value === value || oldValue === oldValue); var invokeArrayFns = (fns, arg) => { for (let i = 0; i < fns.length; i++) { fns[i](arg); } }; var def = (obj, key, value) => { Object.defineProperty(obj, key, { configurable: true, enumerable: false, value }); }; var toNumber = (val) => { const n = parseFloat(val); return isNaN(n) ? val : n; }; var _globalThis; var getGlobalThis = () => { return _globalThis || (_globalThis = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof __webpack_require__.g !== "undefined" ? __webpack_require__.g : {}); }; exports.EMPTY_ARR = EMPTY_ARR; exports.EMPTY_OBJ = EMPTY_OBJ; exports.NO = NO; exports.NOOP = NOOP; exports.PatchFlagNames = PatchFlagNames; exports.babelParserDefaultPlugins = babelParserDefaultPlugins; exports.camelize = camelize; exports.capitalize = capitalize; exports.def = def; exports.escapeHtml = escapeHtml; exports.escapeHtmlComment = escapeHtmlComment; exports.extend = extend; exports.generateCodeFrame = generateCodeFrame; exports.getGlobalThis = getGlobalThis; exports.hasChanged = hasChanged; exports.hasOwn = hasOwn; exports.hyphenate = hyphenate; exports.invokeArrayFns = invokeArrayFns; exports.isArray = isArray; exports.isBooleanAttr = isBooleanAttr2; exports.isDate = isDate; exports.isFunction = isFunction; exports.isGloballyWhitelisted = isGloballyWhitelisted; exports.isHTMLTag = isHTMLTag; exports.isIntegerKey = isIntegerKey; exports.isKnownAttr = isKnownAttr; exports.isMap = isMap; exports.isModelListener = isModelListener; exports.isNoUnitNumericStyleProp = isNoUnitNumericStyleProp; exports.isObject = isObject; exports.isOn = isOn; exports.isPlainObject = isPlainObject; exports.isPromise = isPromise; exports.isReservedProp = isReservedProp; exports.isSSRSafeAttrName = isSSRSafeAttrName; exports.isSVGTag = isSVGTag; exports.isSet = isSet; exports.isSpecialBooleanAttr = isSpecialBooleanAttr; exports.isString = isString; exports.isSymbol = isSymbol; exports.isVoidTag = isVoidTag; exports.looseEqual = looseEqual; exports.looseIndexOf = looseIndexOf; exports.makeMap = makeMap; exports.normalizeClass = normalizeClass; exports.normalizeStyle = normalizeStyle; exports.objectToString = objectToString; exports.parseStringStyle = parseStringStyle; exports.propsToAttrMap = propsToAttrMap; exports.remove = remove; exports.slotFlagsText = slotFlagsText; exports.stringifyStyle = stringifyStyle; exports.toDisplayString = toDisplayString; exports.toHandlerKey = toHandlerKey; exports.toNumber = toNumber; exports.toRawType = toRawType; exports.toTypeString = toTypeString; }); // node_modules/@vue/shared/index.js var require_shared = __commonJS((exports, module) => { "use strict"; if (false) {} else { module.exports = require_shared_cjs(); } }); // node_modules/@vue/reactivity/dist/reactivity.cjs.js var require_reactivity_cjs = __commonJS((exports) => { "use strict"; Object.defineProperty(exports, "__esModule", {value: true}); var shared = require_shared(); var targetMap = new WeakMap(); var effectStack = []; var activeEffect; var ITERATE_KEY = Symbol("iterate"); var MAP_KEY_ITERATE_KEY = Symbol("Map key iterate"); function isEffect(fn) { return fn && fn._isEffect === true; } function effect3(fn, options = shared.EMPTY_OBJ) { if (isEffect(fn)) { fn = fn.raw; } const effect4 = createReactiveEffect(fn, options); if (!options.lazy) { effect4(); } return effect4; } function stop2(effect4) { if (effect4.active) { cleanup(effect4); if (effect4.options.onStop) { effect4.options.onStop(); } effect4.active = false; } } var uid = 0; function createReactiveEffect(fn, options) { const effect4 = function reactiveEffect() { if (!effect4.active) { return fn(); } if (!effectStack.includes(effect4)) { cleanup(effect4); try { enableTracking(); effectStack.push(effect4); activeEffect = effect4; return fn(); } finally { effectStack.pop(); resetTracking(); activeEffect = effectStack[effectStack.length - 1]; } } }; effect4.id = uid++; effect4.allowRecurse = !!options.allowRecurse; effect4._isEffect = true; effect4.active = true; effect4.raw = fn; effect4.deps = []; effect4.options = options; return effect4; } function cleanup(effect4) { const {deps} = effect4; if (deps.length) { for (let i = 0; i < deps.length; i++) { deps[i].delete(effect4); } deps.length = 0; } } var shouldTrack = true; var trackStack = []; function pauseTracking() { trackStack.push(shouldTrack); shouldTrack = false; } function enableTracking() { trackStack.push(shouldTrack); shouldTrack = true; } function resetTracking() { const last = trackStack.pop(); shouldTrack = last === void 0 ? true : last; } function track(target, type, key) { if (!shouldTrack || activeEffect === void 0) { return; } let depsMap = targetMap.get(target); if (!depsMap) { targetMap.set(target, depsMap = new Map()); } let dep = depsMap.get(key); if (!dep) { depsMap.set(key, dep = new Set()); } if (!dep.has(activeEffect)) { dep.add(activeEffect); activeEffect.deps.push(dep); if (activeEffect.options.onTrack) { activeEffect.options.onTrack({ effect: activeEffect, target, type, key }); } } } function trigger(target, type, key, newValue, oldValue, oldTarget) { const depsMap = targetMap.get(target); if (!depsMap) { return; } const effects = new Set(); const add2 = (effectsToAdd) => { if (effectsToAdd) { effectsToAdd.forEach((effect4) => { if (effect4 !== activeEffect || effect4.allowRecurse) { effects.add(effect4); } }); } }; if (type === "clear") { depsMap.forEach(add2); } else if (key === "length" && shared.isArray(target)) { depsMap.forEach((dep, key2) => { if (key2 === "length" || key2 >= newValue) { add2(dep); } }); } else { if (key !== void 0) { add2(depsMap.get(key)); } switch (type) { case "add": if (!shared.isArray(target)) { add2(depsMap.get(ITERATE_KEY)); if (shared.isMap(target)) { add2(depsMap.get(MAP_KEY_ITERATE_KEY)); } } else if (shared.isIntegerKey(key)) { add2(depsMap.get("length")); } break; case "delete": if (!shared.isArray(target)) { add2(depsMap.get(ITERATE_KEY)); if (shared.isMap(target)) { add2(depsMap.get(MAP_KEY_ITERATE_KEY)); } } break; case "set": if (shared.isMap(target)) { add2(depsMap.get(ITERATE_KEY)); } break; } } const run = (effect4) => { if (effect4.options.onTrigger) { effect4.options.onTrigger({ effect: effect4, target, key, type, newValue, oldValue, oldTarget }); } if (effect4.options.scheduler) { effect4.options.scheduler(effect4); } else { effect4(); } }; effects.forEach(run); } var isNonTrackableKeys = /* @__PURE__ */ shared.makeMap(`__proto__,__v_isRef,__isVue`); var builtInSymbols = new Set(Object.getOwnPropertyNames(Symbol).map((key) => Symbol[key]).filter(shared.isSymbol)); var get2 = /* @__PURE__ */ createGetter(); var shallowGet = /* @__PURE__ */ createGetter(false, true); var readonlyGet = /* @__PURE__ */ createGetter(true); var shallowReadonlyGet = /* @__PURE__ */ createGetter(true, true); var arrayInstrumentations = {}; ["includes", "indexOf", "lastIndexOf"].forEach((key) => { const method = Array.prototype[key]; arrayInstrumentations[key] = function(...args) { const arr = toRaw2(this); for (let i = 0, l = this.length; i < l; i++) { track(arr, "get", i + ""); } const res = method.apply(arr, args); if (res === -1 || res === false) { return method.apply(arr, args.map(toRaw2)); } else { return res; } }; }); ["push", "pop", "shift", "unshift", "splice"].forEach((key) => { const method = Array.prototype[key]; arrayInstrumentations[key] = function(...args) { pauseTracking(); const res = method.apply(this, args); resetTracking(); return res; }; }); function createGetter(isReadonly2 = false, shallow = false) { return function get3(target, key, receiver) { if (key === "__v_isReactive") { return !isReadonly2; } else if (key === "__v_isReadonly") { return isReadonly2; } else if (key === "__v_raw" && receiver === (isReadonly2 ? shallow ? shallowReadonlyMap : readonlyMap : shallow ? shallowReactiveMap : reactiveMap).get(target)) { return target; } const targetIsArray = shared.isArray(target); if (!isReadonly2 && targetIsArray && shared.hasOwn(arrayInstrumentations, key)) { return Reflect.get(arrayInstrumentations, key, receiver); } const res = Reflect.get(target, key, receiver); if (shared.isSymbol(key) ? builtInSymbols.has(key) : isNonTrackableKeys(key)) { return res; } if (!isReadonly2) { track(target, "get", key); } if (shallow) { return res; } if (isRef(res)) { const shouldUnwrap = !targetIsArray || !shared.isIntegerKey(key); return shouldUnwrap ? res.value : res; } if (shared.isObject(res)) { return isReadonly2 ? readonly(res) : reactive3(res); } return res; }; } var set2 = /* @__PURE__ */ createSetter(); var shallowSet = /* @__PURE__ */ createSetter(true); function createSetter(shallow = false) { return function set3(target, key, value, receiver) { let oldValue = target[key]; if (!shallow) { value = toRaw2(value); oldValue = toRaw2(oldValue); if (!shared.isArray(target) && isRef(oldValue) && !isRef(value)) { oldValue.value = value; return true; } } const hadKey = shared.isArray(target) && shared.isIntegerKey(key) ? Number(key) < target.length : shared.hasOwn(target, key); const result = Reflect.set(target, key, value, receiver); if (target === toRaw2(receiver)) { if (!hadKey) { trigger(target, "add", key, value); } else if (shared.hasChanged(value, oldValue)) { trigger(target, "set", key, value, oldValue); } } return result; }; } function deleteProperty(target, key) { const hadKey = shared.hasOwn(target, key); const oldValue = target[key]; const result = Reflect.deleteProperty(target, key); if (result && hadKey) { trigger(target, "delete", key, void 0, oldValue); } return result; } function has(target, key) { const result = Reflect.has(target, key); if (!shared.isSymbol(key) || !builtInSymbols.has(key)) { track(target, "has", key); } return result; } function ownKeys(target) { track(target, "iterate", shared.isArray(target) ? "length" : ITERATE_KEY); return Reflect.ownKeys(target); } var mutableHandlers = { get: get2, set: set2, deleteProperty, has, ownKeys }; var readonlyHandlers = { get: readonlyGet, set(target, key) { { console.warn(`Set operation on key "${String(key)}" failed: target is readonly.`, target); } return true; }, deleteProperty(target, key) { { console.warn(`Delete operation on key "${String(key)}" failed: target is readonly.`, target); } return true; } }; var shallowReactiveHandlers = shared.extend({}, mutableHandlers, { get: shallowGet, set: shallowSet }); var shallowReadonlyHandlers = shared.extend({}, readonlyHandlers, { get: shallowReadonlyGet }); var toReactive = (value) => shared.isObject(value) ? reactive3(value) : value; var toReadonly = (value) => shared.isObject(value) ? readonly(value) : value; var toShallow = (value) => value; var getProto = (v) => Reflect.getPrototypeOf(v); function get$1(target, key, isReadonly2 = false, isShallow = false) { target = target["__v_raw"]; const rawTarget = toRaw2(target); const rawKey = toRaw2(key); if (key !== rawKey) { !isReadonly2 && track(rawTarget, "get", key); } !isReadonly2 && track(rawTarget, "get", rawKey); const {has: has2} = getProto(rawTarget); const wrap = isShallow ? toShallow : isReadonly2 ? toReadonly : toReactive; if (has2.call(rawTarget, key)) { return wrap(target.get(key)); } else if (has2.call(rawTarget, rawKey)) { return wrap(target.get(rawKey)); } else if (target !== rawTarget) { target.get(key); } } function has$1(key, isReadonly2 = false) { const target = this["__v_raw"]; const rawTarget = toRaw2(target); const rawKey = toRaw2(key); if (key !== rawKey) { !isReadonly2 && track(rawTarget, "has", key); } !isReadonly2 && track(rawTarget, "has", rawKey); return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey); } function size(target, isReadonly2 = false) { target = target["__v_raw"]; !isReadonly2 && track(toRaw2(target), "iterate", ITERATE_KEY); return Reflect.get(target, "size", target); } function add(value) { value = toRaw2(value); const target = toRaw2(this); const proto = getProto(target); const hadKey = proto.has.call(target, value); if (!hadKey) { target.add(value); trigger(target, "add", value, value); } return this; } function set$1(key, value) { value = toRaw2(value); const target = toRaw2(this); const {has: has2, get: get3} = getProto(target); let hadKey = has2.call(target, key); if (!hadKey) { key = toRaw2(key); hadKey = has2.call(target, key); } else { checkIdentityKeys(target, has2, key); } const oldValue = get3.call(target, key); target.set(key, value); if (!hadKey) { trigger(target, "add", key, value); } else if (shared.hasChanged(value, oldValue)) { trigger(target, "set", key, value, oldValue); } return this; } function deleteEntry(key) { const target = toRaw2(this); const {has: has2, get: get3} = getProto(target); let hadKey = has2.call(target, key); if (!hadKey) { key = toRaw2(key); hadKey = has2.call(target, key); } else { checkIdentityKeys(target, has2, key); } const oldValue = get3 ? get3.call(target, key) : void 0; const result = target.delete(key); if (hadKey) { trigger(target, "delete", key, void 0, oldValue); } return result; } function clear() { const target = toRaw2(this); const hadItems = target.size !== 0; const oldTarget = shared.isMap(target) ? new Map(target) : new Set(target); const result = target.clear(); if (hadItems) { trigger(target, "clear", void 0, void 0, oldTarget); } return result; } function createForEach(isReadonly2, isShallow) { return function forEach(callback, thisArg) { const observed = this; const target = observed["__v_raw"]; const rawTarget = toRaw2(target); const wrap = isShallow ? toShallow : isReadonly2 ? toReadonly : toReactive; !isReadonly2 && track(rawTarget, "iterate", ITERATE_KEY); return target.forEach((value, key) => { return callback.call(thisArg, wrap(value), wrap(key), observed); }); }; } function createIterableMethod(method, isReadonly2, isShallow) { return function(...args) { const target = this["__v_raw"]; const rawTarget = toRaw2(target); const targetIsMap = shared.isMap(rawTarget); const isPair = method === "entries" || method === Symbol.iterator && targetIsMap; const isKeyOnly = method === "keys" && targetIsMap; const innerIterator = target[method](...args); const wrap = isShallow ? toShallow : isReadonly2 ? toReadonly : toReactive; !isReadonly2 && track(rawTarget, "iterate", isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY); return { next() { const {value, done} = innerIterator.next(); return done ? {value, done} : { value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value), done }; }, [Symbol.iterator]() { return this; } }; }; } function createReadonlyMethod(type) { return function(...args) { { const key = args[0] ? `on key "${args[0]}" ` : ``; console.warn(`${shared.capitalize(type)} operation ${key}failed: target is readonly.`, toRaw2(this)); } return type === "delete" ? false : this; }; } var mutableInstrumentations = { get(key) { return get$1(this, key); }, get size() { return size(this); }, has: has$1, add, set: set$1, delete: deleteEntry, clear, forEach: createForEach(false, false) }; var shallowInstrumentations = { get(key) { return get$1(this, key, false, true); }, get size() { return size(this); }, has: has$1, add, set: set$1, delete: deleteEntry, clear, forEach: createForEach(false, true) }; var readonlyInstrumentations = { get(key) { return get$1(this, key, true); }, get size() { return size(this, true); }, has(key) { return has$1.call(this, key, true); }, add: createReadonlyMethod("add"), set: createReadonlyMethod("set"), delete: createReadonlyMethod("delete"), clear: createReadonlyMethod("clear"), forEach: createForEach(true, false) }; var shallowReadonlyInstrumentations = { get(key) { return get$1(this, key, true, true); }, get size() { return size(this, true); }, has(key) { return has$1.call(this, key, true); }, add: createReadonlyMethod("add"), set: createReadonlyMethod("set"), delete: createReadonlyMethod("delete"), clear: createReadonlyMethod("clear"), forEach: createForEach(true, true) }; var iteratorMethods = ["keys", "values", "entries", Symbol.iterator]; iteratorMethods.forEach((method) => { mutableInstrumentations[method] = createIterableMethod(method, false, false); readonlyInstrumentations[method] = createIterableMethod(method, true, false); shallowInstrumentations[method] = createIterableMethod(method, false, true); shallowReadonlyInstrumentations[method] = createIterableMethod(method, true, true); }); function createInstrumentationGetter(isReadonly2, shallow) { const instrumentations = shallow ? isReadonly2 ? shallowReadonlyInstrumentations : shallowInstrumentations : isReadonly2 ? readonlyInstrumentations : mutableInstrumentations; return (target, key, receiver) => { if (key === "__v_isReactive") { return !isReadonly2; } else if (key === "__v_isReadonly") { return isReadonly2; } else if (key === "__v_raw") { return target; } return Reflect.get(shared.hasOwn(instrumentations, key) && key in target ? instrumentations : target, key, receiver); }; } var mutableCollectionHandlers = { get: createInstrumentationGetter(false, false) }; var shallowCollectionHandlers = { get: createInstrumentationGetter(false, true) }; var readonlyCollectionHandlers = { get: createInstrumentationGetter(true, false) }; var shallowReadonlyCollectionHandlers = { get: createInstrumentationGetter(true, true) }; function checkIdentityKeys(target, has2, key) { const rawKey = toRaw2(key); if (rawKey !== key && has2.call(target, rawKey)) { const type = shared.toRawType(target); console.warn(`Reactive ${type} contains both the raw and reactive versions of the same object${type === `Map` ? ` as keys` : ``}, which can lead to inconsistencies. Avoid differentiating between the raw and reactive versions of an object and only use the reactive version if possible.`); } } var reactiveMap = new WeakMap(); var shallowReactiveMap = new WeakMap(); var readonlyMap = new WeakMap(); var shallowReadonlyMap = new WeakMap(); function targetTypeMap(rawType) { switch (rawType) { case "Object": case "Array": return 1; case "Map": case "Set": case "WeakMap": case "WeakSet": return 2; default: return 0; } } function getTargetType(value) { return value["__v_skip"] || !Object.isExtensible(value) ? 0 : targetTypeMap(shared.toRawType(value)); } function reactive3(target) { if (target && target["__v_isReadonly"]) { return target; } return createReactiveObject(target, false, mutableHandlers, mutableCollectionHandlers, reactiveMap); } function shallowReactive(target) { return createReactiveObject(target, false, shallowReactiveHandlers, shallowCollectionHandlers, shallowReactiveMap); } function readonly(target) { return createReactiveObject(target, true, readonlyHandlers, readonlyCollectionHandlers, readonlyMap); } function shallowReadonly(target) { return createReactiveObject(target, true, shallowReadonlyHandlers, shallowReadonlyCollectionHandlers, shallowReadonlyMap); } function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) { if (!shared.isObject(target)) { { console.warn(`value cannot be made reactive: ${String(target)}`); } return target; } if (target["__v_raw"] && !(isReadonly2 && target["__v_isReactive"])) { return target; } const existingProxy = proxyMap.get(target); if (existingProxy) { return existingProxy; } const targetType = getTargetType(target); if (targetType === 0) { return target; } const proxy = new Proxy(target, targetType === 2 ? collectionHandlers : baseHandlers); proxyMap.set(target, proxy); return proxy; } function isReactive2(value) { if (isReadonly(value)) { return isReactive2(value["__v_raw"]); } return !!(value && value["__v_isReactive"]); } function isReadonly(value) { return !!(value && value["__v_isReadonly"]); } function isProxy(value) { return isReactive2(value) || isReadonly(value); } function toRaw2(observed) { return observed && toRaw2(observed["__v_raw"]) || observed; } function markRaw(value) { shared.def(value, "__v_skip", true); return value; } var convert = (val) => shared.isObject(val) ? reactive3(val) : val; function isRef(r) { return Boolean(r && r.__v_isRef === true); } function ref(value) { return createRef(value); } function shallowRef(value) { return createRef(value, true); } var RefImpl = class { constructor(_rawValue, _shallow = false) { this._rawValue = _rawValue; this._shallow = _shallow; this.__v_isRef = true; this._value = _shallow ? _rawValue : convert(_rawValue); } get value() { track(toRaw2(this), "get", "value"); return this._value; } set value(newVal) { if (shared.hasChanged(toRaw2(newVal), this._rawValue)) { this._rawValue = newVal; this._value = this._shallow ? newVal : convert(newVal); trigger(toRaw2(this), "set", "value", newVal); } } }; function createRef(rawValue, shallow = false) { if (isRef(rawValue)) { return rawValue; } return new RefImpl(rawValue, shallow); } function triggerRef(ref2) { trigger(toRaw2(ref2), "set", "value", ref2.value); } function unref(ref2) { return isRef(ref2) ? ref2.value : ref2; } var shallowUnwrapHandlers = { get: (target, key, receiver) => unref(Reflect.get(target, key, receiver)), set: (target, key, value, receiver) => { const oldValue = target[key]; if (isRef(oldValue) && !isRef(value)) { oldValue.value = value; return true; } else { return Reflect.set(target, key, value, receiver); } } }; function proxyRefs(objectWithRefs) { return isReactive2(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers); } var CustomRefImpl = class { constructor(factory) { this.__v_isRef = true; const {get: get3, set: set3} = factory(() => track(this, "get", "value"), () => trigger(this, "set", "value")); this._get = get3; this._set = set3; } get value() { return this._get(); } set value(newVal) { this._set(newVal); } }; function customRef(factory) { return new CustomRefImpl(factory); } function toRefs(object) { if (!isProxy(object)) { console.warn(`toRefs() expects a reactive object but received a plain one.`); } const ret = shared.isArray(object) ? new Array(object.length) : {}; for (const key in object) { ret[key] = toRef(object, key); } return ret; } var ObjectRefImpl = class { constructor(_object, _key) { this._object = _object; this._key = _key; this.__v_isRef = true; } get value() { return this._object[this._key]; } set value(newVal) { this._object[this._key] = newVal; } }; function toRef(object, key) { return isRef(object[key]) ? object[key] : new ObjectRefImpl(object, key); } var ComputedRefImpl = class { constructor(getter, _setter, isReadonly2) { this._setter = _setter; this._dirty = true; this.__v_isRef = true; this.effect = effect3(getter, { lazy: true, scheduler: () => { if (!this._dirty) { this._dirty = true; trigger(toRaw2(this), "set", "value"); } } }); this["__v_isReadonly"] = isReadonly2; } get value() { const self2 = toRaw2(this); if (self2._dirty) { self2._value = this.effect(); self2._dirty = false; } track(self2, "get", "value"); return self2._value; } set value(newValue) { this._setter(newValue); } }; function computed(getterOrOptions) { let getter; let setter; if (shared.isFunction(getterOrOptions)) { getter = getterOrOptions; setter = () => { console.warn("Write operation failed: computed value is readonly"); }; } else { getter = getterOrOptions.get; setter = getterOrOptions.set; } return new ComputedRefImpl(getter, setter, shared.isFunction(getterOrOptions) || !getterOrOptions.set); } exports.ITERATE_KEY = ITERATE_KEY; exports.computed = computed; exports.customRef = customRef; exports.effect = effect3; exports.enableTracking = enableTracking; exports.isProxy = isProxy; exports.isReactive = isReactive2; exports.isReadonly = isReadonly; exports.isRef = isRef; exports.markRaw = markRaw; exports.pauseTracking = pauseTracking; exports.proxyRefs = proxyRefs; exports.reactive = reactive3; exports.readonly = readonly; exports.ref = ref; exports.resetTracking = resetTracking; exports.shallowReactive = shallowReactive; exports.shallowReadonly = shallowReadonly; exports.shallowRef = shallowRef; exports.stop = stop2; exports.toRaw = toRaw2; exports.toRef = toRef; exports.toRefs = toRefs; exports.track = track; exports.trigger = trigger; exports.triggerRef = triggerRef; exports.unref = unref; }); // node_modules/@vue/reactivity/index.js var require_reactivity = __commonJS((exports, module) => { "use strict"; if (false) {} else { module.exports = require_reactivity_cjs(); } }); // packages/alpinejs/src/scheduler.js var flushPending = false; var flushing = false; var queue = []; function scheduler(callback) { queueJob(callback); } function queueJob(job) { if (!queue.includes(job)) queue.push(job); queueFlush(); } function queueFlush() { if (!flushing && !flushPending) { flushPending = true; queueMicrotask(flushJobs); } } function flushJobs() { flushPending = false; flushing = true; for (let i = 0; i < queue.length; i++) { queue[i](); } queue.length = 0; flushing = false; } // packages/alpinejs/src/reactivity.js var reactive; var effect; var release; var raw; var shouldSchedule = true; function disableEffectScheduling(callback) { shouldSchedule = false; callback(); shouldSchedule = true; } function setReactivityEngine(engine) { reactive = engine.reactive; release = engine.release; effect = (callback) => engine.effect(callback, {scheduler: (task) => { if (shouldSchedule) { scheduler(task); } else { task(); } }}); raw = engine.raw; } function overrideEffect(override) { effect = override; } function elementBoundEffect(el) { let cleanup = () => { }; let wrappedEffect = (callback) => { let effectReference = effect(callback); if (!el._x_effects) { el._x_effects = new Set(); el._x_runEffects = () => { el._x_effects.forEach((i) => i()); }; } el._x_effects.add(effectReference); cleanup = () => { if (effectReference === void 0) return; el._x_effects.delete(effectReference); release(effectReference); }; }; return [wrappedEffect, () => { cleanup(); }]; } // packages/alpinejs/src/mutation.js var onAttributeAddeds = []; var onElRemoveds = []; var onElAddeds = []; function onElAdded(callback) { onElAddeds.push(callback); } function onElRemoved(callback) { onElRemoveds.push(callback); } function onAttributesAdded(callback) { onAttributeAddeds.push(callback); } function onAttributeRemoved(el, name, callback) { if (!el._x_attributeCleanups) el._x_attributeCleanups = {}; if (!el._x_attributeCleanups[name]) el._x_attributeCleanups[name] = []; el._x_attributeCleanups[name].push(callback); } function cleanupAttributes(el, names) { if (!el._x_attributeCleanups) return; Object.entries(el._x_attributeCleanups).forEach(([name, value]) => { if (names === void 0 || names.includes(name)) { value.forEach((i) => i()); delete el._x_attributeCleanups[name]; } }); } var observer = new MutationObserver(onMutate); var currentlyObserving = false; function startObservingMutations() { observer.observe(document, {subtree: true, childList: true, attributes: true, attributeOldValue: true}); currentlyObserving = true; } function stopObservingMutations() { flushObserver(); observer.disconnect(); currentlyObserving = false; } var recordQueue = []; var willProcessRecordQueue = false; function flushObserver() { recordQueue = recordQueue.concat(observer.takeRecords()); if (recordQueue.length && !willProcessRecordQueue) { willProcessRecordQueue = true; queueMicrotask(() => { processRecordQueue(); willProcessRecordQueue = false; }); } } function processRecordQueue() { onMutate(recordQueue); recordQueue.length = 0; } function mutateDom(callback) { if (!currentlyObserving) return callback(); stopObservingMutations(); let result = callback(); startObservingMutations(); return result; } var isCollecting = false; var deferredMutations = []; function deferMutations() { isCollecting = true; } function flushAndStopDeferringMutations() { isCollecting = false; onMutate(deferredMutations); deferredMutations = []; } function onMutate(mutations) { if (isCollecting) { deferredMutations = deferredMutations.concat(mutations); return; } let addedNodes = []; let removedNodes = []; let addedAttributes = new Map(); let removedAttributes = new Map(); for (let i = 0; i < mutations.length; i++) { if (mutations[i].target._x_ignoreMutationObserver) continue; if (mutations[i].type === "childList") { mutations[i].addedNodes.forEach((node) => node.nodeType === 1 && addedNodes.push(node)); mutations[i].removedNodes.forEach((node) => node.nodeType === 1 && removedNodes.push(node)); } if (mutations[i].type === "attributes") { let el = mutations[i].target; let name = mutations[i].attributeName; let oldValue = mutations[i].oldValue; let add = () => { if (!addedAttributes.has(el)) addedAttributes.set(el, []); addedAttributes.get(el).push({name, value: el.getAttribute(name)}); }; let remove = () => { if (!removedAttributes.has(el)) removedAttributes.set(el, []); removedAttributes.get(el).push(name); }; if (el.hasAttribute(name) && oldValue === null) { add(); } else if (el.hasAttribute(name)) { remove(); add(); } else { remove(); } } } removedAttributes.forEach((attrs, el) => { cleanupAttributes(el, attrs); }); addedAttributes.forEach((attrs, el) => { onAttributeAddeds.forEach((i) => i(el, attrs)); }); for (let node of addedNodes) { if (removedNodes.includes(node)) continue; onElAddeds.forEach((i) => i(node)); } for (let node of removedNodes) { if (addedNodes.includes(node)) continue; onElRemoveds.forEach((i) => i(node)); } addedNodes = null; removedNodes = null; addedAttributes = null; removedAttributes = null; } // packages/alpinejs/src/scope.js function addScopeToNode(node, data2, referenceNode) { node._x_dataStack = [data2, ...closestDataStack(referenceNode || node)]; return () => { node._x_dataStack = node._x_dataStack.filter((i) => i !== data2); }; } function refreshScope(element, scope) { let existingScope = element._x_dataStack[0]; Object.entries(scope).forEach(([key, value]) => { existingScope[key] = value; }); } function closestDataStack(node) { if (node._x_dataStack) return node._x_dataStack; if (typeof ShadowRoot === "function" && node instanceof ShadowRoot) { return closestDataStack(node.host); } if (!node.parentNode) { return []; } return closestDataStack(node.parentNode); } function mergeProxies(objects) { let thisProxy = new Proxy({}, { ownKeys: () => { return Array.from(new Set(objects.flatMap((i) => Object.keys(i)))); }, has: (target, name) => { return objects.some((obj) => obj.hasOwnProperty(name)); }, get: (target, name) => { return (objects.find((obj) => { if (obj.hasOwnProperty(name)) { let descriptor = Object.getOwnPropertyDescriptor(obj, name); if (descriptor.get && descriptor.get._x_alreadyBound || descriptor.set && descriptor.set._x_alreadyBound) { return true; } if ((descriptor.get || descriptor.set) && descriptor.enumerable) { let getter = descriptor.get; let setter = descriptor.set; let property = descriptor; getter = getter && getter.bind(thisProxy); setter = setter && setter.bind(thisProxy); if (getter) getter._x_alreadyBound = true; if (setter) setter._x_alreadyBound = true; Object.defineProperty(obj, name, { ...property, get: getter, set: setter }); } return true; } return false; }) || {})[name]; }, set: (target, name, value) => { let closestObjectWithKey = objects.find((obj) => obj.hasOwnProperty(name)); if (closestObjectWithKey) { closestObjectWithKey[name] = value; } else { objects[objects.length - 1][name] = value; } return true; } }); return thisProxy; } // packages/alpinejs/src/interceptor.js function initInterceptors(data2) { let isObject = (val) => typeof val === "object" && !Array.isArray(val) && val !== null; let recurse = (obj, basePath = "") => { Object.entries(Object.getOwnPropertyDescriptors(obj)).forEach(([key, {value, enumerable}]) => { if (enumerable === false || value === void 0) return; let path = basePath === "" ? key : `${basePath}.${key}`; if (typeof value === "object" && value !== null && value._x_interceptor) { obj[key] = value.initialize(data2, path, key); } else { if (isObject(value) && value !== obj && !(value instanceof Element)) { recurse(value, path); } } }); }; return recurse(data2); } function interceptor(callback, mutateObj = () => { }) { let obj = { initialValue: void 0, _x_interceptor: true, initialize(data2, path, key) { return callback(this.initialValue, () => get(data2, path), (value) => set(data2, path, value), path, key); } }; mutateObj(obj); return (initialValue) => { if (typeof initialValue === "object" && initialValue !== null && initialValue._x_interceptor) { let initialize = obj.initialize.bind(obj); obj.initialize = (data2, path, key) => { let innerValue = initialValue.initialize(data2, path, key); obj.initialValue = innerValue; return initialize(data2, path, key); }; } else { obj.initialValue = initialValue; } return obj; }; } function get(obj, path) { return path.split(".").reduce((carry, segment) => carry[segment], obj); } function set(obj, path, value) { if (typeof path === "string") path = path.split("."); if (path.length === 1) obj[path[0]] = value; else if (path.length === 0) throw error; else { if (obj[path[0]]) return set(obj[path[0]], path.slice(1), value); else { obj[path[0]] = {}; return set(obj[path[0]], path.slice(1), value); } } } // packages/alpinejs/src/magics.js var magics = {}; function magic(name, callback) { magics[name] = callback; } function injectMagics(obj, el) { Object.entries(magics).forEach(([name, callback]) => { Object.defineProperty(obj, `$${name}`, { get() { return callback(el, {Alpine: alpine_default, interceptor}); }, enumerable: false }); }); return obj; } // packages/alpinejs/src/utils/error.js function tryCatch(el, expression, callback, ...args) { try { return callback(...args); } catch (e) { handleError(e, el, expression); } } function handleError(error2, el, expression = void 0) { Object.assign(error2, {el, expression}); console.warn(`Alpine Expression Error: ${error2.message} ${expression ? 'Expression: "' + expression + '"\n\n' : ""}`, el); setTimeout(() => { throw error2; }, 0); } // packages/alpinejs/src/evaluator.js function evaluate(el, expression, extras = {}) { let result; evaluateLater(el, expression)((value) => result = value, extras); return result; } function evaluateLater(...args) { return theEvaluatorFunction(...args); } var theEvaluatorFunction = normalEvaluator; function setEvaluator(newEvaluator) { theEvaluatorFunction = newEvaluator; } function normalEvaluator(el, expression) { let overriddenMagics = {}; injectMagics(overriddenMagics, el); let dataStack = [overriddenMagics, ...closestDataStack(el)]; if (typeof expression === "function") { return generateEvaluatorFromFunction(dataStack, expression); } let evaluator = generateEvaluatorFromString(dataStack, expression, el); return tryCatch.bind(null, el, expression, evaluator); } function generateEvaluatorFromFunction(dataStack, func) { return (receiver = () => { }, {scope = {}, params = []} = {}) => { let result = func.apply(mergeProxies([scope, ...dataStack]), params); runIfTypeOfFunction(receiver, result); }; } var evaluatorMemo = {}; function generateFunctionFromString(expression, el) { if (evaluatorMemo[expression]) { return evaluatorMemo[expression]; } let AsyncFunction = Object.getPrototypeOf(async function() { }).constructor; let rightSideSafeExpression = /^[\n\s]*if.*\(.*\)/.test(expression) || /^(let|const)\s/.test(expression) ? `(() => { ${expression} })()` : expression; const safeAsyncFunction = () => { try { return new AsyncFunction(["__self", "scope"], `with (scope) { __self.result = ${rightSideSafeExpression} }; __self.finished = true; return __self.result;`); } catch (error2) { handleError(error2, el, expression); return Promise.resolve(); } }; let func = safeAsyncFunction(); evaluatorMemo[expression] = func; return func; } function generateEvaluatorFromString(dataStack, expression, el) { let func = generateFunctionFromString(expression, el); return (receiver = () => { }, {scope = {}, params = []} = {}) => { func.result = void 0; func.finished = false; let completeScope = mergeProxies([scope, ...dataStack]); if (typeof func === "function") { let promise = func(func, completeScope).catch((error2) => handleError(error2, el, expression)); if (func.finished) { runIfTypeOfFunction(receiver, func.result, completeScope, params, el); } else { promise.then((result) => { runIfTypeOfFunction(receiver, result, completeScope, params, el); }).catch((error2) => handleError(error2, el, expression)); } } }; } function runIfTypeOfFunction(receiver, value, scope, params, el) { if (typeof value === "function") { let result = value.apply(scope, params); if (result instanceof Promise) { result.then((i) => runIfTypeOfFunction(receiver, i, scope, params)).catch((error2) => handleError(error2, el, value)); } else { receiver(result); } } else { receiver(value); } } // packages/alpinejs/src/directives.js var prefixAsString = "x-"; function prefix(subject = "") { return prefixAsString + subject; } function setPrefix(newPrefix) { prefixAsString = newPrefix; } var directiveHandlers = {}; function directive(name, callback) { directiveHandlers[name] = callback; } function directives(el, attributes, originalAttributeOverride) { let transformedAttributeMap = {}; let directives2 = Array.from(attributes).map(toTransformedAttributes((newName, oldName) => transformedAttributeMap[newName] = oldName)).filter(outNonAlpineAttributes).map(toParsedDirectives(transformedAttributeMap, originalAttributeOverride)).sort(byPriority); return directives2.map((directive2) => { return getDirectiveHandler(el, directive2); }); } function attributesOnly(attributes) { return Array.from(attributes).map(toTransformedAttributes()).filter((attr) => !outNonAlpineAttributes(attr)); } var isDeferringHandlers = false; var directiveHandlerStacks = new Map(); var currentHandlerStackKey = Symbol(); function deferHandlingDirectives(callback) { isDeferringHandlers = true; let key = Symbol(); currentHandlerStackKey = key; directiveHandlerStacks.set(key, []); let flushHandlers = () => { while (directiveHandlerStacks.get(key).length) directiveHandlerStacks.get(key).shift()(); directiveHandlerStacks.delete(key); }; let stopDeferring = () => { isDeferringHandlers = false; flushHandlers(); }; callback(flushHandlers); stopDeferring(); } function getDirectiveHandler(el, directive2) { let noop = () => { }; let handler3 = directiveHandlers[directive2.type] || noop; let cleanups = []; let cleanup = (callback) => cleanups.push(callback); let [effect3, cleanupEffect] = elementBoundEffect(el); cleanups.push(cleanupEffect); let utilities = { Alpine: alpine_default, effect: effect3, cleanup, evaluateLater: evaluateLater.bind(evaluateLater, el), evaluate: evaluate.bind(evaluate, el) }; let doCleanup = () => cleanups.forEach((i) => i()); onAttributeRemoved(el, directive2.original, doCleanup); let fullHandler = () => { if (el._x_ignore || el._x_ignoreSelf) return; handler3.inline && handler3.inline(el, directive2, utilities); handler3 = handler3.bind(handler3, el, directive2, utilities); isDeferringHandlers ? directiveHandlerStacks.get(currentHandlerStackKey).push(handler3) : handler3(); }; fullHandler.runCleanups = doCleanup; return fullHandler; } var startingWith = (subject, replacement) => ({name, value}) => { if (name.startsWith(subject)) name = name.replace(subject, replacement); return {name, value}; }; var into = (i) => i; function toTransformedAttributes(callback = () => { }) { return ({name, value}) => { let {name: newName, value: newValue} = attributeTransformers.reduce((carry, transform) => { return transform(carry); }, {name, value}); if (newName !== name) callback(newName, name); return {name: newName, value: newValue}; }; } var attributeTransformers = []; function mapAttributes(callback) { attributeTransformers.push(callback); } function outNonAlpineAttributes({name}) { return alpineAttributeRegex().test(name); } var alpineAttributeRegex = () => new RegExp(`^${prefixAsString}([^:^.]+)\\b`); function toParsedDirectives(transformedAttributeMap, originalAttributeOverride) { return ({name, value}) => { let typeMatch = name.match(alpineAttributeRegex()); let valueMatch = name.match(/:([a-zA-Z0-9\-:]+)/); let modifiers = name.match(/\.[^.\]]+(?=[^\]]*$)/g) || []; let original = originalAttributeOverride || transformedAttributeMap[name] || name; return { type: typeMatch ? typeMatch[1] : null, value: valueMatch ? valueMatch[1] : null, modifiers: modifiers.map((i) => i.replace(".", "")), expression: value, original }; }; } var DEFAULT = "DEFAULT"; var directiveOrder = [ "ignore", "ref", "data", "bind", "init", "for", "model", "transition", "show", "if", DEFAULT, "element" ]; function byPriority(a, b) { let typeA = directiveOrder.indexOf(a.type) === -1 ? DEFAULT : a.type; let typeB = directiveOrder.indexOf(b.type) === -1 ? DEFAULT : b.type; return directiveOrder.indexOf(typeA) - directiveOrder.indexOf(typeB); } // packages/alpinejs/src/utils/dispatch.js function dispatch(el, name, detail = {}) { el.dispatchEvent(new CustomEvent(name, { detail, bubbles: true, composed: true, cancelable: true })); } // packages/alpinejs/src/nextTick.js var tickStack = []; var isHolding = false; function nextTick(callback) { tickStack.push(callback); queueMicrotask(() => { isHolding || setTimeout(() => { releaseNextTicks(); }); }); } function releaseNextTicks() { isHolding = false; while (tickStack.length) tickStack.shift()(); } function holdNextTicks() { isHolding = true; } // packages/alpinejs/src/utils/walk.js function walk(el, callback) { if (typeof ShadowRoot === "function" && el instanceof ShadowRoot) { Array.from(el.children).forEach((el2) => walk(el2, callback)); return; } let skip = false; callback(el, () => skip = true); if (skip) return; let node = el.firstElementChild; while (node) { walk(node, callback, false); node = node.nextElementSibling; } } // packages/alpinejs/src/utils/warn.js function warn(message, ...args) { console.warn(`Alpine Warning: ${message}`, ...args); } // packages/alpinejs/src/lifecycle.js function start() { if (!document.body) warn("Unable to initialize. Trying to load Alpine before `<body>` is available. Did you forget to add `defer` in Alpine's `<script>` tag?"); dispatch(document, "alpine:init"); dispatch(document, "alpine:initializing"); startObservingMutations(); onElAdded((el) => initTree(el, walk)); onElRemoved((el) => nextTick(() => destroyTree(el))); onAttributesAdded((el, attrs) => { directives(el, attrs).forEach((handle) => handle()); }); let outNestedComponents = (el) => !closestRoot(el.parentElement, true); Array.from(document.querySelectorAll(allSelectors())).filter(outNestedComponents).forEach((el) => { initTree(el); }); dispatch(document, "alpine:initialized"); } var rootSelectorCallbacks = []; var initSelectorCallbacks = []; function rootSelectors() { return rootSelectorCallbacks.map((fn) => fn()); } function allSelectors() { return rootSelectorCallbacks.concat(initSelectorCallbacks).map((fn) => fn()); } function addRootSelector(selectorCallback) { rootSelectorCallbacks.push(selectorCallback); } function addInitSelector(selectorCallback) { initSelectorCallbacks.push(selectorCallback); } function closestRoot(el, includeInitSelectors = false) { if (!el) return; const selectors = includeInitSelectors ? allSelectors() : rootSelectors(); if (selectors.some((selector) => el.matches(selector))) return el; if (!el.parentElement) return; return closestRoot(el.parentElement, includeInitSelectors); } function isRoot(el) { return rootSelectors().some((selector) => el.matches(selector)); } function initTree(el, walker = walk) { deferHandlingDirectives(() => { walker(el, (el2, skip) => { directives(el2, el2.attributes).forEach((handle) => handle()); el2._x_ignore && skip(); }); }); } function destroyTree(root) { walk(root, (el) => cleanupAttributes(el)); } // packages/alpinejs/src/utils/classes.js function setClasses(el, value) { if (Array.isArray(value)) { return setClassesFromString(el, value.join(" ")); } else if (typeof value === "object" && value !== null) { return setClassesFromObject(el, value); } else if (typeof value === "function") { return setClasses(el, value()); } return setClassesFromString(el, value); } function setClassesFromString(el, classString) { let split = (classString2) => classString2.split(" ").filter(Boolean); let missingClasses = (classString2) => classString2.split(" ").filter((i) => !el.classList.contains(i)).filter(Boolean); let addClassesAndReturnUndo = (classes) => { el.classList.add(...classes); return () => { el.classList.remove(...classes); }; }; classString = classString === true ? classString = "" : classString || ""; return addClassesAndReturnUndo(missingClasses(classString)); } function setClassesFromObject(el, classObject) { let split = (classString) => classString.split(" ").filter(Boolean); let forAdd = Object.entries(classObject).flatMap(([classString, bool]) => bool ? split(classString) : false).filter(Boolean); let forRemove = Object.entries(classObject).flatMap(([classString, bool]) => !bool ? split(classString) : false).filter(Boolean); let added = []; let removed = []; forRemove.forEach((i) => { if (el.classList.contains(i)) { el.classList.remove(i); removed.push(i); } }); forAdd.forEach((i) => { if (!el.classList.contains(i)) { el.classList.add(i); added.push(i); } }); return () => { removed.forEach((i) => el.classList.add(i)); added.forEach((i) => el.classList.remove(i)); }; } // packages/alpinejs/src/utils/styles.js function setStyles(el, value) { if (typeof value === "object" && value !== null) { return setStylesFromObject(el, value); } return setStylesFromString(el, value); } function setStylesFromObject(el, value) { let previousStyles = {}; Object.entries(value).forEach(([key, value2]) => { previousStyles[key] = el.style[key]; el.style.setProperty(kebabCase(key), value2); }); setTimeout(() => { if (el.style.length === 0) { el.removeAttribute("style"); } }); return () => { setStyles(el, previousStyles); }; } function setStylesFromString(el, value) { let cache = el.getAttribute("style", value); el.setAttribute("style", value); return () => { el.setAttribute("style", cache); }; } function kebabCase(subject) { return subject.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase(); } // packages/alpinejs/src/utils/once.js function once(callback, fallback = () => { }) { let called = false; return function() { if (!called) { called = true; callback.apply(this, arguments); } else { fallback.apply(this, arguments); } }; } // packages/alpinejs/src/directives/x-transition.js directive("transition", (el, {value, modifiers, expression}, {evaluate: evaluate2}) => { if (typeof expression === "function") expression = evaluate2(expression); if (!expression) { registerTransitionsFromHelper(el, modifiers, value); } else { registerTransitionsFromClassString(el, expression, value); } }); function registerTransitionsFromClassString(el, classString, stage) { registerTransitionObject(el, setClasses, ""); let directiveStorageMap = { enter: (classes) => { el._x_transition.enter.during = classes; }, "enter-start": (classes) => { el._x_transition.enter.start = classes; }, "enter-end": (classes) => { el._x_transition.enter.end = classes; }, leave: (classes) => { el._x_transition.leave.during = classes; }, "leave-start": (classes) => { el._x_transition.leave.start = classes; }, "leave-end": (classes) => { el._x_transition.leave.end = classes; } }; directiveStorageMap[stage](classString); } function registerTransitionsFromHelper(el, modifiers, stage) { registerTransitionObject(el, setStyles); let doesntSpecify = !modifiers.includes("in") && !modifiers.includes("out") && !stage; let transitioningIn = doesntSpecify || modifiers.includes("in") || ["enter"].includes(stage); let transitioningOut = doesntSpecify || modifiers.includes("out") || ["leave"].includes(stage); if (modifiers.includes("in") && !doesntSpecify) { modifiers = modifiers.filter((i, index) => index < modifiers.indexOf("out")); } if (modifiers.includes("out") && !doesntSpecify) { modifiers = modifiers.filter((i, index) => index > modifiers.indexOf("out")); } let wantsAll = !modifiers.includes("opacity") && !modifiers.includes("scale"); let wantsOpacity = wantsAll || modifiers.includes("opacity"); let wantsScale = wantsAll || modifiers.includes("scale"); let opacityValue = wantsOpacity ? 0 : 1; let scaleValue = wantsScale ? modifierValue(modifiers, "scale", 95) / 100 : 1; let delay = modifierValue(modifiers, "delay", 0); let origin = modifierValue(modifiers, "origin", "center"); let property = "opacity, transform"; let durationIn = modifierValue(modifiers, "duration", 150) / 1e3; let durationOut = modifierValue(modifiers, "duration", 75) / 1e3; let easing = `cubic-bezier(0.4, 0.0, 0.2, 1)`; if (transitioningIn) { el._x_transition.enter.during = { transformOrigin: origin, transitionDelay: delay, transitionProperty: property, transitionDuration: `${durationIn}s`, transitionTimingFunction: easing }; el._x_transition.enter.start = { opacity: opacityValue, transform: `scale(${scaleValue})` }; el._x_transition.enter.end = { opacity: 1, transform: `scale(1)` }; } if (transitioningOut) { el._x_transition.leave.during = { transformOrigin: origin, transitionDelay: delay, transitionProperty: property, transitionDuration: `${durationOut}s`, transitionTimingFunction: easing }; el._x_transition.leave.start = { opacity: 1, transform: `scale(1)` }; el._x_transition.leave.end = { opacity: opacityValue, transform: `scale(${scaleValue})` }; } } function registerTransitionObject(el, setFunction, defaultValue = {}) { if (!el._x_transition) el._x_transition = { enter: {during: defaultValue, start: defaultValue, end: defaultValue}, leave: {during: defaultValue, start: defaultValue, end: defaultValue}, in(before = () => { }, after = () => { }) { transition(el, setFunction, { during: this.enter.during, start: this.enter.start, end: this.enter.end }, before, after); }, out(before = () => { }, after = () => { }) { transition(el, setFunction, { during: this.leave.during, start: this.leave.start, end: this.leave.end }, before, after); } }; } window.Element.prototype._x_toggleAndCascadeWithTransitions = function(el, value, show, hide) { let clickAwayCompatibleShow = () => { document.visibilityState === "visible" ? requestAnimationFrame(show) : setTimeout(show); }; if (value) { if (el._x_transition && (el._x_transition.enter || el._x_transition.leave)) { el._x_transition.enter && (Object.entries(el._x_transition.enter.during).length || Object.entries(el._x_transition.enter.start).length || Object.entries(el._x_transition.enter.end).length) ? el._x_transition.in(show) : clickAwayCompatibleShow(); } else { el._x_transition ? el._x_transition.in(show) : clickAwayCompatibleShow(); } return; } el._x_hidePromise = el._x_transition ? new Promise((resolve, reject) => { el._x_transition.out(() => { }, () => resolve(hide)); el._x_transitioning.beforeCancel(() => reject({isFromCancelledTransition: true})); }) : Promise.resolve(hide); queueMicrotask(() => { let closest = closestHide(el); if (closest) { if (!closest._x_hideChildren) closest._x_hideChildren = []; closest._x_hideChildren.push(el); } else { queueMicrotask(() => { let hideAfterChildren = (el2) => { let carry = Promise.all([ el2._x_hidePromise, ...(el2._x_hideChildren || []).map(hideAfterChildren) ]).then(([i]) => i()); delete el2._x_hidePromise; delete el2._x_hideChildren; return carry; }; hideAfterChildren(el).catch((e) => { if (!e.isFromCancelledTransition) throw e; }); }); } }); }; function closestHide(el) { let parent = el.parentNode; if (!parent) return; return parent._x_hidePromise ? parent : closestHide(parent); } function transition(el, setFunction, {during, start: start2, end} = {}, before = () => { }, after = () => { }) { if (el._x_transitioning) el._x_transitioning.cancel(); if (Object.keys(during).length === 0 && Object.keys(start2).length === 0 && Object.keys(end).length === 0) { before(); after(); return; } let undoStart, undoDuring, undoEnd; performTransition(el, { start() { undoStart = setFunction(el, start2); }, during() { undoDuring = setFunction(el, during); }, before, end() { undoStart(); undoEnd = setFunction(el, end); }, after, cleanup() { undoDuring(); undoEnd(); } }); } function performTransition(el, stages) { let interrupted, reachedBefore, reachedEnd; let finish = once(() => { mutateDom(() => { interrupted = true; if (!reachedBefore) stages.before(); if (!reachedEnd) { stages.end(); releaseNextTicks(); } stages.after(); if (el.isConnected) stages.cleanup(); delete el._x_transitioning; }); }); el._x_transitioning = { beforeCancels: [], beforeCancel(callback) { this.beforeCancels.push(callback); }, cancel: once(function() { while (this.beforeCancels.length) { this.beforeCancels.shift()(); } ; finish(); }), finish }; mutateDom(() => { stages.start(); stages.during(); }); holdNextTicks(); requestAnimationFrame(() => { if (interrupted) return; let duration = Number(getComputedStyle(el).transitionDuration.replace(/,.*/, "").replace("s", "")) * 1e3; let delay = Number(getComputedStyle(el).transitionDelay.replace(/,.*/, "").replace("s", "")) * 1e3; if (duration === 0) duration = Number(getComputedStyle(el).animationDuration.replace("s", "")) * 1e3; mutateDom(() => { stages.before(); }); reachedBefore = true; requestAnimationFrame(() => { if (interrupted) return; mutateDom(() => { stages.end(); }); releaseNextTicks(); setTimeout(el._x_transitioning.finish, duration + delay); reachedEnd = true; }); }); } function modifierValue(modifiers, key, fallback) { if (modifiers.indexOf(key) === -1) return fallback; const rawValue = modifiers[modifiers.indexOf(key) + 1]; if (!rawValue) return fallback; if (key === "scale") { if (isNaN(rawValue)) return fallback; } if (key === "duration") { let match = rawValue.match(/([0-9]+)ms/); if (match) return match[1]; } if (key === "origin") { if (["top", "right", "left", "center", "bottom"].includes(modifiers[modifiers.indexOf(key) + 2])) { return [rawValue, modifiers[modifiers.indexOf(key) + 2]].join(" "); } } return rawValue; } // packages/alpinejs/src/utils/debounce.js function debounce(func, wait) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; func.apply(context, args); }; clearTimeout(timeout); timeout = setTimeout(later, wait); }; } // packages/alpinejs/src/utils/throttle.js function throttle(func, limit) { let inThrottle; return function() { let context = this, args = arguments; if (!inThrottle) { func.apply(context, args); inThrottle = true; setTimeout(() => inThrottle = false, limit); } }; } // packages/alpinejs/src/plugin.js function plugin(callback) { callback(alpine_default); } // packages/alpinejs/src/store.js var stores = {}; var isReactive = false; function store(name, value) { if (!isReactive) { stores = reactive(stores); isReactive = true; } if (value === void 0) { return stores[name]; } stores[name] = value; if (typeof value === "object" && value !== null && value.hasOwnProperty("init") && typeof value.init === "function") { stores[name].init(); } initInterceptors(stores[name]); } function getStores() { return stores; } // packages/alpinejs/src/clone.js var isCloning = false; function skipDuringClone(callback, fallback = () => { }) { return (...args) => isCloning ? fallback(...args) : callback(...args); } function clone(oldEl, newEl) { newEl._x_dataStack = oldEl._x_dataStack; isCloning = true; dontRegisterReactiveSideEffects(() => { cloneTree(newEl); }); isCloning = false; } function cloneTree(el) { let hasRunThroughFirstEl = false; let shallowWalker = (el2, callback) => { walk(el2, (el3, skip) => { if (hasRunThroughFirstEl && isRoot(el3)) return skip(); hasRunThroughFirstEl = true; callback(el3, skip); }); }; initTree(el, shallowWalker); } function dontRegisterReactiveSideEffects(callback) { let cache = effect; overrideEffect((callback2, el) => { let storedEffect = cache(callback2); release(storedEffect); return () => { }; }); callback(); overrideEffect(cache); } // packages/alpinejs/src/datas.js var datas = {}; function data(name, callback) { datas[name] = callback; } function injectDataProviders(obj, context) { Object.entries(datas).forEach(([name, callback]) => { Object.defineProperty(obj, name, { get() { return (...args) => { return callback.bind(context)(...args); }; }, enumerable: false }); }); return obj; } // packages/alpinejs/src/alpine.js var Alpine = { get reactive() { return reactive; }, get release() { return release; }, get effect() { return effect; }, get raw() { return raw; }, version: "3.5.1", flushAndStopDeferringMutations, disableEffectScheduling, setReactivityEngine, skipDuringClone, addRootSelector, deferMutations, mapAttributes, evaluateLater, setEvaluator, mergeProxies, closestRoot, interceptor, transition, setStyles, mutateDom, directive, throttle, debounce, evaluate, initTree, nextTick, prefix: setPrefix, plugin, magic, store, start, clone, data }; var alpine_default = Alpine; // packages/alpinejs/src/index.js var import_reactivity9 = __toModule(require_reactivity()); // packages/alpinejs/src/magics/$nextTick.js magic("nextTick", () => nextTick); // packages/alpinejs/src/magics/$dispatch.js magic("dispatch", (el) => dispatch.bind(dispatch, el)); // packages/alpinejs/src/magics/$watch.js magic("watch", (el) => (key, callback) => { let evaluate2 = evaluateLater(el, key); let firstTime = true; let oldValue; effect(() => evaluate2((value) => { let div = document.createElement("div"); div.dataset.throwAway = value; if (!firstTime) { queueMicrotask(() => { callback(value, oldValue); oldValue = value; }); } else { oldValue = value; } firstTime = false; })); }); // packages/alpinejs/src/magics/$store.js magic("store", getStores); // packages/alpinejs/src/magics/$data.js magic("data", (el) => { return mergeProxies(closestDataStack(el)); }); // packages/alpinejs/src/magics/$root.js magic("root", (el) => closestRoot(el)); // packages/alpinejs/src/magics/$refs.js magic("refs", (el) => { if (el._x_refs_proxy) return el._x_refs_proxy; el._x_refs_proxy = mergeProxies(getArrayOfRefObject(el)); return el._x_refs_proxy; }); function getArrayOfRefObject(el) { let refObjects = []; let currentEl = el; while (currentEl) { if (currentEl._x_refs) refObjects.push(currentEl._x_refs); currentEl = currentEl.parentNode; } return refObjects; } // packages/alpinejs/src/magics/$el.js magic("el", (el) => el); // packages/alpinejs/src/directives/x-ignore.js var handler = () => { }; handler.inline = (el, {modifiers}, {cleanup}) => { modifiers.includes("self") ? el._x_ignoreSelf = true : el._x_ignore = true; cleanup(() => { modifiers.includes("self") ? delete el._x_ignoreSelf : delete el._x_ignore; }); }; directive("ignore", handler); // packages/alpinejs/src/directives/x-effect.js directive("effect", (el, {expression}, {effect: effect3}) => effect3(evaluateLater(el, expression))); // packages/alpinejs/src/utils/bind.js function bind(el, name, value, modifiers = []) { if (!el._x_bindings) el._x_bindings = reactive({}); el._x_bindings[name] = value; name = modifiers.includes("camel") ? camelCase(name) : name; switch (name) { case "value": bindInputValue(el, value); break; case "style": bindStyles(el, value); break; case "class": bindClasses(el, value); break; default: bindAttribute(el, name, value); break; } } function bindInputValue(el, value) { if (el.type === "radio") { if (el.attributes.value === void 0) { el.value = value; } if (window.fromModel) { el.checked = checkedAttrLooseCompare(el.value, value); } } else if (el.type === "checkbox") { if (Number.isInteger(value)) { el.value = value; } else if (!Number.isInteger(value) && !Array.isArray(value) && typeof value !== "boolean" && ![null, void 0].includes(value)) { el.value = String(value); } else { if (Array.isArray(value)) { el.checked = value.some((val) => checkedAttrLooseCompare(val, el.value)); } else { el.checked = !!value; } } } else if (el.tagName === "SELECT") { updateSelect(el, value); } else { if (el.value === value) return; el.value = value; } } function bindClasses(el, value) { if (el._x_undoAddedClasses) el._x_undoAddedClasses(); el._x_undoAddedClasses = setClasses(el, value); } function bindStyles(el, value) { if (el._x_undoAddedStyles) el._x_undoAddedStyles(); el._x_undoAddedStyles = setStyles(el, value); } function bindAttribute(el, name, value) { if ([null, void 0, false].includes(value) && attributeShouldntBePreservedIfFalsy(name)) { el.removeAttribute(name); } else { if (isBooleanAttr(name)) value = name; setIfChanged(el, name, value); } } function setIfChanged(el, attrName, value) { if (el.getAttribute(attrName) != value) { el.setAttribute(attrName, value); } } function updateSelect(el, value) { const arrayWrappedValue = [].concat(value).map((value2) => { return value2 + ""; }); Array.from(el.options).forEach((option) => { option.selected = arrayWrappedValue.includes(option.value); }); } function camelCase(subject) { return subject.toLowerCase().replace(/-(\w)/g, (match, char) => char.toUpperCase()); } function checkedAttrLooseCompare(valueA, valueB) { return valueA == valueB; } function isBooleanAttr(attrName) { const booleanAttributes = [ "disabled", "checked", "required", "readonly", "hidden", "open", "selected", "autofocus", "itemscope", "multiple", "novalidate", "allowfullscreen", "allowpaymentrequest", "formnovalidate", "autoplay", "controls", "loop", "muted", "playsinline", "default", "ismap", "reversed", "async", "defer", "nomodule" ]; return booleanAttributes.includes(attrName); } function attributeShouldntBePreservedIfFalsy(name) { return !["aria-pressed", "aria-checked", "aria-expanded"].includes(name); } // packages/alpinejs/src/utils/on.js function on(el, event, modifiers, callback) { let listenerTarget = el; let handler3 = (e) => callback(e); let options = {}; let wrapHandler = (callback2, wrapper) => (e) => wrapper(callback2, e); if (modifiers.includes("dot")) event = dotSyntax(event); if (modifiers.includes("camel")) event = camelCase2(event); if (modifiers.includes("passive")) options.passive = true; if (modifiers.includes("capture")) options.capture = true; if (modifiers.includes("window")) listenerTarget = window; if (modifiers.includes("document")) listenerTarget = document; if (modifiers.includes("prevent")) handler3 = wrapHandler(handler3, (next, e) => { e.preventDefault(); next(e); }); if (modifiers.includes("stop")) handler3 = wrapHandler(handler3, (next, e) => { e.stopPropagation(); next(e); }); if (modifiers.includes("self")) handler3 = wrapHandler(handler3, (next, e) => { e.target === el && next(e); }); if (modifiers.includes("away") || modifiers.includes("outside")) { listenerTarget = document; handler3 = wrapHandler(handler3, (next, e) => { if (el.contains(e.target)) return; if (el.offsetWidth < 1 && el.offsetHeight < 1) return; if (el._x_isShown === false) return; next(e); }); } handler3 = wrapHandler(handler3, (next, e) => { if (isKeyEvent(event)) { if (isListeningForASpecificKeyThatHasntBeenPressed(e, modifiers)) { return; } } next(e); }); if (modifiers.includes("debounce")) { let nextModifier = modifiers[modifiers.indexOf("debounce") + 1] || "invalid-wait"; let wait = isNumeric(nextModifier.split("ms")[0]) ? Number(nextModifier.split("ms")[0]) : 250; handler3 = debounce(handler3, wait); } if (modifiers.includes("throttle")) { let nextModifier = modifiers[modifiers.indexOf("throttle") + 1] || "invalid-wait"; let wait = isNumeric(nextModifier.split("ms")[0]) ? Number(nextModifier.split("ms")[0]) : 250; handler3 = throttle(handler3, wait); } if (modifiers.includes("once")) { handler3 = wrapHandler(handler3, (next, e) => { next(e); listenerTarget.removeEventListener(event, handler3, options); }); } listenerTarget.addEventListener(event, handler3, options); return () => { listenerTarget.removeEventListener(event, handler3, options); }; } function dotSyntax(subject) { return subject.replace(/-/g, "."); } function camelCase2(subject) { return subject.toLowerCase().replace(/-(\w)/g, (match, char) => char.toUpperCase()); } function isNumeric(subject) { return !Array.isArray(subject) && !isNaN(subject); } function kebabCase2(subject) { return subject.replace(/([a-z])([A-Z])/g, "$1-$2").replace(/[_\s]/, "-").toLowerCase(); } function isKeyEvent(event) { return ["keydown", "keyup"].includes(event); } function isListeningForASpecificKeyThatHasntBeenPressed(e, modifiers) { let keyModifiers = modifiers.filter((i) => { return !["window", "document", "prevent", "stop", "once"].includes(i); }); if (keyModifiers.includes("debounce")) { let debounceIndex = keyModifiers.indexOf("debounce"); keyModifiers.splice(debounceIndex, isNumeric((keyModifiers[debounceIndex + 1] || "invalid-wait").split("ms")[0]) ? 2 : 1); } if (keyModifiers.length === 0) return false; if (keyModifiers.length === 1 && keyToModifiers(e.key).includes(keyModifiers[0])) return false; const systemKeyModifiers = ["ctrl", "shift", "alt", "meta", "cmd", "super"]; const selectedSystemKeyModifiers = systemKeyModifiers.filter((modifier) => keyModifiers.includes(modifier)); keyModifiers = keyModifiers.filter((i) => !selectedSystemKeyModifiers.includes(i)); if (selectedSystemKeyModifiers.length > 0) { const activelyPressedKeyModifiers = selectedSystemKeyModifiers.filter((modifier) => { if (modifier === "cmd" || modifier === "super") modifier = "meta"; return e[`${modifier}Key`]; }); if (activelyPressedKeyModifiers.length === selectedSystemKeyModifiers.length) { if (keyToModifiers(e.key).includes(keyModifiers[0])) return false; } } return true; } function keyToModifiers(key) { if (!key) return []; key = kebabCase2(key); let modifierToKeyMap = { ctrl: "control", slash: "/", space: "-", spacebar: "-", cmd: "meta", esc: "escape", up: "arrow-up", down: "arrow-down", left: "arrow-left", right: "arrow-right", period: ".", equal: "=" }; modifierToKeyMap[key] = key; return Object.keys(modifierToKeyMap).map((modifier) => { if (modifierToKeyMap[modifier] === key) return modifier; }).filter((modifier) => modifier); } // packages/alpinejs/src/directives/x-model.js directive("model", (el, {modifiers, expression}, {effect: effect3, cleanup}) => { let evaluate2 = evaluateLater(el, expression); let assignmentExpression = `${expression} = rightSideOfExpression($event, ${expression})`; let evaluateAssignment = evaluateLater(el, assignmentExpression); var event = el.tagName.toLowerCase() === "select" || ["checkbox", "radio"].includes(el.type) || modifiers.includes("lazy") ? "change" : "input"; let assigmentFunction = generateAssignmentFunction(el, modifiers, expression); let removeListener = on(el, event, modifiers, (e) => { evaluateAssignment(() => { }, {scope: { $event: e, rightSideOfExpression: assigmentFunction }}); }); cleanup(() => removeListener()); let evaluateSetModel = evaluateLater(el, `${expression} = __placeholder`); el._x_model = { get() { let result; evaluate2((value) => result = value); return result; }, set(value) { evaluateSetModel(() => { }, {scope: {__placeholder: value}}); } }; el._x_forceModelUpdate = () => { evaluate2((value) => { if (value === void 0 && expression.match(/\./)) value = ""; window.fromModel = true; mutateDom(() => bind(el, "value", value)); delete window.fromModel; }); }; effect3(() => { if (modifiers.includes("unintrusive") && document.activeElement.isSameNode(el)) return; el._x_forceModelUpdate(); }); }); function generateAssignmentFunction(el, modifiers, expression) { if (el.type === "radio") { mutateDom(() => { if (!el.hasAttribute("name")) el.setAttribute("name", expression); }); } return (event, currentValue) => { return mutateDom(() => { if (event instanceof CustomEvent && event.detail !== void 0) { return event.detail || event.target.value; } else if (el.type === "checkbox") { if (Array.isArray(currentValue)) { let newValue = modifiers.includes("number") ? safeParseNumber(event.target.value) : event.target.value; return event.target.checked ? currentValue.concat([newValue]) : currentValue.filter((el2) => !checkedAttrLooseCompare2(el2, newValue)); } else { return event.target.checked; } } else if (el.tagName.toLowerCase() === "select" && el.multiple) { return modifiers.includes("number") ? Array.from(event.target.selectedOptions).map((option) => { let rawValue = option.value || option.text; return safeParseNumber(rawValue); }) : Array.from(event.target.selectedOptions).map((option) => { return option.value || option.text; }); } else { let rawValue = event.target.value; return modifiers.includes("number") ? safeParseNumber(rawValue) : modifiers.includes("trim") ? rawValue.trim() : rawValue; } }); }; } function safeParseNumber(rawValue) { let number = rawValue ? parseFloat(rawValue) : null; return isNumeric2(number) ? number : rawValue; } function checkedAttrLooseCompare2(valueA, valueB) { return valueA == valueB; } function isNumeric2(subject) { return !Array.isArray(subject) && !isNaN(subject); } // packages/alpinejs/src/directives/x-cloak.js directive("cloak", (el) => queueMicrotask(() => mutateDom(() => el.removeAttribute(prefix("cloak"))))); // packages/alpinejs/src/directives/x-init.js addInitSelector(() => `[${prefix("init")}]`); directive("init", skipDuringClone((el, {expression}) => { if (typeof expression === "string") { return !!expression.trim() && evaluate(el, expression, {}, false); } return evaluate(el, expression, {}, false); })); // packages/alpinejs/src/directives/x-text.js directive("text", (el, {expression}, {effect: effect3, evaluateLater: evaluateLater2}) => { let evaluate2 = evaluateLater2(expression); effect3(() => { evaluate2((value) => { mutateDom(() => { el.textContent = value; }); }); }); }); // packages/alpinejs/src/directives/x-html.js directive("html", (el, {expression}, {effect: effect3, evaluateLater: evaluateLater2}) => { let evaluate2 = evaluateLater2(expression); effect3(() => { evaluate2((value) => { el.innerHTML = value; }); }); }); // packages/alpinejs/src/directives/x-bind.js mapAttributes(startingWith(":", into(prefix("bind:")))); directive("bind", (el, {value, modifiers, expression, original}, {effect: effect3}) => { if (!value) return applyBindingsObject(el, expression, original, effect3); if (value === "key") return storeKeyForXFor(el, expression); let evaluate2 = evaluateLater(el, expression); effect3(() => evaluate2((result) => { if (result === void 0 && expression.match(/\./)) result = ""; mutateDom(() => bind(el, value, result, modifiers)); })); }); function applyBindingsObject(el, expression, original, effect3) { let getBindings = evaluateLater(el, expression); let cleanupRunners = []; effect3(() => { while (cleanupRunners.length) cleanupRunners.pop()(); getBindings((bindings) => { let attributes = Object.entries(bindings).map(([name, value]) => ({name, value})); attributes = attributes.filter((attr) => { return !(typeof attr.value === "object" && !Array.isArray(attr.value) && attr.value !== null); }); let staticAttributes = attributesOnly(attributes); attributes = attributes.map((attribute) => { if (staticAttributes.find((attr) => attr.name === attribute.name)) { return { name: `x-bind:${attribute.name}`, value: `"${attribute.value}"` }; } return attribute; }); directives(el, attributes, original).map((handle) => { cleanupRunners.push(handle.runCleanups); handle(); }); }); }); } function storeKeyForXFor(el, expression) { el._x_keyExpression = expression; } // packages/alpinejs/src/directives/x-data.js addRootSelector(() => `[${prefix("data")}]`); directive("data", skipDuringClone((el, {expression}, {cleanup}) => { expression = expression === "" ? "{}" : expression; let magicContext = {}; injectMagics(magicContext, el); let dataProviderContext = {}; injectDataProviders(dataProviderContext, magicContext); let data2 = evaluate(el, expression, {scope: dataProviderContext}); if (data2 === void 0) data2 = {}; injectMagics(data2, el); let reactiveData = reactive(data2); initInterceptors(reactiveData); let undo = addScopeToNode(el, reactiveData); reactiveData["init"] && evaluate(el, reactiveData["init"]); cleanup(() => { undo(); reactiveData["destroy"] && evaluate(el, reactiveData["destroy"]); }); })); // packages/alpinejs/src/directives/x-show.js directive("show", (el, {modifiers, expression}, {effect: effect3}) => { let evaluate2 = evaluateLater(el, expression); let hide = () => mutateDom(() => { el.style.display = "none"; el._x_isShown = false; }); let show = () => mutateDom(() => { if (el.style.length === 1 && el.style.display === "none") { el.removeAttribute("style"); } else { el.style.removeProperty("display"); } el._x_isShown = true; }); let clickAwayCompatibleShow = () => setTimeout(show); let toggle = once((value) => value ? show() : hide(), (value) => { if (typeof el._x_toggleAndCascadeWithTransitions === "function") { el._x_toggleAndCascadeWithTransitions(el, value, show, hide); } else { value ? clickAwayCompatibleShow() : hide(); } }); let oldValue; let firstTime = true; effect3(() => evaluate2((value) => { if (!firstTime && value === oldValue) return; if (modifiers.includes("immediate")) value ? clickAwayCompatibleShow() : hide(); toggle(value); oldValue = value; firstTime = false; })); }); // packages/alpinejs/src/directives/x-for.js directive("for", (el, {expression}, {effect: effect3, cleanup}) => { let iteratorNames = parseForExpression(expression); let evaluateItems = evaluateLater(el, iteratorNames.items); let evaluateKey = evaluateLater(el, el._x_keyExpression || "index"); el._x_prevKeys = []; el._x_lookup = {}; effect3(() => loop(el, iteratorNames, evaluateItems, evaluateKey)); cleanup(() => { Object.values(el._x_lookup).forEach((el2) => el2.remove()); delete el._x_prevKeys; delete el._x_lookup; }); }); function loop(el, iteratorNames, evaluateItems, evaluateKey) { let isObject = (i) => typeof i === "object" && !Array.isArray(i); let templateEl = el; evaluateItems((items) => { if (isNumeric3(items) && items >= 0) { items = Array.from(Array(items).keys(), (i) => i + 1); } if (items === void 0) items = []; let lookup = el._x_lookup; let prevKeys = el._x_prevKeys; let scopes = []; let keys = []; if (isObject(items)) { items = Object.entries(items).map(([key, value]) => { let scope = getIterationScopeVariables(iteratorNames, value, key, items); evaluateKey((value2) => keys.push(value2), {scope: {index: key, ...scope}}); scopes.push(scope); }); } else { for (let i = 0; i < items.length; i++) { let scope = getIterationScopeVariables(iteratorNames, items[i], i, items); evaluateKey((value) => keys.push(value), {scope: {index: i, ...scope}}); scopes.push(scope); } } let adds = []; let moves = []; let removes = []; let sames = []; for (let i = 0; i < prevKeys.length; i++) { let key = prevKeys[i]; if (keys.indexOf(key) === -1) removes.push(key); } prevKeys = prevKeys.filter((key) => !removes.includes(key)); let lastKey = "template"; for (let i = 0; i < keys.length; i++) { let key = keys[i]; let prevIndex = prevKeys.indexOf(key); if (prevIndex === -1) { prevKeys.splice(i, 0, key); adds.push([lastKey, i]); } else if (prevIndex !== i) { let keyInSpot = prevKeys.splice(i, 1)[0]; let keyForSpot = prevKeys.splice(prevIndex - 1, 1)[0]; prevKeys.splice(i, 0, keyForSpot); prevKeys.splice(prevIndex, 0, keyInSpot); moves.push([keyInSpot, keyForSpot]); } else { sames.push(key); } lastKey = key; } for (let i = 0; i < removes.length; i++) { let key = removes[i]; lookup[key].remove(); lookup[key] = null; delete lookup[key]; } for (let i = 0; i < moves.length; i++) { let [keyInSpot, keyForSpot] = moves[i]; let elInSpot = lookup[keyInSpot]; let elForSpot = lookup[keyForSpot]; let marker = document.createElement("div"); mutateDom(() => { elForSpot.after(marker); elInSpot.after(elForSpot); marker.before(elInSpot); marker.remove(); }); refreshScope(elForSpot, scopes[keys.indexOf(keyForSpot)]); } for (let i = 0; i < adds.length; i++) { let [lastKey2, index] = adds[i]; let lastEl = lastKey2 === "template" ? templateEl : lookup[lastKey2]; let scope = scopes[index]; let key = keys[index]; let clone2 = document.importNode(templateEl.content, true).firstElementChild; addScopeToNode(clone2, reactive(scope), templateEl); mutateDom(() => { lastEl.after(clone2); initTree(clone2); }); if (typeof key === "object") { warn("x-for key cannot be an object, it must be a string or an integer", templateEl); } lookup[key] = clone2; } for (let i = 0; i < sames.length; i++) { refreshScope(lookup[sames[i]], scopes[keys.indexOf(sames[i])]); } templateEl._x_prevKeys = keys; }); } function parseForExpression(expression) { let forIteratorRE = /,([^,\}\]]*)(?:,([^,\}\]]*))?$/; let stripParensRE = /^\s*\(|\)\s*$/g; let forAliasRE = /([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/; let inMatch = expression.match(forAliasRE); if (!inMatch) return; let res = {}; res.items = inMatch[2].trim(); let item = inMatch[1].replace(stripParensRE, "").trim(); let iteratorMatch = item.match(forIteratorRE); if (iteratorMatch) { res.item = item.replace(forIteratorRE, "").trim(); res.index = iteratorMatch[1].trim(); if (iteratorMatch[2]) { res.collection = iteratorMatch[2].trim(); } } else { res.item = item; } return res; } function getIterationScopeVariables(iteratorNames, item, index, items) { let scopeVariables = {}; if (/^\[.*\]$/.test(iteratorNames.item) && Array.isArray(item)) { let names = iteratorNames.item.replace("[", "").replace("]", "").split(",").map((i) => i.trim()); names.forEach((name, i) => { scopeVariables[name] = item[i]; }); } else if (/^\{.*\}$/.test(iteratorNames.item) && !Array.isArray(item) && typeof item === "object") { let names = iteratorNames.item.replace("{", "").replace("}", "").split(",").map((i) => i.trim()); names.forEach((name) => { scopeVariables[name] = item[name]; }); } else { scopeVariables[iteratorNames.item] = item; } if (iteratorNames.index) scopeVariables[iteratorNames.index] = index; if (iteratorNames.collection) scopeVariables[iteratorNames.collection] = items; return scopeVariables; } function isNumeric3(subject) { return !Array.isArray(subject) && !isNaN(subject); } // packages/alpinejs/src/directives/x-ref.js function handler2() { } handler2.inline = (el, {expression}, {cleanup}) => { let root = closestRoot(el); if (!root._x_refs) root._x_refs = {}; root._x_refs[expression] = el; cleanup(() => delete root._x_refs[expression]); }; directive("ref", handler2); // packages/alpinejs/src/directives/x-if.js directive("if", (el, {expression}, {effect: effect3, cleanup}) => { let evaluate2 = evaluateLater(el, expression); let show = () => { if (el._x_currentIfEl) return el._x_currentIfEl; let clone2 = el.content.cloneNode(true).firstElementChild; addScopeToNode(clone2, {}, el); mutateDom(() => { el.after(clone2); initTree(clone2); }); el._x_currentIfEl = clone2; el._x_undoIf = () => { clone2.remove(); delete el._x_currentIfEl; }; return clone2; }; let hide = () => { if (!el._x_undoIf) return; el._x_undoIf(); delete el._x_undoIf; }; effect3(() => evaluate2((value) => { value ? show() : hide(); })); cleanup(() => el._x_undoIf && el._x_undoIf()); }); // packages/alpinejs/src/directives/x-on.js mapAttributes(startingWith("@", into(prefix("on:")))); directive("on", skipDuringClone((el, {value, modifiers, expression}, {cleanup}) => { let evaluate2 = expression ? evaluateLater(el, expression) : () => { }; let removeListener = on(el, value, modifiers, (e) => { evaluate2(() => { }, {scope: {$event: e}, params: [e]}); }); cleanup(() => removeListener()); })); // packages/alpinejs/src/index.js alpine_default.setEvaluator(normalEvaluator); alpine_default.setReactivityEngine({reactive: import_reactivity9.reactive, effect: import_reactivity9.effect, release: import_reactivity9.stop, raw: import_reactivity9.toRaw}); var src_default = alpine_default; // packages/alpinejs/builds/module.js var module_default = src_default; /***/ }), /***/ "./node_modules/axios/index.js": /*!*************************************!*\ !*** ./node_modules/axios/index.js ***! \*************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { module.exports = __webpack_require__(/*! ./lib/axios */ "./node_modules/axios/lib/axios.js"); /***/ }), /***/ "./node_modules/axios/lib/adapters/xhr.js": /*!************************************************!*\ !*** ./node_modules/axios/lib/adapters/xhr.js ***! \************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); var settle = __webpack_require__(/*! ./../core/settle */ "./node_modules/axios/lib/core/settle.js"); var cookies = __webpack_require__(/*! ./../helpers/cookies */ "./node_modules/axios/lib/helpers/cookies.js"); var buildURL = __webpack_require__(/*! ./../helpers/buildURL */ "./node_modules/axios/lib/helpers/buildURL.js"); var buildFullPath = __webpack_require__(/*! ../core/buildFullPath */ "./node_modules/axios/lib/core/buildFullPath.js"); var parseHeaders = __webpack_require__(/*! ./../helpers/parseHeaders */ "./node_modules/axios/lib/helpers/parseHeaders.js"); var isURLSameOrigin = __webpack_require__(/*! ./../helpers/isURLSameOrigin */ "./node_modules/axios/lib/helpers/isURLSameOrigin.js"); var createError = __webpack_require__(/*! ../core/createError */ "./node_modules/axios/lib/core/createError.js"); module.exports = function xhrAdapter(config) { return new Promise(function dispatchXhrRequest(resolve, reject) { var requestData = config.data; var requestHeaders = config.headers; var responseType = config.responseType; if (utils.isFormData(requestData)) { delete requestHeaders['Content-Type']; // Let the browser set it } var request = new XMLHttpRequest(); // HTTP basic authentication if (config.auth) { var username = config.auth.username || ''; var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ''; requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); } var fullPath = buildFullPath(config.baseURL, config.url); request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); // Set the request timeout in MS request.timeout = config.timeout; function onloadend() { if (!request) { return; } // Prepare the response var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; var responseData = !responseType || responseType === 'text' || responseType === 'json' ? request.responseText : request.response; var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, request: request }; settle(resolve, reject, response); // Clean up request request = null; } if ('onloadend' in request) { // Use onloadend if available request.onloadend = onloadend; } else { // Listen for ready state to emulate onloadend request.onreadystatechange = function handleLoad() { if (!request || request.readyState !== 4) { return; } // The request errored out and we didn't get a response, this will be // handled by onerror instead // With one exception: request that using file: protocol, most browsers // will return status as 0 even though it's a successful request if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { return; } // readystate handler is calling before onerror or ontimeout handlers, // so we should call onloadend on the next 'tick' setTimeout(onloadend); }; } // Handle browser request cancellation (as opposed to a manual cancellation) request.onabort = function handleAbort() { if (!request) { return; } reject(createError('Request aborted', config, 'ECONNABORTED', request)); // Clean up request request = null; }; // Handle low level network errors request.onerror = function handleError() { // Real errors are hidden from us by the browser // onerror should only fire if it's a network error reject(createError('Network Error', config, null, request)); // Clean up request request = null; }; // Handle timeout request.ontimeout = function handleTimeout() { var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; if (config.timeoutErrorMessage) { timeoutErrorMessage = config.timeoutErrorMessage; } reject(createError( timeoutErrorMessage, config, config.transitional && config.transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED', request)); // Clean up request request = null; }; // Add xsrf header // This is only done if running in a standard browser environment. // Specifically not if we're in a web worker, or react-native. if (utils.isStandardBrowserEnv()) { // Add xsrf header var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? cookies.read(config.xsrfCookieName) : undefined; if (xsrfValue) { requestHeaders[config.xsrfHeaderName] = xsrfValue; } } // Add headers to the request if ('setRequestHeader' in request) { utils.forEach(requestHeaders, function setRequestHeader(val, key) { if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { // Remove Content-Type if data is undefined delete requestHeaders[key]; } else { // Otherwise add header to the request request.setRequestHeader(key, val); } }); } // Add withCredentials to request if needed if (!utils.isUndefined(config.withCredentials)) { request.withCredentials = !!config.withCredentials; } // Add responseType to request if needed if (responseType && responseType !== 'json') { request.responseType = config.responseType; } // Handle progress if needed if (typeof config.onDownloadProgress === 'function') { request.addEventListener('progress', config.onDownloadProgress); } // Not all browsers support upload events if (typeof config.onUploadProgress === 'function' && request.upload) { request.upload.addEventListener('progress', config.onUploadProgress); } if (config.cancelToken) { // Handle cancellation config.cancelToken.promise.then(function onCanceled(cancel) { if (!request) { return; } request.abort(); reject(cancel); // Clean up request request = null; }); } if (!requestData) { requestData = null; } // Send the request request.send(requestData); }); }; /***/ }), /***/ "./node_modules/axios/lib/axios.js": /*!*****************************************!*\ !*** ./node_modules/axios/lib/axios.js ***! \*****************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./utils */ "./node_modules/axios/lib/utils.js"); var bind = __webpack_require__(/*! ./helpers/bind */ "./node_modules/axios/lib/helpers/bind.js"); var Axios = __webpack_require__(/*! ./core/Axios */ "./node_modules/axios/lib/core/Axios.js"); var mergeConfig = __webpack_require__(/*! ./core/mergeConfig */ "./node_modules/axios/lib/core/mergeConfig.js"); var defaults = __webpack_require__(/*! ./defaults */ "./node_modules/axios/lib/defaults.js"); /** * Create an instance of Axios * * @param {Object} defaultConfig The default config for the instance * @return {Axios} A new instance of Axios */ function createInstance(defaultConfig) { var context = new Axios(defaultConfig); var instance = bind(Axios.prototype.request, context); // Copy axios.prototype to instance utils.extend(instance, Axios.prototype, context); // Copy context to instance utils.extend(instance, context); return instance; } // Create the default instance to be exported var axios = createInstance(defaults); // Expose Axios class to allow class inheritance axios.Axios = Axios; // Factory for creating new instances axios.create = function create(instanceConfig) { return createInstance(mergeConfig(axios.defaults, instanceConfig)); }; // Expose Cancel & CancelToken axios.Cancel = __webpack_require__(/*! ./cancel/Cancel */ "./node_modules/axios/lib/cancel/Cancel.js"); axios.CancelToken = __webpack_require__(/*! ./cancel/CancelToken */ "./node_modules/axios/lib/cancel/CancelToken.js"); axios.isCancel = __webpack_require__(/*! ./cancel/isCancel */ "./node_modules/axios/lib/cancel/isCancel.js"); // Expose all/spread axios.all = function all(promises) { return Promise.all(promises); }; axios.spread = __webpack_require__(/*! ./helpers/spread */ "./node_modules/axios/lib/helpers/spread.js"); // Expose isAxiosError axios.isAxiosError = __webpack_require__(/*! ./helpers/isAxiosError */ "./node_modules/axios/lib/helpers/isAxiosError.js"); module.exports = axios; // Allow use of default import syntax in TypeScript module.exports["default"] = axios; /***/ }), /***/ "./node_modules/axios/lib/cancel/Cancel.js": /*!*************************************************!*\ !*** ./node_modules/axios/lib/cancel/Cancel.js ***! \*************************************************/ /***/ ((module) => { "use strict"; /** * A `Cancel` is an object that is thrown when an operation is canceled. * * @class * @param {string=} message The message. */ function Cancel(message) { this.message = message; } Cancel.prototype.toString = function toString() { return 'Cancel' + (this.message ? ': ' + this.message : ''); }; Cancel.prototype.__CANCEL__ = true; module.exports = Cancel; /***/ }), /***/ "./node_modules/axios/lib/cancel/CancelToken.js": /*!******************************************************!*\ !*** ./node_modules/axios/lib/cancel/CancelToken.js ***! \******************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var Cancel = __webpack_require__(/*! ./Cancel */ "./node_modules/axios/lib/cancel/Cancel.js"); /** * A `CancelToken` is an object that can be used to request cancellation of an operation. * * @class * @param {Function} executor The executor function. */ function CancelToken(executor) { if (typeof executor !== 'function') { throw new TypeError('executor must be a function.'); } var resolvePromise; this.promise = new Promise(function promiseExecutor(resolve) { resolvePromise = resolve; }); var token = this; executor(function cancel(message) { if (token.reason) { // Cancellation has already been requested return; } token.reason = new Cancel(message); resolvePromise(token.reason); }); } /** * Throws a `Cancel` if cancellation has been requested. */ CancelToken.prototype.throwIfRequested = function throwIfRequested() { if (this.reason) { throw this.reason; } }; /** * Returns an object that contains a new `CancelToken` and a function that, when called, * cancels the `CancelToken`. */ CancelToken.source = function source() { var cancel; var token = new CancelToken(function executor(c) { cancel = c; }); return { token: token, cancel: cancel }; }; module.exports = CancelToken; /***/ }), /***/ "./node_modules/axios/lib/cancel/isCancel.js": /*!***************************************************!*\ !*** ./node_modules/axios/lib/cancel/isCancel.js ***! \***************************************************/ /***/ ((module) => { "use strict"; module.exports = function isCancel(value) { return !!(value && value.__CANCEL__); }; /***/ }), /***/ "./node_modules/axios/lib/core/Axios.js": /*!**********************************************!*\ !*** ./node_modules/axios/lib/core/Axios.js ***! \**********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); var buildURL = __webpack_require__(/*! ../helpers/buildURL */ "./node_modules/axios/lib/helpers/buildURL.js"); var InterceptorManager = __webpack_require__(/*! ./InterceptorManager */ "./node_modules/axios/lib/core/InterceptorManager.js"); var dispatchRequest = __webpack_require__(/*! ./dispatchRequest */ "./node_modules/axios/lib/core/dispatchRequest.js"); var mergeConfig = __webpack_require__(/*! ./mergeConfig */ "./node_modules/axios/lib/core/mergeConfig.js"); var validator = __webpack_require__(/*! ../helpers/validator */ "./node_modules/axios/lib/helpers/validator.js"); var validators = validator.validators; /** * Create a new instance of Axios * * @param {Object} instanceConfig The default config for the instance */ function Axios(instanceConfig) { this.defaults = instanceConfig; this.interceptors = { request: new InterceptorManager(), response: new InterceptorManager() }; } /** * Dispatch a request * * @param {Object} config The config specific for this request (merged with this.defaults) */ Axios.prototype.request = function request(config) { /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API if (typeof config === 'string') { config = arguments[1] || {}; config.url = arguments[0]; } else { config = config || {}; } config = mergeConfig(this.defaults, config); // Set config.method if (config.method) { config.method = config.method.toLowerCase(); } else if (this.defaults.method) { config.method = this.defaults.method.toLowerCase(); } else { config.method = 'get'; } var transitional = config.transitional; if (transitional !== undefined) { validator.assertOptions(transitional, { silentJSONParsing: validators.transitional(validators.boolean, '1.0.0'), forcedJSONParsing: validators.transitional(validators.boolean, '1.0.0'), clarifyTimeoutError: validators.transitional(validators.boolean, '1.0.0') }, false); } // filter out skipped interceptors var requestInterceptorChain = []; var synchronousRequestInterceptors = true; this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) { return; } synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); }); var responseInterceptorChain = []; this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); }); var promise; if (!synchronousRequestInterceptors) { var chain = [dispatchRequest, undefined]; Array.prototype.unshift.apply(chain, requestInterceptorChain); chain = chain.concat(responseInterceptorChain); promise = Promise.resolve(config); while (chain.length) { promise = promise.then(chain.shift(), chain.shift()); } return promise; } var newConfig = config; while (requestInterceptorChain.length) { var onFulfilled = requestInterceptorChain.shift(); var onRejected = requestInterceptorChain.shift(); try { newConfig = onFulfilled(newConfig); } catch (error) { onRejected(error); break; } } try { promise = dispatchRequest(newConfig); } catch (error) { return Promise.reject(error); } while (responseInterceptorChain.length) { promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); } return promise; }; Axios.prototype.getUri = function getUri(config) { config = mergeConfig(this.defaults, config); return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); }; // Provide aliases for supported request methods utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, config) { return this.request(mergeConfig(config || {}, { method: method, url: url, data: (config || {}).data })); }; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, data, config) { return this.request(mergeConfig(config || {}, { method: method, url: url, data: data })); }; }); module.exports = Axios; /***/ }), /***/ "./node_modules/axios/lib/core/InterceptorManager.js": /*!***********************************************************!*\ !*** ./node_modules/axios/lib/core/InterceptorManager.js ***! \***********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); function InterceptorManager() { this.handlers = []; } /** * Add a new interceptor to the stack * * @param {Function} fulfilled The function to handle `then` for a `Promise` * @param {Function} rejected The function to handle `reject` for a `Promise` * * @return {Number} An ID used to remove interceptor later */ InterceptorManager.prototype.use = function use(fulfilled, rejected, options) { this.handlers.push({ fulfilled: fulfilled, rejected: rejected, synchronous: options ? options.synchronous : false, runWhen: options ? options.runWhen : null }); return this.handlers.length - 1; }; /** * Remove an interceptor from the stack * * @param {Number} id The ID that was returned by `use` */ InterceptorManager.prototype.eject = function eject(id) { if (this.handlers[id]) { this.handlers[id] = null; } }; /** * Iterate over all the registered interceptors * * This method is particularly useful for skipping over any * interceptors that may have become `null` calling `eject`. * * @param {Function} fn The function to call for each interceptor */ InterceptorManager.prototype.forEach = function forEach(fn) { utils.forEach(this.handlers, function forEachHandler(h) { if (h !== null) { fn(h); } }); }; module.exports = InterceptorManager; /***/ }), /***/ "./node_modules/axios/lib/core/buildFullPath.js": /*!******************************************************!*\ !*** ./node_modules/axios/lib/core/buildFullPath.js ***! \******************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var isAbsoluteURL = __webpack_require__(/*! ../helpers/isAbsoluteURL */ "./node_modules/axios/lib/helpers/isAbsoluteURL.js"); var combineURLs = __webpack_require__(/*! ../helpers/combineURLs */ "./node_modules/axios/lib/helpers/combineURLs.js"); /** * Creates a new URL by combining the baseURL with the requestedURL, * only when the requestedURL is not already an absolute URL. * If the requestURL is absolute, this function returns the requestedURL untouched. * * @param {string} baseURL The base URL * @param {string} requestedURL Absolute or relative URL to combine * @returns {string} The combined full path */ module.exports = function buildFullPath(baseURL, requestedURL) { if (baseURL && !isAbsoluteURL(requestedURL)) { return combineURLs(baseURL, requestedURL); } return requestedURL; }; /***/ }), /***/ "./node_modules/axios/lib/core/createError.js": /*!****************************************************!*\ !*** ./node_modules/axios/lib/core/createError.js ***! \****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var enhanceError = __webpack_require__(/*! ./enhanceError */ "./node_modules/axios/lib/core/enhanceError.js"); /** * Create an Error with the specified message, config, error code, request and response. * * @param {string} message The error message. * @param {Object} config The config. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The created error. */ module.exports = function createError(message, config, code, request, response) { var error = new Error(message); return enhanceError(error, config, code, request, response); }; /***/ }), /***/ "./node_modules/axios/lib/core/dispatchRequest.js": /*!********************************************************!*\ !*** ./node_modules/axios/lib/core/dispatchRequest.js ***! \********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); var transformData = __webpack_require__(/*! ./transformData */ "./node_modules/axios/lib/core/transformData.js"); var isCancel = __webpack_require__(/*! ../cancel/isCancel */ "./node_modules/axios/lib/cancel/isCancel.js"); var defaults = __webpack_require__(/*! ../defaults */ "./node_modules/axios/lib/defaults.js"); /** * Throws a `Cancel` if cancellation has been requested. */ function throwIfCancellationRequested(config) { if (config.cancelToken) { config.cancelToken.throwIfRequested(); } } /** * Dispatch a request to the server using the configured adapter. * * @param {object} config The config that is to be used for the request * @returns {Promise} The Promise to be fulfilled */ module.exports = function dispatchRequest(config) { throwIfCancellationRequested(config); // Ensure headers exist config.headers = config.headers || {}; // Transform request data config.data = transformData.call( config, config.data, config.headers, config.transformRequest ); // Flatten headers config.headers = utils.merge( config.headers.common || {}, config.headers[config.method] || {}, config.headers ); utils.forEach( ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], function cleanHeaderConfig(method) { delete config.headers[method]; } ); var adapter = config.adapter || defaults.adapter; return adapter(config).then(function onAdapterResolution(response) { throwIfCancellationRequested(config); // Transform response data response.data = transformData.call( config, response.data, response.headers, config.transformResponse ); return response; }, function onAdapterRejection(reason) { if (!isCancel(reason)) { throwIfCancellationRequested(config); // Transform response data if (reason && reason.response) { reason.response.data = transformData.call( config, reason.response.data, reason.response.headers, config.transformResponse ); } } return Promise.reject(reason); }); }; /***/ }), /***/ "./node_modules/axios/lib/core/enhanceError.js": /*!*****************************************************!*\ !*** ./node_modules/axios/lib/core/enhanceError.js ***! \*****************************************************/ /***/ ((module) => { "use strict"; /** * Update an Error with the specified config, error code, and response. * * @param {Error} error The error to update. * @param {Object} config The config. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The error. */ module.exports = function enhanceError(error, config, code, request, response) { error.config = config; if (code) { error.code = code; } error.request = request; error.response = response; error.isAxiosError = true; error.toJSON = function toJSON() { return { // Standard message: this.message, name: this.name, // Microsoft description: this.description, number: this.number, // Mozilla fileName: this.fileName, lineNumber: this.lineNumber, columnNumber: this.columnNumber, stack: this.stack, // Axios config: this.config, code: this.code }; }; return error; }; /***/ }), /***/ "./node_modules/axios/lib/core/mergeConfig.js": /*!****************************************************!*\ !*** ./node_modules/axios/lib/core/mergeConfig.js ***! \****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ../utils */ "./node_modules/axios/lib/utils.js"); /** * Config-specific merge-function which creates a new config-object * by merging two configuration objects together. * * @param {Object} config1 * @param {Object} config2 * @returns {Object} New object resulting from merging config2 to config1 */ module.exports = function mergeConfig(config1, config2) { // eslint-disable-next-line no-param-reassign config2 = config2 || {}; var config = {}; var valueFromConfig2Keys = ['url', 'method', 'data']; var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params']; var defaultToConfig2Keys = [ 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer', 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress', 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent', 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding' ]; var directMergeKeys = ['validateStatus']; function getMergedValue(target, source) { if (utils.isPlainObject(target) && utils.isPlainObject(source)) { return utils.merge(target, source); } else if (utils.isPlainObject(source)) { return utils.merge({}, source); } else if (utils.isArray(source)) { return source.slice(); } return source; } function mergeDeepProperties(prop) { if (!utils.isUndefined(config2[prop])) { config[prop] = getMergedValue(config1[prop], config2[prop]); } else if (!utils.isUndefined(config1[prop])) { config[prop] = getMergedValue(undefined, config1[prop]); } } utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { if (!utils.isUndefined(config2[prop])) { config[prop] = getMergedValue(undefined, config2[prop]); } }); utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties); utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { if (!utils.isUndefined(config2[prop])) { config[prop] = getMergedValue(undefined, config2[prop]); } else if (!utils.isUndefined(config1[prop])) { config[prop] = getMergedValue(undefined, config1[prop]); } }); utils.forEach(directMergeKeys, function merge(prop) { if (prop in config2) { config[prop] = getMergedValue(config1[prop], config2[prop]); } else if (prop in config1) { config[prop] = getMergedValue(undefined, config1[prop]); } }); var axiosKeys = valueFromConfig2Keys .concat(mergeDeepPropertiesKeys) .concat(defaultToConfig2Keys) .concat(directMergeKeys); var otherKeys = Object .keys(config1) .concat(Object.keys(config2)) .filter(function filterAxiosKeys(key) { return axiosKeys.indexOf(key) === -1; }); utils.forEach(otherKeys, mergeDeepProperties); return config; }; /***/ }), /***/ "./node_modules/axios/lib/core/settle.js": /*!***********************************************!*\ !*** ./node_modules/axios/lib/core/settle.js ***! \***********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var createError = __webpack_require__(/*! ./createError */ "./node_modules/axios/lib/core/createError.js"); /** * Resolve or reject a Promise based on response status. * * @param {Function} resolve A function that resolves the promise. * @param {Function} reject A function that rejects the promise. * @param {object} response The response. */ module.exports = function settle(resolve, reject, response) { var validateStatus = response.config.validateStatus; if (!response.status || !validateStatus || validateStatus(response.status)) { resolve(response); } else { reject(createError( 'Request failed with status code ' + response.status, response.config, null, response.request, response )); } }; /***/ }), /***/ "./node_modules/axios/lib/core/transformData.js": /*!******************************************************!*\ !*** ./node_modules/axios/lib/core/transformData.js ***! \******************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); var defaults = __webpack_require__(/*! ./../defaults */ "./node_modules/axios/lib/defaults.js"); /** * Transform the data for a request or a response * * @param {Object|String} data The data to be transformed * @param {Array} headers The headers for the request or response * @param {Array|Function} fns A single function or Array of functions * @returns {*} The resulting transformed data */ module.exports = function transformData(data, headers, fns) { var context = this || defaults; /*eslint no-param-reassign:0*/ utils.forEach(fns, function transform(fn) { data = fn.call(context, data, headers); }); return data; }; /***/ }), /***/ "./node_modules/axios/lib/defaults.js": /*!********************************************!*\ !*** ./node_modules/axios/lib/defaults.js ***! \********************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; /* provided dependency */ var process = __webpack_require__(/*! process/browser.js */ "./node_modules/process/browser.js"); var utils = __webpack_require__(/*! ./utils */ "./node_modules/axios/lib/utils.js"); var normalizeHeaderName = __webpack_require__(/*! ./helpers/normalizeHeaderName */ "./node_modules/axios/lib/helpers/normalizeHeaderName.js"); var enhanceError = __webpack_require__(/*! ./core/enhanceError */ "./node_modules/axios/lib/core/enhanceError.js"); var DEFAULT_CONTENT_TYPE = { 'Content-Type': 'application/x-www-form-urlencoded' }; function setContentTypeIfUnset(headers, value) { if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { headers['Content-Type'] = value; } } function getDefaultAdapter() { var adapter; if (typeof XMLHttpRequest !== 'undefined') { // For browsers use XHR adapter adapter = __webpack_require__(/*! ./adapters/xhr */ "./node_modules/axios/lib/adapters/xhr.js"); } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { // For node use HTTP adapter adapter = __webpack_require__(/*! ./adapters/http */ "./node_modules/axios/lib/adapters/xhr.js"); } return adapter; } function stringifySafely(rawValue, parser, encoder) { if (utils.isString(rawValue)) { try { (parser || JSON.parse)(rawValue); return utils.trim(rawValue); } catch (e) { if (e.name !== 'SyntaxError') { throw e; } } } return (encoder || JSON.stringify)(rawValue); } var defaults = { transitional: { silentJSONParsing: true, forcedJSONParsing: true, clarifyTimeoutError: false }, adapter: getDefaultAdapter(), transformRequest: [function transformRequest(data, headers) { normalizeHeaderName(headers, 'Accept'); normalizeHeaderName(headers, 'Content-Type'); if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isBuffer(data) || utils.isStream(data) || utils.isFile(data) || utils.isBlob(data) ) { return data; } if (utils.isArrayBufferView(data)) { return data.buffer; } if (utils.isURLSearchParams(data)) { setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); return data.toString(); } if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) { setContentTypeIfUnset(headers, 'application/json'); return stringifySafely(data); } return data; }], transformResponse: [function transformResponse(data) { var transitional = this.transitional; var silentJSONParsing = transitional && transitional.silentJSONParsing; var forcedJSONParsing = transitional && transitional.forcedJSONParsing; var strictJSONParsing = !silentJSONParsing && this.responseType === 'json'; if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) { try { return JSON.parse(data); } catch (e) { if (strictJSONParsing) { if (e.name === 'SyntaxError') { throw enhanceError(e, this, 'E_JSON_PARSE'); } throw e; } } } return data; }], /** * A timeout in milliseconds to abort a request. If set to 0 (default) a * timeout is not created. */ timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, maxBodyLength: -1, validateStatus: function validateStatus(status) { return status >= 200 && status < 300; } }; defaults.headers = { common: { 'Accept': 'application/json, text/plain, */*' } }; utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { defaults.headers[method] = {}; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); }); module.exports = defaults; /***/ }), /***/ "./node_modules/axios/lib/helpers/bind.js": /*!************************************************!*\ !*** ./node_modules/axios/lib/helpers/bind.js ***! \************************************************/ /***/ ((module) => { "use strict"; module.exports = function bind(fn, thisArg) { return function wrap() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } return fn.apply(thisArg, args); }; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/buildURL.js": /*!****************************************************!*\ !*** ./node_modules/axios/lib/helpers/buildURL.js ***! \****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); function encode(val) { return encodeURIComponent(val). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%20/g, '+'). replace(/%5B/gi, '['). replace(/%5D/gi, ']'); } /** * Build a URL by appending params to the end * * @param {string} url The base of the url (e.g., http://www.google.com) * @param {object} [params] The params to be appended * @returns {string} The formatted url */ module.exports = function buildURL(url, params, paramsSerializer) { /*eslint no-param-reassign:0*/ if (!params) { return url; } var serializedParams; if (paramsSerializer) { serializedParams = paramsSerializer(params); } else if (utils.isURLSearchParams(params)) { serializedParams = params.toString(); } else { var parts = []; utils.forEach(params, function serialize(val, key) { if (val === null || typeof val === 'undefined') { return; } if (utils.isArray(val)) { key = key + '[]'; } else { val = [val]; } utils.forEach(val, function parseValue(v) { if (utils.isDate(v)) { v = v.toISOString(); } else if (utils.isObject(v)) { v = JSON.stringify(v); } parts.push(encode(key) + '=' + encode(v)); }); }); serializedParams = parts.join('&'); } if (serializedParams) { var hashmarkIndex = url.indexOf('#'); if (hashmarkIndex !== -1) { url = url.slice(0, hashmarkIndex); } url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; } return url; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/combineURLs.js": /*!*******************************************************!*\ !*** ./node_modules/axios/lib/helpers/combineURLs.js ***! \*******************************************************/ /***/ ((module) => { "use strict"; /** * Creates a new URL by combining the specified URLs * * @param {string} baseURL The base URL * @param {string} relativeURL The relative URL * @returns {string} The combined URL */ module.exports = function combineURLs(baseURL, relativeURL) { return relativeURL ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/cookies.js": /*!***************************************************!*\ !*** ./node_modules/axios/lib/helpers/cookies.js ***! \***************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs support document.cookie (function standardBrowserEnv() { return { write: function write(name, value, expires, path, domain, secure) { var cookie = []; cookie.push(name + '=' + encodeURIComponent(value)); if (utils.isNumber(expires)) { cookie.push('expires=' + new Date(expires).toGMTString()); } if (utils.isString(path)) { cookie.push('path=' + path); } if (utils.isString(domain)) { cookie.push('domain=' + domain); } if (secure === true) { cookie.push('secure'); } document.cookie = cookie.join('; '); }, read: function read(name) { var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); return (match ? decodeURIComponent(match[3]) : null); }, remove: function remove(name) { this.write(name, '', Date.now() - 86400000); } }; })() : // Non standard browser env (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return { write: function write() {}, read: function read() { return null; }, remove: function remove() {} }; })() ); /***/ }), /***/ "./node_modules/axios/lib/helpers/isAbsoluteURL.js": /*!*********************************************************!*\ !*** ./node_modules/axios/lib/helpers/isAbsoluteURL.js ***! \*********************************************************/ /***/ ((module) => { "use strict"; /** * Determines whether the specified URL is absolute * * @param {string} url The URL to test * @returns {boolean} True if the specified URL is absolute, otherwise false */ module.exports = function isAbsoluteURL(url) { // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL). // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed // by any combination of letters, digits, plus, period, or hyphen. return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); }; /***/ }), /***/ "./node_modules/axios/lib/helpers/isAxiosError.js": /*!********************************************************!*\ !*** ./node_modules/axios/lib/helpers/isAxiosError.js ***! \********************************************************/ /***/ ((module) => { "use strict"; /** * Determines whether the payload is an error thrown by Axios * * @param {*} payload The value to test * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false */ module.exports = function isAxiosError(payload) { return (typeof payload === 'object') && (payload.isAxiosError === true); }; /***/ }), /***/ "./node_modules/axios/lib/helpers/isURLSameOrigin.js": /*!***********************************************************!*\ !*** ./node_modules/axios/lib/helpers/isURLSameOrigin.js ***! \***********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs have full support of the APIs needed to test // whether the request URL is of the same origin as current location. (function standardBrowserEnv() { var msie = /(msie|trident)/i.test(navigator.userAgent); var urlParsingNode = document.createElement('a'); var originURL; /** * Parse a URL to discover it's components * * @param {String} url The URL to be parsed * @returns {Object} */ function resolveURL(url) { var href = url; if (msie) { // IE needs attribute set twice to normalize properties urlParsingNode.setAttribute('href', href); href = urlParsingNode.href; } urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname }; } originURL = resolveURL(window.location.href); /** * Determine if a URL shares the same origin as the current location * * @param {String} requestURL The URL to test * @returns {boolean} True if URL shares the same origin, otherwise false */ return function isURLSameOrigin(requestURL) { var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; return (parsed.protocol === originURL.protocol && parsed.host === originURL.host); }; })() : // Non standard browser envs (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return function isURLSameOrigin() { return true; }; })() ); /***/ }), /***/ "./node_modules/axios/lib/helpers/normalizeHeaderName.js": /*!***************************************************************!*\ !*** ./node_modules/axios/lib/helpers/normalizeHeaderName.js ***! \***************************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ../utils */ "./node_modules/axios/lib/utils.js"); module.exports = function normalizeHeaderName(headers, normalizedName) { utils.forEach(headers, function processHeader(value, name) { if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { headers[normalizedName] = value; delete headers[name]; } }); }; /***/ }), /***/ "./node_modules/axios/lib/helpers/parseHeaders.js": /*!********************************************************!*\ !*** ./node_modules/axios/lib/helpers/parseHeaders.js ***! \********************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); // Headers whose duplicates are ignored by node // c.f. https://nodejs.org/api/http.html#http_message_headers var ignoreDuplicateOf = [ 'age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent' ]; /** * Parse headers into an object * * ``` * Date: Wed, 27 Aug 2014 08:58:49 GMT * Content-Type: application/json * Connection: keep-alive * Transfer-Encoding: chunked * ``` * * @param {String} headers Headers needing to be parsed * @returns {Object} Headers parsed into an object */ module.exports = function parseHeaders(headers) { var parsed = {}; var key; var val; var i; if (!headers) { return parsed; } utils.forEach(headers.split('\n'), function parser(line) { i = line.indexOf(':'); key = utils.trim(line.substr(0, i)).toLowerCase(); val = utils.trim(line.substr(i + 1)); if (key) { if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { return; } if (key === 'set-cookie') { parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); } else { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } } }); return parsed; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/spread.js": /*!**************************************************!*\ !*** ./node_modules/axios/lib/helpers/spread.js ***! \**************************************************/ /***/ ((module) => { "use strict"; /** * Syntactic sugar for invoking a function and expanding an array for arguments. * * Common use case would be to use `Function.prototype.apply`. * * ```js * function f(x, y, z) {} * var args = [1, 2, 3]; * f.apply(null, args); * ``` * * With `spread` this example can be re-written. * * ```js * spread(function(x, y, z) {})([1, 2, 3]); * ``` * * @param {Function} callback * @returns {Function} */ module.exports = function spread(callback) { return function wrap(arr) { return callback.apply(null, arr); }; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/validator.js": /*!*****************************************************!*\ !*** ./node_modules/axios/lib/helpers/validator.js ***! \*****************************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var pkg = __webpack_require__(/*! ./../../package.json */ "./node_modules/axios/package.json"); var validators = {}; // eslint-disable-next-line func-names ['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) { validators[type] = function validator(thing) { return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type; }; }); var deprecatedWarnings = {}; var currentVerArr = pkg.version.split('.'); /** * Compare package versions * @param {string} version * @param {string?} thanVersion * @returns {boolean} */ function isOlderVersion(version, thanVersion) { var pkgVersionArr = thanVersion ? thanVersion.split('.') : currentVerArr; var destVer = version.split('.'); for (var i = 0; i < 3; i++) { if (pkgVersionArr[i] > destVer[i]) { return true; } else if (pkgVersionArr[i] < destVer[i]) { return false; } } return false; } /** * Transitional option validator * @param {function|boolean?} validator * @param {string?} version * @param {string} message * @returns {function} */ validators.transitional = function transitional(validator, version, message) { var isDeprecated = version && isOlderVersion(version); function formatMessage(opt, desc) { return '[Axios v' + pkg.version + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); } // eslint-disable-next-line func-names return function(value, opt, opts) { if (validator === false) { throw new Error(formatMessage(opt, ' has been removed in ' + version)); } if (isDeprecated && !deprecatedWarnings[opt]) { deprecatedWarnings[opt] = true; // eslint-disable-next-line no-console console.warn( formatMessage( opt, ' has been deprecated since v' + version + ' and will be removed in the near future' ) ); } return validator ? validator(value, opt, opts) : true; }; }; /** * Assert object's properties type * @param {object} options * @param {object} schema * @param {boolean?} allowUnknown */ function assertOptions(options, schema, allowUnknown) { if (typeof options !== 'object') { throw new TypeError('options must be an object'); } var keys = Object.keys(options); var i = keys.length; while (i-- > 0) { var opt = keys[i]; var validator = schema[opt]; if (validator) { var value = options[opt]; var result = value === undefined || validator(value, opt, options); if (result !== true) { throw new TypeError('option ' + opt + ' must be ' + result); } continue; } if (allowUnknown !== true) { throw Error('Unknown option ' + opt); } } } module.exports = { isOlderVersion: isOlderVersion, assertOptions: assertOptions, validators: validators }; /***/ }), /***/ "./node_modules/axios/lib/utils.js": /*!*****************************************!*\ !*** ./node_modules/axios/lib/utils.js ***! \*****************************************/ /***/ ((module, __unused_webpack_exports, __webpack_require__) => { "use strict"; var bind = __webpack_require__(/*! ./helpers/bind */ "./node_modules/axios/lib/helpers/bind.js"); // utils is a library of generic helper functions non-specific to axios var toString = Object.prototype.toString; /** * Determine if a value is an Array * * @param {Object} val The value to test * @returns {boolean} True if value is an Array, otherwise false */ function isArray(val) { return toString.call(val) === '[object Array]'; } /** * Determine if a value is undefined * * @param {Object} val The value to test * @returns {boolean} True if the value is undefined, otherwise false */ function isUndefined(val) { return typeof val === 'undefined'; } /** * Determine if a value is a Buffer * * @param {Object} val The value to test * @returns {boolean} True if value is a Buffer, otherwise false */ function isBuffer(val) { return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); } /** * Determine if a value is an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is an ArrayBuffer, otherwise false */ function isArrayBuffer(val) { return toString.call(val) === '[object ArrayBuffer]'; } /** * Determine if a value is a FormData * * @param {Object} val The value to test * @returns {boolean} True if value is an FormData, otherwise false */ function isFormData(val) { return (typeof FormData !== 'undefined') && (val instanceof FormData); } /** * Determine if a value is a view on an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false */ function isArrayBufferView(val) { var result; if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { result = ArrayBuffer.isView(val); } else { result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); } return result; } /** * Determine if a value is a String * * @param {Object} val The value to test * @returns {boolean} True if value is a String, otherwise false */ function isString(val) { return typeof val === 'string'; } /** * Determine if a value is a Number * * @param {Object} val The value to test * @returns {boolean} True if value is a Number, otherwise false */ function isNumber(val) { return typeof val === 'number'; } /** * Determine if a value is an Object * * @param {Object} val The value to test * @returns {boolean} True if value is an Object, otherwise false */ function isObject(val) { return val !== null && typeof val === 'object'; } /** * Determine if a value is a plain Object * * @param {Object} val The value to test * @return {boolean} True if value is a plain Object, otherwise false */ function isPlainObject(val) { if (toString.call(val) !== '[object Object]') { return false; } var prototype = Object.getPrototypeOf(val); return prototype === null || prototype === Object.prototype; } /** * Determine if a value is a Date * * @param {Object} val The value to test * @returns {boolean} True if value is a Date, otherwise false */ function isDate(val) { return toString.call(val) === '[object Date]'; } /** * Determine if a value is a File * * @param {Object} val The value to test * @returns {boolean} True if value is a File, otherwise false */ function isFile(val) { return toString.call(val) === '[object File]'; } /** * Determine if a value is a Blob * * @param {Object} val The value to test * @returns {boolean} True if value is a Blob, otherwise false */ function isBlob(val) { return toString.call(val) === '[object Blob]'; } /** * Determine if a value is a Function * * @param {Object} val The value to test * @returns {boolean} True if value is a Function, otherwise false */ function isFunction(val) { return toString.call(val) === '[object Function]'; } /** * Determine if a value is a Stream * * @param {Object} val The value to test * @returns {boolean} True if value is a Stream, otherwise false */ function isStream(val) { return isObject(val) && isFunction(val.pipe); } /** * Determine if a value is a URLSearchParams object * * @param {Object} val The value to test * @returns {boolean} True if value is a URLSearchParams object, otherwise false */ function isURLSearchParams(val) { return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; } /** * Trim excess whitespace off the beginning and end of a string * * @param {String} str The String to trim * @returns {String} The String freed of excess whitespace */ function trim(str) { return str.trim ? str.trim() : str.replace(/^\s+|\s+$/g, ''); } /** * Determine if we're running in a standard browser environment * * This allows axios to run in a web worker, and react-native. * Both environments support XMLHttpRequest, but not fully standard globals. * * web workers: * typeof window -> undefined * typeof document -> undefined * * react-native: * navigator.product -> 'ReactNative' * nativescript * navigator.product -> 'NativeScript' or 'NS' */ function isStandardBrowserEnv() { if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || navigator.product === 'NativeScript' || navigator.product === 'NS')) { return false; } return ( typeof window !== 'undefined' && typeof document !== 'undefined' ); } /** * Iterate over an Array or an Object invoking a function for each item. * * If `obj` is an Array callback will be called passing * the value, index, and complete array for each item. * * If 'obj' is an Object callback will be called passing * the value, key, and complete object for each property. * * @param {Object|Array} obj The object to iterate * @param {Function} fn The callback to invoke for each item */ function forEach(obj, fn) { // Don't bother if no value provided if (obj === null || typeof obj === 'undefined') { return; } // Force an array if not already something iterable if (typeof obj !== 'object') { /*eslint no-param-reassign:0*/ obj = [obj]; } if (isArray(obj)) { // Iterate over array values for (var i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } else { // Iterate over object keys for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { fn.call(null, obj[key], key, obj); } } } } /** * Accepts varargs expecting each argument to be an object, then * immutably merges the properties of each object and returns result. * * When multiple objects contain the same key the later object in * the arguments list will take precedence. * * Example: * * ```js * var result = merge({foo: 123}, {foo: 456}); * console.log(result.foo); // outputs 456 * ``` * * @param {Object} obj1 Object to merge * @returns {Object} Result of all merge properties */ function merge(/* obj1, obj2, obj3, ... */) { var result = {}; function assignValue(val, key) { if (isPlainObject(result[key]) && isPlainObject(val)) { result[key] = merge(result[key], val); } else if (isPlainObject(val)) { result[key] = merge({}, val); } else if (isArray(val)) { result[key] = val.slice(); } else { result[key] = val; } } for (var i = 0, l = arguments.length; i < l; i++) { forEach(arguments[i], assignValue); } return result; } /** * Extends object a by mutably adding to it the properties of object b. * * @param {Object} a The object to be extended * @param {Object} b The object to copy properties from * @param {Object} thisArg The object to bind function to * @return {Object} The resulting value of object a */ function extend(a, b, thisArg) { forEach(b, function assignValue(val, key) { if (thisArg && typeof val === 'function') { a[key] = bind(val, thisArg); } else { a[key] = val; } }); return a; } /** * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) * * @param {string} content with BOM * @return {string} content value without BOM */ function stripBOM(content) { if (content.charCodeAt(0) === 0xFEFF) { content = content.slice(1); } return content; } module.exports = { isArray: isArray, isArrayBuffer: isArrayBuffer, isBuffer: isBuffer, isFormData: isFormData, isArrayBufferView: isArrayBufferView, isString: isString, isNumber: isNumber, isObject: isObject, isPlainObject: isPlainObject, isUndefined: isUndefined, isDate: isDate, isFile: isFile, isBlob: isBlob, isFunction: isFunction, isStream: isStream, isURLSearchParams: isURLSearchParams, isStandardBrowserEnv: isStandardBrowserEnv, forEach: forEach, merge: merge, extend: extend, trim: trim, stripBOM: stripBOM }; /***/ }), /***/ "./resources/js/app.js": /*!*****************************!*\ !*** ./resources/js/app.js ***! \*****************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var alpinejs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! alpinejs */ "./node_modules/alpinejs/dist/module.esm.js"); __webpack_require__(/*! ./bootstrap */ "./resources/js/bootstrap.js"); window.Alpine = alpinejs__WEBPACK_IMPORTED_MODULE_0__["default"]; alpinejs__WEBPACK_IMPORTED_MODULE_0__["default"].start(); /***/ }), /***/ "./resources/js/bootstrap.js": /*!***********************************!*\ !*** ./resources/js/bootstrap.js ***! \***********************************/ /***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => { window._ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"); /** * We'll load the axios HTTP library which allows us to easily issue requests * to our Laravel back-end. This library automatically handles sending the * CSRF token as a header based on the value of the "XSRF" token cookie. */ window.axios = __webpack_require__(/*! axios */ "./node_modules/axios/index.js"); window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; /** * Echo exposes an expressive API for subscribing to channels and listening * for events that are broadcast by Laravel. Echo and event broadcasting * allows your team to easily build robust real-time web applications. */ // import Echo from 'laravel-echo'; // window.Pusher = require('pusher-js'); // window.Echo = new Echo({ // broadcaster: 'pusher', // key: process.env.MIX_PUSHER_APP_KEY, // cluster: process.env.MIX_PUSHER_APP_CLUSTER, // forceTLS: true // }); /***/ }), /***/ "./node_modules/lodash/lodash.js": /*!***************************************!*\ !*** ./node_modules/lodash/lodash.js ***! \***************************************/ /***/ (function(module, exports, __webpack_require__) { /* module decorator */ module = __webpack_require__.nmd(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.21'; /** 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', INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`'; /** 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 whitespace. */ var reTrimStart = /^\s+/; /** Used to match a single whitespace character. */ var reWhitespace = /\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 validate the `validate` option in `_.template` variable. * * Forbids characters which could potentially change the meaning of the function argument definition: * - "()," (modification of function parameters) * - "=" (default value) * - "[]{}" (destructuring of function parameters) * - "/" (beginning of a comment) * - whitespace */ var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; /** 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 __webpack_require__.g == 'object' && __webpack_require__.g && __webpack_require__.g.Object === Object && __webpack_require__.g; /** 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 = true && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && "object" == '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 `_.trim`. * * @private * @param {string} string The string to trim. * @returns {string} Returns the trimmed string. */ function baseTrim(string) { return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') : string; } /** * 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 `_.trim` and `_.trimEnd` to get the index of the last non-whitespace * character of `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the index of the last non-whitespace character. */ function trimmedEndIndex(string) { var index = string.length; while (index-- && reWhitespace.test(string.charAt(index))) {} return index; } /** * 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) { if (iteratees.length) { iteratees = arrayMap(iteratees, function(iteratee) { if (isArray(iteratee)) { return function(value) { return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); } } return iteratee; }); } else { iteratees = [identity]; } var index = -1; iteratees = arrayMap(iteratees, 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 (key === '__proto__' || key === 'constructor' || key === 'prototype') { return object; } 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) { var low = 0, high = array == null ? 0 : array.length; if (high === 0) { return 0; } value = iteratee(value); var 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; } // Check that cyclic values are equal. var arrStacked = stack.get(array); var othStacked = stack.get(other); if (arrStacked && othStacked) { return arrStacked == other && othStacked == array; } 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; } } // Check that cyclic values are equal. var objStacked = stack.get(object); var othStacked = stack.get(other); if (objStacked && othStacked) { return objStacked == other && othStacked == object; } 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'] * * // Combining several predicates using `_.overEvery` or `_.overSome`. * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); * // => objects for ['fred', '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': 30 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.sortBy(users, [function(o) { return o.user; }]); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] * * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['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 = baseTrim(value); 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 // to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in // and escape the comment, thus injecting code that gets evaled. var sourceURL = '//# sourceURL=' + (hasOwnProperty.call(options, 'sourceURL') ? (options.sourceURL + '').replace(/\s/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. var variable = hasOwnProperty.call(options, 'variable') && options.variable; if (!variable) { source = 'with (obj) {\n' + source + '\n}\n'; } // Throw an error if a forbidden character was found in `variable`, to prevent // potential command injection attacks. else if (reForbiddenIdentifierChars.test(variable)) { throw new Error(INVALID_TEMPL_VAR_ERROR_TEXT); } // 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 baseTrim(string); } 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.slice(0, trimmedEndIndex(string) + 1); } 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. * * **Note:** Multiple values can be checked by combining several matchers * using `_.overSome` * * @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 }] * * // Checking for several possible values * _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })])); * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { '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. * * **Note:** Multiple values can be checked by combining several matchers * using `_.overSome` * * @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 } * * // Checking for several possible values * _.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)])); * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { '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. * * Following shorthands are possible for providing predicates. * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate. * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them. * * @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. * * Following shorthands are possible for providing predicates. * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate. * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them. * * @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 matchesFunc = _.overSome([{ 'a': 1 }, { 'a': 2 }]) * var matchesPropertyFunc = _.overSome([['a', 1], ['a', 2]]) */ 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 {} }.call(this)); /***/ }), /***/ "./resources/css/app.css": /*!*******************************!*\ !*** ./resources/css/app.css ***! \*******************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { "use strict"; __webpack_require__.r(__webpack_exports__); // extracted by mini-css-extract-plugin /***/ }), /***/ "./node_modules/process/browser.js": /*!*****************************************!*\ !*** ./node_modules/process/browser.js ***! \*****************************************/ /***/ ((module) => { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }), /***/ "./node_modules/axios/package.json": /*!*****************************************!*\ !*** ./node_modules/axios/package.json ***! \*****************************************/ /***/ ((module) => { "use strict"; module.exports = JSON.parse('{"_from":"axios@^0.21","_id":"axios@0.21.4","_inBundle":false,"_integrity":"sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==","_location":"/axios","_phantomChildren":{},"_requested":{"type":"range","registry":true,"raw":"axios@^0.21","name":"axios","escapedName":"axios","rawSpec":"^0.21","saveSpec":null,"fetchSpec":"^0.21"},"_requiredBy":["#DEV:/"],"_resolved":"https://registry.npmjs.org/axios/-/axios-0.21.4.tgz","_shasum":"c67b90dc0568e5c1cf2b0b858c43ba28e2eda575","_spec":"axios@^0.21","_where":"C:\\\\laragon\\\\www\\\\Evaluation","author":{"name":"Matt Zabriskie"},"browser":{"./lib/adapters/http.js":"./lib/adapters/xhr.js"},"bugs":{"url":"https://github.com/axios/axios/issues"},"bundleDependencies":false,"bundlesize":[{"path":"./dist/axios.min.js","threshold":"5kB"}],"dependencies":{"follow-redirects":"^1.14.0"},"deprecated":false,"description":"Promise based HTTP client for the browser and node.js","devDependencies":{"coveralls":"^3.0.0","es6-promise":"^4.2.4","grunt":"^1.3.0","grunt-banner":"^0.6.0","grunt-cli":"^1.2.0","grunt-contrib-clean":"^1.1.0","grunt-contrib-watch":"^1.0.0","grunt-eslint":"^23.0.0","grunt-karma":"^4.0.0","grunt-mocha-test":"^0.13.3","grunt-ts":"^6.0.0-beta.19","grunt-webpack":"^4.0.2","istanbul-instrumenter-loader":"^1.0.0","jasmine-core":"^2.4.1","karma":"^6.3.2","karma-chrome-launcher":"^3.1.0","karma-firefox-launcher":"^2.1.0","karma-jasmine":"^1.1.1","karma-jasmine-ajax":"^0.1.13","karma-safari-launcher":"^1.0.0","karma-sauce-launcher":"^4.3.6","karma-sinon":"^1.0.5","karma-sourcemap-loader":"^0.3.8","karma-webpack":"^4.0.2","load-grunt-tasks":"^3.5.2","minimist":"^1.2.0","mocha":"^8.2.1","sinon":"^4.5.0","terser-webpack-plugin":"^4.2.3","typescript":"^4.0.5","url-search-params":"^0.10.0","webpack":"^4.44.2","webpack-dev-server":"^3.11.0"},"homepage":"https://axios-http.com","jsdelivr":"dist/axios.min.js","keywords":["xhr","http","ajax","promise","node"],"license":"MIT","main":"index.js","name":"axios","repository":{"type":"git","url":"git+https://github.com/axios/axios.git"},"scripts":{"build":"NODE_ENV=production grunt build","coveralls":"cat coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js","examples":"node ./examples/server.js","fix":"eslint --fix lib/**/*.js","postversion":"git push && git push --tags","preversion":"npm test","start":"node ./sandbox/server.js","test":"grunt test","version":"npm run build && grunt version && git add -A dist && git add CHANGELOG.md bower.json package.json"},"typings":"./index.d.ts","unpkg":"dist/axios.min.js","version":"0.21.4"}'); /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ id: moduleId, /******/ loaded: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = __webpack_modules__; /******/ /************************************************************************/ /******/ /* webpack/runtime/chunk loaded */ /******/ (() => { /******/ var deferred = []; /******/ __webpack_require__.O = (result, chunkIds, fn, priority) => { /******/ if(chunkIds) { /******/ priority = priority || 0; /******/ for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1]; /******/ deferred[i] = [chunkIds, fn, priority]; /******/ return; /******/ } /******/ var notFulfilled = Infinity; /******/ for (var i = 0; i < deferred.length; i++) { /******/ var [chunkIds, fn, priority] = deferred[i]; /******/ var fulfilled = true; /******/ for (var j = 0; j < chunkIds.length; j++) { /******/ if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) { /******/ chunkIds.splice(j--, 1); /******/ } else { /******/ fulfilled = false; /******/ if(priority < notFulfilled) notFulfilled = priority; /******/ } /******/ } /******/ if(fulfilled) { /******/ deferred.splice(i--, 1) /******/ var r = fn(); /******/ if (r !== undefined) result = r; /******/ } /******/ } /******/ return result; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/global */ /******/ (() => { /******/ __webpack_require__.g = (function() { /******/ if (typeof globalThis === 'object') return globalThis; /******/ try { /******/ return this || new Function('return this')(); /******/ } catch (e) { /******/ if (typeof window === 'object') return window; /******/ } /******/ })(); /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __webpack_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/node module decorator */ /******/ (() => { /******/ __webpack_require__.nmd = (module) => { /******/ module.paths = []; /******/ if (!module.children) module.children = []; /******/ return module; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/jsonp chunk loading */ /******/ (() => { /******/ // no baseURI /******/ /******/ // object to store loaded and loading chunks /******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched /******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded /******/ var installedChunks = { /******/ "/js/app": 0, /******/ "css/app": 0 /******/ }; /******/ /******/ // no chunk on demand loading /******/ /******/ // no prefetching /******/ /******/ // no preloaded /******/ /******/ // no HMR /******/ /******/ // no HMR manifest /******/ /******/ __webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0); /******/ /******/ // install a JSONP callback for chunk loading /******/ var webpackJsonpCallback = (parentChunkLoadingFunction, data) => { /******/ var [chunkIds, moreModules, runtime] = data; /******/ // add "moreModules" to the modules object, /******/ // then flag all "chunkIds" as loaded and fire callback /******/ var moduleId, chunkId, i = 0; /******/ if(chunkIds.some((id) => (installedChunks[id] !== 0))) { /******/ for(moduleId in moreModules) { /******/ if(__webpack_require__.o(moreModules, moduleId)) { /******/ __webpack_require__.m[moduleId] = moreModules[moduleId]; /******/ } /******/ } /******/ if(runtime) var result = runtime(__webpack_require__); /******/ } /******/ if(parentChunkLoadingFunction) parentChunkLoadingFunction(data); /******/ for(;i < chunkIds.length; i++) { /******/ chunkId = chunkIds[i]; /******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) { /******/ installedChunks[chunkId][0](); /******/ } /******/ installedChunks[chunkIds[i]] = 0; /******/ } /******/ return __webpack_require__.O(result); /******/ } /******/ /******/ var chunkLoadingGlobal = self["webpackChunk"] = self["webpackChunk"] || []; /******/ chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0)); /******/ chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal)); /******/ })(); /******/ /************************************************************************/ /******/ /******/ // startup /******/ // Load entry module and return exports /******/ // This entry module depends on other loaded chunks and execution need to be delayed /******/ __webpack_require__.O(undefined, ["css/app"], () => (__webpack_require__("./resources/js/app.js"))) /******/ var __webpack_exports__ = __webpack_require__.O(undefined, ["css/app"], () => (__webpack_require__("./resources/css/app.css"))) /******/ __webpack_exports__ = __webpack_require__.O(__webpack_exports__); /******/ /******/ })() ;
/// <reference path="E:\11.WepAPI\Fridge\Fridge\Fridge.WebClient\bower_components/jquery/dist/jquery.js" /> /// <reference path="E:\11.WepAPI\Fridge\Fridge\Fridge.WebClient\Scripts/_references.js" /> "use strict"; angular.module('app') .controller('HomeController', function ($scope, $rootScope, publicRequests, pagination) { $scope.pagination = pagination; $scope.pagination.bigCurrentPage = 1; //setup for Pagination (ui.bootstrap.pagination) $scope.recipes = []; $scope.slides = []; //recipes for carousel $scope.myInterval = 5000; $scope.noWrapSlides = false; $scope.isFirstPageLoad = true; $scope.getData = function () { var isReturnFromOtherPage = false; if (pagination.bigCurrentPage == 1 && $scope.isFirstPageLoad && sessionStorage["pageNo"] != undefined) { pagination.bigCurrentPage = parseInt(sessionStorage["pageNo"]); isReturnFromOtherPage = true; } publicRequests.getRecipesWithPaging($scope.pagination.bigCurrentPage) .success(function (data) { $scope.recipes = data.Result; $scope.pagination.bigTotalItems = data.NumPages * 10; //setup for Pagination if (!isReturnFromOtherPage && !$scope.isFirstPageLoad) { $scope.scrollTo("html body"); } else { $scope.isFirstPageLoad = false; } }) } $scope.getRandomRecipies = function () { publicRequests.getRandomRecipes(3) .success(function (data) { $scope.slides = data; }) } $scope.scrollTo = function (id) { var scrollTo = $(id); $('html, body').animate({ scrollTop: scrollTo.offset().top }, 1800); } //start point for controller $scope.getData(); $scope.getRandomRecipies(); });
'use strict'; const numeric = require("numeric"); function round(num){ return Math.round(num*10000000000)/10000000000; } function getNormalizationCoefficients(srcPts, dstPts, isInverse){ if(isInverse){ var tmp = dstPts; dstPts = srcPts; srcPts = tmp; } var r1 = [srcPts[0], srcPts[1], 1, 0, 0, 0, -1*dstPts[0]*srcPts[0], -1*dstPts[0]*srcPts[1]]; var r2 = [0, 0, 0, srcPts[0], srcPts[1], 1, -1*dstPts[1]*srcPts[0], -1*dstPts[1]*srcPts[1]]; var r3 = [srcPts[2], srcPts[3], 1, 0, 0, 0, -1*dstPts[2]*srcPts[2], -1*dstPts[2]*srcPts[3]]; var r4 = [0, 0, 0, srcPts[2], srcPts[3], 1, -1*dstPts[3]*srcPts[2], -1*dstPts[3]*srcPts[3]]; var r5 = [srcPts[4], srcPts[5], 1, 0, 0, 0, -1*dstPts[4]*srcPts[4], -1*dstPts[4]*srcPts[5]]; var r6 = [0, 0, 0, srcPts[4], srcPts[5], 1, -1*dstPts[5]*srcPts[4], -1*dstPts[5]*srcPts[5]]; var r7 = [srcPts[6], srcPts[7], 1, 0, 0, 0, -1*dstPts[6]*srcPts[6], -1*dstPts[6]*srcPts[7]]; var r8 = [0, 0, 0, srcPts[6], srcPts[7], 1, -1*dstPts[7]*srcPts[6], -1*dstPts[7]*srcPts[7]]; var matA = [r1, r2, r3, r4, r5, r6, r7, r8]; var matB = dstPts; var matC; try{ matC = numeric.inv(numeric.dotMMsmall(numeric.transpose(matA), matA)); }catch(e){ console.log(e); return [1,0,0,0,1,0,0,0]; } var matD = numeric.dotMMsmall(matC, numeric.transpose(matA)); var matX = numeric.dotMV(matD, matB); for(var i = 0; i < matX.length; i++) { matX[i] = round(matX[i]); } matX[8] = 1; return matX; } function PerspT(srcPts, dstPts){ if( (typeof window !== 'undefined' && window === this) || this === undefined) { return new PerspT(srcPts, dstPts); } this.srcPts = srcPts; this.dstPts = dstPts; this.coeffs = getNormalizationCoefficients(this.srcPts, this.dstPts, false); this.coeffsInv = getNormalizationCoefficients(this.srcPts, this.dstPts, true); return this; } PerspT.prototype = { transform: function(x,y) { var coordinates = []; coordinates[0] = (this.coeffs[0]*x + this.coeffs[1]*y + this.coeffs[2]) / (this.coeffs[6]*x + this.coeffs[7]*y + 1); coordinates[1] = (this.coeffs[3]*x + this.coeffs[4]*y + this.coeffs[5]) / (this.coeffs[6]*x + this.coeffs[7]*y + 1); return coordinates; }, transformInverse: function(x,y) { var coordinates = []; coordinates[0] = (this.coeffsInv[0]*x + this.coeffsInv[1]*y + this.coeffsInv[2]) / (this.coeffsInv[6]*x + this.coeffsInv[7]*y + 1); coordinates[1] = (this.coeffsInv[3]*x + this.coeffsInv[4]*y + this.coeffsInv[5]) / (this.coeffsInv[6]*x + this.coeffsInv[7]*y + 1); return coordinates; } }; module.exports = {PerspT: PerspT, getNormalizationCoefficients: getNormalizationCoefficients};
const DrawCard = require('../../drawcard.js'); class MaesterAtTheRock extends DrawCard { setupCardAbilities(ability) { this.reaction({ when: { onCardPlayed: event => event.card.isFaction('lannister') && event.card.controller === this.controller && event.card.location === 'discard pile' }, cost: ability.costs.kneelSelf(), handler: context => { this.controller.moveCard(context.event.card, 'draw deck'); this.game.addMessage('{0} kneels {1} to move {2} to the top of their deck', this.controller, this, context.event.card); } }); } } MaesterAtTheRock.code = '08010'; module.exports = MaesterAtTheRock;
document.addEventListener("DOMContentLoaded", function(event) { (function(global) { function now() { return new Date(); } var force = ""; if (typeof (window._bokeh_onload_callbacks) === "undefined" || force !== "") { window._bokeh_onload_callbacks = []; window._bokeh_is_loading = undefined; } function run_callbacks() { window._bokeh_onload_callbacks.forEach(function(callback) { callback() }); delete window._bokeh_onload_callbacks console.info("Bokeh: all callbacks have finished"); } function load_libs(js_urls, callback) { window._bokeh_onload_callbacks.push(callback); if (window._bokeh_is_loading > 0) { console.log("Bokeh: BokehJS is being loaded, scheduling callback at", now()); return null; } if (js_urls == null || js_urls.length === 0) { run_callbacks(); return null; } console.log("Bokeh: BokehJS not loaded, scheduling load and callback at", now()); window._bokeh_is_loading = js_urls.length; for (var i = 0; i < js_urls.length; i++) { var url = js_urls[i]; var s = document.createElement('script'); s.src = url; s.async = false; s.onreadystatechange = s.onload = function() { window._bokeh_is_loading--; if (window._bokeh_is_loading === 0) { console.log("Bokeh: all BokehJS libraries loaded"); run_callbacks() } }; s.onerror = function() { console.warn("failed to load library " + url); }; console.log("Bokeh: injecting script tag for BokehJS library: ", url); document.getElementsByTagName("head")[0].appendChild(s); } };var element = document.getElementById("a65c4446-f88b-4145-9e28-419a3ab2e4cf"); if (element == null) { console.log("Bokeh: ERROR: autoload.js configured with elementid 'a65c4446-f88b-4145-9e28-419a3ab2e4cf' but no matching script tag was found. ") return false; } var js_urls = ['https://cdn.bokeh.org/bokeh/release/bokeh-0.12.2.min.js', 'https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.2.min.js', 'https://cdn.bokeh.org/bokeh/release/bokeh-compiler-0.12.2.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.6.0/katex.min.js']; var inline_js = [ function(Bokeh) { Bokeh.set_log_level("info"); }, function(Bokeh) { (function outer(modules, cache, entry) { if (typeof Bokeh !== "undefined") { for (var name in modules) { var module = modules[name]; if (typeof(module) === "string") { try { coffee = Bokeh.require("coffee-script") } catch (e) { throw new Error("Compiler requested but failed to import. Make sure bokeh-compiler(-min).js was included.") } function compile(code) { var body = coffee.compile(code, {bare: true, shiftLine: true}); return new Function("require", "module", "exports", body); } modules[name] = [compile(module), {}]; } } for (var name in modules) { Bokeh.require.modules[name] = modules[name]; } for (var i = 0; i < entry.length; i++) { Bokeh.Models.register_locations(Bokeh.require(entry[i])); } } else { throw new Error("Cannot find Bokeh. You have to load it prior to loading plugins."); } })({ "custom/main":[function(require,module,exports){ module.exports = { Custom: require("custom/custom"), DrawTool: require("custom/draw_tool"), LatexLabel: require("custom/latex_label"), MyFormatter: require("custom/my_formatter"), Surface3d: require("custom/surface3d") }; }, {}], "custom/custom": "\n_ = require \"underscore\"\n$ = require \"jquery\"\n\np = require \"core/properties\"\nLayoutDOM = require \"models/layouts/layout_dom\"\n\nclass CustomView extends LayoutDOM.View\n\n initialize: (options) ->\n super(options)\n\n @render()\n\n # Set Backbone listener so that when the Bokeh slider has a change\n # event, we can process the new data\n @listenTo(@model.slider, \'change\', () => @render())\n\n render: () ->\n # Backbone Views create <div> elements by default, accessible as @$el.\n # Many Bokeh views ignore this default <div>, and instead do things\n # like draw to the HTML canvas. In this case though, we change the\n # contents of the <div>, based on the current slider value.\n @$el.html(\"<h1>#{ @model.text }: #{ @model.slider.value }</h1>\")\n @$(\'h1\').css({ \'color\': \'#686d8e\', \'background-color\': \'#2a3153\' })\n\nclass Custom extends LayoutDOM.Model\n\n # If there is an associated view, this is boilerplate.\n default_view: CustomView\n\n # The ``type`` class attribute should generally match exactly the name\n # of the corresponding Python class.\n type: \"Custom\"\n\n # The @define block adds corresponding \"properties\" to the JS model. These\n # should basically line up 1-1 with the Python model class. Most property\n # types have counterparts, e.g. bokeh.core.properties.String will be\n # p.String in the JS implementation. Where the JS type system is not yet\n # as rich, you can use p.Any as a \"wildcard\" property type.\n @define {\n text: [ p.String ]\n slider: [ p.Any ]\n }\n\n# This is boilerplate. Every implementation should export a Model\n# and (when applicable) also a View.\nmodule.exports =\n Model: Custom\n View: CustomView\n", "custom/draw_tool": "\np = require \"core/properties\"\nGestureTool = require \"models/tools/gestures/gesture_tool\"\n\nclass DrawToolView extends GestureTool.View\n\n # this is executed when the pan/drag event starts\n _pan_start: (e) ->\n @model.source.data = {x: [], y: []}\n\n # this is executed on subsequent mouse/touch moves\n _pan: (e) ->\n frame = @plot_model.frame\n canvas = @plot_view.canvas\n\n vx = canvas.sx_to_vx(e.bokeh.sx)\n vy = canvas.sy_to_vy(e.bokeh.sy)\n if not frame.contains(vx, vy)\n return null\n\n x = frame.get(\'x_mappers\').default.map_from_target(vx)\n y = frame.get(\'y_mappers\').default.map_from_target(vy)\n\n @model.source.data.x.push(x)\n @model.source.data.y.push(y)\n @model.source.trigger(\'change\')\n\n # this is executed then the pan/drag ends\n _pan_end: (e) -> return null\n\nclass DrawTool extends GestureTool.Model\n default_view: DrawToolView\n type: \"DrawTool\"\n\n tool_name: \"Drag Span\"\n icon: \"bk-tool-icon-lasso-select\"\n event_type: \"pan\"\n default_order: 12\n\n @define { source: [ p.Instance ] }\n\nmodule.exports =\n Model: DrawTool\n View: DrawToolView\n", "custom/latex_label": "\nLabel = require \"models/annotations/label\"\n\nclass LatexLabelView extends Label.View\n render: () ->\n\n #--- Start of copied section from ``Label.render`` implementation\n\n ctx = @plot_view.canvas_view.ctx\n\n # Here because AngleSpec does units tranform and label doesn\'t support specs\n switch @mget(\'angle_units\')\n when \"rad\" then angle = -1 * @mget(\'angle\')\n when \"deg\" then angle = -1 * @mget(\'angle\') * Math.PI/180.0\n\n if @mget(\'x_units\') == \"data\"\n vx = @xmapper.map_to_target(@mget(\'x\'))\n else\n vx = @mget(\'x\')\n sx = @canvas.vx_to_sx(vx)\n\n if @mget(\'y_units\') == \"data\"\n vy = @ymapper.map_to_target(@mget(\'y\'))\n else\n vy = @mget(\'y\')\n sy = @canvas.vy_to_sy(vy)\n\n if @model.panel?\n panel_offset = @_get_panel_offset()\n sx += panel_offset.x\n sy += panel_offset.y\n\n #--- End of copied section from ``Label.render`` implementation\n\n # ``katex`` is loaded into the global window at runtime\n # katex.renderToString returns a html ``span`` element\n latex = katex.renderToString(@mget(\'text\'), {displayMode: true})\n\n # Must render as superpositioned div (not on canvas) so that KaTex\n # css can properly style the text\n @_css_text(ctx, latex, sx + @mget(\'x_offset\'), sy - @mget(\'y_offset\'), angle)\n\nclass LatexLabel extends Label.Model\n type: \'LatexLabel\'\n default_view: LatexLabelView\n\nmodule.exports =\n Model: LatexLabel\n View: LatexLabelView\n", "custom/my_formatter": "\nTickFormatter = require \"models/formatters/tick_formatter\"\n\nclass MyFormatter extends TickFormatter.Model\n type: \"MyFormatter\"\n\n # TickFormatters should implement this method, which accepts a lisst\n # of numbers (ticks) and returns a list of strings\n doFormat: (ticks) ->\n # format the first tick as-is\n formatted = [\"#{ticks[0]}\"]\n\n # format the remaining ticks as a difference from the first\n for i in [1...ticks.length]\n formatted.push(\"+#{(ticks[i]-ticks[0]).toPrecision(2)}\")\n\n return formatted\n\nmodule.exports =\n Model: MyFormatter\n", "custom/surface3d": "\n# This file contains the JavaScript (CoffeeScript) implementation\n# for a Bokeh custom extension. The \"surface3d.py\" contains the\n# python counterpart.\n#\n# This custom model wraps one part of the third-party vis.js library:\n#\n# http://visjs.org/index.html\n#\n# Making it easy to hook up python data analytics tools (NumPy, SciPy,\n# Pandas, etc.) to web presentations using the Bokeh server.\n\n# These \"require\" lines are similar to python \"import\" statements\n_ = require \"underscore\"\n$ = require \"jquery\"\n\np = require \"core/properties\"\nLayoutDOM = require \"models/layouts/layout_dom\"\n\n# This defines some default options for the Graph3d feature of vis.js\n# See: http://visjs.org/graph3d_examples.html for more details.\nOPTIONS =\n width: \'600px\'\n height: \'600px\'\n style: \'surface\'\n showPerspective: true\n showGrid: true\n keepAspectRatio: true\n verticalRatio: 1.0\n legendLabel: \'stuff\'\n cameraPosition:\n horizontal: -0.35\n vertical: 0.22\n distance: 1.8\n\n# To create custom model extensions that will render on to the HTML canvas\n# or into the DOM, we must create a View subclass for the model. Currently\n# Bokeh models and views are based on BackBone. More information about\n# using Backbone can be found here:\n#\n# http://backbonejs.org/\n#\n# In this case we will subclass from the existing BokehJS ``LayoutDOM.View``,\n# corresponding to our\nclass Surface3dView extends LayoutDOM.View\n\n initialize: (options) ->\n super(options)\n\n url = \"https://cdnjs.cloudflare.com/ajax/libs/vis/4.16.1/vis.min.js\"\n $.getScript(url).done(@_init)\n\n # NOTE: we have to use the \"fat arrow\" => here so that \"this\" is bound correctly\n _init: () =>\n # Create a new Graph3s using the vis.js API. This assumes the vis.js has\n # already been loaded (e.g. in a custom app template). In the future Bokeh\n # models will be able to specify and load external scripts automatically.\n #\n # Backbone Views create <div> elements by default, accessible as @$el. Many\n # Bokeh views ignore this default <div>, and instead do things like draw\n # to the HTML canvas. In this case though, we use the <div> to attach a\n # Graph3d to the DOM.\n @_graph = new vis.Graph3d(@$el[0], @get_data(), OPTIONS)\n\n # Set Backbone listener so that when the Bokeh data source has a change\n # event, we can process the new data\n @listenTo(@model.data_source, \'change\', () =>\n @_graph.setData(@get_data())\n )\n\n # This is the callback executed when the Bokeh data has an change. Its basic\n # function is to adapt the Bokeh data source to the vis.js DataSet format.\n get_data: () ->\n data = new vis.DataSet()\n source = @model.data_source\n for i in [0...source.get_length()]\n data.add({\n x: source.get_column(@model.x)[i]\n y: source.get_column(@model.y)[i]\n z: source.get_column(@model.z)[i]\n style: source.get_column(@model.color)[i]\n })\n return data\n\n# We must also create a corresponding JavaScript Backbone model sublcass to\n# correspond to the python Bokeh model subclass. In this case, since we want\n# an element that can position itself in the DOM according to a Bokeh layout,\n# we subclass from ``LayoutDOM.model``\nclass Surface3d extends LayoutDOM.Model\n\n # This is usually boilerplate. In some cases there may not be a view.\n default_view: Surface3dView\n\n # The ``type`` class attribute should generally match exactly the name\n # of the corresponding Python class.\n type: \"Surface3d\"\n\n # The @define block adds corresponding \"properties\" to the JS model. These\n # should basically line up 1-1 with the Python model class. Most property\n # types have counterparts, e.g. ``bokeh.core.properties.String`` will be\n # ``p.String`` in the JS implementatin. Where the JS type system is not yet\n # as rich, you can use ``p.Any`` as a \"wildcard\" property type.\n @define {\n x: [ p.String ]\n y: [ p.String ]\n z: [ p.String ]\n color: [ p.String ]\n data_source: [ p.Instance ]\n }\n\n# This is boilerplate. Every implementation should \"export\" a ``Model``\n# and (when applicable) also a ``View``.\nmodule.exports =\n Model: Surface3d\n View: Surface3dView\n" }, {}, ["custom/main"]); }, function(Bokeh) { Bokeh.$(function() { Bokeh.safely(function() { var docs_json = {"43fcf93e-0f0d-4e9d-8b6f-90d1dbfc7614":{"roots":{"references":[{"attributes":{"children":[{"id":"297074f5-5ecd-4e30-acfe-5279c8ce63eb","type":"RadioGroup"}]},"id":"6e7b1d84-795f-4f13-bf43-8e03c0d8bc49","type":"WidgetBox"},{"attributes":{"active":0,"callback":null,"labels":["Option 1","Option 2","Option 3"]},"id":"297074f5-5ecd-4e30-acfe-5279c8ce63eb","type":"RadioGroup"}],"root_ids":["6e7b1d84-795f-4f13-bf43-8e03c0d8bc49"]},"title":"Bokeh Application","version":"0.12.2.9747"}}; var render_items = [{"docid":"43fcf93e-0f0d-4e9d-8b6f-90d1dbfc7614","elementid":"a65c4446-f88b-4145-9e28-419a3ab2e4cf","modelid":"6e7b1d84-795f-4f13-bf43-8e03c0d8bc49"}]; Bokeh.embed.embed_items(docs_json, render_items); }); }); }, function(Bokeh) { console.log("Bokeh: injecting CSS: https://cdn.bokeh.org/bokeh/release/bokeh-0.12.2.min.css"); Bokeh.embed.inject_css("https://cdn.bokeh.org/bokeh/release/bokeh-0.12.2.min.css"); console.log("Bokeh: injecting CSS: https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.2.min.css"); Bokeh.embed.inject_css("https://cdn.bokeh.org/bokeh/release/bokeh-widgets-0.12.2.min.css"); console.log("Bokeh: injecting CSS: https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.6.0/katex.min.css"); Bokeh.embed.inject_css("https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.6.0/katex.min.css"); } ]; function run_inline_js() { for (var i = 0; i < inline_js.length; i++) { inline_js[i](window.Bokeh); } } if (window._bokeh_is_loading === 0) { console.log("Bokeh: BokehJS loaded, going straight to plotting"); run_inline_js(); } else { load_libs(js_urls, function() { console.log("Bokeh: BokehJS plotting callback run at", now()); run_inline_js(); }); } }(this)); });
import {connect} from 'react-redux'; import GearStatSelect from './GearStatSelect'; const mapState = (state, {stats}) => ({ items: stats.map(stat => ({ value: stat.id, label: stat.label, })), }); export default connect( mapState, () => ({}) )(GearStatSelect);
var key = '_RPELcTeq3ZByqi3N5dt18w'; var allStrings = (typeof DEPRECATED_UNIT_TEST === 'undefined' || DEPRECATED_UNIT_TEST) ? require("../resx-strings/en-us.json") : require("resx-strings"); var strings = allStrings[key]; export default strings;
export default { name: '散点图', type: 'scatter', data: [ { name: '简单散点图', data: { columns: ['日期', '余额', '数量', '年龄'], rows: { '上海': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 7123, '年龄': 9, '数量': 3245 }, { '日期': '1-4', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-5', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-6', '余额': 2323, '年龄': 20, '数量': 6537 } ], '北京': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1273, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-4', '余额': 2123, '年龄': 9, '数量': 3245 }, { '日期': '1-5', '余额': 4103, '年龄': 12, '数量': 4355 }, { '日期': '1-6', '余额': 7123, '年龄': 10, '数量': 3567 } ], '广州': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 2123, '年龄': 30, '数量': 3245 }, { '日期': '1-5', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-4', '余额': 5123, '年龄': 18, '数量': 4564 }, { '日期': '1-6', '余额': 3843, '年龄': 30, '数量': 4850 } ] } }, settings: {} }, { name: '点阵图', data: { columns: ['日期', '余额', '数量', '年龄'], rows: [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 7123, '年龄': 9, '数量': 3245 }, { '日期': '1-4', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-5', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-6', '余额': 2323, '年龄': 20, '数量': 6537 } ] }, settings: { symbol: 'rect' } }, { name: '指标维度配置', data: { columns: ['日期', '余额', '数量', '年龄'], rows: { '上海': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 7123, '年龄': 9, '数量': 3245 }, { '日期': '1-4', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-5', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-6', '余额': 2323, '年龄': 20, '数量': 6537 } ], '北京': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1273, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-4', '余额': 2123, '年龄': 9, '数量': 3245 }, { '日期': '1-5', '余额': 4103, '年龄': 12, '数量': 4355 }, { '日期': '1-6', '余额': 7123, '年龄': 10, '数量': 3567 } ], '广州': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 2123, '年龄': 30, '数量': 3245 }, { '日期': '1-5', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-4', '余额': 5123, '年龄': 18, '数量': 4564 }, { '日期': '1-6', '余额': 3843, '年龄': 30, '数量': 4850 } ] } }, settings: { dimension: '日期', metrics: ['年龄', '数量'] } }, { name: '数据类型配置', data: { columns: ['日期', '余额', '数量', '年龄'], rows: { '上海': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 7123, '年龄': 9, '数量': 3245 }, { '日期': '1-4', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-5', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-6', '余额': 2323, '年龄': 20, '数量': 6537 } ], '北京': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1273, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-4', '余额': 2123, '年龄': 9, '数量': 3245 }, { '日期': '1-5', '余额': 4103, '年龄': 12, '数量': 4355 }, { '日期': '1-6', '余额': 7123, '年龄': 10, '数量': 3567 } ], '广州': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 2123, '年龄': 30, '数量': 3245 }, { '日期': '1-5', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-4', '余额': 5123, '年龄': 18, '数量': 4564 }, { '日期': '1-6', '余额': 3843, '年龄': 30, '数量': 4850 } ] } }, settings: { dataType: { '余额': 'KMB', '年龄': 'percent', '数量': 'normal' } } }, { name: '样式配置', data: { columns: ['日期', '余额', '数量', '年龄'], rows: { '上海': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 7123, '年龄': 9, '数量': 3245 }, { '日期': '1-4', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-5', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-6', '余额': 2323, '年龄': 20, '数量': 6537 } ], '北京': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1273, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-4', '余额': 2123, '年龄': 9, '数量': 3245 }, { '日期': '1-5', '余额': 4103, '年龄': 12, '数量': 4355 }, { '日期': '1-6', '余额': 7123, '年龄': 10, '数量': 3567 } ], '广州': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 2123, '年龄': 30, '数量': 3245 }, { '日期': '1-5', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-4', '余额': 5123, '年龄': 18, '数量': 4564 }, { '日期': '1-6', '余额': 3843, '年龄': 30, '数量': 4850 } ] } }, settings: { label: { emphasis: { show: true, position: 'top', formatter (param) { return param.data.value[0] } } }, itemStyle: { normal: { opacity: 0.8, shadowBlur: 10, shadowOffsetX: 0, shadowOffsetY: 0 } } } }, { name: '属性名配置', data: { columns: ['日期', '余额', '数量', '年龄'], rows: { '上海': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 7123, '年龄': 9, '数量': 3245 }, { '日期': '1-4', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-5', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-6', '余额': 2323, '年龄': 20, '数量': 6537 } ], '北京': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1273, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-4', '余额': 2123, '年龄': 9, '数量': 3245 }, { '日期': '1-5', '余额': 4103, '年龄': 12, '数量': 4355 }, { '日期': '1-6', '余额': 7123, '年龄': 10, '数量': 3567 } ], '广州': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 2123, '年龄': 30, '数量': 3245 }, { '日期': '1-5', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-4', '余额': 5123, '年龄': 18, '数量': 4564 }, { '日期': '1-6', '余额': 3843, '年龄': 30, '数量': 4850 } ] } }, settings: { legendName: { '上海': '上海1' }, labelMap: { '余额': 'balance' } } }, { name: '缩放配置', data: { columns: ['日期', '余额', '数量', '年龄'], rows: { '上海': [ { '日期': '1-1', '余额': 1230, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 7123, '年龄': 9, '数量': 3245 }, { '日期': '1-4', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-5', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-6', '余额': 2323, '年龄': 20, '数量': 6537 } ], '北京': [ { '日期': '1-1', '余额': 1230, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1273, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-4', '余额': 2123, '年龄': 9, '数量': 3245 }, { '日期': '1-5', '余额': 4103, '年龄': 12, '数量': 4355 }, { '日期': '1-6', '余额': 7123, '年龄': 10, '数量': 3567 } ], '广州': [ { '日期': '1-1', '余额': 1230, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 2123, '年龄': 30, '数量': 3245 }, { '日期': '1-5', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-4', '余额': 5123, '年龄': 18, '数量': 4564 }, { '日期': '1-6', '余额': 3843, '年龄': 30, '数量': 4850 } ] } }, settings: { scale: true, max: 10000 } }, { name: '坐标轴名配置', data: { columns: ['日期', '余额', '数量', '年龄'], rows: { '上海': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 7123, '年龄': 9, '数量': 3245 }, { '日期': '1-4', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-5', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-6', '余额': 2323, '年龄': 20, '数量': 6537 } ], '北京': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1273, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-4', '余额': 2123, '年龄': 9, '数量': 3245 }, { '日期': '1-5', '余额': 4103, '年龄': 12, '数量': 4355 }, { '日期': '1-6', '余额': 7123, '年龄': 10, '数量': 3567 } ], '广州': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 2123, '年龄': 30, '数量': 3245 }, { '日期': '1-5', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-4', '余额': 5123, '年龄': 18, '数量': 4564 }, { '日期': '1-6', '余额': 3843, '年龄': 30, '数量': 4850 } ] } }, settings: { xAxisName: '日期', yAxisName: '余额' } }, { name: '隐藏坐标轴', data: { columns: ['日期', '余额', '数量', '年龄'], rows: { '上海': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 7123, '年龄': 9, '数量': 3245 }, { '日期': '1-4', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-5', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-6', '余额': 2323, '年龄': 20, '数量': 6537 } ], '北京': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1273, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-4', '余额': 2123, '年龄': 9, '数量': 3245 }, { '日期': '1-5', '余额': 4103, '年龄': 12, '数量': 4355 }, { '日期': '1-6', '余额': 7123, '年龄': 10, '数量': 3567 } ], '广州': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 2123, '年龄': 30, '数量': 3245 }, { '日期': '1-5', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-4', '余额': 5123, '年龄': 18, '数量': 4564 }, { '日期': '1-6', '余额': 3843, '年龄': 30, '数量': 4850 } ] } }, settings: { axisVisible: false } }, { name: '散点样式配置', data: { columns: ['日期', '余额', '数量', '年龄'], rows: { '上海': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 7123, '年龄': 9, '数量': 3245 }, { '日期': '1-4', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-5', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-6', '余额': 2323, '年龄': 20, '数量': 6537 } ], '北京': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1273, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-4', '余额': 2123, '年龄': 9, '数量': 3245 }, { '日期': '1-5', '余额': 4103, '年龄': 12, '数量': 4355 }, { '日期': '1-6', '余额': 7123, '年龄': 10, '数量': 3567 } ], '广州': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 2123, '年龄': 30, '数量': 3245 }, { '日期': '1-5', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-4', '余额': 5123, '年龄': 18, '数量': 4564 }, { '日期': '1-6', '余额': 3843, '年龄': 30, '数量': 4850 } ] } }, settings: { symbol: 'rect', symbolSizeMax: 30, symbolRotate: 45, symbolOffset: [10, 10] } }, { name: '修改提示框触发方式', data: { columns: ['日期', '余额', '数量', '年龄'], rows: { '上海': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 7123, '年龄': 9, '数量': 3245 }, { '日期': '1-4', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-5', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-6', '余额': 2323, '年龄': 20, '数量': 6537 } ], '北京': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1273, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-4', '余额': 2123, '年龄': 9, '数量': 3245 }, { '日期': '1-5', '余额': 4103, '年龄': 12, '数量': 4355 }, { '日期': '1-6', '余额': 7123, '年龄': 10, '数量': 3567 } ], '广州': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 2123, '年龄': 30, '数量': 3245 }, { '日期': '1-5', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-4', '余额': 5123, '年龄': 18, '数量': 4564 }, { '日期': '1-6', '余额': 3843, '年龄': 30, '数量': 4850 } ] } }, settings: { tooltipTrigger: 'axis' } }, { name: '增加涟漪特效动画', data: { columns: ['日期', '余额', '数量', '年龄'], rows: { '上海': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 7123, '年龄': 9, '数量': 3245 }, { '日期': '1-4', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-5', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-6', '余额': 2323, '年龄': 20, '数量': 6537 } ], '北京': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1273, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 3123, '年龄': 15, '数量': 4564 }, { '日期': '1-4', '余额': 2123, '年龄': 9, '数量': 3245 }, { '日期': '1-5', '余额': 4103, '年龄': 12, '数量': 4355 }, { '日期': '1-6', '余额': 7123, '年龄': 10, '数量': 3567 } ], '广州': [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-2', '余额': 1223, '年龄': 6, '数量': 2344 }, { '日期': '1-3', '余额': 2123, '年龄': 30, '数量': 3245 }, { '日期': '1-5', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-4', '余额': 5123, '年龄': 18, '数量': 4564 }, { '日期': '1-6', '余额': 3843, '年龄': 30, '数量': 4850 } ] } }, settings: { showEffect: [ { '日期': '1-1', '余额': 123, '年龄': 3, '数量': 1244 }, { '日期': '1-5', '余额': 4123, '年龄': 12, '数量': 4355 }, { '日期': '1-6', '余额': 3843, '年龄': 30, '数量': 4850 } ] } } ] }
import * as PIXI from 'pixi.js' const radius = 25 const textScale = 0.3 const textColor = 0xffffff const textFontSize = 80 const verticeColor = 0x007d8c const selectedTint = 0x00aa88 const textMarginMultiplier = 30 const g = new PIXI.Graphics() g.lineStyle(0) g.beginFill(verticeColor, 1) g.drawCircle(0, 0, radius) g.endFill() export function getCircle() { return g.clone() } export function makeCircleSprite(vertice, name, that) { const circle = getCircle() const spr = new PIXI.Sprite() spr.addChild(circle) spr.x = vertice.x spr.y = vertice.y spr.id = name spr.clicks = 0 spr.interactive = true spr.addListener('pointerdown', (a) => { const { id, clicks } = a.currentTarget const highlightIds = [] if (clicks === 0) { // eslint-disable-next-line a.currentTarget.clicks += 1 } else { console.log(`you double clicked on ${id}`) // eslint-disable-next-line a.currentTarget.clicks = 0 that.lessonSelected(id) } that.verticeList.forEach((v) => { const lastChild = v.children.length - 1 if (lastChild > -1) { // eslint-disable-next-line v.getChildAt(0).tint = 0xffffff // reset to untinted if (v.id !== id) { // eslint-disable-next-line v.clicks = 0 // set clicks to 0 on all other vertices } } }) // eslint-disable-next-line a.currentTarget.getChildAt(0).tint = selectedTint // tint current vertice const nodeMap = that.nodeMap[id] || [] nodeMap.forEach((edgeSprite) => { highlightIds.push(edgeSprite.id) }) that.edgeContainer.children.forEach((child) => { if (highlightIds.indexOf(child.id) === -1) { // current child is one we DO NOT want to highlight // eslint-disable-next-line child.alpha = that.edgeAlphaMin } else { // eslint-disable-next-line child.alpha = that.edgeAlphaMax } }) }) return spr } export function makeCircleText(name, spr) { const t = new PIXI.Text(name, { align: 'center', fontSize: textFontSize, fill: textColor, }) t.scale.x = textScale t.scale.y = textScale t.x = spr.x - (t.width / 2) t.y = spr.y + (spr.height * textMarginMultiplier) return t }
/* * 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. */ /** * AUTO-GENERATED FILE. DO NOT MODIFY. */ /* * 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. */ /** * Parse and decode geo json */ import * as zrUtil from 'zrender/lib/core/util'; import { GeoJSONRegion } from './Region'; function decode(json) { if (!json.UTF8Encoding) { return json; } var jsonCompressed = json; var encodeScale = jsonCompressed.UTF8Scale; if (encodeScale == null) { encodeScale = 1024; } var features = jsonCompressed.features; for (var f = 0; f < features.length; f++) { var feature = features[f]; var geometry = feature.geometry; if (geometry.type === 'Polygon') { var coordinates = geometry.coordinates; for (var c = 0; c < coordinates.length; c++) { coordinates[c] = decodePolygon(coordinates[c], geometry.encodeOffsets[c], encodeScale); } } else if (geometry.type === 'MultiPolygon') { var coordinates = geometry.coordinates; for (var c = 0; c < coordinates.length; c++) { var coordinate = coordinates[c]; for (var c2 = 0; c2 < coordinate.length; c2++) { coordinate[c2] = decodePolygon(coordinate[c2], geometry.encodeOffsets[c][c2], encodeScale); } } } } // Has been decoded jsonCompressed.UTF8Encoding = false; return jsonCompressed; } function decodePolygon(coordinate, encodeOffsets, encodeScale) { var result = []; var prevX = encodeOffsets[0]; var prevY = encodeOffsets[1]; for (var i = 0; i < coordinate.length; i += 2) { var x = coordinate.charCodeAt(i) - 64; var y = coordinate.charCodeAt(i + 1) - 64; // ZigZag decoding x = x >> 1 ^ -(x & 1); y = y >> 1 ^ -(y & 1); // Delta deocding x += prevX; y += prevY; prevX = x; prevY = y; // Dequantize result.push([x / encodeScale, y / encodeScale]); } return result; } export default function parseGeoJSON(geoJson, nameProperty) { geoJson = decode(geoJson); return zrUtil.map(zrUtil.filter(geoJson.features, function (featureObj) { // Output of mapshaper may have geometry null return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0; }), function (featureObj) { var properties = featureObj.properties; var geo = featureObj.geometry; var geometries = []; if (geo.type === 'Polygon') { var coordinates = geo.coordinates; geometries.push({ type: 'polygon', // According to the GeoJSON specification. // First must be exterior, and the rest are all interior(holes). exterior: coordinates[0], interiors: coordinates.slice(1) }); } if (geo.type === 'MultiPolygon') { var coordinates = geo.coordinates; zrUtil.each(coordinates, function (item) { if (item[0]) { geometries.push({ type: 'polygon', exterior: item[0], interiors: item.slice(1) }); } }); } var region = new GeoJSONRegion(properties[nameProperty || 'name'], geometries, properties.cp); region.properties = properties; return region; }); }
(window.webpackJsonp=window.webpackJsonp||[]).push([[0],{1256:function(module,exports,__webpack_require__){"use strict";var warning=function(){};module.exports=warning},565:function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__),__webpack_require__.d(__webpack_exports__,"WithTooltipPure",(function(){return WithTooltip_WithTooltipPure})),__webpack_require__.d(__webpack_exports__,"WithToolTipState",(function(){return WithTooltip_WithToolTipState})),__webpack_require__.d(__webpack_exports__,"WithTooltip",(function(){return WithTooltip_WithToolTipState}));__webpack_require__(16),__webpack_require__(56),__webpack_require__(24),__webpack_require__(4),__webpack_require__(15),__webpack_require__(10),__webpack_require__(6),__webpack_require__(12),__webpack_require__(7),__webpack_require__(11),__webpack_require__(14),__webpack_require__(17),__webpack_require__(8),__webpack_require__(36);var react=__webpack_require__(0),react_default=__webpack_require__.n(react),esm=__webpack_require__(1),global_window=__webpack_require__(9),window_default=__webpack_require__.n(global_window),objectWithoutPropertiesLoose=__webpack_require__(539),esm_extends=__webpack_require__(55),inheritsLoose=__webpack_require__(538),react_dom=__webpack_require__(174),ManagerReferenceNodeContext=react.createContext(),ManagerReferenceNodeSetterContext=react.createContext();function Manager(_ref){var children=_ref.children,_React$useState=react.useState(null),referenceNode=_React$useState[0],setReferenceNode=_React$useState[1],hasUnmounted=react.useRef(!1);react.useEffect((function(){return function(){hasUnmounted.current=!0}}),[]);var handleSetReferenceNode=react.useCallback((function(node){hasUnmounted.current||setReferenceNode(node)}),[]);return react.createElement(ManagerReferenceNodeContext.Provider,{value:referenceNode},react.createElement(ManagerReferenceNodeSetterContext.Provider,{value:handleSetReferenceNode},children))}var unwrapArray=function unwrapArray(arg){return Array.isArray(arg)?arg[0]:arg},safeInvoke=function safeInvoke(fn){if("function"==typeof fn){for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)args[_key-1]=arguments[_key];return fn.apply(void 0,args)}},setRef=function setRef(ref,node){if("function"==typeof ref)return safeInvoke(ref,node);null!=ref&&(ref.current=node)},fromEntries=function fromEntries(entries){return entries.reduce((function(acc,_ref){var key=_ref[0],value=_ref[1];return acc[key]=value,acc}),{})},useIsomorphicLayoutEffect="undefined"!=typeof window&&window.document&&window.document.createElement?react.useLayoutEffect:react.useEffect;function getWindow(node){if(null==node)return window;if("[object Window]"!==node.toString()){var ownerDocument=node.ownerDocument;return ownerDocument&&ownerDocument.defaultView||window}return node}function isElement(node){return node instanceof getWindow(node).Element||node instanceof Element}function isHTMLElement(node){return node instanceof getWindow(node).HTMLElement||node instanceof HTMLElement}function isShadowRoot(node){return"undefined"!=typeof ShadowRoot&&(node instanceof getWindow(node).ShadowRoot||node instanceof ShadowRoot)}var math_max=Math.max,math_min=Math.min,round=Math.round;function getBoundingClientRect(element,includeScale){void 0===includeScale&&(includeScale=!1);var rect=element.getBoundingClientRect(),scaleX=1,scaleY=1;if(isHTMLElement(element)&&includeScale){var offsetHeight=element.offsetHeight,offsetWidth=element.offsetWidth;offsetWidth>0&&(scaleX=round(rect.width)/offsetWidth||1),offsetHeight>0&&(scaleY=round(rect.height)/offsetHeight||1)}return{width:rect.width/scaleX,height:rect.height/scaleY,top:rect.top/scaleY,right:rect.right/scaleX,bottom:rect.bottom/scaleY,left:rect.left/scaleX,x:rect.left/scaleX,y:rect.top/scaleY}}function getWindowScroll(node){var win=getWindow(node);return{scrollLeft:win.pageXOffset,scrollTop:win.pageYOffset}}function getNodeName(element){return element?(element.nodeName||"").toLowerCase():null}function getDocumentElement(element){return((isElement(element)?element.ownerDocument:element.document)||window.document).documentElement}function getWindowScrollBarX(element){return getBoundingClientRect(getDocumentElement(element)).left+getWindowScroll(element).scrollLeft}function getComputedStyle(element){return getWindow(element).getComputedStyle(element)}function isScrollParent(element){var _getComputedStyle=getComputedStyle(element),overflow=_getComputedStyle.overflow,overflowX=_getComputedStyle.overflowX,overflowY=_getComputedStyle.overflowY;return/auto|scroll|overlay|hidden/.test(overflow+overflowY+overflowX)}function getCompositeRect(elementOrVirtualElement,offsetParent,isFixed){void 0===isFixed&&(isFixed=!1);var isOffsetParentAnElement=isHTMLElement(offsetParent),offsetParentIsScaled=isHTMLElement(offsetParent)&&function isElementScaled(element){var rect=element.getBoundingClientRect(),scaleX=round(rect.width)/element.offsetWidth||1,scaleY=round(rect.height)/element.offsetHeight||1;return 1!==scaleX||1!==scaleY}(offsetParent),documentElement=getDocumentElement(offsetParent),rect=getBoundingClientRect(elementOrVirtualElement,offsetParentIsScaled),scroll={scrollLeft:0,scrollTop:0},offsets={x:0,y:0};return(isOffsetParentAnElement||!isOffsetParentAnElement&&!isFixed)&&(("body"!==getNodeName(offsetParent)||isScrollParent(documentElement))&&(scroll=function getNodeScroll(node){return node!==getWindow(node)&&isHTMLElement(node)?function getHTMLElementScroll(element){return{scrollLeft:element.scrollLeft,scrollTop:element.scrollTop}}(node):getWindowScroll(node)}(offsetParent)),isHTMLElement(offsetParent)?((offsets=getBoundingClientRect(offsetParent,!0)).x+=offsetParent.clientLeft,offsets.y+=offsetParent.clientTop):documentElement&&(offsets.x=getWindowScrollBarX(documentElement))),{x:rect.left+scroll.scrollLeft-offsets.x,y:rect.top+scroll.scrollTop-offsets.y,width:rect.width,height:rect.height}}function getLayoutRect(element){var clientRect=getBoundingClientRect(element),width=element.offsetWidth,height=element.offsetHeight;return Math.abs(clientRect.width-width)<=1&&(width=clientRect.width),Math.abs(clientRect.height-height)<=1&&(height=clientRect.height),{x:element.offsetLeft,y:element.offsetTop,width:width,height:height}}function getParentNode(element){return"html"===getNodeName(element)?element:element.assignedSlot||element.parentNode||(isShadowRoot(element)?element.host:null)||getDocumentElement(element)}function getScrollParent(node){return["html","body","#document"].indexOf(getNodeName(node))>=0?node.ownerDocument.body:isHTMLElement(node)&&isScrollParent(node)?node:getScrollParent(getParentNode(node))}function listScrollParents(element,list){var _element$ownerDocumen;void 0===list&&(list=[]);var scrollParent=getScrollParent(element),isBody=scrollParent===(null==(_element$ownerDocumen=element.ownerDocument)?void 0:_element$ownerDocumen.body),win=getWindow(scrollParent),target=isBody?[win].concat(win.visualViewport||[],isScrollParent(scrollParent)?scrollParent:[]):scrollParent,updatedList=list.concat(target);return isBody?updatedList:updatedList.concat(listScrollParents(getParentNode(target)))}function isTableElement(element){return["table","td","th"].indexOf(getNodeName(element))>=0}function getTrueOffsetParent(element){return isHTMLElement(element)&&"fixed"!==getComputedStyle(element).position?element.offsetParent:null}function getOffsetParent(element){for(var window=getWindow(element),offsetParent=getTrueOffsetParent(element);offsetParent&&isTableElement(offsetParent)&&"static"===getComputedStyle(offsetParent).position;)offsetParent=getTrueOffsetParent(offsetParent);return offsetParent&&("html"===getNodeName(offsetParent)||"body"===getNodeName(offsetParent)&&"static"===getComputedStyle(offsetParent).position)?window:offsetParent||function getContainingBlock(element){var isFirefox=-1!==navigator.userAgent.toLowerCase().indexOf("firefox");if(-1!==navigator.userAgent.indexOf("Trident")&&isHTMLElement(element)&&"fixed"===getComputedStyle(element).position)return null;for(var currentNode=getParentNode(element);isHTMLElement(currentNode)&&["html","body"].indexOf(getNodeName(currentNode))<0;){var css=getComputedStyle(currentNode);if("none"!==css.transform||"none"!==css.perspective||"paint"===css.contain||-1!==["transform","perspective"].indexOf(css.willChange)||isFirefox&&"filter"===css.willChange||isFirefox&&css.filter&&"none"!==css.filter)return currentNode;currentNode=currentNode.parentNode}return null}(element)||window}var enums=__webpack_require__(564);function order(modifiers){var map=new Map,visited=new Set,result=[];function sort(modifier){visited.add(modifier.name),[].concat(modifier.requires||[],modifier.requiresIfExists||[]).forEach((function(dep){if(!visited.has(dep)){var depModifier=map.get(dep);depModifier&&sort(depModifier)}})),result.push(modifier)}return modifiers.forEach((function(modifier){map.set(modifier.name,modifier)})),modifiers.forEach((function(modifier){visited.has(modifier.name)||sort(modifier)})),result}var DEFAULT_OPTIONS={placement:"bottom",modifiers:[],strategy:"absolute"};function areValidElements(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return!args.some((function(element){return!(element&&"function"==typeof element.getBoundingClientRect)}))}function popperGenerator(generatorOptions){void 0===generatorOptions&&(generatorOptions={});var _generatorOptions=generatorOptions,_generatorOptions$def=_generatorOptions.defaultModifiers,defaultModifiers=void 0===_generatorOptions$def?[]:_generatorOptions$def,_generatorOptions$def2=_generatorOptions.defaultOptions,defaultOptions=void 0===_generatorOptions$def2?DEFAULT_OPTIONS:_generatorOptions$def2;return function createPopper(reference,popper,options){void 0===options&&(options=defaultOptions);var fn,pending,state={placement:"bottom",orderedModifiers:[],options:Object.assign({},DEFAULT_OPTIONS,defaultOptions),modifiersData:{},elements:{reference:reference,popper:popper},attributes:{},styles:{}},effectCleanupFns=[],isDestroyed=!1,instance={state:state,setOptions:function setOptions(setOptionsAction){var options="function"==typeof setOptionsAction?setOptionsAction(state.options):setOptionsAction;cleanupModifierEffects(),state.options=Object.assign({},defaultOptions,state.options,options),state.scrollParents={reference:isElement(reference)?listScrollParents(reference):reference.contextElement?listScrollParents(reference.contextElement):[],popper:listScrollParents(popper)};var orderedModifiers=function orderModifiers(modifiers){var orderedModifiers=order(modifiers);return enums.g.reduce((function(acc,phase){return acc.concat(orderedModifiers.filter((function(modifier){return modifier.phase===phase})))}),[])}(function mergeByName(modifiers){var merged=modifiers.reduce((function(merged,current){var existing=merged[current.name];return merged[current.name]=existing?Object.assign({},existing,current,{options:Object.assign({},existing.options,current.options),data:Object.assign({},existing.data,current.data)}):current,merged}),{});return Object.keys(merged).map((function(key){return merged[key]}))}([].concat(defaultModifiers,state.options.modifiers)));return state.orderedModifiers=orderedModifiers.filter((function(m){return m.enabled})),function runModifierEffects(){state.orderedModifiers.forEach((function(_ref3){var name=_ref3.name,_ref3$options=_ref3.options,options=void 0===_ref3$options?{}:_ref3$options,effect=_ref3.effect;if("function"==typeof effect){var cleanupFn=effect({state:state,name:name,instance:instance,options:options}),noopFn=function noopFn(){};effectCleanupFns.push(cleanupFn||noopFn)}}))}(),instance.update()},forceUpdate:function forceUpdate(){if(!isDestroyed){var _state$elements=state.elements,reference=_state$elements.reference,popper=_state$elements.popper;if(areValidElements(reference,popper)){state.rects={reference:getCompositeRect(reference,getOffsetParent(popper),"fixed"===state.options.strategy),popper:getLayoutRect(popper)},state.reset=!1,state.placement=state.options.placement,state.orderedModifiers.forEach((function(modifier){return state.modifiersData[modifier.name]=Object.assign({},modifier.data)}));for(var index=0;index<state.orderedModifiers.length;index++)if(!0!==state.reset){var _state$orderedModifie=state.orderedModifiers[index],fn=_state$orderedModifie.fn,_state$orderedModifie2=_state$orderedModifie.options,_options=void 0===_state$orderedModifie2?{}:_state$orderedModifie2,name=_state$orderedModifie.name;"function"==typeof fn&&(state=fn({state:state,options:_options,name:name,instance:instance})||state)}else state.reset=!1,index=-1}}},update:(fn=function(){return new Promise((function(resolve){instance.forceUpdate(),resolve(state)}))},function(){return pending||(pending=new Promise((function(resolve){Promise.resolve().then((function(){pending=void 0,resolve(fn())}))}))),pending}),destroy:function destroy(){cleanupModifierEffects(),isDestroyed=!0}};if(!areValidElements(reference,popper))return instance;function cleanupModifierEffects(){effectCleanupFns.forEach((function(fn){return fn()})),effectCleanupFns=[]}return instance.setOptions(options).then((function(state){!isDestroyed&&options.onFirstUpdate&&options.onFirstUpdate(state)})),instance}}var passive={passive:!0};function getBasePlacement(placement){return placement.split("-")[0]}function getVariation(placement){return placement.split("-")[1]}function getMainAxisFromPlacement(placement){return["top","bottom"].indexOf(placement)>=0?"x":"y"}function computeOffsets(_ref){var offsets,reference=_ref.reference,element=_ref.element,placement=_ref.placement,basePlacement=placement?getBasePlacement(placement):null,variation=placement?getVariation(placement):null,commonX=reference.x+reference.width/2-element.width/2,commonY=reference.y+reference.height/2-element.height/2;switch(basePlacement){case enums.m:offsets={x:commonX,y:reference.y-element.height};break;case enums.c:offsets={x:commonX,y:reference.y+reference.height};break;case enums.k:offsets={x:reference.x+reference.width,y:commonY};break;case enums.f:offsets={x:reference.x-element.width,y:commonY};break;default:offsets={x:reference.x,y:reference.y}}var mainAxis=basePlacement?getMainAxisFromPlacement(basePlacement):null;if(null!=mainAxis){var len="y"===mainAxis?"height":"width";switch(variation){case enums.l:offsets[mainAxis]=offsets[mainAxis]-(reference[len]/2-element[len]/2);break;case enums.e:offsets[mainAxis]=offsets[mainAxis]+(reference[len]/2-element[len]/2)}}return offsets}var unsetSides={top:"auto",right:"auto",bottom:"auto",left:"auto"};function mapToStyles(_ref2){var _Object$assign2,popper=_ref2.popper,popperRect=_ref2.popperRect,placement=_ref2.placement,variation=_ref2.variation,offsets=_ref2.offsets,position=_ref2.position,gpuAcceleration=_ref2.gpuAcceleration,adaptive=_ref2.adaptive,roundOffsets=_ref2.roundOffsets,isFixed=_ref2.isFixed,_ref3=!0===roundOffsets?function roundOffsetsByDPR(_ref){var x=_ref.x,y=_ref.y,dpr=window.devicePixelRatio||1;return{x:round(x*dpr)/dpr||0,y:round(y*dpr)/dpr||0}}(offsets):"function"==typeof roundOffsets?roundOffsets(offsets):offsets,_ref3$x=_ref3.x,x=void 0===_ref3$x?0:_ref3$x,_ref3$y=_ref3.y,y=void 0===_ref3$y?0:_ref3$y,hasX=offsets.hasOwnProperty("x"),hasY=offsets.hasOwnProperty("y"),sideX=enums.f,sideY=enums.m,win=window;if(adaptive){var offsetParent=getOffsetParent(popper),heightProp="clientHeight",widthProp="clientWidth";if(offsetParent===getWindow(popper)&&"static"!==getComputedStyle(offsetParent=getDocumentElement(popper)).position&&"absolute"===position&&(heightProp="scrollHeight",widthProp="scrollWidth"),offsetParent=offsetParent,placement===enums.m||(placement===enums.f||placement===enums.k)&&variation===enums.e)sideY=enums.c,y-=(isFixed&&win.visualViewport?win.visualViewport.height:offsetParent[heightProp])-popperRect.height,y*=gpuAcceleration?1:-1;if(placement===enums.f||(placement===enums.m||placement===enums.c)&&variation===enums.e)sideX=enums.k,x-=(isFixed&&win.visualViewport?win.visualViewport.width:offsetParent[widthProp])-popperRect.width,x*=gpuAcceleration?1:-1}var _Object$assign,commonStyles=Object.assign({position:position},adaptive&&unsetSides);return gpuAcceleration?Object.assign({},commonStyles,((_Object$assign={})[sideY]=hasY?"0":"",_Object$assign[sideX]=hasX?"0":"",_Object$assign.transform=(win.devicePixelRatio||1)<=1?"translate("+x+"px, "+y+"px)":"translate3d("+x+"px, "+y+"px, 0)",_Object$assign)):Object.assign({},commonStyles,((_Object$assign2={})[sideY]=hasY?y+"px":"",_Object$assign2[sideX]=hasX?x+"px":"",_Object$assign2.transform="",_Object$assign2))}var hash={left:"right",right:"left",bottom:"top",top:"bottom"};function getOppositePlacement(placement){return placement.replace(/left|right|bottom|top/g,(function(matched){return hash[matched]}))}var getOppositeVariationPlacement_hash={start:"end",end:"start"};function getOppositeVariationPlacement(placement){return placement.replace(/start|end/g,(function(matched){return getOppositeVariationPlacement_hash[matched]}))}function contains(parent,child){var rootNode=child.getRootNode&&child.getRootNode();if(parent.contains(child))return!0;if(rootNode&&isShadowRoot(rootNode)){var next=child;do{if(next&&parent.isSameNode(next))return!0;next=next.parentNode||next.host}while(next)}return!1}function rectToClientRect(rect){return Object.assign({},rect,{left:rect.x,top:rect.y,right:rect.x+rect.width,bottom:rect.y+rect.height})}function getClientRectFromMixedType(element,clippingParent){return clippingParent===enums.o?rectToClientRect(function getViewportRect(element){var win=getWindow(element),html=getDocumentElement(element),visualViewport=win.visualViewport,width=html.clientWidth,height=html.clientHeight,x=0,y=0;return visualViewport&&(width=visualViewport.width,height=visualViewport.height,/^((?!chrome|android).)*safari/i.test(navigator.userAgent)||(x=visualViewport.offsetLeft,y=visualViewport.offsetTop)),{width:width,height:height,x:x+getWindowScrollBarX(element),y:y}}(element)):isElement(clippingParent)?function getInnerBoundingClientRect(element){var rect=getBoundingClientRect(element);return rect.top=rect.top+element.clientTop,rect.left=rect.left+element.clientLeft,rect.bottom=rect.top+element.clientHeight,rect.right=rect.left+element.clientWidth,rect.width=element.clientWidth,rect.height=element.clientHeight,rect.x=rect.left,rect.y=rect.top,rect}(clippingParent):rectToClientRect(function getDocumentRect(element){var _element$ownerDocumen,html=getDocumentElement(element),winScroll=getWindowScroll(element),body=null==(_element$ownerDocumen=element.ownerDocument)?void 0:_element$ownerDocumen.body,width=math_max(html.scrollWidth,html.clientWidth,body?body.scrollWidth:0,body?body.clientWidth:0),height=math_max(html.scrollHeight,html.clientHeight,body?body.scrollHeight:0,body?body.clientHeight:0),x=-winScroll.scrollLeft+getWindowScrollBarX(element),y=-winScroll.scrollTop;return"rtl"===getComputedStyle(body||html).direction&&(x+=math_max(html.clientWidth,body?body.clientWidth:0)-width),{width:width,height:height,x:x,y:y}}(getDocumentElement(element)))}function getClippingRect(element,boundary,rootBoundary){var mainClippingParents="clippingParents"===boundary?function getClippingParents(element){var clippingParents=listScrollParents(getParentNode(element)),canEscapeClipping=["absolute","fixed"].indexOf(getComputedStyle(element).position)>=0,clipperElement=canEscapeClipping&&isHTMLElement(element)?getOffsetParent(element):element;return isElement(clipperElement)?clippingParents.filter((function(clippingParent){return isElement(clippingParent)&&contains(clippingParent,clipperElement)&&"body"!==getNodeName(clippingParent)&&(!canEscapeClipping||"static"!==getComputedStyle(clippingParent).position)})):[]}(element):[].concat(boundary),clippingParents=[].concat(mainClippingParents,[rootBoundary]),firstClippingParent=clippingParents[0],clippingRect=clippingParents.reduce((function(accRect,clippingParent){var rect=getClientRectFromMixedType(element,clippingParent);return accRect.top=math_max(rect.top,accRect.top),accRect.right=math_min(rect.right,accRect.right),accRect.bottom=math_min(rect.bottom,accRect.bottom),accRect.left=math_max(rect.left,accRect.left),accRect}),getClientRectFromMixedType(element,firstClippingParent));return clippingRect.width=clippingRect.right-clippingRect.left,clippingRect.height=clippingRect.bottom-clippingRect.top,clippingRect.x=clippingRect.left,clippingRect.y=clippingRect.top,clippingRect}function mergePaddingObject(paddingObject){return Object.assign({},{top:0,right:0,bottom:0,left:0},paddingObject)}function expandToHashMap(value,keys){return keys.reduce((function(hashMap,key){return hashMap[key]=value,hashMap}),{})}function detectOverflow(state,options){void 0===options&&(options={});var _options=options,_options$placement=_options.placement,placement=void 0===_options$placement?state.placement:_options$placement,_options$boundary=_options.boundary,boundary=void 0===_options$boundary?enums.d:_options$boundary,_options$rootBoundary=_options.rootBoundary,rootBoundary=void 0===_options$rootBoundary?enums.o:_options$rootBoundary,_options$elementConte=_options.elementContext,elementContext=void 0===_options$elementConte?enums.i:_options$elementConte,_options$altBoundary=_options.altBoundary,altBoundary=void 0!==_options$altBoundary&&_options$altBoundary,_options$padding=_options.padding,padding=void 0===_options$padding?0:_options$padding,paddingObject=mergePaddingObject("number"!=typeof padding?padding:expandToHashMap(padding,enums.b)),altContext=elementContext===enums.i?enums.j:enums.i,popperRect=state.rects.popper,element=state.elements[altBoundary?altContext:elementContext],clippingClientRect=getClippingRect(isElement(element)?element:element.contextElement||getDocumentElement(state.elements.popper),boundary,rootBoundary),referenceClientRect=getBoundingClientRect(state.elements.reference),popperOffsets=computeOffsets({reference:referenceClientRect,element:popperRect,strategy:"absolute",placement:placement}),popperClientRect=rectToClientRect(Object.assign({},popperRect,popperOffsets)),elementClientRect=elementContext===enums.i?popperClientRect:referenceClientRect,overflowOffsets={top:clippingClientRect.top-elementClientRect.top+paddingObject.top,bottom:elementClientRect.bottom-clippingClientRect.bottom+paddingObject.bottom,left:clippingClientRect.left-elementClientRect.left+paddingObject.left,right:elementClientRect.right-clippingClientRect.right+paddingObject.right},offsetData=state.modifiersData.offset;if(elementContext===enums.i&&offsetData){var offset=offsetData[placement];Object.keys(overflowOffsets).forEach((function(key){var multiply=[enums.k,enums.c].indexOf(key)>=0?1:-1,axis=[enums.m,enums.c].indexOf(key)>=0?"y":"x";overflowOffsets[key]+=offset[axis]*multiply}))}return overflowOffsets}function within(min,value,max){return math_max(min,math_min(value,max))}function getSideOffsets(overflow,rect,preventedOffsets){return void 0===preventedOffsets&&(preventedOffsets={x:0,y:0}),{top:overflow.top-rect.height-preventedOffsets.y,right:overflow.right-rect.width+preventedOffsets.x,bottom:overflow.bottom-rect.height+preventedOffsets.y,left:overflow.left-rect.width-preventedOffsets.x}}function isAnySideFullyClipped(overflow){return[enums.m,enums.k,enums.c,enums.f].some((function(side){return overflow[side]>=0}))}var popper_createPopper=popperGenerator({defaultModifiers:[{name:"eventListeners",enabled:!0,phase:"write",fn:function fn(){},effect:function effect(_ref){var state=_ref.state,instance=_ref.instance,options=_ref.options,_options$scroll=options.scroll,scroll=void 0===_options$scroll||_options$scroll,_options$resize=options.resize,resize=void 0===_options$resize||_options$resize,window=getWindow(state.elements.popper),scrollParents=[].concat(state.scrollParents.reference,state.scrollParents.popper);return scroll&&scrollParents.forEach((function(scrollParent){scrollParent.addEventListener("scroll",instance.update,passive)})),resize&&window.addEventListener("resize",instance.update,passive),function(){scroll&&scrollParents.forEach((function(scrollParent){scrollParent.removeEventListener("scroll",instance.update,passive)})),resize&&window.removeEventListener("resize",instance.update,passive)}},data:{}},{name:"popperOffsets",enabled:!0,phase:"read",fn:function popperOffsets_popperOffsets(_ref){var state=_ref.state,name=_ref.name;state.modifiersData[name]=computeOffsets({reference:state.rects.reference,element:state.rects.popper,strategy:"absolute",placement:state.placement})},data:{}},{name:"computeStyles",enabled:!0,phase:"beforeWrite",fn:function computeStyles(_ref4){var state=_ref4.state,options=_ref4.options,_options$gpuAccelerat=options.gpuAcceleration,gpuAcceleration=void 0===_options$gpuAccelerat||_options$gpuAccelerat,_options$adaptive=options.adaptive,adaptive=void 0===_options$adaptive||_options$adaptive,_options$roundOffsets=options.roundOffsets,roundOffsets=void 0===_options$roundOffsets||_options$roundOffsets,commonStyles={placement:getBasePlacement(state.placement),variation:getVariation(state.placement),popper:state.elements.popper,popperRect:state.rects.popper,gpuAcceleration:gpuAcceleration,isFixed:"fixed"===state.options.strategy};null!=state.modifiersData.popperOffsets&&(state.styles.popper=Object.assign({},state.styles.popper,mapToStyles(Object.assign({},commonStyles,{offsets:state.modifiersData.popperOffsets,position:state.options.strategy,adaptive:adaptive,roundOffsets:roundOffsets})))),null!=state.modifiersData.arrow&&(state.styles.arrow=Object.assign({},state.styles.arrow,mapToStyles(Object.assign({},commonStyles,{offsets:state.modifiersData.arrow,position:"absolute",adaptive:!1,roundOffsets:roundOffsets})))),state.attributes.popper=Object.assign({},state.attributes.popper,{"data-popper-placement":state.placement})},data:{}},{name:"applyStyles",enabled:!0,phase:"write",fn:function applyStyles(_ref){var state=_ref.state;Object.keys(state.elements).forEach((function(name){var style=state.styles[name]||{},attributes=state.attributes[name]||{},element=state.elements[name];isHTMLElement(element)&&getNodeName(element)&&(Object.assign(element.style,style),Object.keys(attributes).forEach((function(name){var value=attributes[name];!1===value?element.removeAttribute(name):element.setAttribute(name,!0===value?"":value)})))}))},effect:function applyStyles_effect(_ref2){var state=_ref2.state,initialStyles={popper:{position:state.options.strategy,left:"0",top:"0",margin:"0"},arrow:{position:"absolute"},reference:{}};return Object.assign(state.elements.popper.style,initialStyles.popper),state.styles=initialStyles,state.elements.arrow&&Object.assign(state.elements.arrow.style,initialStyles.arrow),function(){Object.keys(state.elements).forEach((function(name){var element=state.elements[name],attributes=state.attributes[name]||{},style=Object.keys(state.styles.hasOwnProperty(name)?state.styles[name]:initialStyles[name]).reduce((function(style,property){return style[property]="",style}),{});isHTMLElement(element)&&getNodeName(element)&&(Object.assign(element.style,style),Object.keys(attributes).forEach((function(attribute){element.removeAttribute(attribute)})))}))}},requires:["computeStyles"]},{name:"offset",enabled:!0,phase:"main",requires:["popperOffsets"],fn:function offset_offset(_ref2){var state=_ref2.state,options=_ref2.options,name=_ref2.name,_options$offset=options.offset,offset=void 0===_options$offset?[0,0]:_options$offset,data=enums.h.reduce((function(acc,placement){return acc[placement]=function distanceAndSkiddingToXY(placement,rects,offset){var basePlacement=getBasePlacement(placement),invertDistance=[enums.f,enums.m].indexOf(basePlacement)>=0?-1:1,_ref="function"==typeof offset?offset(Object.assign({},rects,{placement:placement})):offset,skidding=_ref[0],distance=_ref[1];return skidding=skidding||0,distance=(distance||0)*invertDistance,[enums.f,enums.k].indexOf(basePlacement)>=0?{x:distance,y:skidding}:{x:skidding,y:distance}}(placement,state.rects,offset),acc}),{}),_data$state$placement=data[state.placement],x=_data$state$placement.x,y=_data$state$placement.y;null!=state.modifiersData.popperOffsets&&(state.modifiersData.popperOffsets.x+=x,state.modifiersData.popperOffsets.y+=y),state.modifiersData[name]=data}},{name:"flip",enabled:!0,phase:"main",fn:function flip(_ref){var state=_ref.state,options=_ref.options,name=_ref.name;if(!state.modifiersData[name]._skip){for(var _options$mainAxis=options.mainAxis,checkMainAxis=void 0===_options$mainAxis||_options$mainAxis,_options$altAxis=options.altAxis,checkAltAxis=void 0===_options$altAxis||_options$altAxis,specifiedFallbackPlacements=options.fallbackPlacements,padding=options.padding,boundary=options.boundary,rootBoundary=options.rootBoundary,altBoundary=options.altBoundary,_options$flipVariatio=options.flipVariations,flipVariations=void 0===_options$flipVariatio||_options$flipVariatio,allowedAutoPlacements=options.allowedAutoPlacements,preferredPlacement=state.options.placement,basePlacement=getBasePlacement(preferredPlacement),fallbackPlacements=specifiedFallbackPlacements||(basePlacement===preferredPlacement||!flipVariations?[getOppositePlacement(preferredPlacement)]:function getExpandedFallbackPlacements(placement){if(getBasePlacement(placement)===enums.a)return[];var oppositePlacement=getOppositePlacement(placement);return[getOppositeVariationPlacement(placement),oppositePlacement,getOppositeVariationPlacement(oppositePlacement)]}(preferredPlacement)),placements=[preferredPlacement].concat(fallbackPlacements).reduce((function(acc,placement){return acc.concat(getBasePlacement(placement)===enums.a?function computeAutoPlacement(state,options){void 0===options&&(options={});var _options=options,placement=_options.placement,boundary=_options.boundary,rootBoundary=_options.rootBoundary,padding=_options.padding,flipVariations=_options.flipVariations,_options$allowedAutoP=_options.allowedAutoPlacements,allowedAutoPlacements=void 0===_options$allowedAutoP?enums.h:_options$allowedAutoP,variation=getVariation(placement),placements=variation?flipVariations?enums.n:enums.n.filter((function(placement){return getVariation(placement)===variation})):enums.b,allowedPlacements=placements.filter((function(placement){return allowedAutoPlacements.indexOf(placement)>=0}));0===allowedPlacements.length&&(allowedPlacements=placements);var overflows=allowedPlacements.reduce((function(acc,placement){return acc[placement]=detectOverflow(state,{placement:placement,boundary:boundary,rootBoundary:rootBoundary,padding:padding})[getBasePlacement(placement)],acc}),{});return Object.keys(overflows).sort((function(a,b){return overflows[a]-overflows[b]}))}(state,{placement:placement,boundary:boundary,rootBoundary:rootBoundary,padding:padding,flipVariations:flipVariations,allowedAutoPlacements:allowedAutoPlacements}):placement)}),[]),referenceRect=state.rects.reference,popperRect=state.rects.popper,checksMap=new Map,makeFallbackChecks=!0,firstFittingPlacement=placements[0],i=0;i<placements.length;i++){var placement=placements[i],_basePlacement=getBasePlacement(placement),isStartVariation=getVariation(placement)===enums.l,isVertical=[enums.m,enums.c].indexOf(_basePlacement)>=0,len=isVertical?"width":"height",overflow=detectOverflow(state,{placement:placement,boundary:boundary,rootBoundary:rootBoundary,altBoundary:altBoundary,padding:padding}),mainVariationSide=isVertical?isStartVariation?enums.k:enums.f:isStartVariation?enums.c:enums.m;referenceRect[len]>popperRect[len]&&(mainVariationSide=getOppositePlacement(mainVariationSide));var altVariationSide=getOppositePlacement(mainVariationSide),checks=[];if(checkMainAxis&&checks.push(overflow[_basePlacement]<=0),checkAltAxis&&checks.push(overflow[mainVariationSide]<=0,overflow[altVariationSide]<=0),checks.every((function(check){return check}))){firstFittingPlacement=placement,makeFallbackChecks=!1;break}checksMap.set(placement,checks)}if(makeFallbackChecks)for(var _loop=function _loop(_i){var fittingPlacement=placements.find((function(placement){var checks=checksMap.get(placement);if(checks)return checks.slice(0,_i).every((function(check){return check}))}));if(fittingPlacement)return firstFittingPlacement=fittingPlacement,"break"},_i=flipVariations?3:1;_i>0;_i--){if("break"===_loop(_i))break}state.placement!==firstFittingPlacement&&(state.modifiersData[name]._skip=!0,state.placement=firstFittingPlacement,state.reset=!0)}},requiresIfExists:["offset"],data:{_skip:!1}},{name:"preventOverflow",enabled:!0,phase:"main",fn:function preventOverflow(_ref){var state=_ref.state,options=_ref.options,name=_ref.name,_options$mainAxis=options.mainAxis,checkMainAxis=void 0===_options$mainAxis||_options$mainAxis,_options$altAxis=options.altAxis,checkAltAxis=void 0!==_options$altAxis&&_options$altAxis,boundary=options.boundary,rootBoundary=options.rootBoundary,altBoundary=options.altBoundary,padding=options.padding,_options$tether=options.tether,tether=void 0===_options$tether||_options$tether,_options$tetherOffset=options.tetherOffset,tetherOffset=void 0===_options$tetherOffset?0:_options$tetherOffset,overflow=detectOverflow(state,{boundary:boundary,rootBoundary:rootBoundary,padding:padding,altBoundary:altBoundary}),basePlacement=getBasePlacement(state.placement),variation=getVariation(state.placement),isBasePlacement=!variation,mainAxis=getMainAxisFromPlacement(basePlacement),altAxis=function getAltAxis(axis){return"x"===axis?"y":"x"}(mainAxis),popperOffsets=state.modifiersData.popperOffsets,referenceRect=state.rects.reference,popperRect=state.rects.popper,tetherOffsetValue="function"==typeof tetherOffset?tetherOffset(Object.assign({},state.rects,{placement:state.placement})):tetherOffset,normalizedTetherOffsetValue="number"==typeof tetherOffsetValue?{mainAxis:tetherOffsetValue,altAxis:tetherOffsetValue}:Object.assign({mainAxis:0,altAxis:0},tetherOffsetValue),offsetModifierState=state.modifiersData.offset?state.modifiersData.offset[state.placement]:null,data={x:0,y:0};if(popperOffsets){if(checkMainAxis){var _offsetModifierState$,mainSide="y"===mainAxis?enums.m:enums.f,altSide="y"===mainAxis?enums.c:enums.k,len="y"===mainAxis?"height":"width",offset=popperOffsets[mainAxis],min=offset+overflow[mainSide],max=offset-overflow[altSide],additive=tether?-popperRect[len]/2:0,minLen=variation===enums.l?referenceRect[len]:popperRect[len],maxLen=variation===enums.l?-popperRect[len]:-referenceRect[len],arrowElement=state.elements.arrow,arrowRect=tether&&arrowElement?getLayoutRect(arrowElement):{width:0,height:0},arrowPaddingObject=state.modifiersData["arrow#persistent"]?state.modifiersData["arrow#persistent"].padding:{top:0,right:0,bottom:0,left:0},arrowPaddingMin=arrowPaddingObject[mainSide],arrowPaddingMax=arrowPaddingObject[altSide],arrowLen=within(0,referenceRect[len],arrowRect[len]),minOffset=isBasePlacement?referenceRect[len]/2-additive-arrowLen-arrowPaddingMin-normalizedTetherOffsetValue.mainAxis:minLen-arrowLen-arrowPaddingMin-normalizedTetherOffsetValue.mainAxis,maxOffset=isBasePlacement?-referenceRect[len]/2+additive+arrowLen+arrowPaddingMax+normalizedTetherOffsetValue.mainAxis:maxLen+arrowLen+arrowPaddingMax+normalizedTetherOffsetValue.mainAxis,arrowOffsetParent=state.elements.arrow&&getOffsetParent(state.elements.arrow),clientOffset=arrowOffsetParent?"y"===mainAxis?arrowOffsetParent.clientTop||0:arrowOffsetParent.clientLeft||0:0,offsetModifierValue=null!=(_offsetModifierState$=null==offsetModifierState?void 0:offsetModifierState[mainAxis])?_offsetModifierState$:0,tetherMax=offset+maxOffset-offsetModifierValue,preventedOffset=within(tether?math_min(min,offset+minOffset-offsetModifierValue-clientOffset):min,offset,tether?math_max(max,tetherMax):max);popperOffsets[mainAxis]=preventedOffset,data[mainAxis]=preventedOffset-offset}if(checkAltAxis){var _offsetModifierState$2,_mainSide="x"===mainAxis?enums.m:enums.f,_altSide="x"===mainAxis?enums.c:enums.k,_offset=popperOffsets[altAxis],_len="y"===altAxis?"height":"width",_min=_offset+overflow[_mainSide],_max=_offset-overflow[_altSide],isOriginSide=-1!==[enums.m,enums.f].indexOf(basePlacement),_offsetModifierValue=null!=(_offsetModifierState$2=null==offsetModifierState?void 0:offsetModifierState[altAxis])?_offsetModifierState$2:0,_tetherMin=isOriginSide?_min:_offset-referenceRect[_len]-popperRect[_len]-_offsetModifierValue+normalizedTetherOffsetValue.altAxis,_tetherMax=isOriginSide?_offset+referenceRect[_len]+popperRect[_len]-_offsetModifierValue-normalizedTetherOffsetValue.altAxis:_max,_preventedOffset=tether&&isOriginSide?function withinMaxClamp(min,value,max){var v=within(min,value,max);return v>max?max:v}(_tetherMin,_offset,_tetherMax):within(tether?_tetherMin:_min,_offset,tether?_tetherMax:_max);popperOffsets[altAxis]=_preventedOffset,data[altAxis]=_preventedOffset-_offset}state.modifiersData[name]=data}},requiresIfExists:["offset"]},{name:"arrow",enabled:!0,phase:"main",fn:function arrow(_ref){var _state$modifiersData$,state=_ref.state,name=_ref.name,options=_ref.options,arrowElement=state.elements.arrow,popperOffsets=state.modifiersData.popperOffsets,basePlacement=getBasePlacement(state.placement),axis=getMainAxisFromPlacement(basePlacement),len=[enums.f,enums.k].indexOf(basePlacement)>=0?"height":"width";if(arrowElement&&popperOffsets){var paddingObject=function toPaddingObject(padding,state){return mergePaddingObject("number"!=typeof(padding="function"==typeof padding?padding(Object.assign({},state.rects,{placement:state.placement})):padding)?padding:expandToHashMap(padding,enums.b))}(options.padding,state),arrowRect=getLayoutRect(arrowElement),minProp="y"===axis?enums.m:enums.f,maxProp="y"===axis?enums.c:enums.k,endDiff=state.rects.reference[len]+state.rects.reference[axis]-popperOffsets[axis]-state.rects.popper[len],startDiff=popperOffsets[axis]-state.rects.reference[axis],arrowOffsetParent=getOffsetParent(arrowElement),clientSize=arrowOffsetParent?"y"===axis?arrowOffsetParent.clientHeight||0:arrowOffsetParent.clientWidth||0:0,centerToReference=endDiff/2-startDiff/2,min=paddingObject[minProp],max=clientSize-arrowRect[len]-paddingObject[maxProp],center=clientSize/2-arrowRect[len]/2+centerToReference,offset=within(min,center,max),axisProp=axis;state.modifiersData[name]=((_state$modifiersData$={})[axisProp]=offset,_state$modifiersData$.centerOffset=offset-center,_state$modifiersData$)}},effect:function arrow_effect(_ref2){var state=_ref2.state,_options$element=_ref2.options.element,arrowElement=void 0===_options$element?"[data-popper-arrow]":_options$element;null!=arrowElement&&("string"!=typeof arrowElement||(arrowElement=state.elements.popper.querySelector(arrowElement)))&&contains(state.elements.popper,arrowElement)&&(state.elements.arrow=arrowElement)},requires:["popperOffsets"],requiresIfExists:["preventOverflow"]},{name:"hide",enabled:!0,phase:"main",requiresIfExists:["preventOverflow"],fn:function hide(_ref){var state=_ref.state,name=_ref.name,referenceRect=state.rects.reference,popperRect=state.rects.popper,preventedOffsets=state.modifiersData.preventOverflow,referenceOverflow=detectOverflow(state,{elementContext:"reference"}),popperAltOverflow=detectOverflow(state,{altBoundary:!0}),referenceClippingOffsets=getSideOffsets(referenceOverflow,referenceRect),popperEscapeOffsets=getSideOffsets(popperAltOverflow,popperRect,preventedOffsets),isReferenceHidden=isAnySideFullyClipped(referenceClippingOffsets),hasPopperEscaped=isAnySideFullyClipped(popperEscapeOffsets);state.modifiersData[name]={referenceClippingOffsets:referenceClippingOffsets,popperEscapeOffsets:popperEscapeOffsets,isReferenceHidden:isReferenceHidden,hasPopperEscaped:hasPopperEscaped},state.attributes.popper=Object.assign({},state.attributes.popper,{"data-popper-reference-hidden":isReferenceHidden,"data-popper-escaped":hasPopperEscaped})}}]}),react_fast_compare=__webpack_require__(503),react_fast_compare_default=__webpack_require__.n(react_fast_compare),EMPTY_MODIFIERS=[],NOOP=function NOOP(){},NOOP_PROMISE=function NOOP_PROMISE(){return Promise.resolve(null)},Popper_EMPTY_MODIFIERS=[];function Popper(_ref){var _ref$placement=_ref.placement,placement=void 0===_ref$placement?"bottom":_ref$placement,_ref$strategy=_ref.strategy,strategy=void 0===_ref$strategy?"absolute":_ref$strategy,_ref$modifiers=_ref.modifiers,modifiers=void 0===_ref$modifiers?Popper_EMPTY_MODIFIERS:_ref$modifiers,referenceElement=_ref.referenceElement,onFirstUpdate=_ref.onFirstUpdate,innerRef=_ref.innerRef,children=_ref.children,referenceNode=react.useContext(ManagerReferenceNodeContext),_React$useState=react.useState(null),popperElement=_React$useState[0],setPopperElement=_React$useState[1],_React$useState2=react.useState(null),arrowElement=_React$useState2[0],setArrowElement=_React$useState2[1];react.useEffect((function(){setRef(innerRef,popperElement)}),[innerRef,popperElement]);var options=react.useMemo((function(){return{placement:placement,strategy:strategy,onFirstUpdate:onFirstUpdate,modifiers:[].concat(modifiers,[{name:"arrow",enabled:null!=arrowElement,options:{element:arrowElement}}])}}),[placement,strategy,onFirstUpdate,modifiers,arrowElement]),_usePopper=function usePopper(referenceElement,popperElement,options){void 0===options&&(options={});var prevOptions=react.useRef(null),optionsWithDefaults={onFirstUpdate:options.onFirstUpdate,placement:options.placement||"bottom",strategy:options.strategy||"absolute",modifiers:options.modifiers||EMPTY_MODIFIERS},_React$useState=react.useState({styles:{popper:{position:optionsWithDefaults.strategy,left:"0",top:"0"},arrow:{position:"absolute"}},attributes:{}}),state=_React$useState[0],setState=_React$useState[1],updateStateModifier=react.useMemo((function(){return{name:"updateState",enabled:!0,phase:"write",fn:function fn(_ref){var state=_ref.state,elements=Object.keys(state.elements);setState({styles:fromEntries(elements.map((function(element){return[element,state.styles[element]||{}]}))),attributes:fromEntries(elements.map((function(element){return[element,state.attributes[element]]})))})},requires:["computeStyles"]}}),[]),popperOptions=react.useMemo((function(){var newOptions={onFirstUpdate:optionsWithDefaults.onFirstUpdate,placement:optionsWithDefaults.placement,strategy:optionsWithDefaults.strategy,modifiers:[].concat(optionsWithDefaults.modifiers,[updateStateModifier,{name:"applyStyles",enabled:!1}])};return react_fast_compare_default()(prevOptions.current,newOptions)?prevOptions.current||newOptions:(prevOptions.current=newOptions,newOptions)}),[optionsWithDefaults.onFirstUpdate,optionsWithDefaults.placement,optionsWithDefaults.strategy,optionsWithDefaults.modifiers,updateStateModifier]),popperInstanceRef=react.useRef();return useIsomorphicLayoutEffect((function(){popperInstanceRef.current&&popperInstanceRef.current.setOptions(popperOptions)}),[popperOptions]),useIsomorphicLayoutEffect((function(){if(null!=referenceElement&&null!=popperElement){var popperInstance=(options.createPopper||popper_createPopper)(referenceElement,popperElement,popperOptions);return popperInstanceRef.current=popperInstance,function(){popperInstance.destroy(),popperInstanceRef.current=null}}}),[referenceElement,popperElement,options.createPopper]),{state:popperInstanceRef.current?popperInstanceRef.current.state:null,styles:state.styles,attributes:state.attributes,update:popperInstanceRef.current?popperInstanceRef.current.update:null,forceUpdate:popperInstanceRef.current?popperInstanceRef.current.forceUpdate:null}}(referenceElement||referenceNode,popperElement,options),state=_usePopper.state,styles=_usePopper.styles,forceUpdate=_usePopper.forceUpdate,update=_usePopper.update,childrenProps=react.useMemo((function(){return{ref:setPopperElement,style:styles.popper,placement:state?state.placement:placement,hasPopperEscaped:state&&state.modifiersData.hide?state.modifiersData.hide.hasPopperEscaped:null,isReferenceHidden:state&&state.modifiersData.hide?state.modifiersData.hide.isReferenceHidden:null,arrowProps:{style:styles.arrow,ref:setArrowElement},forceUpdate:forceUpdate||NOOP,update:update||NOOP_PROMISE}}),[setPopperElement,setArrowElement,placement,state,styles,update,forceUpdate]);return unwrapArray(children)(childrenProps)}var warning=__webpack_require__(1256),warning_default=__webpack_require__.n(warning);function Reference(_ref){var children=_ref.children,innerRef=_ref.innerRef,setReferenceNode=react.useContext(ManagerReferenceNodeSetterContext),refHandler=react.useCallback((function(node){setRef(innerRef,node),safeInvoke(setReferenceNode,node)}),[innerRef,setReferenceNode]);return react.useEffect((function(){return function(){return setRef(innerRef,null)}})),react.useEffect((function(){warning_default()(Boolean(setReferenceNode),"`Reference` should not be used outside of a `Manager` component.")}),[setReferenceNode]),unwrapArray(children)({ref:refHandler})}var TooltipContext=react_default.a.createContext({}),callAll=function callAll(){for(var _len=arguments.length,fns=new Array(_len),_key=0;_key<_len;_key++)fns[_key]=arguments[_key];return function(){for(var _len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++)args[_key2]=arguments[_key2];return fns.forEach((function(fn){return fn&&fn.apply(void 0,args)}))}},canUseDOM=function canUseDOM(){return!("undefined"==typeof window||!window.document||!window.document.createElement)},react_popper_tooltip_setRef=function setRef(ref,node){if("function"==typeof ref)return ref(node);null!=ref&&(ref.current=node)},react_popper_tooltip_Tooltip=function(_Component){function Tooltip(){for(var _this,_len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return(_this=_Component.call.apply(_Component,[this].concat(args))||this).observer=void 0,_this.tooltipRef=void 0,_this.handleOutsideClick=function(event){if(_this.tooltipRef&&!_this.tooltipRef.contains(event.target)){var parentOutsideClickHandler=_this.context.parentOutsideClickHandler,_this$props=_this.props,hideTooltip=_this$props.hideTooltip;(0,_this$props.clearScheduled)(),hideTooltip(),parentOutsideClickHandler&&parentOutsideClickHandler(event)}},_this.handleOutsideRightClick=function(event){if(_this.tooltipRef&&!_this.tooltipRef.contains(event.target)){var parentOutsideRightClickHandler=_this.context.parentOutsideRightClickHandler,_this$props2=_this.props,hideTooltip=_this$props2.hideTooltip;(0,_this$props2.clearScheduled)(),hideTooltip(),parentOutsideRightClickHandler&&parentOutsideRightClickHandler(event)}},_this.addOutsideClickHandler=function(){document.body.addEventListener("touchend",_this.handleOutsideClick),document.body.addEventListener("click",_this.handleOutsideClick)},_this.removeOutsideClickHandler=function(){document.body.removeEventListener("touchend",_this.handleOutsideClick),document.body.removeEventListener("click",_this.handleOutsideClick)},_this.addOutsideRightClickHandler=function(){return document.body.addEventListener("contextmenu",_this.handleOutsideRightClick)},_this.removeOutsideRightClickHandler=function(){return document.body.removeEventListener("contextmenu",_this.handleOutsideRightClick)},_this.getTooltipRef=function(node){_this.tooltipRef=node,react_popper_tooltip_setRef(_this.props.innerRef,node)},_this.getArrowProps=function(props){return void 0===props&&(props={}),Object(esm_extends.a)({},props,{style:Object(esm_extends.a)({},props.style,_this.props.arrowProps.style)})},_this.getTooltipProps=function(props){return void 0===props&&(props={}),Object(esm_extends.a)({},props,_this.isTriggeredBy("hover")&&{onMouseEnter:callAll(_this.props.clearScheduled,props.onMouseEnter),onMouseLeave:callAll(_this.props.hideTooltip,props.onMouseLeave)},{style:Object(esm_extends.a)({},props.style,_this.props.style)})},_this.contextValue={isParentNoneTriggered:"none"===_this.props.trigger,addParentOutsideClickHandler:_this.addOutsideClickHandler,addParentOutsideRightClickHandler:_this.addOutsideRightClickHandler,parentOutsideClickHandler:_this.handleOutsideClick,parentOutsideRightClickHandler:_this.handleOutsideRightClick,removeParentOutsideClickHandler:_this.removeOutsideClickHandler,removeParentOutsideRightClickHandler:_this.removeOutsideRightClickHandler},_this}Object(inheritsLoose.a)(Tooltip,_Component);var _proto=Tooltip.prototype;return _proto.componentDidMount=function componentDidMount(){var _this2=this;if((this.observer=new MutationObserver((function(){_this2.props.update()}))).observe(this.tooltipRef,this.props.mutationObserverOptions),this.isTriggeredBy("hover")||this.isTriggeredBy("click")||this.isTriggeredBy("right-click")){var _this$context=this.context,removeParentOutsideClickHandler=_this$context.removeParentOutsideClickHandler,removeParentOutsideRightClickHandler=_this$context.removeParentOutsideRightClickHandler;this.addOutsideClickHandler(),this.addOutsideRightClickHandler(),removeParentOutsideClickHandler&&removeParentOutsideClickHandler(),removeParentOutsideRightClickHandler&&removeParentOutsideRightClickHandler()}},_proto.componentDidUpdate=function componentDidUpdate(){this.props.closeOnReferenceHidden&&this.props.isReferenceHidden&&this.props.hideTooltip()},_proto.componentWillUnmount=function componentWillUnmount(){if(this.observer&&this.observer.disconnect(),this.isTriggeredBy("hover")||this.isTriggeredBy("click")||this.isTriggeredBy("right-click")){var _this$context2=this.context,isParentNoneTriggered=_this$context2.isParentNoneTriggered,addParentOutsideClickHandler=_this$context2.addParentOutsideClickHandler,addParentOutsideRightClickHandler=_this$context2.addParentOutsideRightClickHandler;this.removeOutsideClickHandler(),this.removeOutsideRightClickHandler(),this.handleOutsideClick=void 0,this.handleOutsideRightClick=void 0,!isParentNoneTriggered&&addParentOutsideClickHandler&&addParentOutsideClickHandler(),!isParentNoneTriggered&&addParentOutsideRightClickHandler&&addParentOutsideRightClickHandler()}},_proto.render=function render(){var _this$props3=this.props,arrowProps=_this$props3.arrowProps,placement=_this$props3.placement,tooltip=_this$props3.tooltip;return react_default.a.createElement(TooltipContext.Provider,{value:this.contextValue},tooltip({arrowRef:arrowProps.ref,getArrowProps:this.getArrowProps,getTooltipProps:this.getTooltipProps,placement:placement,tooltipRef:this.getTooltipRef}))},_proto.isTriggeredBy=function isTriggeredBy(event){var trigger=this.props.trigger;return trigger===event||Array.isArray(trigger)&&trigger.includes(event)},Tooltip}(react.Component);react_popper_tooltip_Tooltip.contextType=TooltipContext;var react_popper_tooltip_TooltipTrigger=function(_Component){function TooltipTrigger(){for(var _this,_len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++)args[_key]=arguments[_key];return(_this=_Component.call.apply(_Component,[this].concat(args))||this).state={tooltipShown:_this.props.defaultTooltipShown},_this.hideTimeout=void 0,_this.showTimeout=void 0,_this.popperOffset=void 0,_this.setTooltipState=function(state){var cb=function cb(){return _this.props.onVisibilityChange(state.tooltipShown)};_this.isControlled()?cb():_this.setState(state,cb)},_this.clearScheduled=function(){clearTimeout(_this.hideTimeout),clearTimeout(_this.showTimeout)},_this.showTooltip=function(_ref){var pageX=_ref.pageX,pageY=_ref.pageY;_this.clearScheduled();var state={tooltipShown:!0};_this.props.followCursor&&(state=Object(esm_extends.a)({},state,{pageX:pageX,pageY:pageY})),_this.showTimeout=window.setTimeout((function(){return _this.setTooltipState(state)}),_this.props.delayShow)},_this.hideTooltip=function(){_this.clearScheduled(),_this.hideTimeout=window.setTimeout((function(){return _this.setTooltipState({tooltipShown:!1})}),_this.props.delayHide)},_this.toggleTooltip=function(_ref2){var pageX=_ref2.pageX,pageY=_ref2.pageY,action=_this.getState()?"hideTooltip":"showTooltip";_this[action]({pageX:pageX,pageY:pageY})},_this.clickToggle=function(event){event.preventDefault();var pageX=event.pageX,pageY=event.pageY,action=_this.props.followCursor?"showTooltip":"toggleTooltip";_this[action]({pageX:pageX,pageY:pageY})},_this.contextMenuToggle=function(event){event.preventDefault();var pageX=event.pageX,pageY=event.pageY,action=_this.props.followCursor?"showTooltip":"toggleTooltip";_this[action]({pageX:pageX,pageY:pageY})},_this.getTriggerProps=function(props){return void 0===props&&(props={}),Object(esm_extends.a)({},props,_this.isTriggeredBy("click")&&{onClick:callAll(_this.clickToggle,props.onClick),onTouchEnd:callAll(_this.clickToggle,props.onTouchEnd)},_this.isTriggeredBy("right-click")&&{onContextMenu:callAll(_this.contextMenuToggle,props.onContextMenu)},_this.isTriggeredBy("hover")&&Object(esm_extends.a)({onMouseEnter:callAll(_this.showTooltip,props.onMouseEnter),onMouseLeave:callAll(_this.hideTooltip,props.onMouseLeave)},_this.props.followCursor&&{onMouseMove:callAll(_this.showTooltip,props.onMouseMove)}),_this.isTriggeredBy("focus")&&{onFocus:callAll(_this.showTooltip,props.onFocus),onBlur:callAll(_this.hideTooltip,props.onBlur)})},_this}Object(inheritsLoose.a)(TooltipTrigger,_Component);var _proto=TooltipTrigger.prototype;return _proto.componentWillUnmount=function componentWillUnmount(){this.clearScheduled()},_proto.render=function render(){var _this2=this,_this$props=this.props,children=_this$props.children,tooltip=_this$props.tooltip,placement=_this$props.placement,trigger=_this$props.trigger,getTriggerRef=_this$props.getTriggerRef,modifiers=_this$props.modifiers,closeOnReferenceHidden=_this$props.closeOnReferenceHidden,usePortal=_this$props.usePortal,portalContainer=_this$props.portalContainer,followCursor=_this$props.followCursor,getTooltipRef=_this$props.getTooltipRef,mutationObserverOptions=_this$props.mutationObserverOptions,restProps=Object(objectWithoutPropertiesLoose.a)(_this$props,["children","tooltip","placement","trigger","getTriggerRef","modifiers","closeOnReferenceHidden","usePortal","portalContainer","followCursor","getTooltipRef","mutationObserverOptions"]),popper=react_default.a.createElement(Popper,Object(esm_extends.a)({innerRef:getTooltipRef,placement:placement,modifiers:[{name:"followCursor",enabled:followCursor,phase:"main",fn:function fn(data){_this2.popperOffset=data.state.rects.popper}}].concat(modifiers)},restProps),(function(_ref3){var ref=_ref3.ref,style=_ref3.style,placement=_ref3.placement,arrowProps=_ref3.arrowProps,isReferenceHidden=_ref3.isReferenceHidden,update=_ref3.update;if(followCursor&&_this2.popperOffset){var _this2$state=_this2.state,pageX=_this2$state.pageX,pageY=_this2$state.pageY,_this2$popperOffset=_this2.popperOffset,width=_this2$popperOffset.width,height=_this2$popperOffset.height,x=pageX+width>window.pageXOffset+document.body.offsetWidth?pageX-width:pageX,y=pageY+height>window.pageYOffset+document.body.offsetHeight?pageY-height:pageY;style.transform="translate3d("+x+"px, "+y+"px, 0"}return react_default.a.createElement(react_popper_tooltip_Tooltip,Object(esm_extends.a)({arrowProps:arrowProps,closeOnReferenceHidden:closeOnReferenceHidden,isReferenceHidden:isReferenceHidden,placement:placement,update:update,style:style,tooltip:tooltip,trigger:trigger,mutationObserverOptions:mutationObserverOptions},{clearScheduled:_this2.clearScheduled,hideTooltip:_this2.hideTooltip,innerRef:ref}))}));return react_default.a.createElement(Manager,null,react_default.a.createElement(Reference,{innerRef:getTriggerRef},(function(_ref4){var ref=_ref4.ref;return children({getTriggerProps:_this2.getTriggerProps,triggerRef:ref})})),this.getState()&&(usePortal?Object(react_dom.createPortal)(popper,portalContainer):popper))},_proto.isControlled=function isControlled(){return void 0!==this.props.tooltipShown},_proto.getState=function getState(){return this.isControlled()?this.props.tooltipShown:this.state.tooltipShown},_proto.isTriggeredBy=function isTriggeredBy(event){var trigger=this.props.trigger;return trigger===event||Array.isArray(trigger)&&trigger.includes(event)},TooltipTrigger}(react.Component);react_popper_tooltip_TooltipTrigger.defaultProps={closeOnReferenceHidden:!0,defaultTooltipShown:!1,delayHide:0,delayShow:0,followCursor:!1,onVisibilityChange:function noop(){},placement:"right",portalContainer:canUseDOM()?document.body:null,trigger:"hover",usePortal:canUseDOM(),mutationObserverOptions:{childList:!0,subtree:!0},modifiers:[]};var react_popper_tooltip=react_popper_tooltip_TooltipTrigger,memoizerific=(__webpack_require__(69),__webpack_require__(28),__webpack_require__(184),__webpack_require__(18),__webpack_require__(32)),memoizerific_default=__webpack_require__.n(memoizerific),utils=__webpack_require__(105);function _extends(){return _extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target},_extends.apply(this,arguments)}function _objectWithoutProperties(source,excluded){if(null==source)return{};var key,i,target=function _objectWithoutPropertiesLoose(source,excluded){if(null==source)return{};var key,i,target={},sourceKeys=Object.keys(source);for(i=0;i<sourceKeys.length;i++)key=sourceKeys[i],excluded.indexOf(key)>=0||(target[key]=source[key]);return target}(source,excluded);if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i<sourceSymbolKeys.length;i++)key=sourceSymbolKeys[i],excluded.indexOf(key)>=0||Object.prototype.propertyIsEnumerable.call(source,key)&&(target[key]=source[key])}return target}var _templateObject,_templateObject2,match=memoizerific_default()(1e3)((function(requests,actual,value){var fallback=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;return actual.split("-")[0]===requests?value:fallback})),Arrow=esm.styled.div({position:"absolute",borderStyle:"solid"},(function(_ref){var placement=_ref.placement,x=0,y=0;switch(!0){case placement.startsWith("left")||placement.startsWith("right"):y=8;break;case placement.startsWith("top")||placement.startsWith("bottom"):x=8}return{transform:"translate3d(".concat(x,"px, ").concat(y,"px, 0px)")}}),(function(_ref2){var theme=_ref2.theme,color=_ref2.color,placement=_ref2.placement;return{bottom:"".concat(match("top",placement,-8,"auto"),"px"),top:"".concat(match("bottom",placement,-8,"auto"),"px"),right:"".concat(match("left",placement,-8,"auto"),"px"),left:"".concat(match("right",placement,-8,"auto"),"px"),borderBottomWidth:"".concat(match("top",placement,"0",8),"px"),borderTopWidth:"".concat(match("bottom",placement,"0",8),"px"),borderRightWidth:"".concat(match("left",placement,"0",8),"px"),borderLeftWidth:"".concat(match("right",placement,"0",8),"px"),borderTopColor:match("top",placement,theme.color[color]||color||"light"===theme.base?Object(utils.c)(theme.background.app):Object(utils.a)(theme.background.app),"transparent"),borderBottomColor:match("bottom",placement,theme.color[color]||color||"light"===theme.base?Object(utils.c)(theme.background.app):Object(utils.a)(theme.background.app),"transparent"),borderLeftColor:match("left",placement,theme.color[color]||color||"light"===theme.base?Object(utils.c)(theme.background.app):Object(utils.a)(theme.background.app),"transparent"),borderRightColor:match("right",placement,theme.color[color]||color||"light"===theme.base?Object(utils.c)(theme.background.app):Object(utils.a)(theme.background.app),"transparent")}})),Wrapper=esm.styled.div((function(_ref3){return{display:_ref3.hidden?"none":"inline-block",zIndex:2147483647}}),(function(_ref4){var theme=_ref4.theme,color=_ref4.color;return _ref4.hasChrome?{background:theme.color[color]||color||"light"===theme.base?Object(utils.c)(theme.background.app):Object(utils.a)(theme.background.app),filter:"\n drop-shadow(0px 5px 5px rgba(0,0,0,0.05))\n drop-shadow(0 1px 3px rgba(0,0,0,0.1))\n ",borderRadius:2*theme.appBorderRadius,fontSize:theme.typography.size.s1}:{}})),Tooltip_Tooltip=function Tooltip(_ref5){var placement=_ref5.placement,hasChrome=_ref5.hasChrome,children=_ref5.children,arrowProps=_ref5.arrowProps,tooltipRef=_ref5.tooltipRef,arrowRef=_ref5.arrowRef,color=_ref5.color,props=_objectWithoutProperties(_ref5,["placement","hasChrome","children","arrowProps","tooltipRef","arrowRef","color"]);return react_default.a.createElement(Wrapper,_extends({hasChrome:hasChrome,placement:placement,ref:tooltipRef},props,{color:color}),hasChrome&&react_default.a.createElement(Arrow,_extends({placement:placement,ref:arrowRef},arrowProps,{color:color})),children)};function _slicedToArray(arr,i){return function _arrayWithHoles(arr){if(Array.isArray(arr))return arr}(arr)||function _iterableToArrayLimit(arr,i){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(arr)))return;var _arr=[],_n=!0,_d=!1,_e=void 0;try{for(var _s,_i=arr[Symbol.iterator]();!(_n=(_s=_i.next()).done)&&(_arr.push(_s.value),!i||_arr.length!==i);_n=!0);}catch(err){_d=!0,_e=err}finally{try{_n||null==_i.return||_i.return()}finally{if(_d)throw _e}}return _arr}(arr,i)||function _unsupportedIterableToArray(o,minLen){if(!o)return;if("string"==typeof o)return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);"Object"===n&&o.constructor&&(n=o.constructor.name);if("Map"===n||"Set"===n)return Array.from(o);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}(arr,i)||function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _arrayLikeToArray(arr,len){(null==len||len>arr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i<len;i++)arr2[i]=arr[i];return arr2}function WithTooltip_extends(){return WithTooltip_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source)Object.prototype.hasOwnProperty.call(source,key)&&(target[key]=source[key])}return target},WithTooltip_extends.apply(this,arguments)}function WithTooltip_objectWithoutProperties(source,excluded){if(null==source)return{};var key,i,target=function WithTooltip_objectWithoutPropertiesLoose(source,excluded){if(null==source)return{};var key,i,target={},sourceKeys=Object.keys(source);for(i=0;i<sourceKeys.length;i++)key=sourceKeys[i],excluded.indexOf(key)>=0||(target[key]=source[key]);return target}(source,excluded);if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i<sourceSymbolKeys.length;i++)key=sourceSymbolKeys[i],excluded.indexOf(key)>=0||Object.prototype.propertyIsEnumerable.call(source,key)&&(target[key]=source[key])}return target}function _taggedTemplateLiteral(strings,raw){return raw||(raw=strings.slice(0)),Object.freeze(Object.defineProperties(strings,{raw:{value:Object.freeze(raw)}}))}Tooltip_Tooltip.displayName="Tooltip",Tooltip_Tooltip.defaultProps={color:void 0,arrowRef:void 0,tooltipRef:void 0,hasChrome:!0,placement:"top",arrowProps:{}};var WithTooltip_document=window_default.a.document,TargetContainer=esm.styled.div(_templateObject||(_templateObject=_taggedTemplateLiteral(["\n display: inline-block;\n cursor: ",";\n"])),(function(props){return"hover"===props.mode?"default":"pointer"})),TargetSvgContainer=esm.styled.g(_templateObject2||(_templateObject2=_taggedTemplateLiteral(["\n cursor: ",";\n"])),(function(props){return"hover"===props.mode?"default":"pointer"})),WithTooltip_WithTooltipPure=function WithTooltipPure(_ref){var svg=_ref.svg,trigger=_ref.trigger,placement=(_ref.closeOnClick,_ref.placement),modifiers=_ref.modifiers,hasChrome=_ref.hasChrome,_tooltip=_ref.tooltip,children=_ref.children,tooltipShown=_ref.tooltipShown,onVisibilityChange=_ref.onVisibilityChange,props=WithTooltip_objectWithoutProperties(_ref,["svg","trigger","closeOnClick","placement","modifiers","hasChrome","tooltip","children","tooltipShown","onVisibilityChange"]),Container=svg?TargetSvgContainer:TargetContainer;return react_default.a.createElement(react_popper_tooltip,{placement:placement,trigger:trigger,modifiers:modifiers,tooltipShown:tooltipShown,onVisibilityChange:onVisibilityChange,tooltip:function tooltip(_ref2){var getTooltipProps=_ref2.getTooltipProps,getArrowProps=_ref2.getArrowProps,tooltipRef=_ref2.tooltipRef,arrowRef=_ref2.arrowRef,tooltipPlacement=_ref2.placement;return react_default.a.createElement(Tooltip_Tooltip,WithTooltip_extends({hasChrome:hasChrome,placement:tooltipPlacement,tooltipRef:tooltipRef,arrowRef:arrowRef,arrowProps:getArrowProps()},getTooltipProps()),"function"==typeof _tooltip?_tooltip({onHide:function onHide(){return onVisibilityChange(!1)}}):_tooltip)}},(function(_ref3){var getTriggerProps=_ref3.getTriggerProps,triggerRef=_ref3.triggerRef;return react_default.a.createElement(Container,WithTooltip_extends({ref:triggerRef},getTriggerProps(),props),children)}))};WithTooltip_WithTooltipPure.displayName="WithTooltipPure",WithTooltip_WithTooltipPure.defaultProps={svg:!1,trigger:"hover",closeOnClick:!1,placement:"top",modifiers:[{name:"preventOverflow",options:{padding:8}},{name:"offset",options:{offset:[8,8]}},{name:"arrow",options:{padding:8}}],hasChrome:!0,tooltipShown:!1};var WithTooltip_WithToolTipState=function WithToolTipState(_ref4){var startOpen=_ref4.startOpen,onChange=_ref4.onVisibilityChange,rest=WithTooltip_objectWithoutProperties(_ref4,["startOpen","onVisibilityChange"]),_useState2=_slicedToArray(Object(react.useState)(startOpen||!1),2),tooltipShown=_useState2[0],setTooltipShown=_useState2[1],onVisibilityChange=Object(react.useCallback)((function(visibility){onChange&&!1===onChange(visibility)||setTooltipShown(visibility)}),[onChange]);return Object(react.useEffect)((function(){var hide=function hide(){return onVisibilityChange(!1)};WithTooltip_document.addEventListener("keydown",hide,!1);var iframes=Array.from(WithTooltip_document.getElementsByTagName("iframe")),unbinders=[];return iframes.forEach((function(iframe){var bind=function bind(){try{iframe.contentWindow.document&&(iframe.contentWindow.document.addEventListener("click",hide),unbinders.push((function(){try{iframe.contentWindow.document.removeEventListener("click",hide)}catch(e){}})))}catch(e){}};bind(),iframe.addEventListener("load",bind),unbinders.push((function(){iframe.removeEventListener("load",bind)}))})),function(){WithTooltip_document.removeEventListener("keydown",hide),unbinders.forEach((function(unbind){unbind()}))}})),react_default.a.createElement(WithTooltip_WithTooltipPure,WithTooltip_extends({},rest,{tooltipShown:tooltipShown,onVisibilityChange:onVisibilityChange}))};WithTooltip_WithToolTipState.displayName="WithToolTipState"}}]);
var common = require('../common.js').common; // Start of test script. casper.start('http://localhost:9981/', common.initialize_casper); casper.then(function () { casper.test.assertHttpStatus(302); casper.test.assertUrlMatch(/^http:\/\/[^\/]+\/login/, 'Redirected to /login'); }); common.then_log_in(); casper.waitForSelector('#zhome', function () { casper.test.info('Logging out'); casper.click('li[title="Log out"] a'); }); casper.then(function () { casper.test.assertHttpStatus(200); casper.test.assertUrlMatch(/accounts\/login\/$/); }); // Run the above queued actions. casper.run(function () { casper.test.done(); });
import Vue from 'vue' Vue.filter('formatData', function (value) { let date = new Date(value) let year = date.getFullYear() let month = (date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate( ) let hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours() let minute = date.getMinutes() < 10 ? '0' + date .getMinutes() : date.getMinutes() return `${year}-${month}-${day} ${hour}:${minute}` })
const net = require("net"); const server = net.createServer(socket => { socket.once('data', (data) => { console.log(data.toString()); socket.write(data); }); }); server.listen(3000, '127.0.0.1', () => { console.log(`Server running at 127.0.0.1:3000`); });
function get_connectivitytable_index(a){"\n"!=a[a.length-1]&&(a+="\n"),idx={};var b=0,c="",d=a.match(/[^\r\n]+/g);for(var e in d){var f=d[e];if(0==b){var g=f.match(/([0-9]+)(?:\t|[ ]{2,})([^\n]+)/);c=g[2],b=parseInt(g[1]),idx[c]={sequence:"",structure:".".repeat(b)}}else{var g=f.match(/[^\t\ ]+/g);idx[c].sequence+=g[1];var h=parseInt(g[4]);if(0!=h){var i=idx[c].structure.split("");i[h-1]="(",i[parseInt(g[0])-1]=")",idx[c].structure=i.join("")}b-=1}}return idx}
import "./info.js"; import "./inputs.js"; export function initControls(the_map, departure_time, comparison_port) { const infoControl = L.control.sectioninfo({ position: 'topright'}, comparison_port).addTo(the_map); const inputsControl = L.control.inputs({position: 'topleft'}).addTo(the_map); inputsControl.setValueAsNbSeconds(departure_time); return [infoControl, inputsControl]; };
/*! * froala_editor v2.1.0 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms * Copyright 2014-2016 Froala Labs */ !function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof module&&module.exports?module.exports=function(b,c){return void 0===c&&(c="undefined"!=typeof window?require("jquery"):require("jquery")(b)),a(c),c}:a(jQuery)}(function(a){"use strict";a.extend(a.FroalaEditor.POPUP_TEMPLATES,{"table.insert":"[_BUTTONS_][_ROWS_COLUMNS_]","table.edit":"[_BUTTONS_]","table.colors":"[_BUTTONS_][_COLORS_]"}),a.extend(a.FroalaEditor.DEFAULTS,{tableInsertMaxSize:10,tableEditButtons:["tableHeader","tableRemove","|","tableRows","tableColumns","tableStyle","-","tableCells","tableCellBackground","tableCellVerticalAlign","tableCellHorizontalAlign","tableCellStyle"],tableInsertButtons:["tableBack","|"],tableResizerOffset:5,tableResizingLimit:30,tableColorsButtons:["tableBack","|"],tableColors:["#61BD6D","#1ABC9C","#54ACD2","#2C82C9","#9365B8","#475577","#CCCCCC","#41A85F","#00A885","#3D8EB9","#2969B0","#553982","#28324E","#000000","#F7DA64","#FBA026","#EB6B56","#E25041","#A38F84","#EFEFEF","#FFFFFF","#FAC51C","#F37934","#D14841","#B8312F","#7C706B","#D1D5D8","REMOVE"],tableColorsStep:7,tableCellStyles:{"fr-highlighted":"Highlighted","fr-thick":"Thick"},tableStyles:{"fr-dashed-borders":"Dashed Borders","fr-alternate-rows":"Alternate Rows"},tableCellMultipleStyles:!0,tableMultipleStyles:!0,tableInsertHelper:!0,tableInsertHelperOffset:20}),a.FroalaEditor.PLUGINS.table=function(b){function c(){var a=b.$tb.find('.fr-command[data-cmd="insertTable"]'),c=b.popups.get("table.insert");if(c||(c=g()),!c.hasClass("fr-active")){b.popups.refresh("table.insert"),b.popups.setContainer("table.insert",b.$tb);var d=a.offset().left+a.outerWidth()/2,e=a.offset().top+(b.opts.toolbarBottom?10:a.outerHeight()-10);b.popups.show("table.insert",d,e,a.outerHeight())}}function d(){var c=B();if(c){var d=b.popups.get("table.edit");d||(d=i()),b.popups.setContainer("table.edit",a(b.opts.scrollableContainer));var e=I(c),f=(e.left+e.right)/2,g=e.bottom;if(b.popups.show("table.edit",f,g,e.bottom-e.top),b.$el.find(".fr-selected-cell").length>1){b.toolbar.disable(),b.$el.removeClass("fr-no-selection"),b.edit.on();var h=a(b.original_window).scrollTop();b.$el.focus(),b.selection.setAtEnd(b.$el.find(".fr-selected-cell:last").get(0)),b.selection.restore(),a(b.original_window).scrollTop(h),b.button.bulkRefresh()}}}function e(){var c=B();if(c){var d=b.popups.get("table.colors");d||(d=j()),b.popups.setContainer("table.colors",a(b.opts.scrollableContainer));var e=I(c),f=(e.left+e.right)/2,g=e.bottom;l(),b.popups.show("table.colors",f,g,e.bottom-e.top)}}function f(){0===b.$el.get(0).querySelectorAll(".fr-selected-cell").length&&b.toolbar.enable()}function g(){var c="";b.opts.tableInsertButtons.length>0&&(c='<div class="fr-buttons">'+b.button.buildList(b.opts.tableInsertButtons)+"</div>");var d={buttons:c,rows_columns:h()},e=b.popups.create("table.insert",d);return b.popups.onHide("table.insert",function(){e.find('.fr-table-size .fr-select-table-size > span[data-row="1"][data-col="1"]').trigger("mouseenter")}),e.on("mouseenter",".fr-table-size .fr-select-table-size .fr-table-cell",function(c){var d=a(c.currentTarget),e=d.data("row"),f=d.data("col"),g=d.parent();g.siblings(".fr-table-size-info").html(e+" &times; "+f),g.find("> span").removeClass("hover");for(var h=1;h<=b.opts.tableInsertMaxSize;h++)for(var i=0;i<=b.opts.tableInsertMaxSize;i++){var j=g.find('> span[data-row="'+h+'"][data-col="'+i+'"]');e>=h&&f>=i?j.addClass("hover"):e+1>=h||2>=h&&!b.helpers.isMobile()?j.css("display","inline-block"):h>2&&!b.helpers.isMobile()&&j.css("display","none")}}),b.events.on("destroy",function(){e.off("mouseenter",".fr-table-size .fr-select-table-size .fr-table-cell")},!0),e}function h(){for(var a='<div class="fr-table-size"><div class="fr-table-size-info">1 &times; 1</div><div class="fr-select-table-size">',c=1;c<=b.opts.tableInsertMaxSize;c++){for(var d=1;d<=b.opts.tableInsertMaxSize;d++){var e="inline-block";c>2&&!b.helpers.isMobile()&&(e="none");var f="fr-table-cell ";1==c&&1==d&&(f+=" hover"),a+='<span class="fr-command '+f+'" data-cmd="tableInsert" data-row="'+c+'" data-col="'+d+'" data-param1="'+c+'" data-param2="'+d+'" style="display: '+e+';"><span></span></span>'}a+='<div class="new-line"></div>'}return a+="</div></div>"}function i(){var a="";b.opts.tableEditButtons.length>0&&(a='<div class="fr-buttons">'+b.button.buildList(b.opts.tableEditButtons)+"</div>");var c={buttons:a},e=b.popups.create("table.edit",c);return b.popups.onHide("table.edit",f),b.$wp.on("scroll.table-edit",function(){b.popups.isVisible("table.edit")&&d()}),b.events.on("destroy",function(){b.$wp.off("scroll.table-edit")}),e}function j(){var a="";b.opts.tableColorsButtons.length>0&&(a='<div class="fr-buttons fr-table-colors-buttons">'+b.button.buildList(b.opts.tableColorsButtons)+"</div>");var c={buttons:a,colors:k()},d=b.popups.create("table.colors",c);return b.$wp.on("scroll.table-colors",function(){b.popups.isVisible("table.colors")&&e()}),b.events.on("destroy",function(){b.$wp.off("scroll.table-colors")}),d}function k(){for(var a='<div class="fr-table-colors">',c=0;c<b.opts.tableColors.length;c++)0!==c&&c%b.opts.tableColorsStep===0&&(a+="<br>"),a+="REMOVE"!=b.opts.tableColors[c]?'<span class="fr-command" style="background: '+b.opts.tableColors[c]+';" data-cmd="tableCellBackgroundColor" data-param1="'+b.opts.tableColors[c]+'"></span>':'<span class="fr-command" data-cmd="tableCellBackgroundColor" data-param1="REMOVE" title="'+b.language.translate("Clear Formatting")+'"><i class="fa fa-eraser"></i></span>';return a+="</div>"}function l(){var a=b.popups.get("table.colors"),c=b.$el.find(".fr-selected-cell:first");a.find(".fr-selected-color").removeClass("fr-selected-color"),a.find('span[data-param1="'+b.helpers.RGBToHex(c.css("background-color"))+'"]').addClass("fr-selected-color")}function m(c,d){var e,f,g='<table style="width: 100%;"><tbody>',h=100/d;for(e=0;c>e;e++){for(g+="<tr>",f=0;d>f;f++)g+='<td style="width: '+h.toFixed(4)+'%;">',0===e&&0===f&&(g+=a.FroalaEditor.MARKERS),g+="<br></td>";g+="</tr>"}g+="</tbody></table>",b.html.insert(g),b.selection.restore()}function n(){if(b.$el.find(".fr-selected-cell").length>0){var a=b.$el.find(".fr-selected-cell").closest("table");b.selection.setBefore(a.get(0))||b.selection.setAfter(a.get(0)),b.selection.restore(),b.popups.hide("table.edit"),a.remove()}}function o(){var c=b.$el.find(".fr-selected-cell").closest("table");if(c.length>0&&0===c.find("th").length){var e,f="<thead><tr>",g=0;for(c.find("tr:first > td").each(function(){var b=a(this);g+=parseInt(b.attr("colspan"),10)||1}),e=0;g>e;e++)f+="<th><br></th>";f+="</tr></thead>",c.prepend(f),d()}}function p(){var a=b.$el.find(".fr-selected-cell").closest("table"),c=a.find("thead");if(c.length>0)if(0===a.find("tbody tr").length)n();else if(c.remove(),b.$el.find(".fr-selected-cell").length>0)d();else{b.popups.hide("table.edit");var e=a.find("tbody tr:first td:first").get(0);e&&(b.selection.setAtEnd(e),b.selection.restore())}}function q(c){var e=b.$el.find(".fr-selected-cell").closest("table");if(e.length>0){if(b.$el.find("th.fr-selected-cell").length>0&&"above"==c)return;var f,g,h=B(),i=G(h);g="above"==c?i.min_i:i.max_i;var j="<tr>";for(f=0;f<h[g].length;f++)if("below"==c&&g<h.length-1&&h[g][f]==h[g+1][f]||"above"==c&&g>0&&h[g][f]==h[g-1][f]){if(0===f||f>0&&h[g][f]!=h[g][f-1]){var k=a(h[g][f]);k.attr("rowspan",parseInt(k.attr("rowspan"),10)+1)}}else j+="<td><br></td>";j+="</tr>";var l=a(e.find("tr").not(e.find("table tr")).get(g));"below"==c?l.after(j):"above"==c&&(l.before(j),b.popups.isVisible("table.edit")&&d())}}function r(){var c=b.$el.find(".fr-selected-cell").closest("table");if(c.length>0){var d,e,f,g=B(),h=G(g);if(0===h.min_i&&h.max_i==g.length-1)n();else{for(d=h.max_i;d>=h.min_i;d--){for(f=a(c.find("tr").not(c.find("table tr")).get(d)),e=0;e<g[d].length;e++)if(0===e||g[d][e]!=g[d][e-1]){var i=a(g[d][e]);if(parseInt(i.attr("rowspan"),10)>1){var j=parseInt(i.attr("rowspan"),10)-1;1==j?i.removeAttr("rowspan"):i.attr("rowspan",j)}if(d<g.length-1&&g[d][e]==g[d+1][e]&&(0===d||g[d][e]!=g[d-1][e])){for(var k=g[d][e],l=e;l>0&&g[d][l]==g[d][l-1];)l--;0===l?a(c.find("tr").not(c.find("table tr")).get(d+1)).prepend(k):a(g[d+1][l-1]).after(k)}}var m=f.parent();f.remove(),0===m.find("tr").length&&m.remove(),g=B(c)}h.min_i>0?b.selection.setAtEnd(g[h.min_i-1][0]):b.selection.setAtEnd(g[0][0]),b.selection.restore(),b.popups.hide("table.edit")}}}function s(c){var e=b.$el.find(".fr-selected-cell").closest("table");if(e.length>0){var f,g=B(),h=G(g);f="before"==c?h.min_j:h.max_j;var i,j=100/g[0].length,k=100/(g[0].length+1);e.find("th, td").each(function(){i=a(this),i.data("old-width",i.outerWidth()/e.outerWidth()*100)}),e.find("tr").not(e.find("table tr")).each(function(b){for(var d,e=a(this),h=0,i=0;f>h-1;){if(d=e.find("> th, > td").get(i),!d){d=null;break}d==g[b][h]?(h+=parseInt(a(d).attr("colspan"),10)||1,i++):(h+=parseInt(a(g[b][h]).attr("colspan"),10)||1,"after"==c&&(d=0===i?-1:e.find("> th, > td").get(i-1)))}var l=a(d);if("after"==c&&h-1>f||"before"==c&&f>0&&g[b][f]==g[b][f-1]){if(0===b||b>0&&g[b][f]!=g[b-1][f]){var m=parseInt(l.attr("colspan"),10)+1;l.attr("colspan",m),l.css("width",(l.data("old-width")*k/j+k).toFixed(4)+"%"),l.removeData("old-width")}}else{var n;n=e.find("th").length>0?'<th style="width: '+k.toFixed(4)+'%;"><br></th>':'<td style="width: '+k.toFixed(4)+'%;"><br></td>',-1==d?e.prepend(n):null==d?e.append(n):"before"==c?l.before(n):"after"==c&&l.after(n)}}),e.find("th, td").each(function(){i=a(this),i.data("old-width")&&(i.css("width",(i.data("old-width")*k/j).toFixed(4)+"%"),i.removeData("old-width"))}),b.popups.isVisible("table.edit")&&d()}}function t(){var c=b.$el.find(".fr-selected-cell").closest("table");if(c.length>0){var d,e,f,g=B(),h=G(g);if(0===h.min_j&&h.max_j==g[0].length-1)n();else{var i=100/g[0].length,j=100/(g[0].length-h.max_j+h.min_j-1);for(c.find("th, td").each(function(){f=a(this),f.hasClass("fr-selected-cell")||f.data("old-width",f.outerWidth()/c.outerWidth()*100)}),e=h.max_j;e>=h.min_j;e--)for(d=0;d<g.length;d++)if(0===d||g[d][e]!=g[d-1][e])if(f=a(g[d][e]),parseInt(f.attr("colspan"),10)>1){var k=parseInt(f.attr("colspan"),10)-1;1==k?f.removeAttr("colspan"):f.attr("colspan",k),f.css("width",((f.data("old-width")-Y(e,g))*j/i).toFixed(4)+"%"),f.removeData("old-width")}else{var l=a(f.parent().get(0));f.remove(),0===l.find("> th, > td").length&&(0===l.prev().length||0===l.next().length||l.prev().find("> th[rowspan], > td[rowspan]").length<l.prev().find("> th, > td").length)&&l.remove()}h.min_j>0?b.selection.setAtEnd(g[h.min_i][h.min_j-1]):b.selection.setAtEnd(g[h.min_i][0]),b.selection.restore(),b.popups.hide("table.edit"),c.find("th, td").each(function(){f=a(this),f.data("old-width")&&(f.css("width",(f.data("old-width")*j/i).toFixed(4)+"%"),f.removeData("old-width"))})}}}function u(){if(b.$el.find(".fr-selected-cell").length>1&&(0===b.$el.find("th.fr-selected-cell").length||0===b.$el.find("td.fr-selected-cell").length)){var c,e,f,g=B(),h=G(g),i=b.$el.find(".fr-selected-cell"),j=a(i[0]),k=j.parent(),l=k.find(".fr-selected-cell"),m=j.closest("table"),n=j.html(),o=0;for(c=0;c<l.length;c++)o+=a(l[c]).outerWidth();for(j.css("width",(o/k.outerWidth()*100).toFixed(4)+"%"),h.min_j<h.max_j&&j.attr("colspan",h.max_j-h.min_j+1),h.min_i<h.max_i&&j.attr("rowspan",h.max_i-h.min_i+1),c=1;c<i.length;c++)e=a(i[c]),"<br>"!=e.html()&&""!==e.html()&&(n+="<br>"+e.html()),e.remove();j.html(n),b.selection.setAtEnd(j.get(0)),b.selection.restore(),b.toolbar.enable();var p=m.find("tr:empty");for(c=p.length-1;c>=0;c--)f=a(p[c]),(0===f.prev().length||0===f.next().length||f.prev().find("> th[rowspan], > td[rowspan]").length<f.prev().find("> th, > td").length)&&f.remove();d()}}function v(){if(1==b.$el.find(".fr-selected-cell").length){var c=b.$el.find(".fr-selected-cell"),d=c.parent(),e=c.closest("table"),f=parseInt(c.attr("rowspan"),10),g=B(),h=C(c.get(0),g),i=c.clone().html("<br>");if(f>1){var j=Math.ceil(f/2);j>1?c.attr("rowspan",j):c.removeAttr("rowspan"),f-j>1?i.attr("rowspan",f-j):i.removeAttr("rowspan");for(var k=h.row+j,l=0===h.col?h.col:h.col-1;l>=0&&(g[k][l]==g[k][l-1]||k>0&&g[k][l]==g[k-1][l]);)l--;-1==l?a(e.find("tr").not(e.find("table tr")).get(k)).prepend(i):a(g[k][l]).after(i)}else{var m,n=a("<tr>").append(i);for(m=0;m<g[0].length;m++)if(0===m||g[h.row][m]!=g[h.row][m-1]){var o=a(g[h.row][m]);o.is(c)||o.attr("rowspan",(parseInt(o.attr("rowspan"),10)||1)+1)}d.after(n)}E(),b.popups.hide("table.edit")}}function w(){if(1==b.$el.find(".fr-selected-cell").length){var c=b.$el.find(".fr-selected-cell"),d=parseInt(c.attr("colspan"),10)||1,e=c.parent().outerWidth(),f=c.outerWidth(),g=c.clone().html("<br>"),h=B(),i=C(c.get(0),h);if(d>1){var j=Math.ceil(d/2);f=Z(i.col,i.col+j-1,h)/e*100;var k=Z(i.col+j,i.col+d-1,h)/e*100;j>1?c.attr("colspan",j):c.removeAttr("colspan"),d-j>1?g.attr("colspan",d-j):g.removeAttr("colspan"),c.css("width",f.toFixed(4)+"%"),g.css("width",k.toFixed(4)+"%")}else{var l;for(l=0;l<h.length;l++)if(0===l||h[l][i.col]!=h[l-1][i.col]){var m=a(h[l][i.col]);if(!m.is(c)){var n=(parseInt(m.attr("colspan"),10)||1)+1;m.attr("colspan",n)}}f=f/e*100/2,c.css("width",f.toFixed(4)+"%"),g.css("width",f.toFixed(4)+"%")}c.after(g),E(),b.popups.hide("table.edit")}}function x(a){"REMOVE"!=a?b.$el.find(".fr-selected-cell").css("background-color",b.helpers.HEXtoRGB(a)):b.$el.find(".fr-selected-cell").css("background-color","")}function y(a){b.$el.find(".fr-selected-cell").css("vertical-align",a)}function z(a){b.$el.find(".fr-selected-cell").css("text-align",a)}function A(a,b,c,d){if(b.length>0){if(!c){var e=Object.keys(d);e.splice(e.indexOf(a),1),b.removeClass(e.join(" "))}b.toggleClass(a)}}function B(c){c=c||null;var d=[];if(null==c&&b.$el.find(".fr-selected-cell").length>0&&(c=b.$el.find(".fr-selected-cell").closest("table")),c){var e=a(c);return e.find("tr").not(e.find("table tr")).each(function(b,c){var e=a(c),f=0;e.find("> th, > td").each(function(c,e){for(var g=a(e),h=parseInt(g.attr("colspan"),10)||1,i=parseInt(g.attr("rowspan"),10)||1,j=b;b+i>j;j++)for(var k=f;f+h>k;k++)d[j]||(d[j]=[]),d[j][k]?f++:d[j][k]=e;f+=h})}),d}}function C(a,b){for(var c=0;c<b.length;c++)for(var d=0;d<b[c].length;d++)if(b[c][d]==a)return{row:c,col:d}}function D(a,b,c){for(var d=a+1,e=b+1;d<c.length;){if(c[d][b]!=c[a][b]){d--;break}d++}for(d==c.length&&d--;e<c[a].length;){if(c[a][e]!=c[a][b]){e--;break}e++}return e==c[a].length&&e--,{row:d,col:e}}function E(){var c=b.$el.find(".fr-selected-cell");c.length>0&&c.each(function(){var b=a(this);b.removeClass("fr-selected-cell"),""===b.attr("class")&&b.removeAttr("class")})}function F(){setTimeout(function(){b.selection.clear(),b.$el.addClass("fr-no-selection"),b.edit.off(),b.$el.blur()},0)}function G(a){var c,d=a.length,e=0,f=a[0].length,g=0,h=b.$el.find(".fr-selected-cell");for(c=0;c<h.length;c++){var i=C(h[c],a),j=D(i.row,i.col,a);d=Math.min(i.row,d),e=Math.max(j.row,e),f=Math.min(i.col,f),g=Math.max(j.col,g)}return{min_i:d,max_i:e,min_j:f,max_j:g}}function H(b,c,d,e,f){var g,h,i,j,k=b,l=c,m=d,n=e;for(g=k;l>=g;g++)((parseInt(a(f[g][m]).attr("rowspan"),10)||1)>1||(parseInt(a(f[g][m]).attr("colspan"),10)||1)>1)&&(i=C(f[g][m],f),j=D(i.row,i.col,f),k=Math.min(i.row,k),l=Math.max(j.row,l),m=Math.min(i.col,m),n=Math.max(j.col,n)),((parseInt(a(f[g][n]).attr("rowspan"),10)||1)>1||(parseInt(a(f[g][n]).attr("colspan"),10)||1)>1)&&(i=C(f[g][n],f),j=D(i.row,i.col,f),k=Math.min(i.row,k),l=Math.max(j.row,l),m=Math.min(i.col,m),n=Math.max(j.col,n));for(h=m;n>=h;h++)((parseInt(a(f[k][h]).attr("rowspan"),10)||1)>1||(parseInt(a(f[k][h]).attr("colspan"),10)||1)>1)&&(i=C(f[k][h],f),j=D(i.row,i.col,f),k=Math.min(i.row,k),l=Math.max(j.row,l),m=Math.min(i.col,m),n=Math.max(j.col,n)),((parseInt(a(f[l][h]).attr("rowspan"),10)||1)>1||(parseInt(a(f[l][h]).attr("colspan"),10)||1)>1)&&(i=C(f[l][h],f),j=D(i.row,i.col,f),k=Math.min(i.row,k),l=Math.max(j.row,l),m=Math.min(i.col,m),n=Math.max(j.col,n));return k==b&&l==c&&m==d&&n==e?{min_i:b,max_i:c,min_j:d,max_j:e}:H(k,l,m,n,f)}function I(b){var c=G(b),d=a(b[c.min_i][c.min_j]),e=a(b[c.min_i][c.max_j]),f=a(b[c.max_i][c.min_j]),g=d.offset().left,h=e.offset().left+e.outerWidth(),i=d.offset().top,j=f.offset().top+f.outerHeight();return{left:g,right:h,top:i,bottom:j}}function J(b,c){if(a(b).is(c))E(),a(b).addClass("fr-selected-cell");else{F();var d=B(),e=C(b,d),f=C(c,d),g=H(Math.min(e.row,f.row),Math.max(e.row,f.row),Math.min(e.col,f.col),Math.max(e.col,f.col),d);E();for(var h=g.min_i;h<=g.max_i;h++)for(var i=g.min_j;i<=g.max_j;i++)a(d[h][i]).addClass("fr-selected-cell")}}function K(c){var d=null,e=a(c.target);return"TD"==c.target.tagName||"TH"==c.target.tagName?d=c.target:e.closest("td").length>0?d=e.closest("td").get(0):e.closest("th").length>0&&(d=e.closest("th").get(0)),0===b.$el.find(d).length?null:d}function L(c){if(b.$el.find(".fr-selected-cell").length>0&&!c.shiftKey&&(E(),b.$el.removeClass("fr-no-selection"),b.edit.on()),1==c.which){ha=!0;var d=K(c);if(d){b.popups.hide("table.edit"),c.stopPropagation(),b.events.trigger("image.hideResizer"),b.events.trigger("video.hideResizer"),ga=!0;var e=d.tagName.toLowerCase();c.shiftKey&&a(e+".fr-selected-cell").length>0?a(a(e+".fr-selected-cell").closest("table")).is(a(d).closest("table"))?J(ia,d):F():((b.keys.ctrlKey(c)||c.shiftKey)&&F(),ia=d,J(ia,ia))}}}function M(c){if(1==c.which){if(ha=!1,ga){ga=!1;var e=K(c);e||1!=b.$el.find(".fr-selected-cell").length?b.$el.find(".fr-selected-cell").length>0&&(b.selection.isCollapsed()?d():E()):E()}else b.$tb.is(c.target)||b.$tb.is(a(c.target).closest(b.$tb.get(0)))||(b.$el.get(0).querySelectorAll(".fr-selected-cell").length>0&&b.toolbar.enable(),E());if(ka){ka=!1,ea.removeClass("fr-moving"),b.$el.removeClass("fr-no-selection"),b.edit.on();var f=parseFloat(ea.css("left"))+b.opts.tableResizerOffset;b.opts.iframe&&(f-=b.$iframe.offset().left),ea.data("release-position",f),ea.removeData("max-left"),ea.removeData("max-right"),X(c),Q()}}}function N(c){if(ga===!0){var d=a(c.currentTarget);if(d.closest("table").is(b.$el.find(".fr-selected-cell").closest("table"))){if("TD"==c.currentTarget.tagName&&0===b.$el.find("th.fr-selected-cell").length)return void J(ia,c.currentTarget);if("TH"==c.currentTarget.tagName&&0===b.$el.find("td.fr-selected-cell").length)return void J(ia,c.currentTarget)}F()}}function O(a){(37==a.which||38==a.which||39==a.which||40==a.which)&&b.$el.find(".fr-selected-cell").length>0&&(E(),b.popups.hide("table.edit"))}function P(){ea=a('<div class="fr-table-resizer"><div></div></div>'),b.$wp.append(ea),ea.on("mousedown",function(){ka=!0,ea.addClass("fr-moving"),E(),F(),ea.find("div").css("opacity",1)}),b.events.on("destroy",function(){ea.off("mousedown"),ea.html("").removeData().remove()},!0)}function Q(){ea.find("div").css("opacity",0),ea.css("top",0),ea.css("left",0),ea.css("height",0),ea.find("div").css("height",0),ea.hide()}function R(c,d){var e=a(d),f=e.closest("table");if(d&&"TD"!=d.tagName&&"TH"!=d.tagName&&(e.closest("td").length>0?d=e.closest("td"):e.closest("th").length>0&&(d=e.closest("th"))),!d||"TD"!=d.tagName&&"TH"!=d.tagName)e.get(0)!=ea.get(0)&&e.parent().get(0)!=ea.get(0)&&Q();else{if(e=a(d),0===b.$el.find(e).length)return!1;var g=e.offset().left-1,h=g+e.outerWidth();if(Math.abs(c.pageX-g)<=b.opts.tableResizerOffset||Math.abs(h-c.pageX)<=b.opts.tableResizerOffset){var i,j,k,l,m,n=B(f),o=C(d,n),p=D(o.row,o.col,n),q=f.offset().top,r=f.outerHeight()-1;if(o.col>0&&c.pageX-g<=b.opts.tableResizerOffset){k=g;var s=a(n[o.row][o.col-1]);l=1==(parseInt(s.attr("colspan"),10)||1)?s.offset().left-1+b.opts.tableResizingLimit:g-Y(o.col-1,n)+b.opts.tableResizingLimit,m=1==(parseInt(e.attr("colspan"),10)||1)?g+e.outerWidth()-b.opts.tableResizingLimit:g+Y(o.col,n)-b.opts.tableResizingLimit,i=o.col-1,j=o.col}else if(h-c.pageX<=b.opts.tableResizerOffset)if(k=h,p.col<n[p.row].length&&n[p.row][p.col+1]){var t=a(n[p.row][p.col+1]);l=1==(parseInt(e.attr("colspan"),10)||1)?g+b.opts.tableResizingLimit:h-Y(p.col,n)+b.opts.tableResizingLimit,m=1==(parseInt(t.attr("colspan"),10)||1)?h+t.outerWidth()-b.opts.tableResizingLimit:h+Y(o.col+1,n)-b.opts.tableResizingLimit,i=p.col,j=p.col+1}else{i=p.col,j=null;var u=f.parent();l=f.offset().left-1+n[0].length*b.opts.tableResizingLimit,m=u.offset().left-1+u.width()+parseFloat(u.css("padding-left"))}ea.data("table",f),ea.data("first",i),ea.data("second",j);var v=k-b.window.pageXOffset-b.opts.tableResizerOffset,w=q-b.window.pageYOffset;b.opts.iframe&&(v+=b.$iframe.offset().left-a(b.original_window).scrollLeft(),w+=b.$iframe.offset().top-a(b.original_window).scrollTop(),l+=b.$iframe.offset().left,m+=b.$iframe.offset().left),ea.data("max-left",l),ea.data("max-right",m),ea.data("origin",k-b.window.pageXOffset),ea.css("top",w),ea.css("left",v),ea.css("height",r),ea.find("div").css("height",r),ea.css("padding-left",b.opts.tableResizerOffset),ea.css("padding-right",b.opts.tableResizerOffset),ea.show()}else Q()}}function S(c,d){if(b.$box.find(".fr-line-breaker").is(":visible"))return!1;var e=a(d),f=e.find("tr:first"),g=c.pageX,h=0,i=0;b.opts.iframe&&(h+=b.$iframe.offset().left-a(b.original_window).scrollLeft(),i+=b.$iframe.offset().top-a(b.original_window).scrollTop());var j;f.find("th, td").each(function(){var c=a(this);return c.offset().left<=g&&g<c.offset().left+c.outerWidth()/2?(fa.find("a").attr("title",b.language.translate("Insert Column")),j=parseInt(fa.find("a").css("width"),10),fa.css("top",i+c.offset().top-b.window.pageYOffset-j-5),fa.css("left",h+c.offset().left-b.window.pageXOffset-j/2),fa.data("selected-cell",c),fa.data("position","before"),fa.addClass("fr-visible"),!1):c.offset().left+c.outerWidth()/2<=g&&g<c.offset().left+c.outerWidth()?(fa.find("a").attr("title",b.language.translate("Insert Column")),j=parseInt(fa.find("a").css("width"),10),fa.css("top",i+c.offset().top-b.window.pageYOffset-j-5),fa.css("left",h+c.offset().left+c.outerWidth()-b.window.pageXOffset-j/2),fa.data("selected-cell",c),fa.data("position","after"),fa.addClass("fr-visible"),!1):void 0})}function T(c,d){if(b.$box.find(".fr-line-breaker").is(":visible"))return!1;var e=a(d),f=c.pageY,g=0,h=0;b.opts.iframe&&(g+=b.$iframe.offset().left-a(b.original_window).scrollLeft(),h+=b.$iframe.offset().top-a(b.original_window).scrollTop());var i;e.find("tr").each(function(){var c=a(this);return c.offset().top<=f&&f<c.offset().top+c.outerHeight()/2?(fa.find("a").attr("title",b.language.translate("Insert Row")),i=parseInt(fa.find("a").css("width"),10),fa.css("top",h+c.offset().top-b.window.pageYOffset-i/2),fa.css("left",g+c.offset().left-b.window.pageXOffset-i-5),fa.data("selected-cell",c.find("td:first")),fa.data("position","above"),fa.addClass("fr-visible"),!1):c.offset().top+c.outerHeight()/2<=f&&f<c.offset().top+c.outerHeight()?(fa.find("a").attr("title",b.language.translate("Insert Row")),i=parseInt(fa.find("a").css("width"),10),fa.css("top",h+c.offset().top+c.outerHeight()-b.window.pageYOffset-i/2),fa.css("left",g+c.offset().left-b.window.pageXOffset-i-5),fa.data("selected-cell",c.find("td:first")),fa.data("position","below"),fa.addClass("fr-visible"),!1):void 0})}function U(c,d){if(0===b.$el.find(".fr-selected-cell").length){var e,f,g;if(fa.removeClass("fr-visible"),d&&("HTML"==d.tagName||"BODY"==d.tagName||b.node.isElement(d)))for(e=1;e<=b.opts.tableInsertHelperOffset;e++){if(f=b.document.elementFromPoint(c.pageX-b.window.pageXOffset,c.pageY-b.window.pageYOffset+e),f&&("TH"==f.tagName||"TD"==f.tagName||"TABLE"==f.tagName)&&a(f).parents(b.$wp).length){S(c,f.closest("table"));break}if(g=b.document.elementFromPoint(c.pageX-b.window.pageXOffset+e,c.pageY-b.window.pageYOffset),g&&("TH"==g.tagName||"TD"==g.tagName||"TABLE"==g.tagName)&&a(g).parents(b.$wp).length){T(c,g.closest("table"));break}}}}function V(a){ja=null;var c=b.document.elementFromPoint(a.pageX-b.window.pageXOffset,a.pageY-b.window.pageYOffset);(!b.popups.areVisible()||b.popups.areVisible()&&b.popups.isVisible("table.edit"))&&R(a,c),b.popups.areVisible()||b.$tb.hasClass("fr-inline")&&b.$tb.is(":visible")||U(a,c)}function W(){if(ka){var a=ea.data("table");ea.css("top",a.offset().top-b.window.pageYOffset)}}function X(){var c=ea.data("origin"),d=ea.data("release-position");if(c!==d){var e=ea.data("first"),f=ea.data("second"),g=ea.data("table"),h=g.outerWidth();if(null!==e&&null!==f){var i,j,k,l=B(g),m=[],n=[],o=[],p=[];for(i=0;i<l.length;i++)j=a(l[i][e]),k=a(l[i][f]),m[i]=j.outerWidth(),o[i]=k.outerWidth(),n[i]=m[i]/h*100,p[i]=o[i]/h*100;for(i=0;i<l.length;i++){j=a(l[i][e]),k=a(l[i][f]);var q=(n[i]*(m[i]+d-c)/m[i]).toFixed(4);j.css("width",q+"%"),k.css("width",(n[i]+p[i]-q).toFixed(4)+"%")}}else{var r,s=g.parent(),t=h/s.width()*100;r=null==e?(h-d+c)/h*t:(h+d-c)/h*t,g.css("width",Math.round(r).toFixed(4)+"%")}}ea.removeData("origin"),ea.removeData("release-position"),ea.removeData("first"),ea.removeData("second"),ea.removeData("table"),b.undo.saveStep()}function Y(b,c){var d,e=a(c[0][b]).outerWidth();for(d=1;d<c.length;d++)e=Math.min(e,a(c[d][b]).outerWidth());return e}function Z(a,b,c){var d,e=0;for(d=a;b>=d;d++)e+=Y(d,c);return e}function $(a){if(ha===!1&&ga===!1&&ka===!1)ja&&clearTimeout(ja),ja=setTimeout(V,30,a);else if(ka){var c=a.pageX-b.window.pageXOffset;b.opts.iframe&&(c+=b.$iframe.offset().left);var d=ea.data("max-left"),e=ea.data("max-right");c>=d&&e>=c?ea.css("left",c-b.opts.tableResizerOffset):d>c&&parseFloat(ea.css("left"),10)>d-b.opts.tableResizerOffset?ea.css("left",d-b.opts.tableResizerOffset):c>e&&parseFloat(ea.css("left"),10)<e-b.opts.tableResizerOffset&&ea.css("left",e-b.opts.tableResizerOffset)}else ha&&fa.removeClass("fr-visible")}function _(c){b.node.isEmpty(c.get(0))?c.prepend(a.FroalaEditor.MARKERS):c.prepend(a.FroalaEditor.START_MARKER).append(a.FroalaEditor.END_MARKER)}function aa(c){var d=c.which;if(d==a.FroalaEditor.KEYCODE.TAB&&0===b.opts.tabSpaces){var e;if(b.$el.find(".fr-selected-cell").length>0)e=b.$el.find(".fr-selected-cell:last");else{var f=b.selection.element();"TD"==f.tagName||"TH"==f.tagName?e=a(f):a(f).closest("td").length>0?e=a(f).closest("td"):a(f).closest("th").length>0&&(e=a(f).closest("th"))}e&&(c.preventDefault(),E(),b.popups.hide("table.edit"),c.shiftKey?e.prev().length>0?_(e.prev()):e.closest("tr").length>0&&e.closest("tr").prev().length>0?_(e.closest("tr").prev().find("td:last")):e.closest("tbody").length>0&&e.closest("table").find("thead tr").length>0&&_(e.closest("table").find("thead tr th:last")):e.next().length>0?_(e.next()):e.closest("tr").length>0&&e.closest("tr").next().length>0?_(e.closest("tr").next().find("td:first")):e.closest("thead").length>0&&e.closest("table").find("tbody tr").length>0?_(e.closest("table").find("tbody tr td:first")):(e.addClass("fr-selected-cell"),q("below"),E(),_(e.closest("tr").next().find("td:first"))),b.selection.restore())}}function ba(){fa=a('<div class="fr-insert-helper"><a class="fr-floating-btn" role="button" tabindex="-1" title="'+b.language.translate("Insert")+'"><svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg"><path d="M22,16.75 L16.75,16.75 L16.75,22 L15.25,22.000 L15.25,16.75 L10,16.75 L10,15.25 L15.25,15.25 L15.25,10 L16.75,10 L16.75,15.25 L22,15.25 L22,16.75 Z"/></svg></a></div>'),b.$box.append(fa),b.events.on("destroy",function(){fa.html("").removeData().remove()},!0),fa.on("mousemove",function(a){a.stopPropagation()}),a(b.window).on("scroll.table"+b.id,function(){fa.removeClass("fr-visible")}),b.events.bindClick(fa,"a",function(){var a=fa.data("selected-cell"),b=fa.data("position");"before"==b?(a.addClass("fr-selected-cell"),s(b),a.removeClass("fr-selected-cell")):"after"==b?(a.addClass("fr-selected-cell"),s(b),a.removeClass("fr-selected-cell")):"above"==b?(a.addClass("fr-selected-cell"),q(b),a.removeClass("fr-selected-cell")):"below"==b&&(a.addClass("fr-selected-cell"),q(b),a.removeClass("fr-selected-cell")),fa.removeClass("fr-visible")}),b.events.on("destroy",function(){fa.off("mousemove"),a(b.window).off("scroll.table"+b.id)},!0)}function ca(){return b.$wp?(b.helpers.isMobile()||(ha=!1,ga=!1,ka=!1,P(),b.opts.tableInsertHelper&&ba(),b.$el.on("mousedown.table"+b.id,L),b.popups.onShow("image.edit",function(){E(),ha=!1,ga=!1}),b.popups.onShow("link.edit",function(){E(),ha=!1,ga=!1}),b.events.on("commands.mousedown",function(a){a.parents(".fr-toolbar").length>0&&E()}),b.$el.on("mouseenter.table"+b.id,"th, td",N),b.$window.on("mouseup.table"+b.id,M),b.$el.on("keydown.table"+b.id,O),b.$window.on("mousemove.table"+b.id,$),a(b.window).on("scroll.table"+b.id,W),b.events.on("contentChanged",function(){b.$el.find(".fr-selected-cell").length>0&&(d(),b.$el.find("img").on("load.selected-cells",function(){a(this).off("load.selected-cells"),b.$el.find(".fr-selected-cell").length>0&&d()}))}),a(b.original_window).on("resize.table"+b.id,function(){E()}),b.events.on("keydown",function(c){if(b.$el.find(".fr-selected-cell").length>0){if(c.which==a.FroalaEditor.KEYCODE.ESC&&b.popups.isVisible("table.edit"))return E(),b.popups.hide("table.edit"),c.preventDefault(),c.stopPropagation(),c.stopImmediatePropagation(),!1;if(b.$el.find(".fr-selected-cell").length>1)return c.preventDefault(),!1}},!0),a(b.window).on("keydown.table"+b.id,d),a(b.window).on("input.table"+b.id,d),a(b.window).on("keyup.table"+b.id,d),b.events.on("html.get",function(a){return a=a.replace(/<(td|th)((?:[\w\W]*?))class="([\w\W]*?)fr-selected-cell([\w\W]*?)"((?:[\w\W]*?))>((?:[\w\W]*?))<\/(td|th)>/g,'<$1$2class="$3$4"$5>$6</$7>'),a=a.replace(/<(td|th)((?:[\w\W]*?)) class=""((?:[\w\W]*?))>((?:[\w\W]*?))<\/(td|th)>/g,"<$1$2$3>$4</$5>")}),b.events.on("destroy",function(){b.$el.off("mousedown.table"+b.id),b.$el.off("mouseenter.table"+b.id,"th, td"),b.$window.off("mouseup.table"+b.id),b.$el.off("keydown.table"+b.id),b.$window.off("mousemove.table"+b.id),a(b.window).off("scroll.table"+b.id),a(b.window).off("keydown.table"+b.id),a(b.window).off("input.table"+b.id),a(b.window).off("keyup.table"+b.id)},!0)),void b.events.on("keydown",aa,!0)):!1}function da(){b.$el.find(".fr-selected-cell").length>0?d():(b.popups.hide("table.insert"),b.toolbar.showInline())}var ea,fa,ga,ha,ia,ja,ka;return{_init:ca,insert:m,remove:n,insertRow:q,deleteRow:r,insertColumn:s,deleteColumn:t,mergeCells:u,splitCellVertically:w,splitCellHorizontally:v,addHeader:o,removeHeader:p,setBackground:x,showInsertPopup:c,showEditPopup:d,showColorsPopup:e,back:da,verticalAlign:y,horizontalAlign:z,applyStyle:A}},a.FroalaEditor.DefineIcon("insertTable",{NAME:"table"}),a.FroalaEditor.RegisterCommand("insertTable",{title:"Insert Table",undo:!1,focus:!0,refreshOnCallback:!1,popup:!0,callback:function(){this.popups.isVisible("table.insert")?(this.$el.find(".fr-marker")&&(this.events.disableBlur(),this.selection.restore()),this.popups.hide("table.insert")):this.table.showInsertPopup()},plugin:"table"}),a.FroalaEditor.RegisterCommand("tableInsert",{callback:function(a,b,c){this.table.insert(b,c),this.popups.hide("table.insert")}}),a.FroalaEditor.DefineIcon("tableHeader",{NAME:"header"}),a.FroalaEditor.RegisterCommand("tableHeader",{title:"Table Header",focus:!1,callback:function(){var a=this.popups.get("table.edit").find('.fr-command[data-cmd="tableHeader"]');a.hasClass("fr-active")?this.table.removeHeader():this.table.addHeader()},refresh:function(a){var b=this.$el.find(".fr-selected-cell").closest("table");b.length>0&&(0===b.find("th").length?a.removeClass("fr-active"):a.addClass("fr-active"))}}),a.FroalaEditor.DefineIcon("tableRows",{NAME:"bars"}),a.FroalaEditor.RegisterCommand("tableRows",{type:"dropdown",focus:!1,title:"Row",options:{above:"Insert row above",below:"Insert row below","delete":"Delete row"},html:function(){var b='<ul class="fr-dropdown-list">',c=a.FroalaEditor.COMMANDS.tableRows.options;for(var d in c)b+='<li><a class="fr-command" data-cmd="tableRows" data-param1="'+d+'" title="'+this.language.translate(c[d])+'">'+this.language.translate(c[d])+"</a></li>";return b+="</ul>"},callback:function(a,b){"above"==b||"below"==b?this.table.insertRow(b):this.table.deleteRow()}}),a.FroalaEditor.DefineIcon("tableColumns",{NAME:"bars fa-rotate-90"}),a.FroalaEditor.RegisterCommand("tableColumns",{ type:"dropdown",focus:!1,title:"Column",options:{before:"Insert column before",after:"Insert column after","delete":"Delete column"},html:function(){var b='<ul class="fr-dropdown-list">',c=a.FroalaEditor.COMMANDS.tableColumns.options;for(var d in c)b+='<li><a class="fr-command" data-cmd="tableColumns" data-param1="'+d+'" title="'+this.language.translate(c[d])+'">'+this.language.translate(c[d])+"</a></li>";return b+="</ul>"},callback:function(a,b){"before"==b||"after"==b?this.table.insertColumn(b):this.table.deleteColumn()}}),a.FroalaEditor.DefineIcon("tableCells",{NAME:"square-o"}),a.FroalaEditor.RegisterCommand("tableCells",{type:"dropdown",focus:!1,title:"Cell",options:{merge:"Merge cells","vertical-split":"Vertical split","horizontal-split":"Horizontal split"},html:function(){var b='<ul class="fr-dropdown-list">',c=a.FroalaEditor.COMMANDS.tableCells.options;for(var d in c)b+='<li><a class="fr-command" data-cmd="tableCells" data-param1="'+d+'" title="'+this.language.translate(c[d])+'">'+this.language.translate(c[d])+"</a></li>";return b+="</ul>"},callback:function(a,b){"merge"==b?this.table.mergeCells():"vertical-split"==b?this.table.splitCellVertically():this.table.splitCellHorizontally()},refreshOnShow:function(a,b){this.$el.find(".fr-selected-cell").length>1?(b.find('a[data-param1="vertical-split"]').addClass("fr-disabled"),b.find('a[data-param1="horizontal-split"]').addClass("fr-disabled"),b.find('a[data-param1="merge"]').removeClass("fr-disabled")):(b.find('a[data-param1="merge"]').addClass("fr-disabled"),b.find('a[data-param1="vertical-split"]').removeClass("fr-disabled"),b.find('a[data-param1="horizontal-split"]').removeClass("fr-disabled"))}}),a.FroalaEditor.DefineIcon("tableRemove",{NAME:"trash"}),a.FroalaEditor.RegisterCommand("tableRemove",{title:"Remove Table",focus:!1,callback:function(){this.table.remove()}}),a.FroalaEditor.DefineIcon("tableStyle",{NAME:"paint-brush"}),a.FroalaEditor.RegisterCommand("tableStyle",{title:"Table Style",type:"dropdown",focus:!1,html:function(){var a='<ul class="fr-dropdown-list">',b=this.opts.tableStyles;for(var c in b)a+='<li><a class="fr-command" data-cmd="tableStyle" data-param1="'+c+'" title="'+this.language.translate(b[c])+'">'+this.language.translate(b[c])+"</a></li>";return a+="</ul>"},callback:function(a,b){this.table.applyStyle(b,this.$el.find(".fr-selected-cell").closest("table"),this.opts.tableMultipleStyles,this.opts.tableStyles)},refreshOnShow:function(b,c){var d=this.$el.find(".fr-selected-cell").closest("table");d&&c.find(".fr-command").each(function(){var b=a(this).data("param1");a(this).toggleClass("fr-active",d.hasClass(b))})}}),a.FroalaEditor.DefineIcon("tableCellBackground",{NAME:"tint"}),a.FroalaEditor.RegisterCommand("tableCellBackground",{title:"Cell Background",focus:!1,callback:function(){this.table.showColorsPopup()}}),a.FroalaEditor.RegisterCommand("tableCellBackgroundColor",{undo:!0,focus:!1,callback:function(a,b){this.table.setBackground(b)}}),a.FroalaEditor.DefineIcon("tableBack",{NAME:"arrow-left"}),a.FroalaEditor.RegisterCommand("tableBack",{title:"Back",undo:!1,focus:!1,back:!0,callback:function(){this.table.back()},refresh:function(a){0!==this.$el.find(".fr-selected-cell").length||this.opts.toolbarInline?(a.removeClass("fr-hidden"),a.next(".fr-separator").removeClass("fr-hidden")):(a.addClass("fr-hidden"),a.next(".fr-separator").addClass("fr-hidden"))}}),a.FroalaEditor.DefineIcon("tableCellVerticalAlign",{NAME:"arrows-v"}),a.FroalaEditor.RegisterCommand("tableCellVerticalAlign",{type:"dropdown",focus:!1,title:"Vertical Align",options:{Top:"Align Top",Middle:"Align Middle",Bottom:"Align Bottom"},html:function(){var b='<ul class="fr-dropdown-list">',c=a.FroalaEditor.COMMANDS.tableCellVerticalAlign.options;for(var d in c)b+='<li><a class="fr-command" data-cmd="tableCellVerticalAlign" data-param1="'+d.toLowerCase()+'" title="'+this.language.translate(c[d])+'">'+this.language.translate(d)+"</a></li>";return b+="</ul>"},callback:function(a,b){this.table.verticalAlign(b)},refreshOnShow:function(a,b){b.find('.fr-command[data-param1="'+this.$el.find(".fr-selected-cell").css("vertical-align")+'"]').addClass("fr-active")}}),a.FroalaEditor.DefineIcon("tableCellHorizontalAlign",{NAME:"align-left"}),a.FroalaEditor.DefineIcon("align-left",{NAME:"align-left"}),a.FroalaEditor.DefineIcon("align-right",{NAME:"align-right"}),a.FroalaEditor.DefineIcon("align-center",{NAME:"align-center"}),a.FroalaEditor.DefineIcon("align-justify",{NAME:"align-justify"}),a.FroalaEditor.RegisterCommand("tableCellHorizontalAlign",{type:"dropdown",focus:!1,title:"Horizontal Align",options:{left:"Align Left",center:"Align Center",right:"Align Right",justify:"Align Justify"},html:function(){var b='<ul class="fr-dropdown-list">',c=a.FroalaEditor.COMMANDS.tableCellHorizontalAlign.options;for(var d in c)b+='<li><a class="fr-command fr-title" data-cmd="tableCellHorizontalAlign" data-param1="'+d+'" title="'+this.language.translate(c[d])+'">'+this.icon.create("align-"+d)+"</a></li>";return b+="</ul>"},callback:function(a,b){this.table.horizontalAlign(b)},refresh:function(a){a.find("> *:first").replaceWith(this.icon.create("align-"+this.helpers.getAlignment(this.$el.find(".fr-selected-cell:first"))))},refreshOnShow:function(a,b){b.find('.fr-command[data-param1="'+this.helpers.getAlignment(this.$el.find(".fr-selected-cell:first"))+'"]').addClass("fr-active")}}),a.FroalaEditor.DefineIcon("tableCellStyle",{NAME:"magic"}),a.FroalaEditor.RegisterCommand("tableCellStyle",{title:"Cell Style",type:"dropdown",focus:!1,html:function(){var a='<ul class="fr-dropdown-list">',b=this.opts.tableCellStyles;for(var c in b)a+='<li><a class="fr-command" data-cmd="tableCellStyle" data-param1="'+c+'" title="'+this.language.translate(b[c])+'">'+this.language.translate(b[c])+"</a></li>";return a+="</ul>"},callback:function(a,b){this.table.applyStyle(b,this.$el.find(".fr-selected-cell"),this.opts.tableCellMultipleStyles,this.opts.tableCellStyles)},refreshOnShow:function(b,c){var d=this.$el.find(".fr-selected-cell:first");d&&c.find(".fr-command").each(function(){var b=a(this).data("param1");a(this).toggleClass("fr-active",d.hasClass(b))})}})});
/** * API function to create fetch store tests. * * Site Kit by Google, Copyright 2020 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. */ /** * External dependencies */ import invariant from 'invariant'; import isPlainObject from 'lodash/isPlainObject'; /** * WordPress dependencies */ import { createRegistry } from '@wordpress/data'; /** * Internal dependencies */ import API from 'googlesitekit-api'; import { muteConsole, subscribeUntil, unsubscribeFromAll, } from '../../../../tests/js/utils'; import { createFetchStore } from './create-fetch-store'; const STORE_NAME = 'test/some-data'; const STORE_PARAMS = { baseName: 'getSomeData', controlCallback: ( params ) => { const { aParam, objParam } = params; return API.get( 'core', 'test', 'some-data', { aParam, objParam, } ); }, reducerCallback: ( state, response, params ) => { const { aParam } = params; return { ...state, data: { ...( state.data || {} ), [ aParam ]: response, }, }; }, argsToParams: ( objParam, aParam ) => { invariant( isPlainObject( objParam ), 'objParam is required.' ); invariant( aParam !== undefined, 'aParam is required.' ); return { objParam, aParam, }; }, }; describe( 'createFetchStore store', () => { let dispatch; let registry; let select; let storeDefinition; let store; beforeAll( () => { API.setUsingCache( false ); } ); beforeEach( () => { registry = createRegistry(); storeDefinition = createFetchStore( STORE_PARAMS ); registry.registerStore( STORE_NAME, storeDefinition ); dispatch = registry.dispatch( STORE_NAME ); store = registry.stores[ STORE_NAME ].store; select = registry.select( STORE_NAME ); } ); afterAll( () => { API.setUsingCache( true ); } ); afterEach( () => { unsubscribeFromAll( registry ); } ); describe( 'actions', () => { it( 'includes the expected actions', () => { const fetchStoreDefinition = createFetchStore( { baseName: 'SaveSomeData', controlCallback: async () => true, } ); expect( Object.keys( fetchStoreDefinition.actions ) ).toEqual( [ 'fetchSaveSomeData', 'receiveSaveSomeData', ] ); } ); describe( 'fetch', () => { it( 'validates parameters based on argsToParams', () => { const consoleErrorSpy = jest.spyOn( global.console, 'error' ); muteConsole( 'error' ); dispatch.fetchGetSomeData(); expect( consoleErrorSpy ).toHaveBeenCalledWith( 'objParam is required.' ); muteConsole( 'error' ); dispatch.fetchGetSomeData( 123 ); expect( consoleErrorSpy ).toHaveBeenCalledWith( 'objParam is required.' ); muteConsole( 'error' ); dispatch.fetchGetSomeData( {} ); expect( consoleErrorSpy ).toHaveBeenCalledWith( 'aParam is required.' ); consoleErrorSpy.mockClear(); } ); it( 'yields the expected actions for an arguments error', () => { const fetchStoreDefinition = createFetchStore( { baseName: 'SaveSomeData', controlCallback: async () => true, argsToParams: ( requiredParam ) => { invariant( requiredParam, 'requiredParam is required.' ); return { requiredParam, }; }, } ); const action = fetchStoreDefinition.actions.fetchSaveSomeData(); // Catch invariant to get exactly the error we expect. let error; try { muteConsole( 'error' ); invariant( false, 'requiredParam is required.' ); } catch ( err ) { error = err; } expect( action.next().value ).toEqual( { response: undefined, error, } ); } ); it( 'yields the expected actions for a success request', () => { const fetchStoreDefinition = createFetchStore( { baseName: 'SaveSomeData', controlCallback: async () => true, } ); const action = fetchStoreDefinition.actions.fetchSaveSomeData(); expect( action.next().value.type ).toEqual( 'START_FETCH_SAVE_SOME_DATA' ); expect( action.next().value.type ).toEqual( 'FETCH_SAVE_SOME_DATA' ); expect( action.next( 42 ).value.type ).toEqual( 'RECEIVE_SAVE_SOME_DATA' ); expect( action.next().value.type ).toEqual( 'FINISH_FETCH_SAVE_SOME_DATA' ); expect( action.next().value ).toEqual( { response: 42, error: undefined, } ); } ); it( 'yields the expected actions for an error request', () => { const fetchStoreDefinition = createFetchStore( { baseName: 'SaveSomeData', controlCallback: async () => true, } ); const action = fetchStoreDefinition.actions.fetchSaveSomeData(); const error = { code: 'this-went-wrong', message: 'This went wrong.', }; expect( action.next().value.type ).toEqual( 'START_FETCH_SAVE_SOME_DATA' ); expect( action.next().value.type ).toEqual( 'FETCH_SAVE_SOME_DATA' ); expect( action.throw( error ).value.type ).toEqual( 'CATCH_FETCH_SAVE_SOME_DATA' ); expect( action.next().value ).toEqual( { response: undefined, error, } ); } ); it( 'makes a network request based on controlCallback', async () => { const expectedResponse = 'response-value'; fetchMock.getOnce( /^\/google-site-kit\/v1\/core\/test\/data\/some-data/, { body: JSON.stringify( expectedResponse ), status: 200 } ); const { response, error } = await dispatch.fetchGetSomeData( {}, 'value-to-key-response-by' ); expect( error ).toEqual( undefined ); expect( response ).toEqual( expectedResponse ); expect( store.getState().data ).toEqual( { 'value-to-key-response-by': expectedResponse, } ); } ); it( 'dispatches an error if the request fails', async () => { const errorResponse = { code: 'internal_server_error', message: 'Internal server error', data: { status: 500 }, }; fetchMock.getOnce( /^\/google-site-kit\/v1\/core\/test\/data\/some-data/, { body: errorResponse, status: 500 } ); muteConsole( 'error' ); const { response, error } = await dispatch.fetchGetSomeData( {}, 'value-to-key-response-by' ); expect( error ).toEqual( errorResponse ); expect( response ).toEqual( undefined ); expect( store.getState().data ).toEqual( undefined ); } ); it( 'sets flag for request being in progress', async () => { fetchMock.getOnce( /^\/google-site-kit\/v1\/core\/test\/data\/some-data/, { body: { someValue: 42 }, status: 200 } ); const requestArgs = [ {}, 'aValue' ]; // Initially the request is not in progress.. expect( select.isFetchingGetSomeData( ...requestArgs ) ).toEqual( false ); dispatch.fetchGetSomeData( ...requestArgs ); // Now it should be in progress. expect( select.isFetchingGetSomeData( ...requestArgs ) ).toEqual( true ); // A request for other arguments however is not in progress. expect( select.isFetchingGetSomeData( {}, 'anotherValue' ) ).toEqual( false ); await subscribeUntil( registry, () => store.getState().data !== undefined, ); // As the data has been received, the request is now no longer in progress. expect( select.isFetchingGetSomeData( ...requestArgs ) ).toEqual( false ); } ); } ); describe( 'receive', () => { it( 'requires params if argsToParams is provided', () => { const fetchStoreDefinition = createFetchStore( { baseName: 'SaveSomeData', controlCallback: async () => true, argsToParams: ( requiredParam ) => { invariant( requiredParam, 'requiredParam is required.' ); return { requiredParam, }; }, } ); expect( () => { const response = {}; fetchStoreDefinition.actions.receiveSaveSomeData( response ); } ).toThrow( 'params is required.' ); } ); it( 'does not require params if argsToParams is not provided', () => { const fetchStoreDefinition = createFetchStore( { baseName: 'SaveSomeData', controlCallback: async () => true, reducerCallback: ( state ) => state, } ); expect( () => { const response = {}; fetchStoreDefinition.actions.receiveSaveSomeData( response ); } ).not.toThrow( 'params is required.' ); } ); } ); } ); describe( 'selectors', () => { it( 'includes the expected selectors', () => { const fetchStoreDefinition = createFetchStore( { baseName: 'SaveSomeData', controlCallback: async () => true, } ); expect( Object.keys( fetchStoreDefinition.selectors ) ).toEqual( [ 'isFetchingSaveSomeData', ] ); } ); } ); } );
app.canvas.hud.compass = (() => { const tree = engine.utility.bitree.create({ dimension: 'angle', }) generateTree() app.canvas.hud.on('draw', draw) function draw({canvas, context}) { if (!app.settings.computed.graphicsHudCompassOn) { return } const {yaw} = engine.position.getEuler() const {z} = engine.position.getVector() const fov = app.settings.computed.graphicsFov, halfFov = fov / 2, maxAngle = yaw + halfFov, minAngle = yaw - halfFov, points = tree.retrieve(minAngle, fov), protection = engine.utility.clamp(engine.utility.scale(z, 0, content.const.lightZone, 0.125, 1)), rem = app.utility.css.rem(), width = canvas.width, y = rem for (const point of points) { const alpha = point.angle < yaw ? engine.utility.scale(point.angle, minAngle, yaw, 0, 1) : engine.utility.scale(point.angle, yaw, maxAngle, 1, 0) const x = engine.utility.scale(point.angle, minAngle, maxAngle, width, 0) point.draw({ alpha, context, point, protection, rem, x, y, }) } } function drawLine({ alpha, context, rem, x, y, }) { const height = rem let halfHeight = height / 2 y += rem / 2 context.lineWidth = 1 context.strokeStyle = `rgba(255, 255, 255, ${alpha})` // Avoid anti-aliasing x = Math.round(x) + 0.5 y = Math.round(y) + 0.5 halfHeight = Math.round(halfHeight) context.beginPath() context.moveTo(x, y - halfHeight) context.lineTo(x, y + halfHeight) context.stroke() } function drawLineSmall({ alpha, context, rem, x, y, }) { const height = rem / 2 const halfHeight = height / 2 y += rem / 2 context.strokeStyle = `rgba(255, 255, 255, ${alpha})` context.beginPath() context.moveTo(x, y - halfHeight) context.lineTo(x, y + halfHeight) context.stroke() } function drawText({ alpha, context, point, protection, rem, x, y, }) { const height = 2 * rem const halfHeight = height / 2 context.fillStyle = `rgba(0, 0, 0, ${alpha * protection})` context.font = `${height}px/${height}px SuperSubmarine` context.strokeStyle = `rgba(255, 255, 255, ${alpha})` context.textAlign = 'center' context.fillText(point.label, x, y + halfHeight) context.strokeText(point.label, x, y + halfHeight) } function drawTextPrimary({ alpha, context, point, protection, rem, x, y, }) { const height = 2 * rem const halfHeight = height / 2 context.fillStyle = `rgba(255, 255, 255, ${alpha})` context.font = `${height}px/${height}px SuperSubmarine` context.strokeStyle = `rgba(0, 0, 0, ${alpha * protection})` context.textAlign = 'center' context.strokeText(point.label, x, y + halfHeight) context.fillText(point.label, x, y + halfHeight) } function drawTextSmall({ alpha, context, point, protection, rem, x, y, }) { const height = rem * 1.5 const halfHeight = height / 2 y += rem / 6 context.fillStyle = `rgba(0, 0, 0, ${alpha * protection})` context.font = `${height}px/${height}px SuperSubmarine` context.strokeStyle = `rgba(255, 255, 255, ${alpha})` context.textAlign = 'center' context.fillText(point.label, x, y + halfHeight) context.strokeText(point.label, x, y + halfHeight) } function generateTree() { const points = [ { angle: 0, draw: drawText, label: 'E', }, { angle: 1/16 * Math.PI, draw: drawLineSmall, }, { angle: 2/16 * Math.PI, draw: drawLine, label: 'ENE', }, { angle: 3/16 * Math.PI, draw: drawLineSmall, }, { angle: 4/16 * Math.PI, draw: drawTextSmall, label: 'NE', }, { angle: 5/16 * Math.PI, draw: drawLineSmall, }, { angle: 6/16 * Math.PI, draw: drawLine, label: 'NNE', }, { angle: 7/16 * Math.PI, draw: drawLineSmall, }, { angle: 8/16 * Math.PI, draw: drawTextPrimary, label: 'N', }, { angle: 9/16 * Math.PI, draw: drawLineSmall, }, { angle: 10/16 * Math.PI, draw: drawLine, label: 'NNW', }, { angle: 11/16 * Math.PI, draw: drawLineSmall, }, { angle: 12/16 * Math.PI, draw: drawTextSmall, label: 'NW', }, { angle: 13/16 * Math.PI, draw: drawLineSmall, }, { angle: 14/16 * Math.PI, draw: drawLine, label: 'WNW', }, { angle: 15/16 * Math.PI, draw: drawLineSmall, }, { angle: Math.PI, draw: drawText, label: 'W', }, { angle: 17/16 * Math.PI, draw: drawLineSmall, }, { angle: 18/16 * Math.PI, draw: drawLine, label: 'WSW', }, { angle: 19/16 * Math.PI, draw: drawLineSmall, }, { angle: 20/16 * Math.PI, draw: drawTextSmall, label: 'SW', }, { angle: 21/16 * Math.PI, draw: drawLineSmall, }, { angle: 22/16 * Math.PI, draw: drawLine, label: 'SSW', }, { angle: 23/16 * Math.PI, draw: drawLineSmall, }, { angle: 24/16 * Math.PI, draw: drawText, label: 'S', }, { angle: 25/16 * Math.PI, draw: drawLineSmall, }, { angle: 26/16 * Math.PI, draw: drawLine, label: 'SSE', }, { angle: 27/16 * Math.PI, draw: drawLineSmall, }, { angle: 28/16 * Math.PI, draw: drawTextSmall, label: 'SE', }, { angle: 29/16 * Math.PI, draw: drawLineSmall, }, { angle: 30/16 * Math.PI, draw: drawLine, label: 'ESE', }, { angle: 31/16 * Math.PI, draw: drawLineSmall, }, ] for (let rotation = -1; rotation < 2; rotation += 1) { for (const point of points) { tree.insert({ ...point, angle: point.angle + (rotation * Math.PI * 2), }) } } } return {} })()
var PlatformAccessory, Accessory, Service, Characteristic, UUIDGen, CommunityTypes; var _homebridge; const miio = require('miio'); const dgram = require('dgram'); const util = require('util'); const inherits = require('util').inherits; const crypto = require('crypto'); const devices = require('./mijia/'); const types = require('../util/types'); const iv = Buffer.from([0x17, 0x99, 0x6d, 0x09, 0x3d, 0x28, 0xdd, 0xb3, 0xba, 0x69, 0x5a, 0x2e, 0x6f, 0x58, 0x56, 0x2e]); const multicastIp = '224.0.0.50'; const multicastPort = 4321; const udpPort = 9898; class Mijia { // config may be null // api may be null if launched from old homebridge version constructor(log, config, api) { if(!config || !config['mijia']){ log("Mijia initialization skipped. Missing configuration data."); return; } this.PlatformAccessory = PlatformAccessory; this.Accessory = Accessory; this.Service = Service; this.Characteristic = Characteristic; this.UUIDGen = UUIDGen; this.CommunityTypes = CommunityTypes; //define this.udpScoket = null; this.log = log; this.config = config; //init properties this.gateways = {}; this.accessories = {}; //device object this.devices = {}; //supported device parser this._devices = {}; if (api) { // Save the API object as plugin needs to register new accessory via this object. this.api = api; } else { this.log.error("Homebridge's version is too old, please upgrade!"); } //init upd server this.initUpdSocket().then(() => { //init config this.initConfig(config); //init device parsers this.loadDevices(); //discover wifi device this.discoverWifiDevice(); }).catch((err) => { this.log.error('mijia init upd socket error->%s', err); }); if (this.api) { this.api.on('didFinishLaunching', this.didFinishLaunching.bind(this)); } if (_homebridge.mijia != undefined) { _homebridge.mijia = this; } this.log.debug('mijia constructor done'); } /** * static method to export hap properties * @param {*homebridge} homebridge */ static init(homebridge) { return new Promise((resolve, reject) => { homebridge.registerPlatform("homebridge-smarthome", "smarthome-mijia", Mijia, true); resolve(); }); } /** * init properties from config.json */ initConfig(config) { let { mijia } = config; let { sids, passwords, devices } = mijia; if (sids && passwords) { if (sids.length != passwords.length) { throw new Error('sids length and passwords length must be equal'); } } sids.map((sid, index) => { this.gateways[sid] = { password: passwords[index], devices: {} }; }); if (devices && devices.length > 0) { //for wifi devices devices.map((device) => { if (device.sid != undefined) { this.devices[device.sid] = device; } else if (device.name != undefined) { this.devices[device.name] = device; } else { this.log.warn('device do not have sid or name,will discard to register'); } }); } this.log.debug('initConfig done'); } /** * init udpScoket */ initUpdSocket() { return new Promise((resolve, reject) => { this.udpScoket = dgram.createSocket({ type: 'udp4', reuseAddr: true }); this.udpScoket.on('message', (msg, rinfo) => { this.log.debug('mijia udp socket receive -> %s', new String(msg)); this.parseMsg(msg, rinfo); }); this.udpScoket.on('error', (err) => { this.log.error('error, msg -> %s, stack -> %s', err.message, err.stack); reject(error); }); this.udpScoket.on('listening', () => { this.log.debug("mijia upd server is listening on port 9898"); this.udpScoket.addMembership(multicastIp); this.log.debug("mijia add multicast to %s", multicastIp); resolve(); }); this.udpScoket.bind(udpPort); }); } /** * init parsers */ loadDevices() { this._devices = devices(this); this.log.debug('loadDevices done'); } didFinishLaunching() { //1.discover who are mijia gateway let cmd_whois = { cmd: 'whois' }; this.sendMsg(cmd_whois, multicastIp, multicastPort); //2.set interval to update mijia gateway and check the gateway alive setInterval(() => { this.sendMsg(cmd_whois, multicastIp, multicastPort); }, 1800000); //1800s->30m } /** * configure cached accessory * @param {*} accessory */ configureAccessory(accessory) { accessory.reachable = true; accessory.on('identify', (paired, callback) => { this.log.debug(accessory.displayName + " -> Identify!!!"); callback(); }); if (!this.accessories[accessory.UUID]) { this.accessories[accessory.UUID] = accessory; } } /** * discover wifi deivce */ discoverWifiDevice() { for (let key in this.devices) { let device = this.devices[key]; let { type, model } = device; if (type == 'wifi') { if (this._devices[model]) { this._devices[model](this, device); this.log.debug('construct wifi device->%s', util.inspect(device)); } else { this.log.warn('not support device->%s', util.inspect(device)); } } } this.log.debug('discoverWifiDevice done'); } /** * discover zigbee deivce via gateway * @param {*gateway ip} ip * @param {*gateway port} port */ discoverZigbeeDevice(ip, port) { let cmd_get_id_list = { cmd: 'get_id_list' }; this.sendMsg(cmd_get_id_list, ip, port); setInterval(() => { this.sendMsg(cmd_get_id_list, ip, port); }, 300000); //300s->5m } /** * send data via upd socket * @param {*msg} msg * @param {*ip} ip * @param {*port} port */ sendMsg(msg, ip, port) { this.log.debug('send msg->%s', util.inspect(msg)); if (typeof msg == 'string') { this.udpScoket.send(msg, 0, msg.length, port, ip); } else { let str = JSON.stringify(msg); this.udpScoket.send(str, 0, str.length, port, ip); } } /** * send data via upd socket * @param {*msg} msg * @param {*sid} sid */ sendMsgToSid(msg, sid) { this.log.debug('send msg->%s', util.inspect(msg)); let gateway = this.devices[sid]; if (!gateway) { gateway = this.gateways[sid]; } else { gateway = gateway.gateway; } if (!gateway) { this.log.error(`can't find gateway sid->${sid}`); return; } let { ip, port } = gateway; if(!Number.isInteger(port) || port < 0 || port > 65536) { this.log.warn('Wrong port number:' + port ); return; } if (typeof msg == 'string') { this.udpScoket.send(msg, 0, msg.length, port, ip); } else { let str = JSON.stringify(msg); this.udpScoket.send(str, 0, str.length, port, ip); } } /** * parse msg from udp socket * @param {*msg} msg * @param {*remoteaddr} rinfo */ parseMsg(msg, rinfo) { let json; try { json = JSON.parse(msg); } catch (ex) { this.log.error('parse json msg failed -> %s', ex); return; } let cmd = json.cmd; switch (cmd) { case 'iam': { let { ip, port, model } = json; if (model == 'gateway') { this.discoverZigbeeDevice(ip, port); } else { this.log.warn('receive a iam cmd,but model is %s', model); } break; } case 'get_id_list_ack': { let { sid, token } = json; let data = JSON.parse(json.data); let gateway = this.gateways[sid] ? this.gateways[sid] : { sid: sid, model: 'gateway', token: token, devices:{} }; gateway.ip = rinfo.address; gateway.port = rinfo.port; gateway.token = token; gateway.last_time = new Date(); let cmd_read = { cmd: 'read', sid: sid }; this.sendMsg(cmd_read, gateway.ip, gateway.port); data.map((did, index) => { if (!this.devices[did]) { this.devices[did] = { sid: did, type: 'zigbee' }; } this.devices[did].gateway = gateway; this.devices[did].last_time = new Date(); gateway.devices[did] = this.devices[did]; cmd_read.sid = did; this.sendMsg(cmd_read, gateway.ip, gateway.port); }); break; } case 'heartbeat': { let { sid, model, short_id, token } = json; let data = JSON.parse(json.data); if (model == 'gateway') { let gateway = this.gateways[sid] ? this.gateways[sid] : { sid: sid }; this.gateways[sid] = gateway; this.gateways[sid].model = 'gateway'; this.gateways[sid].short_id = short_id; this.gateways[sid].token = token; this.gateways[sid].last_time = new Date(); } else { let device = this.devices[sid] ? this.devices[sid] : { sid: sid, short_id: short_id, type: 'zigbee' }; device = Object.assign(device, data); device.last_time = new Date(); this.devices[sid] = device; } break; } case 'write_ack': { this.log.debug('write_ack ->%s', util.inspect(json)); break; } case 'read_ack': case 'report': { this.parseDevice(json, rinfo); break; } default: { this.log.warn('unkonwn cmd:[%s] from getway[%s]', cmd, (rinfo.address + ':' + rinfo.port)); } } } /** * parse zigbee devices msg * @param {*gateway json msg} json * @param {*remote info} rinfo */ parseDevice(json, rinfo) { //when the device status changed , will recive data let { sid, model, short_id, token } = json; let data = JSON.parse(json.data); if (model == 'gateway') { if (short_id) { this.gateways[sid].short_id = short_id; } if (token) { this.gateways[sid].token = token; } this.gateways[sid].last_time = new Date(); } else { let device = this.devices[sid] ? this.devices[sid] : { sid: sid, short_id: short_id, model: model }; device = Object.assign(device, data); device.last_time = new Date(); this.devices[sid] = device; } if (this._devices[model]) { this._devices[model].parseMsg(json, rinfo); } else { this.log.warn('receive report cmd, but no support device found->%s', model); } } /** * generate gateway write Key * @param {*gateway id} sid */ generateKey(sid) { let gateway = this.devices[sid]; if (!gateway) { gateway = this.gateways[sid]; } else { gateway = gateway.gateway; } if (!gateway) { this.log.error(`can't find gateway sid->${sid}`); return; } let { password, token } = gateway; let cipher = crypto.createCipheriv('aes-128-cbc', password, iv); let key = cipher.update(token, "ascii", "hex"); cipher.final('hex'); return key; } } //module exports define module.exports = (homebridge) => { //export some properties from homebridge PlatformAccessory = homebridge.platformAccessory; Accessory = homebridge.hap.Accessory; Service = homebridge.hap.Service; Characteristic = homebridge.hap.Characteristic; UUIDGen = homebridge.hap.uuid; CommunityTypes = types(homebridge); _homebridge = homebridge; //init mikit return Mijia.init(homebridge); }
app.controller('appSettingsController', ['$scope', '$q', '$rootScope', '$stateParams', '$location', 'projectService', '$timeout', 'appSettingsService', function($scope, $q, $rootScope, $stateParams, $location, projectService, $timeout, appSettingsService){ var id; $rootScope.showAppPanel=true; $rootScope.isFullScreen=false; $rootScope.page='appsettings'; $scope.spinners={}; $scope.generalSettings={ category:"general", settings:{ appName:null, appInProduction:false, appIcon:null } }; $scope.emailSettings={ category:"email", settings:{ mandrill:{ apiKey:null, enabled:true }, mailgun:{ apiKey:null, domain:null, enabled:false }, fromEmail:null, fromName:null } }; $scope.pushSettings={ category:"push", settings:{ apple:{ certificates:[] }, android:{ credentials:[] }, windows:{ credentials:[] } } }; $scope.authSettings={ category:"auth", settings:{ general:{ enabled:true, callbackURL: null, primaryColor: "#549afc" }, custom:{ enabled:true }, sessions:{ enabled:true, sessionLength: 30 }, signupEmail:{ enabled:false, allowOnlyVerifiedLogins:false, template:"" }, resetPasswordEmail:{ enabled:false, template:"" }, facebook:{ enabled:false, appId:null, appSecret:null, attributes:_getFbAttributesList(), permissions:_getFbPermissions() }, google:{ enabled:false, appId:null, appSecret:null, attributes:_getGoogleAttributesList(), permissions:_getGooglePermissions() }, twitter:{ enabled:false, appId:null, appSecret:null, attributes:null, permissions:null }, linkedIn:{ enabled:false, appId:null, appSecret:null, attributes:null, permissions:{ r_basicprofile:true, r_emailaddress:false, rw_company_admin:false, w_share:false } }, github:{ enabled:false, appId:null, appSecret:null, attributes:{ user:{ enabled: true, scope: 'user' }, userEmail:{ enabled: true, scope: 'user:email' } }, permissions:_getGithubPermissions() } } }; $scope.facebook={ moreAttributes:false, morePermissions:false }; $scope.google={ moreAttributes:false, morePermissions:false }; $scope.github={ moreAttributes:false, morePermissions:false }; $scope.signupHtml={ htmlMode:{ css:{ cursor: "pointer", "border-bottom": "1px solid #488ff9", color: "#488ff9" }, enabled:true }, previewMode:{ css:{ cursor: "pointer" }, enabled:false } }; $scope.resetPswdHtml={ htmlMode:{ css:{ cursor: "pointer", "border-bottom": "1px solid #488ff9", color: "#488ff9" }, enabled:true }, previewMode:{ css:{ cursor: "pointer" }, enabled:false } }; $scope.fileAllowedTypes="*";//Files $scope.settingsMenu={ general:true, email:false, push:false, auth:false }; $scope.settingsMenuHover={ general:false, email:false, push:false, auth:false }; $scope.templateEditorOptions = { lineWrapping : false, lineNumbers: true, theme:'monokai', mode : "text/html" }; $scope.authPageSimilate={ authenticateSpinner:false, authenticateError:null, isLogin:true, forgotPasswordPage:false, forgotPasswordSpinner:false, forgotPwdError:null }; $scope.init= function() { id = $stateParams.appId; $rootScope.pageHeaderDisplay="App Settings"; var promises=[]; promises.push(_getDefaultTemplate("reset-password")); promises.push(_getDefaultTemplate("sign-up")); $q.all(promises).then(function(list){ $scope.authSettings.settings.resetPasswordEmail.template=list[0]; $scope.authSettings.settings.signupEmail.template=list[1]; if($rootScope.currentProject && $rootScope.currentProject.appId === id){ //if the same project is already in the rootScope, then dont load it. getSettings(); }else{ loadProject(id); } },function(error){ if($rootScope.currentProject && $rootScope.currentProject.appId === id){ //if the same project is already in the rootScope, then dont load it. getSettings(); }else{ loadProject(id); } }); //Add Callback URL with appId $scope.loginPageURL=SERVER_URL+"/page/"+id+"/authentication"; $scope.fbCallbackURL=SERVER_URL+"/auth/"+id+"/facebook/callback"; $scope.googleCallbackURL=SERVER_URL+"/auth/"+id+"/google/callback"; $scope.twitterCallbackURL=SERVER_URL+"/auth/"+id+"/twitter/callback"; $scope.linkedInCallbackURL=SERVER_URL+"/auth/"+id+"/linkedin/callback"; $scope.githubCallbackURL=SERVER_URL+"/auth/"+id+"/github/callback"; }; $scope.updateSettings=function(categoryName){ var settingsObj=null; var validate=false; var validateMsg=null; if(categoryName=="general"){ settingsObj=$scope.generalSettings.settings; validate=true; validateMsg=null; } if(categoryName=="email"){ settingsObj=$scope.emailSettings.settings; if(((settingsObj.mailgun.domain && settingsObj.mailgun.apiKey) || settingsObj.mandrill.apiKey) && settingsObj.fromEmail){ validate=true; if(settingsObj.mailgun.enabled){ settingsObj.mandrill.apiKey=null; } if(settingsObj.mandrill.enabled){ settingsObj.mailgun.apiKey=null; settingsObj.mailgun.domain=null; } if(!__isDevelopment){ /****Tracking*********/ mixpanel.track('Save Email Settings', {"appId": $rootScope.currentProject.appId}); /****End of Tracking*****/ } }else{ validate=false; validateMsg="All Mandrill API Key,From Email,From Name are required"; } } if(categoryName=="push"){ settingsObj=$scope.pushSettings.settings; validate=true; validateMsg=null; if(!__isDevelopment){ /****Tracking*********/ mixpanel.track('Save Push Settings', {"App id": $rootScope.currentProject.appId}); /****End of Tracking*****/ } } if(categoryName=="auth"){ settingsObj=$scope.authSettings.settings; validate=true; validateMsg=_validateSocialFields(settingsObj); if(validateMsg){ validate=false; }else{ /****Tracking*********/ mixpanel.track('Save Auth Settings', {"appId": $rootScope.currentProject.appId}); /****End of Tracking*****/ } } if(validate){ $scope.spinners[categoryName]=true; appSettingsService.putSettings($rootScope.currentProject.appId,$rootScope.currentProject.keys.master,categoryName,settingsObj) .then(function(settings){ $scope.spinners[categoryName]=false; }, function(error){ $scope.spinners[categoryName]=false; }); }else{ WarningNotify(validateMsg); } }; $scope.initAddAppIcon=function(){ $scope.editableFile=null; $("#md-appsettingsfileviewer").modal(); }; $scope.removeAppIcon=function(){ $scope.generalSettings.settings.appIcon=null; }; $scope.initAddAppleCertificate=function(){ $scope.editableFile=null; $("#md-appsettingsfileviewer").modal(); }; $scope.saveFile=function(file){ if(file){ var names=file.name.split("."); //App Icon if($scope.settingsMenu.general){ if(names[1]=="png"){ $("#md-appsettingsfileviewer").modal("hide"); appSettingsService.upsertAppSettingFile($rootScope.currentProject.appId,$rootScope.currentProject.keys.master,file,"general") .then(function(resp){ $scope.generalSettings.settings.appIcon=resp; },function(error){ errorNotify("Error on saving app icon, try again.."); }); }else{ errorNotify("Only .PNG is allowed"); } } //Apple Certificate if($scope.settingsMenu.push){ if(names[1]=="p12"){ $("#md-appsettingsfileviewer").modal("hide"); appSettingsService.upsertAppSettingFile($rootScope.currentProject.appId,$rootScope.currentProject.keys.master,file,"push") .then(function(resp){ if($scope.pushSettings.settings.apple.certificates.length==0){ $scope.pushSettings.settings.apple.certificates.push(resp); }else if($scope.pushSettings.settings.apple.certificates.length>0){ $scope.pushSettings.settings.apple.certificates[0]=resp; } },function(error){ errorNotify("Error on saving apple certificate, try again.."); }); }else{ errorNotify("Only .P12 is allowed"); } } } }; //Toggler $scope.selectSettings=function(settingsName){ if(settingsName=="general"){ $scope.settingsMenu.general=true; $scope.settingsMenu.email=false; $scope.settingsMenu.push=false; $scope.settingsMenu.auth=false; } if(settingsName=="email"){ $scope.settingsMenu.general=false; $scope.settingsMenu.email=true; $scope.settingsMenu.push=false; $scope.settingsMenu.auth=false; } if(settingsName=="push"){ $scope.settingsMenu.general=false; $scope.settingsMenu.email=false; $scope.settingsMenu.push=true; $scope.settingsMenu.auth=false; } if(settingsName=="auth"){ $scope.settingsMenu.general=false; $scope.settingsMenu.email=false; $scope.settingsMenu.push=false; $scope.settingsMenu.auth=true; } }; $scope.menuHover=function(settingsName){ if(settingsName=="general" && !$scope.settingsMenu.general && !$scope.settingsMenuHover.general){ $scope.settingsMenuHover.general=true; } if(settingsName=="email" && !$scope.settingsMenu.email && !$scope.settingsMenuHover.email){ $scope.settingsMenuHover.email=true; } if(settingsName=="push" && !$scope.settingsMenu.push && !$scope.settingsMenuHover.push){ $scope.settingsMenuHover.push=true; } if(settingsName=="auth" && !$scope.settingsMenu.auth && !$scope.settingsMenuHover.auth){ $scope.settingsMenuHover.auth=true; } }; $scope.menuLeave=function(settingsName){ if(settingsName=="general" && !$scope.settingsMenu.general && $scope.settingsMenuHover.general){ $scope.settingsMenuHover.general=false; } if(settingsName=="email" && !$scope.settingsMenu.email && $scope.settingsMenuHover.email){ $scope.settingsMenuHover.email=false; } if(settingsName=="push" && !$scope.settingsMenu.push && $scope.settingsMenuHover.push){ $scope.settingsMenuHover.push=false; } if(settingsName=="auth" && !$scope.settingsMenu.auth && $scope.settingsMenuHover.auth){ $scope.settingsMenuHover.auth=false; } }; $scope.toggleSignupEmail=function(mode){ if(mode=="html"){ $scope.signupHtml.htmlMode.enabled=true; $scope.signupHtml.htmlMode.css={ cursor: "pointer", "border-bottom": "1px solid #488ff9", color: "#488ff9" }; $scope.signupHtml.previewMode.enabled=false; $scope.signupHtml.previewMode.css={ cursor: "pointer" }; } if(mode=="preview"){ $scope.signupHtml.previewMode.enabled=true; $scope.signupHtml.previewMode.css={ cursor: "pointer", "border-bottom": "1px solid #488ff9", color: "#488ff9" }; $scope.signupHtml.htmlMode.enabled=false; $scope.signupHtml.htmlMode.css={ cursor: "pointer" }; } }; $scope.toggleResetPswdEmail=function(mode){ if(mode=="html"){ $scope.resetPswdHtml.htmlMode.enabled=true; $scope.resetPswdHtml.htmlMode.css={ cursor: "pointer", "border-bottom": "1px solid #488ff9", color: "#488ff9" }; $scope.resetPswdHtml.previewMode.enabled=false; $scope.resetPswdHtml.previewMode.css={ cursor: "pointer" }; } if(mode=="preview"){ $scope.resetPswdHtml.previewMode.enabled=true; $scope.resetPswdHtml.previewMode.css={ cursor: "pointer", "border-bottom": "1px solid #488ff9", color: "#488ff9" }; $scope.resetPswdHtml.htmlMode.enabled=false; $scope.resetPswdHtml.htmlMode.css={ cursor: "pointer" }; } }; $scope.toggleEmailConfig=function(option){ if(option=="mandrill"){ $scope.emailSettings.settings.mandrill.enabled=true; $scope.emailSettings.settings.mailgun.enabled=false; } if(option=="mailgun"){ $scope.emailSettings.settings.mandrill.enabled=false; $scope.emailSettings.settings.mailgun.enabled=true; } }; $scope.toggleFbAttributes=function(bool){ $scope.facebook.moreAttributes=bool; }; $scope.toggleFbPermissions=function(bool){ $scope.facebook.morePermissions=bool; }; $scope.toggleGooglePermissions=function(bool){ $scope.google.morePermissions=bool; }; $scope.toggleGithubPermissions=function(bool){ $scope.github.morePermissions=bool; }; $scope.authSimilateAuth=function(authPage){ if(authPage=="login"){ $scope.authPageSimilate.isLogin=true; } if(authPage=="signup"){ $scope.authPageSimilate.isLogin=false; } }; $scope.similateToForgotPwd=function(bool){ $scope.authPageSimilate.forgotPasswordPage=bool; }; $scope.loginUrlClick=function(){ $scope.loginUrlClippr=true; }; $scope.loginUrlOutsideClick=function(){ $scope.loginUrlClippr=false; }; /********************************Private fuctions****************************/ function loadProject(id){ //$scope.settingsLoading=true; projectService.getProject(id) .then(function(currentProject){ if(currentProject){ $rootScope.currentProject=currentProject; getSettings(); } }, function(error){ console.log(error); $scope.settingsLoading=false; }); } function getSettings(){ //$scope.settingsLoading=true; appSettingsService.getSettings($rootScope.currentProject.appId,$rootScope.currentProject.keys.master) .then(function(settings){ if(settings && settings.length>0){ var general=_.where(settings, {category: "general"}); if(general && general.length>0){ $scope.generalSettings=general[0]; } var email=_.where(settings, {category: "email"}); if(email && email.length>0){ $scope.emailSettings=email[0]; } var push=_.where(settings, {category: "push"}); if(push && push.length>0){ $scope.pushSettings=push[0]; } var auth=_.where(settings, {category: "auth"}); if(auth && auth.length>0){ $scope.authSettings=auth[0]; } $scope.settingsLoading=false; }else{ var promises=[]; promises.push(appSettingsService.putSettings($rootScope.currentProject.appId,$rootScope.currentProject.keys.master,"general",$scope.generalSettings.settings)); promises.push(appSettingsService.putSettings($rootScope.currentProject.appId,$rootScope.currentProject.keys.master,"email",$scope.emailSettings.settings)); promises.push(appSettingsService.putSettings($rootScope.currentProject.appId,$rootScope.currentProject.keys.master,"push",$scope.pushSettings.settings)); promises.push(appSettingsService.putSettings($rootScope.currentProject.appId,$rootScope.currentProject.keys.master,"auth",$scope.authSettings.settings)); $q.all(promises).then(function(settings){ $scope.settingsLoading=false; }, function(error){ $scope.settingsLoading=false; }); } }, function(error){ $scope.settingsLoading=false; }); } function _validateSocialFields(settings){ if(!settings.custom.enabled && !settings.facebook.enabled && !settings.google.enabled && !settings.twitter.enabled && !settings.linkedIn.enabled && !settings.github.enable){ return "You need to enable atleast one authentication provider."; } if(settings.general.callbackURL && !_validateUrl(settings.general.callbackURL)){ return "App callbackURL is invalid."; } if(!_validateNumber(settings.sessions.sessionLength)){ return "Invalid Session Length, should be a number."; } if(Number(settings.sessions.sessionLength)<1 || Number(settings.sessions.sessionLength)>365){ return "Session Length should be in between 1 to 365"; } if(settings.facebook.enabled){ if(!settings.facebook.appId || !settings.facebook.appSecret){ return "Facebook App ID and App Secret is required."; } } if(settings.google.enabled){ if(!settings.google.appId || !settings.google.appSecret){ return "Google App ID and App Secret is required."; } } if(settings.twitter.enabled){ if(!settings.twitter.appId || !settings.twitter.appSecret){ return "Twitter Consumer Key and Consumer Secret is required."; } } if(settings.linkedIn.enabled){ if(!settings.linkedIn.appId || !settings.linkedIn.appSecret){ return "LinkedIn Consumer Key and Consumer Secret is required."; } } if(settings.github.enabled){ if(!settings.github.appId || !settings.github.appSecret){ return "GitHub App ID and App Secret is required."; } } return null; } function _validateUrl(url){ var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/; return regexp.test(url); } function _validateNumber(num){ if(num && num!=""){ var tempData=angular.copy(num); num=Number(num); if(num.toString()!=tempData){ return false; } }else{ return false; } return true; } function _getDefaultTemplate(templateName){ var q=$q.defer(); var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if(xmlhttp.status === 200 && xmlhttp.readyState === 4){ q.resolve(xmlhttp.responseText); } if(xmlhttp.status !== 200 && xmlhttp.status!==0){ q.reject("Failed to load default email template"); } }; xmlhttp.open("GET","assets/files/"+templateName+".html",true); xmlhttp.send(); return q.promise; } function _getFbAttributesList(){ return { id:true, about:false, age_range:false, bio:false, birthday:false, context:false, cover:false, currency:false, devices:false, education:false, email:false, favorite_athletes:false, favorite_teams:false, first_name:false, gender:false, hometown:false, inspirational_people:false, install_type:false, installed:false, interested_in:false, is_shared_login:false, is_verified:false, languages:false, last_name:false, link:false, locale:false, location:false, meeting_for:false, middle_name:false, name:false, name_format:false, payment_pricepoints:false, political:false, public_key:false, quotes:false, relationship_status:false, religion:false, security_settings:false, shared_login_upgrade_required_by:false, significant_other:false, sports:false, test_group:false, third_party_id:false, timezone:false, token_for_business:false, updated_time:false, verified:false, video_upload_limits:false, viewer_can_send_gift:false, website:false, work:false } } function _getFbPermissions(){ return { public_profile:{ enabled:true, scope:"public_profile" }, user_friends:{ enabled:false, scope:"user_friends" }, email:{ enabled:false, scope:"email" }, user_about_me:{ enabled:false, scope:"user_about_me" }, "user_actions_books":{ enabled:false, scope:"user_actions.books" }, "user_actions_fitness":{ enabled:false, scope:"user_actions.fitness" }, "user_actions_music":{ enabled:false, scope:"user_actions.music" }, "user_actions_news":{ enabled:false, scope:"user_actions.news" }, "user_actions_video":{ enabled:false, scope:"user_actions.video" }, user_birthday:{ enabled:false, scope:"user_birthday" }, user_education_history:{ enabled:false, scope:"user_education_history" }, user_events:{ enabled:false, scope:"user_events" }, user_games_activity:{ enabled:false, scope:"user_games_activity" }, user_hometown:{ enabled:false, scope:"user_hometown" }, user_likes:{ enabled:false, scope:"user_likes" }, user_location:{ enabled:false, scope:"user_location" }, user_managed_groups:{ enabled:false, scope:"user_managed_groups" }, user_photos:{ enabled:false, scope:"user_photos" }, user_posts:{ enabled:false, scope:"user_posts" }, user_relationships:{ enabled:false, scope:"user_relationships" }, user_relationship_details:{ enabled:false, scope:"user_relationship_details" }, user_religion_politics:{ enabled:false, scope:"user_religion_politics" }, user_tagged_places:{ enabled:false, scope:"user_tagged_places" }, user_videos:{ enabled:false, scope:"user_videos" }, user_website:{ enabled:false, scope:"user_website" }, user_work_history:{ enabled:false, scope:"user_work_history" }, read_custom_friendlists:{ enabled:false, scope:"read_custom_friendlists" }, read_insights:{ enabled:false, scope:"read_insights" }, read_audience_network_insights:{ enabled:false, scope:"read_audience_network_insights" }, read_page_mailboxes:{ enabled:false, scope:"read_page_mailboxes" }, manage_pages:{ enabled:false, scope:"manage_pages" }, publish_pages:{ enabled:false, scope:"publish_pages" }, publish_actions:{ enabled:false, scope:"publish_actions" }, rsvp_event:{ enabled:false, scope:"rsvp_event" }, pages_show_list:{ enabled:false, scope:"pages_show_list" }, pages_manage_cta:{ enabled:false, scope:"pages_manage_cta" }, pages_manage_instant_articles:{ enabled:false, scope:"pages_manage_instant_articles" }, ads_read:{ enabled:false, scope:"ads_read" }, ads_management:{ enabled:false, scope:"ads_management" } } } function _getGoogleAttributesList(){ return { 'userinfoProfile':{ enabled: true, scope: 'https://www.googleapis.com/auth/userinfo.profile' }, 'userinfoEmail':{ enabled: true, scope: 'https://www.googleapis.com/auth/userinfo.email' } } } function _getGooglePermissions(){ return{ 'contacts':{ enabled: false, scope: 'https://www.googleapis.com/auth/contacts' }, 'blogger':{ enabled: false, scope: 'https://www.googleapis.com/auth/blogger' }, 'calendar':{ enabled: false, scope: 'https://www.googleapis.com/auth/calendar' }, 'gmail':{ enabled: false, scope: 'https://mail.google.com/' }, 'googlePlus':{ enabled: false, scope: 'https://www.googleapis.com/auth/plus.login' }, 'youtube':{ enabled: false, scope: 'https://www.googleapis.com/auth/youtube' }, 'books':{ enabled: false, scope: 'https://www.googleapis.com/auth/books' }, 'drive':{ enabled: false, scope: 'https://www.googleapis.com/auth/drive' }, 'coordinates':{ enabled: false, scope: 'https://www.googleapis.com/auth/coordinate' }, 'picasa':{ enabled: false, scope: 'https://picasaweb.google.com/data/' }, 'spreadsheets':{ enabled: false, scope: 'https://spreadsheets.google.com/feeds/' }, 'webmasters':{ enabled: false, scope: 'https://www.googleapis.com/auth/webmasters' }, 'tasks':{ enabled: false, scope: 'https://www.googleapis.com/auth/tasks' }, 'analytics':{ enabled: false, scope: 'https://www.googleapis.com/auth/analytics' }, 'UrlShortener':{ enabled: false, scope: 'https://www.googleapis.com/auth/urlshortener' } } } function _getGithubPermissions(){ return { userFollow:{ enabled: true, scope: 'user:follow' }, public_repo:{ enabled: false, scope: 'public_repo' }, repo:{ enabled: false, scope: 'repo' }, repo_deployment:{ enabled: false, scope: 'repo_deployment' }, repoStatus:{ enabled: false, scope: 'repo:status' }, delete_repo:{ enabled: false, scope: 'delete_repo' }, notifications:{ enabled: false, scope: 'notifications' }, gist:{ enabled: false, scope: 'gist' }, readRepoHook:{ enabled: false, scope: 'read:repo_hook' }, writeRepoHook:{ enabled: false, scope: 'write:repo_hook' }, adminRepoHook:{ enabled: false, scope: 'admin:repo_hook' }, adminOrgHook:{ enabled: false, scope: 'admin:org_hook' }, readOrg:{ enabled: false, scope: 'read:org' }, writeOrg:{ enabled: false, scope: 'write:org' }, adminOrg:{ enabled: false, scope: 'admin:org' }, readPublicKey:{ enabled: false, scope: 'read:public_key' }, writePublicKey:{ enabled: false, scope: 'write:public_key' }, adminPublicKey:{ enabled: false, scope: 'admin:public_key' }, readGpgKey:{ enabled: false, scope: 'read:gpg_key' }, writeGpgKey:{ enabled: false, scope: 'write:gpg_key' }, adminGpgKey:{ enabled: false, scope: 'admin:gpg_key' } } } }]);
import React from 'react'; import styled from '@emotion/styled' import Image from 'gatsby-image' import Iconos from './iconos' import Layout from './layout' import {graphql} from 'gatsby' const Contenido = styled.div` max-width: 1200px; margin: 0 auto; width: 95%; @media (min-width: 768px) { display:grid; grid-template-columns: 2fr 1fr; column-gap: 5rem; } `; const Sidebar = styled.aside` .precio { font-size: 2rem; color: #75AB00; } .agente { margin-top: 4rem; border-radius: 2rem; background-color: #75AB00; padding: 3rem; color: #fff; p{ margin: 0; } } `; //no es necesario useStaticQuery ya que se ejecuta en gatsbynode antes! export const query =graphql` query($id: String!){ allStrapiPropiedades(filter: {id: {eq: $id}}) { nodes{ nombre descripcion wc estacionamiento habitaciones precio agentes{ nombre telefono email } imagen { sharp:childImageSharp { fluid (maxWidth: 1200) { ...GatsbyImageSharpFluid_withWebp } } } } } } `; const Propiedades = ({data: {allStrapiPropiedades: {nodes}}}) => { const {nombre, descripcion, wc,estacionamiento, habitaciones, agentes, imagen, precio} = nodes[0] return ( <Layout> <h1>{nombre}</h1> <Contenido> <main> <Image fluid={imagen.sharp.fluid} /> <p>{descripcion}</p> </main> <Sidebar> <p className="precio">${precio}</p> <Iconos wc={wc} estacionamiento={estacionamiento} habitaciones ={habitaciones} /> <div className="agente"> <h2>Vendedor:</h2> <p>{agentes.nombre}</p> <p>Tel: {agentes.telefono}</p> <p>Email: {agentes.email}</p> </div> </Sidebar> </Contenido> </Layout> ); } export default Propiedades;
/* * Copyright 2020 New Relic Corporation. All rights reserved. * SPDX-License-Identifier: Apache-2.0 */ 'use strict' const tap = require('tap') const read = require('fs').readFileSync const join = require('path').join const https = require('https') const RemoteMethod = require('../../lib/collector/remote-method') const MAX_PORT_ATTEMPTS = 5 tap.test("RemoteMethod makes two requests with one connection", (t) => { t.ok(true, "Setup Test") // create a basic https server using our standard test certs let opts = { key: read(join(__dirname, '../lib/test-key.key')), cert: read(join(__dirname, '../lib/self-signed-test-certificate.crt')) } const server = https.createServer(opts, function(req, res) { res.write("hello ssl") res.end() }) server.keepAliveTimeout = 2000 // set a reasonable server timeout for cleanup // of the server's keep-alive connections server.setTimeout(5000, (socket) => { socket.end() server.close() }) // close server when test ends t.tearDown(() => { server.close() }) let attempts = 0 server.on('error', (e) => { // server port not guranteed to be not in use if (e.code === 'EADDRINUSE') { if (attempts >= MAX_PORT_ATTEMPTS) { console.log('Exceeded max attempts (%s), bailing out.', MAX_PORT_ATTEMPTS) throw new Error('Unable to get unused port') } attempts++ console.log('Address in use, retrying...') setTimeout(() => { server.close() // start the server using a random port server.listen() }, 1000) } }) // start the server using a random port server.listen() // make requests once successfully running server.on('listening', () => { const port = server.address().port // once we start a server, use a RemoteMethod // object to make a request const method = createRemoteMethod(port) method.invoke({}, [], function(err, res) { t.ok(200 === res.status, "First request success") // once first request is done, create a second request const method2 = createRemoteMethod(port) method2.invoke({}, [], function(err2, res2) { t.ok(200 === res2.status, "Second request success") // end the test t.end() }) }) }) let connections = 0 // setup a connection listener for the server // if we see more than one, keep alive isn't // working. server.on('connection', function() { connections++ if (2 === connections) { t.fail("RemoteMethod made second connection despite keep-alive.") } }) }) function createRemoteMethod(port) { const config = { ssl: true, max_payload_size_in_bytes: 1000000, feature_flag: {} } const endpoint = { host: 'ssl.lvh.me', port: port } config.certificates = [ read(join(__dirname, '../lib/ca-certificate.crt'), 'utf8') ] const method = new RemoteMethod('fake', config, endpoint) return method }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const ethereumjs_util_1 = require("ethereumjs-util"); const baseTransaction_1 = require("./baseTransaction"); const types_1 = require("./types"); const util_1 = require("./util"); const TRANSACTION_TYPE = 1; const TRANSACTION_TYPE_BUFFER = Buffer.from(TRANSACTION_TYPE.toString(16).padStart(2, '0'), 'hex'); /** * Typed transaction with optional access lists * * - TransactionType: 1 * - EIP: [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) */ class AccessListEIP2930Transaction extends baseTransaction_1.BaseTransaction { /** * This constructor takes the values, validates them, assigns them and freezes the object. * * It is not recommended to use this constructor directly. Instead use * the static factory methods to assist in creating a Transaction object from * varying data types. */ constructor(txData, opts = {}) { var _a, _b; super(Object.assign(Object.assign({}, txData), { type: TRANSACTION_TYPE })); /** * The default HF if the tx type is active on that HF * or the first greater HF where the tx is active. * * @hidden */ this.DEFAULT_HARDFORK = 'berlin'; const { chainId, accessList, gasPrice } = txData; this.common = this._getCommon(opts.common, chainId); this.chainId = this.common.chainIdBN(); // EIP-2718 check is done in Common if (!this.common.isActivatedEIP(2930)) { throw new Error('EIP-2930 not enabled on Common'); } this.activeCapabilities = this.activeCapabilities.concat([2718, 2930]); // Populate the access list fields const accessListData = util_1.AccessLists.getAccessListData(accessList !== null && accessList !== void 0 ? accessList : []); this.accessList = accessListData.accessList; this.AccessListJSON = accessListData.AccessListJSON; // Verify the access list format. util_1.AccessLists.verifyAccessList(this.accessList); this.gasPrice = new ethereumjs_util_1.BN((0, ethereumjs_util_1.toBuffer)(gasPrice === '' ? '0x' : gasPrice)); this._validateCannotExceedMaxInteger({ gasPrice: this.gasPrice }); if (this.v && !this.v.eqn(0) && !this.v.eqn(1)) { throw new Error('The y-parity of the transaction should either be 0 or 1'); } if (this.common.gteHardfork('homestead') && ((_a = this.s) === null || _a === void 0 ? void 0 : _a.gt(types_1.N_DIV_2))) { throw new Error('Invalid Signature: s-values greater than secp256k1n/2 are considered invalid'); } const freeze = (_b = opts === null || opts === void 0 ? void 0 : opts.freeze) !== null && _b !== void 0 ? _b : true; if (freeze) { Object.freeze(this); } } /** * EIP-2930 alias for `r` * * @deprecated use `r` instead */ get senderR() { return this.r; } /** * EIP-2930 alias for `s` * * @deprecated use `s` instead */ get senderS() { return this.s; } /** * EIP-2930 alias for `v` * * @deprecated use `v` instead */ get yParity() { return this.v; } /** * Instantiate a transaction from a data dictionary. * * Format: { chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, * v, r, s } * * Notes: * - `chainId` will be set automatically if not provided * - All parameters are optional and have some basic default values */ static fromTxData(txData, opts = {}) { return new AccessListEIP2930Transaction(txData, opts); } /** * Instantiate a transaction from the serialized tx. * * Format: `0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, * signatureYParity (v), signatureR (r), signatureS (s)])` */ static fromSerializedTx(serialized, opts = {}) { if (!serialized.slice(0, 1).equals(TRANSACTION_TYPE_BUFFER)) { throw new Error(`Invalid serialized tx input: not an EIP-2930 transaction (wrong tx type, expected: ${TRANSACTION_TYPE}, received: ${serialized .slice(0, 1) .toString('hex')}`); } const values = ethereumjs_util_1.rlp.decode(serialized.slice(1)); if (!Array.isArray(values)) { throw new Error('Invalid serialized tx input: must be array'); } return AccessListEIP2930Transaction.fromValuesArray(values, opts); } /** * Instantiate a transaction from the serialized tx. * (alias of {@link AccessListEIP2930Transaction.fromSerializedTx}) * * Note: This means that the Buffer should start with 0x01. * * @deprecated this constructor alias is deprecated and will be removed * in favor of the {@link AccessListEIP2930Transaction.fromSerializedTx} constructor */ static fromRlpSerializedTx(serialized, opts = {}) { return AccessListEIP2930Transaction.fromSerializedTx(serialized, opts); } /** * Create a transaction from a values array. * * Format: `[chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, * signatureYParity (v), signatureR (r), signatureS (s)]` */ static fromValuesArray(values, opts = {}) { if (values.length !== 8 && values.length !== 11) { throw new Error('Invalid EIP-2930 transaction. Only expecting 8 values (for unsigned tx) or 11 values (for signed tx).'); } const [chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, v, r, s] = values; const emptyAccessList = []; return new AccessListEIP2930Transaction({ chainId: new ethereumjs_util_1.BN(chainId), nonce, gasPrice, gasLimit, to, value, data, accessList: accessList !== null && accessList !== void 0 ? accessList : emptyAccessList, v: v !== undefined ? new ethereumjs_util_1.BN(v) : undefined, r, s, }, opts); } /** * The amount of gas paid for the data in this tx */ getDataFee() { const cost = super.getDataFee(); cost.iaddn(util_1.AccessLists.getDataFeeEIP2930(this.accessList, this.common)); return cost; } /** * The up front amount that an account must have for this transaction to be valid */ getUpfrontCost() { return this.gasLimit.mul(this.gasPrice).add(this.value); } /** * Returns a Buffer Array of the raw Buffers of the EIP-2930 transaction, in order. * * Format: `[chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, * signatureYParity (v), signatureR (r), signatureS (s)]` * * Use {@link AccessListEIP2930Transaction.serialize} to add a transaction to a block * with {@link Block.fromValuesArray}. * * For an unsigned tx this method uses the empty Buffer values for the * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant * representation for external signing use {@link AccessListEIP2930Transaction.getMessageToSign}. */ raw() { return [ (0, ethereumjs_util_1.bnToUnpaddedBuffer)(this.chainId), (0, ethereumjs_util_1.bnToUnpaddedBuffer)(this.nonce), (0, ethereumjs_util_1.bnToUnpaddedBuffer)(this.gasPrice), (0, ethereumjs_util_1.bnToUnpaddedBuffer)(this.gasLimit), this.to !== undefined ? this.to.buf : Buffer.from([]), (0, ethereumjs_util_1.bnToUnpaddedBuffer)(this.value), this.data, this.accessList, this.v !== undefined ? (0, ethereumjs_util_1.bnToUnpaddedBuffer)(this.v) : Buffer.from([]), this.r !== undefined ? (0, ethereumjs_util_1.bnToUnpaddedBuffer)(this.r) : Buffer.from([]), this.s !== undefined ? (0, ethereumjs_util_1.bnToUnpaddedBuffer)(this.s) : Buffer.from([]), ]; } /** * Returns the serialized encoding of the EIP-2930 transaction. * * Format: `0x01 || rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList, * signatureYParity (v), signatureR (r), signatureS (s)])` * * Note that in contrast to the legacy tx serialization format this is not * valid RLP any more due to the raw tx type preceding and concatenated to * the RLP encoding of the values. */ serialize() { const base = this.raw(); return Buffer.concat([TRANSACTION_TYPE_BUFFER, ethereumjs_util_1.rlp.encode(base)]); } /** * Returns the serialized unsigned tx (hashed or raw), which can be used * to sign the transaction (e.g. for sending to a hardware wallet). * * Note: in contrast to the legacy tx the raw message format is already * serialized and doesn't need to be RLP encoded any more. * * ```javascript * const serializedMessage = tx.getMessageToSign(false) // use this for the HW wallet input * ``` * * @param hashMessage - Return hashed message if set to true (default: true) */ getMessageToSign(hashMessage = true) { const base = this.raw().slice(0, 8); const message = Buffer.concat([TRANSACTION_TYPE_BUFFER, ethereumjs_util_1.rlp.encode(base)]); if (hashMessage) { return (0, ethereumjs_util_1.keccak256)(message); } else { return message; } } /** * Computes a sha3-256 hash of the serialized tx. * * This method can only be used for signed txs (it throws otherwise). * Use {@link AccessListEIP2930Transaction.getMessageToSign} to get a tx hash for the purpose of signing. */ hash() { if (!this.isSigned()) { throw new Error('Cannot call hash method if transaction is not signed'); } if (Object.isFrozen(this)) { if (!this.cache.hash) { this.cache.hash = (0, ethereumjs_util_1.keccak256)(this.serialize()); } return this.cache.hash; } return (0, ethereumjs_util_1.keccak256)(this.serialize()); } /** * Computes a sha3-256 hash which can be used to verify the signature */ getMessageToVerifySignature() { return this.getMessageToSign(); } /** * Returns the public key of the sender */ getSenderPublicKey() { var _a; if (!this.isSigned()) { throw new Error('Cannot call this method if transaction is not signed'); } const msgHash = this.getMessageToVerifySignature(); // EIP-2: All transaction signatures whose s-value is greater than secp256k1n/2 are considered invalid. // Reasoning: https://ethereum.stackexchange.com/a/55728 if (this.common.gteHardfork('homestead') && ((_a = this.s) === null || _a === void 0 ? void 0 : _a.gt(types_1.N_DIV_2))) { throw new Error('Invalid Signature: s-values greater than secp256k1n/2 are considered invalid'); } const { yParity, r, s } = this; try { return (0, ethereumjs_util_1.ecrecover)(msgHash, yParity.addn(27), // Recover the 27 which was stripped from ecsign (0, ethereumjs_util_1.bnToUnpaddedBuffer)(r), (0, ethereumjs_util_1.bnToUnpaddedBuffer)(s)); } catch (e) { throw new Error('Invalid Signature'); } } _processSignature(v, r, s) { const opts = { common: this.common, }; return AccessListEIP2930Transaction.fromTxData({ chainId: this.chainId, nonce: this.nonce, gasPrice: this.gasPrice, gasLimit: this.gasLimit, to: this.to, value: this.value, data: this.data, accessList: this.accessList, v: new ethereumjs_util_1.BN(v - 27), r: new ethereumjs_util_1.BN(r), s: new ethereumjs_util_1.BN(s), }, opts); } /** * Returns an object with the JSON representation of the transaction */ toJSON() { const accessListJSON = util_1.AccessLists.getAccessListJSON(this.accessList); return { chainId: (0, ethereumjs_util_1.bnToHex)(this.chainId), nonce: (0, ethereumjs_util_1.bnToHex)(this.nonce), gasPrice: (0, ethereumjs_util_1.bnToHex)(this.gasPrice), gasLimit: (0, ethereumjs_util_1.bnToHex)(this.gasLimit), to: this.to !== undefined ? this.to.toString() : undefined, value: (0, ethereumjs_util_1.bnToHex)(this.value), data: '0x' + this.data.toString('hex'), accessList: accessListJSON, v: this.v !== undefined ? (0, ethereumjs_util_1.bnToHex)(this.v) : undefined, r: this.r !== undefined ? (0, ethereumjs_util_1.bnToHex)(this.r) : undefined, s: this.s !== undefined ? (0, ethereumjs_util_1.bnToHex)(this.s) : undefined, }; } } exports.default = AccessListEIP2930Transaction; //# sourceMappingURL=eip2930Transaction.js.map
import { FETCH_USER_SUCCESS, USER_INITIAL, FETCH_USER_NOT_FOUND, USER_NOT_FOUND } from 'store/actions/user'; const profileTemplate = { id: USER_INITIAL, github_login: '', github_name: '', email: '', token: '', avatarUrl: '', }; const initialState = { profiles: [], }; const userReducer = (state = initialState, action) => { switch(action.type) { case FETCH_USER_NOT_FOUND: const userNotFound = { ...action.payload.user, id: USER_NOT_FOUND, }; return { ...state, ...action.payload.user, profiles: [...state.profiles, userNotFound], }; case FETCH_USER_SUCCESS: return { ...state, profiles: [...state.profiles, action.payload.user], }; default: return state; } }; export default userReducer;
import React, { Component } from 'react'; import { NavLink } from 'react-router-dom'; import classes from './Drawer.module.css'; import Backdrop from '../../UI/Backdrop/Backdrop'; class Drawer extends Component { clickHandler = () => { this.props.onClose(); }; renderLinks = links => { return links.map((link, index) => ( <li key={index}> <NavLink onClick={this.clickHandler} to={link.to} exact={link.exact} activeClassName={classes.active} > {link.label} </NavLink> </li> )); }; render() { const { isOpen, onClose, isAuthenticated } = this.props; const cls = [classes.Drawer]; if (!isOpen) { cls.push(classes.close); } const links = [{ to: '/', label: 'All Tests', exact: true }]; if (isAuthenticated) { links.push({ to: '/quiz-creator', label: 'Create test', exact: false }); links.push({ to: '/logout', label: 'Logout', exact: false }); } else { links.push({ to: '/auth', label: 'Login/Register', exact: false }); } return ( <React.Fragment> {isOpen ? <Backdrop onClick={onClose} /> : null} <nav className={cls.join(' ')}> <ul>{this.renderLinks(links)}</ul> </nav> </React.Fragment> ); } } export default Drawer;
$(function() { consoleInit(); start(main); }); const LIFT_ABI = [{"inputs":[{"internalType":"address","name":"_boardroom","type":"address"},{"internalType":"address","name":"_share","type":"address"},{"internalType":"address","name":"_lptoken","type":"address"},{"internalType":"uint256","name":"_starttime","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOperator","type":"address"},{"indexed":true,"internalType":"address","name":"newOperator","type":"address"}],"name":"OperatorTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"RewardAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"RewardPaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Staked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Withdrawn","type":"event"},{"inputs":[],"name":"DURATION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"_balances","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"boardroom","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"burnRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"address","name":"sendTo","type":"address"}],"name":"cleanUpDust","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"daysElapsed","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"earned","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"exit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isOperator","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastTimeRewardApplicable","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastUpdateTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"lockedOutDate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lockoutPeriod","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lpt","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"reward","type":"uint256"}],"name":"notifyRewardAmount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"operator","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"periodFinish","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"rewardDistribution","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardPerToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardPerTokenStored","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"rewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_rewardDistribution","type":"address"}],"name":"setRewardDistribution","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"share","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"stake","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"stakeInBoardroom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"staker","type":"address"},{"internalType":"address","name":"from","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bool","name":"lockout","type":"bool"}],"name":"stakeLP","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"starttime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOperator_","type":"address"}],"name":"transferOperator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newBoardroom","type":"address"}],"name":"updateBoardroom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newToken","type":"address"}],"name":"updateStakingToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"userRewardPerTokenPaid","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"}] const ShortPools = [ { address : "0xc62e2C1E8e7078F66A989ebD47936B00aadF05f9", stakeTokenFunction : "alUSD", abi: [{"inputs":[{"internalType":"address","name":"_LIFT","type":"address"},{"internalType":"address","name":"_alUSD","type":"address"},{"internalType":"address","name":"_boardroom","type":"address"},{"internalType":"uint256","name":"_starttime","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOperator","type":"address"},{"indexed":true,"internalType":"address","name":"newOperator","type":"address"}],"name":"OperatorTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"RewardAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"RewardPaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Staked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Withdrawn","type":"event"},{"inputs":[],"name":"DURATION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LIFT","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"alUSD","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"boardroom","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"burnRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"address","name":"sendTo","type":"address"}],"name":"cleanUpDust","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"deposits","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"earned","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"exit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isOperator","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastTimeRewardApplicable","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastUpdateTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"reward","type":"uint256"}],"name":"notifyRewardAmount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"operator","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"periodFinish","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"rewardDistribution","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardPerToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardPerTokenStored","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"rewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_rewardDistribution","type":"address"}],"name":"setRewardDistribution","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"stake","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"stakeInBoardroom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"starttime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOperator_","type":"address"}],"name":"transferOperator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"userRewardPerTokenPaid","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"}] },{ address : "0x9551e5528f7D191Eb6ee45bCE4c455C2C238C9c2", stakeTokenFunction : "BASv2", abi: [{"inputs":[{"internalType":"address","name":"_LIFT","type":"address"},{"internalType":"address","name":"_BASv2","type":"address"},{"internalType":"address","name":"_boardroom","type":"address"},{"internalType":"uint256","name":"_starttime","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOperator","type":"address"},{"indexed":true,"internalType":"address","name":"newOperator","type":"address"}],"name":"OperatorTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"RewardAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"RewardPaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Staked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Withdrawn","type":"event"},{"inputs":[],"name":"BASv2","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DURATION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LIFT","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"boardroom","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"burnRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"address","name":"sendTo","type":"address"}],"name":"cleanUpDust","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"deposits","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"earned","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"exit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isOperator","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastTimeRewardApplicable","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastUpdateTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"reward","type":"uint256"}],"name":"notifyRewardAmount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"operator","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"periodFinish","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"rewardDistribution","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardPerToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardPerTokenStored","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"rewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_rewardDistribution","type":"address"}],"name":"setRewardDistribution","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"stake","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"stakeInBoardroom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"starttime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOperator_","type":"address"}],"name":"transferOperator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"userRewardPerTokenPaid","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"}] },{ address : "0xe325b9f54B35692cEd0952B0459133e200088096", stakeTokenFunction : "iFARM", abi: [{"inputs":[{"internalType":"address","name":"_LIFT","type":"address"},{"internalType":"address","name":"_iFARM","type":"address"},{"internalType":"address","name":"_boardroom","type":"address"},{"internalType":"uint256","name":"_starttime","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOperator","type":"address"},{"indexed":true,"internalType":"address","name":"newOperator","type":"address"}],"name":"OperatorTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"RewardAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"RewardPaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Staked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Withdrawn","type":"event"},{"inputs":[],"name":"DURATION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LIFT","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"boardroom","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"burnRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"address","name":"sendTo","type":"address"}],"name":"cleanUpDust","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"deposits","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"earned","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"exit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"iFARM","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isOperator","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastTimeRewardApplicable","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastUpdateTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"reward","type":"uint256"}],"name":"notifyRewardAmount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"operator","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"periodFinish","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"rewardDistribution","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardPerToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardPerTokenStored","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"rewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_rewardDistribution","type":"address"}],"name":"setRewardDistribution","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"stake","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"stakeInBoardroom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"starttime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOperator_","type":"address"}],"name":"transferOperator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"userRewardPerTokenPaid","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"}] },{ address : "0xe2Cf4ab503276BC693fB05eb2Da00c997E26ee68", stakeTokenFunction : "KBTC", abi: [{"inputs":[{"internalType":"address","name":"_LIFT","type":"address"},{"internalType":"address","name":"_KBTC","type":"address"},{"internalType":"address","name":"_boardroom","type":"address"},{"internalType":"uint256","name":"_starttime","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOperator","type":"address"},{"indexed":true,"internalType":"address","name":"newOperator","type":"address"}],"name":"OperatorTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"RewardAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"RewardPaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Staked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Withdrawn","type":"event"},{"inputs":[],"name":"DURATION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"KBTC","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LIFT","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"boardroom","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"burnRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"address","name":"sendTo","type":"address"}],"name":"cleanUpDust","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"deposits","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"earned","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"exit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isOperator","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastTimeRewardApplicable","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastUpdateTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"reward","type":"uint256"}],"name":"notifyRewardAmount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"operator","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"periodFinish","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"rewardDistribution","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardPerToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardPerTokenStored","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"rewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_rewardDistribution","type":"address"}],"name":"setRewardDistribution","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"stake","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"stakeInBoardroom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"starttime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOperator_","type":"address"}],"name":"transferOperator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"userRewardPerTokenPaid","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"}] },{ address : "0x570CcB67cD8511f959e8842c5F78d62CeD873DF3", stakeTokenFunction : "PICKLE", abi: [{"inputs":[{"internalType":"address","name":"_LIFT","type":"address"},{"internalType":"address","name":"_PICKLE","type":"address"},{"internalType":"address","name":"_boardroom","type":"address"},{"internalType":"uint256","name":"_starttime","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOperator","type":"address"},{"indexed":true,"internalType":"address","name":"newOperator","type":"address"}],"name":"OperatorTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"RewardAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"reward","type":"uint256"}],"name":"RewardPaid","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Staked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Withdrawn","type":"event"},{"inputs":[],"name":"DURATION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LIFT","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PICKLE","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"boardroom","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"burnRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"tokenAddress","type":"address"},{"internalType":"address","name":"sendTo","type":"address"}],"name":"cleanUpDust","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"deposits","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"earned","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"exit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"isOperator","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastTimeRewardApplicable","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lastUpdateTime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"reward","type":"uint256"}],"name":"notifyRewardAmount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"operator","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"periodFinish","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"rewardDistribution","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardPerToken","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardPerTokenStored","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"rewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_rewardDistribution","type":"address"}],"name":"setRewardDistribution","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"stake","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"stakeInBoardroom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"starttime","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newOperator_","type":"address"}],"name":"transferOperator","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"userRewardPerTokenPaid","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdraw","outputs":[],"stateMutability":"nonpayable","type":"function"}] },].map(a => { return { address: a.address, abi: a.abi, stakeTokenFunction: a.stakeTokenFunction, rewardTokenFunction: "LIFT" } }) const Pools = [ "0x4DB2fa451e1051A013A42FaD98b04C2aB81043Af", //wbtc - lfbtc "0xC3C79869ED93c88E1227a1Ca3542c9B947BA9e0c" //lfbtc - lift, ].map(a => { return { address: a, abi: LIFT_ABI, stakeTokenFunction: "lpt", rewardTokenFunction: "share" } }) async function main() { const App = await init_ethers(); _print(`Initialized ${App.YOUR_ADDRESS}`); _print("Reading smart contracts...\n"); let tokens = {}; let prices = {}; //load deathpool prices await loadSynthetixPoolInfo(App, tokens, prices, Pools[0].abi, Pools[0].address, Pools[0].rewardTokenFunction, Pools[0].stakeTokenFunction); await loadSynthetixPoolInfo(App, tokens, prices, Pools[1].abi, Pools[1].address, Pools[1].rewardTokenFunction, Pools[1].stakeTokenFunction); let p = await loadMultipleSynthetixLIFTPools(App, tokens, prices, Pools.concat(ShortPools)) _print_bold(`Total staked: $${formatMoney(p.staked_tvl)}`); if (p.totalUserStaked > 0) { _print(`You are staking a total of $${formatMoney(p.totalUserStaked)} at an APR of ${(p.totalAPR * 100).toFixed(2)}%\n`); } hideLoading(); } async function printSynthetixLIFTPool(App, info, chain="eth") { info.poolPrices.print_price(chain); _print(`${info.rewardTokenTicker} Per Week: ${info.weeklyRewards.toFixed(2)} ($${formatMoney(info.usdPerWeek)})`); const weeklyAPR = info.usdPerWeek / info.staked_tvl * 100; const dailyAPR = weeklyAPR / 7; const yearlyAPR = weeklyAPR * 52; _print(`APR: Day ${dailyAPR.toFixed(2)}% Week ${weeklyAPR.toFixed(2)}% Year ${yearlyAPR.toFixed(2)}%`); const userStakedUsd = info.userStaked * info.stakeTokenPrice; const userStakedPct = userStakedUsd / info.staked_tvl * 100; _print(`You are staking ${info.userStaked.toFixed(6)} ${info.stakeTokenTicker} ` + `$${formatMoney(userStakedUsd)} (${userStakedPct.toFixed(2)}% of the pool).`); if (info.userStaked > 0) { info.poolPrices.print_contained_price(info.userStaked); const userWeeklyRewards = userStakedPct * info.weeklyRewards / 100; const userDailyRewards = userWeeklyRewards / 7; const userYearlyRewards = userWeeklyRewards * 52; _print(`Estimated ${info.rewardTokenTicker} earnings:` + ` Day ${userDailyRewards.toFixed(2)} ($${formatMoney(userDailyRewards*info.rewardTokenPrice)})` + ` Week ${userWeeklyRewards.toFixed(2)} ($${formatMoney(userWeeklyRewards*info.rewardTokenPrice)})` + ` Year ${userYearlyRewards.toFixed(2)} ($${formatMoney(userYearlyRewards*info.rewardTokenPrice)})`); } const approveTENDAndStake = async function() { return rewardsContract_stake(info.stakeTokenAddress, info.stakingAddress, App) } const unstake = async function() { return rewardsContract_unstake(info.stakingAddress, App) } const movetoboardroom = async function() { return rewardsContract_movetobardroom(info.stakingAddress, App) } const exit = async function() { return rewardsContract_exit(info.stakingAddress, App) } const revoke = async function() { return rewardsContract_resetApprove(info.stakeTokenAddress, info.stakingAddress, App) } switch (chain) { case "eth": _print(`<a target="_blank" href="https://etherscan.io/address/${info.stakingAddress}#code">Etherscan</a>`); break; } _print_link(`Unstake ${info.userStaked.toFixed(6)} ${info.stakeTokenTicker}`, unstake) _print_link(`Move to Boardroom ${info.earned.toFixed(6)} ${info.rewardTokenTicker} ($${formatMoney(info.earned*info.rewardTokenPrice)})`, movetoboardroom) if (info.stakeTokenTicker != "ETH") { _print_link(`Revoke (set approval to 0)`, revoke) } _print_link(`Exit`, exit) _print(""); return { staked_tvl: info.poolPrices.staked_tvl, userStaked : userStakedUsd, apr : yearlyAPR } } async function loadMultipleSynthetixLIFTPools(App, tokens, prices, pools) { let totalStaked = 0, totalUserStaked = 0, individualAPRs = []; const infos = await Promise.all(pools.map(p => loadSynthetixPoolInfo(App, tokens, prices, p.abi, p.address, p.rewardTokenFunction, p.stakeTokenFunction))); for (const i of infos) { let p = await printSynthetixLIFTPool(App, i); totalStaked += p.staked_tvl || 0; totalUserStaked += p.userStaked || 0; if (p.userStaked > 0) { individualAPRs.push(p.userStaked * p.apr / 100); } } let totalAPR = totalUserStaked == 0 ? 0 : individualAPRs.reduce((x,y)=>x+y, 0) / totalUserStaked; return { staked_tvl : totalStaked, totalUserStaked, totalAPR }; }
import React from 'react'; import { Box, Button, Heading, Paragraph } from 'grommet'; import RoutedAnchor from '../components/RoutedAnchor'; import Page from '../components/Page'; import { ComponentDoc, Properties, Property, PropertyValue, Description, Example, ThemeDoc, PropOptions, } from '../components/Doc'; import Item from './Components/Item'; import { GenericA11yTitle, GenericAlignSelf, GenericAs, GenericBool, GenericGridArea, GenericMargin, GenericBoolFalse, GenericBoolTrue, SizesXsmallXlarge, GenericFill, } from '../utils/genericPropExamples'; import { GenericExtend, GenericColor, GlobalHoverColor, GenericOpacity, GenericWeight, } from '../utils/genericThemeExamples'; import { FocusStyle, DisabledStyle } from '../utils/themeDocUtils'; const ButtonPage = () => ( <Page> <ComponentDoc name="Button" availableAt={[ { url: 'https://storybook.grommet.io/?selectedKind=Controls-Button&full=0&stories=1&panelRight=0', badge: 'https://cdn-images-1.medium.com/fit/c/120/120/1*TD1P0HtIH9zF0UEH28zYtw.png', label: 'Storybook', }, { url: 'https://codesandbox.io/s/github/grommet/grommet-sandbox?initialpath=/button&module=%2Fsrc%2FButton.js', badge: 'https://codesandbox.io/static/img/play-codesandbox.svg', label: 'CodeSandbox', }, { url: 'https://github.com/grommet/grommet/tree/master/src/js/components/Button', label: 'Github', }, ]} intrinsicElement="button" code={`<Button primary label="label" />`} > <Box> <Paragraph size="large"> A grommet Button is used for anything that looks like a button on the screen. If an <code>href</code> is provided, it will be rendered in the DOM with <code>&lt;a/&gt;</code>. An{' '} <RoutedAnchor path="/anchor" label="Anchor" /> component should be used for inline anchors within textual contexts. </Paragraph> <Paragraph size="large"> In May 2020, we enhanced Button to have three kinds, outlined below. In order to maintain backwards compatibility, this approach is only available when the theme being used defines{' '} <code>button.default</code>. </Paragraph> <Heading level={2}>default</Heading> <Paragraph size="large"> The majority of Buttons on the page. Their affordance is primarily driven by their context, in a <RoutedAnchor path="/nav" label="Nav" />{' '} in a <RoutedAnchor path="/header" label="Header" /> or{' '} <RoutedAnchor path="/sidebar" label="Sidebar" />, the corner of a tile or card, etc. </Paragraph> <Heading level={2}>primary</Heading> <Paragraph size="large"> The primary call to action. There should typically be at most one primary Button on the screen. In a{' '} <RoutedAnchor path="/form" label="Form" /> context, it signifies the action bound to the enter key that will submit the form. </Paragraph> <Heading level={2}>secondary</Heading> <Paragraph size="large"> When there isn’t enough context to indicate its affordance, or when it should call extra attention to itself but isn’t the primary call to action, use a secondary Button. Secondary buttons are only available when the underlying theme being used defines{' '} <code>button.default</code>. </Paragraph> </Box> <Properties> <Property name="a11yTitle"> <Description> Custom label to be used by screen readers. When provided, an aria-label will be added to the element. </Description> <GenericA11yTitle /> </Property> <Property name="alignSelf"> <Description> How to align along the cross axis when contained in a Box or along the column axis when contained in a Grid. </Description> <GenericAlignSelf /> </Property> <Property name="gridArea"> <Description> The name of the area to place this inside a parent Grid. </Description> <GenericGridArea /> </Property> <Property name="margin"> <Description>The amount of margin around the component.</Description> <GenericMargin /> </Property> <Property name="children"> <Description> Function that can be called to render the visual representation. When Button has children, it is styled as a plain button. </Description> <PropertyValue type="function"> <Description> 'disabled', 'hover', and 'focus' can be passed as an argument that would then return a react element. </Description> <Example>{`({ disabled, hover, focus }) => {<Box>...</Box>}`}</Example> </PropertyValue> <PropertyValue type="object" /> <PropertyValue type="node"> <Example>{`<Box>...</Box>`}</Example> </PropertyValue> </Property> <Property name="active"> <Description>Whether the button is active.</Description> <GenericBoolFalse /> </Property> <Property name="as"> <Description> The DOM tag or react component to use for the element. </Description> <GenericAs /> </Property> <Property name="badge"> <Description> An indicator to show on the top-right of the Button. For accessibility, supplement the badge by adding an a11yTitle to the Button which provides a useful message to screen readers. For example, "2 unread notifications". </Description> <PropertyValue type="boolean"> <Description> When badge is a boolean, the badge will be a circle with background color 'brand'. </Description> <Example>true</Example> <Example>false</Example> </PropertyValue> <PropertyValue type="element"> <Example>{`<Box>...</Box>`}</Example> </PropertyValue> <PropertyValue type="number"> <Description> When badge is a number, that number will appear inside the badge. </Description> <Example>10</Example> </PropertyValue> <PropertyValue type="object"> <Description> When badge is an object, background refers to the background color of the badge, value refers to either the numeric value that appears within the badge or a boolean if background has been defined on the object but no numeric content is desired, and max refers to the max value that can appear inside the badge. For example, if value is 10 and max is 9, the content in the badge will be displayed as 9+. </Description> <Example> {` { background: { color: "...", dark: "...", image: "string", position: "string", opacity: "...", repeat: "...", size: "...", light: "string" } max: number, value: "..." } `} </Example> <PropOptions prop="color"> <Example>"string"</Example> <Example>{`{ dark: "string", light: "string" }`}</Example> </PropOptions> <PropOptions prop="dark"> <Example>boolean</Example> <Example>"string"</Example> </PropOptions> <PropOptions prop="opacity"> <Example>boolean</Example> <Example>number</Example> <Example>"weak"</Example> <Example>"medium"</Example> <Example>"strong"</Example> </PropOptions> <PropOptions prop="repeat"> <Example>"no-repeat"</Example> <Example>"repeat"</Example> <Example>"string"</Example> </PropOptions> <PropOptions prop="size"> <Example>"cover"</Example> <Example>"contain"</Example> <Example>"string"</Example> </PropOptions> <PropOptions prop="value"> <Example>boolean</Example> <Example>number</Example> </PropOptions> </PropertyValue> </Property> <Property name="color"> <Description> Fill color for primary, label color for plain, border color otherwise. If button.default is defined in the theme, the color prop will fill the background color for primary and secondary button types. Color prop will change the text color for default button. </Description> <PropertyValue type="string"> <Description>A hex, name, or rgb value.</Description> <Example>"control"</Example> </PropertyValue> <PropertyValue type="object"> <Description> An object with a color for dark and light modes. </Description> <Example> {`{ dark: "string", light: "string" }`}</Example> </PropertyValue> </Property> <Property name="disabled"> <Description>Whether the button is disabled.</Description> <GenericBoolFalse /> </Property> <Property name="fill"> <Description> Whether the button expands to fill all of the available width and/or height. </Description> <GenericFill /> </Property> <Property name="focusIndicator"> <Description> Whether when 'plain' it should receive a focus outline. </Description> <GenericBoolTrue /> </Property> <Property name="gap"> <Description> The amount of spacing between icon and label in the button. </Description> <PropertyValue type="string"> <Description> T-shirt sizing based off the theme or a specific size in px, em, etc. </Description> <Example>"xxsmall"</Example> <SizesXsmallXlarge /> <Example>"string"</Example> </PropertyValue> </Property> <Property name="hoverIndicator"> <Description> The hover indicator to apply when the user is mousing over the button. This prop is meant to be used only with plain Buttons. </Description> <GenericBoolFalse /> <PropertyValue type="string"> <Example>"background"</Example> </PropertyValue> <PropertyValue type="object"> <Description> An object defining the background or the background and elevation. </Description> <Example> {` { color: "...", dark: "...", image: "string", position: "string", opacity: "...", repeat: "...", size: "...", light: "string" } `} </Example> <Example> {` { background: { color: "...", dark: "...", image: "string", position: "string", opacity: "...", repeat: "...", size: "...", light: "string" }, elevation: "..." } `} </Example> <PropOptions prop="color"> <Example>"string"</Example> <Example>{`{ dark: "string", light: "string" }`}</Example> </PropOptions> <PropOptions prop="dark"> <Example>boolean</Example> <Example>"string"</Example> </PropOptions> <PropOptions prop="opacity"> <Example>boolean</Example> <Example>number</Example> <Example>"weak"</Example> <Example>"medium"</Example> <Example>"strong"</Example> </PropOptions> <PropOptions prop="repeat"> <Example>"no-repeat"</Example> <Example>"repeat"</Example> <Example>"string"</Example> </PropOptions> <PropOptions prop="size"> <Example>"cover"</Example> <Example>"contain"</Example> <Example>"string"</Example> </PropOptions> <PropOptions prop="elevation"> <Example>"none"</Example> <SizesXsmallXlarge /> <Example>"string"</Example> </PropOptions> </PropertyValue> </Property> <Property name="href"> <Description> If specified, the button will behave like an anchor tag. </Description> <PropertyValue type="string"> <Example>"//my.com/path"</Example> </PropertyValue> </Property> <Property name="icon"> <Description> Icon element to place in the button. For accessibility with screen readers, if using just an icon (no label), add an a11yTitle to the Button that describes the icon. </Description> <PropertyValue type="element"> <Example>{`<Add />`}</Example> </PropertyValue> </Property> <Property name="justify"> <Description> How to align the contents within the button. </Description> <PropertyValue type="string"> <Example>"around"</Example> <Example defaultValue>"between"</Example> <Example>"center"</Example> <Example>"end"</Example> <Example>"evenly"</Example> <Example>"start"</Example> <Example>"stretch"</Example> </PropertyValue> </Property> <Property name="label"> <Description>Label text to place in the button.</Description> <PropertyValue type="string"> <Example>"label"</Example> </PropertyValue> <PropertyValue type="node"> <Example>{`<Box>...</Box>`}</Example> </PropertyValue> </Property> <Property name="onClick"> <Description> Click handler. Not setting this property and not specifying a href causes the Button to be disabled. </Description> <PropertyValue type="function"> <Example>{`() => {}`}</Example> </PropertyValue> </Property> <Property name="plain"> <Description> Whether this is a plain button with no border or pad. Non plain button will show both pad and border. When using the kind button (i.e. button.default on the theme), the usage of plain is deprecated. </Description> <GenericBoolFalse /> </Property> <Property name="primary"> <Description> Whether this is a primary button. There should be at most one per page or screen. </Description> <GenericBoolFalse /> </Property> <Property name="reverse"> <Description> Whether an icon and label should be reversed so that the icon is at the end of the anchor. </Description> <GenericBoolFalse /> </Property> <Property name="secondary"> <Description>Whether this is a secondary button.</Description> <GenericBool /> </Property> <Property name="size"> <Description> The possible sizes of Button, that impacts the overall Button padding, border radius, text size and line height. 'size' will not impact any icon related sizing. </Description> <PropertyValue type="string"> <Example>"small"</Example> <Example>"medium"</Example> <Example>"large"</Example> </PropertyValue> </Property> <Property name="target"> <Description> Specifies where to display the URL defined in the href property. </Description> <PropertyValue type="string"> <Example>"_self"</Example> <Example>"_blank"</Example> <Example>"_parent"</Example> <Example>"_top"</Example> <Example>"string"</Example> </PropertyValue> </Property> <Property name="tip"> <Description> tooltip or a hint when hovering over the button. </Description> <PropertyValue type="string"> <Description> If the value is a string and no a11yTitle value is provided, tip value will be used for the a11yTitle default value. </Description> <Example>"example tooltip"</Example> </PropertyValue> <PropertyValue type="object"> <Example> {` { content: node | "string", dropProps: {...} plain: boolean } `} </Example> </PropertyValue> </Property> <Property name="type"> <Description> The type of button. Set the type to submit for the default button on forms. </Description> <PropertyValue type="string"> <Example defaultValue>"button"</Example> <Example>"reset"</Example> <Example>"submit"</Example> </PropertyValue> </Property> </Properties> <ThemeDoc> <Property name="global.active.background.color"> <Description> The background color when using active prop. </Description> <PropertyValue type="string"> <Description>A hex, name, or rgb value.</Description> <Example defaultValue>"active"</Example> </PropertyValue> <PropertyValue type="object"> <Description> An object with a color for dark and light modes. </Description> <Example>{`{ dark: "string", light: "string" }`}</Example> </PropertyValue> </Property> <Property name="global.active.background.opacity"> <Description> The value used for active button background opacity. </Description> <PropertyValue type="string"> <Example defaultValue>"medium"</Example> </PropertyValue> <PropertyValue type="number"> <Example>0.5</Example> </PropertyValue> </Property> <Property name="global.active.color"> <Description>The text color when using active prop.</Description> <PropertyValue type="string"> <Description>A hex, name, or rgb value.</Description> <Example>"black"</Example> </PropertyValue> <PropertyValue type="object"> <Description> An object with a color for dark and light modes. </Description> <Example defaultValue> {`{ dark: "white", light: "black" }`} </Example> </PropertyValue> </Property> <Property name="global.hover.background"> <Description>The background style when hovering.</Description> <PropertyValue type="string"> <Description>A hex, name, or rgb value.</Description> <Example>"active"</Example> </PropertyValue> <PropertyValue type="object"> <Description> An object with a color for dark and light modes. </Description> <Example defaultValue> {`{ color: "active", opacity: "medium" }`} </Example> </PropertyValue> </Property> <Property name="global.hover.color"> <Description>The text color when hovering.</Description> <GlobalHoverColor /> </Property> <Property name="global.edgeSize.small"> <Description>The padding around an icon-only button.</Description> <PropertyValue type="string"> <Example defaultValue>"12px"</Example> </PropertyValue> </Property> <Property name="global.colors.control"> <Description>The color of the border.</Description> <PropertyValue type="string"> <Description>A hex, name, or rgb value.</Description> <Example>"accent-1"</Example> </PropertyValue> <PropertyValue type="object"> <Description> An object with a color for dark and light modes. </Description> <Example defaultValue> {`{ dark: "accent-1", light: "brand" }`} </Example> </PropertyValue> </Property> <Property name="global.colors.brand"> <Description>The light version of the border.</Description> <PropertyValue type="string"> <Example defaultValue>"#7D4CDB"</Example> </PropertyValue> </Property> <Property name="global.colors.text"> <Description>The color of the text label.</Description> <PropertyValue type="string"> <Description>A hex, name, or rgb value.</Description> <Example>"black"</Example> </PropertyValue> <PropertyValue type="object"> <Description> An object with a color for dark and light modes. </Description> <Example defaultValue> {`{ dark: '#f8f8f8', light: '#444444' }`} </Example> </PropertyValue> </Property> <Property name="text.medium.size"> <Description>The font size of the text label.</Description> <PropertyValue type="string"> <Example defaultValue>"18px"</Example> </PropertyValue> </Property> <Property name="text.medium.height"> <Description>The line height of the text label.</Description> <PropertyValue type="string"> <Example defaultValue>"24px"</Example> </PropertyValue> </Property> <Property name="button.active.background.color"> <Description>Background color when the button is active.</Description> <GenericColor /> </Property> <Property name="button.active.border.color"> <Description>The border color when the button is active.</Description> <GenericColor /> </Property> <Property name="button.active.color"> <Description>Label color when the button is active.</Description> <GenericColor /> </Property> <Property name="button.active.extend"> <Description>Any additional style for an active Button.</Description> <GenericExtend /> </Property> <Property name="button.active.default"> <Description> Adjustments to the default Button style when the Button is active. </Description> <PropertyValue type="object"> <Example>{`{}`}</Example> </PropertyValue> </Property> <Property name="button.active.primary"> <Description> Adjustments to the primary Button style when the Button is active. Only relevant for themes that have defined a value for button.default. </Description> <PropertyValue type="object"> <Example>{`{}`}</Example> </PropertyValue> </Property> <Property name="button.active.secondary"> <Description> Adjustments to the secondary Button style when the Button is active. Only relevant for themes that have defined a value for button.default. </Description> <PropertyValue type="object"> <Example>{`{}`}</Example> </PropertyValue> </Property> <Property name="button.badge.container.background"> <Description>The background of the badge.</Description> <PropertyValue type="string"> <Example defaultValue>"brand"</Example> </PropertyValue> <PropertyValue type="object"> <Example>{`{ dark: "string", light: "string" }`}</Example> <Example> {` { color: { dark: "string", light: "string" } | "string", dark: bool, image: "string", position: "string", opacity: bool | "string", repeat: "no-repeat" | "repeat", size: "cover" | "contain" | "string" } `} </Example> </PropertyValue> </Property> <Property name="button.badge.container.extend"> <Description>Any additional styles for the badge.</Description> <GenericExtend /> </Property> <Property name="button.badge.container.pad"> <Description> When badge has a value, the amount of pad to apply. </Description> <PropertyValue type="string"> <Description> T-shirt sizing based off the theme or a specific size in px, em, etc. </Description> <Example>"small"</Example> </PropertyValue> <PropertyValue type="object"> <Description> An object can be specified to distinguish horizontal padding, vertical padding, and padding on a particular side. </Description> <Example> {` { vertical: "...", horizontal: "...", top: "...", bottom: "...", left: "...", right: "..." } `} </Example> </PropertyValue> </Property> <Property name="button.badge.size.medium"> <Description> The minimum width and height of the badge when the badge contains a value. If badge is a boolean, the default width and height will be one half of this value. </Description> <PropertyValue type="string"> <Example defaultValue>"24px"</Example> </PropertyValue> </Property> <Property name="button.badge.text.size.medium"> <Description> The size of the text that is mapped according to 'button.badge.size.medium'. </Description> <PropertyValue type="string"> <Example defaultValue>"14px"</Example> </PropertyValue> </Property> <Property name="button.border.color"> <Description>The color of the border.</Description> <GenericColor /> </Property> <Property name="button.border.radius"> <Description>The corner radius.</Description> <PropertyValue type="string"> <Example defaultValue>"18px"</Example> </PropertyValue> </Property> <Property name="button.border.width"> <Description>The border width.</Description> <PropertyValue type="string"> <Example defaultValue>"2px"</Example> </PropertyValue> </Property> <Property name="button.color"> <Description>The color of the text label.</Description> <GenericColor /> </Property> <Property name="button.default.background.color"> <Description> The color of the background for default buttons. </Description> <GenericColor /> </Property> <Property name="button.default.background.opacity"> <Description> The value used for default button background opacity. </Description> <GenericOpacity /> </Property> <Property name="button.default.border.color"> <Description> The color of the border for default buttons. </Description> <GenericColor /> </Property> <Property name="button.default.color"> <Description>The color of the label for default buttons.</Description> <GenericColor /> </Property> <Property name="button.default.font.weight"> <Description> The weight of the text label for default buttons. </Description> <GenericWeight /> </Property> <Property name="button.default.extend"> <Description>Any additional style for a default button.</Description> <GenericExtend /> </Property> <Property name="button.default.padding.horizontal"> <Description> The horizontal padding for a default button. </Description> <PropertyValue type="string"> <Example defaultValue>"22px"</Example> </PropertyValue> </Property> <Property name="button.default.padding.vertical"> <Description>The vertical padding for a default button.</Description> <PropertyValue type="string"> <Example defaultValue>"4px"</Example> </PropertyValue> </Property> <Property name="button.disabled.color"> <Description>Label color when the button is disabled.</Description> <GenericColor /> </Property> <Property name="button.disabled.border.color"> <Description> The border color when the button is disabled. </Description> <GenericColor /> </Property> <Property name="button.disabled.background.color"> <Description> Background color when the button is disabled. </Description> <GenericColor /> </Property> <Property name="button.disabled.opacity"> <Description>The opacity when the button is disabled.</Description> <PropertyValue type="number"> <Example defaultValue>0.3</Example> </PropertyValue> </Property> <Property name="button.disabled.extend"> <Description>Any additional style for a disabled Button.</Description> <GenericExtend /> </Property> <Property name="button.disabled.default"> <Description> Adjustments to the default Button style when the Button is disabled. </Description> <PropertyValue type="object"> <Example>{`{}`}</Example> </PropertyValue> </Property> <Property name="button.disabled.primary"> <Description> Adjustments to the primary Button style when the Button is disabled. Only relevant for themes that have defined a value for button.default. </Description> <PropertyValue type="object"> <Example>{`{}`}</Example> </PropertyValue> </Property> <Property name="button.disabled.secondary"> <Description> Adjustments to the secondary Button style when the Button is disabled. Only relevant for themes that have defined a value for button.default. </Description> <PropertyValue type="object"> <Example>{`{}`}</Example> </PropertyValue> </Property> <Property name="button.hover.color"> <Description>Label color when the button is hovered.</Description> <GenericColor /> </Property> <Property name="button.hover.border.color"> <Description> The border color when the button is hovered. </Description> <GenericColor /> </Property> <Property name="button.hover.background.color"> <Description> Background color when the button is hovered. </Description> <GenericColor /> </Property> <Property name="button.hover.extend"> <Description>Any additional style for a hovered Button.</Description> <GenericExtend /> </Property> <Property name="button.hover.default"> <Description> Adjustments to the default Button style when the Button is hovered. </Description> <PropertyValue type="object"> <Example>{`{}`}</Example> </PropertyValue> </Property> <Property name="button.hover.primary"> <Description> Adjustments to the primary Button style when the Button is hovered. Only relevant for themes that have defined a value for button.default. </Description> <PropertyValue type="object"> <Example>{`{}`}</Example> </PropertyValue> </Property> <Property name="button.hover.secondary"> <Description> Adjustments to the secondary Button style when the Button is hovered. Only relevant for themes that have defined a value for button.default. </Description> <PropertyValue type="object"> <Example>{`{}`}</Example> </PropertyValue> </Property> <Property name="button.padding.horizontal"> <Description>The horizontal padding.</Description> <PropertyValue type="string"> <Example defaultValue>"22px"</Example> </PropertyValue> </Property> <Property name="button.padding.vertical"> <Description>The vertical padding.</Description> <PropertyValue type="string"> <Example defaultValue>"4px"</Example> </PropertyValue> </Property> <Property name="button.primary.background.color"> <Description> The color of the background for primary buttons. Only relevant for themes that have defined a value for button.default. </Description> <GenericColor /> </Property> <Property name="button.primary.background.opacity"> <Description> The value used for primary button background opacity. Only relevant for themes that have defined a value for button.default. </Description> <GenericOpacity /> </Property> <Property name="button.primary.border.color"> <Description> The color of the border for primary buttons. Only relevant for themes that have defined a value for button.default. </Description> <GenericColor /> </Property> <Property name="button.primary.color"> <Description>The color of the label for primary buttons.</Description> <GenericColor /> </Property> <Property name="button.primary.font.weight"> <Description> The weight of the text label for primary buttons. </Description> <GenericWeight /> </Property> <Property name="button.primary.padding.horizontal"> <Description> The horizontal padding for a primary button. </Description> <PropertyValue type="string"> <Example defaultValue>"22px"</Example> </PropertyValue> </Property> <Property name="button.primary.padding.vertical"> <Description>The vertical padding for a primary button.</Description> <PropertyValue type="string"> <Example defaultValue>"4px"</Example> </PropertyValue> </Property> <Property name="button.primary.extend"> <Description>Any additional style for a primary button.</Description> <GenericExtend /> </Property> <Property name="button.secondary.background.color"> <Description> The color of the background for secondary buttons. Only relevant for themes that have defined a value for button.default. </Description> <GenericColor /> </Property> <Property name="button.secondary.background.opacity"> <Description> The value used for secondary button background opacity. Only relevant for themes that have defined a value for button.default. </Description> <GenericOpacity /> </Property> <Property name="button.secondary.border.color"> <Description> The color of the border for secondary buttons. Only relevant for themes that have defined a value for button.default. </Description> <GenericColor /> </Property> <Property name="button.secondary.color"> <Description> The color of the label for secondary buttons. Only relevant for themes that have defined a value for button.default. </Description> <GenericColor /> </Property> <Property name="button.secondary.font.weight"> <Description> The weight of the text label for secondary buttons. Only relevant for themes that have defined a value for button.default. </Description> <GenericWeight /> </Property> <Property name="button.secondary.padding.horizontal"> <Description> The horizontal padding for a secondary button. Only relevant for themes that have defined a value for button.default. </Description> <PropertyValue type="string"> <Example defaultValue>"22px"</Example> </PropertyValue> </Property> <Property name="button.secondary.padding.vertical"> <Description> The vertical padding for a secondary button. Only relevant for themes that have defined a value for button.default. </Description> <PropertyValue type="string"> <Example defaultValue>"4px"</Example> </PropertyValue> </Property> <Property name="button.secondary.extend"> <Description> Any additional style for a secondary button. Only relevant for themes that have defined a value for button.default. </Description> <GenericExtend /> </Property> <Property name="button.size.small.border.radius"> <Description>The border corner radius.</Description> <PropertyValue type="string"> <Example defaultValue>"18px"</Example> </PropertyValue> </Property> <Property name="button.size.small.pad.horizontal"> <Description>The pad</Description> <PropertyValue type="string"> <Example defaultValue>"20px"</Example> </PropertyValue> </Property> <Property name="button.size.small.pad.vertical"> <Description>The pad</Description> <PropertyValue type="string"> <Example defaultValue>"4px"</Example> </PropertyValue> </Property> <Property name="button.size.medium.border.radius"> <Description>The border corner radius.</Description> <PropertyValue type="string"> <Example defaultValue>"18px"</Example> </PropertyValue> </Property> <Property name="button.size.medium.pad.horizontal"> <Description>The pad</Description> <PropertyValue type="string"> <Example defaultValue>"22px"</Example> </PropertyValue> </Property> <Property name="button.size.medium.pad.vertical"> <Description>The pad</Description> <PropertyValue type="string"> <Example defaultValue>"4px"</Example> </PropertyValue> </Property> <Property name="button.size.large.border.radius"> <Description>The border corner radius.</Description> <PropertyValue type="string"> <Example defaultValue>"24px"</Example> </PropertyValue> </Property> <Property name="button.size.large.pad.horizontal"> <Description>The pad</Description> <PropertyValue type="string"> <Example defaultValue>"32px"</Example> </PropertyValue> </Property> <Property name="button.size.large.pad.vertical"> <Description>The pad</Description> <PropertyValue type="string"> <Example defaultValue>"8px"</Example> </PropertyValue> </Property> <Property name="button.transition.duration"> <Description> The length of time it will take for the element to transition between two states. </Description> <PropertyValue type="number"> <Example defaultValue>0.1</Example> </PropertyValue> </Property> <Property name="button.transition.properties"> <Description> The CSS properties you want to add the transition to. </Description> <PropertyValue type="string"> <Example>"color"</Example> <Example>"background-color"</Example> <Example>"border-color"</Example> <Example>"box-shadow"</Example> </PropertyValue> </Property> <Property name="button.transition.timing"> <Description> Describes how a transition will progress over one cycle of its duration and allowing it to change speed during its course. </Description> <PropertyValue type="string"> <Example defaultValue>ease-in-out</Example> </PropertyValue> </Property> <Property name="button.extend"> <Description>Any additional style for the Button.</Description> <GenericExtend /> </Property> <Property name="tip.content"> <Description> When using tip prop, any valid Box property for the Tip container. </Description> <PropertyValue type="object"> <Example> {` { background: "background-contrast", elevation: "small", margin: "xsmall", pad: { vertical: "xsmall", horizontal: "small" }, round: "small" } `} </Example> </PropertyValue> </Property> <Property name="tip.drop"> <Description> When using tip prop, any valid Drop property for the Tooltip. </Description> <PropertyValue type="object"> <Example> {` { align: { top: "bottom" }, background: "none", elevation: "none", margin: "none" } `} </Example> </PropertyValue> </Property> <FocusStyle /> <DisabledStyle /> </ThemeDoc> </ComponentDoc> </Page> ); export default ButtonPage; export const ButtonItem = ({ name, path }) => ( <Item name={name} path={path} center> <Button label="i'm a button" primary onClick={() => {}} /> </Item> ); ButtonItem.propTypes = Item.propTypes;
import Typography from 'typography' import Wordpress2016 from 'typography-theme-wordpress-2016' import './global.css' import './prismjs.css' Wordpress2016.overrideThemeStyles = () => ({ 'body': { color: 'var(--c-text-primary)', }, 'a': { color: 'var(--text-link-color)', }, 'a.gatsby-resp-image-link': { boxShadow: 'none', }, 'h4': { textTransform: 'none', letterSpacing: 0, }, 'blockquote': { fontSize: '1rem', color: 'var(--quote-color)', borderLeftColor: 'var(--quote-border)', }, }) delete Wordpress2016.googleFonts const typography = new Typography(Wordpress2016) // Hot reload typography in development. if (process.env.NODE_ENV !== 'production') { typography.injectStyles() } export const rhythm = typography.rhythm export const scale = typography.scale export default typography
import Alt from '../utils/Alt'; import CrudActions from '../actions/CrudActions'; class CrudStore { constructor() { this.resourceName = ''; this.status = 'fetchings'; // ok | fetching | getting | deleting | saving this.stuff = {}; this.one = null; this.list = []; this.pagination = { showTotal: total => `总共 ${total} 条`, pageSize: 20, showQuickJumper: true, }; this.params = { page: 1, key: '', }; this.saveModal = { title: '', visible: false, initialValues: {}, }; this.rowSelectionSelect = {}; this.rowSelectionSelectAll = {}; this.selectedRowKeys = []; this.selectedRows = []; this.bindListeners({ handleSetResourceName: CrudActions.SET_RESOURCE_NAME, handleUpdateStuff: CrudActions.UPDATE_STUFF, handleUpdateData: CrudActions.UPDATE_DATA, handleUpdateOne: CrudActions.UPDATE_ONE, handleFetch: CrudActions.FETCH, handleFetchOne: CrudActions.FETCH_ONE, handleFetchStuff: CrudActions.FETCH_STUFF, handleSave: CrudActions.SAVE, handleDelete: CrudActions.DELETE, handleShowSaveForm: CrudActions.SHOW_SAVE_FORM, handleHideSaveForm: CrudActions.HIDE_SAVE_FORM, handleRowSelectionChange: CrudActions.ROW_SELECTION_CHANGE, handleRowSelectionSelect: CrudActions.ROW_SELECTION_SELECT, handleRowSelectionSelectAll: CrudActions.ROW_SELECTION_SELECT_ALL, }); } handleSetResourceName(resourceName) { this.list = []; this.one = null; this.resourceName = resourceName; } handleUpdateData({ list, pagination, params }) { this.list = list; this.pagination = pagination; this.params = params; this.rowSelectionSelect = {}; this.rowSelectionSelectAll = {}; this.selectedRowKeys = []; this.selectedRows = []; this.status = 'ok'; } handleUpdateOne(data) { this.one = data; this.status = 'ok'; } handleUpdateStuff(stuff) { this.stuff = stuff; } handleFetch(callback) { this.status = 'fetching'; this.list = []; callback(this); } handleFetchOne(callback) { this.status = 'getting'; this.one = null; callback(this); } handleFetchStuff(callback) { callback(this); } handleSave(callback) { this.status = 'saving'; callback(this); } handleDelete(callback) { this.status = 'deleting'; callback(this); } handleRowSelectionChange({ selectedRowKeys, selectedRows }) { this.selectedRowKeys = selectedRowKeys; this.selectedRows = selectedRows; } handleRowSelectionSelect(params) { this.rowSelectionSelect = params; } handleRowSelectionSelectAll(params) { this.rowSelectionSelectAll = params; } handleShowSaveForm({ title, initialValues }) { this.saveModal.title = title, this.saveModal.initialValues = initialValues; this.saveModal.visible = true; } handleHideSaveForm() { this.saveModal.initialValues = {}; this.saveModal.visible = false; } } export default Alt.createStore(CrudStore, 'CrudStore');
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc); switch (arguments.length) { case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target); case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0); case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc); } }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; import { Injectable } from 'angular2/src/core/di'; /** * Specifies app root url for the application. * * Used by the {@link Compiler} when resolving HTML and CSS template URLs. * * This interface can be overridden by the application developer to create custom behavior. * * See {@link Compiler} */ export let AppRootUrl = class { constructor(value) { this.value = value; } }; AppRootUrl = __decorate([ Injectable(), __metadata('design:paramtypes', [String]) ], AppRootUrl); //# sourceMappingURL=app_root_url.js.map
import React from "react"; // nodejs library to set properties for components import PropTypes from "prop-types"; // @material-ui/core components import { makeStyles } from "@material-ui/core/styles"; import Grid from "@material-ui/core/Grid"; const styles = { grid: { position: "relative", width: "100%", minHeight: "1px", paddingRight: "0px", paddingLeft: "0px", flexBasis: "auto" } }; const useStyles = makeStyles(styles); export default function GridItem(props) { const classes = useStyles(); const { children, className, ...rest } = props; return ( <Grid item {...rest} className={classes.grid + " " + className}> {children} </Grid> ); } GridItem.defaultProps = { className: "" }; GridItem.propTypes = { children: PropTypes.node, className: PropTypes.string };
import NextAuth from "next-auth" import Providers from "next-auth/providers" // import CredentialsProvider from "next-auth/providers" const axios = require('axios'); // For more information on each option (and a full list of options) go to // https://next-auth.js.org/configuration/options export default NextAuth({ // https://next-auth.js.org/configuration/providers providers: [ Providers.Credentials({ name: 'user name and password', credentials: { email: { label: "Username", type: "text",value:"admin@admin.com", placeholder: "Username" }, password: { label: "Password", type: "password", value:'designer', placeholder : "Password" }, }, async authorize(credentials, req) { // You need to provide your own logic here that takes the credentials // submitted and returns either a object representing a user or value // that is false/null if the credentials are invalid. // e.g. return { id: 1, name: 'J Smith', email: 'jsmith@example.com' } // You can also use the `req` object to obtain additional parameters // (i.e., the request IP address) // const res = await fetch(process.env.BLUFZER_URL, { // method: 'POST', // body: {...credentials}, // // body: JSON.stringify(credentials), // headers: { "Content-Type": "application/x-www-form-urlencoded", 'x-api-key': process.env.BLUFZER_X_API_KEY } // }) const response = await axios.post(process.env.BLUFZER_URL, { email: credentials.email, password: credentials.password }) // .then(function (response) { // }) // .catch(function (error) { // console.log(error); // }); console.log("I am in sign in"); var resp = response.data.response; console.log(resp.success); if (resp.success && resp.token) { const user = { name : 'Yogendra Pokhrel', email: 'yogen@gmail.com', token: resp.token } console.log(user); return resp.token }else{ return null } // const response = await res.json() // console.log(response); // const response = {}; // If no error and we have user data, return it // Return null if user data could not be retrieved // return null } }), // Providers.Email({ // server: process.env.EMAIL_SERVER, // from: process.env.EMAIL_FROM, // }), // Temporarily removing the Apple provider from the demo site as the // callback URL for it needs updating due to Vercel changing domains /* Providers.Apple({ clientId: process.env.APPLE_ID, clientSecret: { appleId: process.env.APPLE_ID, teamId: process.env.APPLE_TEAM_ID, privateKey: process.env.APPLE_PRIVATE_KEY, keyId: process.env.APPLE_KEY_ID, }, }), */ Providers.Facebook({ clientId: process.env.FACEBOOK_ID, clientSecret: process.env.FACEBOOK_SECRET, }), Providers.GitHub({ clientId: process.env.GITHUB_ID, clientSecret: process.env.GITHUB_SECRET, // https://docs.github.com/en/developers/apps/building-oauth-apps/scopes-for-oauth-apps scope: "read:user" }), Providers.Google({ clientId: process.env.GOOGLE_ID, clientSecret: process.env.GOOGLE_SECRET, }), Providers.Twitter({ clientId: process.env.TWITTER_ID, clientSecret: process.env.TWITTER_SECRET, }), // Providers.Auth0({ // clientId: process.env.AUTH0_ID, // clientSecret: process.env.AUTH0_SECRET, // domain: process.env.AUTH0_DOMAIN, // }), ], // Database optional. MySQL, Maria DB, Postgres and MongoDB are supported. // https://next-auth.js.org/configuration/databases // // Notes: // * You must install an appropriate node_module for your database // * The Email provider requires a database (OAuth providers do not) database: process.env.DATABASE_URL, // The secret should be set to a reasonably long random string. // It is used to sign cookies and to sign and encrypt JSON Web Tokens, unless // a separate secret is defined explicitly for encrypting the JWT. secret: process.env.SECRET, session: { // Use JSON Web Tokens for session instead of database sessions. // This option can be used with or without a database for users/accounts. // Note: `jwt` is automatically set to `true` if no database is specified. jwt: true, // Seconds - How long until an idle session expires and is no longer valid. // maxAge: 30 * 24 * 60 * 60, // 30 days // Seconds - Throttle how frequently to write to database to extend a session. // Use it to limit write operations. Set to 0 to always update the database. // Note: This option is ignored if using JSON Web Tokens // updateAge: 24 * 60 * 60, // 24 hours }, // JSON Web tokens are only used for sessions if the `jwt: true` session // option is set - or by default if no database is specified. // https://next-auth.js.org/configuration/options#jwt jwt: { // A secret to use for key generation (you should set this explicitly) // secret: 'INp8IvdIyeMcoGAgFGoA61DdBglwwSqnXJZkgz8PSnw', // Set to true to use encryption (default: false) // encryption: true, // You can define your own encode/decode functions for signing and encryption // if you want to override the default behaviour. // encode: async ({ secret, token, maxAge }) => {}, // decode: async ({ secret, token, maxAge }) => {}, }, // You can define custom pages to override the built-in ones. These will be regular Next.js pages // so ensure that they are placed outside of the '/api' folder, e.g. signIn: '/auth/mycustom-signin' // The routes shown here are the default URLs that will be used when a custom // pages is not specified for that route. // https://next-auth.js.org/configuration/pages pages: { // signIn: '/auth/signin', // Displays signin buttons // signOut: '/auth/signout', // Displays form with sign out button // error: '/auth/error', // Error code passed in query string as ?error= // verifyRequest: '/auth/verify-request', // Used for check email page // newUser: null // If set, new users will be directed here on first sign in }, // Callbacks are asynchronous functions you can use to control what happens // when an action is performed. // https://next-auth.js.org/configuration/callbacks callbacks: { async signIn(user, account, profile) { const isAllowedToSignIn = false; if (isAllowedToSignIn) { return true } else { // Return false to display a default error message return false // Or you can return a URL to redirect to: // return '/unauthorized' } }, async redirect(url, baseUrl) { return baseUrl }, async session(session, user) { return session }, async jwt(token, user, account, profile, isNewUser) { return token } }, // Events are useful for logging // https://next-auth.js.org/configuration/events events: {}, // You can set the theme to 'light', 'dark' or use 'auto' to default to the // whatever prefers-color-scheme is set to in the browser. Default is 'auto' theme: 'light', // Enable debug messages in the console if you are having problems debug: false, })
/********************************* * Themes, rules, and i18n support * Locale: English *********************************/ (function(factory) { 'function' === typeof define && (define.amd || define.cmd) ? define(function(require, exports, module){ var $ = require('jquery')||jQuery; $._VALIDATOR_URI = module.uri; require('../jquery.validator')($); factory($); }) : factory(jQuery); }(function($) { /* Global configuration */ $.validator.config({ //stopOnError: true, //focusCleanup: true, //theme: 'yellow_right', //timely: 2, // Custom rules rules: { digits: [/^\d+$/, "Please enter only digits."] ,letters: [/^[a-z]+$/i, "Please enter only letters."] ,date: [/^\d{4}-\d{2}-\d{2}$/, "Please enter a valid date, format: yyyy-mm-dd"] ,time: [/^([01]\d|2[0-3])(:[0-5]\d){1,2}$/, "Please enter a valid time, between 00:00 and 23:59"] ,email: [/^[\w\+\-]+(\.[\w\+\-]+)*@[a-z\d\-]+(\.[a-z\d\-]+)*\.([a-z]{2,4})$/i, "Please enter a valid email address."] ,url: [/^(https?|s?ftp):\/\/\S+$/i, "Please enter a valid URL."] ,accept: function (element, params){ if (!params) return true; var ext = params[0], value = $(element).val(); return (ext === '*') || (new RegExp(".(?:" + ext + ")$", "i")).test(value) || this.renderMsg("Only accept {1} file extension.", ext.replace(/\|/g, ', ')); } }, // Default error messages messages: { fallback: "This field is not valid.", loading: "Validating...", error: "Network Error.", timeout: "Request timed out.", required: "This field is required.", remote: "Please try another name.", integer: { '*': "Please enter an integer.", '+': "Please enter a positive integer.", '+0': "Please enter a positive integer or 0.", '-': "Please enter a negative integer.", '-0': "Please enter a negative integer or 0." }, match: { eq: "{0} must be equal to {1}.", neq: "{0} must be not equal to {1}.", lt: "{0} must be less than {1}.", gt: "{0} must be greater than {1}.", lte: "{0} must be less than or equal to {1}.", gte: "{0} must be greater than or equal to {1}." }, range: { rg: "Please enter a number between {1} and {2}.", gte: "Please enter a number greater than or equal to {1}.", lte: "Please enter a number less than or equal to {1}." }, checked: { eq: "Please check {1} items.", rg: "Please check between {1} and {2} items.", gte: "Please check at least {1} items.", lte: "Please check no more than {1} items." }, length: { eq: "Please enter {1} characters.", rg: "Please enter a value between {1} and {2} characters long.", gte: "Please enter at least {1} characters.", lte: "Please enter no more than {1} characters.", eq_2: "", rg_2: "", gte_2: "", lte_2: "" } } }); /* Themes */ var TPL_ARROW = '<span class="n-arrow"><b>◆</b><i>◆</i></span>'; $.validator.setTheme({ 'simple_right': { formClass: 'n-simple', msgClass: 'n-right' }, 'simple_bottom': { formClass: 'n-simple', msgClass: 'n-bottom' }, 'yellow_top': { formClass: 'n-yellow', msgClass: 'n-top', msgArrow: TPL_ARROW }, 'yellow_right': { formClass: 'n-yellow', msgClass: 'n-right', msgArrow: TPL_ARROW }, 'yellow_right_effect': { formClass: 'n-yellow', msgClass: 'n-right', msgArrow: TPL_ARROW, msgShow: function($msgbox, type){ var $el = $msgbox.children(); if ($el.is(':animated')) return; if (type === 'error') { $el.css({left: '20px', opacity: 0}) .delay(100).show().stop() .animate({left: '-4px', opacity: 1}, 150) .animate({left: '3px'}, 80) .animate({left: 0}, 80); } else { $el.css({left: 0, opacity: 1}).fadeIn(200); } }, msgHide: function($msgbox, type){ var $el = $msgbox.children(); $el.stop().delay(100).show() .animate({left: '20px', opacity: 0}, 300, function(){ $msgbox.hide(); }); } } }); }));
// https://threejs.org/docs/#manual/en/introduction/Loading-3D-models // https://threejs.org/examples/#webgl_loader_gltf // https://gist.github.com/bellbind/c4f8c502fcacbe29422e5ac315273858 // https://github.com/funwithtriangles/blender-to-threejs-export-guide/blob/master/readme.md // https://threejsfundamentals.org/threejs/lessons/threejs-load-gltf.html // https://discoverthreejs.com/book/first-steps/load-models/ // https://www.pentacreation.com/blog/2019/09/190916.html // https://www.pentacreation.com/blog/2019/10/191016.html // https://gltf-viewer.donmccurdy.com/ // https://github.com/donmccurdy/three-gltf-viewer import * as THREE from 'three'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; // import { Raf } from '../lib/raf/raf'; import {DomWatcher} from '../lib/dom/dom-watcher'; import { RafProgress } from '../lib/raf/raf-progress'; import {dom} from '../lib/dom/dom'; import {EASE} from '../lib/ease/ease'; export default class ThreeObjectViewer2 { constructor() { console.log('ThreeJS Object Viewer Demo'); this.parentElement = document.getElementById('parent'); this.canvasContainer = document.getElementById('canvas-container'); this.domWatcher = new DomWatcher(); this.rafProgress = new RafProgress(); this.rafProgress.watch(this.onProgressUpdate.bind(this)); this.domWatcher.add({ element: window, on: 'scroll', callback: (event) => { this.progress = dom.getElementScrolledPercent(this.parentElement); this.rafProgress.easeTo(this.progress, 0.18, EASE.Linear); }, eventOptions: {passive: true}, }); this.scene = new THREE.Scene(); var loader = new GLTFLoader(); // const path = 'https://threejs.org/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf'; // const path = '/public/dude.glb'; const path = '/public/monster-scene3.glb'; loader.load(path, (gltf) => { this.clock = new THREE.Clock(); const scene = gltf.scenes[0]; this.activeScene = scene; this.animations = gltf.animations; // Animation Mixerインスタンスを生成 this.mixer = new THREE.AnimationMixer(scene); //全てのAnimation Clipに対して for (var i = 0; i < this.animations.length; i++) { var animation = this.animations[i]; //Animation Actionを生成 var action = this.mixer.clipAction(animation); console.log('added', animation); action.play(); } this.scene.add(scene); console.log(this.mixer); // http://learningthreejs.com/blog/2012/01/20/casting-shadows/ this.scene.traverse((child) => { if(child instanceof THREE.Light) { child.castShadow = true; console.log('cast', child); // Debugging light positions. child.shadowCameraVisible = true; // Adjust shadow bias. child.shadowBias = -0.005; child.shadowDarkness = 0.1; // child.shadow.camera.near = 0; // child.shadow.camera.far = 1000; // Lights come off a bit stronger compared to Eevee, so // lower the intensity. child.intensity = child.intensity * 0.3; // var helper = new THREE.CameraHelper( child.shadow.camera ); // scene.add( helper ); } else if(child instanceof THREE.Mesh) { child.castShadow = true; child.receiveShadow = true; console.log('receive', child); } else { console.log('nothing', child); } // if(child.name.startsWith('Cube003')) { // child.receiveShadow = true; // } // Fix eyes if(child.name.startsWith('Cube006')) { child.castShadow = false; child.receiveShadow = false; } }); // Set the camera exported in gltf. // Requires camera to be exported for gltf. this.camera = gltf.cameras[0]; console.log(this.camera); this.resize(); }, undefined, (error) => { console.error(error); }); this.renderer = new THREE.WebGLRenderer({ antialias: true }); this.canvasContainer.appendChild(this.renderer.domElement); window.addEventListener('resize', this.resize.bind(this), false); } resize() { this.progress = dom.getElementScrolledPercent(this.parentElement); this.rafProgress.easeTo(this.progress, 1, EASE.Linear); this.width = this.canvasContainer.parentElement.offsetWidth; this.height = this.canvasContainer.parentElement.offsetHeight; // https://github.com/donmccurdy/three-gltf-viewer/blob/master/src/viewer.js this.renderer.setPixelRatio(window.devicePixelRatio); this.renderer.setSize(this.width, this.height); // Important to get the correct colors. this.renderer.physicallyCorrectLights = true; // Background as black. this.renderer.setClearColor(0x000000); // this.renderer.setClearColor(0xFFFFFF, 1.0); // Affects how strongly lights come exposed. // this.renderer.toneMappingExposure = 0.4; // Enable shadows. this.renderer.shadowMap.enabled = true; // To antialias the shadow this.renderer.shadowMapType = THREE.PCFSoftShadowMap; this.renderer.gammaOutput = true; this.renderer.gammaFactor = 2.2; // The camera aspect goes off since it could be exported at a different // ratio. Force update the aspect ratio. // this.camera.fov = this.width / this.height; this.camera.aspect = this.width / this.height; this.camera.updateProjectionMatrix(); } getAnimationByName(name) { return this.animations.filter((animationClip) => { return animationClip.name == name; })[0]; } getObjectByName(name) { return this.activeScene.children.filter((object3d) => { return object3d.name == name; })[0]; } onProgressUpdate(progress) { //Animation Mixerを実行 if (this.mixer) { // We need to find out how long the animation is. // The mixer appears to have no knowledge oft this so we need to // look up a specific animation and get the duration to // get the total duration of the animation. const cameraAnimation = this.getAnimationByName('Action'); const duration = cameraAnimation.duration; // When duration hits it's max, animationMixer seems to hit the first // frame so next allow it to reach the max value. this.mixer.setTime(Math.min(duration * progress, duration - 0.001)); } this.renderer.render(this.scene, this.camera); } }
(function () { if (window.PollStart) return; window.PollStart = function (container, params) { this.Container = typeof (container) == "object" ? container : document.getElementById(container); if (!this.Container) return; params = params || {}; this.Objects = { OwnerID: params.OwnerID, OwnerType: params.OwnerType, CopyFromPollID: params.CopyFromPollID, PollID: params.PollID, PollName: Base64.decode(params.PollName), Poll: params.Poll, AudienceCount: params.AudienceCount, IsWorkFlowAdmin: params.IsWorkFlowAdmin }; this.Options = { HideSummary: params.HideSummary, UseExistingPoll: params.UseExistingPoll === true, DefaultButtonTitle: params.DefaultButtonTitle }; var that = this; GlobalUtilities.load_files(["API/FGAPI.js"], { OnLoad: function () { that.preinit(); }}); }; PollStart.prototype = { preinit: function () { var that = this; FGAPI.GetPollStatus({ IsCopyOfPollID: that.Objects.CopyFromPollID, PollID: that.Objects.PollID, ParseResults: true, ResponseHandler: function (result) { if ((result || {}).Poll) that.Objects.Poll = result.Poll; that.initialize(result); } }); }, initialize: function (params) { var that = this; params = params || {}; var instanceId = params.InstanceID; that.Container.innerHTML = ""; var elems = GlobalUtilities.create_nested_elements([{ Type: "div", Class: "small-12 medium-12 large-12", Style: "display:flex; flex-flow:column; height:100%;", Childs: [ { Type: "div", Style: "flex:0 1 auto; text-align:center; font-weight:bold; font-size:0.8rem; margin-bottom:0.5rem;", Childs: [{ Type: "text", TextValue: that.Objects.PollName }] }, { Type: "div", Style: "flex:1 1 auto;", Childs: [{ Type: "middle", Style: "padding-bottom:0.5rem;", Childs: [ { Type: "div", Name: "desc", Style: "text-align:center; font-size:0.8rem; display:none;" }, { Type: "div", Class: "small-12 medium-12 large-12", Name: "info", Style: "text-align:center; font-size:0.7rem; color:rgb(100,100,100); margin-top:0.3rem; display:none;" } ] }] }, { Type: "div", Class: "rv-air-button rv-border-radius-quarter", Name: "actionButton", Style: "flex:0 1 auto; margin:0.5rem auto 0 auto; padding:0.3rem 1rem; text-align:center; font-size:0.7rem;" } ] } ], that.Container); if (params.Description) { jQuery(elems["desc"]).fadeIn(500); GlobalUtilities.append_markup_text(elems["desc"], Base64.decode(params.Description)); } //set the title of the action button var actionButtonTitle = that.Options.DefaultButtonTitle || RVDic.FillTheForm; if (+params.FilledElementsCount && (params.FilledElementsCount < params.ElementsCount)) { actionButtonTitle = RVDic.Edit + " (" + RVDic.YouHaveFilledNOfMFields .replace("[n]", params.FilledElementsCount).replace("[m]", params.ElementsCount) + ")"; } else if ((params.ElementsCount > 0) && (params.FilledElementsCount == params.ElementsCount)) actionButtonTitle = RVDic.Edit + " (" + RVDic.Done + ")"; GlobalUtilities.set_text(elems["actionButton"], GlobalUtilities.convert_numbers_to_persian(actionButtonTitle)); //end of set the title of the action button //set the number of users that have done if (that.Objects.AudienceCount && (that.Objects.AudienceCount > 1)) { var ttl = ""; if (params.AllFilledFormsCount == that.Objects.AudienceCount) ttl = RVDic.FG.Poll.AllOfTheNUsersHaveDone.replace("[n]", that.Objects.AudienceCount); else { ttl = RVDic.FG.Poll.NOfTheMUsersHaveDone.replace("[n]", params.AllFilledFormsCount) .replace("[m]", that.Objects.AudienceCount); } jQuery(elems["info"]).html(GlobalUtilities.convert_numbers_to_persian(ttl)).fadeIn(500); } //end of set the number ob users that have done var processing = false; elems["actionButton"].onclick = function () { if (processing) return; if (instanceId) show_poll(); else { processing = true; FGAPI.GetPollInstance({ CopyFromPollID: that.Objects.CopyFromPollID, PollID: that.Objects.PollID, OwnerID: that.Objects.OwnerID, UseExistingPoll: that.Options.UseExistingPoll, ParseResults: true, ResponseHandler: function (result) { if (result.ErrorText) alert(RVDic.MSG[result.ErrorText] || result.ErrorText); else if (result.Succeed) { instanceId = result.InstanceID; if (result.Poll) that.Objects.Poll = result.Poll; show_poll(); } processing = false; } }); } }; var showed = null; var show_poll = function () { if (that.PollInstanceContainer) return showed = GlobalUtilities.show(that.PollInstanceContainer); var _div = that.PollInstanceContainer = GlobalUtilities.create_nested_elements([ { Type: "div", Class: "small-10 medium-9 large-8 rv-border-radius-1 SoftBackgroundColor", Style: "margin:0rem auto; padding:1rem;", Name: "_div" } ])["_div"]; GlobalUtilities.loading(_div); showed = GlobalUtilities.show(_div); GlobalUtilities.load_files(["FormsManager/FormViewer.js"], { OnLoad: function () { new FormViewer(_div, { InstanceID: instanceId, LimitOwnerID: that.Objects.OwnerID, ShowAllIfNoLimit: true, PollAbstract: true, Editable: true, FooterSaveButton: true, HideHeader: false, HideTitle: true, HideDescription: false, FillButton: false, Poll: that.Objects.Poll, PollOwnerType: that.Objects.OwnerType, IsWorkFlowAdmin: that.Objects.IsWorkFlowAdmin, OnInit: function () { this.goto_edit_mode(); }, OnAfterSave: function () { GlobalUtilities.confirm(RVDic.FG.Poll.PollSavedMessage, function (r) { if (r) showed.Close(); }); } }); } }); }; } }; })();
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M19.97 19.2c.18.96-.55 1.8-1.47 1.8H14v-3l1-4H9c-1.65 0-3-1.35-3-3V3h6v6h5c1.1 0 2 .9 2 2l-2 7h1.44c.73 0 1.39.49 1.53 1.2zM5 12V3H3v9c0 2.76 2.24 5 5 5h4v-2H8c-1.66 0-3-1.34-3-3z" /></React.Fragment> , 'AirlineSeatLegroomReducedTwoTone');
/* global CloudCmd */ 'use strict'; const itype = require('itype/legacy'); const exec = require('execon'); const jonny = require('jonny'); const Util = require('../../common/util'); const { getTitle, FS, Entity, } = require('../../common/cloudfunc'); const DOMTree = require('./dom-tree'); const DOM = Object.assign({}, DOMTree, new CmdProto()); module.exports = DOM; const Images = require('./images'); const load = require('./load'); const Files = require('./files'); const RESTful = require('./rest'); const Storage = require('./storage'); DOM.Images = Images; DOM.load = load; DOM.Files = Files; DOM.RESTful = RESTful; DOM.Storage = Storage; DOM.uploadDirectory = require('./directory'); DOM.Buffer = require('./buffer'); DOM.Events = require('./events'); const loadRemote = require('./load-remote'); const selectByPattern = require('./select-by-pattern'); function CmdProto() { let Title; let CurrentInfo = {}; const Cmd = this; const CURRENT_FILE = 'current-file'; const SELECTED_FILE = 'selected-file'; const TITLE = 'Cloud Commander'; const TabPanel = { 'js-left' : null, 'js-right' : null }; this.loadRemote = (name, options, callback) => { loadRemote(name, options, callback); return DOM; }; /** * load jquery from google cdn or local copy * @param callback */ this.loadJquery = function(callback) { DOM.loadRemote('jquery', { name : '$' }, callback); return DOM; }; this.loadSocket = function(callback) { DOM.loadRemote('socket', { name : 'io' }, callback); return DOM; }; /** function loads css and js of Menu * @param callback */ this.loadMenu = function(callback) { return DOM.loadRemote('menu', callback); }; /** * create new folder * */ this.promptNewDir = function() { promptNew('directory', '?dir'); }; /** * create new file * * @typeName * @type */ this.promptNewFile = () => { promptNew('file'); }; function promptNew(typeName, type) { const {Dialog} = DOM; const dir = Cmd.getCurrentDirPath(); const msg = 'New ' + typeName || 'File'; const getName = () => { const name = Cmd.getCurrentName(); if (name === '..') return ''; return name; }; const name = getName(); const cancel = false; Dialog.prompt(TITLE, msg, name, {cancel}).then((name) => { if (!name) return; const path = (type) => { const result = dir + name; if (!type) return result; return result + type; }; RESTful.write(path(type), (error) => { if (error) return; const currentName = name; CloudCmd.refresh({ currentName }); }); }); } /** * get current direcotory name */ this.getCurrentDirName = () => { const href = DOM.getCurrentDirPath() .replace(/\/$/, ''); const substr = href.substr(href, href.lastIndexOf('/')); const ret = href.replace(substr + '/', '') || '/'; return ret; }; /** * get current direcotory path */ this.getCurrentDirPath = (panel = DOM.getPanel()) => { const path = DOM.getByDataName('js-path', panel); const ret = path && path.textContent; return ret; }; /** * get current direcotory path */ this.getParentDirPath = (panel) => { const path = DOM.getCurrentDirPath(panel); const dirName = DOM.getCurrentDirName() + '/'; if (path !== '/') return path.replace(RegExp(dirName + '$'), ''); return path; }; /** * get not current direcotory path */ this.getNotCurrentDirPath = () => { const panel = DOM.getPanel({active: false}); const path = DOM.getCurrentDirPath(panel); return path; }; /** * unified way to get current file * * @currentFile */ this.getCurrentFile = () => { return DOM.getByClass(CURRENT_FILE); }; /** * get current file by name */ this.getCurrentByName = (name, panel = CurrentInfo.panel) => { const dataName = 'js-file-' + name; const element = DOM.getByDataName(dataName, panel); return element; }; /** * unified way to get current file * * @currentFile */ this.getSelectedFiles = () => { const panel = DOM.getPanel(); const selected = DOM.getByClassAll(SELECTED_FILE, panel); return [...selected]; }; /* * unselect all files */ this.unselectFiles = (files) => { files = files || DOM.getSelectedFiles(); [...files].forEach(DOM.toggleSelectedFile); }; /** * get all selected files or current when none selected * * @currentFile */ this.getActiveFiles = () => { const current = DOM.getCurrentFile(); const files = DOM.getSelectedFiles(); const name = DOM.getCurrentName(current); if (!files.length && name !== '..') return [current]; return files; }; this.getCurrentDate = (currentFile) => { const current = currentFile || Cmd.getCurrentFile(); const date = DOM .getByDataName('js-date', current) .textContent; return date; }; /** * get size * @currentFile */ this.getCurrentSize = (currentFile) => { const current = currentFile || Cmd.getCurrentFile(); /* если это папка - возвращаем слово dir вместо размера*/ const size = DOM.getByDataName('js-size', current) .textContent .replace(/^<|>$/g, ''); return size; }; /** * get size * @currentFile */ this.loadCurrentSize = (callback, currentFile) => { const current = currentFile || DOM.getCurrentFile(); const query = '?size'; const link = DOM.getCurrentPath(current); Images.show.load(); if (name === '..') return; RESTful.read(link + query, (error, size) => { if (error) return; DOM.setCurrentSize(size, current); exec(callback, current); Images.hide(); }); }; /** * load hash * @callback * @currentFile */ this.loadCurrentHash = (callback, currentFile) => { const current = currentFile || DOM.getCurrentFile(); const query = '?hash'; const link = DOM.getCurrentPath(current); RESTful.read(link + query, callback); }; /** * load current modification time of file * @callback * @currentFile */ this.loadCurrentTime = (callback, currentFile) => { const current = currentFile || DOM.getCurrentFile(); const query = '?time'; const link = DOM.getCurrentPath(current); RESTful.read(link + query, callback); }; /** * set size * @currentFile */ this.setCurrentSize = (size, currentFile) => { const current = currentFile || DOM.getCurrentFile(); const sizeElement = DOM.getByDataName('js-size', current); sizeElement.textContent = size; }; /** * @currentFile */ this.getCurrentMode = (currentFile) => { const current = currentFile || DOM.getCurrentFile(); const mode = DOM.getByDataName('js-mode', current); return mode.textContent; }; /** * @currentFile */ this.getCurrentOwner = (currentFile) => { const current = currentFile || DOM.getCurrentFile(); const owner = DOM.getByDataName('js-owner', current); return owner.textContent; }; /** * unified way to get current file content * * @param callback * @param currentFile */ this.getCurrentData = (callback, currentFile) => { let hash; const Dialog = DOM.Dialog; const Info = DOM.CurrentInfo; const current = currentFile || DOM.getCurrentFile(); const path = DOM.getCurrentPath(current); const isDir = DOM.isCurrentIsDir(current); const func = (error, data) => { const ONE_MEGABYTE = 1024 * 1024 * 1024; if (!error) { if (itype.object(data)) data = jonny.stringify(data); const length = data.length; if (hash && length < ONE_MEGABYTE) DOM.saveDataToStorage(path, data, hash); } callback(error, data); }; if (Info.name === '..') { Dialog.alert.noFiles(TITLE); return callback(Error('No files selected!')); } if (isDir) return RESTful.read(path, func); DOM.checkStorageHash(path, (error, equal, hashNew) => { if (error) return callback(error); if (equal) return DOM.getDataFromStorage(path, callback); hash = hashNew; RESTful.read(path, func); }); }; /** * unified way to save current file content * * @callback - function({data, name}) {} * @currentFile */ this.saveCurrentData = (url, data, callback, query = '') => { DOM.RESTful.write(url + query, data, (error) => { !error && DOM.saveDataToStorage(url, data); }); }; /** * unified way to get RefreshButton */ this.getRefreshButton = (panel) => { const currentPanel = panel || DOM.getPanel(); const refresh = DOM.getByDataName('js-refresh', currentPanel); return refresh; }; this.setCurrentByName = (name) => { const current = DOM.getCurrentByName(name); return DOM.setCurrentFile(current); }; /** * private function thet unset currentfile * * @currentFile */ function unsetCurrentFile(currentFile) { const is = DOM.isCurrentFile(currentFile); if (!is) return; currentFile.classList.remove(CURRENT_FILE); } /** * unified way to set current file */ this.setCurrentFile = (currentFile, options) => { const o = options; const CENTER = true; const currentFileWas = DOM.getCurrentFile(); if (!currentFile) return DOM; let pathWas = ''; if (currentFileWas) { pathWas = DOM.getCurrentDirPath(); unsetCurrentFile(currentFileWas); } currentFile.classList.add(CURRENT_FILE); let path = DOM.getCurrentDirPath(); const name = CloudCmd.config('name'); if (path !== pathWas) { DOM.setTitle(getTitle({ name, path, })); /* history could be present * but it should be false * to prevent default behavior */ if (!o || o.history !== false) { if (path !== '/') path = FS + path; DOM.setHistory(path, null, path); } } /* scrolling to current file */ DOM.scrollIntoViewIfNeeded(currentFile, CENTER); Cmd.updateCurrentInfo(currentFile); return DOM; }; /* * set current file by position * * @param layer - element * @param - position {x, y} */ this.getCurrentByPosition = ({x, y}) => { const element = document.elementFromPoint(x, y); const getEl = (el) => { const {tagName} = el; const isChild = /A|SPAN|LI/.test(tagName); if (!isChild) return null; if (tagName === 'A') return el.parentElement.parentElement; if (tagName === 'SPAN') return el.parentElement; return el; }; const el = getEl(element); if (el && el.tagName !== 'LI') return null; return el; }; /** * select current file * @param currentFile */ this.selectFile = (currentFile) => { const current = currentFile || DOM.getCurrentFile(); current.classList.add(SELECTED_FILE); return Cmd; }; this.unselectFile = (currentFile) => { const current = currentFile || DOM.getCurrentFile(); current.classList.remove(SELECTED_FILE); return Cmd; }; this.toggleSelectedFile = (currentFile) => { const current = currentFile || DOM.getCurrentFile(); const name = DOM.getCurrentName(current); if (name === '..') return Cmd; current.classList.toggle(SELECTED_FILE); return Cmd; }; this.toggleAllSelectedFiles = () => { DOM.getAllFiles().map(DOM.toggleSelectedFile); return Cmd; }; this.selectAllFiles = () => { DOM.getAllFiles().map(DOM.selectFile); return Cmd; }; this.getAllFiles = () => { const panel = DOM.getPanel(); const files = DOM.getFiles(panel); const name = DOM.getCurrentName(files[0]); const from = (a) => a === '..' ? 1 : 0; const i = from(name); return [...files].slice(i); }; /** * open dialog with expand selection */ this.expandSelection = () => { const msg = 'expand'; const files = CurrentInfo.files; selectByPattern(msg, files); }; /** * open dialog with shrink selection */ this.shrinkSelection = () => { const msg = 'shrink'; const files = CurrentInfo.files; selectByPattern(msg, files); }; /** * setting history wrapper */ this.setHistory = (data, title, url) => { const ret = window.history; url = CloudCmd.PREFIX + url; if (ret) history.pushState(data, title, url); return ret; }; /** * set title or create title element * * @param name */ this.setTitle = (name) => { if (!Title) Title = DOM.getByTag('title')[0] || DOM.load({ name : 'title', innerHTML : name, parentElement : document.head }); Title.textContent = name; return DOM; }; /** * current file check * * @param currentFile */ this.isCurrentFile = (currentFile) => { if (!currentFile) return false; return DOM.isContainClass(currentFile, CURRENT_FILE); }; /** * selected file check * * @param currentFile */ this.isSelected = (selected) => { if (!selected) return false; return DOM.isContainClass(selected, SELECTED_FILE); }; /** * check is current file is a directory * * @param currentFile */ this.isCurrentIsDir = (currentFile) => { const current = currentFile || this.getCurrentFile(); const fileType = DOM.getByDataName('js-type', current); const ret = DOM.isContainClass(fileType, 'directory'); return ret; }; /** * get link from current (or param) file * * @param currentFile - current file by default */ this.getCurrentLink = (currentFile) => { const current = currentFile || this.getCurrentFile(); const link = DOM.getByTag('a', current); return link[0]; }; /** * get link from current (or param) file * * @param currentFile - current file by default */ this.getCurrentPath = (currentFile) => { const current = currentFile || DOM.getCurrentFile(); const element = DOM.getByTag('a', current)[0]; const prefix = CloudCmd.PREFIX; const path = element.getAttribute('href') .replace(RegExp('^' + prefix + FS), ''); return path; }; /** * get name from current (or param) file * * @param currentFile */ this.getCurrentName = (currentFile) => { const current = currentFile || DOM.getCurrentFile(); if (!current) return ''; const link = DOM.getCurrentLink(current); if (!link) return ''; const name = link.title; return name; }; this.getFilenames = (files) => { if (!files) throw Error('AllFiles could not be empty'); const first = files[0] || DOM.getCurrentFile(); const name = DOM.getCurrentName(first); const allFiles = [...files]; if (name === '..') allFiles.shift(); const names = allFiles.map((current) => { return DOM.getCurrentName(current); }); return names; }; /** * set name from current (or param) file * * @param name * @param current */ this.setCurrentName = (name, current) => { const Info = CurrentInfo; const link = Info.link; const PREFIX = CloudCmd.PREFIX; const dir = PREFIX + FS + Info.dirPath; link.title = name; link.innerHTML = Entity.encode(name); link.href = dir + name; current.setAttribute('data-name', 'js-file-' + name); return link; }; /** * check storage hash */ this.checkStorageHash = (name, callback) => { const parallel = exec.parallel; const loadHash = DOM.loadCurrentHash; const nameHash = name + '-hash'; const getStoreHash = exec.with(Storage.get, nameHash); if (typeof name !== 'string') throw Error('name should be a string!'); if (typeof callback !== 'function') throw Error('callback should be a function!'); parallel([loadHash, getStoreHash], (error, loadHash, storeHash) => { let equal; const isContain = /error/.test(loadHash); if (isContain) error = loadHash; else if (loadHash === storeHash) equal = true; callback(error, equal, loadHash); }); }; /** * save data to storage * * @param name * @param data * @param hash * @param callback */ this.saveDataToStorage = function(name, data, hash, callback) { const allowed = CloudCmd.config('localStorage'); const isDir = DOM.isCurrentIsDir(); const nameHash = name + '-hash'; const nameData = name + '-data'; if (!allowed || isDir) return exec(callback); exec.if(hash, () => { Storage.set(nameHash, hash); Storage.set(nameData, data); exec(callback, hash); }, (callback) => { DOM.loadCurrentHash((error, loadHash) => { hash = loadHash; callback(); }); }); }; /** * save data to storage * * @param name * @param data * @param callback */ this.getDataFromStorage = (name, callback) => { const nameHash = name + '-hash'; const nameData = name + '-data'; const allowed = CloudCmd.config('localStorage'); const isDir = DOM.isCurrentIsDir(); if (!allowed || isDir) return exec(callback); exec.parallel([ exec.with(Storage.get, nameData), exec.with(Storage.get, nameHash), ], callback); }; this.getFM = () => { return DOM.getPanel().parentElement; }; this.getPanelPosition = (panel) => { panel = panel || DOM.getPanel(); return panel.dataset.name.replace('js-', ''); }; /** function getting panel active, or passive * @param options = {active: true} */ this.getPanel = (options) => { var files, panel, isLeft, dataName = 'js-', current = DOM.getCurrentFile(); if (!current) { panel = DOM.getByDataName('js-left'); } else { files = current.parentElement, panel = files.parentElement, isLeft = panel.getAttribute('data-name') === 'js-left'; } /* if {active : false} getting passive panel */ if (options && !options.active) { dataName += isLeft ? 'right' : 'left'; panel = DOM.getByDataName(dataName); } /* if two panels showed * then always work with passive * panel */ if (window.innerWidth < CloudCmd.MIN_ONE_PANEL_WIDTH) panel = DOM.getByDataName('js-left'); if (!panel) throw Error('can not find Active Panel!'); return panel; }; this.getFiles = (element) => { const files = DOM.getByDataName('js-files', element); return files.children || []; }; /** * shows panel right or left (or active) */ this.showPanel = (active) => { const panel = DOM.getPanel({active: active}); if (!panel) return false; DOM.show(panel); return true; }; /** * hides panel right or left (or active) */ this.hidePanel = (active) => { var ret = false, panel = DOM.getPanel({active: active}); if (panel) ret = DOM.hide(panel); return ret; }; /** * open window with URL * @param url */ this.openWindow = (url) => { var left = 140, top = 187, width = 1000, height = 650, options = 'left=' + left + ',top=' + top + ',width=' + width + ',height=' + height + ',personalbar=0,toolbar=0' + ',scrollbars=1,resizable=1', wnd = window.open(url, 'Cloud Commander Auth', options); if (!wnd) DOM.Dialog.alert(TITLE, 'Please disable your popup blocker and try again.'); return wnd; }; /** * remove child of element * @param pChild * @param element */ this.remove = (child, element) => { const parent = element || document.body; parent.removeChild(child); return DOM; }; /** * remove current file from file table * @param current * */ this.deleteCurrent = (current) => { var next, prev, currentNew; if (!current) Cmd.getCurrentFile(); var parent = current && current.parentElement; var name = Cmd.getCurrentName(current); if (current && name !== '..') { next = current.nextSibling, prev = current.previousSibling; if (next) currentNew = next; else if (prev) currentNew = prev; DOM.setCurrentFile(currentNew); parent.removeChild(current); } return currentNew; }; /** * remove selected files from file table * @Selected */ this.deleteSelected = (selected) => { var i, n, current; if (!selected) selected = DOM.getSelectedFiles(); if (selected) { n = selected.length; for (i = 0; i < n; i++) { current = selected[i]; DOM.deleteCurrent(current); } } return selected; }; /** * rename current file * * @currentFile */ this.renameCurrent = (current) => { const Dialog = DOM.Dialog; if (!Cmd.isCurrentFile(current)) current = Cmd.getCurrentFile(); const from = Cmd.getCurrentName(current); if (from === '..') return Dialog.alert.noFiles(TITLE); const cancel = false; Dialog.prompt(TITLE, 'Rename', from, {cancel}).then((to) => { const isExist = !!DOM.getCurrentByName(to); const dirPath = Cmd.getCurrentDirPath(); if (from === to) return; const files = { from : dirPath + from, to : dirPath + to }; RESTful.mv(files, (error) => { if (error) return; DOM.setCurrentName(to, current); Cmd.updateCurrentInfo(current); Storage.remove(dirPath); if (isExist) CloudCmd.refresh(); }); }); }; /** * unified way to scrollIntoViewIfNeeded * (native suporte by webkit only) * @param element * @param pCenter */ this.scrollIntoViewIfNeeded = function(element, center) { var ret = element && element.scrollIntoViewIfNeeded; /* for scroll as small as possible * param should be false */ if (arguments.length === 1) center = false; if (ret) element.scrollIntoViewIfNeeded(center); return ret; }; /* scroll on one page*/ this.scrollByPages = (element, pPages) => { var ret = element && element.scrollByPages && pPages; if (ret) element.scrollByPages(pPages); return ret; }; this.changePanel = () => { let panel = DOM.getPanel(); const panelPassive = DOM.getPanel({ active: false }); let name = DOM.getCurrentName(); const filesPassive = DOM.getFiles(panelPassive); let dataName = panel.getAttribute('data-name'); TabPanel[dataName] = name; panel = panelPassive; dataName = panel.getAttribute('data-name'); name = TabPanel[dataName]; let files; let current; if (name) { current = DOM.getCurrentByName(name, panel); if (current) files = current.parentElement; } if (!files || !files.parentElement) { current = DOM.getCurrentByName(name, panel); if (!current) current = filesPassive[0]; } DOM.setCurrentFile(current, { history: true }); return DOM; }; this.getPackerExt = (type) => { if (type === 'zip') return '.zip'; return '.tar.gz'; }; this.goToDirectory = () => { const msg = 'Go to directory:'; const path = CurrentInfo.dirPath; const Dialog = DOM.Dialog; const cancel = false; Dialog.prompt(TITLE, msg, path, {cancel}).then((path) => { CloudCmd.loadDir({ path: path }); }); }, this.duplicatePanel = () => { const Info = CurrentInfo; const isDir = Info.isDir; const panel = Info.panelPassive; const noCurrent = !Info.isOnePanel; const getPath = (isDir) => { if (isDir) return Info.path; return Info.dirPath; }; const path = getPath(isDir); CloudCmd.loadDir({ path, panel, noCurrent, }); }; this.swapPanels = () => { const Info = CurrentInfo; const {panel} = Info; const {files} = Info; const {element} = Info; const panelPassive = Info.panelPassive; const dirPath = DOM.getCurrentDirPath(); const dirPathPassive = DOM.getNotCurrentDirPath(); let currentIndex = files.indexOf(element); CloudCmd.loadDir({ path: dirPath, panel: panelPassive, noCurrent: true }); CloudCmd.loadDir({ path: dirPathPassive, panel: panel }, () => { const files = Info.files; const length = files.length - 1; if (currentIndex > length) currentIndex = length; const el = files[currentIndex]; DOM.setCurrentFile(el); }); }; this.CurrentInfo = CurrentInfo, this.updateCurrentInfo = (currentFile) => { const info = Cmd.CurrentInfo; const current = currentFile || Cmd.getCurrentFile(); const files = current.parentElement; const panel = files.parentElement; const panelPassive = Cmd.getPanel({ active: false }); const filesPassive = DOM.getFiles(panelPassive); const name = Cmd.getCurrentName(current); info.dir = Cmd.getCurrentDirName(); info.dirPath = Cmd.getCurrentDirPath(); info.parentDirPath = Cmd.getParentDirPath(); info.element = current; info.ext = Util.getExt(name); info.files = [...files.children]; info.filesPassive = [...filesPassive]; info.first = files.firstChild; info.getData = Cmd.getCurrentData; info.last = files.lastChild; info.link = Cmd.getCurrentLink(current); info.mode = Cmd.getCurrentMode(current); info.name = name; info.path = Cmd.getCurrentPath(current); info.panel = panel; info.panelPassive = panelPassive; info.size = Cmd.getCurrentSize(current); info.isDir = Cmd.isCurrentIsDir(); info.isSelected = Cmd.isSelected(current); info.panelPosition = Cmd.getPanel().dataset.name.replace('js-', ''); info.isOnePanel = info.panel.getAttribute('data-name') === info.panelPassive.getAttribute('data-name'); }; }
const { EOL } = require("os"); const path = require("path"); const fs = require("fs-extra"); const chalk = require("chalk"); const dedent = require("dedent"); const initTempDir = require("../utils/initTempDir"); const runCreateCorvidApp = require("../utils/runCreateCorvidApp"); const { start: startFakeNpmRegistry, publishPackage } = require("../utils/fakeNpmRegistry"); const fakeCorvidCliPath = path.join( __dirname, "..", "utils", "fake-packages", "fake-corvid-cli" ); const fakeCorvidTypesPath = path.join( __dirname, "..", "utils", "fake-packages", "fake-corvid-types" ); describe("create", () => { let fakeNpmRegistry; let createCorvidApp = () => {}; beforeAll(async () => { fakeNpmRegistry = await startFakeNpmRegistry(); await publishPackage(fakeNpmRegistry.registryUrl, fakeCorvidCliPath); await publishPackage(fakeNpmRegistry.registryUrl, fakeCorvidTypesPath); createCorvidApp = args => runCreateCorvidApp(args, fakeNpmRegistry); }); afterAll(async () => { await fakeNpmRegistry.close(); }); describe("project template", () => { it("should create the given directory if it doesn't exist", async () => { const projectDir = await initTempDir(); await createCorvidApp(projectDir); expect(await fs.exists(projectDir)).toBeTruthy(); }); it("should fail working with a non-empty directory", async () => { const projectDir = await initTempDir(); await fs.writeFile(path.join(projectDir, "file.js"), "some file content"); const { stderr } = await createCorvidApp(projectDir).catch(err => err); expect(stderr).toMatch("Cannot initialize a non-empty directory."); }); it("should create a .gitignore file", async () => { const projectDir = await initTempDir(); await createCorvidApp(projectDir); const gitIgnore = await fs.readFile( path.join(projectDir, ".gitignore"), "utf8" ); expect(gitIgnore.split(EOL)).toEqual( expect.arrayContaining(["/node_modules", "/.corvid/session.log"]) ); }); it("should create a package.json with the project name and corvid-cli, corvid-types dependencies", async () => { const projectDir = path.join(await initTempDir(), "project-name"); await createCorvidApp(projectDir); const packageJson = await fs.readFile( path.join(projectDir, "package.json"), "utf8" ); expect(packageJson.trim(EOL)).toEqual( JSON.stringify( { name: "project-name", version: "0.1.0", private: true, devDependencies: { "corvid-cli": "^6.5.4", "corvid-types": "^9.8.7" } }, null, 2 ) ); }); }); describe("dependencies", () => { it("should install corvid-cli dependency", async () => { const projectDir = await initTempDir(); await createCorvidApp(projectDir); expect( fs.existsSync( path.join(projectDir, "node_modules", "corvid-cli", "package.json") ) ).toBeTruthy(); }); it("should install corvid-types dependency", async () => { const projectDir = await initTempDir(); await createCorvidApp(projectDir); expect( fs.existsSync( path.join(projectDir, "node_modules", "corvid-types", "package.json") ) ).toBeTruthy(); }); }); describe("site clone", () => { it("should clone a user site when given its url", async () => { const projectDir = await initTempDir(); const { stdout } = await createCorvidApp( `${projectDir} http://my.wix.site` ); expect(stdout).toMatch( `fake corvid-cli called in [${projectDir}] with [clone http://my.wix.site]` ); }); }); describe("errors", () => { it("should cleanup in case of initialization error", async () => { // TODO: implement }); it("should cleanup in case of an error while cloning a site", async () => { // TODO: implement }); }); describe("output", () => { it("should output relevant execution steps", async () => { const projectDir = await initTempDir(); const { stdout } = await createCorvidApp(projectDir); expect(stdout).toMatch(dedent` Initializing a new project in ${chalk.cyan(projectDir)} Installing dependencies: ${chalk.cyan("corvid-cli")}, ${chalk.cyan( "corvid-types" )}... (this might take a few minutes) `); }); it("should instruct the user to clone a site if no url was given", async () => { const projectDir = await initTempDir(); const { stdout } = await createCorvidApp(projectDir); expect(stdout).toMatch(dedent` Done! A project was initialized in ${chalk.cyan(projectDir)} To clone a site, run: ${chalk.cyan(`cd ${projectDir}`)} ${chalk.cyan("npx corvid clone <site-url>")} `); }); it("should instruct a user to start the local editor after a site was cloned", async () => { const projectDir = await initTempDir(); const { stdout } = await createCorvidApp( `${projectDir} http://my.wix.site` ); expect(stdout).toMatch(dedent` Done! Your site was cloned into ${chalk.cyan(projectDir)} You can now start working on your site by running: ${chalk.cyan(`cd ${projectDir}`)} ${chalk.cyan("npx corvid open-editor")} `); }); }); });
/** * Define Swatches * * This command can be used to define a color swatch. After generating the Color Inventory, select a color swatch (layer group) and * run this command which will show a dialog where a name can be entered. */ @import '../inventory.js' var onRun = function (context) { // old school variable doc = context.document; selection = context.selection; com.getflourish.common.init(context); // doc.deselectAllLayers(); // selection.clear(); var selected = selection; for (var i = 0; i < selected.count(); i++) { var layer = selected.objectAtIndex(i); layer.isSelected = true; // com.getflourish.view.centerTo(layer); var name = [doc askForUserInput:"Color name: (e.g. Primary > Blue)" initialValue:""] if(name != "") { layer.setName(name); var children = layer.children(); for (var j = 0; j < children.count(); j++) { if(children[j].name() == "Swatch Name") { var label = children[j]; label.setStringValue(name); label.adjustFrameToFit(); label.setTextAlignment(0); } } } else { break; } layer.isSelected = false } // com.getflourish.view.centerTo(com.getflourish.doc.currentPage().currentArtboard()); com.getflourish.colorInventory.generate(); }
ace.define("ace/snippets/sparql",["require","exports","module"],function(r,e,m){"use strict";e.snippetText=undefined;e.scope="";});
/** @jsx jsx */ import { jsx } from '@emotion/core' export default ({ children }) => ( <div css={{ margin: '0 auto', maxWidth: 960, padding: '0px 1em 1.5em', paddingTop: 0, }} > {children} </div> )
var assert = require('assert') var request = require('request') var versionator = require('../') var appEngine = require('connect') describe('versionator', function() { describe('#createBasic', function() { it('throws an error if no version is passed', function() { assert.throws(function() { versionator.createBasic() }, /version is required/) }) it('returns a middleware function', function() { versionator.createBasic('0.0.0').middleware.should.be.type('function') }) describe('#versionPath', function() { it('should inject the version correctly', function() { var basic = versionator.createBasic('v0.0.0') basic.versionPath('/js/test.js').should.eql('/js/v0.0.0/test.js') }) it('should URLs with querystring', function() { var basic = versionator.createBasic('v0.0.0') basic .versionPath('/js/test-bar.js?test=1') .should.eql('/js/v0.0.0/test-bar.js?test=1') }) it('should basic URLs with hash', function() { var basic = versionator.createBasic('v0.0.0') basic .versionPath('/js/test-bar.js#hashy') .should.eql('/js/v0.0.0/test-bar.js#hashy') }) it('should basic URLs with querystring and hash', function() { var basic = versionator.createBasic('v0.0.0') basic .versionPath('/js/test-bar.js?test=1#hashy') .should.eql('/js/v0.0.0/test-bar.js?test=1#hashy') }) it('strings without a "/" will be left unchanged', function() { var basic = versionator.createBasic('v0.0.0') basic .versionPath('Hello this is an odd path') .should.eql('Hello this is an odd path') }) it('should convert all urls in an array', function() { var basic = versionator.createBasic('v0.0.0') basic.versionPath(['/js/test.js']).should.eql(['/js/v0.0.0/test.js']) }) it('should return an empty array when passed an empty url', function() { var basic = versionator.createBasic('v0.0.0') basic.versionPath([]).should.eql([]) }) }) }) describe('basic middleware', function() { function startServer(port) { var app = appEngine() .use(versionator.createBasic('v0.1.2').middleware) .use(function(req, res) { res.setHeader('x-url', req.url) res.end(req.url) }) return app.listen(port) } it('req.url has version removed from pathname', function(done) { var app = startServer(9898) request('http://localhost:9898/images/v0.1.2/sprite.png', function( ignoreError, response, data ) { data.should.eql('/images/sprite.png') app.close() done() }) }) it('should allow GET', function(done) { var app = startServer(9898) request.get('http://localhost:9898/images/v0.1.2/sprite.png', function( ignoreError, response, data ) { data.should.eql('/images/sprite.png') app.close() done() }) }) it('should allow HEAD', function(done) { var app = startServer(9898) request.head('http://localhost:9898/images/v0.1.2/sprite.png', function( ignoreError, response ) { response.headers['x-url'].should.eql('/images/sprite.png') app.close() done() }) }) it('req.url is unchanged if no version match is found', function(done) { var app = startServer(9899) request('http://localhost:9899/images/sprite.png', function( ignoreError, response, data ) { data.should.eql('/images/sprite.png') app.close() done() }) }) }) })
/**! * LibreMoney AbstractAppendix 0.2 * Copyright (c) LibreMoney Team <libremoney@yandex.com> * CC0 license */ if (typeof module !== "undefined") { var Appendix = require(__dirname + '/Appendix'); var Convert = require(__dirname + '/../../../Lib/Util/Convert'); } function AbstractAppendix(data) { this.prototype = new Appendix(); if (typeof data.attachmentData != 'undefined') { this.version = Convert.NullToZero(attachmentData["version." + GetAppendixName()]); } else if (typeof data.buffer != 'undefined' && data.transactionVersion != 'undefined') { if (data.transactionVersion == 0) { this.version = 0; } else { this.version = data.buffer[0]; } } else if (typeof data.version != 'undefined') { this.version = data.version; } else this.version = 1; return this; } AbstractAppendix.prototype.Apply = function(transaction, senderAccount, recipientAccount) { } AbstractAppendix.prototype.GetAppendixName = function() { return ''; } AbstractAppendix.prototype.GetJsonObject = function() { var json = {}; json["version." + this.GetAppendixName()] = version; this.PutMyJson(json); return json; } AbstractAppendix.prototype.GetMySize = function() { return 0; } AbstractAppendix.prototype.GetSize = function() { return this.GetMySize() + 1; } AbstractAppendix.prototype.GetVersion = function() { return this.version; } AbstractAppendix.prototype.PutMyBytes = function(buffer) { } AbstractAppendix.prototype.PutMyJson = function(json) { } AbstractAppendix.prototype.PutBytes = function(buffer) { buffer.push(version); this.PutMyBytes(buffer); } AbstractAppendix.prototype.Undo = function(transaction, senderAccount, recipientAccount) { } AbstractAppendix.prototype.Validate = function(transaction) { } AbstractAppendix.prototype.VerifyVersion = function(transactionVersion) { return transactionVersion == 0 ? this.version == 0 : this.version > 0; } if (typeof module !== "undefined") { module.exports = AbstractAppendix; }
// 代码的自动测试 function twoNumberAdd(a,b) { return parseInt(a) + parseInt(b) } module.exports = twoNumberAdd
const express = require('express') const exphbs = require('express-handlebars') const conn = require('./db/conn') const Address = require('./models/Address') const User = require('./models/User') //Não é preciso utilizar para criar a tabela tendo o caminho do arquivo aqui o sequelize entende e mapeia ele criando a tabela ao iniciar a aplicação const app = express() //ATENÇÃO OCORREU UM ERRO AO INICIAR ESSE APP PARA RESOLVER FOI INSTALADO O mysql2 a partir do comando npm install mysql2 app.use( //Utilizando middleware para pegar dados do url express.urlencoded({ extended: true, }) ) app.use(express.json()) //Transformando dados do url em json app.engine('handlebars', exphbs()) app.set('view engine', 'handlebars') app.use(express.static('public')) //Ponte para arquivos estáticos app.get('/users/create', (req, res) => { res.render('adduse') }) app.post('/users/create', async (req, res) => { //Os dados abaixo são apenas didático. É preciso tratar os dados em uma aplicação real por motivo de segurança const name = req.body.name const occupation = req.body.occupation let newsletter = req.body.newsletter if (newsletter === 'on') { newsletter = true } else { newsletter = false //Necessário para a variável não ficar nula } console.log(req.body) await User.create({ name, occupation, newsletter }) //Com isso é possível criar as querys no bando de dados automaticamente com o sequelize o await garante que o redirecionamento so irá acontecer após o usuário ser criado res.redirect('/') }) app.get('/users/:id', async (req, res) => { //Pegando ID dinamicamente do url utilizando sequelize const id = req.params.id const user = await User.findOne({ raw: true, where: { id: id } }) //Pegando 1 usuário da tabela res.render('userview', { user }) //Renderizando html do handlebars com o nome userview }) app.post('/users/delete/:id', async (req, res) => { //Deletando usuários const id = req.params.id await User.destroy({ where: { id: id } }) res.redirect('/') }) app.get('/users/edit/:id', async (req, res) => { //Pegando usuários para edição const id = req.params.id try { const user = await User.findOne({ include: Address, where: { id: id } }) res.render('useredit', { user: user.get({ plain: true }) }) } catch (error) { console.log(error) } // const user = await User.findOne({ raw: true, where: { id: id } }) //raw permite utilizar o dado // res.render('useredit', { user: user.get({ plain: true }) }) }) app.post('/users/update', async (req, res) => { //Editando usuários const id = req.body.id const name = req.body.name const occupation = req.body.occupation let newsletter = req.body.newsletter if (newsletter === 'on') { newsletter = true } else { newsletter = false } const userData = { id, //Abreviação de "id: id" -> mesmo nome já atribui o valor à variável (destructuring) name, occupation, newsletter, } await User.update(userData, { where: { id: id } }) //Atenção ao trabalhar com SeQueLize "User" utilize o where para filtrar res.redirect('/') }) app.get('/', async (req, res) => { const users = await User.findAll({ raw: true }) console.log(users) res.render('home', { users: users }) }) app.post('/address/create', async (req, res) => { const UserId = req.body.UserId const street = req.body.street const number = req.body.number const city = req.body.city const address = { UserId, //Forma reduzida de "UserId: UserId" (constante acima) street, number, city, } await Address.create(address) //Criando e esperando a tabela ser criada res.redirect(`/users/edit/${UserId}`) }) app.post('/address/delete', async (req, res) => { const UserId = req.body.UserId const id = req.body.id await Address.destroy({ where: { id: id } //Sempre lembre-se do WHERE }) res.redirect(`/users/edit/${UserId}`) }) conn .sync() //.sync({force: true}) //Recria as tabelas e apaga os dados a partir do momento que salva .then(() => { //A aplicação só vai funcionar quando as tabelas necessárias forem criadas app.listen(3000) }) .catch((err) => console.log(err))
import CardSet from "../../../src/artifact/js/CardSet.js"; import CardSetType from "../../../src/artifact/js/CardSetType.js"; import CardSubset from "../../../src/artifact/js/CardSubset.js"; QUnit.module("CardSubset"); var CardSubsetTest = {}; QUnit.test("CardSubset properties The Hunt for Gollum", function(assert) { var cardSubset = CardSubset.SOM1_THE_HUNT_FOR_GOLLUM; var properties = CardSubset.properties[cardSubset]; assert.equal(properties.name, "The Hunt for Gollum"); assert.equal(properties.cardSetKey, CardSet.SHADOWS_OF_MIRKWOOD); assert.equal(properties.number, 1); assert.equal(properties.typeKey, CardSetType.ADVENTURE_PACK); assert.equal(properties.key, "som1TheHuntForGollum"); }); QUnit.test("keys and values", function(assert) { // Setup. // Run. var result = CardSubset.keys(); var ownPropertyNames = Object.getOwnPropertyNames(CardSubset); // Verify. ownPropertyNames.forEach(function(key) { var key2 = CardSubset[key]; if (key !== "properties" && typeof key2 === "string") { assert.ok(CardSubset.properties[key2], "Missing value for key = " + key); } }); result.forEach(function(value) { var p = ownPropertyNames.filter(function(key) { return CardSubset[key] === value; }); assert.equal(p.length, 1, "Missing key for value = " + value); }); }); QUnit.test("CardSubset.keys()", function(assert) { // Run. var result = CardSubset.keys(); // Verify. assert.ok(result); var length = 30; assert.equal(result.length, length); var i = 0; assert.equal(result[i++], CardSubset.AA1_THE_WASTES_OF_ERIADOR); assert.equal(result[i++], CardSubset.AA2_ESCAPE_FROM_MOUNT_GRAM); assert.equal(result[i++], CardSubset.AA3_ACROSS_THE_ETTENMOORS); assert.equal(result[i++], CardSubset.AA4_THE_TREACHERY_OF_RHUDAUR); assert.equal(result[i++], CardSubset.AA5_THE_BATTLE_OF_CARN_DUM); assert.equal(result[i++], CardSubset.AA6_THE_DREAD_REALM); assert.equal(result[i++], CardSubset.ATS1_THE_STEWARDS_FEAR); assert.equal(result[i++], CardSubset.ATS2_THE_DRUADAN_FOREST); assert.equal(result[i++], CardSubset.ATS3_ENCOUNTER_AT_AMON_DIN); assert.equal(result[i++], CardSubset.ATS4_ASSAULT_ON_OSGILIATH); assert.equal(result[i++], CardSubset.ATS5_THE_BLOOD_OF_GONDOR); assert.equal(result[i++], CardSubset.ATS6_THE_MORGUL_VALE); assert.equal(result[i++], CardSubset.D1_THE_REDHORN_GATE); assert.equal(result[i++], CardSubset.D2_ROAD_TO_RIVENDELL); assert.equal(result[i++], CardSubset.D3_THE_WATCHER_IN_THE_WATER); assert.equal(result[i++], CardSubset.D4_THE_LONG_DARK); assert.equal(result[i++], CardSubset.D5_FOUNDATIONS_OF_STONE); assert.equal(result[i++], CardSubset.D6_SHADOW_AND_FLAME); assert.equal(result[i++], CardSubset.SOM1_THE_HUNT_FOR_GOLLUM); assert.equal(result[i++], CardSubset.SOM2_CONFLICT_AT_THE_CARROCK); assert.equal(result[i++], CardSubset.SOM3_A_JOURNEY_TO_RHOSGOBEL); assert.equal(result[i++], CardSubset.SOM4_THE_HILLS_OF_EMYN_MUIL); assert.equal(result[i++], CardSubset.SOM5_THE_DEAD_MARSHES); assert.equal(result[i++], CardSubset.SOM6_RETURN_TO_MIRKWOOD); assert.equal(result[i++], CardSubset.TRM1_THE_DUNLAND_TRAP); assert.equal(result[i++], CardSubset.TRM2_THE_THREE_TRIALS); assert.equal(result[i++], CardSubset.TRM3_TROUBLE_IN_THARBAD); assert.equal(result[i++], CardSubset.TRM4_THE_NIN_IN_EILPH); assert.equal(result[i++], CardSubset.TRM5_CELEBRIMBORS_SECRET); assert.equal(result[i++], CardSubset.TRM6_THE_ANTLERED_CROWN); }); export default CardSubsetTest;
module.exports={A:{A:{"2":"J C G E TB","129":"B A"},B:{"129":"D X","1025":"g H L"},C:{"2":"3 RB F I J C G E B A D X g H L M N O P Q R S T U V W t PB OB","513":"1 2 Y Z a b c d e f K h i j k l m n o p q v w x y z s r"},D:{"1":"1 2 7 9 J C G E B A D X g H L M N O P Q R S T U V W t Y Z a b c d e f K h i j k l m n o p q v w x y z s r DB SB AB BB","2":"F I"},E:{"1":"I J C G E B A EB FB GB HB IB JB","2":"6 F CB"},F:{"1":"0 4 5 E A D H L M N O P Q R S T U V W t Y Z a b c d e f K h i j k l m n o p q KB LB MB NB QB"},G:{"388":"6 8 G A u UB VB WB XB YB ZB aB bB"},H:{"2":"cB"},I:{"2":"3 dB eB fB","388":"F r gB u hB iB"},J:{"2":"C","388":"B"},K:{"1":"0 4 5 B A D","388":"K"},L:{"388":"7"},M:{"641":"s"},N:{"388":"B A"},O:{"388":"jB"},P:{"388":"F I"},Q:{"1":"kB"},R:{"388":"lB"}},B:1,C:"Number input type"};
/* istanbul instrument in package npmdoc_axios */ /*jslint bitwise: true, browser: true, maxerr: 8, maxlen: 96, node: true, nomen: true, regexp: true, stupid: true */ (function () { 'use strict'; var local; // run shared js-env code - pre-init (function () { // init local local = {}; // init modeJs local.modeJs = (function () { try { return typeof navigator.userAgent === 'string' && typeof document.querySelector('body') === 'object' && typeof XMLHttpRequest.prototype.open === 'function' && 'browser'; } catch (errorCaughtBrowser) { return module.exports && typeof process.versions.node === 'string' && typeof require('http').createServer === 'function' && 'node'; } }()); // init global local.global = local.modeJs === 'browser' ? window : global; // init utility2_rollup local = local.global.utility2_rollup || local; // init lib local.local = local.npmdoc_axios = local; // init exports if (local.modeJs === 'browser') { local.global.utility2_npmdoc_axios = local; } else { module.exports = local; module.exports.__dirname = __dirname; module.exports.module = module; } }()); }());
/** * DevExtreme (ui/date_box.js) * Version: 16.2.1-16294 * Build date: Thu Oct 20 2016 * * Copyright (c) 2012 - 2016 Developer Express Inc. ALL RIGHTS RESERVED * EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml */ "use strict"; module.exports = require("./date_box/ui.date_box"); module.exports.default = module.exports;
'use strict'; /** * Module for all communication with libre.fm */ define((require) => { const $ = require('jquery'); const AudioScrobbler = require('scrobbler/audioscrobbler'); const ServiceCallResult = require('object/service-call-result'); class LibreFm extends AudioScrobbler { /** @override */ sendRequest(method, params, signed) { if ('post' !== method.toLowerCase()) { return super.sendRequest(method, params, signed); } const url = this.makeRequestUrl(params, signed); return new Promise((resolve, reject) => { $.post(url, $.param(params)).done((xmlDoc) => { let text = new XMLSerializer().serializeToString(xmlDoc); this.debugLog(`${params.method} response:\n${text}`); resolve($(xmlDoc)); }).fail((jqXHR, status, text) => { this.debugLog(`${params.method} response:\n${text}`, 'error'); reject(new ServiceCallResult(ServiceCallResult.ERROR_OTHER)); }); }); } } return new LibreFm({ label: 'Libre.fm', storage: 'LibreFM', apiUrl: 'https://libre.fm/2.0/', apiKey: 'r8i1y91hz71tcx7vyrp9hk1alhqp1898', apiSecret: '8187db5vg234yq6tm7o62q8mtl1niala', authUrl: 'https://www.libre.fm/api/auth/', statusUrl: null, profileUrl: 'https://libre.fm/user/', }); });
import { lazy, Suspense } from "react"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import Box from "@material-ui/core/Box"; import { styled } from "@material-ui/core/styles"; import Loading from "../components/animations/Loading"; const Room = lazy(() => import("../components/room/Room")); const Sidebar = lazy(() => import("../components/sidebar/Sidebar")); export default function App() { const AppBody = styled(Box)({ display: "flex", backgroundColor: "#d8e3e7", height: "90vh", boxShadow: "-1px 4px 20px -6px #d8e3e7", }); return ( <Router> <AppBody> <Suspense fallback={<Loading title="Loading App Pages" />}> <Sidebar /> <Switch> <Suspense fallback={<Loading title="Loading Rooms" />}> <Route path="/rooms/:roomId" component={Room} /> </Suspense> </Switch> </Suspense> </AppBody> </Router> ); }
/** * app.js * * FooFighter.js — Primary Game Controller * * Purpose of this module is to initialize the game assets, * build game environment and entities, and emit Phaser events * (via Shout object). */ ;(function( FooFighter, Phaser, BUILDNUM ){ 'use strict'; var app, game, gameState; app = { /** * Preload game assets (spritesheets, atlas data, individuals images) * @return {void} */ preload: function(){ var entities = gameState.entities, modules = gameState.modules, background = game.add.group(), backGroup = game.add.group(), frontGroup = game.add.group(), bigAsteroids = game.add.group(), smallAsteroids = game.add.group(), enemyShips = game.add.group(), enemyUFOs = game.add.group(), lasers = game.add.group(), enemyLasers = game.add.group(), hudGroup = game.add.group(); // Keep group references so we can maintain a proper display index gameState.groups = { background: background, backGroup: backGroup, frontGroup: frontGroup, hudGroup: hudGroup, asteroids: [ bigAsteroids, smallAsteroids ], enemyShips: enemyShips, enemyUFOs: enemyUFOs, lasers: lasers, enemyLasers: enemyLasers }; game.load.bitmapFont('KenPixel', 'assets/fonts/KenPixel.png', 'assets/fonts/KenPixel.fnt'); // Grab keyboard references for keydown events gameState.cursors = game.input.keyboard.createCursorKeys(); gameState.keyboard = game.input.keyboard; // Primary spritesheet -- atlas generated by Texture Packer game.load.atlasJSONHash( 'sprites', 'assets/img/space-sheet.png?d=' + BUILDNUM, 'assets/json/space-sheet.json?d=' + BUILDNUM ); // Set scale mode to strech to browser window, but preserve aspect ratio game.stage.scaleMode = Phaser.StageScaleMode.SHOW_ALL; game.stage.scale.setShowAll(); game.stage.scale.refresh(); game.stage.backgroundColor = '#301404'; // Create discrete game objects/entities gameState.gameEngine = new FooFighter.GameEngine(gameState); modules.startScreen = new FooFighter.StartScreen(gameState, hudGroup); entities.starField = new FooFighter.StarField(gameState, background); entities.player = new FooFighter.Player(gameState, frontGroup); entities.score = new FooFighter.Score(gameState, hudGroup); entities.timer = new FooFighter.Timer(gameState, hudGroup); }, /** * Initialize game state (data, canvas, etc) * @return {void} */ create: function(){ gameState.vent.emit('create'); }, /** * Primary game loop * @return {void} */ update: function(){ gameState.vent.emit('update'); } }; game = new Phaser.Game( 1280, 768, Phaser.AUTO, 'main', { preload: app.preload, create: app.create, update: app.update } ); gameState = FooFighter._gs = new FooFighter.GameState(game); })(FooFighter, Phaser, window.BUILDNUM);
const {Rule} = require('../src') describe('number', () => { test('required constraint', async () => { const rule = Rule.number().required() await expect(rule.validate(undefined)).resolves.toMatchSnapshot( 'required: undefined' ) await expect(rule.validate(13)).resolves.toMatchSnapshot('required: valid') }) test('min constraint', async () => { const rule = Rule.number().min(10) await expect(rule.validate(3)).resolves.toMatchSnapshot('min: too low') await expect(rule.validate(10)).resolves.toMatchSnapshot( 'min: valid, at limit' ) await expect(rule.validate(20)).resolves.toMatchSnapshot('min: valid') }) test('greater than constraint', async () => { const rule = Rule.number().greaterThan(10) await expect(rule.validate(3)).resolves.toMatchSnapshot('gt: too low') await expect(rule.validate(10)).resolves.toMatchSnapshot( 'gt: too low, at limit' ) await expect(rule.validate(20)).resolves.toMatchSnapshot('gt: valid') }) test('max constraint', async () => { const rule = Rule.number().max(10) await expect(rule.validate(20)).resolves.toMatchSnapshot('max: too large') await expect(rule.validate(10)).resolves.toMatchSnapshot( 'max: valid, at limit' ) await expect(rule.validate(5)).resolves.toMatchSnapshot('max: valid') }) test('less than constraint', async () => { const rule = Rule.number().lessThan(10) await expect(rule.validate(20)).resolves.toMatchSnapshot('lt: too high') await expect(rule.validate(10)).resolves.toMatchSnapshot( 'lt: too high, at limit' ) await expect(rule.validate(3)).resolves.toMatchSnapshot('lt: valid') }) test('integer constraint', async () => { const rule = Rule.number().integer() await expect(rule.validate(31.14)).resolves.toMatchSnapshot( 'integer: invalid (float)' ) await expect(rule.validate(31)).resolves.toMatchSnapshot('integer: valid') }) test('precision constraint', async () => { const rule = Rule.number().precision(3) await expect(rule.validate(Math.PI)).resolves.toMatchSnapshot( 'precision: invalid (pi)' ) await expect(rule.validate(31.133)).resolves.toMatchSnapshot( 'precision: valid (at limit)' ) await expect(rule.validate(31.3)).resolves.toMatchSnapshot( 'precision: valid (below limit)' ) }) test('positive constraint', async () => { const rule = Rule.number().positive() await expect(rule.validate(-31.14)).resolves.toMatchSnapshot( 'positive: invalid' ) await expect(rule.validate(0)).resolves.toMatchSnapshot( 'positive: valid (zero)' ) await expect(rule.validate(13)).resolves.toMatchSnapshot('positive: valid') }) test('negative constraint', async () => { const rule = Rule.number().negative() await expect(rule.validate(31.14)).resolves.toMatchSnapshot( 'negative: invalid' ) await expect(rule.validate(0)).resolves.toMatchSnapshot( 'negative: invalid (zero)' ) await expect(rule.validate(-13)).resolves.toMatchSnapshot('negative: valid') }) })
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- function test0() { var GiantPrintArray = []; var IntArr1 = []; for(var i = 0; i < 2; ++i) { var id30 = IntArr1; IntArr1 = IntArr1.pop(); IntArr1 = id30; GiantPrintArray.push(IntArr1[IntArr1.length]); GiantPrintArray.push(test0a()); } function test0a() { try { } catch(ex) { } } }; test0(); test0(); WScript.Echo("pass");
// moment.js language configuration // language : norwegian bokmål (nb) // author : Espen Hovlandsdal : https://github.com/rexxars require('TiTools2/ThirdParty/moment').lang('nb', { months : "januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"), monthsShort : "jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"), weekdays : "søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"), weekdaysShort : "søn_man_tir_ons_tor_fre_lør".split("_"), weekdaysMin : "sø_ma_ti_on_to_fr_lø".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: '[I dag klokken] LT', nextDay: '[I morgen klokken] LT', nextWeek: 'dddd [klokken] LT', lastDay: '[I går klokken] LT', lastWeek: '[Forrige] dddd [klokken] LT', sameElse: 'L' }, relativeTime : { future : "om %s", past : "for %s siden", s : "noen sekunder", m : "ett minutt", mm : "%d minutter", h : "en time", hh : "%d timer", d : "en dag", dd : "%d dager", M : "en måned", MM : "%d måneder", y : "ett år", yy : "%d år" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var React = tslib_1.__importStar(require("react")); var StyledIconBase_1 = require("../../StyledIconBase"); exports.LocationOutline = React.forwardRef(function (props, ref) { var attrs = { "fill": "currentColor", }; return (React.createElement(StyledIconBase_1.StyledIconBase, tslib_1.__assign({ iconAttrs: attrs, iconVerticalAlign: "middle", iconViewBox: "0 0 24 24" }, props, { ref: ref }), React.createElement("path", { d: "M12 5c1.609 0 3.12.614 4.254 1.73C17.38 7.837 18 9.309 18 10.87s-.62 3.03-1.745 4.139L12 19.193l-4.254-4.186c-1.125-1.107-1.745-2.576-1.745-4.139s.62-3.032 1.745-4.141A6.04 6.04 0 0 1 12 5m0-2a8.04 8.04 0 0 0-5.657 2.305 7.782 7.782 0 0 0 0 11.131L12 21.999l5.657-5.565a7.78 7.78 0 0 0 0-11.129A8.039 8.039 0 0 0 12 3zm0 5.499c.668 0 1.296.26 1.768.731a2.502 2.502 0 0 1 0 3.537c-.473.472-1.1.731-1.768.731s-1.295-.26-1.768-.731a2.502 2.502 0 0 1 0-3.537A2.49 2.49 0 0 1 12 8.499m0-1a3.501 3.501 0 1 0 2.475 5.975 3.503 3.503 0 0 0 0-4.951A3.489 3.489 0 0 0 12 7.499z", key: "k0" }))); }); exports.LocationOutline.displayName = 'LocationOutline'; exports.LocationOutlineDimensions = { height: 24, width: 24 };
import { onMounted, ref } from 'vue'; import { detectFlexGapSupported } from '../styleChecker'; export default (function () { var flexible = ref(false); onMounted(function () { flexible.value = detectFlexGapSupported(); }); return flexible; });
"use strict"; $(document).ready(function(){ $('#auto-fill').DataTable( { autoFill: true } ); $('#keytable').DataTable( { keys: true, autoFill: true } ); $('#column-selector').DataTable( { columnDefs: [ { orderable: false, className: 'select-checkbox', targets: 0 } ], select: { style: 'os', selector: 'td:first-child' }, order: [[ 1, 'asc' ]], autoFill: { columns: ':not(:first-child)' } } ); var table = $('#scrolling-datatable').dataTable( { scrollY: 400, scrollX: true, scrollCollapse: true, paging: false, autoFill: true } ); var table = $('#basic-row-reorder').DataTable( { rowReorder: true } ); //full row selection var table = $('#full-row').DataTable( { rowReorder: { selector: 'tr' }, columnDefs: [ { targets: 0, visible: false } ] } ); // Restricted column ordering var table = $('#rest-column').DataTable( { rowReorder: true, columnDefs: [ { orderable: true, className: 'reorder', targets: 0 }, { orderable: false, targets: '_all' } ] } ); $('#export-button').DataTable( { dom: 'Bfrtip', buttons: [ 'copyHtml5', 'excelHtml5', 'csvHtml5', 'pdfHtml5' ] } ); $('#column-selector').DataTable( { dom: 'Bfrtip', buttons: [ { extend: 'copyHtml5', exportOptions: { columns: [ 0, ':visible' ] } }, { extend: 'excelHtml5', exportOptions: { columns: ':visible' } }, { extend: 'pdfHtml5', exportOptions: { columns: [ 0, 1, 2, 5 ] } }, 'colvis' ] } ); $('#excel-cust-bolder').DataTable( { dom: 'Bfrtip', buttons: [ { extend: 'excelHtml5', customize: function ( xlsx ){ var sheet = xlsx.xl.worksheets['sheet1.xml']; // jQuery selector to add a border $('row c[r*="10"]', sheet).attr( 's', '25' ); } } ] } ); $('#cust-json').DataTable( { dom: 'Bfrtip', buttons: [ { text: 'JSON', action: function ( e, dt, button, config ) { var data = dt.buttons.exportData(); $.fn.dataTable.fileSave( new Blob( [ JSON.stringify( data ) ] ), 'Export.json' ); } } ] } ); $('#basic-key-table').DataTable( { keys: true } ); var table = $('#scrolling').DataTable( { scrollY: 300, paging: false, keys: true } ); $('#focus-cell').DataTable( { keys: true } ); $('#basic-scroller').DataTable( { ajax: "../assets/json/datatable-extension/data.txt", deferRender: true, scrollY: 200, scrollCollapse: true, scroller: true } ); $('#state-saving').DataTable( { ajax: "../assets/json/datatable-extension/data.txt", deferRender: true, scrollY: 200, scrollCollapse: true, scroller: true, stateSave: true } ); $('#api').DataTable( { ajax: "../assets/json/datatable-extension/data.txt", deferRender: true, scrollY: 200, scrollCollapse: true, scroller: true, initComplete: function () { this.api().row( 1000 ).scrollTo(); } } ); $('#responsive').DataTable( { responsive: true } ); var table = $('#new-cons').DataTable(); // new $.fn.dataTable.Responsive( table ); $('#show-hidden-row').DataTable( { responsive: { details: { display: $.fn.dataTable.Responsive.display.childRowImmediate, type: '' } } } ); $('#basic-colreorder').DataTable( { colReorder: true } ); $('#state-saving').dataTable( { colReorder: true, stateSave: true } ); $('#real-time').dataTable( { colReorder: { realtime: false } } ); $('#custom-button').DataTable( { dom: 'Bfrtip', buttons: [ { text: 'Add to cart', action: function ( e, dt, node, config ) { alert( 'Button activated' ); } } ] } ); $('#class-button').DataTable( { dom: 'Bfrtip', buttons: [ { text: 'Secondary', className: 'btn-secondary' }, { text: 'Success', className: 'btn-success' }, { text: 'Danger', className: 'btn-danger' } ] } ); $('#keyboard-btn').DataTable( { dom: 'Bfrtip', buttons: [ { text: 'Button <u>1</u>', key: '1', action: function ( e, dt, node, config ) { alert( 'Button 1 activated' ); } }, { text: 'Button <u><i>shift</i> 2</u>', key: { shiftKey: true, key: '2' }, action: function ( e, dt, node, config ) { alert( 'Button 2 activated' ); } } ] } ); $('#multilevel-btn').DataTable( { dom: 'Bfrtip', buttons: [ { extend: 'collection', text: 'Table control', buttons: [ { text: 'Toggle start date', action: function ( e, dt, node, config ) { dt.column( -2 ).visible( ! dt.column( -2 ).visible() ); } }, { text: 'Toggle salary', action: function ( e, dt, node, config ) { dt.column( -1 ).visible( ! dt.column( -1 ).visible() ); } }, 'colvis' ] } ] } ); $('#pagelength-btn').DataTable( { dom: 'Bfrtip', lengthMenu: [ [ 10, 25, 50, -1 ], [ '10 rows', '25 rows', '50 rows', 'Show all' ] ], buttons: [ 'pageLength' ] } ); $('#basic-fixed-header').DataTable( { fixedHeader: true } ); var table = $('#fixed-header-footer').DataTable( { fixedHeader: { header: true, footer: true } } ); });
import toTopButton from '../components/shared/to-top-button.vue' /** * Add a "infinite scroll" functionality to any component using this mixin. * Such a component should have a `scrolling` method bound to `scroll` event on * the wrapper element: @scroll="scrolling" */ export default { components: { toTopButton }, data () { return { numOfItems: 30, // Number of currently loaded and displayed items perPage: 30 // Number of items to be loaded per "page" } }, methods: { scrolling ({ target: { scrollTop, clientHeight, scrollHeight }}) { // Here we check if the user has scrolled to the end of the wrapper (or 32px to the end). // If that's true, load more items. if (scrollTop + clientHeight >= scrollHeight - 32) { this.displayMore() } }, /** * Load and display more items into the scrollable area. */ displayMore () { this.numOfItems += this.perPage } } }
// This is a basic example strategy for Gekko. // For more information on everything please refer // to this document: // // https://gekko.wizb.it/docs/strategies/creating_a_strategy.html // // The example below is pretty bad investment advice: on every new candle there is // a 10% chance it will recommend to change your position (to either // long or short). var log = require('../core/log'); const util = require('util'); // Let's create our own strat var strat = {}; //CHECK BACKTESTRESULTEXPORTER.JS FOR NEWEST LOGIC // const findInflection = function(range, store, candle) { // if (range % 2 !== 1) { // console.log('range must be odd number!'); // return; // } else if (store.length < range) { // console.log('not enough data points'); // return; // } // const middle = Math.floor(range / 2); // // console.log('middle is', middle); // const results = []; // let followTrend = true; // const sample = store.slice(store.length - range, store.length); // var middleVal = sample[middle].low; // // console.log('mmm', middleVal); // //verify values to left of middle are increasing // for (let i = middle - 1; i >= 0; i--) { // if (sample[i].low < sample[i + 1].low) followTrend = false; // } // //verify values to right of middle are increasing // for (let j = middle + 1; j < range; j++) { // if (sample[j].low < sample[j - 1].low) followTrend = false; // } // if (followTrend) return sample[middle]; // }; // Prepare everything our method needs strat.init = function() { this.input = 'candle'; this.currentTrend = null; this.requiredHistory = 0; this.historicalClose = []; this.inflectionPoints = []; }; // What happens on every new candle? strat.update = function(candle) { // console.log('singleCandle', candle); //add close data to to array this.historicalClose.push({ low: this.candle.low, close: this.candle.close, volume: this.candle.volume, time: this.candle.start, }); const result = findInflection(3, this.historicalClose, candle); if (result) { this.inflectionPoints.push(result); // if (this.currentTrend === null || this.currentTrend === 'short') { // this.advice('long'); // this.currentTrend = 'long'; // } else { // this.advice('short'); // this.currentTrend = 'short'; // } } // Get a random number between 0 and 1. // this.randomNumber = Math.random(); // There is a 10% chance it is smaller than 0.1 // this.toUpdate = this.randomNumber < 0.1; }; // For debugging purposes. // strat.log = function() { // log.debug('calculated random number:'); // log.debug('\t', this.randomNumber.toFixed(3)); // }; // Based on the newly calculated // information, check if we should // update or not. strat.check = function() { // Only continue if we have a new update. if (!this.toUpdate) return; // if (this.currentTrend === 'long') { // // If it was long, set it to short // this.currentTrend = 'short'; // this.advice('short'); // } else { // // If it was short, set it to long // this.currentTrend = 'long'; // this.advice('long'); // } }; strat.end = function() { //print collated historical data // console.log('historical data'); // console.log(util.inspect(this.historicalClose, { maxArrayLength: null })); // console.log('inflections', this.inflectionPoints); }; module.exports = strat;
export function randomKey () { return new Date().getTime().toString() + Math.random().toString().substring(3) }
define({"topics" : [{"title":"BigQuery Data Types","shortdesc":"\n <p class=\"shortdesc\">The Google BigQuery destination maps fields from records to BigQuery columns in existing tables based on matching\n names and compatible data types. If needed, the destination converts <span class=\"ph\">Data Collector</span> data types to BigQuery data types.\n </p>\n ","href":"datacollector\/UserGuide\/Destinations\/BigQuery.html#concept_edg_kwm_3bb","attributes": {"data-id":"concept_edg_kwm_3bb",},"menu": {"hasChildren":false,},"tocID":"concept_edg_kwm_3bb-d46e97053","topics":[]},{"title":"Credentials","href":"datacollector\/UserGuide\/Destinations\/BigQuery.html#concept_ym2_mww_hbb","attributes": {"data-id":"concept_ym2_mww_hbb",},"menu": {"hasChildren":true,},"tocID":"concept_ym2_mww_hbb-d46e97081","next":"concept_ym2_mww_hbb-d46e97081",},{"title":"Configuring a Google BigQuery Destination","href":"datacollector\/UserGuide\/Destinations\/BigQuery.html#task_gxn_dsk_dbb","attributes": {"data-id":"task_gxn_dsk_dbb",},"menu": {"hasChildren":false,},"tocID":"task_gxn_dsk_dbb-d46e97210","topics":[]}]});
import { act } from 'react-dom/test-utils'; import { mountPage, preflight200, preflight400, preflight403, } from '../../Utilities/tests/helpers'; import fetchMock from 'fetch-mock-jest'; import OrganizationStatistics from './OrganizationStatistics'; const chartRoots = [ 'd3-grouped-bar-chart-root', 'd3-donut-1-chart-root', 'd3-donut-2-chart-root', ]; const jobExplorerUrl = 'path:/api/tower-analytics/v1/job_explorer/'; const dummyOrgData = (size) => ({ dates: [...Array(size).keys()].map((el) => ({ items: [...Array(size).keys()].map((i) => ({ id: i - 1, total_count: i * el, name: i === 0 ? '' : 'org name', })), date: new Date(), })), }); const dummyPieData = (size) => ({ items: [...Array(size).keys()].map((i) => ({ id: i - 1, host_count: i * 10, name: i === 0 ? '' : 'org name', })), }); const hostExplorerUrl = 'path:/api/tower-analytics/v1/host_explorer/'; const dummyHostsData = (size) => ({ dates: [...Array(size).keys()].map((el) => ({ items: [...Array(size).keys()].map((i) => ({ id: i - 1, total_count: i * el, name: i === 0 ? '' : 'org name', host_task_count: 8000, total_org_count: 1, total_unique_host_count: 100, })), date: new Date(), })), }); const jobExplorerOptionsUrl = 'path:/api/tower-analytics/v1/dashboard_organization_statistics_options/'; const jobExplorerOptions = { quick_date_range: [ { key: 'last_30_days', value: 'Last 30 days' }, { key: 'last_2_weeks', value: 'Last 2 weeks' }, { key: 'last_week', value: 'Last week' }, { key: 'last_72_hours', value: 'Last 72 hours' }, { key: 'last_24_hours', value: 'Last 24 hours' }, { key: 'custom', value: 'Custom' }, ], }; const defaultQueryParams = { group_by: 'org', quick_date_range: 'last_30_days', limit: 5, offset: 0, job_type: ['workflowjob', 'job'], cluster_id: [], start_date: null, end_date: null, org_id: [], status: [], template_id: [], inventory_id: [], }; const defaultHostsQueryParams = { status: [], org_id: [], quick_date_range: 'last_30_days', limit: 5, offset: 0, job_type: ['workflowjob', 'job'], cluster_id: [], template_id: [], inventory_id: [], start_date: null, end_date: null, }; const lastCallBody = (url) => JSON.parse(fetchMock.lastCall(url)[1].body); describe('Containers/OrganizationStatistics', () => { let wrapper; beforeEach(() => { chartRoots.forEach((item) => { let d3Container = document.createElement('div'); d3Container.setAttribute('id', item); document.body.appendChild(d3Container); }); fetchMock.get({ ...preflight200 }); fetchMock.post( { url: jobExplorerUrl, body: { group_by: 'org', group_by_time: true }, matchPartialBody: true, }, { ...dummyOrgData(5) } ); fetchMock.post( { url: jobExplorerUrl, body: { group_by: 'org', include_others: true }, matchPartialBody: true, overwriteRoutes: false, }, { ...dummyPieData(5) } ); fetchMock.post({ url: jobExplorerOptionsUrl }, { ...jobExplorerOptions }); fetchMock.post({ url: hostExplorerUrl }, { ...dummyHostsData(5) }); }); afterEach(() => { chartRoots.forEach((item) => { let d3Container = document.getElementById(item); d3Container.remove(); }); fetchMock.restore(); wrapper = null; }); it('should render without any errors', async () => { await act(async () => { wrapper = mountPage(OrganizationStatistics); }); wrapper.update(); expect(wrapper).toBeTruthy(); }); it('should render with data', async () => { await act(async () => { wrapper = mountPage(OrganizationStatistics); }); wrapper.update(); expect(wrapper.text()).not.toEqual(expect.stringContaining('*No Data*')); expect(wrapper.text()).not.toEqual(expect.stringContaining('*Loading*')); }); it('should render preflight error', async () => { fetchMock.get({ ...preflight400, overwriteRoutes: true }); await act(async () => { wrapper = mountPage(OrganizationStatistics); }); wrapper.update(); expect(wrapper.text()).toEqual(expect.stringContaining('Not authorized')); }); it('should render RBAC Access error', async () => { fetchMock.get({ ...preflight403, overwriteRoutes: true }); await act(async () => { wrapper = mountPage(OrganizationStatistics); }); wrapper.update(); expect(wrapper.text()).toEqual( expect.stringContaining('RBAC Access Denied') ); }); it('should render api error', async () => { fetchMock.post({ url: jobExplorerUrl, overwriteRoutes: true, response: { throws: { error: 'General Error' }, status: 400 }, }); await act(async () => { wrapper = mountPage(OrganizationStatistics); }); wrapper.update(); expect(wrapper.text()).toEqual(expect.stringContaining('General Error')); }); it('should render with empty response', async () => { fetchMock.post({ url: jobExplorerUrl, overwriteRoutes: true }, {}); await act(async () => { wrapper = mountPage(OrganizationStatistics); }); wrapper.update(); expect(wrapper.text()).toEqual(expect.stringContaining('No Data')); }); it('should send the default queryParams', async () => { await act(async () => { wrapper = mountPage(OrganizationStatistics); }); wrapper.update(); const { sort_by, attributes, granularity, include_others, ...rest } = lastCallBody(jobExplorerUrl); expect(sort_by.split(':')[1]).toBe('desc'); expect(rest).toEqual(defaultQueryParams); }); it('should handle the tab switching correctly', async () => { await act(async () => { wrapper = mountPage(OrganizationStatistics); }); wrapper.update(); const tabs = wrapper.find('.pf-c-tabs__link'); // Click on the hosts tab await act(async () => { tabs.at(2).simulate('click'); }); wrapper.update(); // Wait for the call to hosts options and hosts data const checkHostsCall = () => { const { sort_by, attributes, granularity, group_by, group_by_time, ...rest } = lastCallBody(hostExplorerUrl); expect(rest).toEqual(defaultHostsQueryParams); }; checkHostsCall(); // Click on the orgs tab await act(async () => { tabs.at(0).simulate('click'); }); wrapper.update(); // Wait for the calls for the orgs options and orgs data const checkOrgsCall = () => { const { sort_by, attributes, granularity, group_by_time, ...rest } = lastCallBody(jobExplorerUrl); expect(rest).toEqual(defaultQueryParams); }; checkOrgsCall(); }); xit('shoud redirect to the job explorer page with the correct params', async () => { // This test is not possible to run, since the d3 is not rendering // in enzyme. await act(async () => { wrapper = mountPage(OrganizationStatistics); }); wrapper.update(); // Click on a bar which is not an other // Wait last call to be to JobExplorer page }); xit('should not redirect to job explorer clicking on the hosts chart', async () => { // This test is not possible to run, since the d3 is not rendering // in enzyme. await act(async () => { wrapper = mountPage(OrganizationStatistics); }); wrapper.update(); // Click on the hosts chart // Click on the bar // Await no new call }); });