code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
angular.module('CareFull', ['ui.router','rzModule']);
danielcaldas/carefull
public/app/modules.js
JavaScript
gpl-3.0
54
{"exchanges":[{"info":[{"onclick":null,"link":"mailto:[email protected]","value":"[email protected] Monica Arensi, General Secretary"},{"onclick":null,"link":null,"value":"39 02 409 15701"},{"onclick":null,"link":"mailto:[email protected]","value":"[email protected]"},{"onclick":"window.open(this.href,'ix-new-window');return false;","link":"http://www.mix-it.net","value":"Website"},{"onclick":null,"link":null,"value":"Online since: 1996"}],"slug":"mix-it-milan-italy","name":"MIX-IT"}],"address":["Via Caldera 21 D3","Via Caldera 21","D3","Milan, Italy"],"id":18863}
brangerbriz/webroutes
nw-app/telegeography-data/internetexchanges/buildings/18863.js
JavaScript
gpl-3.0
563
import React, { Component } from 'react' import PropTypes from 'prop-types' import ModalsContainer from '../containers/ModalsContainer' import { bytesToSize } from '../common' const Store = window.require('electron-store') import './ViewSwitcher.css' class PersonalFiles extends Component { constructor(props) { super(props) this.onSearchInputChange = this.onSearchInputChange.bind(this) this.selectFile = this.selectFile.bind(this) this.isSelected = this.isSelected.bind(this) this.refresh = this.refresh.bind(this) this.handleCancelRestore = this.handleCancelRestore.bind(this) this.handleValidateRestore = this.handleValidateRestore.bind(this) this.store = new Store() this.state = { searchTerm: '', matchingFiles: [], target_directory: '/', refresh: 0, lock: false, } } componentDidMount() { this.props.dispatch.init() clearInterval(this.interval) this.interval = setInterval(this.refresh, 250) } componentWillUnmount() { this.props.dispatch.end() clearInterval(this.interval) } shouldComponentUpdate(nextProps, nextState) { if(nextProps.state.files !== this.props.state.files) this.setState(Object.assign(this.state, {lock: false})) if(nextProps.state.socket.loading && !this.props.state.socket.loading && nextProps.state.view.loading_animation) return true if(!nextState.lock && nextProps.state.view.loading_animation && !this.props.state.view.loading_animation) return true if(nextProps.state.breadcrumb[nextProps.state.breadcrumb.length - 1].route !== this.props.state.breadcrumb[this.props.state.breadcrumb.length - 1].route) return true var newFiles = [] for (var i = nextProps.state.files.length - 1; i >= 0; i--) { newFiles.push([nextProps.state.files[i].path, nextProps.state.files[i].type]) } var oldFiles = [] for (i = this.props.state.files.length - 1; i >= 0; i--) { oldFiles.push([this.props.state.files[i].path, this.props.state.files[i].type]) } if(newFiles.length !== oldFiles.length || (newFiles.length > 1 && newFiles.every(function(item, i) {return item[0] !== oldFiles[i][0] || item[1] !== oldFiles[i][1]}))) return true var newSelectedFiles = [] for (i = nextProps.state.selection.selected.length - 1; i >= 0; i--) { newSelectedFiles.push([nextProps.state.selection.selected[i].path, nextProps.state.selection.selected[i].type]) } var oldSelectedFiles = [] for (i = this.props.state.selection.selected.length - 1; i >= 0; i--) { oldSelectedFiles.push([this.props.state.selection.selected[i].path, this.props.state.selection.selected[i].type]) } if(newSelectedFiles.length !== oldSelectedFiles.length || (newSelectedFiles.length > 1 && newSelectedFiles.every(function(item, i) {return item[0] !== oldSelectedFiles[i][0] || item[1] !== oldSelectedFiles[i][1]}))) return true return false } refresh() { var new_refresh_state = 0 if(this.state.refresh >= 12) new_refresh_state = 0 else new_refresh_state = this.state.refresh + 1 this.setState(Object.assign(this.state, {refresh: new_refresh_state})) if(this.state.target_directory === this.props.state.breadcrumb[this.props.state.breadcrumb.length - 1].route && new_refresh_state !== 1) return var animate = false var target_directory = this.props.state.breadcrumb[this.props.state.breadcrumb.length - 1].route if(this.state.target_directory !== target_directory) { target_directory = this.state.target_directory animate = true } if(!this.state.lock) { this.setState(Object.assign(this.state, {lock: true})) this.props.dispatch.listDir(target_directory, animate) } } onSearchInputChange(event, route) { var grep = function(what, where, callback) { console.log('onSearchInputChange') console.log(route) console.log(what) console.log(where) var exec = window.require('child_process').exec; where = where.replace(' ', '\\ ') console.log(where) exec('grep -l ' + what + ' ' + where + ' 2> /dev/null', function(err, stdin, stdout) { console.log('GREP') console.log(stdin) console.log(stdout) console.log(err) var results = stdin.split('\n') console.log('RES') console.log(results) console.log('RES2') results.pop() console.log(results) callback(results) }); } var target = event.target.value console.log('SEARCH IN') if (target.toLowerCase() === '') { console.log('EMPTY TARGET') this.setState({ matchingFiles: [], searchTerm: target.toLowerCase() }) } else { if (!route.endsWith('/')) route += '/' grep(target, route + '*.txt', function(list) { this.setState({ matchingFiles: list, searchTerm: target.toLowerCase() }) console.log('MATCHING') console.log(list) }.bind(this)) } } isSelected(file) { for(var i = 0; i < this.props.state.selection.selected.length; i++) { if(this.props.state.selection.selected[i].path === file.path) { // console.log(file.path + ' selected') return true } } return false } selectFile(event, file) { const selected = !this.isSelected(file) this.props.dispatch.selectFile(file, selected) } handleCancelRestore(event) { this.props.dispatch.restoring(false) } handleValidateRestore(event) { } render() { var files = this.props.state.files const selected = this.props.state.selection.selected const view = this.props.state.view const loading = this.props.state.socket.loading const loading_animation = this.props.state.view.loading_animation const breadcrumb = this.props.state.breadcrumb this.currentPath = breadcrumb[breadcrumb.length -1] const openFile = this.props.dispatch.openFile files.sort((a, b) => { if(a.type === 'folder' && b.type === 'file') return -1 else if (a.type === 'file' && b.type === 'folder') return 1 if (a.name > b.name) return 1 if (b.name > a.name) return -1 return 0 }) let displayedFiles = files.filter(file => { // console.log('filtre') // console.log(this.state.searchTerm) // console.log(this.state.matchingFiles) return this.state.searchTerm === '' || file.name.toLowerCase().includes(this.state.searchTerm) || this.state.matchingFiles.indexOf(file.mountpoint) !== -1 }) class IconFormatter extends React.Component { static propTypes = { file: PropTypes.object.isRequired } render() { const file = this.props.file var re = /(?:\.([^.]+))?$/ var type = re.exec(file['name'])[1] const icons = { folder: 'fa-folder-o', file: 'fa-file-o', zip: 'fa-file-archive-o', mp3: 'fa-file-audio-o', py: 'fa-file-code-o', xls: 'fa-file-excel-o', jpg: 'fa-file-image-o', pdf: 'fa-file-pdf-o', txt: 'fa-file-text-o', avi: 'fa-file-video-o', doc: 'fa-file-word-o' } if (type === undefined || !(type in icons) || file['type'] === 'folder') type = file['type'] return ( <div className='icon'> <i className={'fa ' + icons[type]}/> </div> ) } } const ListFiles = () => { if(loading && loading_animation) return (<div id="loader-wrapper"><div id="loader"></div></div>) if(files.length === 0) return ( <div className="empty-list"> <i className="fa fa-folder-open-o"/> <h1>This folder is empty</h1> </div> ) const listFiles = displayedFiles.map((file) => { const details = file.type === 'file' ? bytesToSize(file['size']) : file.children.length + ' element' + (file.children.length > 1 ? 's' : '') const hidden = (selected.length === 0) ? 'hidden' : '' var selected_file = this.isSelected(file) return ( <a key={file.path} onClick={(event) => { if(selected.length === 0) { if(file.type === 'folder') { this.setState(Object.assign(this.state, {target_directory: file.path})) } else { openFile(file) } } else { this.selectFile(event, file) } }}> <li className="file-item" id={file.path}> <input className={hidden} id={'select_' + file.path} name={file.path} type="checkbox" title={selected_file ? 'Deselect' : 'Select'} onClick={(event) => {this.selectFile(event, file); event.stopPropagation()}} checked={selected_file} readOnly/> <IconFormatter file={file}/> <div className="title">{file.name}</div> <div className="details">{details}</div> </li> </a> ) }) return ( <div className={view.list ? 'file-view list-view' : 'file-view grid-view'}> <ul>{ listFiles }</ul> </div> ) } return ( <div className="view-switcher"> <div className="header"> <div className="title"> Personal Files </div> <div className="search"> <span className="fa fa-search"></span> <input onKeyUp={(event) => this.onSearchInputChange(event, this.store.get('mountpoint', '') + this.currentPath.route)} placeholder="Search"/> </div> <div className="breadcrumb"> <ul> <li> <div className="dropdown-content"> {breadcrumb.map((path, i) => <button key={path.route} onClick={() => {this.setState(Object.assign(this.state, {target_directory: path.route}))}} className={`button path-button ${i === 0 ? 'first-path-button' : ''} ${(i + 1) === breadcrumb.length ? 'last-path-button' : ''}`}>{(i + 1) === breadcrumb.length ? <i className="fa fa-folder-open"/> : ''} {path.libelle}</button> )} </div> </li> </ul> </div> <div className="clear"></div> </div> { ListFiles() } <ModalsContainer></ModalsContainer> </div> ) } } export default PersonalFiles
Scille/parsec-gui
src/components/PersonalFiles.js
JavaScript
gpl-3.0
10,526
import { check } from "meteor/check"; import processDoc from "./processDoc"; /** * getDoc * fetch repo profile from github and store in RepoData collection * @param {Object} doc - mongo style selector for the doc * @returns {undefined} returns */ function getDoc(options) { check(options, Object); // get repo details const docRepo = ReDoc.Collections.Repos.findOne({ repo: options.repo }); // we need to have a repo if (!docRepo) { console.log(`redoc/getDocSet: Failed to load repo data for ${options.repo}`); return false; } // TOC item for this doc const tocItem = ReDoc.Collections.TOC.findOne({ alias: options.alias, repo: options.repo }); processDoc({ branch: options.branch, repo: options.repo, alias: options.alias, docRepo, tocItem }); } export default getDoc; export { flushDocCache };
reactioncommerce/redoc
packages/redoc-core/server/methods/getDoc.js
JavaScript
gpl-3.0
875
/* Um carro, e só */ class Car { constructor(posx, posy, width, height, lifeTime, color) { this.x = posx; this.y = posy; this.lifeTime = lifeTime; this.color = color; this.width = width; this.height = height; this.im = new Image(); this.im.src = carSprite.src; } draw(ctx) { ctx.save(); ctx.fillStyle = this.color; ctx.lineWidth = 1; ctx.drawImage( this.im, carSprite.x, carSprite.y, carSprite.w, carSprite.h, this.x, this.y, this.width, this.height ); } }
Juliano-rb/CrossChallenge
js/basegame/car.js
JavaScript
gpl-3.0
724
var _engine_core_8h = [ [ "EngineCore", "class_ludo_1_1_engine_core.html", "class_ludo_1_1_engine_core" ], [ "LD_EXPORT_ENGINE_CORE", "_engine_core_8h.html#a0ced60c95a44fd7969a8d0b789257241", null ] ];
TwinDrills/Ludo
Docs/html/_engine_core_8h.js
JavaScript
gpl-3.0
209
(function () { 'use strict'; angular.module('ph.account') // http://bartwullems.blogspot.hu/2015/02/angular-13-pending.html .directive("isUniqueEmailAddress", ['$q', '$http', function ($q, $http) { return { restrict: "A", require: "ngModel", link: function (scope, element, attributes, ngModel) { ngModel.$asyncValidators.isUnique = function (modelValue, viewValue) { return $http.post('/api/v0/email-address-check', {emailAddress: viewValue}).then( function (response) { if (!response.data.validEmailAddress) { return $q.reject(response.data.errorMessage); } return true; } ); }; } }; }]); })();
indr/phundus-spa
app/modules/account/directives/is-unique-email-address.js
JavaScript
gpl-3.0
796
function drawBall() { ctx.beginPath(); ctx.arc(x, y, ballRadius, 0, Math.PI*2); ctx.fillStyle = color; ctx.strokeStyle = "#FF0000"; ctx.stroke(); ctx.fill(); ctx.closePath(); }
zacharyacutey/zacharyacutey.github.io
Breakout/ball.js
JavaScript
gpl-3.0
216
/* Nodics - Enterprice Micro-Services Management Framework Copyright (c) 2017 Nodics All rights reserved. This software is the confidential and proprietary information of Nodics ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only in accordance with the terms of the license agreement you entered into with Nodics. */ const _ = require('lodash'); const RequireFromString = require('require-from-string'); module.exports = { /** * This function is used to initiate entity loader process. If there is any functionalities, required to be executed on entity loading. * defined it that with Promise way * @param {*} options */ init: function (options) { return new Promise((resolve, reject) => { resolve(true); }); }, /** * This function is used to finalize entity loader process. If there is any functionalities, required to be executed after entity loading. * defined it that with Promise way * @param {*} options */ postInit: function (options) { return new Promise((resolve, reject) => { resolve(true); }); }, getClass: function (request) { return new Promise((resolve, reject) => { let className = request.className; SERVICE.DefaultClassConfigurationService.get({ tenant: 'default', query: { code: className } }).then(success => { let classDefinition = 'No data found for class: ' + className; if (success.result && success.result.length > 0 && success.result[0].body) { classDefinition = success.result[0].body.toString('utf8'); classDefinition = classDefinition.replaceAll('\n', '').replaceAll("\"", ""); } resolve(classDefinition); }).catch(error => { reject(error); }); }); }, getSnapshot: function (request) { return new Promise((resolve, reject) => { let className = request.className; let type = request.type; if (!type || !global[type]) { reject(new CLASSES.NodicsError('ERR_SYS_00001', 'Invlid type: ' + type)); } else if (!className || !global[type][className.toUpperCaseFirstChar()]) { reject(new CLASSES.NodicsError('ERR_SYS_00001', 'Invlid className: ' + className)); } else { var cache = []; let finalClassData = JSON.stringify(global[type][className.toUpperCaseFirstChar()], function (key, value) { if (typeof value === 'object' && value !== null) { if (cache.indexOf(value) !== -1) { return; } cache.push(value); } if (typeof value === 'function') { return value.toString(); } else if (typeof value === 'string') { return '\'' + value + '\''; } else { return value; } }, 4); resolve('module.exports = ' + finalClassData.replace(/\\n/gm, '\n').replace(/\\t/gm, '').replaceAll("\"", "") + ';'); } }); }, updateClass: function (request) { return new Promise((resolve, reject) => { let className = request.className; let type = request.type; this.finalizeClass(className, request.body).then(success => { this.save({ tenant: 'default', model: { code: className, type: type, active: true, body: success } }).then(success => { resolve(success); }).catch(error => { reject(error); }); }).catch(error => { reject(error); }); }); }, finalizeClass: function (className, body) { let byteBody = null; return new Promise((resolve, reject) => { SERVICE.DefaultClassConfigurationService.get({ tenant: 'default', query: { code: className } }).then(success => { if (success.result && success.result.length > 0 && success.result[0].body) { let currentClassBody = RequireFromString('module.exports = ' + body.replace(/\\n/gm, '\n').replaceAll("\"", "") + ';'); let mergedClass = _.merge(RequireFromString(success.result[0].body.toString('utf8')), currentClassBody); let finalClassData = JSON.stringify(mergedClass, function (key, value) { if (typeof value === 'function') { return value.toString(); } else if (typeof value === 'string') { return '\'' + value + '\''; } else { return value; } }, 4); finalClassData = 'module.exports = ' + finalClassData.replace(/\\n/gm, '\n').replace(/\\t/gm, '').replaceAll("\"", "") + ';'; byteBody = Buffer.from(finalClassData, 'utf8'); } else { byteBody = Buffer.from('module.exports = ' + body + ';', 'utf8'); } resolve(byteBody); }).catch(error => { reject(error); }); }); }, classUpdateEventHandler: function (request) { return new Promise((resolve, reject) => { if (!request.event.data.models || request.event.data.models.length <= 0) { reject(new CLASSES.NodicsError('ERR_SYS_00001', 'ClassName can not be null or empty')); } this.get({ tenant: 'default', query: { code: { $in: request.event.data.models } } }).then(success => { if (success.result && success.result.length > 0) { success.result.forEach(classData => { let classObject = RequireFromString(classData.body.toString('utf8')); if (global[classData.type]) { if (global[classData.type][classData.code.toUpperCaseFirstChar()]) { global[classData.type][classData.code.toUpperCaseFirstChar()] = _.merge( GLOBAL[classData.type][classData.code.toUpperCaseFirstChar()], classObject); } else { global[classData.type][classData.code.toUpperCaseFirstChar()] = classObject; } this.LOG.debug('Successfully updated class: ' + classData.code); resolve('Successfully updated class: ' + classData.code); } else { this.LOG.error('Invalid type: ' + classData.code); reject(new CLASSES.NodicsError('ERR_SYS_00001', 'Invalid type: ' + classData.type)); } }); } else { this.LOG.error('Could not found any data for class name ' + request.event.data.models); reject(new CLASSES.NodicsError('ERR_SYS_00001', 'Could not found any data for class name ' + request.event.data.models)); } }).catch(error => { reject(error); }); }); }, loadPersistedClasses: function () { return new Promise((resolve, reject) => { this.get({ tenant: 'default' }).then(success => { try { if (success.result && success.result.length > 0) { success.result.forEach(classModel => { let classBody = RequireFromString(classModel.body.toString('utf8')); if (global[classModel.type][classModel.code.toUpperCaseFirstChar()]) { global[classModel.type][classModel.code.toUpperCaseFirstChar()] = _.merge( global[classModel.type][classModel.code.toUpperCaseFirstChar()], classBody ); } else { global[classModel.type][classModel.code.toUpperCaseFirstChar()] = classBody; } }); } resolve(true); } catch (error) { reject(error); } }).catch(error => { reject(error); }); }); }, executeClass: function (request) { return new Promise((resolve, reject) => { if (!request.body.className) { reject(new CLASSES.NodicsError('ERR_SYS_00001', 'ClassName can not be null or empty')); } else if (!request.body.type || !GLOBAL[request.body.type]) { reject(new CLASSES.NodicsError('ERR_SYS_00001', 'Invalid type: ' + request.body.type + ' it should not be null, empty or wrong value')); } else if (!GLOBAL[request.body.type][request.body.className.toUpperCaseFirstChar()]) { reject(new CLASSES.NodicsError('ERR_SYS_00001', 'Class: ' + request.body.className + ' not exist, please validate your request')); } else if (!request.body.operationName || !GLOBAL[request.body.type][request.body.className.toUpperCaseFirstChar()][request.body.operationName]) { reject(new CLASSES.NodicsError('ERR_SYS_00001', 'Operation name: ' + request.body.operationName + ' can not be null or empty')); } else { let entityString = request.body.type + '.' + request.body.className.toUpperCaseFirstChar() + '.' + request.body.operationName; entityString = entityString + '('; if (request.body.params && request.body.params.length > 0) { for (let counter = 0; counter < request.body.params.length; counter++) { entityString = entityString + 'request.body.params[' + counter + ']'; if (counter <= request.body.params.length - 1) { entityString = entityString + ','; } } } entityString = entityString + ')'; if (request.body.isReturnPromise) { eval(entityString).then(success => { resolve(success); }).catch(error => { reject(error); }); } else { try { let response = eval(entityString); if (!response) response = 'void'; resolve({ message: 'Successfully executed operation: ' + request.body.operationName + ' from class: ' + request.body.className, response: response }); } catch (error) { reject(new CLASSES.NodicsError(error, null, 'ERR_SYS_00000')); } } } }); } };
Nodics/nodics
gFramework/nDynamo/src/service/class/defaultClassConfigurationService.js
JavaScript
gpl-3.0
11,955
const {series} = require("gulp"), bump = require("./gulp_modules/task-bump"), bump_minor = require("./gulp_modules/task-bump-minor"), bump_major = require("./gulp_modules/task-bump-major"), readme = require("./gulp_modules/task-readme"), replace_version = require("./gulp_modules/task-replace-version"), make_pot = series(replace_version, require("./gulp_modules/task-pot")), // pot = series(make_pot, require("./gulp_modules/task-clean-pot")), pot = make_pot, pomo = series(pot, require("./gulp_modules/task-tivwp_pomo")), sass = require("./gulp_modules/task-sass"), uglify = require("./gulp_modules/task-uglify"), product_info = require("./gulp_modules/task-product-info"), dist = series(readme, sass, uglify, product_info, pomo) ; exports.bump = bump; exports.bump_minor = bump_minor; exports.bump_major = bump_major; exports.readme = readme; exports.replace_version = replace_version; exports.pot = pot; exports.pomo = pomo; exports.sass = sass; exports.uglify = uglify; exports.dist = dist; exports.default = exports.dist;
WPGlobus/WPGlobus
Gulpfile.js
JavaScript
gpl-3.0
1,044
var createFakeModel = function () { return sinon.createStubInstance(Backbone.Model); }; var createFakeCollection = function () { return sinon.createStubInstance(Backbone.Collection); }; requireMock.requireWithStubs( { 'models/SearchParamsModel': sinon.stub().returns(createFakeModel()), 'collections/SearchResultsCollection': sinon.stub().returns(createFakeCollection()) }, [ 'views/right_column/results_footer/PaginationControlsView', 'collections/SearchResultsCollection', 'models/SearchParamsModel', 'lib/Mediator' ], function ( PaginationControlsView, SearchResultsCollection, SearchParamsModel, Mediator ) { describe('Pagination Controls View', function () { var mediator, resultsCollection, searchParamsModel, view; beforeEach(function () { mediator = sinon.stub(new Mediator()); resultsCollection = new SearchResultsCollection(); resultsCollection.getLastPageNumber = sinon.stub().returns(7); resultsCollection.getPageNumber = sinon.stub().returns(4); resultsCollection.getTotalResultsCount = sinon.stub().returns(10); searchParamsModel = new SearchParamsModel(); searchParamsModel.setPageNumber = sinon.spy(); searchParamsModel.get = sinon.stub(); view = new PaginationControlsView({ collection: resultsCollection, model: searchParamsModel }); view.setMediator(mediator); view.render(); }); describe('Basic rendering and appearance', function () { it('creates a container element with class .pagination', function () { expect(view.$el).toHaveClass('pagination'); }); it('has a first page button', function () { expect(view.$('a[title="Go to page 1"]').length).toEqual(1); }); it('has a last page button', function () { expect(view.$('a[title="Go to page 7"]').length).toEqual(1); }); it('has a previous page button', function () { expect(view.$('a.prev').length).toEqual(1); }); it('has a next page button', function () { expect(view.$('a.next').length).toEqual(1); }); }); describe('the visible page numbers with 7 pages of results', function () { var range, options; // key: current page // value: the page numbers that should be visible and clickable options = { 1: [1, 2, 7], 2: [1, 2, 3, 7], 3: [1, 2, 3, 4, 7], 4: [1, 2, 3, 4, 5, 6, 7], 5: [1, 4, 5, 6, 7], 6: [1, 5, 6, 7], 7: [1, 6, 7] }; range = [1, 2, 3, 4, 5, 6, 7]; _.each(options, function (visiblePages, currentPage) { it('gives links for pages ' + visiblePages + ' and only those pages when on page ' + currentPage, function () { var hiddenPages = _.difference(range, visiblePages); resultsCollection.getPageNumber = sinon.stub().returns(currentPage); view.render(); _.each(visiblePages, function (visiblePage) { expect(view.$el.html()).toContain('title="Go to page ' + visiblePage + '"'); }); _.each(hiddenPages, function (hiddenPage) { expect(view.$el.html()).not.toContain('title="Go to page ' + hiddenPage + '"'); }); }); }); }); describe('a single page of results', function () { beforeEach(function () { resultsCollection.getLastPageNumber = sinon.stub().returns(1); resultsCollection.getPageNumber = sinon.stub().returns(1); }); it('is hidden', function () { view.onSearchComplete(); expect(view.$el).toHaveClass('hidden'); }); }); describe('no results', function () { beforeEach(function () { resultsCollection.getTotalResultsCount = sinon.stub().returns(0); }); it('is hidden', function () { view.showControls(); view.onSearchComplete(); expect(view.$el).toHaveClass('hidden'); }); }); describe('updating the search params model', function () { it('decrements the searchParamsModel pageNumber value when the prev page button is clicked', function () { view.onClickPrevPageButton(); expect(searchParamsModel.setPageNumber).toHaveBeenCalledWith(3); }); it('sets the searchParamsModel pageNumber value to 1 when the first page button is clicked', function () { view.onClickPageSelector({ target: view.$('a[title="Go to page 1"]')[0] }); expect(searchParamsModel.setPageNumber).toHaveBeenCalledWith(1); }); it('increments the searchParamsModel pageNumber value when the next page button is clicked', function () { view.onClickNextPageButton(); expect(searchParamsModel.setPageNumber).toHaveBeenCalledWith(5); }); }); describe('triggering the "search:refinedSearch" event', function () { it('triggers when a page number is clicked', function () { view.onClickPageSelector({ target: { text: '1' } }); expect(mediator.trigger).toHaveBeenCalledWith('search:refinedSearch'); }); it('triggers when the previous page button is clicked', function () { view.onClickPrevPageButton(); expect(mediator.trigger).toHaveBeenCalledWith('search:refinedSearch'); }); it('triggers when the next page button is clicked', function () { view.onClickNextPageButton(); expect(mediator.trigger).toHaveBeenCalledWith('search:refinedSearch'); }); }); describe('mediated event handling', function () { beforeEach(function () { mediator = new Mediator(); view.setMediator(mediator); }); it('hides itself when the app goes home', function () { // guard assertion expect(view.$el).not.toHaveClass('hidden'); mediator.trigger('app:home'); expect(view.$el).toHaveClass('hidden'); }); it('hides itself when a new search is intiated', function () { // guard assertion expect(view.$el).not.toHaveClass('hidden'); mediator.trigger('search:initiated'); expect(view.$el).toHaveClass('hidden'); }); it('shows itself when a new set of search results is ready', function () { view.hideControls(); mediator.trigger('search:complete'); expect(view.$el).not.toHaveClass('hidden'); }); it('shows itself when an in-progress search is canceled if there are previous results', function () { view.hideControls(); mediator.trigger('search:displayPreviousResults'); expect(view.$el).not.toHaveClass('hidden'); }); }); }); });
hwilcox/bcube-interface
spec/views/right_column/PaginationControlsView_spec.js
JavaScript
gpl-3.0
7,093
function date(pub_date){ var date = new Date( Date.parse(pub_date+' UTC')); return date.toLocaleString(); }
donkeyxote/djangle
djangle/forum/static/forum/js/localTime.js
JavaScript
gpl-3.0
120
/* Copyright 2019-2022 Michael Pozhidaev <[email protected]> This file is part of LUWRAIN. LUWRAIN is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. LUWRAIN is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ Luwrain.addCommand("suspend", function(){ if (!Luwrain.popups.confirmDefaultYes(Luwrain.i18n.static.powerSuspendPopupName, Luwrain.i18n.static.powerSuspendPopupText)) return; Luwrain.os.suspend(); });
luwrain/extensions
js/pm.js
JavaScript
gpl-3.0
800
'use strict'; // Create the valorchat configuration module.exports = function (io, socket) { // Emit the status event when a new socket client is connected io.emit('ValorchatMessage', { type: 'status', text: 'Is now connected', created: Date.now(), profileImageURL: socket.request.user.profileImageURL, username: socket.request.user.username }); // Send a valorchat messages to all connected sockets when a message is received socket.on('ValorchatMessage', function (message) { message.type = 'message'; message.created = Date.now(); message.profileImageURL = socket.request.user.profileImageURL; message.username = socket.request.user.username; // Emit the 'ValorchatMessage' event io.emit('ValorchatMessage', message); }); // Emit the status event when a socket client is disconnected socket.on('disconnect', function () { io.emit('ValorchatMessage', { type: 'status', text: 'disconnected', created: Date.now(), profileImageURL: socket.request.user.profileImageURL, username: socket.request.user.username }); }); };
AnnaGenev/pokeapp-meanjs
modules/valorchat/server/sockets/valorchat.server.socket.config.js
JavaScript
gpl-3.0
1,122
///////////////////////////////////////////////////////////////////////////////// // // Jobbox WebGUI // Copyright (C) 2014-2015 Komatsu Yuji(Zheng Chuyu) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// // // Function: // // Purpose: // // Parameters: // // Return value: // // Author: Komatsu Yuji(Zheng Chuyu) // ///////////////////////////////////////////////////////////////////////////////// Ext.define('Jobbox.store.HistJobunit', { extend: 'Ext.data.Store', model: 'Jobbox.model.HistJobunit', autoLoad: true, autoDestroy: false, autoSync: false, remoteSort: true, proxy: { type: 'rest', url: location.pathname + '/hist_jobunits', appendId: true, format: 'json', reader: { root: 'hist_jobunits', totalProperty: 'total_count', }, }, });
komatsuyuji/jobbox
frontends/public/app/store/HistJobunit.js
JavaScript
gpl-3.0
1,563
// @flow import React from 'react'; import type { Trigger } from '../../Domain/Trigger'; import type { Maintenance } from '../../Domain/Maintenance'; import TriggerListItem from '../TriggerListItem/TriggerListItem'; import cn from './TriggerList.less'; type Props = {| items: Array<Trigger>; onChange?: (triggerId: string, maintenance: Maintenance, metric: string) => void; onRemove?: (triggerId: string, metric: string) => void; |}; export default function TriggerList(props: Props): React.Element<*> { const { items, onChange, onRemove } = props; return ( <div> {items.length === 0 ? <div className={cn('no-result')}>No results :-(</div> : items.map(item => <div className={cn('item')} key={item.id}> <TriggerListItem data={item} onChange={onChange && ((maintenance, metric) => onChange(item.id, maintenance, metric))} onRemove={onRemove && (metric => onRemove(item.id, metric))} /> </div> )} </div> ); }
sashasushko/moira-front
src/Components/TriggerList/TriggerList.js
JavaScript
gpl-3.0
1,197
var jsVars = { appBaseUrl: null, appBasePath: null, init: function () { var jsVarsAttributes = angular.element('#js-vars')[0].attributes; jsVars.appBaseUrl = jsVarsAttributes['data-base-url'].value; jsVars.appBasePath = jsVarsAttributes['data-basepath'].value; } }; jsVars.init(); var config = { basePath: jsVars.appBasePath+'/ng-front/', restServer: jsVars.appBaseUrl+'/api' }; var Question = { TYPE_QCM: 1, TYPE_FREE: 2 }; function getUTCTimestamp() { var now = new Date(); var utc_now = new Date( now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds() ); return utc_now.getTime(); } /** * Filter to create a Javascript date */ angular.module('zcpeFilters', []).filter('jsDate', function () { return function (sDate) { return new Date(sDate); } }); var zcpe = angular.module('zcpe', [ 'ngRoute', 'pascalprecht.translate', 'ngCookies', 'ngStorage', 'angular-locker', 'controllers-quizz', 'hljs', 'timer', 'zcpeFilters' ]);
Antione7/ZCEPracticeTest
web/ng-front/app.js
JavaScript
gpl-3.0
1,224
const Command = require('../../structures/Command'); const request = require('node-superfetch'); const { GOOGLE_KEY } = process.env; module.exports = class ToxicityCommand extends Command { constructor(client) { super(client, { name: 'toxicity', aliases: ['perspective', 'comment-toxicity'], group: 'analyze', memberName: 'toxicity', description: 'Determines the toxicity of text.', credit: [ { name: 'Perspective API', url: 'https://www.perspectiveapi.com/#/' } ], args: [ { key: 'text', prompt: 'What text do you want to test the toxicity of?', type: 'string' } ] }); } async run(msg, { text }) { try { const { body } = await request .post('https://commentanalyzer.googleapis.com/v1alpha1/comments:analyze') .query({ key: GOOGLE_KEY }) .send({ comment: { text }, languages: ['en'], requestedAttributes: { TOXICITY: {} } }); const toxicity = Math.round(body.attributeScores.TOXICITY.summaryScore.value * 100); if (toxicity >= 70) return msg.reply(`Likely to be perceived as toxic. (${toxicity}%)`); if (toxicity >= 40) return msg.reply(`Unsure if this will be perceived as toxic. (${toxicity}%)`); return msg.reply(`Unlikely to be perceived as toxic. (${toxicity}%)`); } catch (err) { return msg.reply(`Oh no, an error occurred: \`${err.message}\`. Try again later!`); } } };
dragonfire535/xiaobot
commands/analyze/toxicity.js
JavaScript
gpl-3.0
1,410
export const getIsAdmin = (state) => state.session.user?.administrator; export const getUserId = (state) => state.session.user?.id; export const getDevices = (state) => Object.values(state.devices.items); export const getPosition = (id) => (state) => state.positions.items[id];
tananaev/traccar-web
modern/src/common/selectors.js
JavaScript
gpl-3.0
281
import sinon from 'sinon'; import chai from 'chai'; import sinonChai from "sinon-chai"; import subset from 'chai-subset'; window.sinon = sinon; window.chai = chai; chai.use(sinonChai); chai.use(subset); window.expect = chai.expect; window.should = chai.should; import * as fixtures from './fixtures.js'; window.fixtures = fixtures; var context = require.context('.', true, /.spec.js(x?)$/); //make sure you have your directory and regex test set correctly! context.keys().forEach(context);
getfireside/fireside
client/test/index.js
JavaScript
gpl-3.0
493
var classglobal = [ [ "Buffer", "df/d84/classglobal.html#a77b5ab3a88955255ac7abc7251919fbc", null ], [ "run", "df/d84/classglobal.html#a917c15ea7d2eafaa6df0aea5868a86e7", null ], [ "require", "df/d84/classglobal.html#a9b11defd1000737a5b70b50edfcc8156", null ], [ "GC", "df/d84/classglobal.html#a02a28758a633a7b1493471415c8949ba", null ], [ "console", "df/d84/classglobal.html#a69cd8fa430cb4536156e8052a37c9303", null ] ];
xushiwei/fibjs
docs/df/d84/classglobal.js
JavaScript
gpl-3.0
441
//Settings actype = ['image/png','image/jpeg','image/jpg','image/gif']; /* Accepted mime type */ maxweight = 819200; /* Max file size in octets */ maxwidth = 150; /* Max width of the image */ maxheight = 150; /* Max height*/ //Caching variable selector ish = $('.ish'); /* On attach element hide or show */ msgUp = $('.msgUp'); /* container message, infos, error... */ filezone = $('.filezone'); /* Selector filezone label */ fileprev = $('.filezone').children('img'); /* Selector img element */ filesend = $('#filesend'); /* Selector input file (children label) */ fileup = $('#fileup'); /* Selector button submit */ reset = $('#reset'); /* Selector button reset */ ish.hide(); /* Initial hide */ $(':file').change(function(e) { //Cancel the default execution e.preventDefault(); //Full file file = this.files[0]; var filer = new FileReader; filer.onload = function() { //Get size and type var aType = file.type; var aSize = file.size; //Check the file size if(aSize > maxweight) { msgUp.text('To large, maximum'+ maxweight +' bytes'); return; } //Check the file type if($.inArray(aType, actype) === -1) { msgUp.text('File type not allowed'); return; } //Set src / preview fileprev.attr('src', filer.result); //Make new Image for get the width / height var image = new Image(); image.src = filer.result; image.onload = function() { //Set width / height aWidth = image.width; aHeight = image.height; //Check width if(aWidth > maxwidth) { msgUp.text('Maximum' + maxwidth +' width allowed'); return; } //Check height if(aHeight > maxheight) { msgUp.text('Maximum' + maxheight +' height allowed'); return; } //Success of every check, display infos about the image and show up the <img> tag msgUp.html('Size :'+ aSize +' bytes<br>Filetype : '+ aType +'<br>Width :'+ aWidth +' px<br>Height: '+ aHeight +' px'); ish.show(); filesend.addClass('lock').css('height','0%'); //End image }; //End filer }; //File is up filer.readAsDataURL(file); }); //input file prevent on lock $(document).off('click', '#filesend'); $(document).on('click', '#filesend', function(e) { //Cancel the default execution if img ready to be send to php if($(this).hasClass('lock')) e.preventDefault(); }); //On reset $(document).off('click', '#reset'); $(document).on('click', '#reset', function(e) { //Cancel the default execution e.preventDefault(); //Remove the href link fileprev.attr('src', ''); //Set default message msgUp.text('Drop your avatar !'); //Remove the lock of the input file if(filesend.hasClass('lock')) filesend.css('height','100%').removeClass(); //Set default reset value $(this).val('Clear'); //Back to hide ish.hide(); }); //On fileup $(document).off('click', '#fileup'); $(document).on('click', '#fileup', function(e) { //Cancel the default execution e.preventDefault(); //Set variable which contain the entiere form / field var filesfm = new FormData(document.querySelector("form")); $.ajax({ url: 'upload.php', //Server side script (php...) type: 'POST', data:filesfm, processData: false, //Avoid jquery process contentType: false //Avoid set content type (done by var filesfm) }).done(function(msg) { //Hide the button upload fileup.hide(); //Change the text reset button (make as reinitialize the form) reset.val('Upload again !'); //On success upload if(msg === 'err') msgUp.text('Something went wrong, try again.'); //That should not happen ! else msgUp.text('Success, your file is available '+ msg); //Add the url of your file except the filename generated }); });
Anyon3/simplehtml5upload
upload.js
JavaScript
gpl-3.0
3,860
const {ipcFuncMain, ipcFuncMainCb, getIpcNameFunc, sendToBackgroundPage} = require('./util-main') const {ipcMain} = require('electron') const getIpcName = getIpcNameFunc('ContextMenus') const extInfos = require('../../extensionInfos') const sharedState = require('../../sharedStateMain') ipcMain.on('get-extension-menu',(e) => ipcMain.emit('get-extension-menu-reply', null, sharedState.extensionMenu)) ipcMain.on('chrome-context-menus-clicked', async (e, extensionId, tabId, info)=>{ sendToBackgroundPage(extensionId, getIpcName('onClicked'), info, tabId) }) ipcFuncMainCb('contextMenus', 'create', (e, extensionId, createProperties, cb)=> { console.log('contextMenu', 'create', extensionId, createProperties) const manifest = extInfos[extensionId].manifest const icon = Object.values(manifest.icons)[0] const menuItemId = createProperties.id if(!sharedState.extensionMenu[extensionId]) sharedState.extensionMenu[extensionId] = [] sharedState.extensionMenu[extensionId].push({properties: createProperties, menuItemId, icon}) sharedState.extensionMenu[extensionId].sort((a,b) => (a.properties.count || 99) - (b.properties.count || 99)) //TODO onClick cb() }) ipcFuncMain('contextMenus', 'update', (e, extensionId, id, updateProperties) => { const menu = sharedState.extensionMenu[extensionId] if(menu){ const item = menu.find(propeties=>propeties.id === id || propeties.menuItemId === id) if(item) Object.assign(item.properties,updateProperties) } }) ipcFuncMain('contextMenus', 'remove', (e, extensionId, menuItemId) => { const menu = sharedState.extensionMenu[extensionId] if(menu){ const i = menu.findIndex(propeties=>propeties.menuItemId === menuItemId || propeties.id === menuItemId) if(i != -1) menu.splice(i,1) } }) ipcFuncMain('contextMenus', 'removeAll', (e, extensionId) => { console.log('contextMenu', 'removeAll', extensionId) delete sharedState.extensionMenu[extensionId] })
kura52/sushi-browser
src/remoted-chrome/browser/context-menus-main.js
JavaScript
gpl-3.0
1,947
var Card = require("./Card"); var CARDS = require("./cards"); var CARDNUM = require("./cardnum"); var api = require("../rpcapi"); var util = require("../util"); var state = require("../state"); var imgUtil = require("../img"); // INDEX ----------------------------------------------------------------------- function IndexCard() { Card.call(this, CARDNUM.INDEX, "#card-index"); } IndexCard.prototype = Object.create(Card.prototype); IndexCard.prototype.show = function() { Card.prototype.show.call(this); state.toCard(this); util.setHeader("Foxi"); util.setSubheader(); util.showBackButton(function() { CARDS.CONNECTION.activate(); }); }; IndexCard.prototype.load = function() { var card = this; card.render('index'); $("a[data-card-link]").on('click', function() { util.freezeUI(this); var linked = CARDS[$(this).attr('data-card-link')]; linked.activate(); }); api.VideoLibrary.GetRecentlyAddedMovies({ properties: [ 'art' ], limits: { end: 4 } }).then(function(data) { card.render('index_recent_movies', data.result, '#index-recent-movies'); imgUtil.loadImages($("#index-recent-movies img[data-cache-url]"), imgUtil.dimensions.movie); }); api.VideoLibrary.GetRecentlyAddedEpisodes({ properties: [ 'art' ], limits: { end: 4 } }).then(function(data) { card.render('index_recent_episodes', data.result, '#index-recent-episodes'); imgUtil.loadImages($("#index-recent-episodes img[data-cache-url]"), imgUtil.dimensions.tv_thumb); }); this.loaded = true; this.show(); }; module.exports = new IndexCard();
soupytwist/Foxi
src/cards/IndexCard.js
JavaScript
gpl-3.0
1,623
/* * Katana - a powerful, open-source screenshot utility * * Copyright (C) 2018, Gage Alexander <[email protected]> * * Katana is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Katana is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Katana. If not, see <http://www.gnu.org/licenses/>. */ const packager = require('electron-packager') const options = { platform: ['darwin'], arch: 'x64', icon: './app/static/images/icon', dir: '.', ignore: ['build'], out: './build/Release', overwrite: true, prune: true } packager(options, (error, path) => { if (error) { return ( console.log(`Error: ${error}`) ) } console.log(`Package created, path: ${path}`) })
bluegill/katana
build/index.js
JavaScript
gpl-3.0
1,149
// GoSquared var GoSquared = {}; GoSquared.acct = "GSN-064561-T"; (function(w){ function gs(){ w._gstc_lt = +new Date; var d = document, g = d.createElement("script"); g.type = "text/javascript"; g.src = "//d1l6p2sc9645hc.cloudfront.net/tracker.js"; var s = d.getElementsByTagName("script")[0]; s.parentNode.insertBefore(g, s); } w.addEventListener ? w.addEventListener("load", gs, false) : w.attachEvent("onload", gs); })(window); // Google Analytics var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-40084408-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();
Moussa/Wiki-Fi
static/js/analytics.js
JavaScript
gpl-3.0
905
/*! * jQuery UI Effects Transfer 1.10.1 * http://jqueryui.com * * Copyright 2013 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/transfer-effect/ * * Depends: * jquery.ui.effect.js */ (function( $, undefined ) { $.effects.effect.transfer = function( o, done ) { var elem = $( this ), target = $( o.to ), targetFixed = target.css( "position" ) === "fixed", body = $("body"), fixTop = targetFixed ? body.scrollTop() : 0, fixLeft = targetFixed ? body.scrollLeft() : 0, endPosition = target.offset(), animation = { top: endPosition.top - fixTop , left: endPosition.left - fixLeft , height: target.innerHeight(), width: target.innerWidth() }, startPosition = elem.offset(), transfer = $( "<div class='ui-effects-transfer'></div>" ) .appendTo( document.body ) .addClass( o.className ) .css({ top: startPosition.top - fixTop , left: startPosition.left - fixLeft , height: elem.innerHeight(), width: elem.innerWidth(), position: targetFixed ? "fixed" : "absolute" }) .animate( animation, o.duration, o.easing, function() { transfer.remove(); done(); }); }; })(jQuery);
Tinchosan/wingpanel
admin/js/jquery-ui/development-bundle/ui/jquery.ui.effect-transfer.js
JavaScript
gpl-3.0
1,284
var xForRefIcon = 0; var yForRefIcon = 0; var xForSubDiagramIcon = 0; var yForSubDiagramIcon = 0; var xForTransIcon = 0; var yForTransIcon = 0; var fileLinks = []; var folderLinks = []; var urlLinks = []; var diagramLinks = []; var shapeLinks = []; var subdiagramLinks = []; var fromTransitorLinks = []; var toTransitorLinks = []; // vplink var vpLinkProjectLink; var vpLinkPageUrl; var vpLinkProjectLinkWithName; var vpLinkPageUrlWithName; function showDefaultReferenceIcon(imageId, modelValues, objectId) { if (modelValues != ''){ var xyValueArray = modelValues.split(","); var shapeWidth = xyValueArray[2]*1 - xyValueArray[0]*1; // if (shapeWidth > 24){ var diagram = document.getElementById(imageId); var xOffset = findPosX(diagram); var yOffset = findPosY(diagram); var shapeX = xyValueArray[0]*1; var shapeY = xyValueArray[1]*1; var x = shapeX + xOffset*1; var y = shapeY + yOffset*1 - 13; var h = xyValueArray[3]*1 - xyValueArray[1]*1; var url = xyValueArray[4]; var referenceIconLayer = document.getElementById(objectId); N = (document.all) ? 0 : 1; if (N) { referenceIconLayer.style.left = x - 3; referenceIconLayer.style.top = y + h; } else { referenceIconLayer.style.posLeft = x - 3; referenceIconLayer.style.posTop = y + h; } referenceIconLayer.style.visibility="visible" // } } } function showReferenceIcon(imageId, modelValues) { if (modelValues != '') { var xyValueArray = modelValues.split(","); var shapeWidth = xyValueArray[2]*1 - xyValueArray[0]*1; // if (shapeWidth > 24){ var diagram = document.getElementById(imageId); var xOffset = findPosX(diagram); var yOffset = findPosY(diagram); var shapeX = xyValueArray[0]*1; var shapeY = xyValueArray[1]*1; var x = shapeX + xOffset*1; var y = shapeY + yOffset*1 - 13; var h = xyValueArray[3]*1 - xyValueArray[1]*1; var url = xyValueArray[4]; var referenceIconLayer = document.getElementById("referenceIconLayer"); N = (document.all) ? 0 : 1; if (N) { referenceIconLayer.style.left = x - 3; referenceIconLayer.style.top = y + h; } else { referenceIconLayer.style.posLeft = x - 3; referenceIconLayer.style.posTop = y + h; } referenceIconLayer.style.visibility="visible" // } } } function hideReferenceIcon() { var referenceIconLayer = document.getElementById("referenceIconLayer"); if (referenceIconLayer != null) { referenceIconLayer.style.visibility="hidden" } } function showDefaultSubdiagramIcon(imageId, modelValues, objectId) { if (modelValues != ''){ var xyValueArray = modelValues.split(","); var shapeWidth = xyValueArray[2]*1 - xyValueArray[0]*1; // if (shapeWidth > 24){ var diagram = document.getElementById(imageId); var xOffset = findPosX(diagram); var yOffset = findPosY(diagram); var shapeRightX = xyValueArray[2]*1; var shapeRightY = xyValueArray[1]*1; var x = shapeRightX + xOffset*1 - 10; var y = shapeRightY + yOffset*1 - 13; var h = xyValueArray[3]*1 - xyValueArray[1]*1; var url = xyValueArray[4]; var subdiagramIconLayer = document.getElementById(objectId); N = (document.all) ? 0 : 1; if (N) { subdiagramIconLayer.style.left = x - 3; subdiagramIconLayer.style.top = y + h; } else { subdiagramIconLayer.style.posLeft = x - 3; subdiagramIconLayer.style.posTop = y + h; } subdiagramIconLayer.style.visibility="visible" // } } } function showSubdiagramIcon(imageId, modelValues) { if (modelValues != ''){ var xyValueArray = modelValues.split(","); var shapeWidth = xyValueArray[2]*1 - xyValueArray[0]*1; // if (shapeWidth > 24){ var diagram = document.getElementById(imageId); var xOffset = findPosX(diagram); var yOffset = findPosY(diagram); var shapeRightX = xyValueArray[2]*1; var shapeRightY = xyValueArray[1]*1; var x = shapeRightX + xOffset*1 - 10; var y = shapeRightY + yOffset*1 - 13; var h = xyValueArray[3]*1 - xyValueArray[1]*1; var url = xyValueArray[4]; var subdiagramIconLayer = document.getElementById("subdiagramIconLayer"); N = (document.all) ? 0 : 1; if (N) { subdiagramIconLayer.style.left = x - 3; subdiagramIconLayer.style.top = y + h; } else { subdiagramIconLayer.style.posLeft = x - 3; subdiagramIconLayer.style.posTop = y + h; } subdiagramIconLayer.style.visibility="visible" // } } } function hideSubdiagramIcon() { var subdiagramIconLayer = document.getElementById("subdiagramIconLayer"); if (subdiagramIconLayer != null) { subdiagramIconLayer.style.visibility="hidden" } } function showDefaultTransitorIcon(imageId, modelValues, objectId) { if (modelValues != ''){ var xyValueArray = modelValues.split(","); var shapeWidth = xyValueArray[2]*1 - xyValueArray[0]*1; // if (shapeWidth > 24){ var diagram = document.getElementById(imageId); var xOffset = findPosX(diagram); var yOffset = findPosY(diagram); var shapeRightX = xyValueArray[2]*1; var shapeRightY = xyValueArray[1]*1; var x = shapeRightX + xOffset*1 - 10; var y = shapeRightY + yOffset*1; var h = xyValueArray[3]*1 - xyValueArray[1]*1; var url = xyValueArray[4]; var transitorIconLayer = document.getElementById(objectId); N = (document.all) ? 0 : 1; if (N) { transitorIconLayer.style.left = x - 3; transitorIconLayer.style.top = y + h; } else { transitorIconLayer.style.posLeft = x - 3; transitorIconLayer.style.posTop = y + h; } transitorIconLayer.style.visibility="visible" // } } } function showTransitorIcon(imageId, modelValues) { if (modelValues != ''){ var xyValueArray = modelValues.split(","); var shapeWidth = xyValueArray[2]*1 - xyValueArray[0]*1; // if (shapeWidth > 24){ var diagram = document.getElementById(imageId); var xOffset = findPosX(diagram); var yOffset = findPosY(diagram); var shapeRightX = xyValueArray[2]*1; var shapeRightY = xyValueArray[1]*1; var x = shapeRightX + xOffset*1 - 10; var y = shapeRightY + yOffset*1; var h = xyValueArray[3]*1 - xyValueArray[1]*1; var url = xyValueArray[4]; var transitorIconLayer = document.getElementById("transitorIconLayer"); N = (document.all) ? 0 : 1; if (N) { transitorIconLayer.style.left = x - 3; transitorIconLayer.style.top = y + h; } else { transitorIconLayer.style.posLeft = x - 3; transitorIconLayer.style.posTop = y + h; } transitorIconLayer.style.visibility="visible" // } } } function hideTransitorIcon() { var transitorIconLayer = document.getElementById("transitorIconLayer"); if (transitorIconLayer != null) { transitorIconLayer.style.visibility="hidden" } } function showDefaultDocumentationIcon(imageId, modelValues, objectId) { if (modelValues != ''){ var xyValueArray = modelValues.split(","); var shapeWidth = xyValueArray[2]*1 - xyValueArray[0]*1; // if (shapeWidth > 24){ var diagram = document.getElementById(imageId); var xOffset = findPosX(diagram); var yOffset = findPosY(diagram); var shapeX = xyValueArray[0]*1; var shapeY = xyValueArray[1]*1; var x = shapeX + xOffset*1; var y = shapeY + yOffset*1; var h = xyValueArray[3]*1 - xyValueArray[1]*1; var url = xyValueArray[4]; var documentationIconLayer = document.getElementById(objectId); N = (document.all) ? 0 : 1; if (N) { documentationIconLayer.style.left = x - 3; documentationIconLayer.style.top = y + h; } else { documentationIconLayer.style.posLeft = x - 3; documentationIconLayer.style.posTop = y + h; } documentationIconLayer.style.visibility="visible" // } } } function storeReferenceAndSubdiagramInfos(imageId, coords, fileRefs, folderRefs, urlRefs, diagramRefs, shapeRefs, subdiagrams, modelElementRefs, fromTransitors, toTransitors) { if (coords != ''){ var xyValueArray = coords.split(","); var shapeWidth = xyValueArray[2]*1 - xyValueArray[0]*1; // if (shapeWidth > 24){ fileLinks = []; folderLinks = []; urlLinks = []; diagramLinks = []; shapeLinks = []; subdiagramLinks = []; modelElementLinks = []; fromTransitorLinks = []; toTransitorLinks = []; var popup = document.getElementById("linkPopupMenuTable"); popup.width = 250; // reset to 250 first (forZachman may changed it to 500) for (i = 0 ; i < fileRefs.length ; i++) { fileLinks[i] = fileRefs[i]; } for (i = 0 ; i < folderRefs.length ; i++) { folderLinks[i] = folderRefs[i]; } for (i = 0 ; i < urlRefs.length ; i++) { urlLinks[i] = urlRefs[i]; } for (j = 0 ; j < diagramRefs.length ; j++) { diagramLinks[j] = diagramRefs[j] } for (j = 0 ; j < shapeRefs.length ; j++) { shapeLinks[j] = shapeRefs[j] } for (j = 0 ; j < subdiagrams.length ; j++) { subdiagramLinks[j] = subdiagrams[j] } for (j = 0 ; j < modelElementRefs.length ; j++) { modelElementLinks[j] = modelElementRefs[j] } for (j = 0 ; j < fromTransitors.length ; j++) { fromTransitorLinks[j] = fromTransitors[j] } for (j = 0 ; j < toTransitors.length ; j++) { toTransitorLinks[j] = toTransitors[j] } var diagram = document.getElementById(imageId); var xOffset = findPosX(diagram); var yOffset = findPosY(diagram); var shapeX = xyValueArray[0]*1; var shapeY = xyValueArray[1]*1; var x = shapeX + xOffset*1; var y = shapeY + yOffset*1 + 2; var w = xyValueArray[2]*1 - xyValueArray[0]*1; var h = xyValueArray[3]*1 - xyValueArray[1]*1; var url = xyValueArray[4]; xForRefIcon = x; yForRefIcon = y + h; shapeX = xyValueArray[2]*1; shapeY = xyValueArray[1]*1; x = shapeX + xOffset*1 - 12; y = shapeY + yOffset*1 + 2; w = xyValueArray[2]*1 - xyValueArray[0]*1; h = xyValueArray[3]*1 - xyValueArray[1]*1; url = xyValueArray[4]; xForSubDiagramIcon = x; yForSubDiagramIcon = y + h; xForTransIcon = x; yForTransIcon = y + h + 12; // } } } function resetPopupForReference() { clearLinkPopupContent(); var popup = document.getElementById("linkPopupMenuTable"); // file references for (i = 0 ; i < fileLinks.length ; i++) { var fileNameUrl = fileLinks[i].split("*"); var name = fileNameUrl[0]; var url = fileNameUrl[1]; // may be null var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(../images/icons/FileReference.png) !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/icons/FileReference.png'); background-repeat: no-repeat;\"></div>&nbsp;"+name; imgPopupCell.valign="middle"; if (url == null) { imgPopupCell.className="PopupMenuRowNonSelectable"; } else { imgPopupCell.destination=url; imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; imgPopupCell.onclick= function onclick(event) { window.open(this.destination);hideLinkPopup(); }; } } // folder reference for (i = 0 ; i < folderLinks.length ; i++) { var folderNameUrl = folderLinks[i].split("*"); var name = folderNameUrl[0]; var url = folderNameUrl[1]; // may be null var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(../images/icons/FolderReference.png) !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/icons/FolderReference.png'); background-repeat: no-repeat;\"></div>&nbsp;"+name; imgPopupCell.valign="middle"; if (url == null) { imgPopupCell.className="PopupMenuRowNonSelectable"; } else if (url != null) { imgPopupCell.destination=url; imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; imgPopupCell.onclick= function onclick(event) { window.open(this.destination);hideLinkPopup(); }; } } // url reference for (i = 0 ; i < urlLinks.length ; i++) { var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); var destination = urlLinks[i][0]; var name = urlLinks[i][1]; if (name == null || name == '') { name = destination; } imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(../images/icons/UrlReference.png) !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../images/icons/UrlReference.png'); background-repeat: no-repeat;\"></div>&nbsp;"+name imgPopupCell.valign="middle" imgPopupCell.destination=destination; imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; imgPopupCell.onclick= function onclick(event) { window.open(this.destination);hideLinkPopup(); }; } // diagram reference for (j = 0 ; j < diagramLinks.length ; j++) { var diagramUrlNameType = diagramLinks[j].split("/"); var url = diagramUrlNameType[0]; var name = diagramUrlNameType[1]; var type = diagramUrlNameType[2]; var imgSrc = '../images/icons/'+type+'.png'; var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(" + imgSrc + ") !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSrc + "'); background-repeat: no-repeat;\"></div>&nbsp;"+name imgPopupCell.valign="middle" imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; if (url == 'vplink') { imgPopupCell.destination= diagramUrlNameType[3].replace('@','/'); imgPopupCell.vpLinkWithName= diagramUrlNameType[4].replace('@','/'); imgPopupCell.onclick= function onclick(event) { showVpLink(this.destination, this.vpLinkWithName, null, this) }; } else { imgPopupCell.destination=url if (url != null && url != '') { imgPopupCell.onclick= function onclick(event) { window.open(this.destination,'_self') }; } } } // shape reference for (j = 0 ; j < shapeLinks.length ; j++) { var shapeUrlNameType = shapeLinks[j].split("/"); var url = shapeUrlNameType[0]; var name = shapeUrlNameType[1]; var iconFileName = shapeUrlNameType[2]; var imgSrc = '../images/icons/'+iconFileName+'.png'; var row = popup.insertRow(popup.rows.length) var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(" + imgSrc + ") !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSrc + "'); background-repeat: no-repeat;\"></div>&nbsp;"+name imgPopupCell.valign="middle" imgPopupCell.destination=url imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; if (iconFileName.length > 0){ imgPopupCell.onclick= function onclick(event) { window.open(this.destination,'_self') }; } } // model element reference for (j = 0 ; j < modelElementLinks.length ; j++) { var modelElementUrlNameType = modelElementLinks[j].split("/"); var url = modelElementUrlNameType[0]; var name = modelElementUrlNameType[1]; var iconFileName = modelElementUrlNameType[2]; var imgSrc = '../images/icons/'+iconFileName+'.png'; var row = popup.insertRow(popup.rows.length) var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(" + imgSrc + ") !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSrc + "'); background-repeat: no-repeat;\"></div>&nbsp;"+name imgPopupCell.valign="middle" imgPopupCell.destination=url imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; if (iconFileName.length > 0) { imgPopupCell.onclick= function onclick(event) { window.open(this.destination,'_self') }; } } } function resetPopupForSubdiagram() { clearLinkPopupContent(); var popup = document.getElementById("linkPopupMenuTable"); // subdiagram for (j = 0 ; j < subdiagramLinks.length ; j++) { var diagramUrlNameType = subdiagramLinks[j].split("/"); var url = diagramUrlNameType[0]; var name = diagramUrlNameType[1]; var type = diagramUrlNameType[2]; var imgSrc = '../images/icons/'+type+'.png'; var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(" + imgSrc + ") !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSrc + "'); background-repeat: no-repeat;\"></div>&nbsp;"+name imgPopupCell.valign="middle" imgPopupCell.destination=url imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; if (url != null && url != '') { imgPopupCell.onclick= function onclick(event) { window.open(this.destination,'_self') }; } } } function movePopupPositionToReferenceIconPosition() { movePopupPositionToSpecificPosition(xForRefIcon, yForRefIcon); } function movePopupPositionToSubdiagramIconPosition() { movePopupPositionToSpecificPosition(xForSubDiagramIcon, yForSubDiagramIcon); } function movePopupPositionToCursorPosition(imageId, event) { var diagram = document.getElementById(imageId); var xOffset = 0; var yOffset = 0; var e = (window.event) ? window.event : event; xOffset = e.clientX; yOffset = e.clientY; if (document.all) { if (!document.documentElement.scrollLeft) xOffset += document.body.scrollLeft; else xOffset += document.documentElement.scrollLeft; if (!document.documentElement.scrollTop) yOffset += document.body.scrollTop; else yOffset += document.documentElement.scrollTop; }else{ xOffset += window.pageXOffset; yOffset += window.pageYOffset; } var nX = xOffset*1; var nY = yOffset*1; movePopupPositionToSpecificPosition(nX, nY); } function movePopupPositionToSpecificPosition(x, y) { var popupLayer = document.getElementById("linkPopupMenuLayer"); N = (document.all) ? 0 : 1; if (N) { popupLayer.style.left = x; popupLayer.style.top = y; } else { popupLayer.style.posLeft = x; popupLayer.style.posTop = y; } } function switchPopupShowHideStatus(){ var popup = document.getElementById("linkPopupMenuTable"); if (popup.style.visibility=="visible") { hideLinkPopup(); }else{ showLinkPopup(); } } function switchPopupShowHideStatusForZachman(aForZachmanKind) { var popup = document.getElementById("linkPopupMenuTable"); if (popup.style.visibility=="visible") { if (aForZachmanKind == popup.forZachmanKind) { popup.forZachmanKind = null; hideLinkPopup(); } else { // keep popup shown, just need change its forZachmanKind popup.forZachmanKind = aForZachmanKind; } }else{ popup.forZachmanKind = aForZachmanKind; showLinkPopup(); } } function adjustPopupPositionForSpotLightTable() { movePopupPositionToSpecificPosition(cursorX,cursorY); } function showLinkPopup(){ hideVpLink(); hideReferencedBys(); var popup = document.getElementById("linkPopupMenuTable"); popup.style.visibility="visible" document.getElementById("linkPopupMenuLayer").style.visibility="visible"; } function hideLinkPopup(){ var popup = document.getElementById("linkPopupMenuTable"); if (popup != null) { popup.style.visibility="hidden" document.getElementById("linkPopupMenuLayer").style.visibility="hidden"; } } function clearLinkPopupContent(){ var popup = document.getElementById("linkPopupMenuTable"); for (i = popup.rows.length ; i >0 ; i--) { popup.deleteRow(0); } } function movePopupPositionToTransitorIconPosition() { movePopupPositionToSpecificPosition(xForTransIcon, yForTransIcon); } function resetPopupForTransitor() { clearLinkPopupContent(); var popup = document.getElementById("linkPopupMenuTable"); // transitor var row = popup.insertRow(popup.rows.length); var popupCell = row.insertCell(0); popupCell.innerHTML="<div style=\"font-size:11px\">From:</div>"; for (j = 0 ; j < fromTransitorLinks.length ; j++) { var shapeUrlNameType = fromTransitorLinks[j].split("/"); addPopupItem(popup, shapeUrlNameType); } row = popup.insertRow(popup.rows.length); popupCell = row.insertCell(0); popupCell.innerHTML="<div style=\"font-size:11px\">To:</div>"; for (j = 0 ; j < toTransitorLinks.length ; j++) { var shapeUrlNameType = toTransitorLinks[j].split("/"); addPopupItem(popup, shapeUrlNameType); } } // for From/To Transitor function addPopupItem(popup, shapeUrlNameType) { var url = shapeUrlNameType[0]; var name = shapeUrlNameType[1]; var iconFileName = shapeUrlNameType[2]; var imgSrc = '../images/icons/'+iconFileName+'.png'; var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(" + imgSrc + ") !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSrc + "'); background-repeat: no-repeat;\"></div>&nbsp;"+name imgPopupCell.valign="middle"; imgPopupCell.destination=url; imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; imgPopupCell.onclick= function onclick(event) { window.open(this.destination,'_self') }; } // for Zachman // @param format: url/name/type, url/name/type, ... function resetPopupForZachmanCellDiagrams(lCellId, lValues) { clearLinkPopupContent(); var popup = document.getElementById("linkPopupMenuTable"); popup.style.width = 250; var lZachmanCell = document.getElementById(lCellId); var lZachmanCellX = findPosX(lZachmanCell); var lZachmanCellY = findPosY(lZachmanCell); if (lZachmanCellX > 250) { // show on left movePopupPositionToSpecificPosition(lZachmanCellX+lZachmanCell.offsetWidth-popup.offsetWidth-5, lZachmanCellY+lZachmanCell.offsetHeight-5); } else { // show on right // x+5 & y-5 to let the popup overlap with current cell movePopupPositionToSpecificPosition(lZachmanCellX+5, lZachmanCellY+lZachmanCell.offsetHeight-5); } // ZachmanCell.diagrams for (j = 0 ; j < lValues.length ; j++) { var diagramUrlNameType = lValues[j].split("/"); var url = diagramUrlNameType[0]; var name = diagramUrlNameType[1]; var type = diagramUrlNameType[2]; var imgSrc = '../images/icons/'+type+'.png'; var row = popup.insertRow(popup.rows.length); var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(" + imgSrc + ") !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSrc + "'); background-repeat: no-repeat;\"></div>&nbsp;"+name; imgPopupCell.valign="middle"; imgPopupCell.destination=url; imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; if (url != null && url != '') { imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onclick= function onclick(event) { window.open(this.destination,'_self') }; } else { imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowNonSelectable"; }; } } } // @param format: url/name/aliases/labels/documentation, url/name/aliases/labels/documentation, ... function resetPopupForZachmanCellTerms(lCellId, lValues) { clearLinkPopupContent(); var popup = document.getElementById("linkPopupMenuTable"); popup.style.width = 500; var lZachmanCell = document.getElementById(lCellId); var lZachmanCellX = findPosX(lZachmanCell); var lZachmanCellY = findPosY(lZachmanCell); if (lZachmanCellX > 500) { // show on left movePopupPositionToSpecificPosition(lZachmanCellX+lZachmanCell.offsetWidth-popup.offsetWidth-5, lZachmanCellY+lZachmanCell.offsetHeight-5); } else { // show on right // x+5 & y-5 to let the popup overlap with current cell movePopupPositionToSpecificPosition(lZachmanCellX+5, lZachmanCellY+lZachmanCell.offsetHeight-5); } // ZachmanCell.terms { var row = popup.insertRow(popup.rows.length); row.className="PopupMenuHeaderRow"; { var lPopupCell = row.insertCell(0); lPopupCell.innerHTML="Name"; lPopupCell.valign="middle"; } { var lPopupCell = row.insertCell(1); lPopupCell.innerHTML="Aliases"; lPopupCell.valign="middle"; } { var lPopupCell = row.insertCell(2); lPopupCell.innerHTML="Labels"; lPopupCell.valign="middle"; } { var lPopupCell = row.insertCell(3); lPopupCell.innerHTML="Documentation"; lPopupCell.valign="middle"; } } for (j = 0 ; j < lValues.length ; j++) { var lValue = lValues[j].split("/"); var url = lValue[0]; var name = lValue[1]; var aliases = lValue[2]; var labels = lValue[3]; var documentation = lValue[4]; var row = popup.insertRow(popup.rows.length); for (lCellIndex = 1; lCellIndex < lValue.length; lCellIndex++) { var lPopupCell = row.insertCell(lCellIndex-1); lPopupCell.id="cell"+j+","+lCellIndex-1; lPopupCell.innerHTML=lValue[lCellIndex]; lPopupCell.valign="middle"; } if (url != null && url != '') { row.destination=url; row.className="PopupMenuRowDeselected"; row.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; row.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; row.onclick= function onclick(event) { window.open(this.destination,'_self') }; } else { row.className="PopupMenuRowNonSelectable"; } } } // @param format: url/id/name/ruleText, url/id/name/ruleText, ... function resetPopupForZachmanCellRules(lCellId, lValues) { clearLinkPopupContent(); var popup = document.getElementById("linkPopupMenuTable"); popup.style.width = 500; var lZachmanCell = document.getElementById(lCellId); var lZachmanCellX = findPosX(lZachmanCell); var lZachmanCellY = findPosY(lZachmanCell); if (lZachmanCellX > 500) { // show on left movePopupPositionToSpecificPosition(lZachmanCellX+lZachmanCell.offsetWidth-popup.offsetWidth-5, lZachmanCellY+lZachmanCell.offsetHeight-5); } else { // show on right // x+5 & y-5 to let the popup overlap with current cell movePopupPositionToSpecificPosition(lZachmanCellX+5, lZachmanCellY+lZachmanCell.offsetHeight-5); } // ZachmanCell.rules { var row = popup.insertRow(popup.rows.length); row.className="PopupMenuHeaderRow"; { var lPopupCell = row.insertCell(0); lPopupCell.innerHTML="ID"; lPopupCell.valign="middle"; } { var lPopupCell = row.insertCell(1); lPopupCell.innerHTML="Name"; lPopupCell.valign="middle"; } { var lPopupCell = row.insertCell(2); lPopupCell.innerHTML="Rule"; lPopupCell.valign="middle"; } } for (j = 0 ; j < lValues.length ; j++) { var lValue = lValues[j].split("/"); var url = lValue[0]; var id = lValue[1]; var name = lValue[2]; var ruleText = lValue[3]; var row = popup.insertRow(popup.rows.length); for (lCellIndex = 1; lCellIndex < lValue.length; lCellIndex++) { var lPopupCell = row.insertCell(lCellIndex-1); lPopupCell.id="cell"+j+","+lCellIndex-1; lPopupCell.innerHTML=lValue[lCellIndex]; lPopupCell.valign="middle"; } if (url != null && url != '') { row.destination=url; row.className="PopupMenuRowDeselected"; row.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; row.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; row.onclick= function onclick(event) { window.open(this.destination,'_self') }; } else { row.className="PopupMenuRowNonSelectable"; } } } function showVpLink(link, linkWithName, pageUrlElementName, linkElem) { // getting absolute location in page var lLeft = 0; var lTop = 0; var lParent = linkElem; while (lParent != null) { lLeft += lParent.offsetLeft; lTop += lParent.offsetTop; lParent = lParent.offsetParent; } showVpLinkAt(link, linkWithName, pageUrlElementName, lLeft, lTop + linkElem.offsetHeight); } function showVpLinkAtDiagram(link, linkWithName, pageUrlElementName, aLeft, aTop) { var lLeft = 0; var lTop = 0; var diagramElem = document.getElementById('diagram'); var lParent = diagramElem; while (lParent != null) { lLeft += lParent.offsetLeft; lTop += lParent.offsetTop; lParent = lParent.offsetParent; } showVpLinkAt(link, linkWithName, pageUrlElementName, lLeft + aLeft, lTop + aTop); } function showVpLinkAt(link, linkWithName, pageUrlElementName, aLeft, aTop) { var popup = document.getElementById("vplink"); if (popup.style.visibility == "visible") { popup.style.visibility="hidden"; } else { var linktext = document.getElementById("vplink-text"); var withName = document.getElementById("vplink-checkbox"); var lLinkType = document.getElementById("vplink-linkType") // read from cookies (https://earth.space/#issueId=81262) var lWithNameValue = getCookie("vpProjectPublisher_vpLink_withName"); if (lWithNameValue != null) { if (lWithNameValue == "true") { withName.checked = true; } else { withName.checked = false; } } var lLinkTypeValue = getCookie("vpProjectPublisher_vpLink_type"); if (lLinkTypeValue != null) { if (lLinkTypeValue == "Page URL") { lLinkType.selectedIndex = 1; // 1 should be "Page URL" } else { lLinkType.selectedIndex = 0; // 0 should be "Project Link" } } vpLinkProjectLink = link; vpLinkProjectLinkWithName = linkWithName; if (pageUrlElementName != null) { vpLinkPageUrl = document.location.href; vpLinkPageUrlWithName = pageUrlElementName+"\n"+vpLinkPageUrl; lLinkType.disabled = false; } else { vpLinkPageUrl = null; vpLinkPageUrlWithName = null; lLinkType.selectedIndex = 0; // 0 should be "Project Link" lLinkType.disabled = true; } if (withName.checked) { if (lLinkType.disabled == false && lLinkType.options[lLinkType.selectedIndex].value == "Page URL") { // Page URL linktext.value = vpLinkPageUrlWithName; } else { // Project Link linktext.value = vpLinkProjectLinkWithName; } } else { if (lLinkType.disabled == false && lLinkType.options[lLinkType.selectedIndex].value == "Page URL") { // Page URL linktext.value = vpLinkPageUrl; } else { // Project Link linktext.value = vpLinkProjectLink; } } N = (document.all) ? 0 : 1; if (N) { popup.style.left = aLeft; popup.style.top = aTop; } else { popup.style.posLeft = aLeft; popup.style.posTop = aTop; } hideLinkPopup(); hideReferencedBys(); popup.style.visibility="visible" linktext.focus(); linktext.select(); } } function hideVpLink() { var popupLayer = document.getElementById("vplink"); if (popupLayer != null && popupLayer.style.visibility == "visible") { popupLayer.style.visibility="hidden"; } } function vpLinkToggleName() { var linktext = document.getElementById("vplink-text"); var withName = document.getElementById("vplink-checkbox"); var lLinkType = document.getElementById("vplink-linkType") // write to cookies (https://earth.space/#issueId=81262) setCookie("vpProjectPublisher_vpLink_withName", withName.checked); setCookie("vpProjectPublisher_vpLink_type", lLinkType.options[lLinkType.selectedIndex].value); if (withName.checked) { if (lLinkType.disabled == false && lLinkType.options[lLinkType.selectedIndex].value == "Page URL") { // Page URL linktext.value = vpLinkPageUrlWithName; } else { // Project Link linktext.value = vpLinkProjectLinkWithName; } } else { if (lLinkType.disabled == false && lLinkType.options[lLinkType.selectedIndex].value == "Page URL") { // Page URL linktext.value = vpLinkPageUrl; } else { // Project Link linktext.value = vpLinkProjectLink; } } linktext.focus(); linktext.select(); } function showReferencedBys(invokerId, refByDiagrams, refByModels) { var popupLayer = document.getElementById("referencedBys"); if (popupLayer.style.visibility == "visible") { popupLayer.style.visibility="hidden"; } else { var popup = document.getElementById("referencedBysTable"); for (i = popup.rows.length ; i >0 ; i--) { popup.deleteRow(0); } var refByDiagramLinks = []; var refByModelLinks = []; { popup.width = 250; // reset to 250 first (forZachman may changed it to 500) for (i = 0 ; i < refByDiagrams.length ; i++) { refByDiagramLinks[i] = refByDiagrams[i]; } for (i = 0 ; i < refByModels.length ; i++) { refByModelLinks[i] = refByModels[i]; } } { // ref by diagrams for (j = 0 ; j < refByDiagramLinks.length ; j++) { var diagramUrlNameType = refByDiagramLinks[j].split("/"); var url = diagramUrlNameType[0]; var name = diagramUrlNameType[1]; var type = diagramUrlNameType[2]; var imgSrc = '../images/icons/'+type+'.png'; var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(" + imgSrc + ") !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSrc + "'); background-repeat: no-repeat;\"></div>&nbsp;"+name imgPopupCell.valign="middle" imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; if (url == 'vplink') { imgPopupCell.destination= diagramUrlNameType[3].replace('@','/'); imgPopupCell.vpLinkWithName= diagramUrlNameType[4].replace('@','/'); imgPopupCell.onclick= function onclick(event) { showVpLink(this.destination, this.vpLinkWithName, null, this) }; } else { imgPopupCell.destination=url if (url != null && url != '') { imgPopupCell.onclick= function onclick(event) { window.open(this.destination,'_self') }; } } } // ref by models for (j = 0 ; j < refByModelLinks.length ; j++) { var modelElementUrlNameType = refByModelLinks[j].split("/"); var url = modelElementUrlNameType[0]; var name = modelElementUrlNameType[1]; var iconFileName = modelElementUrlNameType[2]; var imgSrc = '../images/icons/'+iconFileName+'.png'; var row = popup.insertRow(popup.rows.length) var row = popup.insertRow(popup.rows.length) var imgPopupCell = row.insertCell(0); imgPopupCell.innerHTML="<div style=\"float: left; width: 18px !important;height: 18px !important;background-image:url(" + imgSrc + ") !important; background-image:url(''); filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSrc + "'); background-repeat: no-repeat;\"></div>&nbsp;"+name imgPopupCell.valign="middle" imgPopupCell.destination=url imgPopupCell.className="PopupMenuRowDeselected"; imgPopupCell.onmouseover= function onmouseover(event) { this.className="PopupMenuRowSelected"; }; imgPopupCell.onmouseout= function onmouseover(event) { this.className="PopupMenuRowDeselected"; }; if (iconFileName.length > 0) { imgPopupCell.onclick= function onclick(event) { window.open(this.destination,'_self') }; } } } var invoker = document.getElementById(invokerId); var xOffset = findPosX(invoker); var yOffset = findPosY(invoker); yOffset = yOffset+18; N = (document.all) ? 0 : 1; if (N) { popupLayer.style.left = xOffset; popupLayer.style.top = yOffset; } else { popupLayer.style.posLeft = xOffset; popupLayer.style.posTop = yOffset; } hideLinkPopup(); hideVpLink(); popupLayer.style.visibility = "visible"; } } function hideReferencedBys() { var popupLayer = document.getElementById("referencedBys"); if (popupLayer != null && popupLayer.style.visibility == "visible") { popupLayer.style.visibility="hidden"; } } function setCookie(c_name, value) { var c_value = escape(value); document.cookie = c_name + "=" + c_value; } function getCookie(c_name) { var c_value = document.cookie; var c_start = c_value.indexOf(" " + c_name + "="); if (c_start == -1) { c_start = c_value.indexOf(c_name + "="); } if (c_start == -1) { c_value = null; } else { c_start = c_value.indexOf("=", c_start)+1; var c_end = c_value.indexOf(";", c_start); if (c_end == -1) { c_end = c_value.length; } c_value = unescape(c_value.substring(c_start, c_end)); } return c_value; }
EdwardWuYiHsuan/Student-Course-System
poseitech-java-assignments/docs/content/link_popup.js
JavaScript
gpl-3.0
39,618
var request = require('request'); var cheerio = require('cheerio'); var admin = require("firebase-admin"); //var serviceAccount = require("tehillim-17559-firebase-adminsdk-gx90v-b712a63ab5.json"); admin.initializeApp({ credential: admin.credential.cert("tehillim-17559-firebase-adminsdk-gx90v-b712a63ab5.json"), databaseURL: "https://tehillim-17559.firebaseio.com" }); // As an admin, the app has access to read and write all data, regardless of Security Rules var db = admin.database(); // Attach an asynchronous callback to read the data at our posts reference //ref.on("value", function (snapshot) { // console.log(snapshot.val()); //}, function (errorObject) { // console.log("The read failed: " + errorObject.code); //}); var psalmId = 1; var stripeHtml = function (text) { return text.replace(/<i><\/i>/g, ''); }; var removeLeadingVerseIndex = function (text) { return text.replace(/\d{1,2}/g, ''); }; var runEnHeRequest = function (id) { request('http://www.sefaria.org/api/texts/Psalms.' + id + '?commentary=0&context=1&pad=0', function (error, response, html) { if (!error && response.statusCode == 200) { console.log("Psalm: " + id + " OK"); var objHtml = JSON.parse(html); var enArray = []; objHtml.text.forEach(function (item) { enArray.push(stripeHtml(item)); }); var newObj = { id: id, name: "Psalm " + id, en: enArray, he: objHtml.he } var path = "psalms/" + (id-1).toString(); var ref = db.ref(path); ref.update(newObj, function (error) { if (error) { console.log("Data could not be saved." + error); } else { console.log("Psalm " + id + " saved successfully."); } }); } if (error) { console.log(response); } }); } var runPhonetiqueFrRequest = function (id) { request('http://tehilim-online.com/les-psaumes-de-David/Tehilim-' + id, function (error, response, html) { if (!error && response.statusCode == 200) { console.log("Psalm: " + id + " OK"); var $ = cheerio.load(html); var ph = $('#phonetiqueBlock span').text().split("\n"); var frNotFormatted = $('#traductionBlock p').text().split("\n"); var fr = []; frNotFormatted.forEach(function (item) { fr.push(removeLeadingVerseIndex(item)); }); var newObj = { ph: ph, fr: fr } // console.log(newObj); var path = "psalms/" + (id - 1).toString(); var ref = db.ref(path); ref.update(newObj, function (error) { if (error) { console.log("Data could not be saved." + error); } else { console.log("Psalm " + id + " saved successfully."); } }); } if (error) { console.log(response); } }); } while(psalmId <= 150) { var psalmTextArray = []; //runEnHeRequest(psalmId); runPhonetiqueFrRequest(psalmId); psalmId++; }
miroo93/TehillimForAll
TehillimForAll/srv/scrape.js
JavaScript
gpl-3.0
3,344
var _ = require('lodash'); var doFacesIntersect = require('./face-intersection').doFacesIntersect; function flatMeshIntersects(mesh){ var numFaces = mesh.faces.length; for (var i = 0; i < numFaces; ++i) { var firstFace = _.map(mesh.faces[i].vertices, function(vertexIndex){ return mesh.vertices[vertexIndex]; }); for (var j = i + 1; j < numFaces; ++j) { var secondFace = _.map(mesh.faces[j].vertices, function(vertexIndex){ return mesh.vertices[vertexIndex]; }); if (doFacesIntersect(firstFace, secondFace)) { return true; } } } return false; } exports.flatMeshIntersects = flatMeshIntersects;
mjleehh/paper-model
lib/algorithms/flat-mesh-intersection.js
JavaScript
gpl-3.0
737
angular.module('app.travels', ['pascalprecht.translate']) .controller('TravelsCtrl', function($scope, $http, $ionicModal, $timeout, $ionicLoading, $filter) { $scope.loadMorePagination = true; $scope.travels = []; $scope.page = 0; $scope.doRefresh = function() { /* travels refresh: */ $http.get(urlapi + 'travels?page=' + $scope.page) .then(function(data) { console.log('data success travels'); console.log(data); // for browser console //$scope.travels = data.data; // for UI $scope.travels = $scope.travels.concat(data.data); $scope.$broadcast('scroll.refreshComplete'); //refresher stop $scope.$broadcast('scroll.infiniteScrollComplete'); if (data.data.length < 1) { console.log("setting loadMorePagination to false"); $scope.loadMorePagination = false; $scope.$broadcast('scroll.infiniteScrollComplete'); } }, function(data) { console.log('data error'); $scope.$broadcast('scroll.refreshComplete'); //refresher stop $ionicLoading.show({ template: 'Error connecting server', noBackdrop: true, duration: 2000 }); }); }; $scope.doRefresh(); $scope.paginationNext = function() { if ($scope.loadMorePagination == true) { $scope.page++; console.log($scope.page); $scope.doRefresh(); }else{ console.log("limit pagination reached"); $scope.$broadcast('scroll.infiniteScrollComplete'); } }; });
arnaucode/carsincommonApp
www/js/travels.js
JavaScript
gpl-3.0
1,615
'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /******/(function (modules) { // webpackBootstrap /******/ // The module cache /******/var installedModules = {}; /******/ /******/ // The require function /******/function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/if (installedModules[moduleId]) { /******/return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/var module = installedModules[moduleId] = { /******/i: moduleId, /******/l: false, /******/exports: {} /******/ }; /******/ /******/ // Execute the module function /******/modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/module.l = true; /******/ /******/ // Return the exports of the module /******/return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/__webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/__webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/__webpack_require__.d = function (exports, name, getter) { /******/if (!__webpack_require__.o(exports, name)) { /******/Object.defineProperty(exports, name, { /******/configurable: false, /******/enumerable: true, /******/get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/__webpack_require__.n = function (module) { /******/var getter = module && module.__esModule ? /******/function getDefault() { return module['default']; } : /******/function getModuleExports() { return module; }; /******/__webpack_require__.d(getter, 'a', getter); /******/return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/__webpack_require__.o = function (object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/__webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/return __webpack_require__(__webpack_require__.s = 34); /******/ })( /************************************************************************/ /******/{ /***/2: /***/function _(module, __webpack_exports__, __webpack_require__) { "use strict"; /** * File get-customize-action.js. * * Function to get the Customize action for a given panel. */ /* harmony default export */ __webpack_exports__["a"] = function (panel) { var _window$wp$i18n = window.wp.i18n, __ = _window$wp$i18n.__, sprintf = _window$wp$i18n.sprintf; var panelInstance = panel && panel.length ? window.wp.customize.panel.instance(panel) : undefined; if (panelInstance) { return sprintf(__('Customizing &#9656; %s', 'super-awesome-theme'), panelInstance.params.title); } return __('Customizing', 'super-awesome-theme'); }; /***/ }, /***/3: /***/function _(module, __webpack_exports__, __webpack_require__) { "use strict"; /** * File customize-controls-util.js. * * Class containing Customizer controls utility methods. */ var CustomizeControlsUtil = function () { function CustomizeControlsUtil(wpCustomize) { _classCallCheck(this, CustomizeControlsUtil); this.customizer = wpCustomize || window.wp.customize; } _createClass(CustomizeControlsUtil, [{ key: 'bindSetting', value: function bindSetting(settingId, callback) { this.customizer.instance(settingId, function (setting) { callback(setting.get()); setting.bind(function () { callback(setting.get()); }); }); } }, { key: 'bindSettingToComponents', value: function bindSettingToComponents(settingId, componentIds, callback, componentType) { var self = this; componentType = componentType || 'control'; function listenToSetting() { var components = Array.prototype.slice.call(arguments, 0, componentIds.length); self.bindSetting(settingId, function (value) { components.forEach(function (component) { callback(value, component); }); }); } this.customizer[componentType].instance.apply(this.customizer[componentType], componentIds.concat([listenToSetting])); } }, { key: 'bindSettingToPanels', value: function bindSettingToPanels(settingId, panelIds, callback) { this.bindSettingToComponents(settingId, panelIds, callback, 'panel'); } }, { key: 'bindSettingToSections', value: function bindSettingToSections(settingId, sectionIds, callback) { this.bindSettingToComponents(settingId, sectionIds, callback, 'section'); } }, { key: 'bindSettingToControls', value: function bindSettingToControls(settingId, controlIds, callback) { this.bindSettingToComponents(settingId, controlIds, callback, 'control'); } }, { key: 'bindSettings', value: function bindSettings(settingIds, callback) { function bindSettings() { var settings = Array.prototype.slice.call(arguments, 0, settingIds.length); var values = {}; function updateSetting(setting) { values[setting.id] = setting.get(); } settings.forEach(function (setting) { updateSetting(setting); setting.bind(function () { updateSetting(setting); callback(values); }); }); callback(values); } this.customizer.instance.apply(this.customizer, settingIds.concat([bindSettings])); } }, { key: 'bindSettingsToComponents', value: function bindSettingsToComponents(settingIds, componentIds, callback, componentType) { var self = this; componentType = componentType || 'control'; function listenToSettings() { var components = Array.prototype.slice.call(arguments, 0, componentIds.length); self.bindSettings(settingIds, function (values) { components.forEach(function (component) { callback(values, component); }); }); } this.customizer[componentType].instance.apply(this.customizer[componentType], componentIds.concat([listenToSettings])); } }, { key: 'bindSettingsToPanels', value: function bindSettingsToPanels(settingIds, panelIds, callback) { this.bindSettingsToComponents(settingIds, panelIds, callback, 'panel'); } }, { key: 'bindSettingsToSections', value: function bindSettingsToSections(settingIds, sectionIds, callback) { this.bindSettingsToComponents(settingIds, sectionIds, callback, 'section'); } }, { key: 'bindSettingsToControls', value: function bindSettingsToControls(settingIds, controlIds, callback) { this.bindSettingsToComponents(settingIds, controlIds, callback, 'control'); } }]); return CustomizeControlsUtil; }(); /* harmony default export */ __webpack_exports__["a"] = CustomizeControlsUtil; /***/ }, /***/34: /***/function _(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */var __WEBPACK_IMPORTED_MODULE_0__customize_customize_controls_util__ = __webpack_require__(3); /* harmony import */var __WEBPACK_IMPORTED_MODULE_1__customize_get_customize_action__ = __webpack_require__(2); /** * File sidebar.customize-controls.js. * * Theme Customizer handling for the sidebar. */ (function (wp, data) { var api = wp.customize; var util = new __WEBPACK_IMPORTED_MODULE_0__customize_customize_controls_util__["a" /* default */](api); var __ = wp.i18n.__; var sidebarModeDependants = ['sidebar_size', 'blog_sidebar_enabled']; if (data.displayShopSidebarEnabledSetting) { sidebarModeDependants.push('shop_sidebar_enabled'); } api.bind('ready', function () { api.when('sidebar_mode', 'sidebar_size', 'blog_sidebar_enabled', function (sidebarMode, sidebarSize, blogSidebarEnabled) { sidebarMode.transport = 'postMessage'; sidebarSize.transport = 'postMessage'; blogSidebarEnabled.transport = 'postMessage'; }); api.panel.instance('layout', function () { api.section.add(new api.Section('sidebar', { panel: 'layout', title: __('Sidebar', 'super-awesome-theme'), customizeAction: Object(__WEBPACK_IMPORTED_MODULE_1__customize_get_customize_action__["a" /* default */])('layout') })); api.control.add(new api.Control('sidebar_mode', { setting: 'sidebar_mode', section: 'sidebar', label: __('Sidebar Mode', 'super-awesome-theme'), description: __('Specify if and how the sidebar should be displayed.', 'super-awesome-theme'), type: 'radio', choices: data.sidebarModeChoices })); api.control.add(new api.Control('sidebar_size', { setting: 'sidebar_size', section: 'sidebar', label: __('Sidebar Size', 'super-awesome-theme'), description: __('Specify the width of the sidebar.', 'super-awesome-theme'), type: 'radio', choices: data.sidebarSizeChoices })); api.control.add(new api.Control('blog_sidebar_enabled', { setting: 'blog_sidebar_enabled', section: 'sidebar', label: __('Enable Blog Sidebar?', 'super-awesome-theme'), description: __('If you enable the blog sidebar, it will be shown beside your blog and single post content instead of the primary sidebar.', 'super-awesome-theme'), type: 'checkbox' })); if (data.displayShopSidebarEnabledSetting) { api.control.add(new api.Control('shop_sidebar_enabled', { setting: 'shop_sidebar_enabled', section: 'sidebar', label: __('Enable Shop Sidebar?', 'super-awesome-theme'), description: __('If you enable the shop sidebar, it will be shown beside your shop and single product content instead of the primary sidebar.', 'super-awesome-theme'), type: 'checkbox' })); } }); // Handle visibility of the sidebar controls. util.bindSettingToControls('sidebar_mode', sidebarModeDependants, function (value, control) { control.active.set('no_sidebar' !== value); }); // Handle visibility of the actual blog sidebar widget area. util.bindSettingToSections('blog_sidebar_enabled', ['sidebar-widgets-blog'], function (value, section) { if (value) { section.activate(); return; } section.deactivate(); }); // Handle visibility of the actual shop sidebar widget area. if (data.displayShopSidebarEnabledSetting) { util.bindSettingToSections('shop_sidebar_enabled', ['sidebar-widgets-shop'], function (value, section) { if (value) { section.activate(); return; } section.deactivate(); }); } // Show a notification for the blog sidebar instead of hiding it. api.control('blog_sidebar_enabled', function (control) { var origOnChangeActive = control.onChangeActive; var hasNotification = false; control.onChangeActive = function (active) { var noticeCode = 'blog_sidebar_not_available'; if (active) { if (hasNotification) { hasNotification = false; control.container.find('input[type="checkbox"]').prop('disabled', false); control.container.find('.description').slideDown(180); control.notifications.remove(noticeCode); } origOnChangeActive.apply(this, arguments); } else { if ('no_sidebar' === api.instance('sidebar_mode').get()) { origOnChangeActive.apply(this, arguments); return; } hasNotification = true; control.container.find('input[type="checkbox"]').prop('disabled', true); control.container.find('.description').slideUp(180); control.notifications.add(noticeCode, new api.Notification(noticeCode, { type: 'info', message: __('This page doesn&#8217;t support the blog sidebar. Navigate to the blog page or another page that supports it.', 'super-awesome-theme') })); } }; }); }); })(window.wp, window.themeSidebarControlsData); /***/ } /******/ });
taco-themes/boilerplate
assets/dist/js/sidebar.customize-controls.js
JavaScript
gpl-3.0
13,082
import React, { Component } from 'react'; import { Link } from 'react-router-dom' import { CSSTransition } from 'react-transition-group'; class Nav extends Component { constructor(props) { super(props); this.state = { menuActive: false } this.handleClick = this.handleClick.bind(this); } handleClick() { var obj = {}; obj['menuActive'] = !this.state.menuActive; this.setState(obj); } render() { return ( <div className={this.state.menuActive? 'nav active': 'nav'} > <div className='nav__button' onClick={this.handleClick}> <div className='nav__buttonPart' /> <div className='nav__buttonPart' /> <div className='nav__buttonPart' /> <div className="nav__buttonTitle"> {this.state.menuActive? <div>Close</div> : <div>Menu</div>} </div> </div> <div className='nav__menuBox'> <ul className='nav__menu'> <li className='nav__menuItem'> <Link to='/'> home </Link> </li> <li className='nav__menuItem'> <Link to='/'> blog </Link> </li> <li className='nav__menuItem'> <Link to='/About'> about </Link> </li> </ul> </div> <CSSTransition in={this.state.menuActive} timeout={300} classNames="nav__background" > <div className="nav__background"/> </CSSTransition> <CSSTransition in={this.state.menuActive} timeout={300} classNames="nav__shadowBackground" > <div className="nav__shadowBackground"/> </CSSTransition> </div> ); } } export default Nav;
7sleepwalker/addicted-to-mnt
src/js/Components/Nav.js
JavaScript
gpl-3.0
1,662
/* * Copyright (C) 2009-2016 by the geOrchestra PSC * * This file is part of geOrchestra. * * geOrchestra is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) * any later version. * * geOrchestra is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * geOrchestra. If not, see <http://www.gnu.org/licenses/>. */ /* * @requires GeoExt/Lang.js */ /* * French translation file */ OpenLayers.Lang.fr = OpenLayers.Util.extend(OpenLayers.Lang.fr, { /* General purpose strings */ "Yes": "Oui", "No": "Non", "OK": "OK", "or": "ou", "Cancel": "Annuler", "Save": "Sauvegarder", "Loading...": "Chargement...", "File": "Fichier", "Layer": "Couche", "layers": "couches", "Description": "Description", "Error": "Erreur", "Server": "Serveur", "Close": "Fermer", "labelSeparator": " : ", "File submission failed or invalid file": "L'envoi du fichier a échoué - le fichier est peut-être non valide", "Type": "Type", "Title": "Titre", "Actions": "Actions", "Incorrect server response.": "Réponse du serveur incorrecte.", "No features found.": "Aucun objet trouvé.", /* GEOR.js strings */ "Cities": "Localités", "Recentering on GeoNames cities": "Recentrage sur localités<br />de la base GeoNames", "Referentials": "Référentiels", "Recentering on a selection of referential layers": "Recentrage sur une sélection<br />de couches \"référentiels\"", "Addresses": "Adresses", "Recentering on a given address": "Recentrage sur point adresse", "Available layers": "Couches disponibles", "WMS Search": "Recherche WMS", "WFS Search": "Recherche WFS", "resultspanel.emptytext": "<p>Sélectionnez l'outil d'interrogation " + "ou construisez une requête sur une couche.<br />" + "Les attributs des objets s'afficheront dans ce cadre.</p>", /* GEOR_ClassificationPanel.js strings */ "Attribute": "Attribut", "Number of classes": "Nombre de classes", "Minimum size": "Taille minimum", "Maximum size": "Taille maximum", "First color": "Première couleur", "Last color": "Dernière couleur", "Palette": "Palette", "Auto classification": "Classification automatique", "Classify": "Classifier", "Unique values": "Valeurs uniques", "Color range": "Plages de couleurs", "Proportional symbols": "Symboles proportionnels", /* GEOR_FeatureDataModel.js strings */ "objects": "objets", /* GEOR_address.js strings */ "Go to: ": "Aller à : ", "searching...": "recherche en cours...", "adressSearchExemple": "ex: 4, Hugo, Brest", /* GEOR_ajaxglobal.js strings strings */ "Server did not respond.": "Le serveur n'a pas répondu.", "Server access denied.": "Le serveur a refusé de répondre.", "ajax.badresponse": "Le service a répondu, mais le contenu de la " + "réponse n'est pas conforme à celle attendue", "Server unavailable.": "Le serveur est temporairement indisponible. Veuillez réessayer ultérieurement.", "Too much data.": "Données trop volumineuses.", "Server exception.": "Le serveur a renvoyé une exception.", "ajax.defaultexception": "Pour plus d'information, vous pouvez " + "chercher le code de retour sur <a href=\"http://" + "en.wikipedia.org/wiki/List_of_HTTP_status_codes\" target=\"_blank\">" + "cette page</a>.", "An error occured.<br />": "Une erreur est survenue.<br />", "Warning : browser may freeze": "Attention : risque de blocage du navigateur", "ajaxglobal.data.too.big": "Les données provenant du serveur sont trop " + "volumineuses.<br />Le serveur a envoyé ${SENT}KO " + "(la limite est à ${LIMIT}KO)<br />Voulez-vous tout de même continuer ?", /* GEOR_config.js strings */ /* GEOR_cswbrowser.js strings */ "NAME layer": "Couche ${NAME}", "Metadata without a name": "Métadonnée non nommée", "The getDomain CSW query failed": "La requête CSW getDomain a échoué", "Error for the thesaurus": "Erreur sur le thésaurus", "Missing key to access the thesaurus": "Absence de clé pour accéder à ce thésaurus", "Keywords query failed": "La requête des mots clés a échoué", "Thesaurus:": "Thésaurus :", "Thesaurus": "Thésaurus", "cswbrowser.default.thesaurus.mismatch": "Administrateur : problème de configuration - " + "la variable DEFAULT_THESAURUS_KEY ne correspond à aucune" + " valeur exportée par GeoNetwork", /* GEOR_cswquerier.js strings */ "cswquerier.help.title": "Syntaxe pour la recherche avancée", "cswquerier.help.message": "<ul><li><b>@mot</b> cherche dans le nom de l'organisation.</li><li><b>#mot</b> cherche dans les mots clés de la métadonnée.</li><li><b>?mot</b> élargit la recherche à tous les champs de la métadonnée.</li></ul>", "NAME layer on VALUE": "Couche ${NAME} sur ${VALUE}", "Show metadata essentials in a window": "Afficher les métadonnées basiques", "Show metadata sheet in a new browser tab": "Afficher la métadonnée complète dans un nouvel onglet", "more": "plus", "Click to select or deselect the layer": "Cliquez pour sélectionner ou désélectionner la couche", "Open the URL url in a new window": "Ouvrir l'url ${URL} dans une nouvelle fenêtre", "Unreachable server": "Serveur non disponible", "Catalogue": "Catalogue", "Find": "Chercher", "in": "dans", "No linked layer.": "Aucune couche.", "One layer found.": "Une couche trouvée.", "NB layers found.": "${NB} couches trouvées.", "NB metadata match the query.": "${NB} métadonnées correspondent à la requête.", "A single metadata matches the query.": "Une unique métadonnée correspond à la requête.", "Precise your request.": "Précisez votre requête.", "No metadata matches the query.": "Aucune métadonnée ne correspond à la requête.", "Limit to map extent": "Limiter à l'étendue de la carte", "Search limited to current map extent.": "Recherche limitée à l'étendue de la carte.", /* GEOR_fileupload.js strings */ "2D only": "géométries 2D", "Local file": "Fichier", "The service is inactive": "Le service est inactif", "Upload a vector data file.": "Uploadez un fichier de données vectorielles.", "The allowed formats are the following: ": "Les formats acceptés sont les suivants : ", "Use ZIP compression for multifiles formats, such as": "Utilisez la compression ZIP pour les formats multi-fichiers comme", "fileupload_error_incompleteMIF": "Fichier MIF/MID incomplet.", "fileupload_error_incompleteSHP": "Fichier shapefile incomplet.", "fileupload_error_incompleteTAB": "Fichier TAB incomplet.", "fileupload_error_ioError": "Erreur d'I/O sur le serveur. Contacter l'administrateur de la plateforme pour plus de détails.", "fileupload_error_multipleFiles": "L'archive ZIP contient plusieurs fichiers de données. Elle ne doit en contenir qu'un seul.", "fileupload_error_outOfMemory": "Le serveur ne dispose plus de la mémoire suffisante. Contacter l'administrateur de la plateforme pour plus de détails.", "fileupload_error_sizeError": "Le fichier est trop grand pour pouvoir être traité.", "fileupload_error_unsupportedFormat": "Ce format de données n'est pas géré par l'application.", "fileupload_error_projectionError": "Une erreur est survenue lors de la lecture des coordonnées géographiques. Êtes-vous sûr que le fichier contient les informations de projection ?", "server upload error: ERROR": "L'upload du fichier a échoué. ${ERROR}", /* GEOR_geonames.js strings */ /* GEOR_getfeatureinfo.js strings */ "<div>Searching...</div>": "<div>Recherche en cours...</div>", "<div>No layer selected</div>": "<div>Aucune couche sélectionnée</div>", "<div>Search on objects active for NAME layer. Click on the map.</div>": "<div>Recherche d\'objets activée sur la couche ${NAME}. " + "Cliquez sur la carte.</div>", "WMS GetFeatureInfo at ": "GetFeatureInfo WMS sur ", /* GEOR_layerfinder.js strings */ "metadata": "métadonnée", "Add layers from local files": "Ajouter des couches en uploadant un fichier depuis votre ordinateur", "Find layers searching in metadata": "Trouvez des couches en cherchant dans les métadonnées", "Find layers from keywords": "Trouvez des couches par mots clés", "Find layers querying OGC services": "Trouvez des couches en interrogeant des services OGC", "layerfinder.layer.unavailable": "La couche ${NAME} n'a pas été trouvée dans le service WMS.<br/<br/>" + "Peut-être n'avez-vous pas le droit d'y accéder " + "ou alors cette couche n'est plus disponible", "Layer projection is not compatible": "La projection de la couche n'est pas compatible.", "The NAME layer does not contain a valid geometry column": "La couche ${NAME} ne possède pas de colonne géométrique valide.", "Add": "Ajouter", "Add layers from a ...": "Ajouter des couches depuis un ...", "Malformed URL": "URL non conforme.", "Queryable": "Interrogeable", "Opaque": "Opaque", "OGC server": "Serveur OGC", "I'm looking for ...": "Je recherche ...", "Service type": "Type de service", "Choose a server": "Choisissez un serveur", "... or enter its address": "... ou saisissez son adresse", "The server is publishing one layer with an incompatible projection": "Le serveur publie une couche dont la projection n'est pas compatible", "The server is publishing NB layers with an incompatible projection": "Le serveur publie ${NB} couches dont la projection n'est pas " + "compatible", "This server does not support HTTP POST": "Ce serveur ne supporte pas HTTP POST", "Unreachable server or insufficient rights": "Réponse invalide du " + "serveur. Raisons possibles : droits insuffisants, " + "serveur injoignable, trop de données, etc.", /* GEOR_managelayers.js strings */ "layergroup": "couche composite", "Service": "Service", "Protocol": "Protocole", "About this layer": "A propos de cette couche", "Set as overlay": "Passer en calque", "Set as baselayer": "Passer en couche de fond", "Tiled mode" : "Mode tuilé", "Confirm NAME layer deletion ?": "Voulez-vous réellement supprimer la couche ${NAME} ?", "1:MAXSCALE to 1:MINSCALE": "1:${MAXSCALE} à 1:${MINSCALE}", "Visibility range (indicative):<br />from TEXT": "Plage de visibilité (indicative):<br />de ${TEXT}", "Information on objects of this layer": "Interroger les objets de cette couche", "default style": "style par défaut", "no styling": "absence de style", "Recenter on the layer": "Recentrer sur la couche", "Impossible to get layer extent": "Impossible d'obtenir l'étendue de la couche.", "Refresh layer": "Recharger la couche", "Show metadata": "Afficher les métadonnées", "Edit symbology": "Éditer la symbologie", "Build a query": "Construire une requête", "Download data": "Extraire les données", "Choose a style": "Choisir un style", "Modify format": "Modifier le format", "Delete this layer": "Supprimer cette couche", "Push up this layer": "Monter cette couche", "Push down this layer": "descendre cette couche", "Add layers": "Ajouter des couches", "Remove all layers": "Supprimer toutes les couches", "Are you sure you want to remove all layers ?": "Voulez vous réellement supprimer toutes les couches ?", "source: ": "source : ", "unknown": "inconnue", "Draw new point": "Dessiner un nouveau point", "Draw new line": "Dessiner une nouvelle ligne", "Draw new polygon": "Dessiner un nouveau polygone", "Edition": "Edition", "Editing": "Edition en cours", "Switch on/off edit mode for this layer": "Basculer cette couche en mode édition", "No geometry column.": "Colonne géométrique non détectée.", "Geometry column type (TYPE) is unsupported.": "Le type de la colonne géométrique (${TYPE}) n'est pas supporté.", "Switching to attributes-only edition.": "Seuls les attributs des objets existants seront éditables.", /* GEOR_map.js strings */ "Location map": "Carte de situation", "Warning after loading layer": "Avertissement suite au chargement de couche", "The <b>NAME</b> layer could not appear for this reason: ": "La couche <b>${NAME}</b> pourrait ne pas apparaître pour " + "la raison suivante : ", "Min/max visibility scales are invalid": "Les échelles min/max de visibilité sont invalides.", "Visibility range does not match map scales": "La plage de visibilité ne correspond pas aux échelles de la carte.", "Geografic extent does not match map extent": "L'étendue géographique ne correspond pas à celle de la carte.", /* GEOR_mapinit.js strings */ "Add layers from WMS services": "Ajouter des couches depuis des services WMS", "Add layers from WFS services": "Ajouter des couches depuis des services WFS", "NB layers not imported": "${NB} couches non importées", "One layer not imported": "Une couche non importée", "mapinit.layers.load.error": "Les couches nommées ${LIST} n'ont pas pu être chargées. " + "Raisons possibles : droits insuffisants, SRS incompatible ou couche non existante", "NB layers imported": "${NB} couches importées", "One layer imported": "Une couche importée", "No layer imported": "Aucune couche importée", "The provided context is not valid": "Le contexte fourni n'est pas valide", "The default context is not defined (and it is a BIG problem!)": "Le contexte par défaut n'est pas défini " + "(et ce n'est pas du tout normal !)", "Error while loading file": "Erreur au chargement du fichier", /* GEOR_mappanel.js strings */ "Coordinates in ": "Coordonnées en ", "scale picker": "échelle", /* GEOR_ows.js strings */ "The NAME layer was not found in WMS service.": "La couche ${NAME} n'a pas été trouvée dans le service WMS.", "Problem restoring a context saved with buggy Chrome 36 or 37": "Nous ne pouvons restaurer un contexte enregistré avec Chrome 36 ou 37", /* GEOR_print.js strings */ "Sources: ": "Sources : ", "Source: ": "Source : ", "Projection: PROJ": "Projection : ${PROJ}", "Print error": "Impression impossible", "Print server returned an error": "Le service d'impression a signalé une erreur.", "Contact platform administrator": "Contactez l'administrateur de la plateforme.", "Layer unavailable for printing": "Couche non disponible pour impression", "The NAME layer cannot be printed.": "La couche ${NAME} ne peut pas encore être imprimée.", "Unable to print": "Impression non disponible", "The print server is currently unreachable": "Le service d'impression est actuellement inaccessible.", "print.unknown.layout": "Erreur de configuration: DEFAULT_PRINT_LAYOUT " + "${LAYOUT} n'est pas dans la liste des formats d'impression", "print.unknown.resolution": "Erreur de configuration: DEFAULT_PRINT_RESOLUTION " + "${RESOLUTION} n'est pas dans la liste des résolutions d'impression", "print.unknown.format": "Erreur de configuration: le format " + "${FORMAT} n'est pas supporté par le serveur d'impression", "Pick an output format": "Choisissez un format de sortie", "Comments": "Commentaires", "Scale: ": "Échelle : ", "Date: ": "Date : ", "Minimap": "Mini-carte", "North": "Nord", "Scale": "Échelle", "Date": "Date", "Legend": "Légende", "Format": "Format", "Resolution": "Résolution", "Print the map": "Impression de la carte", "Print": "Imprimer", "Printing...": "Impression en cours...", "Print current map": "Imprimer la carte courante", /* GEOR_Querier.js strings */ "Fields of filters with a red mark are mandatory": "Vous devez remplir " + "les champs des filtres marqués en rouge.", "Request on NAME": "Requêteur sur ${NAME}", "WFS GetFeature on filter": "GetFeature WFS sur un filtre", "Search": "Rechercher", "querier.layer.no.geom": "La couche ne possède pas de colonne géométrique." + "<br />Le requêteur géométrique ne sera pas fonctionnel.", "querier.layer.error": "Impossible d'obtenir les caractéristiques de la couche demandée." + "<br />Le requêteur ne sera pas disponible.", /* GEOR_referentials.js strings */ "Referential": "Référentiel", "There is no geometry column in the selected referential": "Le référentiel sélectionné ne possède pas de colonne géométrique", "Choose a referential": "Choisissez un référentiel", /* GEOR_resultspanel.js strings */ "Symbology": "Symbologie", "Edit this panel's features symbology": "Editer la symbologie de la sélection", "Reset": "Réinitialiser", "Export is not possible: features have no geometry": "Export impossible : absence de géométries", "resultspanel.maxfeature.reached": " <span ext:qtip=\"Utilisez un navigateur plus performant " + "pour augmenter le nombre d'objets affichables\">" + "Nombre maximum d'objets atteint (${NB})</span>", "NB results": "${NB} résultats", "One result": "1 résultat", "No result": "Aucun résultat", "Clean": "Effacer", "All": "Tous", "None": "Aucun", "Invert selection": "Inverser la sélection", "Actions on the selection or on all results if no row is selected": "Actions sur la sélection ou sur tous les résultats si aucun n'est sélectionné", "Store the geometry": "Enregistrer la géométrie", "Aggregates the geometries of the selected features and stores it in your browser for later use in the querier": "La géométrie des objets sélectionnés est enregistrée pour un usage ultérieur dans le requêteur", "Geometry successfully stored in this browser": "Géométrie enregistrée avec succès sur ce navigateur", "Clean all results on the map and in the table": "Supprimer les " + "résultats affichés sur la carte et dans le tableau", "Zoom": "Zoom", "Zoom to results extent": "Cadrer l'étendue de la carte sur celle " + "des résultats", "Export": "Export", "Export results as": "Exporter l'ensemble des résultats en", "<p>No result for this request.</p>": "<p>Aucun objet ne " + "correspond à votre requête.</p>", /* GEOR_scalecombo.js strings */ /* GEOR_selectfeature.js strings */ "<div>Select features activated on NAME layer. Click on the map.</div>": "<div>Sélection d\'objets activée sur la couche ${NAME}. " + "Cliquez sur la carte.</div>", "OpenLayers SelectFeature":"Sélection d\'objets", /* GEOR_styler.js strings */ "Download style": "Télécharger le style", "You can download your SLD style at ": "Votre SLD est disponible à " + "l\'adresse suivante : ", "Thanks!": "Merci !", "Saving SLD": "Sauvegarde du SLD", "Some classes are invalid, verify that all fields are correct": "Des " + "classes ne sont pas valides, vérifier que les champs sont corrects", "Get SLD": "Récupération du SLD", "Malformed SLD": "Le SLD n'est pas conforme.", "circle": "cercle", "square": "carré", "triangle": "triangle", "star": "étoile", "cross": "croix", "x": "x", "customized...": "personnalisé...", "Classification ...<br/>(this operation can take some time)": "Classification ...<br/>(cette opération peut prendre du temps)", "Class": "Classe", "Untitled": "Sans titre", "styler.guidelines": "Utiliser le bouton \"+\" pour créer une classe, et le bouton " + "\"Analyse\" pour créer un ensemble de classes définies par une " + "analyse thématique.</p>", "Analyze": "Analyse", "Add a class": "Ajouter une classe", "Delete the selected class": "Supprimer la classe sélectionnée", "Styler": "Styleur", "Apply": "Appliquer", "Impossible to complete the operation:": "Opération impossible :", "no available attribute": "aucun attribut disponible.", /* GEOR_toolbar.js strings */ "m": "m", "hectares": "hectares", "zoom to global extent of the map": "zoom sur l'étendue globale de la " + "carte", "pan": "glisser - déplacer la carte", "zoom in": "zoom en avant (pour zoomer sur une emprise: appuyer sur SHIFT + dessiner l'emprise)", "zoom out": "zoom en arrière", "back to previous zoom": "revenir à la précédente emprise", "go to next zoom": "aller à l'emprise suivante", "Login": "Connexion", "Logout": "Déconnexion", "Help": "Aide", "Query all active layers": "Interroger toutes les couches actives", "Show legend": "Afficher la légende", "Leave this page ? You will lose the current cartographic context.": "Vous allez quitter cette page et perdre le contexte cartographique " + "courant", "Online help": "Aide en ligne", "Display the user guide": "Afficher le guide de l'utilisateur", "Contextual help": "Aide contextuelle", "Activate or deactivate contextual help bubbles": "Activer ou désactiver les bulles d'aide contextuelle", /* GEOR_tools.js strings */ "Tools": "Outils", "tools": "outils", "tool": "outil", "No tool": "aucun outil", "Manage tools": "Gérer les outils", "remember the selection": "se souvenir de la sélection", "Available tools:": "Outils disponibles :", "Click to select or deselect the tool": "Cliquez pour (dé)sélectionner l'outil", "Could not load addon ADDONNAME": "Impossible de charger l'addon ${ADDONNAME}", "Your new tools are now available in the tools menu.": 'Vos nouveaux outils sont disponibles dans le menu "outils"', /* GEOR_util.js strings */ "Characters": "Caractères", "Digital": "Numérique", "Boolean": "Booléen", "Other": "Autre", "Confirmation": "Confirmation", "Information": "Information", "pointOfContact": "contact", "custodian": "producteur", "distributor": "distributeur", "originator": "instigateur", "More": "Plus", "Could not parse metadata.": "Impossible d'analyser la métadonnée", "Could not get metadata.": "Impossible d'obtenir la métadonnée", /* GEOR_waiter.js strings */ /* GEOR_wmc.js strings */ "The provided file is not a valid OGC context": "Le fichier fourni n'est pas un contexte OGC valide", "Warning: trying to restore WMC with a different projection (PROJCODE1, while map SRS is PROJCODE2). Strange things might occur !": "Attention: le contexte restauré avait été sauvegardé en ${PROJCODE1} alors que la carte actuelle est en ${PROJCODE2}. Il pourrait y avoir des comportements inattendus.", /* GEOR_wmcbrowser.js strings */ "all contexts": "toutes les cartes", "Could not find WMC file": "Le fichier spécifié n'existe pas", "... or a local context": "... ou une carte locale", "Load or add the layers from one of these map contexts:": "Charger ou ajouter les couches de l'une de ces cartes :", "A unique OSM layer": "Une unique couche OpenStreetMap", "default viewer context": "carte par défaut", "(default)": "<br/>(carte par défaut)", /* GEOR_workspace.js strings */ "Created:": "Date de création : ", "Last accessed:": "Date de dernier accès : ", "Access count:": "Nombre d'accès : ", "Permalink:": "Permalien : ", "My contexts": "Mes cartes", "Created": "Création", "Accessed": "Accédé", "Count": "Accès", "View": "Visualiser", "View the selected context": "Visualiser la carte sélectionnée (attention : remplacera la carte courante)", "Download": "Télécharger", "Download the selected context": "Télécharger la carte sélectionnée", "Delete": "Supprimer", "Delete the selected context": "Supprimer la carte sélectionnée", "Failed to delete context": "Impossible de supprimer la carte", "Manage my contexts": "Gérer mes cartes", "Keywords": "Mots clés", "comma separated keywords": "mots clés séparés par une virgule", "Save to metadata": "Créer une métadonnée", "in group": "dans le groupe", "The context title is mandatory": "Le titre de la carte est obligatoire", "There was an error creating the metadata.": "La création de la métadonnée a échoué.", "Share this map": "Partager cette carte", "Mobile viewer": "Visualiseur mobile", "Mobile compatible viewer on sdi.georchestra.org": "Visualiseur mobile sur sdi.georchestra.org", "Desktop viewer": "Visualiseur web", "Desktop viewer on sdi.georchestra.org": "Visualiseur web sur sdi.georchestra.org", "Abstract": "Résumé", "Context saving": "Sauvegarde de la carte", "The file is required.": "Un nom de fichier est nécessaire.", "Context restoring": "Restauration d'une carte", "<p>Please note that the WMC must be UTF-8 encoded</p>": "<p>Notez que le" + " fichier de contexte doit être encodé en UTF-8.</p>", "Load": "Charger", "Workspace": "Espace de travail", "Save the map context": "Sauvegarder la carte", "Load a map context": "Charger une carte", "Get a permalink": "Obtenir un permalien", "Permalink": "Permalien", "Share your map with this URL: ": "Partagez la carte avec l'adresse suivante : ", /* GEOR_edit.js */ "Req.": "Req.", // requis "Required": "Requis", "Not required": "Non requis", "Synchronization failed.": "Erreur lors de la synchronisation.", "Edit activated": "Edition activée", "Hover the feature you wish to edit, or choose \"new feature\" in the edit menu": "Survolez les objets de la couche que vous souhaitez modifier, ou choisissez \"nouvel objet\" dans le menu d'édition de la couche", /* GeoExt.data.CSW.js */ "no abstract": "pas de résumé" // no trailing comma }); GeoExt.Lang.add("fr", { "GeoExt.ux.FeatureEditorGrid.prototype": { deleteMsgTitle: "Suppression", deleteMsg: "Confirmer la suppression de cet objet vectoriel ?", deleteButtonText: "Supprimer", deleteButtonTooltip: "Supprimer cet objet", cancelMsgTitle: "Annulation", cancelMsg: "L'objet a été modifié localement. Confirmer l'abandon des changements ?", cancelButtonText: "Annuler", cancelButtonTooltip: "Abandonner les modifications en cours", saveButtonText: "Enregistrer", saveButtonTooltip: "Enregistrer les modifications", nameHeader: "Attribut", valueHeader: "Valeur" } });
jusabatier/georchestra
mapfishapp/src/main/webapp/app/js/GEOR_Lang/fr.js
JavaScript
gpl-3.0
27,587
(function () { angular .module("WebAppMaker") .controller("EditPageController", EditPageController) .controller("PageListController", PageListController) .controller("NewPageController", NewPageController); function EditPageController(PageService, $routeParams, $location) { var vm = this; vm.updatePage = updatePage; vm.deletePage = deletePage; vm.userId = $routeParams['uid']; vm.websiteId = $routeParams['wid']; vm.pageId = $routeParams['pid']; function init() { PageService.findPageById(vm.pageId) .then( res => { vm.page = res.data; }, res => { vm.pageNotFound = true; }); } init(); function updatePage(page) { PageService.updatePage( vm.pageId, page ) .then( res => { $location.url(`/user/${vm.userId}/website/${vm.websiteId}/page`); }, res => { vm.errorUpdating = true; }); } function deletePage() { PageService.deletePage(vm.pageId) .then( res => { $location.url(`/user/${ vm.userId }/website/${ vm.websiteId }/page`); }, res => { vm.errorDeleting = true; }); } }; function PageListController(PageService, $routeParams) { var vm = this; var userId = $routeParams.uid; var websiteId = $routeParams.wid; vm.userId = userId; vm.websiteId = websiteId; function init() { PageService.findPagesByWebsiteId( vm.websiteId ) .then( res => { vm.pages = res.data; }, res => { vm.error = true; }); } init(); }; function NewPageController(PageService, $routeParams, $location) { var vm = this; vm.create = create; function init() { vm.userId = $routeParams.uid; vm.websiteId = $routeParams.wid; PageService.findPagesByWebsiteId( vm.websiteId ) .then( res => { vm.pages = res.data; }, res => { vm.error = true; }); } init(); function create(newPage) { PageService.createPage( vm.websiteId, newPage ) .then( res => { $location.url(`/user/${ vm.userId }/website/${ vm.websiteId }/page`); }, res => { vm.errorCreating = true; }); } }; })();
knuevena/knueven-andrew-webdev
public/assignment/views/page/page.controller.client.js
JavaScript
gpl-3.0
2,586
define(['react','app','dataTable','dataTableBoot'], function (React,app,DataTable,dataTableBoot) { return React.createClass({ mixins: [app.mixins.touchMixins()], getInitialState : function() { var dataSet = []; return { dataSet:dataSet, mainChecker:[], emailInFolder:0, displayedFolder:"", }; }, componentWillReceiveProps: function(nextProps) { //console.log(this.props.folderId); if(this.props.folderId!=nextProps.folderId && this.props.folderId!=""){ this.updateEmails(nextProps.folderId,''); //console.log(nextProps.folderId); } //this.setState({ // likesIncreasing: nextProps.likeCount > this.props.likeCount //}); }, updateEmails: function(folderId,noRefresh) { var thisComp = this; var emails = app.user.get('emails')['folders'][folderId]; // if (thisComp.state.emailInFolder == Object.keys(emails).length && thisComp.state.displayedFolder == app.transform.from64str(app.user.get('folders')[folderId]['name'])) { //} else { var emailListCopy=app.user.get("folderCached"); if(emailListCopy[folderId]===undefined){ emailListCopy[folderId]={}; } thisComp.setState({ "displayedFolder": app.transform.from64str(app.user.get('folders')[folderId]['name']), "emailInFolder": Object.keys(emails).length }); app.user.set({ 'currentFolder': app.transform.from64str(app.user.get('folders')[folderId]['name']) }); //console.log(app.user.get('folders')[folderId]['role']); if (app.user.get('folders')[folderId]['role'] != undefined) { var t = app.transform.from64str(app.user.get('folders')[folderId]['role']); } else { var t = ''; } //console.log(t); var data = []; var d = new Date(); var trusted = app.user.get("trustedSenders"); var encrypted2 = ""; $.each(emails, function (index, folderData) { if(emailListCopy[folderId][index]!==undefined){ var unread = folderData['st'] == 0 ? "unread" : folderData['st'] == 1 ? "fa fa-mail-reply" : folderData['st'] == 2 ? "fa fa-mail-forward" : ""; var row = { "DT_RowId": index, "email": { "display": '<div class="email no-padding ' + unread + '">' + emailListCopy[folderId][index]["checkBpart"] + emailListCopy[folderId][index]["dateAtPart"] + emailListCopy[folderId][index]["fromPart"] + '<div class="title ellipsisText col-xs-10 col-md-6"><span>' + emailListCopy[folderId][index]["sb"] + '</span> - ' + emailListCopy[folderId][index]["bd"] + '</div>' +emailListCopy[folderId][index]["tagPart"] + '</div>', //"open":folderData['o']?1:0, "timestamp": emailListCopy[folderId][index]["timestamp"] } }; }else { var time = folderData['tr'] != undefined ? folderData['tr'] : folderData['tc'] != undefined ? folderData['tc'] : ''; //console.log(time); if (d.toDateString() == new Date(parseInt(time + '000')).toDateString()) { var dispTime = new Date(parseInt(time + '000')).toLocaleTimeString(); } else { var dispTime = new Date(parseInt(time + '000')).toLocaleDateString(); } var fromEmail = []; var fromTitle = []; var recipient = []; var recipientTitle = []; var trust = ""; if (folderData['to'].length > 0) { $.each(folderData['to'], function (indexTo, email) { // console.log(email); if (app.transform.check64str(email)) { var str = app.transform.from64str(email); } else { var str = email; } recipient.push(app.globalF.parseEmail(str)['name']); recipientTitle.push(app.globalF.parseEmail(str)['email']); }); } else if (Object.keys(folderData['to']).length > 0) { $.each(folderData['to'], function (indexTo, email) { try { var str = app.transform.from64str(indexTo); var name = ""; if (email === undefined) { name = str; } else { if (email['name'] === undefined) { name = str; } else { if (email['name'] === "") { name = str; } else { name = app.transform.from64str(email['name']); } } } recipient.push(name); recipientTitle.push(str); } catch (err) { recipient.push('error'); recipientTitle.push('error'); } }); } //console.log(recipient); if (t == 'Sent' || t == 'Draft') { // console.log(folderData['to']); // console.log(folderData['cc']); // console.log(folderData['bcc']); fromEmail = ''; fromTitle = ''; if (folderData['cc'] != undefined && Object.keys(folderData['cc']).length > 0) { $.each(folderData['cc'], function (indexCC, email) { try { var str = app.transform.from64str(indexCC); var name = ""; if (email === undefined) { name = str; } else { if (email['name'] === undefined) { name = str; } else { if (email['name'] === "") { name = str; } else { name = app.transform.from64str(email['name']); } } } recipient.push(name); recipientTitle.push(str); } catch (err) { recipient.push('error'); recipientTitle.push('error'); } }); } if (folderData['bcc'] != undefined && Object.keys(folderData['bcc']).length > 0) { $.each(folderData['bcc'], function (indexBCC, email) { try { var str = app.transform.from64str(indexBCC); var name = ""; if (email === undefined) { name = str; } else { if (email['name'] === undefined) { name = str; } else { if (email['name'] === "") { name = str; } else { name = app.transform.from64str(email['name']); } } } recipient.push(name); recipientTitle.push(str); } catch (err) { recipient.push('error'); recipientTitle.push('error'); } }); } recipient = recipient.join(', '); recipientTitle = recipientTitle.join(', '); fromEmail = recipient; fromTitle = recipientTitle; } else { var str = app.transform.from64str(folderData['fr']); //console.log(str); fromEmail = app.globalF.parseEmail(str, true)['name']; fromTitle = app.globalF.parseEmail(str, true)['email']; if (trusted.indexOf(app.transform.SHA256(app.globalF.parseEmail(str)['email'])) !== -1) { //console.log('X'); trust = "<img src='/img/logo/logo.png' style='height:25px'/>" } else { trust = "" } recipient = recipient.join(', '); recipientTitle = recipientTitle.join(', '); } if (folderData['tg'].length > 0) { //console.log(folderData['tg']); var tag = folderData['tg'][0]['name']; } else { var tag = ""; } if (parseInt(folderData['en']) == 1) { encrypted2 = "<i class='fa fa-lock fa-lg'></i>"; } else if (parseInt(folderData['en']) == 0) { encrypted2 = "<i class='fa fa-unlock fa-lg'></i>"; } else if (parseInt(folderData['en']) == 3) { encrypted2 = ""; } //console.log(tag); tag = app.globalF.stripHTML(app.transform.from64str(tag)); //console.log(app.transform.from64str(tag)); var unread = folderData['st'] == 0 ? "unread" : folderData['st'] == 1 ? "fa fa-mail-reply" : folderData['st'] == 2 ? "fa fa-mail-forward" : ""; var attch = folderData['at'] == "1" ? '<span class="fa fa-paperclip fa-lg"></span>' : ""; if (fromEmail == "") { fromEmail = fromTitle; } var checkBpart = '<label><input class="emailchk hidden-xs" type="checkbox"/></label>'; var fromPart = '<span class="from no-padding col-xs-8 col-md-3 ellipsisText margin-right-10" data-placement="bottom" data-toggle="popover-hover" title="" data-content="' + fromTitle + '">' + trust + ' ' + fromEmail + '</span>'; var dateAtPart = '<span class="no-padding date col-xs-3 col-sm-2">' + attch + '&nbsp;' + encrypted2 + ' ' + dispTime + '<span class="label label-primary f-s-10"></span><span class="label label-primary f-s-10"></span></span>'; var tagPart = '<div class="mailListLabel pull-right text-right col-xs-2"><div class="ellipsisText visible-xs"><span class="label label-success">' + tag + '</span></div><div class="ellipsisText hidden-xs col-xs-12 pull-right"><span class="label label-success">' + tag + '</span></div></div>'; emailListCopy[folderId][index]={ "DT_RowId": index, "unread":unread, "checkBpart":checkBpart, "dateAtPart":dateAtPart, "fromPart":fromPart, "sb":app.transform.escapeTags(app.transform.from64str(folderData['sb'])), "bd":app.transform.escapeTags(app.transform.from64str(folderData['bd'])), "tagPart":tagPart, "timestamp": time }; var row = { "DT_RowId": index, "email": { "display": '<div class="email no-padding ' + emailListCopy[folderId][index]["unread"] + '">' + emailListCopy[folderId][index]["checkBpart"] + emailListCopy[folderId][index]["dateAtPart"] + emailListCopy[folderId][index]["fromPart"] + '<div class="title ellipsisText col-xs-10 col-md-6"><span>' + emailListCopy[folderId][index]["sb"] + '</span> - ' + emailListCopy[folderId][index]["bd"] + '</div>' +emailListCopy[folderId][index]["tagPart"] + '</div>', //"open":folderData['o']?1:0, "timestamp": emailListCopy[folderId][index]["timestamp"] } }; } data.push(row); }); app.user.set({"folderCached":emailListCopy}); // console.log(data); var t = $('#emailListTable').DataTable(); t.clear(); if (noRefresh == '') { t.draw(); //$('#mMiddlePanel').scrollTop(0); } t.rows.add(data); t.draw(false); this.attachTooltip(); $('#emailListTable td').click(function () { var selectedEmails = app.user.get('selectedEmails'); if ($(this).find('.emailchk').prop("checked")) { selectedEmails[$(this).parents('tr').attr('id')] = true; } else { delete selectedEmails[$(this).parents('tr').attr('id')]; } // console.log(selectedEmails); }); //} }, componentDidMount: function() { //todo delete // setInterval(function(){ // console.log('sdsads'); // app.globalF.syncUpdates(); //},10000); //console.log(this.state.dataSet); var dtSet=this.state.dataSet; var thisComp=this; //require(['dataTable','dataTableBoot'], function(DataTable,dataTableBoot) { //data example //}); $('#emailListTable').dataTable( { "dom": '<"#checkAll"><"#emailListNavigation"pi>rt<"pull-right"p><"pull-right"i>', "data": dtSet, "columns": [ { data: { _: "email.display", sort: "email.timestamp", filter: "email.display" } } ], "columnDefs": [ { "sClass": 'col-xs-12 border-right text-align-left no-padding padding-vertical-10', "targets": 0}, { "orderDataType": "data-sort", "targets": 0 } ], "sPaginationType": "simple", "order": [[0,"desc"]], "iDisplayLength": app.user.get("mailPerPage"), "language": { "emptyTable": "Empty", "info": "_START_ - _END_ of _TOTAL_", "infoEmpty": "No entries", "paginate": { "sPrevious": "<i class='fa fa-chevron-left'></i>", "sNext": "<i class='fa fa-chevron-right'></i>" } }, fnDrawCallback: function(nRow, aData, iDisplayIndex, iDisplayIndexFull) { $("#emailListTable thead").remove(); //console.log(nRow); //console.log($('#mMiddlePanel').scrollTop()); //$('#mMiddlePanel').scrollTop(0); }, "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) { // console.log($(nRow).attr('id')); // console.log(app.user.get('currentMessageView')['id']); if($(nRow).attr('id')==app.user.get('currentMessageView')['id']){ $(nRow).addClass('selected') } if( app.user.get("selectedEmails")[$(nRow).attr('id')]!==undefined){ $(nRow).find('.emailchk').prop('checked',true); } //$(nRow).attr('id', aData[0]); return nRow; } } ); //console.log(app.globalF.getInboxFolderId()); app.globalF.getInboxFolderId(function(inbox){ thisComp.updateEmails(inbox,''); }); app.user.on("change:resetSelectedItems",function() { if(app.user.get("resetSelectedItems")){ app.user.set({"selectedEmails":{}}); app.user.set({"resetSelectedItems":false}); } },thisComp); // app.user.set({"resetSelectedItems":true}); app.user.on("change:emailListRefresh",function() { // console.log(app.user.get("resetSelectedItems")); thisComp.updateEmails(thisComp.props.folderId,'noRefresh') // $('#selectAll>input').prop("checked",false); },thisComp); var container = $('#checkAll'); //$(thisComp.selectAll()).appendTo(container); var mainChecker=[]; $('#checkAll').html('<div class="btn-group btn btn-default borderless pull-left hidden-xs" id="selectAll"><input type="checkbox"/> </div>'); /* <i class="fa fa-angle-down fa-lg" data-toggle="dropdown"></i><ul id="mvtofolder1" class="dropdown-menu"><li><a id="thisPage">this page</a></li><li><a id="wholeFolder">All in folder</a></li></ul> */ /* $('#thisPage').click( function () { if($('#selectAll>input').prop("checked")){ $('#selectAll>input').prop("checked",false); }else{ $('#selectAll>input').prop("checked",true); } thisComp.selectThisPage(thisComp.state.selectedEmails); } ); $('#wholeFolder').click( function () { if($('#selectAll>input').prop("checked")){ $('#selectAll>input').prop("checked",false); }else{ $('#selectAll>input').prop("checked",true); } thisComp.selectAll(thisComp.state.selectedEmails); } ); */ $('#selectAll').change(function() { var selectedEmails=app.user.get('selectedEmails'); if($('#selectAll>input').prop("checked")){ $(".emailchk").prop('checked', true); $( ".emailchk" ).each(function( index ) { var messageId=$( this ).closest('tr').attr('id'); selectedEmails[messageId]=true; }); // console.log(selectedEmails); }else{ //console.log('unselecting') //console.log(selectedEmails); $(".emailchk").prop('checked', false); app.user.set({"selectedEmails":{}}); } // console.log($('#selectAll>input').prop("checked")); }); }, /*selectThisPage:function(thisComp){ selectedEmails=thisComp.state.selectedEmails; },*/ componentWillUnmount: function () { app.user.off("change:emailListRefresh"); }, handleClick: function(i,event) { switch(i) { case 'wholeFolder': // console.log('wholeFolder') break; case 'thisPage': // console.log('thisPage') break; case 'readEmail': //console.log('ghfghfg'); var thisComp=this; var folder=app.user.get('folders')[this.props.folderId]['name']; app.mixins.canNavigate(function(decision){ if(decision){ var id=$(event.target).parents('tr').attr('id'); if(!$(event.target).is('input')){ app.globalF.resetCurrentMessage(); app.globalF.resetDraftMessage(); Backbone.history.navigate("/mail/"+app.transform.from64str(folder), { trigger : true }); if(id!=undefined && $(event.target).attr('type')!="checkbox" && $(event.target).prop("tagName")!="LABEL"){ var table = $('#emailListTable').DataTable(); table.$('tr.selected').removeClass('selected'); $(event.target).parents('tr').toggleClass('selected'); //table.row('.selected').remove().draw( false ); //var modKey=app.user.get('emails')['messages'][id]['mK']; //console.log(id); //console.log(modKey); app.globalF.renderEmail(id); //thisComp.handleClick('editFolder',id); app.mixins.hidePopHover(); //thisComp.handleClick('toggleEmail'); } } }else{ } }); break; } }, attachTooltip: function() { //console.log('gg'); $('[data-toggle="popover-hover"]').popover({ trigger: "hover" ,container: 'body'}); $('[data-toggle="popover-hover"]').on('shown.bs.popover', function () { var $pop = $(this); setTimeout(function () { $pop.popover('hide'); }, 5000); }); }, componentDidUpdate:function(){ //this.attachTooltip(); }, render: function () { var middleClass="Middle inbox checkcentr col-lg-6 col-xs-12"; //console.log(this.props.panel.middlePanel); //$('[data-toggle="popover-hover"]').popover({ trigger: "hover" ,container: 'body'}); return ( <div className={this.props.panel.middlePanel+ " no-padding"} id="mMiddlePanel"> <table className="table table-hover table-inbox row-border clickable" id="emailListTable" onClick={this.handleClick.bind(this, 'readEmail')}> </table> </div> ); } }); });
SCRYPTmail/frontEnd
app/src/authorized/mailbox/middlepanel/emailList.js
JavaScript
gpl-3.0
23,324
$(function() { (function() { $('.j_toClass').each(function(index, el) { var $it = $(this); var targetTo = $it.attr('data-target'); var thisTo = $it.attr('data-this'); var targetId = $it.attr('href'); var $target = $(targetId); var _fn = { on: function() { $target.addClass(targetTo); $it.addClass(thisTo); }, off: function() { $target.removeClass(targetTo); $it.removeClass(thisTo); } }; targetTo = targetTo && targetTo !== '' ? targetTo : 'on'; thisTo = thisTo && thisTo !== '' ? thisTo : 'on'; $it.on('click', function(e) { e.preventDefault; }).on('mouseenter', function() { _fn.on(); return false; }).on('mouseleave', function() { _fn.off(); return false; }); }); })(); $('.j-tab').on('click','a',function(e){ e.preventDefault(); var $it=$(this); var targetId=$it.attr('href'); var $target=$(targetId); $it.addClass('on').siblings('.on').removeClass('on'); $target.addClass('on').siblings('.on').removeClass('on'); $target.find('img[data-src]').each(function(index, el) { var $it=$(this); var src=$it.attr('data-src'); $it.attr('src',src).removeAttr('data-src'); }); }); //弹出框 $('body').on('click','.modal-close, .modal .j-close',function(e){ e.preventDefault(); var $it=$(this); var $moldal=$it.parents('.modal'); $it.parents('.modal').removeClass('on'); }).on('click','.j-modal',function(e){ e.preventDefault(); var $it=$(this); var targetId=$it.attr('href'); var $target=$(targetId); $target.addClass('on'); }); });
pro27/kezhanbang-m
static/global/js/global.js
JavaScript
gpl-3.0
1,583
'use strict'; var Dispatcher = require('../core/appDispatcher'); var EventEmitter = require('events').EventEmitter; var ActionTypes = require('./actionTypes'); var CHANGE_EVENT = 'change'; var utils = require('../core/utils'); function TradingStore() { var previousRate = null; var symbols = "GBP/USD"; var quantity = "GBP 1,000,000"; var model = null; var self = this; var store = { getInitialState: getInitialState, addChangeListener: addChangeListener, removeChangeListener: removeChangeListener }; init(); return store; //////////////////////// function init() { model = { isExecuting: false, symbols: 'GBP/USD', quantity: "GBP 1,000,000", movement: "none", spread: 1.6, buyPips: { bigFig: "1.61", fractionalPips: "5", pips: "49" }, sellPips: { bigFig: "1.61", fractionalPips: "9", pips: "47" } }; Dispatcher.register(function(action) { switch(action.actionType) { case ActionTypes.RATE_CHANGED: onRateChanged(action.updatedRate); break; case ActionTypes.TRADE_WILLEXECUTE: onTradeWillExecute(); break; case ActionTypes.TRADE_EXECUTED: onTradeDidExecute(action.updatedTrade); break; default: // no op } }); } function onTradeDidExecute(updatedTrade) { model.isExecuting = false; } function onTradeWillExecute() { model.isExecuting = true; self.emit(CHANGE_EVENT, model); } function onRateChanged(newRate) { if (model.isExecuting) { return; } model = $.extend(model, { movement: calculateMovement(previousRate || newRate, newRate), buyPips: formatPips(newRate.buy), sellPips: formatPips(newRate.sell) }, newRate); previousRate = newRate; self.emit(CHANGE_EVENT, model); } function addChangeListener(callback) { self.on(CHANGE_EVENT, callback); } function removeChangeListener(callback) { self.removeListener(CHANGE_EVENT, callback); } function calculateMovement(priorRate, newRate) { var x = newRate.buy - priorRate.buy; switch(true) { case x < 0 : return "down"; case x > 0 : return "up"; default : return "none"; } } function formatPips(spotRate) { var str = "" + spotRate; var pad = "0000000"; var ans = str + pad.substring(0, pad.length - str.length); return { bigFig: ans.substring(0, 4), pips: ans.substring(4, 6), fractionalPips: ans.substring(6, 8) }; } function getInitialState() { return model; } } utils.inherits(TradingStore, EventEmitter); module.exports = new TradingStore();
Digiterre/trading-tile-clients
react-standard-flux/src/app/trading/tradingStore.js
JavaScript
gpl-3.0
2,742
require.config({ baseUrl: 'vendor', waitSeconds: 10, paths: { core: '../core', lang: '../lang', root: '..' }, shim: { 'backbone': { deps: ['underscore', 'jquery'], exports: 'Backbone' }, 'underscore': { exports: '_' } } }); require(['root/config'],function(Config){ require.config({ paths: { theme: '../themes/'+ Config.theme } }); require(['jquery', 'core/app-utils', 'core/app', 'core/router', 'core/region-manager', 'core/stats', 'core/phonegap-utils'], function ($, Utils, App, Router, RegionManager, Stats, PhoneGap) { var launch = function() { // Initialize application before using it App.initialize( function() { RegionManager.buildHead(function(){ RegionManager.buildLayout(function(){ RegionManager.buildHeader(function(){ App.router = new Router(); require(['theme/js/functions'], function(){ App.sync( function(){ RegionManager.buildMenu(function(){ //Menu items are loaded by App.sync Stats.updateVersion(); Stats.incrementCountOpen(); Stats.incrementLastOpenTime(); if( Config.debug_mode == 'on' ){ Utils.log( 'App version : ', Stats.getVersionDiff() ); Utils.log( 'App opening count : ', Stats.getCountOpen() ); Utils.log( 'Last app opening was on ', Stats.getLastOpenDate() ); } App.launchRouting(); App.sendInfo('app-launched'); //triggers info:app-ready, info:app-first-launch and info:app-version-changed //Refresh at app launch can be canceled using the 'refresh-at-app-launch' App param, //this is useful if we set a specific launch page and don't want to be redirected //after the refresh. if( App.getParam('refresh-at-app-launch') ){ //Refresh at app launch : as the theme is now loaded, use theme-app : require(['core/theme-app'],function(ThemeApp){ last_updated = App.options.get( 'last_updated' ); refresh_interval = App.options.get( 'refresh_interval' ); if( undefined === last_updated || undefined === refresh_interval || Date.now() > last_updated.get( 'value' ) + ( refresh_interval.get( 'value' ) * 1000 ) ) { Utils.log( 'Refresh interval exceeded, refreshing', { last_updated: last_updated, refresh_interval: refresh_interval } ); ThemeApp.refresh(); } }); } PhoneGap.hideSplashScreen(); }); }, function(){ Backbone.history.start(); Utils.log("launch.js error : App could not synchronize with website."); PhoneGap.hideSplashScreen(); App.sendInfo('no-content'); }, false //true to force refresh local storage at each app launch. ); }, function(error){ Utils.log('Error : theme/js/functions.js not found', error); } ); }); }); }); }); }; if( PhoneGap.isLoaded() ){ PhoneGap.setNetworkEvents(App.onOnline,App.onOffline); document.addEventListener('deviceready', launch, false); }else{ window.ononline = App.onOnline; window.onoffline = App.onOffline; $(document).ready(launch); } }); },function(){ //Config.js not found //Can't use Utils.log here : log messages by hand : var message = 'WP AppKit error : config.js not found.'; console && console.log(message); document.write(message); //Check if we are simulating in browser : var query = window.location.search.substring(1); if( query.length && query.indexOf('wpak_app_id') != -1 ){ message = 'Please check that you are connected to your WordPress back office.'; console && console.log(message); document.write('<br>'+ message); } });
HammyHavoc/Voidance-Records-App
core/launch.js
JavaScript
gpl-3.0
4,158
import { module, test } from 'qunit'; import { setupTest } from 'ember-qunit'; module('Unit | Service | slider', function(hooks) { setupTest(hooks); // Replace this with your real tests. test('it exists', function(assert) { let service = this.owner.lookup('service:slider'); assert.ok(service); }); });
adiwg/mdEditor
tests/unit/services/slider-test.js
JavaScript
gpl-3.0
321
module.exports = function(el, state, container) { var ul = el.getElementsByTagName('ul')[0] var lastFlags = [] var controlsTouch = -1 var containerTouch = {"id":-1, "x":-1, "y":-1} el.addEventListener('touchstart', startTouchControls) el.addEventListener('touchmove', handleTouchControls) el.addEventListener('touchend', unTouchControls) container.addEventListener('touchstart', startTouchContainer) container.addEventListener('touchmove', handleTouchContainer) container.addEventListener('touchend', unTouchContainer) function startTouchControls(event) { if (controlsTouch === -1) { controlsTouch = event.targetTouches[0].identifier } handleTouchControls(event) } function handleTouchControls(event) { event.preventDefault() var touch = null if (event.targetTouches.length > 1) { for (t in event.targetTouches) { if (event.targetTouches[t].identifier === controlsTouch) { touch = event.targetTouches[t] break } } } else { touch = event.targetTouches[0] } if (touch === null) return var top=touch.clientY-el.offsetTop var left=touch.clientX-el.offsetLeft var flags=[] if (top < 50) flags.push('forward') if (left < 50 && top < 100) flags.push('left') if (left > 100 && top < 100) flags.push('right') if (top > 100 && left > 50 && left < 100) flags.push('backward') if (top > 50 && top < 100 && left > 50 && left < 100) flags.push('jump') if (flags.indexOf('jump') === -1) { for (flag in lastFlags) { if (flags.indexOf(lastFlags[flag]) !== -1) { lastFlags.splice(flag, 1) } } setState(lastFlags, 0) setState(flags, 1) lastFlags = flags } else if (lastFlags.indexOf('jump') === -1) { // Start jumping (in additional to existing movement) lastFlags.push('jump') setState(['jump'], 1) } } function unTouchControls() { setState(lastFlags, 0) lastFlags = [] controlsTouch = -1 } function setState(states, value) { var delta = {} for(s in states) { delta[states[s]] = value } state.write(delta) } function startTouchContainer(event) { if (containerTouch.id === -1) { containerTouch.id = event.targetTouches[0].identifier containerTouch.x = event.targetTouches[0].clientX containerTouch.y = event.targetTouches[0].clientY } handleTouchContainer(event) } function handleTouchContainer(event) { event.preventDefault() var touch = null, x = y = -1, delta = {} for (t in event.targetTouches) { if (event.targetTouches[t].identifier === containerTouch.id) { touch = event.targetTouches[t] break } } if (touch === null) return dx = containerTouch.x - touch.clientX dy = containerTouch.y - touch.clientY delta.x_rotation_accum = dy * 2 delta.y_rotation_accum = dx * 8 state.write(delta) containerTouch.x = touch.clientX containerTouch.y = touch.clientY } function unTouchContainer(event) { containerTouch = {"id":-1, "x":-1, "y":-1} } }
pauln/voxel-touchcontrols
index.js
JavaScript
gpl-3.0
3,130
/** @license MIT License (c) copyright B Cavalier & J Hann */ /** * when * A lightweight CommonJS Promises/A and when() implementation * * when is part of the cujo.js family of libraries (http://cujojs.com/) * * Licensed under the MIT License at: * http://www.opensource.org/licenses/mit-license.php * * @version 1.3.0 */ (function(define) { define(function() { var freeze, reduceArray, slice, undef; // // Public API // when.defer = defer; when.reject = reject; when.isPromise = isPromise; when.all = all; when.some = some; when.any = any; when.map = map; when.reduce = reduce; when.chain = chain; /** Object.freeze */ freeze = Object.freeze || function(o) { return o; }; /** * Trusted Promise constructor. A Promise created from this constructor is * a trusted when.js promise. Any other duck-typed promise is considered * untrusted. * * @constructor */ function Promise() {} Promise.prototype = freeze({ always: function(alwaysback, progback) { return this.then(alwaysback, alwaysback, progback); }, otherwise: function(errback) { return this.then(undef, errback); } }); /** * Create an already-resolved promise for the supplied value * @private * * @param value anything * @return {Promise} */ function resolved(value) { var p = new Promise(); p.then = function(callback) { try { return promise(callback ? callback(value) : value); } catch(e) { return rejected(e); } }; return freeze(p); } /** * Create an already-rejected {@link Promise} with the supplied * rejection reason. * @private * * @param reason rejection reason * @return {Promise} */ function rejected(reason) { var p = new Promise(); p.then = function(callback, errback) { try { return errback ? promise(errback(reason)) : rejected(reason); } catch(e) { return rejected(e); } }; return freeze(p); } /** * Returns a rejected promise for the supplied promiseOrValue. If * promiseOrValue is a value, it will be the rejection value of the * returned promise. If promiseOrValue is a promise, its * completion value will be the rejected value of the returned promise * * @param promiseOrValue {*} the rejected value of the returned {@link Promise} * * @return {Promise} rejected {@link Promise} */ function reject(promiseOrValue) { return when(promiseOrValue, function(value) { return rejected(value); }); } /** * Creates a new, CommonJS compliant, Deferred with fully isolated * resolver and promise parts, either or both of which may be given out * safely to consumers. * The Deferred itself has the full API: resolve, reject, progress, and * then. The resolver has resolve, reject, and progress. The promise * only has then. * * @memberOf when * @function * * @returns {Deferred} */ function defer() { var deferred, promise, listeners, progressHandlers, _then, _progress, complete; listeners = []; progressHandlers = []; /** * Pre-resolution then() that adds the supplied callback, errback, and progback * functions to the registered listeners * * @private * * @param [callback] {Function} resolution handler * @param [errback] {Function} rejection handler * @param [progback] {Function} progress handler * * @throws {Error} if any argument is not null, undefined, or a Function */ _then = function unresolvedThen(callback, errback, progback) { var deferred = defer(); listeners.push(function(promise) { promise.then(callback, errback) .then(deferred.resolve, deferred.reject, deferred.progress); }); progback && progressHandlers.push(progback); return deferred.promise; }; /** * Registers a handler for this {@link Deferred}'s {@link Promise}. Even though all arguments * are optional, each argument that *is* supplied must be null, undefined, or a Function. * Any other value will cause an Error to be thrown. * * @memberOf Promise * * @param [callback] {Function} resolution handler * @param [errback] {Function} rejection handler * @param [progback] {Function} progress handler * * @throws {Error} if any argument is not null, undefined, or a Function */ function then(callback, errback, progback) { return _then(callback, errback, progback); } /** * Resolves this {@link Deferred}'s {@link Promise} with val as the * resolution value. * * @memberOf Resolver * * @param val anything */ function resolve(val) { complete(resolved(val)); } /** * Rejects this {@link Deferred}'s {@link Promise} with err as the * reason. * * @memberOf Resolver * * @param err anything */ function reject(err) { complete(rejected(err)); } /** * @private * @param update */ _progress = function(update) { var progress, i = 0; while (progress = progressHandlers[i++]) progress(update); }; /** * Emits a progress update to all progress observers registered with * this {@link Deferred}'s {@link Promise} * * @memberOf Resolver * * @param update anything */ function progress(update) { _progress(update); } /** * Transition from pre-resolution state to post-resolution state, notifying * all listeners of the resolution or rejection * * @private * * @param completed {Promise} the completed value of this deferred */ complete = function(completed) { var listener, i = 0; // Replace _then with one that directly notifies with the result. _then = completed.then; // Replace complete so that this Deferred can only be completed // once. Also Replace _progress, so that subsequent attempts to issue // progress throw. complete = _progress = function alreadyCompleted() { // TODO: Consider silently returning here so that parties who // have a reference to the resolver cannot tell that the promise // has been resolved using try/catch throw new Error("already completed"); }; // Free progressHandlers array since we'll never issue progress events // for this promise again now that it's completed progressHandlers = undef; // Notify listeners // Traverse all listeners registered directly with this Deferred while (listener = listeners[i++]) { listener(completed); } listeners = []; }; /** * The full Deferred object, with both {@link Promise} and {@link Resolver} * parts * @class Deferred * @name Deferred */ deferred = {}; // Promise and Resolver parts // Freeze Promise and Resolver APIs promise = new Promise(); promise.then = deferred.then = then; /** * The {@link Promise} for this {@link Deferred} * @memberOf Deferred * @name promise * @type {Promise} */ deferred.promise = freeze(promise); /** * The {@link Resolver} for this {@link Deferred} * @memberOf Deferred * @name resolver * @class Resolver */ deferred.resolver = freeze({ resolve: (deferred.resolve = resolve), reject: (deferred.reject = reject), progress: (deferred.progress = progress) }); return deferred; } /** * Determines if promiseOrValue is a promise or not. Uses the feature * test from http://wiki.commonjs.org/wiki/Promises/A to determine if * promiseOrValue is a promise. * * @param promiseOrValue anything * * @returns {Boolean} true if promiseOrValue is a {@link Promise} */ function isPromise(promiseOrValue) { return promiseOrValue && typeof promiseOrValue.then === 'function'; } /** * Register an observer for a promise or immediate value. * * @function * @name when * @namespace * * @param promiseOrValue anything * @param {Function} [callback] callback to be called when promiseOrValue is * successfully resolved. If promiseOrValue is an immediate value, callback * will be invoked immediately. * @param {Function} [errback] callback to be called when promiseOrValue is * rejected. * @param {Function} [progressHandler] callback to be called when progress updates * are issued for promiseOrValue. * * @returns {Promise} a new {@link Promise} that will complete with the return * value of callback or errback or the completion value of promiseOrValue if * callback and/or errback is not supplied. */ function when(promiseOrValue, callback, errback, progressHandler) { // Get a promise for the input promiseOrValue // See promise() var trustedPromise = promise(promiseOrValue); // Register promise handlers return trustedPromise.then(callback, errback, progressHandler); } /** * Returns promiseOrValue if promiseOrValue is a {@link Promise}, a new Promise if * promiseOrValue is a foreign promise, or a new, already-resolved {@link Promise} * whose resolution value is promiseOrValue if promiseOrValue is an immediate value. * * Note that this function is not safe to export since it will return its * input when promiseOrValue is a {@link Promise} * * @private * * @param promiseOrValue anything * * @returns Guaranteed to return a trusted Promise. If promiseOrValue is a when.js {@link Promise} * returns promiseOrValue, otherwise, returns a new, already-resolved, when.js {@link Promise} * whose resolution value is: * * the resolution value of promiseOrValue if it's a foreign promise, or * * promiseOrValue if it's a value */ function promise(promiseOrValue) { var promise, deferred; if(promiseOrValue instanceof Promise) { // It's a when.js promise, so we trust it promise = promiseOrValue; } else { // It's not a when.js promise. Check to see if it's a foreign promise // or a value. deferred = defer(); if(isPromise(promiseOrValue)) { // It's a compliant promise, but we don't know where it came from, // so we don't trust its implementation entirely. Introduce a trusted // middleman when.js promise // IMPORTANT: This is the only place when.js should ever call .then() on // an untrusted promise. promiseOrValue.then(deferred.resolve, deferred.reject, deferred.progress); promise = deferred.promise; } else { // It's a value, not a promise. Create an already-resolved promise // for it. deferred.resolve(promiseOrValue); promise = deferred.promise; } } return promise; } /** * Return a promise that will resolve when howMany of the supplied promisesOrValues * have resolved. The resolution value of the returned promise will be an array of * length howMany containing the resolutions values of the triggering promisesOrValues. * * @memberOf when * * @param promisesOrValues {Array} array of anything, may contain a mix * of {@link Promise}s and values * @param howMany * @param [callback] * @param [errback] * @param [progressHandler] * * @returns {Promise} */ function some(promisesOrValues, howMany, callback, errback, progressHandler) { checkCallbacks(2, arguments); return when(promisesOrValues, function(promisesOrValues) { var toResolve, results, ret, deferred, resolver, rejecter, handleProgress, len, i; len = promisesOrValues.length >>> 0; toResolve = Math.max(0, Math.min(howMany, len)); results = []; deferred = defer(); ret = when(deferred, callback, errback, progressHandler); // Wrapper so that resolver can be replaced function resolve(val) { resolver(val); } // Wrapper so that rejecter can be replaced function reject(err) { rejecter(err); } // Wrapper so that progress can be replaced function progress(update) { handleProgress(update); } function complete() { resolver = rejecter = handleProgress = noop; } // No items in the input, resolve immediately if (!toResolve) { deferred.resolve(results); } else { // Resolver for promises. Captures the value and resolves // the returned promise when toResolve reaches zero. // Overwrites resolver var with a noop once promise has // be resolved to cover case where n < promises.length resolver = function(val) { // This orders the values based on promise resolution order // Another strategy would be to use the original position of // the corresponding promise. results.push(val); if (!--toResolve) { complete(); deferred.resolve(results); } }; // Rejecter for promises. Rejects returned promise // immediately, and overwrites rejecter var with a noop // once promise to cover case where n < promises.length. // TODO: Consider rejecting only when N (or promises.length - N?) // promises have been rejected instead of only one? rejecter = function(err) { complete(); deferred.reject(err); }; handleProgress = deferred.progress; // TODO: Replace while with forEach for(i = 0; i < len; ++i) { if(i in promisesOrValues) { when(promisesOrValues[i], resolve, reject, progress); } } } return ret; }); } /** * Return a promise that will resolve only once all the supplied promisesOrValues * have resolved. The resolution value of the returned promise will be an array * containing the resolution values of each of the promisesOrValues. * * @memberOf when * * @param promisesOrValues {Array|Promise} array of anything, may contain a mix * of {@link Promise}s and values * @param [callback] {Function} * @param [errback] {Function} * @param [progressHandler] {Function} * * @returns {Promise} */ function all(promisesOrValues, callback, errback, progressHandler) { checkCallbacks(1, arguments); return when(promisesOrValues, function(promisesOrValues) { return _reduce(promisesOrValues, reduceIntoArray, []); }).then(callback, errback, progressHandler); } function reduceIntoArray(current, val, i) { current[i] = val; return current; } /** * Return a promise that will resolve when any one of the supplied promisesOrValues * has resolved. The resolution value of the returned promise will be the resolution * value of the triggering promiseOrValue. * * @memberOf when * * @param promisesOrValues {Array|Promise} array of anything, may contain a mix * of {@link Promise}s and values * @param [callback] {Function} * @param [errback] {Function} * @param [progressHandler] {Function} * * @returns {Promise} */ function any(promisesOrValues, callback, errback, progressHandler) { function unwrapSingleResult(val) { return callback ? callback(val[0]) : val[0]; } return some(promisesOrValues, 1, unwrapSingleResult, errback, progressHandler); } /** * Traditional map function, similar to `Array.prototype.map()`, but allows * input to contain {@link Promise}s and/or values, and mapFunc may return * either a value or a {@link Promise} * * @memberOf when * * @param promise {Array|Promise} array of anything, may contain a mix * of {@link Promise}s and values * @param mapFunc {Function} mapping function mapFunc(value) which may return * either a {@link Promise} or value * * @returns {Promise} a {@link Promise} that will resolve to an array containing * the mapped output values. */ function map(promise, mapFunc) { return when(promise, function(array) { return _map(array, mapFunc); }); } /** * Private map helper to map an array of promises * @private * * @param promisesOrValues {Array} * @param mapFunc {Function} * @return {Promise} */ function _map(promisesOrValues, mapFunc) { var results, len, i; // Since we know the resulting length, we can preallocate the results // array to avoid array expansions. len = promisesOrValues.length >>> 0; results = new Array(len); // Since mapFunc may be async, get all invocations of it into flight // asap, and then use reduce() to collect all the results for(i = 0; i < len; i++) { if(i in promisesOrValues) results[i] = when(promisesOrValues[i], mapFunc); } // Could use all() here, but that would result in another array // being allocated, i.e. map() would end up allocating 2 arrays // of size len instead of just 1. Since all() uses reduce() // anyway, avoid the additional allocation by calling reduce // directly. return _reduce(results, reduceIntoArray, results); } /** * Traditional reduce function, similar to `Array.prototype.reduce()`, but * input may contain {@link Promise}s and/or values, and reduceFunc * may return either a value or a {@link Promise}, *and* initialValue may * be a {@link Promise} for the starting value. * * @memberOf when * * @param promise {Array|Promise} array of anything, may contain a mix * of {@link Promise}s and values. May also be a {@link Promise} for * an array. * @param reduceFunc {Function} reduce function reduce(currentValue, nextValue, index, total), * where total is the total number of items being reduced, and will be the same * in each call to reduceFunc. * @param initialValue starting value, or a {@link Promise} for the starting value * * @returns {Promise} that will resolve to the final reduced value */ function reduce(promise, reduceFunc, initialValue) { var args = slice.call(arguments, 1); return when(promise, function(array) { return _reduce.apply(undef, [array].concat(args)); }); } /** * Private reduce to reduce an array of promises * @private * * @param promisesOrValues {Array} * @param reduceFunc {Function} * @param initialValue {*} * @return {Promise} */ function _reduce(promisesOrValues, reduceFunc, initialValue) { var total, args; total = promisesOrValues.length; // Skip promisesOrValues, since it will be used as 'this' in the call // to the actual reduce engine below. // Wrap the supplied reduceFunc with one that handles promises and then // delegates to the supplied. args = [ function (current, val, i) { return when(current, function (c) { return when(val, function (value) { return reduceFunc(c, value, i, total); }); }); } ]; if (arguments.length > 2) args.push(initialValue); return reduceArray.apply(promisesOrValues, args); } /** * Ensure that resolution of promiseOrValue will complete resolver with the completion * value of promiseOrValue, or instead with resolveValue if it is provided. * * @memberOf when * * @param promiseOrValue * @param resolver {Resolver} * @param [resolveValue] anything * * @returns {Promise} */ function chain(promiseOrValue, resolver, resolveValue) { var useResolveValue = arguments.length > 2; return when(promiseOrValue, function(val) { if(useResolveValue) val = resolveValue; resolver.resolve(val); return val; }, function(e) { resolver.reject(e); return rejected(e); }, resolver.progress ); } // // Utility functions // /** * Helper that checks arrayOfCallbacks to ensure that each element is either * a function, or null or undefined. * * @private * * @param arrayOfCallbacks {Array} array to check * @throws {Error} if any element of arrayOfCallbacks is something other than * a Functions, null, or undefined. */ function checkCallbacks(start, arrayOfCallbacks) { var arg, i = arrayOfCallbacks.length; while(i > start) { arg = arrayOfCallbacks[--i]; if (arg != null && typeof arg != 'function') throw new Error('callback is not a function'); } } /** * No-Op function used in method replacement * @private */ function noop() {} slice = [].slice; // ES5 reduce implementation if native not available // See: http://es5.github.com/#x15.4.4.21 as there are many // specifics and edge cases. reduceArray = [].reduce || function(reduceFunc /*, initialValue */) { // ES5 dictates that reduce.length === 1 // This implementation deviates from ES5 spec in the following ways: // 1. It does not check if reduceFunc is a Callable var arr, args, reduced, len, i; i = 0; arr = Object(this); len = arr.length >>> 0; args = arguments; // If no initialValue, use first item of array (we know length !== 0 here) // and adjust i to start at second item if(args.length <= 1) { // Skip to the first real element in the array for(;;) { if(i in arr) { reduced = arr[i++]; break; } // If we reached the end of the array without finding any real // elements, it's a TypeError if(++i >= len) { throw new TypeError(); } } } else { // If initialValue provided, use it reduced = args[1]; } // Do the actual reduce for(;i < len; ++i) { // Skip holes if(i in arr) reduced = reduceFunc(reduced, arr[i], i, arr); } return reduced; }; return when; }); })(typeof define == 'function' ? define : function (factory) { typeof module != 'undefined' ? (module.exports = factory()) : (this.when = factory()); } // Boilerplate for AMD, Node, and browser global ); /** * @license * Lo-Dash 1.2.0 <http://lodash.com/> * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.4.4 <http://underscorejs.org/> * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud Inc. * Available under MIT license <http://lodash.com/license> */ ;(function(window) { /** Used as a safe reference for `undefined` in pre ES5 environments */ var undefined; /** Detect free variable `exports` */ var freeExports = typeof exports == 'object' && exports; /** Detect free variable `module` */ var freeModule = typeof module == 'object' && module && module.exports == freeExports && module; /** Detect free variable `global`, from Node.js or Browserified code, and use it as `window` */ var freeGlobal = typeof global == 'object' && global; if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { window = freeGlobal; } /** Used to generate unique IDs */ var idCounter = 0; /** Used internally to indicate various things */ var indicatorObject = {}; /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */ var keyPrefix = +new Date + ''; /** Used as the size when optimizations are enabled for large arrays */ var largeArraySize = 200; /** 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 */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g; /** * Used to match ES6 template delimiters * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.8.6 */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match regexp flags from their coerced string values */ var reFlags = /\w*$/; /** Used to match "interpolate" template delimiters */ var reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match leading zeros to be removed */ var reLeadingZeros = /^0+(?=.$)/; /** Used to ensure capturing order of template delimiters */ var reNoMatch = /($^)/; /** Used to match HTML characters */ var reUnescapedHtml = /[&<>"']/g; /** Used to match unescaped characters in compiled string literals */ var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g; /** Used to assign default `context` object properties */ var contextProps = [ 'Array', 'Boolean', 'Date', 'Function', 'Math', 'Number', 'Object', 'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN', 'parseInt', 'setImmediate', 'setTimeout' ]; /** Used to fix the JScript [[DontEnum]] bug */ var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; /** Used to make template sourceURLs easier to identify */ var templateCounter = 0; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; /** Used to identify object classifications that `_.clone` supports */ var cloneableClasses = {}; cloneableClasses[funcClass] = false; cloneableClasses[argsClass] = cloneableClasses[arrayClass] = cloneableClasses[boolClass] = cloneableClasses[dateClass] = cloneableClasses[numberClass] = cloneableClasses[objectClass] = cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true; /** Used to determine if values are of the language type Object */ var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; /** Used to escape characters for inclusion in compiled string literals */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\t': 't', '\u2028': 'u2028', '\u2029': 'u2029' }; /*--------------------------------------------------------------------------*/ /** * Create a new `lodash` function using the given `context` object. * * @static * @memberOf _ * @category Utilities * @param {Object} [context=window] The context object. * @returns {Function} Returns the `lodash` function. */ function runInContext(context) { // Avoid issues with some ES3 environments that attempt to use values, named // after built-in constructors like `Object`, for the creation of literals. // ES5 clears this up by stating that literals must use built-in constructors. // See http://es5.github.com/#x11.1.5. context = context ? _.defaults(window.Object(), context, _.pick(window, contextProps)) : window; /** Native constructor references */ var Array = context.Array, Boolean = context.Boolean, Date = context.Date, Function = context.Function, Math = context.Math, Number = context.Number, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** Used for `Array` and `Object` method references */ var arrayRef = Array(), objectRef = Object(); /** Used to restore the original `_` reference in `noConflict` */ var oldDash = context._; /** Used to detect if a method is native */ var reNative = RegExp('^' + String(objectRef.valueOf) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/valueOf|for [^\]]+/g, '.+?') + '$' ); /** Native method shortcuts */ var ceil = Math.ceil, clearTimeout = context.clearTimeout, concat = arrayRef.concat, floor = Math.floor, getPrototypeOf = reNative.test(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, hasOwnProperty = objectRef.hasOwnProperty, push = arrayRef.push, setImmediate = context.setImmediate, setTimeout = context.setTimeout, toString = objectRef.toString; /* Native method shortcuts for methods with the same name as other `lodash` methods */ var nativeBind = reNative.test(nativeBind = toString.bind) && nativeBind, nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray, nativeIsFinite = context.isFinite, nativeIsNaN = context.isNaN, nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys, nativeMax = Math.max, nativeMin = Math.min, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeSlice = arrayRef.slice; /** Detect various environments */ var isIeOpera = reNative.test(context.attachEvent), isV8 = nativeBind && !/\n|true/.test(nativeBind + isIeOpera); /** Used to lookup a built-in constructor by [[Class]] */ var ctorByClass = {}; ctorByClass[arrayClass] = Array; ctorByClass[boolClass] = Boolean; ctorByClass[dateClass] = Date; ctorByClass[objectClass] = Object; ctorByClass[numberClass] = Number; ctorByClass[regexpClass] = RegExp; ctorByClass[stringClass] = String; /*--------------------------------------------------------------------------*/ /** * Creates a `lodash` object, which wraps the given `value`, to enable method * chaining. * * In addition to Lo-Dash methods, wrappers also have the following `Array` methods: * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`, * and `unshift` * * Chaining is supported in custom builds as long as the `value` method is * implicitly or explicitly included in the build. * * The chainable wrapper functions are: * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`, * `compose`, `concat`, `countBy`, `createCallback`, `debounce`, `defaults`, * `defer`, `delay`, `difference`, `filter`, `flatten`, `forEach`, `forIn`, * `forOwn`, `functions`, `groupBy`, `initial`, `intersection`, `invert`, * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`, * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `push`, `range`, * `reject`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, `sortBy`, `splice`, * `tap`, `throttle`, `times`, `toArray`, `union`, `uniq`, `unshift`, `unzip`, * `values`, `where`, `without`, `wrap`, and `zip` * * The non-chainable wrapper functions are: * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `has`, * `identity`, `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, * `isElement`, `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, * `isNull`, `isNumber`, `isObject`, `isPlainObject`, `isRegExp`, `isString`, * `isUndefined`, `join`, `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, * `pop`, `random`, `reduce`, `reduceRight`, `result`, `shift`, `size`, `some`, * `sortedIndex`, `runInContext`, `template`, `unescape`, `uniqueId`, and `value` * * The wrapper functions `first` and `last` return wrapped values when `n` is * passed, otherwise they return unwrapped values. * * @name _ * @constructor * @category Chaining * @param {Mixed} value The value to wrap in a `lodash` instance. * @returns {Object} Returns a `lodash` instance. * @example * * var wrapped = _([1, 2, 3]); * * // returns an unwrapped value * wrapped.reduce(function(sum, num) { * return sum + num; * }); * // => 6 * * // returns a wrapped value * var squares = wrapped.map(function(num) { * return num * num; * }); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__')) ? value : new lodashWrapper(value); } /** * An object used to flag environments features. * * @static * @memberOf _ * @type Object */ var support = lodash.support = {}; (function() { var ctor = function() { this.x = 1; }, object = { '0': 1, 'length': 1 }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var prop in new ctor) { props.push(prop); } for (prop in arguments) { } /** * Detect if `arguments` objects are `Object` objects (all but Narwhal and Opera < 10.5). * * @memberOf _.support * @type Boolean */ support.argsObject = arguments.constructor == Object && !(arguments instanceof Array); /** * Detect if an `arguments` object's [[Class]] is resolvable (all but Firefox < 4, IE < 9). * * @memberOf _.support * @type Boolean */ support.argsClass = isArguments(arguments); /** * Detect if `prototype` properties are enumerable by default. * * Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 * (if the prototype or a property on the prototype has been set) * incorrectly sets a function's `prototype` property [[Enumerable]] * value to `true`. * * @memberOf _.support * @type Boolean */ support.enumPrototypes = ctor.propertyIsEnumerable('prototype'); /** * Detect if `Function#bind` exists and is inferred to be fast (all but V8). * * @memberOf _.support * @type Boolean */ support.fastBind = nativeBind && !isV8; /** * Detect if own properties are iterated after inherited properties (all but IE < 9). * * @memberOf _.support * @type Boolean */ support.ownLast = props[0] != 'x'; /** * Detect if `arguments` object indexes are non-enumerable * (Firefox < 4, IE < 9, PhantomJS, Safari < 5.1). * * @memberOf _.support * @type Boolean */ support.nonEnumArgs = prop != 0; /** * Detect if properties shadowing those on `Object.prototype` are non-enumerable. * * In IE < 9 an objects own properties, shadowing non-enumerable ones, are * made non-enumerable as well (a.k.a the JScript [[DontEnum]] bug). * * @memberOf _.support * @type Boolean */ support.nonEnumShadows = !/valueOf/.test(props); /** * Detect if `Array#shift` and `Array#splice` augment array-like objects correctly. * * Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array `shift()` * and `splice()` functions that fail to remove the last element, `value[0]`, * of array-like objects even though the `length` property is set to `0`. * The `shift()` method is buggy in IE 8 compatibility mode, while `splice()` * is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9. * * @memberOf _.support * @type Boolean */ support.spliceObjects = (arrayRef.splice.call(object, 0, 1), !object[0]); /** * Detect lack of support for accessing string characters by index. * * IE < 8 can't access characters by index and IE 8 can only access * characters by index on string literals. * * @memberOf _.support * @type Boolean */ support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx'; /** * Detect if a DOM node's [[Class]] is resolvable (all but IE < 9) * and that the JS engine errors when attempting to coerce an object to * a string without a `toString` function. * * @memberOf _.support * @type Boolean */ try { support.nodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { support.nodeClass = true; } }(1)); /** * By default, the template delimiters used by Lo-Dash are similar to those in * embedded Ruby (ERB). 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': /<%-([\s\S]+?)%>/g, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type RegExp */ 'evaluate': /<%([\s\S]+?)%>/g, /** * 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 } }; /*--------------------------------------------------------------------------*/ /** * The template used to create iterator functions. * * @private * @param {Object} data The data object used to populate the text. * @returns {String} Returns the interpolated text. */ var iteratorTemplate = template( // the `iterable` may be reassigned by the `top` snippet 'var index, iterable = <%= firstArg %>, ' + // assign the `result` variable an initial value 'result = <%= init %>;\n' + // exit early if the first argument is falsey 'if (!iterable) return result;\n' + // add code before the iteration branches '<%= top %>;\n' + // array-like iteration: '<% if (arrays) { %>' + 'var length = iterable.length; index = -1;\n' + 'if (<%= arrays %>) {' + // add support for accessing string characters by index if needed ' <% if (support.unindexedChars) { %>\n' + ' if (isString(iterable)) {\n' + " iterable = iterable.split('')\n" + ' }' + ' <% } %>\n' + // iterate over the array-like value ' while (++index < length) {\n' + ' <%= loop %>\n' + ' }\n' + '}\n' + 'else {' + // object iteration: // add support for iterating over `arguments` objects if needed ' <% } else if (support.nonEnumArgs) { %>\n' + ' var length = iterable.length; index = -1;\n' + ' if (length && isArguments(iterable)) {\n' + ' while (++index < length) {\n' + " index += '';\n" + ' <%= loop %>\n' + ' }\n' + ' } else {' + ' <% } %>' + // avoid iterating over `prototype` properties in older Firefox, Opera, and Safari ' <% if (support.enumPrototypes) { %>\n' + " var skipProto = typeof iterable == 'function';\n" + ' <% } %>' + // iterate own properties using `Object.keys` if it's fast ' <% if (useHas && useKeys) { %>\n' + ' var ownIndex = -1,\n' + ' ownProps = objectTypes[typeof iterable] ? keys(iterable) : [],\n' + ' length = ownProps.length;\n\n' + ' while (++ownIndex < length) {\n' + ' index = ownProps[ownIndex];\n' + " <% if (support.enumPrototypes) { %>if (!(skipProto && index == 'prototype')) {\n <% } %>" + ' <%= loop %>\n' + ' <% if (support.enumPrototypes) { %>}\n<% } %>' + ' }' + // else using a for-in loop ' <% } else { %>\n' + ' for (index in iterable) {<%' + ' if (support.enumPrototypes || useHas) { %>\n if (<%' + " if (support.enumPrototypes) { %>!(skipProto && index == 'prototype')<% }" + ' if (support.enumPrototypes && useHas) { %> && <% }' + ' if (useHas) { %>hasOwnProperty.call(iterable, index)<% }' + ' %>) {' + ' <% } %>\n' + ' <%= loop %>;' + ' <% if (support.enumPrototypes || useHas) { %>\n }<% } %>\n' + ' }' + // Because IE < 9 can't set the `[[Enumerable]]` attribute of an // existing property and the `constructor` property of a prototype // defaults to non-enumerable, Lo-Dash skips the `constructor` // property when it infers it's iterating over a `prototype` object. ' <% if (support.nonEnumShadows) { %>\n\n' + ' var ctor = iterable.constructor;\n' + ' <% for (var k = 0; k < 7; k++) { %>\n' + " index = '<%= shadowedProps[k] %>';\n" + ' if (<%' + " if (shadowedProps[k] == 'constructor') {" + ' %>!(ctor && ctor.prototype === iterable) && <%' + ' } %>hasOwnProperty.call(iterable, index)) {\n' + ' <%= loop %>\n' + ' }' + ' <% } %>' + ' <% } %>' + ' <% } %>' + ' <% if (arrays || support.nonEnumArgs) { %>\n}<% } %>\n' + // add code to the bottom of the iteration function '<%= bottom %>;\n' + // finally, return the `result` 'return result' ); /** Reusable iterator options for `assign` and `defaults` */ var defaultsIteratorOptions = { 'args': 'object, source, guard', 'top': 'var args = arguments,\n' + ' argsIndex = 0,\n' + " argsLength = typeof guard == 'number' ? 2 : args.length;\n" + 'while (++argsIndex < argsLength) {\n' + ' iterable = args[argsIndex];\n' + ' if (iterable && objectTypes[typeof iterable]) {', 'loop': "if (typeof result[index] == 'undefined') result[index] = iterable[index]", 'bottom': ' }\n}' }; /** Reusable iterator options shared by `each`, `forIn`, and `forOwn` */ var eachIteratorOptions = { 'args': 'collection, callback, thisArg', 'top': "callback = callback && typeof thisArg == 'undefined' ? callback : lodash.createCallback(callback, thisArg)", 'arrays': "typeof length == 'number'", 'loop': 'if (callback(iterable[index], index, collection) === false) return result' }; /** Reusable iterator options for `forIn` and `forOwn` */ var forOwnIteratorOptions = { 'top': 'if (!objectTypes[typeof iterable]) return result;\n' + eachIteratorOptions.top, 'arrays': false }; /*--------------------------------------------------------------------------*/ /** * Creates a function optimized to search large arrays for a given `value`, * starting at `fromIndex`, using strict equality for comparisons, i.e. `===`. * * @private * @param {Array} array The array to search. * @param {Mixed} value The value to search for. * @returns {Boolean} Returns `true`, if `value` is found, else `false`. */ function cachedContains(array) { var length = array.length, isLarge = length >= largeArraySize; if (isLarge) { var cache = {}, index = -1; while (++index < length) { var key = keyPrefix + array[index]; (cache[key] || (cache[key] = [])).push(array[index]); } } return function(value) { if (isLarge) { var key = keyPrefix + value; return cache[key] && indexOf(cache[key], value) > -1; } return indexOf(array, value) > -1; } } /** * Used by `_.max` and `_.min` as the default `callback` when a given * `collection` is a string value. * * @private * @param {String} value The character to inspect. * @returns {Number} Returns the code unit of given character. */ function charAtCallback(value) { return value.charCodeAt(0); } /** * Used by `sortBy` to compare transformed `collection` values, stable sorting * them in ascending order. * * @private * @param {Object} a The object to compare to `b`. * @param {Object} b The object to compare to `a`. * @returns {Number} Returns the sort order indicator of `1` or `-1`. */ function compareAscending(a, b) { var ai = a.index, bi = b.index; a = a.criteria; b = b.criteria; // ensure a stable sort in V8 and other engines // http://code.google.com/p/v8/issues/detail?id=90 if (a !== b) { if (a > b || typeof a == 'undefined') { return 1; } if (a < b || typeof b == 'undefined') { return -1; } } return ai < bi ? -1 : 1; } /** * Creates a function that, when called, invokes `func` with the `this` binding * of `thisArg` and prepends any `partialArgs` to the arguments passed to the * bound function. * * @private * @param {Function|String} func The function to bind or the method name. * @param {Mixed} [thisArg] The `this` binding of `func`. * @param {Array} partialArgs An array of arguments to be partially applied. * @param {Object} [idicator] Used to indicate binding by key or partially * applying arguments from the right. * @returns {Function} Returns the new bound function. */ function createBound(func, thisArg, partialArgs, indicator) { var isFunc = isFunction(func), isPartial = !partialArgs, key = thisArg; // juggle arguments if (isPartial) { var rightIndicator = indicator; partialArgs = thisArg; } else if (!isFunc) { if (!indicator) { throw new TypeError; } thisArg = func; } function bound() { // `Function#bind` spec // http://es5.github.com/#x15.3.4.5 var args = arguments, thisBinding = isPartial ? this : thisArg; if (!isFunc) { func = thisArg[key]; } if (partialArgs.length) { args = args.length ? (args = nativeSlice.call(args), rightIndicator ? args.concat(partialArgs) : partialArgs.concat(args)) : partialArgs; } if (this instanceof bound) { // ensure `new bound` is an instance of `func` noop.prototype = func.prototype; thisBinding = new noop; noop.prototype = null; // mimic the constructor's `return` behavior // http://es5.github.com/#x13.2.2 var result = func.apply(thisBinding, args); return isObject(result) ? result : thisBinding; } return func.apply(thisBinding, args); } return bound; } /** * Creates compiled iteration functions. * * @private * @param {Object} [options1, options2, ...] The compile options object(s). * arrays - A string of code to determine if the iterable is an array or array-like. * useHas - A boolean to specify using `hasOwnProperty` checks in the object loop. * useKeys - A boolean to specify using `_.keys` for own property iteration. * args - A string of comma separated arguments the iteration function will accept. * top - A string of code to execute before the iteration branches. * loop - A string of code to execute in the object loop. * bottom - A string of code to execute after the iteration branches. * @returns {Function} Returns the compiled function. */ function createIterator() { var data = { // data properties 'shadowedProps': shadowedProps, 'support': support, // iterator options 'arrays': 'isArray(iterable)', 'bottom': '', 'init': 'iterable', 'loop': '', 'top': '', 'useHas': true, 'useKeys': !!keys }; // merge options into a template data object for (var object, index = 0; object = arguments[index]; index++) { for (var key in object) { data[key] = object[key]; } } var args = data.args; data.firstArg = /^[^,]+/.exec(args)[0]; // create the function factory var factory = Function( 'hasOwnProperty, isArguments, isArray, isString, keys, ' + 'lodash, objectTypes', 'return function(' + args + ') {\n' + iteratorTemplate(data) + '\n}' ); // return the compiled function return factory( hasOwnProperty, isArguments, isArray, isString, keys, lodash, objectTypes ); } /** * Used by `template` to escape characters for inclusion in compiled * string literals. * * @private * @param {String} match The matched character to escape. * @returns {String} Returns the escaped character. */ function escapeStringChar(match) { return '\\' + stringEscapes[match]; } /** * Used by `escape` to convert characters to HTML entities. * * @private * @param {String} match The matched character to escape. * @returns {String} Returns the escaped character. */ function escapeHtmlChar(match) { return htmlEscapes[match]; } /** * Checks if `value` is a DOM node in IE < 9. * * @private * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true` if the `value` is a DOM node, else `false`. */ function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } /** * A fast path for creating `lodash` wrapper objects. * * @private * @param {Mixed} value The value to wrap in a `lodash` instance. * @returns {Object} Returns a `lodash` instance. */ function lodashWrapper(value) { this.__wrapped__ = value; } // ensure `new lodashWrapper` is an instance of `lodash` lodashWrapper.prototype = lodash.prototype; /** * A no-operation function. * * @private */ function noop() { // no operation performed } /** * A fallback implementation of `isPlainObject` which checks if a given `value` * is an object created by the `Object` constructor, assuming objects created * by the `Object` constructor have no inherited enumerable properties and that * there are no `Object.prototype` extensions. * * @private * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if `value` is a plain object, else `false`. */ function shimIsPlainObject(value) { // avoid non-objects and false positives for `arguments` objects var result = false; if (!(value && toString.call(value) == objectClass) || (!support.argsClass && isArguments(value))) { return result; } // check that the constructor is `Object` (i.e. `Object instanceof Object`) var ctor = value.constructor; if (isFunction(ctor) ? ctor instanceof ctor : (support.nodeClass || !isNode(value))) { // IE < 9 iterates inherited properties before own properties. If the first // iterated property is an object's own property then there are no inherited // enumerable properties. if (support.ownLast) { forIn(value, function(value, key, object) { result = hasOwnProperty.call(object, key); return false; }); return result === true; } // In most environments an object's own properties are iterated before // its inherited properties. If the last iterated property is an object's // own property then there are no inherited enumerable properties. forIn(value, function(value, key) { result = key; }); return result === false || hasOwnProperty.call(value, result); } return result; } /** * Slices the `collection` from the `start` index up to, but not including, * the `end` index. * * Note: This function is used, instead of `Array#slice`, to support node lists * in IE < 9 and to ensure dense arrays are returned. * * @private * @param {Array|Object|String} collection The collection to slice. * @param {Number} start The start index. * @param {Number} end The end index. * @returns {Array} Returns the new array. */ function slice(array, start, end) { start || (start = 0); if (typeof end == 'undefined') { end = array ? array.length : 0; } var index = -1, length = end - start || 0, result = Array(length < 0 ? 0 : length); while (++index < length) { result[index] = array[start + index]; } return result; } /** * Used by `unescape` to convert HTML entities to characters. * * @private * @param {String} match The matched character to unescape. * @returns {String} Returns the unescaped character. */ function unescapeHtmlChar(match) { return htmlUnescapes[match]; } /*--------------------------------------------------------------------------*/ /** * Checks if `value` is an `arguments` object. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is an `arguments` object, else `false`. * @example * * (function() { return _.isArguments(arguments); })(1, 2, 3); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { return toString.call(value) == argsClass; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!support.argsClass) { isArguments = function(value) { return value ? hasOwnProperty.call(value, 'callee') : false; }; } /** * A fallback implementation of `Object.keys` which produces an array of the * given object's own enumerable property names. * * @private * @type Function * @param {Object} object The object to inspect. * @returns {Array} Returns a new array of property names. */ var shimKeys = createIterator({ 'args': 'object', 'init': '[]', 'top': 'if (!(objectTypes[typeof object])) return result', 'loop': 'result.push(index)', 'arrays': false }); /** * Creates an array composed of the own enumerable property names of `object`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns a new array of property names. * @example * * _.keys({ 'one': 1, 'two': 2, 'three': 3 }); * // => ['one', 'two', 'three'] (order is not guaranteed) */ var keys = !nativeKeys ? shimKeys : function(object) { if (!isObject(object)) { return []; } if ((support.enumPrototypes && typeof object == 'function') || (support.nonEnumArgs && object.length && isArguments(object))) { return shimKeys(object); } return nativeKeys(object); }; /** * A function compiled to iterate `arguments` objects, arrays, objects, and * strings consistenly across environments, executing the `callback` for each * element in the `collection`. The `callback` is bound to `thisArg` and invoked * with three arguments; (value, index|key, collection). Callbacks may exit * iteration early by explicitly returning `false`. * * @private * @type Function * @param {Array|Object|String} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array|Object|String} Returns `collection`. */ var each = createIterator(eachIteratorOptions); /** * Used to convert characters to HTML entities: * * Though the `>` character is escaped for symmetry, characters like `>` and `/` * don't require escaping in HTML and have no special meaning unless they're part * of a tag or an unquoted attribute value. * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact") */ var htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }; /** Used to convert HTML entities to characters */ var htmlUnescapes = invert(htmlEscapes); /*--------------------------------------------------------------------------*/ /** * Assigns own enumerable properties of source object(s) to the destination * object. Subsequent sources will overwrite property assignments of previous * sources. If a `callback` function is passed, it will be executed to produce * the assigned values. The `callback` is bound to `thisArg` and invoked with * two arguments; (objectValue, sourceValue). * * @static * @memberOf _ * @type Function * @alias extend * @category Objects * @param {Object} object The destination object. * @param {Object} [source1, source2, ...] The source objects. * @param {Function} [callback] The function to customize assigning values. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the destination object. * @example * * _.assign({ 'name': 'moe' }, { 'age': 40 }); * // => { 'name': 'moe', 'age': 40 } * * var defaults = _.partialRight(_.assign, function(a, b) { * return typeof a == 'undefined' ? b : a; * }); * * var food = { 'name': 'apple' }; * defaults(food, { 'name': 'banana', 'type': 'fruit' }); * // => { 'name': 'apple', 'type': 'fruit' } */ var assign = createIterator(defaultsIteratorOptions, { 'top': defaultsIteratorOptions.top.replace(';', ';\n' + "if (argsLength > 3 && typeof args[argsLength - 2] == 'function') {\n" + ' var callback = lodash.createCallback(args[--argsLength - 1], args[argsLength--], 2);\n' + "} else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {\n" + ' callback = args[--argsLength];\n' + '}' ), 'loop': 'result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]' }); /** * Creates a clone of `value`. If `deep` is `true`, nested objects will also * be cloned, otherwise they will be assigned by reference. If a `callback` * function is passed, it will be executed to produce the cloned values. If * `callback` returns `undefined`, cloning will be handled by the method instead. * The `callback` is bound to `thisArg` and invoked with one argument; (value). * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to clone. * @param {Boolean} [deep=false] A flag to indicate a deep clone. * @param {Function} [callback] The function to customize cloning values. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @param- {Array} [stackA=[]] Tracks traversed source objects. * @param- {Array} [stackB=[]] Associates clones with source counterparts. * @returns {Mixed} Returns the cloned `value`. * @example * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * var shallow = _.clone(stooges); * shallow[0] === stooges[0]; * // => true * * var deep = _.clone(stooges, true); * deep[0] === stooges[0]; * // => false * * _.mixin({ * 'clone': _.partialRight(_.clone, function(value) { * return _.isElement(value) ? value.cloneNode(false) : undefined; * }) * }); * * var clone = _.clone(document.body); * clone.childNodes.length; * // => 0 */ function clone(value, deep, callback, thisArg, stackA, stackB) { var result = value; // allows working with "Collections" methods without using their `callback` // argument, `index|key`, for this method's `callback` if (typeof deep == 'function') { thisArg = callback; callback = deep; deep = false; } if (typeof callback == 'function') { callback = (typeof thisArg == 'undefined') ? callback : lodash.createCallback(callback, thisArg, 1); result = callback(result); if (typeof result != 'undefined') { return result; } result = value; } // inspect [[Class]] var isObj = isObject(result); if (isObj) { var className = toString.call(result); if (!cloneableClasses[className] || (!support.nodeClass && isNode(result))) { return result; } var isArr = isArray(result); } // shallow clone if (!isObj || !deep) { return isObj ? (isArr ? slice(result) : assign({}, result)) : result; } var ctor = ctorByClass[className]; switch (className) { case boolClass: case dateClass: return new ctor(+result); case numberClass: case stringClass: return new ctor(result); case regexpClass: return ctor(result.source, reFlags.exec(result)); } // check for circular references and return corresponding clone stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == value) { return stackB[length]; } } // init cloned object result = isArr ? ctor(result.length) : {}; // add array properties assigned by `RegExp#exec` if (isArr) { if (hasOwnProperty.call(value, 'index')) { result.index = value.index; } if (hasOwnProperty.call(value, 'input')) { result.input = value.input; } } // add the source value to the stack of traversed objects // and associate it with its clone stackA.push(value); stackB.push(result); // recursively populate clone (susceptible to call stack limits) (isArr ? forEach : forOwn)(value, function(objValue, key) { result[key] = clone(objValue, deep, callback, undefined, stackA, stackB); }); return result; } /** * Creates a deep clone of `value`. If a `callback` function is passed, * it will be executed to produce the cloned values. If `callback` returns * `undefined`, cloning will be handled by the method instead. The `callback` * is bound to `thisArg` and invoked with one argument; (value). * * Note: This function is loosely based on the structured clone algorithm. Functions * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and * objects created by constructors other than `Object` are cloned to plain `Object` objects. * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to deep clone. * @param {Function} [callback] The function to customize cloning values. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the deep cloned `value`. * @example * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * var deep = _.cloneDeep(stooges); * deep[0] === stooges[0]; * // => false * * var view = { * 'label': 'docs', * 'node': element * }; * * var clone = _.cloneDeep(view, function(value) { * return _.isElement(value) ? value.cloneNode(true) : undefined; * }); * * clone.node == view.node; * // => false */ function cloneDeep(value, callback, thisArg) { return clone(value, true, callback, thisArg); } /** * Assigns own enumerable properties of source object(s) to the destination * object for all destination properties that resolve to `undefined`. Once a * property is set, additional defaults of the same property will be ignored. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The destination object. * @param {Object} [source1, source2, ...] The source objects. * @param- {Object} [guard] Allows working with `_.reduce` without using its * callback's `key` and `object` arguments as sources. * @returns {Object} Returns the destination object. * @example * * var food = { 'name': 'apple' }; * _.defaults(food, { 'name': 'banana', 'type': 'fruit' }); * // => { 'name': 'apple', 'type': 'fruit' } */ var defaults = createIterator(defaultsIteratorOptions); /** * This method is similar to `_.find`, except that it returns the key of the * element that passes the callback check, instead of the element itself. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to search. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the key of the found element, else `undefined`. * @example * * _.findKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) { * return num % 2 == 0; * }); * // => 'b' */ function findKey(object, callback, thisArg) { var result; callback = lodash.createCallback(callback, thisArg); forOwn(object, function(value, key, object) { if (callback(value, key, object)) { result = key; return false; } }); return result; } /** * Iterates over `object`'s own and inherited enumerable properties, executing * the `callback` for each property. The `callback` is bound to `thisArg` and * invoked with three arguments; (value, key, object). Callbacks may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * function Dog(name) { * this.name = name; * } * * Dog.prototype.bark = function() { * alert('Woof, woof!'); * }; * * _.forIn(new Dog('Dagny'), function(value, key) { * alert(key); * }); * // => alerts 'name' and 'bark' (order is not guaranteed) */ var forIn = createIterator(eachIteratorOptions, forOwnIteratorOptions, { 'useHas': false }); /** * Iterates over an object's own enumerable properties, executing the `callback` * for each property. The `callback` is bound to `thisArg` and invoked with three * arguments; (value, key, object). Callbacks may exit iteration early by explicitly * returning `false`. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { * alert(key); * }); * // => alerts '0', '1', and 'length' (order is not guaranteed) */ var forOwn = createIterator(eachIteratorOptions, forOwnIteratorOptions); /** * Creates a sorted array of all enumerable properties, own and inherited, * of `object` that have function values. * * @static * @memberOf _ * @alias methods * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns a new array of property names that have function values. * @example * * _.functions(_); * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...] */ function functions(object) { var result = []; forIn(object, function(value, key) { if (isFunction(value)) { result.push(key); } }); return result.sort(); } /** * Checks if the specified object `property` exists and is a direct property, * instead of an inherited property. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to check. * @param {String} property The property to check for. * @returns {Boolean} Returns `true` if key is a direct property, else `false`. * @example * * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); * // => true */ function has(object, property) { return object ? hasOwnProperty.call(object, property) : false; } /** * Creates an object composed of the inverted keys and values of the given `object`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to invert. * @returns {Object} Returns the created inverted object. * @example * * _.invert({ 'first': 'moe', 'second': 'larry' }); * // => { 'moe': 'first', 'larry': 'second' } */ function invert(object) { var index = -1, props = keys(object), length = props.length, result = {}; while (++index < length) { var key = props[index]; result[object[key]] = key; } return result; } /** * Checks if `value` is an array. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is an array, else `false`. * @example * * (function() { return _.isArray(arguments); })(); * // => false * * _.isArray([1, 2, 3]); * // => true */ function isArray(value) { // `instanceof` may cause a memory leak in IE 7 if `value` is a host object // http://ajaxian.com/archives/working-aroung-the-instanceof-memory-leak return (support.argsObject && value instanceof Array) || (nativeIsArray ? nativeIsArray(value) : toString.call(value) == arrayClass); } /** * Checks if `value` is a boolean value. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is a boolean value, else `false`. * @example * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || toString.call(value) == boolClass; } /** * Checks if `value` is a date. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is a date, else `false`. * @example * * _.isDate(new Date); * // => true */ function isDate(value) { return value instanceof Date || toString.call(value) == dateClass; } /** * Checks if `value` is a DOM element. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true */ function isElement(value) { return value ? value.nodeType === 1 : false; } /** * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a * length of `0` and objects with no own enumerable properties are considered * "empty". * * @static * @memberOf _ * @category Objects * @param {Array|Object|String} value The value to inspect. * @returns {Boolean} Returns `true`, if the `value` is empty, else `false`. * @example * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({}); * // => true * * _.isEmpty(''); * // => true */ function isEmpty(value) { var result = true; if (!value) { return result; } var className = toString.call(value), length = value.length; if ((className == arrayClass || className == stringClass || (support.argsClass ? className == argsClass : isArguments(value))) || (className == objectClass && typeof length == 'number' && isFunction(value.splice))) { return !length; } forOwn(value, function() { return (result = false); }); return result; } /** * Performs a deep comparison between two values to determine if they are * equivalent to each other. If `callback` is passed, it will be executed to * compare values. If `callback` returns `undefined`, comparisons will be handled * by the method instead. The `callback` is bound to `thisArg` and invoked with * two arguments; (a, b). * * @static * @memberOf _ * @category Objects * @param {Mixed} a The value to compare. * @param {Mixed} b The other value to compare. * @param {Function} [callback] The function to customize comparing values. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @param- {Array} [stackA=[]] Tracks traversed `a` objects. * @param- {Array} [stackB=[]] Tracks traversed `b` objects. * @returns {Boolean} Returns `true`, if the values are equivalent, else `false`. * @example * * var moe = { 'name': 'moe', 'age': 40 }; * var copy = { 'name': 'moe', 'age': 40 }; * * moe == copy; * // => false * * _.isEqual(moe, copy); * // => true * * var words = ['hello', 'goodbye']; * var otherWords = ['hi', 'goodbye']; * * _.isEqual(words, otherWords, function(a, b) { * var reGreet = /^(?:hello|hi)$/i, * aGreet = _.isString(a) && reGreet.test(a), * bGreet = _.isString(b) && reGreet.test(b); * * return (aGreet || bGreet) ? (aGreet == bGreet) : undefined; * }); * // => true */ function isEqual(a, b, callback, thisArg, stackA, stackB) { // used to indicate that when comparing objects, `a` has at least the properties of `b` var whereIndicator = callback === indicatorObject; if (typeof callback == 'function' && !whereIndicator) { callback = lodash.createCallback(callback, thisArg, 2); var result = callback(a, b); if (typeof result != 'undefined') { return !!result; } } // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (!a || (type != 'function' && type != 'object')) && (!b || (otherType != 'function' && otherType != 'object'))) { return false; } // exit early for `null` and `undefined`, avoiding ES3's Function#call behavior // http://es5.github.com/#x15.3.4.4 if (a == null || b == null) { return a === b; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0`, treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `+0` vs. `-0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.com/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // unwrap any `lodash` wrapped values if (hasOwnProperty.call(a, '__wrapped__ ') || hasOwnProperty.call(b, '__wrapped__')) { return isEqual(a.__wrapped__ || a, b.__wrapped__ || b, callback, thisArg, stackA, stackB); } // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !( isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB )) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.com/#x15.12.3) stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { length = a.length; size = b.length; // compare lengths to determine if a deep comparison is necessary result = size == a.length; if (!result && !whereIndicator) { return result; } // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (whereIndicator) { while (index--) { if ((result = isEqual(a[index], value, callback, thisArg, stackA, stackB))) { break; } } } else if (!(result = isEqual(a[size], value, callback, thisArg, stackA, stackB))) { break; } } return result; } // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly forIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && isEqual(a[key], value, callback, thisArg, stackA, stackB)); } }); if (result && !whereIndicator) { // ensure both objects have the same number of properties forIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } return result; } /** * Checks if `value` is, or can be coerced to, a finite number. * * Note: This is not the same as native `isFinite`, which will return true for * booleans and empty strings. See http://es5.github.com/#x15.1.2.5. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is finite, else `false`. * @example * * _.isFinite(-101); * // => true * * _.isFinite('10'); * // => true * * _.isFinite(true); * // => false * * _.isFinite(''); * // => false * * _.isFinite(Infinity); * // => false */ function isFinite(value) { return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value)); } /** * Checks if `value` is a function. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true */ function isFunction(value) { return typeof value == 'function'; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return value instanceof Function || toString.call(value) == funcClass; }; } /** * Checks if `value` is the language type of Object. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.com/#x8 // and avoid a V8 bug // http://code.google.com/p/v8/issues/detail?id=2291 return value ? objectTypes[typeof value] : false; } /** * Checks if `value` is `NaN`. * * Note: This is not the same as native `isNaN`, which will return `true` for * `undefined` and other values. See http://es5.github.com/#x15.1.2.4. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // `NaN` as a primitive is the only value that is not equal to itself // (perform the [[Class]] check first to avoid errors with some host objects in IE) return isNumber(value) && value != +value } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(undefined); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is a number. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is a number, else `false`. * @example * * _.isNumber(8.4 * 5); * // => true */ function isNumber(value) { return typeof value == 'number' || toString.call(value) == numberClass; } /** * Checks if a given `value` is an object created by the `Object` constructor. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if `value` is a plain object, else `false`. * @example * * function Stooge(name, age) { * this.name = name; * this.age = age; * } * * _.isPlainObject(new Stooge('moe', 40)); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'name': 'moe', 'age': 40 }); * // => true */ var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { if (!(value && toString.call(value) == objectClass) || (!support.argsClass && isArguments(value))) { return false; } var valueOf = value.valueOf, objProto = typeof valueOf == 'function' && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); return objProto ? (value == objProto || getPrototypeOf(value) == objProto) : shimIsPlainObject(value); }; /** * Checks if `value` is a regular expression. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is a regular expression, else `false`. * @example * * _.isRegExp(/moe/); * // => true */ function isRegExp(value) { return value instanceof RegExp || toString.call(value) == regexpClass; } /** * Checks if `value` is a string. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is a string, else `false`. * @example * * _.isString('moe'); * // => true */ function isString(value) { return typeof value == 'string' || toString.call(value) == stringClass; } /** * Checks if `value` is `undefined`. * * @static * @memberOf _ * @category Objects * @param {Mixed} value The value to check. * @returns {Boolean} Returns `true`, if the `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true */ function isUndefined(value) { return typeof value == 'undefined'; } /** * Recursively merges own enumerable properties of the source object(s), that * don't resolve to `undefined`, into the destination object. Subsequent sources * will overwrite property assignments of previous sources. If a `callback` function * is passed, it will be executed to produce the merged values of the destination * and source properties. If `callback` returns `undefined`, merging will be * handled by the method instead. The `callback` is bound to `thisArg` and * invoked with two arguments; (objectValue, sourceValue). * * @static * @memberOf _ * @category Objects * @param {Object} object The destination object. * @param {Object} [source1, source2, ...] The source objects. * @param {Function} [callback] The function to customize merging properties. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @param- {Object} [deepIndicator] Indicates that `stackA` and `stackB` are * arrays of traversed objects, instead of source objects. * @param- {Array} [stackA=[]] Tracks traversed source objects. * @param- {Array} [stackB=[]] Associates values with source counterparts. * @returns {Object} Returns the destination object. * @example * * var names = { * 'stooges': [ * { 'name': 'moe' }, * { 'name': 'larry' } * ] * }; * * var ages = { * 'stooges': [ * { 'age': 40 }, * { 'age': 50 } * ] * }; * * _.merge(names, ages); * // => { 'stooges': [{ 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 }] } * * var food = { * 'fruits': ['apple'], * 'vegetables': ['beet'] * }; * * var otherFood = { * 'fruits': ['banana'], * 'vegetables': ['carrot'] * }; * * _.merge(food, otherFood, function(a, b) { * return _.isArray(a) ? a.concat(b) : undefined; * }); * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] } */ function merge(object, source, deepIndicator) { var args = arguments, index = 0, length = 2; if (!isObject(object)) { return object; } if (deepIndicator === indicatorObject) { var callback = args[3], stackA = args[4], stackB = args[5]; } else { stackA = []; stackB = []; // allows working with `_.reduce` and `_.reduceRight` without // using their `callback` arguments, `index|key` and `collection` if (typeof deepIndicator != 'number') { length = args.length; } if (length > 3 && typeof args[length - 2] == 'function') { callback = lodash.createCallback(args[--length - 1], args[length--], 2); } else if (length > 2 && typeof args[length - 1] == 'function') { callback = args[--length]; } } while (++index < length) { (isArray(args[index]) ? forEach : forOwn)(args[index], function(source, key) { var found, isArr, result = source, value = object[key]; if (source && ((isArr = isArray(source)) || isPlainObject(source))) { // avoid merging previously merged cyclic sources var stackLength = stackA.length; while (stackLength--) { if ((found = stackA[stackLength] == source)) { value = stackB[stackLength]; break; } } if (!found) { var isShallow; if (callback) { result = callback(value, source); if ((isShallow = typeof result != 'undefined')) { value = result; } } if (!isShallow) { value = isArr ? (isArray(value) ? value : []) : (isPlainObject(value) ? value : {}); } // add `source` and associated `value` to the stack of traversed objects stackA.push(source); stackB.push(value); // recursively merge objects and arrays (susceptible to call stack limits) if (!isShallow) { value = merge(value, source, indicatorObject, callback, stackA, stackB); } } } else { if (callback) { result = callback(value, source); if (typeof result == 'undefined') { result = source; } } if (typeof result != 'undefined') { value = result; } } object[key] = value; }); } return object; } /** * Creates a shallow clone of `object` excluding the specified properties. * Property names may be specified as individual arguments or as arrays of * property names. If a `callback` function is passed, it will be executed * for each property in the `object`, omitting the properties `callback` * returns truthy for. The `callback` is bound to `thisArg` and invoked * with three arguments; (value, key, object). * * @static * @memberOf _ * @category Objects * @param {Object} object The source object. * @param {Function|String} callback|[prop1, prop2, ...] The properties to omit * or the function called per iteration. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns an object without the omitted properties. * @example * * _.omit({ 'name': 'moe', 'age': 40 }, 'age'); * // => { 'name': 'moe' } * * _.omit({ 'name': 'moe', 'age': 40 }, function(value) { * return typeof value == 'number'; * }); * // => { 'name': 'moe' } */ function omit(object, callback, thisArg) { var isFunc = typeof callback == 'function', result = {}; if (isFunc) { callback = lodash.createCallback(callback, thisArg); } else { var props = concat.apply(arrayRef, nativeSlice.call(arguments, 1)); } forIn(object, function(value, key, object) { if (isFunc ? !callback(value, key, object) : indexOf(props, key) < 0 ) { result[key] = value; } }); return result; } /** * Creates a two dimensional array of the given object's key-value pairs, * i.e. `[[key1, value1], [key2, value2]]`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns new array of key-value pairs. * @example * * _.pairs({ 'moe': 30, 'larry': 40 }); * // => [['moe', 30], ['larry', 40]] (order is not guaranteed) */ function pairs(object) { var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { var key = props[index]; result[index] = [key, object[key]]; } return result; } /** * Creates a shallow clone of `object` composed of the specified properties. * Property names may be specified as individual arguments or as arrays of property * names. If `callback` is passed, it will be executed for each property in the * `object`, picking the properties `callback` returns truthy for. The `callback` * is bound to `thisArg` and invoked with three arguments; (value, key, object). * * @static * @memberOf _ * @category Objects * @param {Object} object The source object. * @param {Array|Function|String} callback|[prop1, prop2, ...] The function called * per iteration or properties to pick, either as individual arguments or arrays. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns an object composed of the picked properties. * @example * * _.pick({ 'name': 'moe', '_userid': 'moe1' }, 'name'); * // => { 'name': 'moe' } * * _.pick({ 'name': 'moe', '_userid': 'moe1' }, function(value, key) { * return key.charAt(0) != '_'; * }); * // => { 'name': 'moe' } */ function pick(object, callback, thisArg) { var result = {}; if (typeof callback != 'function') { var index = -1, props = concat.apply(arrayRef, nativeSlice.call(arguments, 1)), length = isObject(object) ? props.length : 0; while (++index < length) { var key = props[index]; if (key in object) { result[key] = object[key]; } } } else { callback = lodash.createCallback(callback, thisArg); forIn(object, function(value, key, object) { if (callback(value, key, object)) { result[key] = value; } }); } return result; } /** * Creates an array composed of the own enumerable property values of `object`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns a new array of property values. * @example * * _.values({ 'one': 1, 'two': 2, 'three': 3 }); * // => [1, 2, 3] (order is not guaranteed) */ function values(object) { var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { result[index] = object[props[index]]; } return result; } /*--------------------------------------------------------------------------*/ /** * Creates an array of elements from the specified indexes, or keys, of the * `collection`. Indexes may be specified as individual arguments or as arrays * of indexes. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Array|Number|String} [index1, index2, ...] The indexes of * `collection` to retrieve, either as individual arguments or arrays. * @returns {Array} Returns a new array of elements corresponding to the * provided indexes. * @example * * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]); * // => ['a', 'c', 'e'] * * _.at(['moe', 'larry', 'curly'], 0, 2); * // => ['moe', 'curly'] */ function at(collection) { var index = -1, props = concat.apply(arrayRef, nativeSlice.call(arguments, 1)), length = props.length, result = Array(length); if (support.unindexedChars && isString(collection)) { collection = collection.split(''); } while(++index < length) { result[index] = collection[props[index]]; } return result; } /** * Checks if a given `target` element is present in a `collection` using strict * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used * as the offset from the end of the collection. * * @static * @memberOf _ * @alias include * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Mixed} target The value to check for. * @param {Number} [fromIndex=0] The index to search from. * @returns {Boolean} Returns `true` if the `target` element is found, else `false`. * @example * * _.contains([1, 2, 3], 1); * // => true * * _.contains([1, 2, 3], 1, 2); * // => false * * _.contains({ 'name': 'moe', 'age': 40 }, 'moe'); * // => true * * _.contains('curly', 'ur'); * // => true */ function contains(collection, target, fromIndex) { var index = -1, length = collection ? collection.length : 0, result = false; fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0; if (typeof length == 'number') { result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex) ) > -1; } else { each(collection, function(value) { if (++index >= fromIndex) { return !(result = value === target); } }); } return result; } /** * Creates an object composed of keys returned from running each element of the * `collection` through the given `callback`. The corresponding value of each key * is the number of times the key was returned by the `callback`. The `callback` * is bound to `thisArg` and invoked with three arguments; (value, index|key, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); * // => { '4': 1, '6': 2 } * * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math); * // => { '4': 1, '6': 2 } * * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ function countBy(collection, callback, thisArg) { var result = {}; callback = lodash.createCallback(callback, thisArg); forEach(collection, function(value, key, collection) { key = String(callback(value, key, collection)); (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1); }); return result; } /** * Checks if the `callback` returns a truthy value for **all** elements of a * `collection`. The `callback` is bound to `thisArg` and invoked with three * arguments; (value, index|key, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias all * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Boolean} Returns `true` if all elements pass the callback check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * // using "_.pluck" callback shorthand * _.every(stooges, 'age'); * // => true * * // using "_.where" callback shorthand * _.every(stooges, { 'age': 50 }); * // => false */ function every(collection, callback, thisArg) { var result = true; callback = lodash.createCallback(callback, thisArg); if (isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { if (!(result = !!callback(collection[index], index, collection))) { break; } } } else { each(collection, function(value, index, collection) { return (result = !!callback(value, index, collection)); }); } return result; } /** * Examines each element in a `collection`, returning an array of all elements * the `callback` returns truthy for. The `callback` is bound to `thisArg` and * invoked with three arguments; (value, index|key, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias select * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of elements that passed the callback check. * @example * * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); * // => [2, 4, 6] * * var food = [ * { 'name': 'apple', 'organic': false, 'type': 'fruit' }, * { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } * ]; * * // using "_.pluck" callback shorthand * _.filter(food, 'organic'); * // => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }] * * // using "_.where" callback shorthand * _.filter(food, { 'type': 'fruit' }); * // => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }] */ function filter(collection, callback, thisArg) { var result = []; callback = lodash.createCallback(callback, thisArg); if (isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; if (callback(value, index, collection)) { result.push(value); } } } else { each(collection, function(value, index, collection) { if (callback(value, index, collection)) { result.push(value); } }); } return result; } /** * Examines each element in a `collection`, returning the first that the `callback` * returns truthy for. The `callback` is bound to `thisArg` and invoked with three * arguments; (value, index|key, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias detect * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the found element, else `undefined`. * @example * * _.find([1, 2, 3, 4], function(num) { * return num % 2 == 0; * }); * // => 2 * * var food = [ * { 'name': 'apple', 'organic': false, 'type': 'fruit' }, * { 'name': 'banana', 'organic': true, 'type': 'fruit' }, * { 'name': 'beet', 'organic': false, 'type': 'vegetable' } * ]; * * // using "_.where" callback shorthand * _.find(food, { 'type': 'vegetable' }); * // => { 'name': 'beet', 'organic': false, 'type': 'vegetable' } * * // using "_.pluck" callback shorthand * _.find(food, 'organic'); * // => { 'name': 'banana', 'organic': true, 'type': 'fruit' } */ function find(collection, callback, thisArg) { callback = lodash.createCallback(callback, thisArg); if (isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; if (callback(value, index, collection)) { return value; } } } else { var result; each(collection, function(value, index, collection) { if (callback(value, index, collection)) { result = value; return false; } }); return result; } } /** * Iterates over a `collection`, executing the `callback` for each element in * the `collection`. The `callback` is bound to `thisArg` and invoked with three * arguments; (value, index|key, collection). Callbacks may exit iteration early * by explicitly returning `false`. * * @static * @memberOf _ * @alias each * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array|Object|String} Returns `collection`. * @example * * _([1, 2, 3]).forEach(alert).join(','); * // => alerts each number and returns '1,2,3' * * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert); * // => alerts each number value (order is not guaranteed) */ function forEach(collection, callback, thisArg) { if (callback && typeof thisArg == 'undefined' && isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { if (callback(collection[index], index, collection) === false) { break; } } } else { each(collection, callback, thisArg); } return collection; } /** * Creates an object composed of keys returned from running each element of the * `collection` through the `callback`. The corresponding value of each key is * an array of elements passed to `callback` that returned the key. The `callback` * is bound to `thisArg` and invoked with three arguments; (value, index|key, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false` * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); }); * // => { '4': [4.2], '6': [6.1, 6.4] } * * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); * // => { '4': [4.2], '6': [6.1, 6.4] } * * // using "_.pluck" callback shorthand * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ function groupBy(collection, callback, thisArg) { var result = {}; callback = lodash.createCallback(callback, thisArg); forEach(collection, function(value, key, collection) { key = String(callback(value, key, collection)); (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value); }); return result; } /** * Invokes the method named by `methodName` on each element in the `collection`, * returning an array of the results of each invoked method. Additional arguments * will be passed to each invoked method. If `methodName` is a function, it will * be invoked for, and `this` bound to, each element in the `collection`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|String} methodName The name of the method to invoke or * the function invoked per iteration. * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with. * @returns {Array} Returns a new array of the results of each invoked method. * @example * * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invoke([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ function invoke(collection, methodName) { var args = nativeSlice.call(arguments, 2), index = -1, isFunc = typeof methodName == 'function', length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); forEach(collection, function(value) { result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args); }); return result; } /** * Creates an array of values by running each element in the `collection` * through the `callback`. The `callback` is bound to `thisArg` and invoked with * three arguments; (value, index|key, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias collect * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of the results of each `callback` execution. * @example * * _.map([1, 2, 3], function(num) { return num * 3; }); * // => [3, 6, 9] * * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); * // => [3, 6, 9] (order is not guaranteed) * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * // using "_.pluck" callback shorthand * _.map(stooges, 'name'); * // => ['moe', 'larry'] */ function map(collection, callback, thisArg) { var index = -1, length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); callback = lodash.createCallback(callback, thisArg); if (isArray(collection)) { while (++index < length) { result[index] = callback(collection[index], index, collection); } } else { each(collection, function(value, key, collection) { result[++index] = callback(value, key, collection); }); } return result; } /** * Retrieves the maximum value of an `array`. If `callback` is passed, * it will be executed for each value in the `array` to generate the * criterion by which the value is ranked. The `callback` is bound to * `thisArg` and invoked with three arguments; (value, index, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the maximum value. * @example * * _.max([4, 2, 8, 6]); * // => 8 * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * _.max(stooges, function(stooge) { return stooge.age; }); * // => { 'name': 'larry', 'age': 50 }; * * // using "_.pluck" callback shorthand * _.max(stooges, 'age'); * // => { 'name': 'larry', 'age': 50 }; */ function max(collection, callback, thisArg) { var computed = -Infinity, result = computed; if (!callback && isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; if (value > result) { result = value; } } } else { callback = (!callback && isString(collection)) ? charAtCallback : lodash.createCallback(callback, thisArg); each(collection, function(value, index, collection) { var current = callback(value, index, collection); if (current > computed) { computed = current; result = value; } }); } return result; } /** * Retrieves the minimum value of an `array`. If `callback` is passed, * it will be executed for each value in the `array` to generate the * criterion by which the value is ranked. The `callback` is bound to `thisArg` * and invoked with three arguments; (value, index, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the minimum value. * @example * * _.min([4, 2, 8, 6]); * // => 2 * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * _.min(stooges, function(stooge) { return stooge.age; }); * // => { 'name': 'moe', 'age': 40 }; * * // using "_.pluck" callback shorthand * _.min(stooges, 'age'); * // => { 'name': 'moe', 'age': 40 }; */ function min(collection, callback, thisArg) { var computed = Infinity, result = computed; if (!callback && isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; if (value < result) { result = value; } } } else { callback = (!callback && isString(collection)) ? charAtCallback : lodash.createCallback(callback, thisArg); each(collection, function(value, index, collection) { var current = callback(value, index, collection); if (current < computed) { computed = current; result = value; } }); } return result; } /** * Retrieves the value of a specified property from all elements in the `collection`. * * @static * @memberOf _ * @type Function * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {String} property The property to pluck. * @returns {Array} Returns a new array of property values. * @example * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * _.pluck(stooges, 'name'); * // => ['moe', 'larry'] */ var pluck = map; /** * Reduces a `collection` to a value which is the accumulated result of running * each element in the `collection` through the `callback`, where each successive * `callback` execution consumes the return value of the previous execution. * If `accumulator` is not passed, the first element of the `collection` will be * used as the initial `accumulator` value. The `callback` is bound to `thisArg` * and invoked with four arguments; (accumulator, value, index|key, collection). * * @static * @memberOf _ * @alias foldl, inject * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {Mixed} [accumulator] Initial value of the accumulator. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the accumulated value. * @example * * var sum = _.reduce([1, 2, 3], function(sum, num) { * return sum + num; * }); * // => 6 * * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { * result[key] = num * 3; * return result; * }, {}); * // => { 'a': 3, 'b': 6, 'c': 9 } */ function reduce(collection, callback, accumulator, thisArg) { var noaccum = arguments.length < 3; callback = lodash.createCallback(callback, thisArg, 4); if (isArray(collection)) { var index = -1, length = collection.length; if (noaccum) { accumulator = collection[++index]; } while (++index < length) { accumulator = callback(accumulator, collection[index], index, collection); } } else { each(collection, function(value, index, collection) { accumulator = noaccum ? (noaccum = false, value) : callback(accumulator, value, index, collection) }); } return accumulator; } /** * This method is similar to `_.reduce`, except that it iterates over a * `collection` from right to left. * * @static * @memberOf _ * @alias foldr * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {Mixed} [accumulator] Initial value of the accumulator. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the accumulated value. * @example * * var list = [[0, 1], [2, 3], [4, 5]]; * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, callback, accumulator, thisArg) { var iterable = collection, length = collection ? collection.length : 0, noaccum = arguments.length < 3; if (typeof length != 'number') { var props = keys(collection); length = props.length; } else if (support.unindexedChars && isString(collection)) { iterable = collection.split(''); } callback = lodash.createCallback(callback, thisArg, 4); forEach(collection, function(value, index, collection) { index = props ? props[--length] : --length; accumulator = noaccum ? (noaccum = false, iterable[index]) : callback(accumulator, iterable[index], index, collection); }); return accumulator; } /** * The opposite of `_.filter`, this method returns the elements of a * `collection` that `callback` does **not** return truthy for. * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of elements that did **not** pass the * callback check. * @example * * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); * // => [1, 3, 5] * * var food = [ * { 'name': 'apple', 'organic': false, 'type': 'fruit' }, * { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } * ]; * * // using "_.pluck" callback shorthand * _.reject(food, 'organic'); * // => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }] * * // using "_.where" callback shorthand * _.reject(food, { 'type': 'fruit' }); * // => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }] */ function reject(collection, callback, thisArg) { callback = lodash.createCallback(callback, thisArg); return filter(collection, function(value, index, collection) { return !callback(value, index, collection); }); } /** * Creates an array of shuffled `array` values, using a version of the * Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to shuffle. * @returns {Array} Returns a new shuffled collection. * @example * * _.shuffle([1, 2, 3, 4, 5, 6]); * // => [4, 1, 6, 3, 5, 2] */ function shuffle(collection) { var index = -1, length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); forEach(collection, function(value) { var rand = floor(nativeRandom() * (++index + 1)); result[index] = result[rand]; result[rand] = value; }); return result; } /** * Gets the size of the `collection` by returning `collection.length` for arrays * and array-like objects or the number of own enumerable properties for objects. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to inspect. * @returns {Number} Returns `collection.length` or number of own enumerable properties. * @example * * _.size([1, 2]); * // => 2 * * _.size({ 'one': 1, 'two': 2, 'three': 3 }); * // => 3 * * _.size('curly'); * // => 5 */ function size(collection) { var length = collection ? collection.length : 0; return typeof length == 'number' ? length : keys(collection).length; } /** * Checks if the `callback` returns a truthy value for **any** element of a * `collection`. The function returns as soon as it finds passing value, and * does not iterate over the entire `collection`. The `callback` is bound to * `thisArg` and invoked with three arguments; (value, index|key, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias any * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Boolean} Returns `true` if any element passes the callback check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var food = [ * { 'name': 'apple', 'organic': false, 'type': 'fruit' }, * { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } * ]; * * // using "_.pluck" callback shorthand * _.some(food, 'organic'); * // => true * * // using "_.where" callback shorthand * _.some(food, { 'type': 'meat' }); * // => false */ function some(collection, callback, thisArg) { var result; callback = lodash.createCallback(callback, thisArg); if (isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { if ((result = callback(collection[index], index, collection))) { break; } } } else { each(collection, function(value, index, collection) { return !(result = callback(value, index, collection)); }); } return !!result; } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in the `collection` through the `callback`. This method * performs a stable sort, that is, it will preserve the original sort order of * equal elements. The `callback` is bound to `thisArg` and invoked with three * arguments; (value, index|key, collection). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of sorted elements. * @example * * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); * // => [3, 1, 2] * * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); * // => [3, 1, 2] * * // using "_.pluck" callback shorthand * _.sortBy(['banana', 'strawberry', 'apple'], 'length'); * // => ['apple', 'banana', 'strawberry'] */ function sortBy(collection, callback, thisArg) { var index = -1, length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); callback = lodash.createCallback(callback, thisArg); forEach(collection, function(value, key, collection) { result[++index] = { 'criteria': callback(value, key, collection), 'index': index, 'value': value }; }); length = result.length; result.sort(compareAscending); while (length--) { result[length] = result[length].value; } return result; } /** * Converts the `collection` to an array. * * @static * @memberOf _ * @category Collections * @param {Array|Object|String} collection The collection to convert. * @returns {Array} Returns the new converted array. * @example * * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); * // => [2, 3, 4] */ function toArray(collection) { if (collection && typeof collection.length == 'number') { return (support.unindexedChars && isString(collection)) ? collection.split('') : slice(collection); } return values(collection); } /** * Examines each element in a `collection`, returning an array of all elements * that have the given `properties`. When checking `properties`, this method * performs a deep comparison between values to determine if they are equivalent * to each other. * * @static * @memberOf _ * @type Function * @category Collections * @param {Array|Object|String} collection The collection to iterate over. * @param {Object} properties The object of property values to filter by. * @returns {Array} Returns a new array of elements that have the given `properties`. * @example * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * _.where(stooges, { 'age': 40 }); * // => [{ 'name': 'moe', 'age': 40 }] */ var where = filter; /*--------------------------------------------------------------------------*/ /** * Creates an array with all falsey values of `array` removed. The values * `false`, `null`, `0`, `""`, `undefined` and `NaN` are all falsey. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to compact. * @returns {Array} Returns a new filtered array. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array ? array.length : 0, result = []; while (++index < length) { var value = array[index]; if (value) { result.push(value); } } return result; } /** * Creates an array of `array` elements not present in the other arrays * using strict equality for comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to process. * @param {Array} [array1, array2, ...] Arrays to check. * @returns {Array} Returns a new array of `array` elements not present in the * other arrays. * @example * * _.difference([1, 2, 3, 4, 5], [5, 2, 10]); * // => [1, 3, 4] */ function difference(array) { var index = -1, length = array ? array.length : 0, flattened = concat.apply(arrayRef, nativeSlice.call(arguments, 1)), contains = cachedContains(flattened), result = []; while (++index < length) { var value = array[index]; if (!contains(value)) { result.push(value); } } return result; } /** * This method is similar to `_.find`, except that it returns the index of * the element that passes the callback check, instead of the element itself. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the index of the found element, else `-1`. * @example * * _.findIndex(['apple', 'banana', 'beet'], function(food) { * return /^b/.test(food); * }); * // => 1 */ function findIndex(array, callback, thisArg) { var index = -1, length = array ? array.length : 0; callback = lodash.createCallback(callback, thisArg); while (++index < length) { if (callback(array[index], index, array)) { return index; } } return -1; } /** * Gets the first element of the `array`. If a number `n` is passed, the first * `n` elements of the `array` are returned. If a `callback` function is passed, * elements at the beginning of the array are returned as long as the `callback` * returns truthy. The `callback` is bound to `thisArg` and invoked with three * arguments; (value, index, array). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias head, take * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|Number|String} [callback|n] The function called * per element or the number of elements to return. If a property name or * object is passed, it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the first element(s) of `array`. * @example * * _.first([1, 2, 3]); * // => 1 * * _.first([1, 2, 3], 2); * // => [1, 2] * * _.first([1, 2, 3], function(num) { * return num < 3; * }); * // => [1, 2] * * var food = [ * { 'name': 'banana', 'organic': true }, * { 'name': 'beet', 'organic': false }, * ]; * * // using "_.pluck" callback shorthand * _.first(food, 'organic'); * // => [{ 'name': 'banana', 'organic': true }] * * var food = [ * { 'name': 'apple', 'type': 'fruit' }, * { 'name': 'banana', 'type': 'fruit' }, * { 'name': 'beet', 'type': 'vegetable' } * ]; * * // using "_.where" callback shorthand * _.first(food, { 'type': 'fruit' }); * // => [{ 'name': 'apple', 'type': 'fruit' }, { 'name': 'banana', 'type': 'fruit' }] */ function first(array, callback, thisArg) { if (array) { var n = 0, length = array.length; if (typeof callback != 'number' && callback != null) { var index = -1; callback = lodash.createCallback(callback, thisArg); while (++index < length && callback(array[index], index, array)) { n++; } } else { n = callback; if (n == null || thisArg) { return array[0]; } } return slice(array, 0, nativeMin(nativeMax(0, n), length)); } } /** * Flattens a nested array (the nesting can be to any depth). If `isShallow` * is truthy, `array` will only be flattened a single level. If `callback` * is passed, each element of `array` is passed through a callback` before * flattening. The `callback` is bound to `thisArg` and invoked with three * arguments; (value, index, array). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to flatten. * @param {Boolean} [isShallow=false] A flag to indicate only flattening a single level. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new flattened array. * @example * * _.flatten([1, [2], [3, [[4]]]]); * // => [1, 2, 3, 4]; * * _.flatten([1, [2], [3, [[4]]]], true); * // => [1, 2, 3, [[4]]]; * * var stooges = [ * { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, * { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] } * ]; * * // using "_.pluck" callback shorthand * _.flatten(stooges, 'quotes'); * // => ['Oh, a wise guy, eh?', 'Poifect!', 'Spread out!', 'You knucklehead!'] */ function flatten(array, isShallow, callback, thisArg) { var index = -1, length = array ? array.length : 0, result = []; // juggle arguments if (typeof isShallow != 'boolean' && isShallow != null) { thisArg = callback; callback = isShallow; isShallow = false; } if (callback != null) { callback = lodash.createCallback(callback, thisArg); } while (++index < length) { var value = array[index]; if (callback) { value = callback(value, index, array); } // recursively flatten arrays (susceptible to call stack limits) if (isArray(value)) { push.apply(result, isShallow ? value : flatten(value)); } else { result.push(value); } } return result; } /** * Gets the index at which the first occurrence of `value` is found using * strict equality for comparisons, i.e. `===`. If the `array` is already * sorted, passing `true` for `fromIndex` will run a faster binary search. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {Mixed} value The value to search for. * @param {Boolean|Number} [fromIndex=0] The index to search from or `true` to * perform a binary search on a sorted `array`. * @returns {Number} Returns the index of the matched value or `-1`. * @example * * _.indexOf([1, 2, 3, 1, 2, 3], 2); * // => 1 * * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); * // => 4 * * _.indexOf([1, 1, 2, 2, 3, 3], 2, true); * // => 2 */ function indexOf(array, value, fromIndex) { var index = -1, length = array ? array.length : 0; if (typeof fromIndex == 'number') { index = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0) - 1; } else if (fromIndex) { index = sortedIndex(array, value); return array[index] === value ? index : -1; } while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * Gets all but the last element of `array`. If a number `n` is passed, the * last `n` elements are excluded from the result. If a `callback` function * is passed, elements at the end of the array are excluded from the result * as long as the `callback` returns truthy. The `callback` is bound to * `thisArg` and invoked with three arguments; (value, index, array). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|Number|String} [callback|n=1] The function called * per element or the number of elements to exclude. If a property name or * object is passed, it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] * * _.initial([1, 2, 3], 2); * // => [1] * * _.initial([1, 2, 3], function(num) { * return num > 1; * }); * // => [1] * * var food = [ * { 'name': 'beet', 'organic': false }, * { 'name': 'carrot', 'organic': true } * ]; * * // using "_.pluck" callback shorthand * _.initial(food, 'organic'); * // => [{ 'name': 'beet', 'organic': false }] * * var food = [ * { 'name': 'banana', 'type': 'fruit' }, * { 'name': 'beet', 'type': 'vegetable' }, * { 'name': 'carrot', 'type': 'vegetable' } * ]; * * // using "_.where" callback shorthand * _.initial(food, { 'type': 'vegetable' }); * // => [{ 'name': 'banana', 'type': 'fruit' }] */ function initial(array, callback, thisArg) { if (!array) { return []; } var n = 0, length = array.length; if (typeof callback != 'number' && callback != null) { var index = length; callback = lodash.createCallback(callback, thisArg); while (index-- && callback(array[index], index, array)) { n++; } } else { n = (callback == null || thisArg) ? 1 : callback || n; } return slice(array, 0, nativeMin(nativeMax(0, length - n), length)); } /** * Computes the intersection of all the passed-in arrays using strict equality * for comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} [array1, array2, ...] Arrays to process. * @returns {Array} Returns a new array of unique elements that are present * in **all** of the arrays. * @example * * _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); * // => [1, 2] */ function intersection(array) { var args = arguments, argsLength = args.length, cache = { '0': {} }, index = -1, length = array ? array.length : 0, isLarge = length >= largeArraySize, result = [], seen = result; outer: while (++index < length) { var value = array[index]; if (isLarge) { var key = keyPrefix + value; var inited = cache[0][key] ? !(seen = cache[0][key]) : (seen = cache[0][key] = []); } if (inited || indexOf(seen, value) < 0) { if (isLarge) { seen.push(value); } var argsIndex = argsLength; while (--argsIndex) { if (!(cache[argsIndex] || (cache[argsIndex] = cachedContains(args[argsIndex])))(value)) { continue outer; } } result.push(value); } } return result; } /** * Gets the last element of the `array`. If a number `n` is passed, the * last `n` elements of the `array` are returned. If a `callback` function * is passed, elements at the end of the array are returned as long as the * `callback` returns truthy. The `callback` is bound to `thisArg` and * invoked with three arguments;(value, index, array). * * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|Number|String} [callback|n] The function called * per element or the number of elements to return. If a property name or * object is passed, it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Mixed} Returns the last element(s) of `array`. * @example * * _.last([1, 2, 3]); * // => 3 * * _.last([1, 2, 3], 2); * // => [2, 3] * * _.last([1, 2, 3], function(num) { * return num > 1; * }); * // => [2, 3] * * var food = [ * { 'name': 'beet', 'organic': false }, * { 'name': 'carrot', 'organic': true } * ]; * * // using "_.pluck" callback shorthand * _.last(food, 'organic'); * // => [{ 'name': 'carrot', 'organic': true }] * * var food = [ * { 'name': 'banana', 'type': 'fruit' }, * { 'name': 'beet', 'type': 'vegetable' }, * { 'name': 'carrot', 'type': 'vegetable' } * ]; * * // using "_.where" callback shorthand * _.last(food, { 'type': 'vegetable' }); * // => [{ 'name': 'beet', 'type': 'vegetable' }, { 'name': 'carrot', 'type': 'vegetable' }] */ function last(array, callback, thisArg) { if (array) { var n = 0, length = array.length; if (typeof callback != 'number' && callback != null) { var index = length; callback = lodash.createCallback(callback, thisArg); while (index-- && callback(array[index], index, array)) { n++; } } else { n = callback; if (n == null || thisArg) { return array[length - 1]; } } return slice(array, nativeMax(0, length - n)); } } /** * Gets the index at which the last occurrence of `value` is found using strict * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used * as the offset from the end of the collection. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {Mixed} 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 or `-1`. * @example * * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); * // => 4 * * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var index = array ? array.length : 0; if (typeof fromIndex == 'number') { index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1; } while (index--) { if (array[index] === value) { return index; } } return -1; } /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to but not including `end`. * * @static * @memberOf _ * @category Arrays * @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 a new range array. * @example * * _.range(10); * // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] * * _.range(1, 11); * // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] * * _.range(0, 30, 5); * // => [0, 5, 10, 15, 20, 25] * * _.range(0, -10, -1); * // => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] * * _.range(0); * // => [] */ function range(start, end, step) { start = +start || 0; step = +step || 1; if (end == null) { end = start; start = 0; } // use `Array(length)` so V8 will avoid the slower "dictionary" mode // http://youtu.be/XAqIpGU8ZZk#t=17m25s var index = -1, length = nativeMax(0, ceil((end - start) / step)), result = Array(length); while (++index < length) { result[index] = start; start += step; } return result; } /** * The opposite of `_.initial`, this method gets all but the first value of * `array`. If a number `n` is passed, the first `n` values are excluded from * the result. If a `callback` function is passed, elements at the beginning * of the array are excluded from the result as long as the `callback` returns * truthy. The `callback` is bound to `thisArg` and invoked with three * arguments; (value, index, array). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias drop, tail * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|Number|String} [callback|n=1] The function called * per element or the number of elements to exclude. If a property name or * object is passed, it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a slice of `array`. * @example * * _.rest([1, 2, 3]); * // => [2, 3] * * _.rest([1, 2, 3], 2); * // => [3] * * _.rest([1, 2, 3], function(num) { * return num < 3; * }); * // => [3] * * var food = [ * { 'name': 'banana', 'organic': true }, * { 'name': 'beet', 'organic': false }, * ]; * * // using "_.pluck" callback shorthand * _.rest(food, 'organic'); * // => [{ 'name': 'beet', 'organic': false }] * * var food = [ * { 'name': 'apple', 'type': 'fruit' }, * { 'name': 'banana', 'type': 'fruit' }, * { 'name': 'beet', 'type': 'vegetable' } * ]; * * // using "_.where" callback shorthand * _.rest(food, { 'type': 'fruit' }); * // => [{ 'name': 'beet', 'type': 'vegetable' }] */ function rest(array, callback, thisArg) { if (typeof callback != 'number' && callback != null) { var n = 0, index = -1, length = array ? array.length : 0; callback = lodash.createCallback(callback, thisArg); while (++index < length && callback(array[index], index, array)) { n++; } } else { n = (callback == null || thisArg) ? 1 : nativeMax(0, callback); } return slice(array, n); } /** * Uses a binary search to determine the smallest index at which the `value` * should be inserted into `array` in order to maintain the sort order of the * sorted `array`. If `callback` is passed, it will be executed for `value` and * each element in `array` to compute their sort ranking. The `callback` is * bound to `thisArg` and invoked with one argument; (value). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to inspect. * @param {Mixed} value The value to evaluate. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Number} Returns the index at which the value should be inserted * into `array`. * @example * * _.sortedIndex([20, 30, 50], 40); * // => 2 * * // using "_.pluck" callback shorthand * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); * // => 2 * * var dict = { * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } * }; * * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { * return dict.wordToNumber[word]; * }); * // => 2 * * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { * return this.wordToNumber[word]; * }, dict); * // => 2 */ function sortedIndex(array, value, callback, thisArg) { var low = 0, high = array ? array.length : low; // explicitly reference `identity` for better inlining in Firefox callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity; value = callback(value); while (low < high) { var mid = (low + high) >>> 1; (callback(array[mid]) < value) ? low = mid + 1 : high = mid; } return low; } /** * Computes the union of the passed-in arrays using strict equality for * comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} [array1, array2, ...] Arrays to process. * @returns {Array} Returns a new array of unique values, in order, that are * present in one or more of the arrays. * @example * * _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); * // => [1, 2, 3, 101, 10] */ function union(array) { if (!isArray(array)) { arguments[0] = array ? nativeSlice.call(array) : arrayRef; } return uniq(concat.apply(arrayRef, arguments)); } /** * Creates a duplicate-value-free version of the `array` using strict equality * for comparisons, i.e. `===`. If the `array` is already sorted, passing `true` * for `isSorted` will run a faster algorithm. If `callback` is passed, each * element of `array` is passed through a callback` before uniqueness is computed. * The `callback` is bound to `thisArg` and invoked with three arguments; (value, index, array). * * If a property name is passed for `callback`, the created "_.pluck" style * callback will return the property value of the given element. * * If an object is passed for `callback`, the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias unique * @category Arrays * @param {Array} array The array to process. * @param {Boolean} [isSorted=false] A flag to indicate that the `array` is already sorted. * @param {Function|Object|String} [callback=identity] The function called per * iteration. If a property name or object is passed, it will be used to create * a "_.pluck" or "_.where" style callback, respectively. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a duplicate-value-free array. * @example * * _.uniq([1, 2, 1, 3, 1]); * // => [1, 2, 3] * * _.uniq([1, 1, 2, 2, 3], true); * // => [1, 2, 3] * * _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return Math.floor(num); }); * // => [1, 2, 3] * * _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return this.floor(num); }, Math); * // => [1, 2, 3] * * // using "_.pluck" callback shorthand * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniq(array, isSorted, callback, thisArg) { var index = -1, length = array ? array.length : 0, result = [], seen = result; // juggle arguments if (typeof isSorted != 'boolean' && isSorted != null) { thisArg = callback; callback = isSorted; isSorted = false; } // init value cache for large arrays var isLarge = !isSorted && length >= largeArraySize; if (isLarge) { var cache = {}; } if (callback != null) { seen = []; callback = lodash.createCallback(callback, thisArg); } while (++index < length) { var value = array[index], computed = callback ? callback(value, index, array) : value; if (isLarge) { var key = keyPrefix + computed; var inited = cache[key] ? !(seen = cache[key]) : (seen = cache[key] = []); } if (isSorted ? !index || seen[seen.length - 1] !== computed : inited || indexOf(seen, computed) < 0 ) { if (callback || isLarge) { seen.push(computed); } result.push(value); } } return result; } /** * The inverse of `_.zip`, this method splits groups of elements into arrays * composed of elements from each group at their corresponding indexes. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to process. * @returns {Array} Returns a new array of the composed arrays. * @example * * _.unzip([['moe', 30, true], ['larry', 40, false]]); * // => [['moe', 'larry'], [30, 40], [true, false]]; */ function unzip(array) { var index = -1, length = array ? array.length : 0, tupleLength = length ? max(pluck(array, 'length')) : 0, result = Array(tupleLength); while (++index < length) { var tupleIndex = -1, tuple = array[index]; while (++tupleIndex < tupleLength) { (result[tupleIndex] || (result[tupleIndex] = Array(length)))[index] = tuple[tupleIndex]; } } return result; } /** * Creates an array with all occurrences of the passed values removed using * strict equality for comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to filter. * @param {Mixed} [value1, value2, ...] Values to remove. * @returns {Array} Returns a new filtered array. * @example * * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); * // => [2, 3, 4] */ function without(array) { return difference(array, nativeSlice.call(arguments, 1)); } /** * Groups the elements of each array at their corresponding indexes. Useful for * separate data sources that are coordinated through matching array indexes. * For a matrix of nested arrays, `_.zip.apply(...)` can transpose the matrix * in a similar fashion. * * @static * @memberOf _ * @category Arrays * @param {Array} [array1, array2, ...] Arrays to process. * @returns {Array} Returns a new array of grouped elements. * @example * * _.zip(['moe', 'larry'], [30, 40], [true, false]); * // => [['moe', 30, true], ['larry', 40, false]] */ function zip(array) { var index = -1, length = array ? max(pluck(arguments, 'length')) : 0, result = Array(length); while (++index < length) { result[index] = pluck(arguments, index); } return result; } /** * Creates an object composed from arrays of `keys` and `values`. Pass either * a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`, or * two arrays, one of `keys` and one of corresponding `values`. * * @static * @memberOf _ * @alias object * @category Arrays * @param {Array} keys The array of keys. * @param {Array} [values=[]] The array of values. * @returns {Object} Returns an object composed of the given keys and * corresponding values. * @example * * _.zipObject(['moe', 'larry'], [30, 40]); * // => { 'moe': 30, 'larry': 40 } */ function zipObject(keys, values) { var index = -1, length = keys ? keys.length : 0, result = {}; while (++index < length) { var key = keys[index]; if (values) { result[key] = values[index]; } else { result[key[0]] = key[1]; } } return result; } /*--------------------------------------------------------------------------*/ /** * If `n` is greater than `0`, a function is created that is restricted to * executing `func`, with the `this` binding and arguments of the created * function, only after it is called `n` times. If `n` is less than `1`, * `func` is executed immediately, without a `this` binding or additional * arguments, and its result is returned. * * @static * @memberOf _ * @category Functions * @param {Number} n The number of times the function must be called before * it is executed. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var renderNotes = _.after(notes.length, render); * _.forEach(notes, function(note) { * note.asyncSave({ 'success': renderNotes }); * }); * // `renderNotes` is run once, after all notes have saved */ function after(n, func) { if (n < 1) { return func(); } return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that, when called, invokes `func` with the `this` * binding of `thisArg` and prepends any additional `bind` arguments to those * passed to the bound function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to bind. * @param {Mixed} [thisArg] The `this` binding of `func`. * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var func = function(greeting) { * return greeting + ' ' + this.name; * }; * * func = _.bind(func, { 'name': 'moe' }, 'hi'); * func(); * // => 'hi moe' */ function bind(func, thisArg) { // use `Function#bind` if it exists and is fast // (in V8 `Function#bind` is slower except when partially applied) return support.fastBind || (nativeBind && arguments.length > 2) ? nativeBind.call.apply(nativeBind, arguments) : createBound(func, thisArg, nativeSlice.call(arguments, 2)); } /** * Binds methods on `object` to `object`, overwriting the existing method. * Method names may be specified as individual arguments or as arrays of method * names. If no method names are provided, all the function properties of `object` * will be bound. * * @static * @memberOf _ * @category Functions * @param {Object} object The object to bind and assign the bound methods to. * @param {String} [methodName1, methodName2, ...] Method names on the object to bind. * @returns {Object} Returns `object`. * @example * * var view = { * 'label': 'docs', * 'onClick': function() { alert('clicked ' + this.label); } * }; * * _.bindAll(view); * jQuery('#docs').on('click', view.onClick); * // => alerts 'clicked docs', when the button is clicked */ function bindAll(object) { var funcs = arguments.length > 1 ? concat.apply(arrayRef, nativeSlice.call(arguments, 1)) : functions(object), index = -1, length = funcs.length; while (++index < length) { var key = funcs[index]; object[key] = bind(object[key], object); } return object; } /** * Creates a function that, when called, invokes the method at `object[key]` * and prepends any additional `bindKey` arguments to those passed to the bound * function. This method differs from `_.bind` by allowing bound functions to * reference methods that will be redefined or don't yet exist. * See http://michaux.ca/articles/lazy-function-definition-pattern. * * @static * @memberOf _ * @category Functions * @param {Object} object The object the method belongs to. * @param {String} key The key of the method. * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'name': 'moe', * 'greet': function(greeting) { * return greeting + ' ' + this.name; * } * }; * * var func = _.bindKey(object, 'greet', 'hi'); * func(); * // => 'hi moe' * * object.greet = function(greeting) { * return greeting + ', ' + this.name + '!'; * }; * * func(); * // => 'hi, moe!' */ function bindKey(object, key) { return createBound(object, key, nativeSlice.call(arguments, 2), indicatorObject); } /** * Creates a function that is the composition of the passed functions, * where each function consumes the return value of the function that follows. * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. * Each function is executed with the `this` binding of the composed function. * * @static * @memberOf _ * @category Functions * @param {Function} [func1, func2, ...] Functions to compose. * @returns {Function} Returns the new composed function. * @example * * var greet = function(name) { return 'hi ' + name; }; * var exclaim = function(statement) { return statement + '!'; }; * var welcome = _.compose(exclaim, greet); * welcome('moe'); * // => 'hi moe!' */ function compose() { var funcs = arguments; return function() { var args = arguments, length = funcs.length; while (length--) { args = [funcs[length].apply(this, args)]; } return args[0]; }; } /** * Produces a callback bound to an optional `thisArg`. If `func` is a property * name, the created callback will return the property value for a given element. * If `func` is an object, the created callback will return `true` for elements * that contain the equivalent object properties, otherwise it will return `false`. * * Note: All Lo-Dash methods, that accept a `callback` argument, use `_.createCallback`. * * @static * @memberOf _ * @category Functions * @param {Mixed} [func=identity] The value to convert to a callback. * @param {Mixed} [thisArg] The `this` binding of the created callback. * @param {Number} [argCount=3] The number of arguments the callback accepts. * @returns {Function} Returns a callback function. * @example * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * // wrap to create custom callback shorthands * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) { * var match = /^(.+?)__([gl]t)(.+)$/.exec(callback); * return !match ? func(callback, thisArg) : function(object) { * return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3]; * }; * }); * * _.filter(stooges, 'age__gt45'); * // => [{ 'name': 'larry', 'age': 50 }] * * // create mixins with support for "_.pluck" and "_.where" callback shorthands * _.mixin({ * 'toLookup': function(collection, callback, thisArg) { * callback = _.createCallback(callback, thisArg); * return _.reduce(collection, function(result, value, index, collection) { * return (result[callback(value, index, collection)] = value, result); * }, {}); * } * }); * * _.toLookup(stooges, 'name'); * // => { 'moe': { 'name': 'moe', 'age': 40 }, 'larry': { 'name': 'larry', 'age': 50 } } */ function createCallback(func, thisArg, argCount) { if (func == null) { return identity; } var type = typeof func; if (type != 'function') { if (type != 'object') { return function(object) { return object[func]; }; } var props = keys(func); return function(object) { var length = props.length, result = false; while (length--) { if (!(result = isEqual(object[props[length]], func[props[length]], indicatorObject))) { break; } } return result; }; } if (typeof thisArg != 'undefined') { if (argCount === 1) { return function(value) { return func.call(thisArg, value); }; } if (argCount === 2) { return function(a, b) { return func.call(thisArg, a, b); }; } if (argCount === 4) { return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; } return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; } return func; } /** * Creates a function that will delay the execution of `func` until after * `wait` milliseconds have elapsed since the last time it was invoked. Pass * an `options` object to indicate that `func` should be invoked on the leading * and/or trailing edge of the `wait` timeout. Subsequent calls to the debounced * function will return the result of the last `func` call. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to debounce. * @param {Number} wait The number of milliseconds to delay. * @param {Object} options The options object. * [leading=false] A boolean to specify execution on the leading edge of the timeout. * [trailing=true] A boolean to specify execution on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * var lazyLayout = _.debounce(calculateLayout, 300); * jQuery(window).on('resize', lazyLayout); */ function debounce(func, wait, options) { var args, result, thisArg, timeoutId, trailing = true; function delayed() { timeoutId = null; if (trailing) { result = func.apply(thisArg, args); } } if (options === true) { var leading = true; trailing = false; } else if (options && objectTypes[typeof options]) { leading = options.leading; trailing = 'trailing' in options ? options.trailing : trailing; } return function() { var isLeading = leading && !timeoutId; args = arguments; thisArg = this; clearTimeout(timeoutId); timeoutId = setTimeout(delayed, wait); if (isLeading) { result = func.apply(thisArg, args); } return result; }; } /** * Defers executing the `func` function until the current call stack has cleared. * Additional arguments will be passed to `func` when it is invoked. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to defer. * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with. * @returns {Number} Returns the timer id. * @example * * _.defer(function() { alert('deferred'); }); * // returns from the function before `alert` is called */ function defer(func) { var args = nativeSlice.call(arguments, 1); return setTimeout(function() { func.apply(undefined, args); }, 1); } // use `setImmediate` if it's available in Node.js if (isV8 && freeModule && typeof setImmediate == 'function') { defer = bind(setImmediate, context); } /** * Executes the `func` function after `wait` milliseconds. Additional arguments * will be passed to `func` when it is invoked. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to delay. * @param {Number} wait The number of milliseconds to delay execution. * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with. * @returns {Number} Returns the timer id. * @example * * var log = _.bind(console.log, console); * _.delay(log, 1000, 'logged later'); * // => 'logged later' (Appears after one second.) */ function delay(func, wait) { var args = nativeSlice.call(arguments, 2); return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * passed, it will be used to determine the cache key for storing the result * based on the arguments passed to the memoized function. By default, the first * argument passed to the memoized function is used as the cache key. The `func` * is executed with the `this` binding of the memoized function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] A function used to resolve the cache key. * @returns {Function} Returns the new memoizing function. * @example * * var fibonacci = _.memoize(function(n) { * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); * }); */ function memoize(func, resolver) { var cache = {}; return function() { var key = keyPrefix + (resolver ? resolver.apply(this, arguments) : arguments[0]); return hasOwnProperty.call(cache, key) ? cache[key] : (cache[key] = func.apply(this, arguments)); }; } /** * Creates a function that is restricted to execute `func` once. Repeat calls to * the function will return the value of the first call. The `func` is executed * with the `this` binding of the created function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // `initialize` executes `createApplication` once */ function once(func) { var ran, result; return function() { if (ran) { return result; } ran = true; result = func.apply(this, arguments); // clear the `func` variable so the function may be garbage collected func = null; return result; }; } /** * Creates a function that, when called, invokes `func` with any additional * `partial` arguments prepended to those passed to the new function. This * method is similar to `_.bind`, except it does **not** alter the `this` binding. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to partially apply arguments to. * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var greet = function(greeting, name) { return greeting + ' ' + name; }; * var hi = _.partial(greet, 'hi'); * hi('moe'); * // => 'hi moe' */ function partial(func) { return createBound(func, nativeSlice.call(arguments, 1)); } /** * This method is similar to `_.partial`, except that `partial` arguments are * appended to those passed to the new function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to partially apply arguments to. * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var defaultsDeep = _.partialRight(_.merge, _.defaults); * * var options = { * 'variable': 'data', * 'imports': { 'jq': $ } * }; * * defaultsDeep(options, _.templateSettings); * * options.variable * // => 'data' * * options.imports * // => { '_': _, 'jq': $ } */ function partialRight(func) { return createBound(func, nativeSlice.call(arguments, 1), null, indicatorObject); } /** * Creates a function that, when executed, will only call the `func` function * at most once per every `wait` milliseconds. If the throttled function is * invoked more than once during the `wait` timeout, `func` will also be called * on the trailing edge of the timeout. Pass an `options` object to indicate * that `func` should be invoked on the leading and/or trailing edge of the * `wait` timeout. Subsequent calls to the throttled function will return * the result of the last `func` call. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to throttle. * @param {Number} wait The number of milliseconds to throttle executions to. * @param {Object} options The options object. * [leading=true] A boolean to specify execution on the leading edge of the timeout. * [trailing=true] A boolean to specify execution on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * var throttled = _.throttle(updatePosition, 100); * jQuery(window).on('scroll', throttled); */ function throttle(func, wait, options) { var args, result, thisArg, timeoutId, lastCalled = 0, leading = true, trailing = true; function trailingCall() { lastCalled = new Date; timeoutId = null; if (trailing) { result = func.apply(thisArg, args); } } if (options === false) { leading = false; } else if (options && objectTypes[typeof options]) { leading = 'leading' in options ? options.leading : leading; trailing = 'trailing' in options ? options.trailing : trailing; } return function() { var now = new Date; if (!timeoutId && !leading) { lastCalled = now; } var remaining = wait - (now - lastCalled); args = arguments; thisArg = this; if (remaining <= 0) { clearTimeout(timeoutId); timeoutId = null; lastCalled = now; result = func.apply(thisArg, args); } else if (!timeoutId) { timeoutId = setTimeout(trailingCall, remaining); } return result; }; } /** * Creates a function that passes `value` to the `wrapper` function as its * first argument. Additional arguments passed to the function are appended * to those passed to the `wrapper` function. The `wrapper` is executed with * the `this` binding of the created function. * * @static * @memberOf _ * @category Functions * @param {Mixed} value The value to wrap. * @param {Function} wrapper The wrapper function. * @returns {Function} Returns the new function. * @example * * var hello = function(name) { return 'hello ' + name; }; * hello = _.wrap(hello, function(func) { * return 'before, ' + func('moe') + ', after'; * }); * hello(); * // => 'before, hello moe, after' */ function wrap(value, wrapper) { return function() { var args = [value]; push.apply(args, arguments); return wrapper.apply(this, args); }; } /*--------------------------------------------------------------------------*/ /** * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their * corresponding HTML entities. * * @static * @memberOf _ * @category Utilities * @param {String} string The string to escape. * @returns {String} Returns the escaped string. * @example * * _.escape('Moe, Larry & Curly'); * // => 'Moe, Larry &amp; Curly' */ function escape(string) { return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar); } /** * This function returns the first argument passed to it. * * @static * @memberOf _ * @category Utilities * @param {Mixed} value Any value. * @returns {Mixed} Returns `value`. * @example * * var moe = { 'name': 'moe' }; * moe === _.identity(moe); * // => true */ function identity(value) { return value; } /** * Adds functions properties of `object` to the `lodash` function and chainable * wrapper. * * @static * @memberOf _ * @category Utilities * @param {Object} object The object of function properties to add to `lodash`. * @example * * _.mixin({ * 'capitalize': function(string) { * return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); * } * }); * * _.capitalize('moe'); * // => 'Moe' * * _('moe').capitalize(); * // => 'Moe' */ function mixin(object) { forEach(functions(object), function(methodName) { var func = lodash[methodName] = object[methodName]; lodash.prototype[methodName] = function() { var value = this.__wrapped__, args = [value]; push.apply(args, arguments); var result = func.apply(lodash, args); return (value && typeof value == 'object' && value == result) ? this : new lodashWrapper(result); }; }); } /** * Reverts the '_' variable to its previous value and returns a reference to * the `lodash` function. * * @static * @memberOf _ * @category Utilities * @returns {Function} Returns the `lodash` function. * @example * * var lodash = _.noConflict(); */ function noConflict() { context._ = oldDash; return this; } /** * Converts the given `value` into an integer of the specified `radix`. * * Note: This method avoids differences in native ES3 and ES5 `parseInt` * implementations. See http://es5.github.com/#E. * * @static * @memberOf _ * @category Utilities * @param {Mixed} value The value to parse. * @returns {Number} Returns the new integer value. * @example * * _.parseInt('08'); * // => 8 */ var parseInt = nativeParseInt('08') == 8 ? nativeParseInt : function(value, radix) { // Firefox and Opera still follow the ES3 specified implementation of `parseInt` return nativeParseInt(isString(value) ? value.replace(reLeadingZeros, '') : value, radix || 0); }; /** * Produces a random number between `min` and `max` (inclusive). If only one * argument is passed, a number between `0` and the given number will be returned. * * @static * @memberOf _ * @category Utilities * @param {Number} [min=0] The minimum possible value. * @param {Number} [max=1] The maximum possible value. * @returns {Number} Returns a random number. * @example * * _.random(0, 5); * // => a number between 0 and 5 * * _.random(5); * // => also a number between 0 and 5 */ function random(min, max) { if (min == null && max == null) { max = 1; } min = +min || 0; if (max == null) { max = min; min = 0; } return min + floor(nativeRandom() * ((+max || 0) - min + 1)); } /** * Resolves the value of `property` on `object`. If `property` is a function, * it will be invoked with the `this` binding of `object` and its result returned, * else the property value is returned. If `object` is falsey, then `undefined` * is returned. * * @static * @memberOf _ * @category Utilities * @param {Object} object The object to inspect. * @param {String} property The property to get the value of. * @returns {Mixed} Returns the resolved value. * @example * * var object = { * 'cheese': 'crumpets', * 'stuff': function() { * return 'nonsense'; * } * }; * * _.result(object, 'cheese'); * // => 'crumpets' * * _.result(object, 'stuff'); * // => 'nonsense' */ function result(object, property) { var value = object ? object[property] : undefined; return isFunction(value) ? object[property]() : value; } /** * A micro-templating method that handles arbitrary delimiters, preserves * whitespace, and correctly escapes quotes within interpolated code. * * Note: In the development build, `_.template` utilizes sourceURLs for easier * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl * * For more information on precompiling templates see: * http://lodash.com/#custom-builds * * For more information on Chrome extension sandboxes see: * http://developer.chrome.com/stable/extensions/sandboxingEval.html * * @static * @memberOf _ * @category Utilities * @param {String} text The template text. * @param {Object} data The data object used to populate the text. * @param {Object} options The options object. * escape - The "escape" delimiter regexp. * evaluate - The "evaluate" delimiter regexp. * interpolate - The "interpolate" delimiter regexp. * sourceURL - The sourceURL of the template's compiled source. * variable - The data object variable name. * @returns {Function|String} Returns a compiled function when no `data` object * is given, else it returns the interpolated text. * @example * * // using a compiled template * var compiled = _.template('hello <%= name %>'); * compiled({ 'name': 'moe' }); * // => 'hello moe' * * var list = '<% _.forEach(people, function(name) { %><li><%= name %></li><% }); %>'; * _.template(list, { 'people': ['moe', 'larry'] }); * // => '<li>moe</li><li>larry</li>' * * // using the "escape" delimiter to escape HTML in data property values * _.template('<b><%- value %></b>', { 'value': '<script>' }); * // => '<b>&lt;script&gt;</b>' * * // using the ES6 delimiter as an alternative to the default "interpolate" delimiter * _.template('hello ${ name }', { 'name': 'curly' }); * // => 'hello curly' * * // using the internal `print` function in "evaluate" delimiters * _.template('<% print("hello " + epithet); %>!', { 'epithet': 'stooge' }); * // => 'hello stooge!' * * // using custom template delimiters * _.templateSettings = { * 'interpolate': /{{([\s\S]+?)}}/g * }; * * _.template('hello {{ name }}!', { 'name': 'mustache' }); * // => 'hello mustache!' * * // using the `sourceURL` option to specify a custom sourceURL for the template * var compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' }); * compiled(data); * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector * * // using the `variable` option to ensure a with-statement isn't used in the compiled template * var compiled = _.template('hi <%= data.name %>!', null, { 'variable': 'data' }); * compiled.source; * // => function(data) { * var __t, __p = '', __e = _.escape; * __p += 'hi ' + ((__t = ( data.name )) == null ? '' : __t) + '!'; * return __p; * } * * // using the `source` property to inline compiled templates for meaningful * // line numbers in error messages and a stack trace * fs.writeFileSync(path.join(cwd, 'jst.js'), '\ * var JST = {\ * "main": ' + _.template(mainText).source + '\ * };\ * '); */ function template(text, data, options) { // 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; text || (text = ''); // avoid missing dependencies when `iteratorTemplate` is not defined options = iteratorTemplate ? defaults({}, options, settings) : settings; var imports = iteratorTemplate && defaults({}, options.imports, settings.imports), importsKeys = iteratorTemplate ? keys(imports) : ['_'], importsValues = iteratorTemplate ? values(imports) : [lodash]; var 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'); text.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // escape characters that cannot be included in string literals source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar); // replace delimiters with snippets if (escapeValue) { 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 requires returning the `match` // string 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 = options.variable, hasVariable = variable; if (!hasVariable) { variable = 'obj'; source = 'with (' + variable + ') {\n' + source + '\n}\n'; } // cleanup code by stripping empty strings source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) .replace(reEmptyStringMiddle, '$1') .replace(reEmptyStringTrailing, '$1;'); // frame code as the function body source = 'function(' + variable + ') {\n' + (hasVariable ? '' : variable + ' || (' + variable + ' = {});\n') + "var __t, __p = '', __e = _.escape" + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n' ) + source + 'return __p\n}'; // Use a sourceURL for easier debugging and wrap in a multi-line comment to // avoid issues with Narwhal, IE conditional compilation, and the JS engine // embedded in Adobe products. // http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl var sourceURL = '\n/*\n//@ sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']') + '\n*/'; try { var result = Function(importsKeys, 'return ' + source + sourceURL).apply(undefined, importsValues); } catch(e) { e.source = source; throw e; } if (data) { return result(data); } // provide the compiled function's source via its `toString` method, in // supported environments, or the `source` property as a convenience for // inlining compiled templates during the build process result.source = source; return result; } /** * Executes the `callback` function `n` times, returning an array of the results * of each `callback` execution. The `callback` is bound to `thisArg` and invoked * with one argument; (index). * * @static * @memberOf _ * @category Utilities * @param {Number} n The number of times to execute the callback. * @param {Function} callback The function called per iteration. * @param {Mixed} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of the results of each `callback` execution. * @example * * var diceRolls = _.times(3, _.partial(_.random, 1, 6)); * // => [3, 6, 4] * * _.times(3, function(n) { mage.castSpell(n); }); * // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively * * _.times(3, function(n) { this.cast(n); }, mage); * // => also calls `mage.castSpell(n)` three times */ function times(n, callback, thisArg) { n = (n = +n) > -1 ? n : 0; var index = -1, result = Array(n); callback = lodash.createCallback(callback, thisArg, 1); while (++index < n) { result[index] = callback(index); } return result; } /** * The inverse of `_.escape`, this method converts the HTML entities * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to their * corresponding characters. * * @static * @memberOf _ * @category Utilities * @param {String} string The string to unescape. * @returns {String} Returns the unescaped string. * @example * * _.unescape('Moe, Larry &amp; Curly'); * // => 'Moe, Larry & Curly' */ function unescape(string) { return string == null ? '' : String(string).replace(reEscapedHtml, unescapeHtmlChar); } /** * Generates a unique ID. If `prefix` is passed, the ID will be appended to it. * * @static * @memberOf _ * @category Utilities * @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 String(prefix == null ? '' : prefix) + id; } /*--------------------------------------------------------------------------*/ /** * Invokes `interceptor` with the `value` as the first argument, and then * returns `value`. The purpose of this method is to "tap into" a method chain, * in order to perform operations on intermediate results within the chain. * * @static * @memberOf _ * @category Chaining * @param {Mixed} value The value to pass to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {Mixed} Returns `value`. * @example * * _([1, 2, 3, 4]) * .filter(function(num) { return num % 2 == 0; }) * .tap(alert) * .map(function(num) { return num * num; }) * .value(); * // => // [2, 4] (alerted) * // => [4, 16] */ function tap(value, interceptor) { interceptor(value); return value; } /** * Produces the `toString` result of the wrapped value. * * @name toString * @memberOf _ * @category Chaining * @returns {String} Returns the string result. * @example * * _([1, 2, 3]).toString(); * // => '1,2,3' */ function wrapperToString() { return String(this.__wrapped__); } /** * Extracts the wrapped value. * * @name valueOf * @memberOf _ * @alias value * @category Chaining * @returns {Mixed} Returns the wrapped value. * @example * * _([1, 2, 3]).valueOf(); * // => [1, 2, 3] */ function wrapperValueOf() { return this.__wrapped__; } /*--------------------------------------------------------------------------*/ // add functions that return wrapped values when chaining lodash.after = after; lodash.assign = assign; lodash.at = at; lodash.bind = bind; lodash.bindAll = bindAll; lodash.bindKey = bindKey; lodash.compact = compact; lodash.compose = compose; lodash.countBy = countBy; lodash.createCallback = createCallback; lodash.debounce = debounce; lodash.defaults = defaults; lodash.defer = defer; lodash.delay = delay; lodash.difference = difference; lodash.filter = filter; lodash.flatten = flatten; lodash.forEach = forEach; lodash.forIn = forIn; lodash.forOwn = forOwn; lodash.functions = functions; lodash.groupBy = groupBy; lodash.initial = initial; lodash.intersection = intersection; lodash.invert = invert; lodash.invoke = invoke; lodash.keys = keys; lodash.map = map; lodash.max = max; lodash.memoize = memoize; lodash.merge = merge; lodash.min = min; lodash.omit = omit; lodash.once = once; lodash.pairs = pairs; lodash.partial = partial; lodash.partialRight = partialRight; lodash.pick = pick; lodash.pluck = pluck; lodash.range = range; lodash.reject = reject; lodash.rest = rest; lodash.shuffle = shuffle; lodash.sortBy = sortBy; lodash.tap = tap; lodash.throttle = throttle; lodash.times = times; lodash.toArray = toArray; lodash.union = union; lodash.uniq = uniq; lodash.unzip = unzip; lodash.values = values; lodash.where = where; lodash.without = without; lodash.wrap = wrap; lodash.zip = zip; lodash.zipObject = zipObject; // add aliases lodash.collect = map; lodash.drop = rest; lodash.each = forEach; lodash.extend = assign; lodash.methods = functions; lodash.object = zipObject; lodash.select = filter; lodash.tail = rest; lodash.unique = uniq; // add functions to `lodash.prototype` mixin(lodash); /*--------------------------------------------------------------------------*/ // add functions that return unwrapped values when chaining lodash.clone = clone; lodash.cloneDeep = cloneDeep; lodash.contains = contains; lodash.escape = escape; lodash.every = every; lodash.find = find; lodash.findIndex = findIndex; lodash.findKey = findKey; lodash.has = has; lodash.identity = identity; lodash.indexOf = indexOf; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isBoolean = isBoolean; lodash.isDate = isDate; lodash.isElement = isElement; lodash.isEmpty = isEmpty; lodash.isEqual = isEqual; lodash.isFinite = isFinite; lodash.isFunction = isFunction; lodash.isNaN = isNaN; lodash.isNull = isNull; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isPlainObject = isPlainObject; lodash.isRegExp = isRegExp; lodash.isString = isString; lodash.isUndefined = isUndefined; lodash.lastIndexOf = lastIndexOf; lodash.mixin = mixin; lodash.noConflict = noConflict; lodash.parseInt = parseInt; lodash.random = random; lodash.reduce = reduce; lodash.reduceRight = reduceRight; lodash.result = result; lodash.runInContext = runInContext; lodash.size = size; lodash.some = some; lodash.sortedIndex = sortedIndex; lodash.template = template; lodash.unescape = unescape; lodash.uniqueId = uniqueId; // add aliases lodash.all = every; lodash.any = some; lodash.detect = find; lodash.foldl = reduce; lodash.foldr = reduceRight; lodash.include = contains; lodash.inject = reduce; forOwn(lodash, function(func, methodName) { if (!lodash.prototype[methodName]) { lodash.prototype[methodName] = function() { var args = [this.__wrapped__]; push.apply(args, arguments); return func.apply(lodash, args); }; } }); /*--------------------------------------------------------------------------*/ // add functions capable of returning wrapped and unwrapped values when chaining lodash.first = first; lodash.last = last; // add aliases lodash.take = first; lodash.head = first; forOwn(lodash, function(func, methodName) { if (!lodash.prototype[methodName]) { lodash.prototype[methodName]= function(callback, thisArg) { var result = func(this.__wrapped__, callback, thisArg); return callback == null || (thisArg && typeof callback != 'function') ? result : new lodashWrapper(result); }; } }); /*--------------------------------------------------------------------------*/ /** * The semantic version number. * * @static * @memberOf _ * @type String */ lodash.VERSION = '1.2.0'; // add "Chaining" functions to the wrapper lodash.prototype.toString = wrapperToString; lodash.prototype.value = wrapperValueOf; lodash.prototype.valueOf = wrapperValueOf; // add `Array` functions that return unwrapped values each(['join', 'pop', 'shift'], function(methodName) { var func = arrayRef[methodName]; lodash.prototype[methodName] = function() { return func.apply(this.__wrapped__, arguments); }; }); // add `Array` functions that return the wrapped value each(['push', 'reverse', 'sort', 'unshift'], function(methodName) { var func = arrayRef[methodName]; lodash.prototype[methodName] = function() { func.apply(this.__wrapped__, arguments); return this; }; }); // add `Array` functions that return new wrapped values each(['concat', 'slice', 'splice'], function(methodName) { var func = arrayRef[methodName]; lodash.prototype[methodName] = function() { return new lodashWrapper(func.apply(this.__wrapped__, arguments)); }; }); // avoid array-like object bugs with `Array#shift` and `Array#splice` // in Firefox < 10 and IE < 9 if (!support.spliceObjects) { each(['pop', 'shift', 'splice'], function(methodName) { var func = arrayRef[methodName], isSplice = methodName == 'splice'; lodash.prototype[methodName] = function() { var value = this.__wrapped__, result = func.apply(value, arguments); if (value.length === 0) { delete value[0]; } return isSplice ? new lodashWrapper(result) : result; }; }); } // add pseudo private property to be used and removed during the build process lodash._each = each; lodash._iteratorTemplate = iteratorTemplate; lodash._shimKeys = shimKeys; return lodash; } /*--------------------------------------------------------------------------*/ // expose Lo-Dash var _ = runInContext(); // some AMD build optimizers, like r.js, check for specific condition patterns like the following: if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { // Expose Lo-Dash to the global object even when an AMD loader is present in // case Lo-Dash was injected by a third-party script and not intended to be // loaded as a module. The global assignment can be reverted in the Lo-Dash // module via its `noConflict()` method. window._ = _; // define as an anonymous module so, through path mapping, it can be // referenced as the "underscore" module define(function() { return _; }); } // check for `exports` after `define` in case a build optimizer adds an `exports` object else if (freeExports && !freeExports.nodeType) { // in Node.js or RingoJS v0.8.0+ if (freeModule) { (freeModule.exports = _)._ = _; } // in Narwhal or RingoJS v0.7.0- else { freeExports._ = _; } } else { // in a browser or Rhino window._ = _; } }(this)); /*global setImmediate: false, setTimeout: false, console: false */ (function () { var async = {}; // global on the server, window in the browser var root, previous_async; root = this; if (root != null) { previous_async = root.async; } async.noConflict = function () { root.async = previous_async; return async; }; function only_once(fn) { var called = false; return function() { if (called) throw new Error("Callback was already called."); called = true; fn.apply(root, arguments); } } //// cross-browser compatiblity functions //// var _each = function (arr, iterator) { if (arr.forEach) { return arr.forEach(iterator); } for (var i = 0; i < arr.length; i += 1) { iterator(arr[i], i, arr); } }; var _map = function (arr, iterator) { if (arr.map) { return arr.map(iterator); } var results = []; _each(arr, function (x, i, a) { results.push(iterator(x, i, a)); }); return results; }; var _reduce = function (arr, iterator, memo) { if (arr.reduce) { return arr.reduce(iterator, memo); } _each(arr, function (x, i, a) { memo = iterator(memo, x, i, a); }); return memo; }; var _keys = function (obj) { if (Object.keys) { return Object.keys(obj); } var keys = []; for (var k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys; }; //// exported async module functions //// //// nextTick implementation with browser-compatible fallback //// if (typeof process === 'undefined' || !(process.nextTick)) { if (typeof setImmediate === 'function') { async.setImmediate = setImmediate; async.nextTick = setImmediate; } else { async.setImmediate = async.nextTick; async.nextTick = function (fn) { setTimeout(fn, 0); }; } } else { async.nextTick = process.nextTick; if (typeof setImmediate !== 'undefined') { async.setImmediate = setImmediate; } else { async.setImmediate = async.nextTick; } } async.each = function (arr, iterator, callback) { callback = callback || function () {}; if (!arr.length) { return callback(); } var completed = 0; _each(arr, function (x) { iterator(x, only_once(function (err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; if (completed >= arr.length) { callback(null); } } })); }); }; async.forEach = async.each; async.eachSeries = function (arr, iterator, callback) { callback = callback || function () {}; if (!arr.length) { return callback(); } var completed = 0; var iterate = function () { iterator(arr[completed], function (err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; if (completed >= arr.length) { callback(null); } else { iterate(); } } }); }; iterate(); }; async.forEachSeries = async.eachSeries; async.eachLimit = function (arr, limit, iterator, callback) { var fn = _eachLimit(limit); fn.apply(null, [arr, iterator, callback]); }; async.forEachLimit = async.eachLimit; var _eachLimit = function (limit) { return function (arr, iterator, callback) { callback = callback || function () {}; if (!arr.length || limit <= 0) { return callback(); } var completed = 0; var started = 0; var running = 0; (function replenish () { if (completed >= arr.length) { return callback(); } while (running < limit && started < arr.length) { started += 1; running += 1; iterator(arr[started - 1], function (err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; running -= 1; if (completed >= arr.length) { callback(); } else { replenish(); } } }); } })(); }; }; var doParallel = function (fn) { return function () { var args = Array.prototype.slice.call(arguments); return fn.apply(null, [async.each].concat(args)); }; }; var doParallelLimit = function(limit, fn) { return function () { var args = Array.prototype.slice.call(arguments); return fn.apply(null, [_eachLimit(limit)].concat(args)); }; }; var doSeries = function (fn) { return function () { var args = Array.prototype.slice.call(arguments); return fn.apply(null, [async.eachSeries].concat(args)); }; }; var _asyncMap = function (eachfn, arr, iterator, callback) { var results = []; arr = _map(arr, function (x, i) { return {index: i, value: x}; }); eachfn(arr, function (x, callback) { iterator(x.value, function (err, v) { results[x.index] = v; callback(err); }); }, function (err) { callback(err, results); }); }; async.map = doParallel(_asyncMap); async.mapSeries = doSeries(_asyncMap); async.mapLimit = function (arr, limit, iterator, callback) { return _mapLimit(limit)(arr, iterator, callback); }; var _mapLimit = function(limit) { return doParallelLimit(limit, _asyncMap); }; // reduce only has a series version, as doing reduce in parallel won't // work in many situations. async.reduce = function (arr, memo, iterator, callback) { async.eachSeries(arr, function (x, callback) { iterator(memo, x, function (err, v) { memo = v; callback(err); }); }, function (err) { callback(err, memo); }); }; // inject alias async.inject = async.reduce; // foldl alias async.foldl = async.reduce; async.reduceRight = function (arr, memo, iterator, callback) { var reversed = _map(arr, function (x) { return x; }).reverse(); async.reduce(reversed, memo, iterator, callback); }; // foldr alias async.foldr = async.reduceRight; var _filter = function (eachfn, arr, iterator, callback) { var results = []; arr = _map(arr, function (x, i) { return {index: i, value: x}; }); eachfn(arr, function (x, callback) { iterator(x.value, function (v) { if (v) { results.push(x); } callback(); }); }, function (err) { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); }; async.filter = doParallel(_filter); async.filterSeries = doSeries(_filter); // select alias async.select = async.filter; async.selectSeries = async.filterSeries; var _reject = function (eachfn, arr, iterator, callback) { var results = []; arr = _map(arr, function (x, i) { return {index: i, value: x}; }); eachfn(arr, function (x, callback) { iterator(x.value, function (v) { if (!v) { results.push(x); } callback(); }); }, function (err) { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); }; async.reject = doParallel(_reject); async.rejectSeries = doSeries(_reject); var _detect = function (eachfn, arr, iterator, main_callback) { eachfn(arr, function (x, callback) { iterator(x, function (result) { if (result) { main_callback(x); main_callback = function () {}; } else { callback(); } }); }, function (err) { main_callback(); }); }; async.detect = doParallel(_detect); async.detectSeries = doSeries(_detect); async.some = function (arr, iterator, main_callback) { async.each(arr, function (x, callback) { iterator(x, function (v) { if (v) { main_callback(true); main_callback = function () {}; } callback(); }); }, function (err) { main_callback(false); }); }; // any alias async.any = async.some; async.every = function (arr, iterator, main_callback) { async.each(arr, function (x, callback) { iterator(x, function (v) { if (!v) { main_callback(false); main_callback = function () {}; } callback(); }); }, function (err) { main_callback(true); }); }; // all alias async.all = async.every; async.sortBy = function (arr, iterator, callback) { async.map(arr, function (x, callback) { iterator(x, function (err, criteria) { if (err) { callback(err); } else { callback(null, {value: x, criteria: criteria}); } }); }, function (err, results) { if (err) { return callback(err); } else { var fn = function (left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; }; callback(null, _map(results.sort(fn), function (x) { return x.value; })); } }); }; async.auto = function (tasks, callback) { callback = callback || function () {}; var keys = _keys(tasks); if (!keys.length) { return callback(null); } var results = {}; var listeners = []; var addListener = function (fn) { listeners.unshift(fn); }; var removeListener = function (fn) { for (var i = 0; i < listeners.length; i += 1) { if (listeners[i] === fn) { listeners.splice(i, 1); return; } } }; var taskComplete = function () { _each(listeners.slice(0), function (fn) { fn(); }); }; addListener(function () { if (_keys(results).length === keys.length) { callback(null, results); callback = function () {}; } }); _each(keys, function (k) { var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k]; var taskCallback = function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } if (err) { var safeResults = {}; _each(_keys(results), function(rkey) { safeResults[rkey] = results[rkey]; }); safeResults[k] = args; callback(err, safeResults); // stop subsequent errors hitting callback multiple times callback = function () {}; } else { results[k] = args; async.setImmediate(taskComplete); } }; var requires = task.slice(0, Math.abs(task.length - 1)) || []; var ready = function () { return _reduce(requires, function (a, x) { return (a && results.hasOwnProperty(x)); }, true) && !results.hasOwnProperty(k); }; if (ready()) { task[task.length - 1](taskCallback, results); } else { var listener = function () { if (ready()) { removeListener(listener); task[task.length - 1](taskCallback, results); } }; addListener(listener); } }); }; async.waterfall = function (tasks, callback) { callback = callback || function () {}; if (tasks.constructor !== Array) { var err = new Error('First argument to waterfall must be an array of functions'); return callback(err); } if (!tasks.length) { return callback(); } var wrapIterator = function (iterator) { return function (err) { if (err) { callback.apply(null, arguments); callback = function () {}; } else { var args = Array.prototype.slice.call(arguments, 1); var next = iterator.next(); if (next) { args.push(wrapIterator(next)); } else { args.push(callback); } async.setImmediate(function () { iterator.apply(null, args); }); } }; }; wrapIterator(async.iterator(tasks))(); }; var _parallel = function(eachfn, tasks, callback) { callback = callback || function () {}; if (tasks.constructor === Array) { eachfn.map(tasks, function (fn, callback) { if (fn) { fn(function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } callback.call(null, err, args); }); } }, callback); } else { var results = {}; eachfn.each(_keys(tasks), function (k, callback) { tasks[k](function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } results[k] = args; callback(err); }); }, function (err) { callback(err, results); }); } }; async.parallel = function (tasks, callback) { _parallel({ map: async.map, each: async.each }, tasks, callback); }; async.parallelLimit = function(tasks, limit, callback) { _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback); }; async.series = function (tasks, callback) { callback = callback || function () {}; if (tasks.constructor === Array) { async.mapSeries(tasks, function (fn, callback) { if (fn) { fn(function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } callback.call(null, err, args); }); } }, callback); } else { var results = {}; async.eachSeries(_keys(tasks), function (k, callback) { tasks[k](function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } results[k] = args; callback(err); }); }, function (err) { callback(err, results); }); } }; async.iterator = function (tasks) { var makeCallback = function (index) { var fn = function () { if (tasks.length) { tasks[index].apply(null, arguments); } return fn.next(); }; fn.next = function () { return (index < tasks.length - 1) ? makeCallback(index + 1): null; }; return fn; }; return makeCallback(0); }; async.apply = function (fn) { var args = Array.prototype.slice.call(arguments, 1); return function () { return fn.apply( null, args.concat(Array.prototype.slice.call(arguments)) ); }; }; var _concat = function (eachfn, arr, fn, callback) { var r = []; eachfn(arr, function (x, cb) { fn(x, function (err, y) { r = r.concat(y || []); cb(err); }); }, function (err) { callback(err, r); }); }; async.concat = doParallel(_concat); async.concatSeries = doSeries(_concat); async.whilst = function (test, iterator, callback) { if (test()) { iterator(function (err) { if (err) { return callback(err); } async.whilst(test, iterator, callback); }); } else { callback(); } }; async.doWhilst = function (iterator, test, callback) { iterator(function (err) { if (err) { return callback(err); } if (test()) { async.doWhilst(iterator, test, callback); } else { callback(); } }); }; async.until = function (test, iterator, callback) { if (!test()) { iterator(function (err) { if (err) { return callback(err); } async.until(test, iterator, callback); }); } else { callback(); } }; async.doUntil = function (iterator, test, callback) { iterator(function (err) { if (err) { return callback(err); } if (!test()) { async.doUntil(iterator, test, callback); } else { callback(); } }); }; async.queue = function (worker, concurrency) { if (concurrency === undefined) { concurrency = 1; } function _insert(q, data, pos, callback) { if(data.constructor !== Array) { data = [data]; } _each(data, function(task) { var item = { data: task, callback: typeof callback === 'function' ? callback : null }; if (pos) { q.tasks.unshift(item); } else { q.tasks.push(item); } if (q.saturated && q.tasks.length === concurrency) { q.saturated(); } async.setImmediate(q.process); }); } var workers = 0; var q = { tasks: [], concurrency: concurrency, saturated: null, empty: null, drain: null, push: function (data, callback) { _insert(q, data, false, callback); }, unshift: function (data, callback) { _insert(q, data, true, callback); }, process: function () { if (workers < q.concurrency && q.tasks.length) { var task = q.tasks.shift(); if (q.empty && q.tasks.length === 0) { q.empty(); } workers += 1; var next = function () { workers -= 1; if (task.callback) { task.callback.apply(task, arguments); } if (q.drain && q.tasks.length + workers === 0) { q.drain(); } q.process(); }; var cb = only_once(next); worker(task.data, cb); } }, length: function () { return q.tasks.length; }, running: function () { return workers; } }; return q; }; async.cargo = function (worker, payload) { var working = false, tasks = []; var cargo = { tasks: tasks, payload: payload, saturated: null, empty: null, drain: null, push: function (data, callback) { if(data.constructor !== Array) { data = [data]; } _each(data, function(task) { tasks.push({ data: task, callback: typeof callback === 'function' ? callback : null }); if (cargo.saturated && tasks.length === payload) { cargo.saturated(); } }); async.setImmediate(cargo.process); }, process: function process() { if (working) return; if (tasks.length === 0) { if(cargo.drain) cargo.drain(); return; } var ts = typeof payload === 'number' ? tasks.splice(0, payload) : tasks.splice(0); var ds = _map(ts, function (task) { return task.data; }); if(cargo.empty) cargo.empty(); working = true; worker(ds, function () { working = false; var args = arguments; _each(ts, function (data) { if (data.callback) { data.callback.apply(null, args); } }); process(); }); }, length: function () { return tasks.length; }, running: function () { return working; } }; return cargo; }; var _console_fn = function (name) { return function (fn) { var args = Array.prototype.slice.call(arguments, 1); fn.apply(null, args.concat([function (err) { var args = Array.prototype.slice.call(arguments, 1); if (typeof console !== 'undefined') { if (err) { if (console.error) { console.error(err); } } else if (console[name]) { _each(args, function (x) { console[name](x); }); } } }])); }; }; async.log = _console_fn('log'); async.dir = _console_fn('dir'); /*async.info = _console_fn('info'); async.warn = _console_fn('warn'); async.error = _console_fn('error');*/ async.memoize = function (fn, hasher) { var memo = {}; var queues = {}; hasher = hasher || function (x) { return x; }; var memoized = function () { var args = Array.prototype.slice.call(arguments); var callback = args.pop(); var key = hasher.apply(null, args); if (key in memo) { callback.apply(null, memo[key]); } else if (key in queues) { queues[key].push(callback); } else { queues[key] = [callback]; fn.apply(null, args.concat([function () { memo[key] = arguments; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, arguments); } }])); } }; memoized.memo = memo; memoized.unmemoized = fn; return memoized; }; async.unmemoize = function (fn) { return function () { return (fn.unmemoized || fn).apply(null, arguments); }; }; async.times = function (count, iterator, callback) { var counter = []; for (var i = 0; i < count; i++) { counter.push(i); } return async.map(counter, iterator, callback); }; async.timesSeries = function (count, iterator, callback) { var counter = []; for (var i = 0; i < count; i++) { counter.push(i); } return async.mapSeries(counter, iterator, callback); }; async.compose = function (/* functions... */) { var fns = Array.prototype.reverse.call(arguments); return function () { var that = this; var args = Array.prototype.slice.call(arguments); var callback = args.pop(); async.reduce(fns, args, function (newargs, fn, cb) { fn.apply(that, newargs.concat([function () { var err = arguments[0]; var nextargs = Array.prototype.slice.call(arguments, 1); cb(err, nextargs); }])) }, function (err, results) { callback.apply(that, [err].concat(results)); }); }; }; var _applyEach = function (eachfn, fns /*args...*/) { var go = function () { var that = this; var args = Array.prototype.slice.call(arguments); var callback = args.pop(); return eachfn(fns, function (fn, cb) { fn.apply(that, args.concat([cb])); }, callback); }; if (arguments.length > 2) { var args = Array.prototype.slice.call(arguments, 2); return go.apply(this, args); } else { return go; } }; async.applyEach = doParallel(_applyEach); async.applyEachSeries = doSeries(_applyEach); async.forever = function (fn, callback) { function next(err) { if (err) { if (callback) { return callback(err); } throw err; } fn(next); } next(); }; // AMD / RequireJS if (typeof define !== 'undefined' && define.amd) { define([], function () { return async; }); } // Node.js else if (typeof module !== 'undefined' && module.exports) { module.exports = async; } // included directly via <script> tag else { root.async = async; } }()); /*! * Platform.js v1.0.0 <http://mths.be/platform> * Copyright 2010-2012 John-David Dalton <http://allyoucanleet.com/> * Available under MIT license <http://mths.be/mit> */ ;(function(window) { 'use strict'; /** Backup possible window/global object */ var oldWin = window; /** Detect free variable `exports` */ var freeExports = typeof exports == 'object' && exports; /** Detect free variable `global` */ var freeGlobal = typeof global == 'object' && global && (global == global.global ? (window = global) : global); /** Opera regexp */ var reOpera = /Opera/; /** Used to resolve a value's internal [[Class]] */ var toString = {}.toString; /** Detect Java environment */ var java = /Java/.test(getClassOf(window.java)) && window.java; /** A character to represent alpha */ var alpha = java ? 'a' : '\u03b1'; /** A character to represent beta */ var beta = java ? 'b' : '\u03b2'; /** Browser document object */ var doc = window.document || {}; /** Used to check for own properties of an object */ var hasOwnProperty = {}.hasOwnProperty; /** Browser navigator object */ var nav = window.navigator || {}; /** * Detect Opera browser * http://www.howtocreate.co.uk/operaStuff/operaObject.html * http://dev.opera.com/articles/view/opera-mini-web-content-authoring-guidelines/#operamini */ var opera = window.operamini || window.opera; /** Opera [[Class]] */ var operaClass = reOpera.test(operaClass = getClassOf(opera)) ? operaClass : (opera = null); /** Possible global object */ var thisBinding = this; /** Browser user agent string */ var userAgent = nav.userAgent || ''; /*--------------------------------------------------------------------------*/ /** * Capitalizes a string value. * * @private * @param {String} string The string to capitalize. * @returns {String} The capitalized string. */ function capitalize(string) { string = String(string); return string.charAt(0).toUpperCase() + string.slice(1); } /** * An iteration utility for arrays and objects. * * @private * @param {Array|Object} object The object to iterate over. * @param {Function} callback The function called per iteration. */ function each(object, callback) { var index = -1, length = object.length; if (length == length >>> 0) { while (++index < length) { callback(object[index], index, object); } } else { forOwn(object, callback); } } /** * Trim and conditionally capitalize string values. * * @private * @param {String} string The string to format. * @returns {String} The formatted string. */ function format(string) { string = trim(string); return /^(?:webOS|i(?:OS|P))/.test(string) ? string : capitalize(string); } /** * Iterates over an object's own properties, executing the `callback` for each. * * @private * @param {Object} object The object to iterate over. * @param {Function} callback The function executed per own property. */ function forOwn(object, callback) { for (var key in object) { hasKey(object, key) && callback(object[key], key, object); } } /** * Gets the internal [[Class]] of a value. * * @private * @param {Mixed} value The value. * @returns {String} The [[Class]]. */ function getClassOf(value) { return value == null ? capitalize(value) : toString.call(value).slice(8, -1); } /** * Checks if an object has the specified key as a direct property. * * @private * @param {Object} object The object to check. * @param {String} key The key to check for. * @returns {Boolean} Returns `true` if key is a direct property, else `false`. */ function hasKey() { // lazy define for others (not as accurate) hasKey = function(object, key) { var parent = object != null && (object.constructor || Object).prototype; return !!parent && key in Object(object) && !(key in parent && object[key] === parent[key]); }; // for modern browsers if (getClassOf(hasOwnProperty) == 'Function') { hasKey = function(object, key) { return object != null && hasOwnProperty.call(object, key); }; } // for Safari 2 else if ({}.__proto__ == Object.prototype) { hasKey = function(object, key) { var result = false; if (object != null) { object = Object(object); object.__proto__ = [object.__proto__, object.__proto__ = null, result = key in object][0]; } return result; }; } return hasKey.apply(this, arguments); } /** * Host objects can return type values that are different from their actual * data type. The objects we are concerned with usually return non-primitive * types of object, function, or unknown. * * @private * @param {Mixed} object The owner of the property. * @param {String} property The property to check. * @returns {Boolean} Returns `true` if the property value is a non-primitive, else `false`. */ function isHostType(object, property) { var type = object != null ? typeof object[property] : 'number'; return !/^(?:boolean|number|string|undefined)$/.test(type) && (type == 'object' ? !!object[property] : true); } /** * Prepares a string for use in a RegExp constructor by making hyphens and * spaces optional. * * @private * @param {String} string The string to qualify. * @returns {String} The qualified string. */ function qualify(string) { return String(string).replace(/([ -])(?!$)/g, '$1?'); } /** * A bare-bones` Array#reduce` like utility function. * * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function called per iteration. * @param {Mixed} accumulator Initial value of the accumulator. * @returns {Mixed} The accumulator. */ function reduce(array, callback) { var accumulator = null; each(array, function(value, index) { accumulator = callback(accumulator, value, index, array); }); return accumulator; } /** * Removes leading and trailing whitespace from a string. * * @private * @param {String} string The string to trim. * @returns {String} The trimmed string. */ function trim(string) { return String(string).replace(/^ +| +$/g, ''); } /*--------------------------------------------------------------------------*/ /** * Creates a new platform object. * * @memberOf platform * @param {String} [ua = navigator.userAgent] The user agent string. * @returns {Object} A platform object. */ function parse(ua) { ua || (ua = userAgent); /** Temporary variable used over the script's lifetime */ var data; /** The CPU architecture */ var arch = ua; /** Platform description array */ var description = []; /** Platform alpha/beta indicator */ var prerelease = null; /** A flag to indicate that environment features should be used to resolve the platform */ var useFeatures = ua == userAgent; /** The browser/environment version */ var version = useFeatures && opera && typeof opera.version == 'function' && opera.version(); /* Detectable layout engines (order is important) */ var layout = getLayout([ { 'label': 'WebKit', 'pattern': 'AppleWebKit' }, 'iCab', 'Presto', 'NetFront', 'Tasman', 'Trident', 'KHTML', 'Gecko' ]); /* Detectable browser names (order is important) */ var name = getName([ 'Adobe AIR', 'Arora', 'Avant Browser', 'Camino', 'Epiphany', 'Fennec', 'Flock', 'Galeon', 'GreenBrowser', 'iCab', 'Iceweasel', 'Iron', 'K-Meleon', 'Konqueror', 'Lunascape', 'Maxthon', 'Midori', 'Nook Browser', 'PhantomJS', 'Raven', 'Rekonq', 'RockMelt', 'SeaMonkey', { 'label': 'Silk', 'pattern': '(?:Cloud9|Silk-Accelerated)' }, 'Sleipnir', 'SlimBrowser', 'Sunrise', 'Swiftfox', 'WebPositive', 'Opera Mini', 'Opera', 'Chrome', { 'label': 'Chrome Mobile', 'pattern': '(?:CriOS|CrMo)' }, { 'label': 'Firefox', 'pattern': '(?:Firefox|Minefield)' }, { 'label': 'IE', 'pattern': 'MSIE' }, 'Safari' ]); /* Detectable products (order is important) */ var product = getProduct([ 'BlackBerry', { 'label': 'Galaxy S', 'pattern': 'GT-I9000' }, { 'label': 'Galaxy S2', 'pattern': 'GT-I9100' }, 'Google TV', 'iPad', 'iPod', 'iPhone', 'Kindle', { 'label': 'Kindle Fire', 'pattern': '(?:Cloud9|Silk-Accelerated)' }, 'Nook', 'PlayBook', 'PlayStation Vita', 'TouchPad', 'Transformer', 'Xoom' ]); /* Detectable manufacturers */ var manufacturer = getManufacturer({ 'Apple': { 'iPad': 1, 'iPhone': 1, 'iPod': 1 }, 'Amazon': { 'Kindle': 1, 'Kindle Fire': 1 }, 'Asus': { 'Transformer': 1 }, 'Barnes & Noble': { 'Nook': 1 }, 'BlackBerry': { 'PlayBook': 1 }, 'Google': { 'Google TV': 1 }, 'HP': { 'TouchPad': 1 }, 'LG': { }, 'Motorola': { 'Xoom': 1 }, 'Nokia': { }, 'Samsung': { 'Galaxy S': 1, 'Galaxy S2': 1 }, 'Sony': { 'PlayStation Vita': 1 } }); /* Detectable OSes (order is important) */ var os = getOS([ 'Android', 'CentOS', 'Debian', 'Fedora', 'FreeBSD', 'Gentoo', 'Haiku', 'Kubuntu', 'Linux Mint', 'Red Hat', 'SuSE', 'Ubuntu', 'Xubuntu', 'Cygwin', 'Symbian OS', 'hpwOS', 'webOS ', 'webOS', 'Tablet OS', 'Linux', 'Mac OS X', 'Macintosh', 'Mac', 'Windows 98;', 'Windows ' ]); /*------------------------------------------------------------------------*/ /** * Picks the layout engine from an array of guesses. * * @private * @param {Array} guesses An array of guesses. * @returns {String|Null} The detected layout engine. */ function getLayout(guesses) { return reduce(guesses, function(result, guess) { return result || RegExp('\\b' + ( guess.pattern || qualify(guess) ) + '\\b', 'i').exec(ua) && (guess.label || guess); }); } /** * Picks the manufacturer from an array of guesses. * * @private * @param {Array} guesses An array of guesses. * @returns {String|Null} The detected manufacturer. */ function getManufacturer(guesses) { return reduce(guesses, function(result, value, key) { // lookup the manufacturer by product or scan the UA for the manufacturer return result || ( value[product] || value[0/*Opera 9.25 fix*/, /^[a-z]+(?: +[a-z]+\b)*/i.exec(product)] || RegExp('\\b' + (key.pattern || qualify(key)) + '(?:\\b|\\w*\\d)', 'i').exec(ua) ) && (key.label || key); }); } /** * Picks the browser name from an array of guesses. * * @private * @param {Array} guesses An array of guesses. * @returns {String|Null} The detected browser name. */ function getName(guesses) { return reduce(guesses, function(result, guess) { return result || RegExp('\\b' + ( guess.pattern || qualify(guess) ) + '\\b', 'i').exec(ua) && (guess.label || guess); }); } /** * Picks the OS name from an array of guesses. * * @private * @param {Array} guesses An array of guesses. * @returns {String|Null} The detected OS name. */ function getOS(guesses) { return reduce(guesses, function(result, guess) { var pattern = guess.pattern || qualify(guess); if (!result && (result = RegExp('\\b' + pattern + '(?:/[\\d.]+|[ \\w.]*)', 'i').exec(ua))) { // platform tokens defined at // http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx // http://web.archive.org/web/20081122053950/http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx data = { '6.2': '8', '6.1': 'Server 2008 R2 / 7', '6.0': 'Server 2008 / Vista', '5.2': 'Server 2003 / XP 64-bit', '5.1': 'XP', '5.01': '2000 SP1', '5.0': '2000', '4.0': 'NT', '4.90': 'ME' }; // detect Windows version from platform tokens if (/^Win/i.test(result) && (data = data[0/*Opera 9.25 fix*/, /[\d.]+$/.exec(result)])) { result = 'Windows ' + data; } // correct character case and cleanup result = format(String(result) .replace(RegExp(pattern, 'i'), guess.label || guess) .replace(/ ce$/i, ' CE') .replace(/hpw/i, 'web') .replace(/Macintosh/, 'Mac OS') .replace(/_PowerPC/i, ' OS') .replace(/(OS X) [^ \d]+/i, '$1') .replace(/\/(\d)/, ' $1') .replace(/_/g, '.') .replace(/(?: BePC|[ .]*fc[ \d.]+)$/i, '') .replace(/x86\.64/gi, 'x86_64') .split(' on ')[0]); } return result; }); } /** * Picks the product name from an array of guesses. * * @private * @param {Array} guesses An array of guesses. * @returns {String|Null} The detected product name. */ function getProduct(guesses) { return reduce(guesses, function(result, guess) { var pattern = guess.pattern || qualify(guess); if (!result && (result = RegExp('\\b' + pattern + ' *\\d+[.\\w_]*', 'i').exec(ua) || RegExp('\\b' + pattern + '(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)', 'i').exec(ua) )) { // split by forward slash and append product version if needed if ((result = String(guess.label || result).split('/'))[1] && !/[\d.]+/.test(result[0])) { result[0] += ' ' + result[1]; } // correct character case and cleanup guess = guess.label || guess; result = format(result[0] .replace(RegExp(pattern, 'i'), guess) .replace(RegExp('; *(?:' + guess + '[_-])?', 'i'), ' ') .replace(RegExp('(' + guess + ')(\\w)', 'i'), '$1 $2')); } return result; }); } /** * Resolves the version using an array of UA patterns. * * @private * @param {Array} patterns An array of UA patterns. * @returns {String|Null} The detected version. */ function getVersion(patterns) { return reduce(patterns, function(result, pattern) { return result || (RegExp(pattern + '(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)', 'i').exec(ua) || 0)[1] || null; }); } /*------------------------------------------------------------------------*/ /** * Returns `platform.description` when the platform object is coerced to a string. * * @name toString * @memberOf platform * @returns {String} Returns `platform.description` if available, else an empty string. */ function toStringPlatform() { return this.description || ''; } /*------------------------------------------------------------------------*/ // convert layout to an array so we can add extra details layout && (layout = [layout]); // detect product names that contain their manufacturer's name if (manufacturer && !product) { product = getProduct([manufacturer]); } // clean up Google TV if ((data = /Google TV/.exec(product))) { product = data[0]; } // detect simulators if (/\bSimulator\b/i.test(ua)) { product = (product ? product + ' ' : '') + 'Simulator'; } // detect iOS if (/^iP/.test(product)) { name || (name = 'Safari'); os = 'iOS' + ((data = / OS ([\d_]+)/i.exec(ua)) ? ' ' + data[1].replace(/_/g, '.') : ''); } // detect Kubuntu else if (name == 'Konqueror' && !/buntu/i.test(os)) { os = 'Kubuntu'; } // detect Android browsers else if (manufacturer && manufacturer != 'Google' && /Chrome|Vita/.test(name + ';' + product)) { name = 'Android Browser'; os = /Android/.test(os) ? os : 'Android'; } // detect false positives for Firefox/Safari else if (!name || (data = !/\bMinefield\b/i.test(ua) && /Firefox|Safari/.exec(name))) { // escape the `/` for Firefox 1 if (name && !product && /[\/,]|^[^(]+?\)/.test(ua.slice(ua.indexOf(data + '/') + 8))) { // clear name of false positives name = null; } // reassign a generic name if ((data = product || manufacturer || os) && (product || manufacturer || /Android|Symbian OS|Tablet OS|webOS/.test(os))) { name = /[a-z]+(?: Hat)?/i.exec(/Android/.test(os) ? os : data) + ' Browser'; } } // detect non-Opera versions (order is important) if (!version) { version = getVersion([ '(?:Cloud9|CriOS|CrMo|Opera ?Mini|Raven|Silk(?!/[\\d.]+$))', 'Version', qualify(name), '(?:Firefox|Minefield|NetFront)' ]); } // detect stubborn layout engines if (layout == 'iCab' && parseFloat(version) > 3) { layout = ['WebKit']; } else if (data = /Opera/.test(name) && 'Presto' || /\b(?:Midori|Nook|Safari)\b/i.test(ua) && 'WebKit' || !layout && /\bMSIE\b/i.test(ua) && (/^Mac/.test(os) ? 'Tasman' : 'Trident')) { layout = [data]; } // leverage environment features if (useFeatures) { // detect server-side environments // Rhino has a global function while others have a global object if (isHostType(window, 'global')) { if (java) { data = java.lang.System; arch = data.getProperty('os.arch'); os = os || data.getProperty('os.name') + ' ' + data.getProperty('os.version'); } if (typeof exports == 'object' && exports) { // if `thisBinding` is the [ModuleScope] if (thisBinding == oldWin && typeof system == 'object' && (data = [system])[0]) { os || (os = data[0].os || null); try { data[1] = require('ringo/engine').version; version = data[1].join('.'); name = 'RingoJS'; } catch(e) { if (data[0].global == freeGlobal) { name = 'Narwhal'; } } } else if (typeof process == 'object' && (data = process)) { name = 'Node.js'; arch = data.arch; os = data.platform; version = /[\d.]+/.exec(data.version)[0]; } } else if (getClassOf(window.environment) == 'Environment') { name = 'Rhino'; } } // detect Adobe AIR else if (getClassOf(data = window.runtime) == 'ScriptBridgingProxyObject') { name = 'Adobe AIR'; os = data.flash.system.Capabilities.os; } // detect PhantomJS else if (getClassOf(data = window.phantom) == 'RuntimeObject') { name = 'PhantomJS'; version = (data = data.version || null) && (data.major + '.' + data.minor + '.' + data.patch); } // detect IE compatibility modes else if (typeof doc.documentMode == 'number' && (data = /\bTrident\/(\d+)/i.exec(ua))) { // we're in compatibility mode when the Trident version + 4 doesn't // equal the document mode version = [version, doc.documentMode]; if ((data = +data[1] + 4) != version[1]) { description.push('IE ' + version[1] + ' mode'); layout[1] = ''; version[1] = data; } version = name == 'IE' ? String(version[1].toFixed(1)) : version[0]; } os = os && format(os); } // detect prerelease phases if (version && (data = /(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(version) || /(?:alpha|beta)(?: ?\d)?/i.exec(ua + ';' + (useFeatures && nav.appMinorVersion)) || /\bMinefield\b/i.test(ua) && 'a')) { prerelease = /b/i.test(data) ? 'beta' : 'alpha'; version = version.replace(RegExp(data + '\\+?$'), '') + (prerelease == 'beta' ? beta : alpha) + (/\d+\+?/.exec(data) || ''); } // rename code name "Fennec" if (name == 'Fennec') { name = 'Firefox Mobile'; } // obscure Maxthon's unreliable version else if (name == 'Maxthon' && version) { version = version.replace(/\.[\d.]+/, '.x'); } // detect Silk desktop/accelerated modes else if (name == 'Silk') { if (!/Mobi/i.test(ua)) { os = 'Android'; description.unshift('desktop mode'); } if (/Accelerated *= *true/i.test(ua)) { description.unshift('accelerated'); } } // detect Windows Phone desktop mode else if (name == 'IE' && (data = (/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(ua) || 0)[1])) { name += ' Mobile'; os = 'Windows Phone OS ' + data + '.x'; description.unshift('desktop mode'); } // add mobile postfix else if ((name == 'IE' || name && !product && !/Browser|Mobi/.test(name)) && (os == 'Windows CE' || /Mobi/i.test(ua))) { name += ' Mobile'; } // detect IE platform preview else if (name == 'IE' && useFeatures && typeof external == 'object' && !external) { description.unshift('platform preview'); } // detect BlackBerry OS version // http://docs.blackberry.com/en/developers/deliverables/18169/HTTP_headers_sent_by_BB_Browser_1234911_11.jsp else if (/BlackBerry/.test(product) && (data = (RegExp(product.replace(/ +/g, ' *') + '/([.\\d]+)', 'i').exec(ua) || 0)[1] || version)) { os = 'Device Software ' + data; version = null; } // detect Opera identifying/masking itself as another browser // http://www.opera.com/support/kb/view/843/ else if (this != forOwn && ( (useFeatures && opera) || (/Opera/.test(name) && /\b(?:MSIE|Firefox)\b/i.test(ua)) || (name == 'Firefox' && /OS X (?:\d+\.){2,}/.test(os)) || (name == 'IE' && ( (os && !/^Win/.test(os) && version > 5.5) || /Windows XP/.test(os) && version > 8 || version == 8 && !/Trident/.test(ua) )) ) && !reOpera.test(data = parse.call(forOwn, ua.replace(reOpera, '') + ';')) && data.name) { // when "indentifying", the UA contains both Opera and the other browser's name data = 'ing as ' + data.name + ((data = data.version) ? ' ' + data : ''); if (reOpera.test(name)) { if (/IE/.test(data) && os == 'Mac OS') { os = null; } data = 'identify' + data; } // when "masking", the UA contains only the other browser's name else { data = 'mask' + data; if (operaClass) { name = format(operaClass.replace(/([a-z])([A-Z])/g, '$1 $2')); } else { name = 'Opera'; } if (/IE/.test(data)) { os = null; } if (!useFeatures) { version = null; } } layout = ['Presto']; description.push(data); } // detect WebKit Nightly and approximate Chrome/Safari versions if ((data = (/\bAppleWebKit\/([\d.]+\+?)/i.exec(ua) || 0)[1])) { // correct build for numeric comparison // (e.g. "532.5" becomes "532.05") data = [parseFloat(data.replace(/\.(\d)$/, '.0$1')), data]; // nightly builds are postfixed with a `+` if (name == 'Safari' && data[1].slice(-1) == '+') { name = 'WebKit Nightly'; prerelease = 'alpha'; version = data[1].slice(0, -1); } // clear incorrect browser versions else if (version == data[1] || version == (/\bSafari\/([\d.]+\+?)/i.exec(ua) || 0)[1]) { version = null; } // use the full Chrome version when available data = [data[0], (/\bChrome\/([\d.]+)/i.exec(ua) || 0)[1]]; // detect JavaScriptCore // http://stackoverflow.com/questions/6768474/how-can-i-detect-which-javascript-engine-v8-or-jsc-is-used-at-runtime-in-androi if (!useFeatures || (/internal|\n/i.test(toString.toString()) && !data[1])) { layout[1] = 'like Safari'; data = (data = data[0], data < 400 ? 1 : data < 500 ? 2 : data < 526 ? 3 : data < 533 ? 4 : data < 534 ? '4+' : data < 535 ? 5 : '5'); } else { layout[1] = 'like Chrome'; data = data[1] || (data = data[0], data < 530 ? 1 : data < 532 ? 2 : data < 532.05 ? 3 : data < 533 ? 4 : data < 534.03 ? 5 : data < 534.07 ? 6 : data < 534.10 ? 7 : data < 534.13 ? 8 : data < 534.16 ? 9 : data < 534.24 ? 10 : data < 534.30 ? 11 : data < 535.01 ? 12 : data < 535.02 ? '13+' : data < 535.07 ? 15 : data < 535.11 ? 16 : data < 535.19 ? 17 : data < 536.05 ? 18 : data < 536.10 ? 19 : data < 537.01 ? 20 : '21'); } // add the postfix of ".x" or "+" for approximate versions layout[1] += ' ' + (data += typeof data == 'number' ? '.x' : /[.+]/.test(data) ? '' : '+'); // obscure version for some Safari 1-2 releases if (name == 'Safari' && (!version || parseInt(version) > 45)) { version = data; } } // detect Opera desktop modes if (name == 'Opera' && (data = /(?:zbov|zvav)$/.exec(os))) { name += ' '; description.unshift('desktop mode'); if (data == 'zvav') { name += 'Mini'; version = null; } else { name += 'Mobile'; } } // detect Chrome desktop mode else if (name == 'Safari' && /Chrome/.exec(layout[1])) { description.unshift('desktop mode'); name = 'Chrome Mobile'; version = null; if (/Mac OS X/.test(os)) { manufacturer = 'Apple'; os = 'iOS 4.3+'; } else { os = null; } } // strip incorrect OS versions if (version && version.indexOf(data = /[\d.]+$/.exec(os)) == 0 && ua.indexOf('/' + data + '-') > -1) { os = trim(os.replace(data, '')); } // add layout engine if (layout && !/Avant|Nook/.test(name) && ( /Browser|Lunascape|Maxthon/.test(name) || /^(?:Adobe|Arora|Midori|Phantom|Rekonq|Rock|Sleipnir|Web)/.test(name) && layout[1])) { // don't add layout details to description if they are falsey (data = layout[layout.length - 1]) && description.push(data); } // combine contextual information if (description.length) { description = ['(' + description.join('; ') + ')']; } // append manufacturer if (manufacturer && product && product.indexOf(manufacturer) < 0) { description.push('on ' + manufacturer); } // append product if (product) { description.push((/^on /.test(description[description.length -1]) ? '' : 'on ') + product); } // parse OS into an object if (os) { data = / ([\d.+]+)$/.exec(os); os = { 'architecture': 32, 'family': data ? os.replace(data[0], '') : os, 'version': data ? data[1] : null, 'toString': function() { var version = this.version; return this.family + (version ? ' ' + version : '') + (this.architecture == 64 ? ' 64-bit' : ''); } }; } // add browser/OS architecture if ((data = / (?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(arch)) && !/\bi686\b/i.test(arch)) { if (os) { os.architecture = 64; os.family = os.family.replace(data, ''); } if (name && (/WOW64/i.test(ua) || (useFeatures && /\w(?:86|32)$/.test(nav.cpuClass || nav.platform)))) { description.unshift('32-bit'); } } ua || (ua = null); /*------------------------------------------------------------------------*/ /** * The platform object. * * @name platform * @type Object */ return { /** * The browser/environment version. * * @memberOf platform * @type String|Null */ 'version': name && version && (description.unshift(version), version), /** * The name of the browser/environment. * * @memberOf platform * @type String|Null */ 'name': name && (description.unshift(name), name), /** * The name of the operating system. * * @memberOf platform * @type Object */ 'os': os ? (name && !(os == String(os).split(' ')[0] && (os == name.split(' ')[0] || product)) && description.push(product ? '(' + os + ')' : 'on ' + os), os) : { /** * The CPU architecture the OS is built for. * * @memberOf platform.os * @type String|Null */ 'architecture': null, /** * The family of the OS. * * @memberOf platform.os * @type String|Null */ 'family': null, /** * The version of the OS. * * @memberOf platform.os * @type String|Null */ 'version': null, /** * Returns the OS string. * * @memberOf platform.os * @returns {String} The OS string. */ 'toString': function() { return 'null'; } }, /** * The platform description. * * @memberOf platform * @type String|Null */ 'description': description.length ? description.join(' ') : ua, /** * The name of the browser layout engine. * * @memberOf platform * @type String|Null */ 'layout': layout && layout[0], /** * The name of the product's manufacturer. * * @memberOf platform * @type String|Null */ 'manufacturer': manufacturer, /** * The alpha/beta release indicator. * * @memberOf platform * @type String|Null */ 'prerelease': prerelease, /** * The name of the product hosting the browser. * * @memberOf platform * @type String|Null */ 'product': product, /** * The browser's user agent string. * * @memberOf platform * @type String|Null */ 'ua': ua, // parses a user agent string into a platform object 'parse': parse, // returns the platform description 'toString': toStringPlatform }; } /*--------------------------------------------------------------------------*/ // expose platform // some AMD build optimizers, like r.js, check for specific condition patterns like the following: if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { // define as an anonymous module so, through path mapping, it can be aliased define(function() { return parse(); }); } // check for `exports` after `define` in case a build optimizer adds an `exports` object else if (freeExports) { // in Narwhal, Node.js, or RingoJS forOwn(parse(), function(value, key) { freeExports[key] = value; }); } // in a browser or Rhino else { // use square bracket notation so Closure Compiler won't munge `platform` // http://code.google.com/closure/compiler/docs/api-tutorial3.html#export window['platform'] = parse(); } }(this)); var buster = this.buster = this.buster || {}; buster._ = buster.lodash = this._; buster.when = this.when; buster.async = this.async; buster.platform = this.platform; this.define = (function () { function resolve(ns) { var pieces = ns.replace(/^buster-test\//, "").replace(/^buster-/, "").replace(/-(.)/g, function (m, l) { return l.toUpperCase(); }).split("/"); return { property: pieces.pop(), object: buster._.reduce(pieces, function (ctx, name) { if (!ctx[name]) { ctx[name] = {}; } return ctx[name]; }, buster) }; } return function (id, dependencies, factory) { if (arguments.length === 2) { factory = dependencies; dependencies = []; } var deps = [], dep; for (var j, i = 0, l = dependencies.length; i < l; ++i) { dep = resolve(dependencies[i]); if (!dep.object[dep.property]) { throw new Error(id + " depends on unknown module " + dep.property); } deps.push(dep.object[dep.property]); } dep = resolve(id); dep.object[dep.property] = factory.apply(this, deps); }; }()); this.define.amd = true; ((typeof define === "function" && define.amd && function (m) { define("bane", m); }) || (typeof module === "object" && function (m) { module.exports = m(); }) || function (m) { this.bane = m(); } )(function () { "use strict"; var slice = Array.prototype.slice; function handleError(event, error, errbacks) { var i, l = errbacks.length; if (l > 0) { for (i = 0; i < l; ++i) { errbacks[i](event, error); } return; } setTimeout(function () { error.message = event + " listener threw error: " + error.message; throw error; }, 0); } function assertFunction(fn) { if (typeof fn !== "function") { throw new TypeError("Listener is not function"); } return fn; } function supervisors(object) { if (!object.supervisors) { object.supervisors = []; } return object.supervisors; } function listeners(object, event) { if (!object.listeners) { object.listeners = {}; } if (event && !object.listeners[event]) { object.listeners[event] = []; } return event ? object.listeners[event] : object.listeners; } function errbacks(object) { if (!object.errbacks) { object.errbacks = []; } return object.errbacks; } /** * @signature var emitter = bane.createEmitter([object]); * * Create a new event emitter. If an object is passed, it will be modified * by adding the event emitter methods (see below). */ function createEventEmitter(object) { object = object || {}; function notifyListener(event, listener, args) { try { listener.listener.apply(listener.thisp || object, args); } catch (e) { handleError(event, e, errbacks(object)); } } object.on = function (event, listener, thisp) { if (typeof event === "function") { return supervisors(this).push({ listener: event, thisp: listener }); } listeners(this, event).push({ listener: assertFunction(listener), thisp: thisp }); }; object.off = function (event, listener) { var fns, events, i, l; if (!event) { fns = supervisors(this); fns.splice(0, fns.length); events = listeners(this); for (i in events) { if (events.hasOwnProperty(i)) { fns = listeners(this, i); fns.splice(0, fns.length); } } fns = errbacks(this); fns.splice(0, fns.length); return; } if (typeof event === "function") { fns = supervisors(this); listener = event; } else { fns = listeners(this, event); } if (!listener) { fns.splice(0, fns.length); return; } for (i = 0, l = fns.length; i < l; ++i) { if (fns[i].listener === listener) { fns.splice(i, 1); return; } } }; object.once = function (event, listener, thisp) { var wrapper = function () { object.off(event, wrapper); listener.apply(this, arguments); }; object.on(event, wrapper, thisp); }; object.bind = function (object, events) { var prop, i, l; if (!events) { for (prop in object) { if (typeof object[prop] === "function") { this.on(prop, object[prop], object); } } } else { for (i = 0, l = events.length; i < l; ++i) { if (typeof object[events[i]] === "function") { this.on(events[i], object[events[i]], object); } else { throw new Error("No such method " + events[i]); } } } return object; }; object.emit = function (event) { var toNotify = supervisors(this); var args = slice.call(arguments), i, l; for (i = 0, l = toNotify.length; i < l; ++i) { notifyListener(event, toNotify[i], args); } toNotify = listeners(this, event).slice(); args = slice.call(arguments, 1); for (i = 0, l = toNotify.length; i < l; ++i) { notifyListener(event, toNotify[i], args); } }; object.errback = function (listener) { if (!this.errbacks) { this.errbacks = []; } this.errbacks.push(assertFunction(listener)); }; return object; } return { createEventEmitter: createEventEmitter }; }); ((typeof define === "function" && define.amd && function (m) { define("samsam", m); }) || (typeof module === "object" && function (m) { module.exports = m(); }) || // Node function (m) { this.samsam = m(); } // Browser globals )(function () { var o = Object.prototype; var div = typeof document !== "undefined" && document.createElement("div"); function isNaN(value) { // Unlike global isNaN, this avoids type coercion // typeof check avoids IE host object issues, hat tip to // lodash var val = value; // JsLint thinks value !== value is "weird" return typeof value === "number" && value !== val; } function getClass(value) { // Returns the internal [[Class]] by calling Object.prototype.toString // with the provided value as this. Return value is a string, naming the // internal class, e.g. "Array" return o.toString.call(value).split(/[ \]]/)[1]; } /** * @name samsam.isArguments * @param Object object * * Returns ``true`` if ``object`` is an ``arguments`` object, * ``false`` otherwise. */ function isArguments(object) { if (typeof object !== "object" || typeof object.length !== "number" || getClass(object) === "Array") { return false; } if (typeof object.callee == "function") { return true; } try { object[object.length] = 6; delete object[object.length]; } catch (e) { return true; } return false; } /** * @name samsam.isElement * @param Object object * * Returns ``true`` if ``object`` is a DOM element node. Unlike * Underscore.js/lodash, this function will return ``false`` if ``object`` * is an *element-like* object, i.e. a regular object with a ``nodeType`` * property that holds the value ``1``. */ function isElement(object) { if (!object || object.nodeType !== 1 || !div) { return false; } try { object.appendChild(div); object.removeChild(div); } catch (e) { return false; } return true; } /** * @name samsam.keys * @param Object object * * Return an array of own property names. */ function keys(object) { var ks = [], prop; for (prop in object) { if (o.hasOwnProperty.call(object, prop)) { ks.push(prop); } } return ks; } /** * @name samsam.isDate * @param Object value * * Returns true if the object is a ``Date``, or *date-like*. Duck typing * of date objects work by checking that the object has a ``getTime`` * function whose return value equals the return value from the object's * ``valueOf``. */ function isDate(value) { return typeof value.getTime == "function" && value.getTime() == value.valueOf(); } /** * @name samsam.isNegZero * @param Object value * * Returns ``true`` if ``value`` is ``-0``. */ function isNegZero(value) { return value === 0 && 1 / value === -Infinity; } /** * @name samsam.equal * @param Object obj1 * @param Object obj2 * * Returns ``true`` if two objects are strictly equal. Compared to * ``===`` there are two exceptions: * * - NaN is considered equal to NaN * - -0 and +0 are not considered equal */ function identical(obj1, obj2) { if (obj1 === obj2 || (isNaN(obj1) && isNaN(obj2))) { return obj1 !== 0 || isNegZero(obj1) === isNegZero(obj2); } } /** * @name samsam.deepEqual * @param Object obj1 * @param Object obj2 * * Deep equal comparison. Two values are "deep equal" if: * * - They are equal, according to samsam.identical * - They are both date objects representing the same time * - They are both arrays containing elements that are all deepEqual * - They are objects with the same set of properties, and each property * in ``obj1`` is deepEqual to the corresponding property in ``obj2`` * * Supports cyclic objects. */ function deepEqualCyclic(obj1, obj2) { // used for cyclic comparison // contain already visited objects var objects1 = [], objects2 = [], // contain pathes (position in the object structure) // of the already visited objects // indexes same as in objects arrays paths1 = [], paths2 = [], // contains combinations of already compared objects // in the manner: { "$1['ref']$2['ref']": true } compared = {}; /** * used to check, if the value of a property is an object * (cyclic logic is only needed for objects) * only needed for cyclic logic */ function isObject(value) { if (typeof value === 'object' && value !== null && !(value instanceof Boolean) && !(value instanceof Date) && !(value instanceof Number) && !(value instanceof RegExp) && !(value instanceof String)) { return true; } return false; } /** * returns the index of the given object in the * given objects array, -1 if not contained * only needed for cyclic logic */ function getIndex(objects, obj) { var i; for (i = 0; i < objects.length; i++) { if (objects[i] === obj) { return i; } } return -1; } // does the recursion for the deep equal check return (function deepEqual(obj1, obj2, path1, path2) { var type1 = typeof obj1; var type2 = typeof obj2; // == null also matches undefined if (obj1 === obj2 || isNaN(obj1) || isNaN(obj2) || obj1 == null || obj2 == null || type1 !== "object" || type2 !== "object") { return identical(obj1, obj2); } // Elements are only equal if identical(expected, actual) if (isElement(obj1) || isElement(obj2)) { return false; } var isDate1 = isDate(obj1), isDate2 = isDate(obj2); if (isDate1 || isDate2) { if (!isDate1 || !isDate2 || obj1.getTime() !== obj2.getTime()) { return false; } } if (obj1 instanceof RegExp && obj2 instanceof RegExp) { if (obj1.toString() !== obj2.toString()) { return false; } } var class1 = getClass(obj1); var class2 = getClass(obj2); var keys1 = keys(obj1); var keys2 = keys(obj2); if (isArguments(obj1) || isArguments(obj2)) { if (obj1.length !== obj2.length) { return false; } } else { if (type1 !== type2 || class1 !== class2 || keys1.length !== keys2.length) { return false; } } var key, i, l, // following vars are used for the cyclic logic value1, value2, isObject1, isObject2, index1, index2, newPath1, newPath2; for (i = 0, l = keys1.length; i < l; i++) { key = keys1[i]; if (!o.hasOwnProperty.call(obj2, key)) { return false; } // Start of the cyclic logic value1 = obj1[key]; value2 = obj2[key]; isObject1 = isObject(value1); isObject2 = isObject(value2); // determine, if the objects were already visited // (it's faster to check for isObject first, than to // get -1 from getIndex for non objects) index1 = isObject1 ? getIndex(objects1, value1) : -1; index2 = isObject2 ? getIndex(objects2, value2) : -1; // determine the new pathes of the objects // - for non cyclic objects the current path will be extended // by current property name // - for cyclic objects the stored path is taken newPath1 = index1 !== -1 ? paths1[index1] : path1 + '[' + JSON.stringify(key) + ']'; newPath2 = index2 !== -1 ? paths2[index2] : path2 + '[' + JSON.stringify(key) + ']'; // stop recursion if current objects are already compared if (compared[newPath1 + newPath2]) { return true; } // remember the current objects and their pathes if (index1 === -1 && isObject1) { objects1.push(value1); paths1.push(newPath1); } if (index2 === -1 && isObject2) { objects2.push(value2); paths2.push(newPath2); } // remember that the current objects are already compared if (isObject1 && isObject2) { compared[newPath1 + newPath2] = true; } // End of cyclic logic // neither value1 nor value2 is a cycle // continue with next level if (!deepEqual(value1, value2, newPath1, newPath2)) { return false; } } return true; }(obj1, obj2, '$1', '$2')); } var match; function arrayContains(array, subset) { var i, l, j, k; for (i = 0, l = array.length; i < l; ++i) { if (match(array[i], subset[0])) { for (j = 0, k = subset.length; j < k; ++j) { if (!match(array[i + j], subset[j])) { return false; } } return true; } } return false; } /** * @name samsam.match * @param Object object * @param Object matcher * * Compare arbitrary value ``object`` with matcher. */ match = function match(object, matcher) { if (matcher && typeof matcher.test === "function") { return matcher.test(object); } if (typeof matcher === "function") { return matcher(object) === true; } if (typeof matcher === "string") { matcher = matcher.toLowerCase(); var notNull = typeof object === "string" || !!object; return notNull && (String(object)).toLowerCase().indexOf(matcher) >= 0; } if (typeof matcher === "number") { return matcher === object; } if (typeof matcher === "boolean") { return matcher === object; } if (getClass(object) === "Array" && getClass(matcher) === "Array") { return arrayContains(object, matcher); } if (matcher && typeof matcher === "object") { var prop; for (prop in matcher) { if (!match(object[prop], matcher[prop])) { return false; } } return true; } throw new Error("Matcher was not a string, a number, a " + "function, a boolean or an object"); }; return { isArguments: isArguments, isElement: isElement, isDate: isDate, isNegZero: isNegZero, identical: identical, deepEqual: deepEqualCyclic, match: match }; }); ((typeof define === "function" && define.amd && function (m) { define("evented-logger", ["lodash", "bane"], m); }) || (typeof module === "object" && typeof require === "function" && function (m) { module.exports = m(require("lodash"), require("bane")); }) || function (m) { this.eventedLogger = m(this._, this.bane); } )(function (_, bane) { "use strict"; function formatMessage(logger, message) { if (!logger.logFunctions && typeof message === "function") { return logger.format(message()); } return logger.format(message); } function createLogger(name, level) { return function () { if (level > _.indexOf(this.levels, this.level)) { return; } var self = this; var message = _.reduce(arguments, function (memo, arg) { return memo.concat(formatMessage(self, arg)); }, []).join(" "); this.emit("log", { message: message, level: this.levels[level] }); }; } function Logger(opt) { var logger = this; logger.levels = opt.levels || ["error", "warn", "log", "debug"]; logger.level = opt.level || logger.levels[logger.levels.length - 1]; _.each(logger.levels, function (level, i) { logger[level] = createLogger(level, i); }); if (opt.formatter) { logger.format = opt.formatter; } logger.logFunctions = !!opt.logFunctions; } Logger.prototype = bane.createEventEmitter({ create: function (opt) { return new Logger(opt || {}); }, format: function (obj) { if (typeof obj !== "object") { return String(obj); } try { return JSON.stringify(obj); } catch (e) { return String(obj); } } }); return Logger.prototype; }); ((typeof define === "function" && define.amd && function (m) { define("referee", ["lodash", "samsam", "bane"], m); }) || (typeof module === "object" && function (m) { module.exports = m(require("lodash"), require("samsam"), require("bane")); }) || function (m) { this.referee = m(this._, this.samsam, this.bane); } )(function (_, samsam, bane) { "use strict"; var toString = Object.prototype.toString; var slice = Array.prototype.slice; var assert, refute, referee = bane.createEventEmitter(); referee.countAssertion = function countAssertion() { if (typeof referee.count !== "number") { referee.count = 0; } referee.count += 1; }; function interpolate(string, prop, value) { return string.replace(new RegExp("\\$\\{" + prop + "\\}", "g"), value); } // Interpolate positional arguments. Replaces occurences of ${<index>} in // the string with the corresponding entry in values[<index>] function interpolatePosArg(message, values) { return _.reduce(values, function (msg, value, index) { return interpolate(msg, index, referee.format(value)); }, message); } function interpolateProperties(message, properties) { return _.reduce(_.keys(properties), function (msg, name) { return interpolate(msg, name, referee.format(properties[name])); }, message || ""); } // Fail an assertion. Interpolates message before calling referee.fail function fail(type, assertion, msg) { delete this.fail; var message = interpolateProperties(interpolatePosArg( referee[type][assertion][msg] || msg, [].slice.call(arguments, 3) ), this); referee.fail("[" + type + "." + assertion + "] " + message); } // Internal helper. Used throughout to fail assertions if they receive // too few arguments. The name is provided for a helpful error message. function assertArgNum(name, args, num) { if (args.length < num) { referee.fail("[" + name + "] Expected to receive at least " + num + " argument" + (num > 1 ? "s" : "")); return false; } return true; } // Internal helper. Not the most elegant of functions, but it takes // care of all the nitty-gritty of assertion functions: counting, // verifying parameter count, interpolating messages with actual // values and so on. function defineAssertion(type, name, func, minArgs, messageValues) { referee[type][name] = function () { referee.countAssertion(); var fullName = type + "." + name, failed = false; if (!assertArgNum(fullName, arguments, minArgs || func.length)) { return; } var ctx = { fail: function () { failed = true; var failArgs = [type, name].concat(slice.call(arguments)); fail.apply(this, failArgs); return true; } }; var args = slice.call(arguments, 0); if (typeof messageValues === "function") { args = messageValues.apply(this, args); } if (!func.apply(ctx, arguments)) { return fail.apply(ctx, [type, name, "message"].concat(args)); } if (!failed) { referee.emit.apply(referee, ["pass", fullName].concat(args)); } }; } referee.add = function (name, opt) { var refuteArgs; if (opt.refute) { refuteArgs = opt.refute.length; } else { refuteArgs = opt.assert.length; opt.refute = function () { return !opt.assert.apply(this, arguments); }; } var values = opt.values; defineAssertion("assert", name, opt.assert, opt.assert.length, values); defineAssertion("refute", name, opt.refute, refuteArgs, values); assert[name].message = opt.assertMessage; refute[name].message = opt.refuteMessage; if (opt.expectation) { if (referee.expect && referee.expect.wrapAssertion) { referee.expect.wrapAssertion(name, opt.expectation); } else { assert[name].expectationName = opt.expectation; refute[name].expectationName = opt.expectation; } } }; assert = referee.assert = function assert(actual, message) { referee.countAssertion(); if (!assertArgNum("assert", arguments, 1)) { return; } if (!actual) { var v = referee.format(actual); referee.fail(message || "[assert] Expected " + v + " to be truthy"); } else { referee.emit("pass", "assert", message || "", actual); } }; assert.toString = function () { return "referee.assert()"; }; refute = referee.refute = function (actual, message) { referee.countAssertion(); if (!assertArgNum("refute", arguments, 1)) { return; } if (actual) { var v = referee.format(actual); referee.fail(message || "[refute] Expected " + v + " to be falsy"); } else { referee.emit("pass", "refute", message || "", actual); } }; assert.message = "[assert] Expected ${0} to be truthy"; referee.count = 0; referee.fail = function (message) { var exception = new Error(message); exception.name = "AssertionError"; try { throw exception; } catch (e) { referee.emit("failure", e); } if (typeof referee.throwOnFailure !== "boolean" || referee.throwOnFailure) { throw exception; } }; referee.format = function (object) { return String(object); }; function msg(message) { if (!message) { return ""; } return message + (/[.:!?]$/.test(message) ? " " : ": "); } referee.prepareMessage = msg; function actualAndExpectedMessageValues(actual, expected, message) { return [actual, expected, msg(message)]; } function actualMessageValues(actual, message) { return [actual, msg(message)]; } function actualAndTypeOfMessageValues(actual, message) { return [actual, typeof actual, msg(message)]; } referee.add("same", { assert: function (actual, expected) { return samsam.identical(actual, expected); }, refute: function (actual, expected) { return !samsam.identical(actual, expected); }, assertMessage: "${2}${0} expected to be the same object as ${1}", refuteMessage: "${2}${0} expected not to be the same object as ${1}", expectation: "toBe", values: actualAndExpectedMessageValues }); // Extract/replace with separate module that does a more detailed // visualization of multi-line strings function multiLineStringDiff(actual, expected, message) { if (actual === expected) { return true; } var heading = assert.equals.multiLineStringHeading; message = interpolatePosArg(heading, [message]); var actualLines = actual.split("\n"); var expectedLines = expected.split("\n"); var lineCount = Math.max(expectedLines.length, actualLines.length); var i, lines = []; for (i = 0; i < lineCount; ++i) { if (expectedLines[i] !== actualLines[i]) { lines.push("line " + (i + 1) + ": " + (expectedLines[i] || "") + "\nwas: " + (actualLines[i] || "")); } } referee.fail("[assert.equals] " + message + lines.join("\n\n")); return false; } referee.add("equals", { // Uses arguments[2] because the function's .length is used to determine // the minimum required number of arguments. assert: function (actual, expected) { if (typeof actual === "string" && typeof expected === "string" && (actual.indexOf("\n") >= 0 || expected.indexOf("\n") >= 0)) { var message = msg(arguments[2]); return multiLineStringDiff(actual, expected, message); } return samsam.deepEqual(actual, expected); }, refute: function (actual, expected) { return !samsam.deepEqual(actual, expected); }, assertMessage: "${2}${0} expected to be equal to ${1}", refuteMessage: "${2}${0} expected not to be equal to ${1}", expectation: "toEqual", values: actualAndExpectedMessageValues }); assert.equals.multiLineStringHeading = "${0}Expected multi-line strings " + "to be equal:\n"; referee.add("greater", { assert: function (actual, expected) { return actual > expected; }, assertMessage: "${2}Expected ${0} to be greater than ${1}", refuteMessage: "${2}Expected ${0} to be less than or equal to ${1}", expectation: "toBeGreaterThan", values: actualAndExpectedMessageValues }); referee.add("less", { assert: function (actual, expected) { return actual < expected; }, assertMessage: "${2}Expected ${0} to be less than ${1}", refuteMessage: "${2}Expected ${0} to be greater than or equal to ${1}", expectation: "toBeLessThan", values: actualAndExpectedMessageValues }); referee.add("defined", { assert: function (actual) { return typeof actual !== "undefined"; }, assertMessage: "${2}Expected to be defined", refuteMessage: "${2}Expected ${0} (${1}) not to be defined", expectation: "toBeDefined", values: actualAndTypeOfMessageValues }); referee.add("isNull", { assert: function (actual) { return actual === null; }, assertMessage: "${1}Expected ${0} to be null", refuteMessage: "${1}Expected not to be null", expectation: "toBeNull", values: actualMessageValues }); referee.match = function (actual, matcher) { try { return samsam.match(actual, matcher); } catch (e) { throw new Error("Matcher (" + referee.format(matcher) + ") was not a string, a number, a function, " + "a boolean or an object"); } }; referee.add("match", { assert: function (actual, matcher) { var passed; try { passed = referee.match(actual, matcher); } catch (e) { // Uses arguments[2] because the function's .length is used // to determine the minimum required number of arguments. var message = msg(arguments[2]); return this.fail("exceptionMessage", e.message, message); } return passed; }, refute: function (actual, matcher) { var passed; try { passed = referee.match(actual, matcher); } catch (e) { return this.fail("exceptionMessage", e.message); } return !passed; }, assertMessage: "${2}${0} expected to match ${1}", refuteMessage: "${2}${0} expected not to match ${1}", expectation: "toMatch", values: actualAndExpectedMessageValues }); assert.match.exceptionMessage = "${1}${0}"; refute.match.exceptionMessage = "${1}${0}"; referee.add("isObject", { assert: function (actual) { return typeof actual === "object" && !!actual; }, assertMessage: "${2}${0} (${1}) expected to be object and not null", refuteMessage: "${2}${0} expected to be null or not an object", expectation: "toBeObject", values: actualAndTypeOfMessageValues }); referee.add("isFunction", { assert: function (actual) { return typeof actual === "function"; }, assertMessage: "${2}${0} (${1}) expected to be function", refuteMessage: "${2}${0} expected not to be function", expectation: "toBeFunction", values: function (actual) { // Uses arguments[1] because the function's .length is used to // determine the minimum required number of arguments. var message = msg(arguments[1]); return [String(actual).replace("\n", ""), typeof actual, message]; } }); referee.add("isTrue", { assert: function (actual) { return actual === true; }, assertMessage: "${1}Expected ${0} to be true", refuteMessage: "${1}Expected ${0} to not be true", expectation: "toBeTrue", values: actualMessageValues }); referee.add("isFalse", { assert: function (actual) { return actual === false; }, assertMessage: "${1}Expected ${0} to be false", refuteMessage: "${1}Expected ${0} to not be false", expectation: "toBeFalse", values: actualMessageValues }); referee.add("isString", { assert: function (actual) { return typeof actual === "string"; }, assertMessage: "${2}Expected ${0} (${1}) to be string", refuteMessage: "${2}Expected ${0} not to be string", expectation: "toBeString", values: actualAndTypeOfMessageValues }); referee.add("isBoolean", { assert: function (actual) { return typeof actual === "boolean"; }, assertMessage: "${2}Expected ${0} (${1}) to be boolean", refuteMessage: "${2}Expected ${0} not to be boolean", expectation: "toBeBoolean", values: actualAndTypeOfMessageValues }); referee.add("isNumber", { assert: function (actual) { return typeof actual === "number" && !isNaN(actual); }, assertMessage: "${2}Expected ${0} (${1}) to be a non-NaN number", refuteMessage: "${2}Expected ${0} to be NaN or a non-number value", expectation: "toBeNumber", values: actualAndTypeOfMessageValues }); referee.add("isNaN", { assert: function (actual) { return typeof actual === "number" && isNaN(actual); }, assertMessage: "${2}Expected ${0} to be NaN", refuteMessage: "${2}Expected not to be NaN", expectation: "toBeNaN", values: actualAndTypeOfMessageValues }); referee.add("isArray", { assert: function (actual) { return toString.call(actual) === "[object Array]"; }, assertMessage: "${2}Expected ${0} to be array", refuteMessage: "${2}Expected ${0} not to be array", expectation: "toBeArray", values: actualAndTypeOfMessageValues }); function isArrayLike(object) { return _.isArray(object) || (!!object && typeof object.length === "number" && typeof object.splice === "function") || _.isArguments(object); } referee.isArrayLike = isArrayLike; referee.add("isArrayLike", { assert: function (actual) { return isArrayLike(actual); }, assertMessage: "${2}Expected ${0} to be array like", refuteMessage: "${2}Expected ${0} not to be array like", expectation: "toBeArrayLike", values: actualAndTypeOfMessageValues }); function exactKeys(object, keys) { var keyMap = {}; var keyCnt = 0; for (var i=0; i < keys.length; i++) { keyMap[keys[i]] = true; keyCnt += 1; } for (var key in object) { if (object.hasOwnProperty(key)) { if (! keyMap[key]) { return false; } keyCnt -= 1; } } return keyCnt === 0; } referee.add('keys', { assert: function (actual, keys) { return exactKeys(actual, keys); }, assertMessage: "Expected ${0} to have exact keys ${1}!", refuteMessage: "Expected ${0} not to have exact keys ${1}!", expectation: "toHaveKeys" }); function captureException(callback) { try { callback(); } catch (e) { return e; } return null; } referee.captureException = captureException; assert.exception = function (callback, matcher, message) { referee.countAssertion(); if (!assertArgNum("assert.exception", arguments, 1)) { return; } if (!callback) { return; } if (typeof matcher === "string") { message = matcher; matcher = undefined; } var err = captureException(callback); message = msg(message); if (!err) { if (typeof matcher === "object") { return fail.call( {}, "assert", "exception", "typeNoExceptionMessage", message, referee.format(matcher) ); } else { return fail.call({}, "assert", "exception", "message", message); } } if (typeof matcher === "object" && !referee.match(err, matcher)) { return fail.call( {}, "assert", "exception", "typeFailMessage", message, referee.format(matcher), err.name, err.message, err.stack ); } if (typeof matcher === "function" && matcher(err) !== true) { return fail.call({}, "assert", "exception", "matchFailMessage", message, err.name, err.message); } referee.emit("pass", "assert.exception", message, callback, matcher); }; assert.exception.typeNoExceptionMessage = "${0}Expected ${1} but no " + "exception was thrown"; assert.exception.message = "${0}Expected exception"; assert.exception.typeFailMessage = "${0}Expected ${1} but threw ${2} " + "(${3})\n${4}"; assert.exception.matchFailMessage = "${0}Expected thrown ${1} (${2}) to " + "pass matcher function"; assert.exception.expectationName = "toThrow"; refute.exception = function (callback) { referee.countAssertion(); if (!assertArgNum("refute.exception", arguments, 1)) { return; } var err = captureException(callback); if (err) { // Uses arguments[1] because the function's .length is used to // determine the minimum required number of arguments. fail.call({}, "refute", "exception", "message", msg(arguments[1]), err.name, err.message, callback); } else { referee.emit("pass", "refute.exception", callback); } }; refute.exception.message = "${0}Expected not to throw but " + "threw ${1} (${2})"; refute.exception.expectationName = "toThrow"; referee.add("near", { assert: function (actual, expected, delta) { return Math.abs(actual - expected) <= delta; }, assertMessage: "${3}Expected ${0} to be equal to ${1} +/- ${2}", refuteMessage: "${3}Expected ${0} not to be equal to ${1} +/- ${2}", expectation: "toBeNear", values: function (actual, expected, delta, message) { return [actual, expected, delta, msg(message)]; } }); referee.add("hasPrototype", { assert: function (actual, protoObj) { return protoObj.isPrototypeOf(actual); }, assertMessage: "${2}Expected ${0} to have ${1} on its prototype chain", refuteMessage: "${2}Expected ${0} not to have ${1} on its " + "prototype chain", expectation: "toHavePrototype", values: actualAndExpectedMessageValues }); referee.add("contains", { assert: function (haystack, needle) { return _.include(haystack, needle); }, assertMessage: "${2}Expected [${0}] to contain ${1}", refuteMessage: "${2}Expected [${0}] not to contain ${1}", expectation: "toContain", values: actualAndExpectedMessageValues }); referee.add("tagName", { assert: function (element, tagName) { // Uses arguments[2] because the function's .length is used to // determine the minimum required number of arguments. if (!element.tagName) { return this.fail( "noTagNameMessage", tagName, element, msg(arguments[2]) ); } return tagName.toLowerCase && tagName.toLowerCase() === element.tagName.toLowerCase(); }, assertMessage: "${2}Expected tagName to be ${0} but was ${1}", refuteMessage: "${2}Expected tagName not to be ${0}", expectation: "toHaveTagName", values: function (element, tagName, message) { return [tagName, element.tagName, msg(message)]; } }); assert.tagName.noTagNameMessage = "${2}Expected ${1} to have tagName " + "property"; refute.tagName.noTagNameMessage = "${2}Expected ${1} to have tagName " + "property"; referee.add("className", { assert: function (element, name) { if (typeof element.className === "undefined") { // Uses arguments[2] because the function's .length is used to // determine the minimum required number of arguments. return this.fail( "noClassNameMessage", name, element, msg(arguments[2]) ); } var expected = typeof name === "string" ? name.split(" ") : name; var actual = element.className.split(" "); var i, l; for (i = 0, l = expected.length; i < l; i++) { if (!_.include(actual, expected[i])) { return false; } } return true; }, assertMessage: "${2}Expected object's className to include ${0} " + "but was ${1}", refuteMessage: "${2}Expected object's className not to include ${0}", expectation: "toHaveClassName", values: function (element, className, message) { return [className, element.className, msg(message)]; } }); assert.className.noClassNameMessage = "${2}Expected object to have " + "className property"; refute.className.noClassNameMessage = "${2}Expected object to have " + "className property"; if (typeof module !== "undefined" && typeof require === "function") { referee.expect = function () { referee.expect = require("./expect"); return referee.expect.apply(referee, arguments); }; } return referee; }); ((typeof define === "function" && define.amd && function (m) { define("referee/expect", ["lodash", "referee"], m); }) || (typeof module === "object" && function (m) { module.exports = m(require("lodash"), require("./referee")); }) || function (m) { this.referee.expect = m(this._, this.referee); } )(function (_, referee) { var expectation = {}; function F() {} var create = function (object) { F.prototype = object; return new F(); }; var expect = function (actual) { var expectation = _.extend(create(expect.expectation), { actual: actual, assertMode: true }); expectation.not = create(expectation); expectation.not.assertMode = false; return expectation; }; expect.expectation = expectation; expect.wrapAssertion = function (assertion, expectation) { expect.expectation[expectation] = function () { var args = [this.actual].concat(_.toArray(arguments)); var type = this.assertMode ? "assert" : "refute"; var callFunc; if (assertion === "assert") { callFunc = this.assertMode ? referee.assert : referee.refute; } else if (assertion === "refute") { callFunc = this.assertMode ? referee.refute : referee.assert; } else { callFunc = referee[type][assertion]; } try { return callFunc.apply(referee.expect, args); } catch (e) { e.message = (e.message || "").replace( "[" + type + "." + assertion + "]", "[expect." + (this.assertMode ? "" : "not.") + expectation + "]" ); throw e; } }; }; _.each(_.keys(referee.assert), function (name) { var expectationName = referee.assert[name].expectationName; if (expectationName) { expect.wrapAssertion(name, expectationName); } }); expect.wrapAssertion("assert", "toBeTruthy"); expect.wrapAssertion("refute", "toBeFalsy"); if (expect.expectation.toBeNear) { expect.expectation.toBeCloseTo = expect.expectation.toBeNear; } return expect; }); ((typeof define === "function" && define.amd && function (m) { define("formatio", ["samsam", "lodash"], m); }) || (typeof module === "object" && function (m) { module.exports = m(require("samsam"), require("lodash")); }) || function (m) { this.formatio = m(this.samsam, this._); } )(function (samsam, _) { "use strict"; var formatio = { excludeConstructors: ["Object", /^.$/], quoteStrings: true }; var hasOwn = Object.prototype.hasOwnProperty; var specialObjects = []; if (typeof global !== "undefined") { specialObjects.push({ object: global, value: "[object global]" }); } if (typeof document !== "undefined") { specialObjects.push({ object: document, value: "[object HTMLDocument]" }); } if (typeof window !== "undefined") { specialObjects.push({ object: window, value: "[object Window]" }); } function functionName(func) { if (!func) { return ""; } if (func.displayName) { return func.displayName; } if (func.name) { return func.name; } var matches = func.toString().match(/function\s+([^\(]+)/m); return (matches && matches[1]) || ""; } function constructorName(f, object) { var name = functionName(object && object.constructor); var excludes = f.excludeConstructors || formatio.excludeConstructors || []; var i, l; for (i = 0, l = excludes.length; i < l; ++i) { if (typeof excludes[i] === "string" && excludes[i] === name) { return ""; } else if (excludes[i].test && excludes[i].test(name)) { return ""; } } return name; } function isCircular(object, objects) { if (typeof object !== "object") { return false; } var i, l; for (i = 0, l = objects.length; i < l; ++i) { if (objects[i] === object) { return true; } } return false; } function ascii(f, object, processed, indent) { if (typeof object === "string") { var qs = f.quoteStrings; var quote = typeof qs !== "boolean" || qs; return processed || quote ? '"' + object + '"' : object; } if (typeof object === "function" && !(object instanceof RegExp)) { return ascii.func(object); } processed = processed || []; if (isCircular(object, processed)) { return "[Circular]"; } if (_.isArray(object)) { return ascii.array.call(f, object, processed); } if (!object) { return String(object === -0 ? "-0" : object); } if (samsam.isElement(object)) { return ascii.element(object); } if (typeof object.toString === "function" && object.toString !== Object.prototype.toString) { return object.toString(); } var i, l; for (i = 0, l = specialObjects.length; i < l; i++) { if (object === specialObjects[i].object) { return specialObjects[i].value; } } return ascii.object.call(f, object, processed, indent); } ascii.func = function (func) { return "function " + functionName(func) + "() {}"; }; ascii.array = function (array, processed) { processed = processed || []; processed.push(array); var i, l, pieces = []; for (i = 0, l = array.length; i < l; ++i) { pieces.push(ascii(this, array[i], processed)); } return "[" + pieces.join(", ") + "]"; }; ascii.object = function (object, processed, indent) { processed = processed || []; processed.push(object); indent = indent || 0; var pieces = [], properties = _.keys(object).sort(); var length = 3; var prop, str, obj, i, l; for (i = 0, l = properties.length; i < l; ++i) { prop = properties[i]; obj = object[prop]; if (isCircular(obj, processed)) { str = "[Circular]"; } else { str = ascii(this, obj, processed, indent + 2); } str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str; length += str.length; pieces.push(str); } var cons = constructorName(this, object); var prefix = cons ? "[" + cons + "] " : ""; var is = ""; for (i = 0, l = indent; i < l; ++i) { is += " "; } if (length + indent > 80) { return prefix + "{\n " + is + pieces.join(",\n " + is) + "\n" + is + "}"; } return prefix + "{ " + pieces.join(", ") + " }"; }; ascii.element = function (element) { var tagName = element.tagName.toLowerCase(); var attrs = element.attributes, attr, pairs = [], attrName, i, l, val; for (i = 0, l = attrs.length; i < l; ++i) { attr = attrs.item(i); attrName = attr.nodeName.toLowerCase().replace("html:", ""); val = attr.nodeValue; if (attrName !== "contenteditable" || val !== "inherit") { if (!!val) { pairs.push(attrName + "=\"" + val + "\""); } } } var formatted = "<" + tagName + (pairs.length > 0 ? " " : ""); var content = element.innerHTML; if (content.length > 20) { content = content.substr(0, 20) + "[...]"; } var res = formatted + pairs.join(" ") + ">" + content + "</" + tagName + ">"; return res.replace(/ contentEditable="inherit"/, ""); }; function Formatio(options) { for (var opt in options) { this[opt] = options[opt]; } } Formatio.prototype = { functionName: functionName, configure: function (options) { return new Formatio(options); }, constructorName: function (object) { return constructorName(this, object); }, ascii: function (object, processed, indent) { return ascii(this, object, processed, indent); } }; return Formatio.prototype; }); ((typeof define === "function" && define.amd && function (m) { define("stack-filter", m); }) || (typeof module === "object" && function (m) { module.exports = m(); }) || function (m) { this.stackFilter = m(); } )(function () { "use strict"; var regexpes = {}; return { filters: [], configure: function (opt) { opt = opt || {}; var instance = Object.create(this); instance.filters = opt.filters || []; instance.cwd = opt.cwd; return instance; }, /** * Return true if the stack trace line matches any filter */ match: function (line) { var i, l, filters = this.filters; for (i = 0, l = filters.length; i < l; ++i) { if (!regexpes[filters[i]]) { // Backslashes must be double-escaped: // new RegExp("\\") is equivalent to /\/ - which is an invalid pattern // new RegExp("\\\\") is equivalent to /\\/ - an escaped backslash // This must be done for Windows paths to work properly regexpes[filters[i]] = new RegExp(filters[i].replace(/\\/g, "\\\\")); } if (regexpes[filters[i]].test(line)) { return true; } } return false; }, /** * Filter a stack trace and optionally trim off the current * working directory. Accepts a stack trace as a string, and * an optional cwd (also a string). The cwd can also be * configured directly on the instance. * * Returns an array of lines - a pruned stack trace. The * result only includes lines that point to a file and a * location - the initial error message is stripped off. If a * cwd is available, all paths will be stripped of it. Any * line matching any filter will not be included in the * result. */ filter: function (stack, cwd) { var lines = (stack || "").split("\n"); var i, l, line, stackLines = [], replacer = "./"; cwd = cwd || this.cwd; if (typeof cwd === "string") { cwd = cwd.replace(/\/?$/, "/"); } if (cwd instanceof RegExp && !/\/\/$/.test(cwd)) { replacer = "."; } for (i = 0, l = lines.length; i < l; ++i) { if (/(\d+)?:\d+\)?$/.test(lines[i])) { if (!this.match(lines[i])) { line = lines[i].replace(/^\s+|\s+$/g, ""); if (cwd) { line = line.replace(cwd, replacer); } stackLines.push(line); } } } return stackLines; } }; }); /*jslint eqeqeq: false, onevar: false, forin: true, nomen: false, regexp: false, plusplus: false*/ /*global module, require, __dirname, document*/ /** * Sinon core utilities. For internal use only. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; var sinon = (function (buster) { var div = typeof document != "undefined" && document.createElement("div"); var hasOwn = Object.prototype.hasOwnProperty; function isDOMNode(obj) { var success = false; try { obj.appendChild(div); success = div.parentNode == obj; } catch (e) { return false; } finally { try { obj.removeChild(div); } catch (e) { // Remove failed, not much we can do about that } } return success; } function isElement(obj) { return div && obj && obj.nodeType === 1 && isDOMNode(obj); } function isFunction(obj) { return typeof obj === "function" || !!(obj && obj.constructor && obj.call && obj.apply); } function mirrorProperties(target, source) { for (var prop in source) { if (!hasOwn.call(target, prop)) { target[prop] = source[prop]; } } } function isRestorable (obj) { return typeof obj === "function" && typeof obj.restore === "function" && obj.restore.sinon; } var sinon = { wrapMethod: function wrapMethod(object, property, method) { if (!object) { throw new TypeError("Should wrap property of object"); } if (typeof method != "function") { throw new TypeError("Method wrapper should be function"); } var wrappedMethod = object[property]; if (!isFunction(wrappedMethod)) { throw new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " + property + " as function"); } if (wrappedMethod.restore && wrappedMethod.restore.sinon) { throw new TypeError("Attempted to wrap " + property + " which is already wrapped"); } if (wrappedMethod.calledBefore) { var verb = !!wrappedMethod.returns ? "stubbed" : "spied on"; throw new TypeError("Attempted to wrap " + property + " which is already " + verb); } // IE 8 does not support hasOwnProperty on the window object. var owned = hasOwn.call(object, property); object[property] = method; method.displayName = property; method.restore = function () { // For prototype properties try to reset by delete first. // If this fails (ex: localStorage on mobile safari) then force a reset // via direct assignment. if (!owned) { delete object[property]; } if (object[property] === method) { object[property] = wrappedMethod; } }; method.restore.sinon = true; mirrorProperties(method, wrappedMethod); return method; }, extend: function extend(target) { for (var i = 1, l = arguments.length; i < l; i += 1) { for (var prop in arguments[i]) { if (arguments[i].hasOwnProperty(prop)) { target[prop] = arguments[i][prop]; } // DONT ENUM bug, only care about toString if (arguments[i].hasOwnProperty("toString") && arguments[i].toString != target.toString) { target.toString = arguments[i].toString; } } } return target; }, create: function create(proto) { var F = function () {}; F.prototype = proto; return new F(); }, deepEqual: function deepEqual(a, b) { if (sinon.match && sinon.match.isMatcher(a)) { return a.test(b); } if (typeof a != "object" || typeof b != "object") { return a === b; } if (isElement(a) || isElement(b)) { return a === b; } if (a === b) { return true; } if ((a === null && b !== null) || (a !== null && b === null)) { return false; } var aString = Object.prototype.toString.call(a); if (aString != Object.prototype.toString.call(b)) { return false; } if (aString == "[object Array]") { if (a.length !== b.length) { return false; } for (var i = 0, l = a.length; i < l; i += 1) { if (!deepEqual(a[i], b[i])) { return false; } } return true; } if (aString == "[object Date]") { return a.valueOf() === b.valueOf(); } var prop, aLength = 0, bLength = 0; for (prop in a) { aLength += 1; if (!deepEqual(a[prop], b[prop])) { return false; } } for (prop in b) { bLength += 1; } return aLength == bLength; }, functionName: function functionName(func) { var name = func.displayName || func.name; // Use function decomposition as a last resort to get function // name. Does not rely on function decomposition to work - if it // doesn't debugging will be slightly less informative // (i.e. toString will say 'spy' rather than 'myFunc'). if (!name) { var matches = func.toString().match(/function ([^\s\(]+)/); name = matches && matches[1]; } return name; }, functionToString: function toString() { if (this.getCall && this.callCount) { var thisValue, prop, i = this.callCount; while (i--) { thisValue = this.getCall(i).thisValue; for (prop in thisValue) { if (thisValue[prop] === this) { return prop; } } } } return this.displayName || "sinon fake"; }, getConfig: function (custom) { var config = {}; custom = custom || {}; var defaults = sinon.defaultConfig; for (var prop in defaults) { if (defaults.hasOwnProperty(prop)) { config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop]; } } return config; }, format: function (val) { return "" + val; }, defaultConfig: { injectIntoThis: true, injectInto: null, properties: ["spy", "stub", "mock", "clock", "server", "requests"], useFakeTimers: true, useFakeServer: true }, timesInWords: function timesInWords(count) { return count == 1 && "once" || count == 2 && "twice" || count == 3 && "thrice" || (count || 0) + " times"; }, calledInOrder: function (spies) { for (var i = 1, l = spies.length; i < l; i++) { if (!spies[i - 1].calledBefore(spies[i]) || !spies[i].called) { return false; } } return true; }, orderByFirstCall: function (spies) { return spies.sort(function (a, b) { // uuid, won't ever be equal var aCall = a.getCall(0); var bCall = b.getCall(0); var aId = aCall && aCall.callId || -1; var bId = bCall && bCall.callId || -1; return aId < bId ? -1 : 1; }); }, log: function () {}, logError: function (label, err) { var msg = label + " threw exception: " sinon.log(msg + "[" + err.name + "] " + err.message); if (err.stack) { sinon.log(err.stack); } setTimeout(function () { err.message = msg + err.message; throw err; }, 0); }, typeOf: function (value) { if (value === null) { return "null"; } else if (value === undefined) { return "undefined"; } var string = Object.prototype.toString.call(value); return string.substring(8, string.length - 1).toLowerCase(); }, createStubInstance: function (constructor) { if (typeof constructor !== "function") { throw new TypeError("The constructor should be a function."); } return sinon.stub(sinon.create(constructor.prototype)); }, restore: function (object) { if (object !== null && typeof object === "object") { for (var prop in object) { if (isRestorable(object[prop])) { object[prop].restore(); } } } else if (isRestorable(object)) { object.restore(); } } }; var isNode = typeof module == "object" && typeof require == "function"; if (isNode) { try { buster = { format: require("buster-format") }; } catch (e) {} module.exports = sinon; module.exports.spy = require("./sinon/spy"); module.exports.stub = require("./sinon/stub"); module.exports.mock = require("./sinon/mock"); module.exports.collection = require("./sinon/collection"); module.exports.assert = require("./sinon/assert"); module.exports.sandbox = require("./sinon/sandbox"); module.exports.test = require("./sinon/test"); module.exports.testCase = require("./sinon/test_case"); module.exports.assert = require("./sinon/assert"); module.exports.match = require("./sinon/match"); } if (buster) { var formatter = sinon.create(buster.format); formatter.quoteStrings = false; sinon.format = function () { return formatter.ascii.apply(formatter, arguments); }; } else if (isNode) { try { var util = require("util"); sinon.format = function (value) { return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value; }; } catch (e) { /* Node, but no util module - would be very old, but better safe than sorry */ } } return sinon; }(typeof buster == "object" && buster)); /** * @depend ../sinon.js * @depend match.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global module, require, sinon*/ /** * Spy calls * * @author Christian Johansen ([email protected]) * @author Maximilian Antoni ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen * Copyright (c) 2013 Maximilian Antoni */ "use strict"; var commonJSModule = typeof module == "object" && typeof require == "function"; if (!this.sinon && commonJSModule) { var sinon = require("../sinon"); } (function (sinon) { function throwYieldError(proxy, text, args) { var msg = sinon.functionName(proxy) + text; if (args.length) { msg += " Received [" + slice.call(args).join(", ") + "]"; } throw new Error(msg); } var slice = Array.prototype.slice; var callProto = { calledOn: function calledOn(thisValue) { if (sinon.match && sinon.match.isMatcher(thisValue)) { return thisValue.test(this.thisValue); } return this.thisValue === thisValue; }, calledWith: function calledWith() { for (var i = 0, l = arguments.length; i < l; i += 1) { if (!sinon.deepEqual(arguments[i], this.args[i])) { return false; } } return true; }, calledWithMatch: function calledWithMatch() { for (var i = 0, l = arguments.length; i < l; i += 1) { var actual = this.args[i]; var expectation = arguments[i]; if (!sinon.match || !sinon.match(expectation).test(actual)) { return false; } } return true; }, calledWithExactly: function calledWithExactly() { return arguments.length == this.args.length && this.calledWith.apply(this, arguments); }, notCalledWith: function notCalledWith() { return !this.calledWith.apply(this, arguments); }, notCalledWithMatch: function notCalledWithMatch() { return !this.calledWithMatch.apply(this, arguments); }, returned: function returned(value) { return sinon.deepEqual(value, this.returnValue); }, threw: function threw(error) { if (typeof error === "undefined" || !this.exception) { return !!this.exception; } return this.exception === error || this.exception.name === error; }, calledWithNew: function calledWithNew(thisValue) { return this.thisValue instanceof this.proxy; }, calledBefore: function (other) { return this.callId < other.callId; }, calledAfter: function (other) { return this.callId > other.callId; }, callArg: function (pos) { this.args[pos](); }, callArgOn: function (pos, thisValue) { this.args[pos].apply(thisValue); }, callArgWith: function (pos) { this.callArgOnWith.apply(this, [pos, null].concat(slice.call(arguments, 1))); }, callArgOnWith: function (pos, thisValue) { var args = slice.call(arguments, 2); this.args[pos].apply(thisValue, args); }, "yield": function () { this.yieldOn.apply(this, [null].concat(slice.call(arguments, 0))); }, yieldOn: function (thisValue) { var args = this.args; for (var i = 0, l = args.length; i < l; ++i) { if (typeof args[i] === "function") { args[i].apply(thisValue, slice.call(arguments, 1)); return; } } throwYieldError(this.proxy, " cannot yield since no callback was passed.", args); }, yieldTo: function (prop) { this.yieldToOn.apply(this, [prop, null].concat(slice.call(arguments, 1))); }, yieldToOn: function (prop, thisValue) { var args = this.args; for (var i = 0, l = args.length; i < l; ++i) { if (args[i] && typeof args[i][prop] === "function") { args[i][prop].apply(thisValue, slice.call(arguments, 2)); return; } } throwYieldError(this.proxy, " cannot yield to '" + prop + "' since no callback was passed.", args); }, toString: function () { var callStr = this.proxy.toString() + "("; var args = []; for (var i = 0, l = this.args.length; i < l; ++i) { args.push(sinon.format(this.args[i])); } callStr = callStr + args.join(", ") + ")"; if (typeof this.returnValue != "undefined") { callStr += " => " + sinon.format(this.returnValue); } if (this.exception) { callStr += " !" + this.exception.name; if (this.exception.message) { callStr += "(" + this.exception.message + ")"; } } return callStr; } }; callProto.invokeCallback = callProto.yield; function createSpyCall(spy, thisValue, args, returnValue, exception, id) { if (typeof id !== "number") { throw new TypeError("Call id is not a number"); } var proxyCall = sinon.create(callProto); proxyCall.proxy = spy; proxyCall.thisValue = thisValue; proxyCall.args = args; proxyCall.returnValue = returnValue; proxyCall.exception = exception; proxyCall.callId = id; return proxyCall; }; createSpyCall.toString = callProto.toString; // used by mocks sinon.spyCall = createSpyCall; }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global module, require, sinon*/ /** * Spy functions * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; var push = Array.prototype.push; var slice = Array.prototype.slice; var callId = 0; function spy(object, property) { if (!property && typeof object == "function") { return spy.create(object); } if (!object && !property) { return spy.create(function () { }); } var method = object[property]; return sinon.wrapMethod(object, property, spy.create(method)); } function matchingFake(fakes, args, strict) { if (!fakes) { return; } var alen = args.length; for (var i = 0, l = fakes.length; i < l; i++) { if (fakes[i].matches(args, strict)) { return fakes[i]; } } } function incrementCallCount() { this.called = true; this.callCount += 1; this.notCalled = false; this.calledOnce = this.callCount == 1; this.calledTwice = this.callCount == 2; this.calledThrice = this.callCount == 3; } function createCallProperties() { this.firstCall = this.getCall(0); this.secondCall = this.getCall(1); this.thirdCall = this.getCall(2); this.lastCall = this.getCall(this.callCount - 1); } var vars = "a,b,c,d,e,f,g,h,i,j,k,l"; function createProxy(func) { // Retain the function length: var p; if (func.length) { eval("p = (function proxy(" + vars.substring(0, func.length * 2 - 1) + ") { return p.invoke(func, this, slice.call(arguments)); });"); } else { p = function proxy() { return p.invoke(func, this, slice.call(arguments)); }; } return p; } var uuid = 0; // Public API var spyApi = { reset: function () { this.called = false; this.notCalled = true; this.calledOnce = false; this.calledTwice = false; this.calledThrice = false; this.callCount = 0; this.firstCall = null; this.secondCall = null; this.thirdCall = null; this.lastCall = null; this.args = []; this.returnValues = []; this.thisValues = []; this.exceptions = []; this.callIds = []; if (this.fakes) { for (var i = 0; i < this.fakes.length; i++) { this.fakes[i].reset(); } } }, create: function create(func) { var name; if (typeof func != "function") { func = function () { }; } else { name = sinon.functionName(func); } var proxy = createProxy(func); sinon.extend(proxy, spy); delete proxy.create; sinon.extend(proxy, func); proxy.reset(); proxy.prototype = func.prototype; proxy.displayName = name || "spy"; proxy.toString = sinon.functionToString; proxy._create = sinon.spy.create; proxy.id = "spy#" + uuid++; return proxy; }, invoke: function invoke(func, thisValue, args) { var matching = matchingFake(this.fakes, args); var exception, returnValue; incrementCallCount.call(this); push.call(this.thisValues, thisValue); push.call(this.args, args); push.call(this.callIds, callId++); try { if (matching) { returnValue = matching.invoke(func, thisValue, args); } else { returnValue = (this.func || func).apply(thisValue, args); } } catch (e) { push.call(this.returnValues, undefined); exception = e; throw e; } finally { push.call(this.exceptions, exception); } push.call(this.returnValues, returnValue); createCallProperties.call(this); return returnValue; }, getCall: function getCall(i) { if (i < 0 || i >= this.callCount) { return null; } return sinon.spyCall(this, this.thisValues[i], this.args[i], this.returnValues[i], this.exceptions[i], this.callIds[i]); }, calledBefore: function calledBefore(spyFn) { if (!this.called) { return false; } if (!spyFn.called) { return true; } return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1]; }, calledAfter: function calledAfter(spyFn) { if (!this.called || !spyFn.called) { return false; } return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1]; }, withArgs: function () { var args = slice.call(arguments); if (this.fakes) { var match = matchingFake(this.fakes, args, true); if (match) { return match; } } else { this.fakes = []; } var original = this; var fake = this._create(); fake.matchingAguments = args; push.call(this.fakes, fake); fake.withArgs = function () { return original.withArgs.apply(original, arguments); }; for (var i = 0; i < this.args.length; i++) { if (fake.matches(this.args[i])) { incrementCallCount.call(fake); push.call(fake.thisValues, this.thisValues[i]); push.call(fake.args, this.args[i]); push.call(fake.returnValues, this.returnValues[i]); push.call(fake.exceptions, this.exceptions[i]); push.call(fake.callIds, this.callIds[i]); } } createCallProperties.call(fake); return fake; }, matches: function (args, strict) { var margs = this.matchingAguments; if (margs.length <= args.length && sinon.deepEqual(margs, args.slice(0, margs.length))) { return !strict || margs.length == args.length; } }, printf: function (format) { var spy = this; var args = slice.call(arguments, 1); var formatter; return (format || "").replace(/%(.)/g, function (match, specifyer) { formatter = spyApi.formatters[specifyer]; if (typeof formatter == "function") { return formatter.call(null, spy, args); } else if (!isNaN(parseInt(specifyer), 10)) { return sinon.format(args[specifyer - 1]); } return "%" + specifyer; }); } }; function delegateToCalls(method, matchAny, actual, notCalled) { spyApi[method] = function () { if (!this.called) { if (notCalled) { return notCalled.apply(this, arguments); } return false; } var currentCall; var matches = 0; for (var i = 0, l = this.callCount; i < l; i += 1) { currentCall = this.getCall(i); if (currentCall[actual || method].apply(currentCall, arguments)) { matches += 1; if (matchAny) { return true; } } } return matches === this.callCount; }; } delegateToCalls("calledOn", true); delegateToCalls("alwaysCalledOn", false, "calledOn"); delegateToCalls("calledWith", true); delegateToCalls("calledWithMatch", true); delegateToCalls("alwaysCalledWith", false, "calledWith"); delegateToCalls("alwaysCalledWithMatch", false, "calledWithMatch"); delegateToCalls("calledWithExactly", true); delegateToCalls("alwaysCalledWithExactly", false, "calledWithExactly"); delegateToCalls("neverCalledWith", false, "notCalledWith", function () { return true; }); delegateToCalls("neverCalledWithMatch", false, "notCalledWithMatch", function () { return true; }); delegateToCalls("threw", true); delegateToCalls("alwaysThrew", false, "threw"); delegateToCalls("returned", true); delegateToCalls("alwaysReturned", false, "returned"); delegateToCalls("calledWithNew", true); delegateToCalls("alwaysCalledWithNew", false, "calledWithNew"); delegateToCalls("callArg", false, "callArgWith", function () { throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); }); spyApi.callArgWith = spyApi.callArg; delegateToCalls("callArgOn", false, "callArgOnWith", function () { throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); }); spyApi.callArgOnWith = spyApi.callArgOn; delegateToCalls("yield", false, "yield", function () { throw new Error(this.toString() + " cannot yield since it was not yet invoked."); }); // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode. spyApi.invokeCallback = spyApi.yield; delegateToCalls("yieldOn", false, "yieldOn", function () { throw new Error(this.toString() + " cannot yield since it was not yet invoked."); }); delegateToCalls("yieldTo", false, "yieldTo", function (property) { throw new Error(this.toString() + " cannot yield to '" + property + "' since it was not yet invoked."); }); delegateToCalls("yieldToOn", false, "yieldToOn", function (property) { throw new Error(this.toString() + " cannot yield to '" + property + "' since it was not yet invoked."); }); spyApi.formatters = { "c": function (spy) { return sinon.timesInWords(spy.callCount); }, "n": function (spy) { return spy.toString(); }, "C": function (spy) { var calls = []; for (var i = 0, l = spy.callCount; i < l; ++i) { var stringifiedCall = " " + spy.getCall(i).toString(); if (/\n/.test(calls[i - 1])) { stringifiedCall = "\n" + stringifiedCall; } push.call(calls, stringifiedCall); } return calls.length > 0 ? "\n" + calls.join("\n") : ""; }, "t": function (spy) { var objects = []; for (var i = 0, l = spy.callCount; i < l; ++i) { push.call(objects, sinon.format(spy.thisValues[i])); } return objects.join(", "); }, "*": function (spy, args) { var formatted = []; for (var i = 0, l = args.length; i < l; ++i) { push.call(formatted, sinon.format(args[i])); } return formatted.join(", "); } }; sinon.extend(spy, spyApi); spy.spyCall = sinon.spyCall; if (commonJSModule) { module.exports = spy; } else { sinon.spy = spy; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend match.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global module, require, sinon*/ /** * Spy calls * * @author Christian Johansen ([email protected]) * @author Maximilian Antoni ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen * Copyright (c) 2013 Maximilian Antoni */ "use strict"; (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function throwYieldError(proxy, text, args) { var msg = sinon.functionName(proxy) + text; if (args.length) { msg += " Received [" + slice.call(args).join(", ") + "]"; } throw new Error(msg); } var slice = Array.prototype.slice; var callProto = { calledOn: function calledOn(thisValue) { if (sinon.match && sinon.match.isMatcher(thisValue)) { return thisValue.test(this.thisValue); } return this.thisValue === thisValue; }, calledWith: function calledWith() { for (var i = 0, l = arguments.length; i < l; i += 1) { if (!sinon.deepEqual(arguments[i], this.args[i])) { return false; } } return true; }, calledWithMatch: function calledWithMatch() { for (var i = 0, l = arguments.length; i < l; i += 1) { var actual = this.args[i]; var expectation = arguments[i]; if (!sinon.match || !sinon.match(expectation).test(actual)) { return false; } } return true; }, calledWithExactly: function calledWithExactly() { return arguments.length == this.args.length && this.calledWith.apply(this, arguments); }, notCalledWith: function notCalledWith() { return !this.calledWith.apply(this, arguments); }, notCalledWithMatch: function notCalledWithMatch() { return !this.calledWithMatch.apply(this, arguments); }, returned: function returned(value) { return sinon.deepEqual(value, this.returnValue); }, threw: function threw(error) { if (typeof error === "undefined" || !this.exception) { return !!this.exception; } return this.exception === error || this.exception.name === error; }, calledWithNew: function calledWithNew(thisValue) { return this.thisValue instanceof this.proxy; }, calledBefore: function (other) { return this.callId < other.callId; }, calledAfter: function (other) { return this.callId > other.callId; }, callArg: function (pos) { this.args[pos](); }, callArgOn: function (pos, thisValue) { this.args[pos].apply(thisValue); }, callArgWith: function (pos) { this.callArgOnWith.apply(this, [pos, null].concat(slice.call(arguments, 1))); }, callArgOnWith: function (pos, thisValue) { var args = slice.call(arguments, 2); this.args[pos].apply(thisValue, args); }, "yield": function () { this.yieldOn.apply(this, [null].concat(slice.call(arguments, 0))); }, yieldOn: function (thisValue) { var args = this.args; for (var i = 0, l = args.length; i < l; ++i) { if (typeof args[i] === "function") { args[i].apply(thisValue, slice.call(arguments, 1)); return; } } throwYieldError(this.proxy, " cannot yield since no callback was passed.", args); }, yieldTo: function (prop) { this.yieldToOn.apply(this, [prop, null].concat(slice.call(arguments, 1))); }, yieldToOn: function (prop, thisValue) { var args = this.args; for (var i = 0, l = args.length; i < l; ++i) { if (args[i] && typeof args[i][prop] === "function") { args[i][prop].apply(thisValue, slice.call(arguments, 2)); return; } } throwYieldError(this.proxy, " cannot yield to '" + prop + "' since no callback was passed.", args); }, toString: function () { var callStr = this.proxy.toString() + "("; var args = []; for (var i = 0, l = this.args.length; i < l; ++i) { args.push(sinon.format(this.args[i])); } callStr = callStr + args.join(", ") + ")"; if (typeof this.returnValue != "undefined") { callStr += " => " + sinon.format(this.returnValue); } if (this.exception) { callStr += " !" + this.exception.name; if (this.exception.message) { callStr += "(" + this.exception.message + ")"; } } return callStr; } }; callProto.invokeCallback = callProto.yield; function createSpyCall(spy, thisValue, args, returnValue, exception, id) { if (typeof id !== "number") { throw new TypeError("Call id is not a number"); } var proxyCall = sinon.create(callProto); proxyCall.proxy = spy; proxyCall.thisValue = thisValue; proxyCall.args = args; proxyCall.returnValue = returnValue; proxyCall.exception = exception; proxyCall.callId = id; return proxyCall; }; createSpyCall.toString = callProto.toString; // used by mocks if (commonJSModule) { module.exports = createSpyCall; } else { sinon.spyCall = createSpyCall; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend spy.js */ /*jslint eqeqeq: false, onevar: false*/ /*global module, require, sinon*/ /** * Stub functions * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function stub(object, property, func) { if (!!func && typeof func != "function") { throw new TypeError("Custom stub should be function"); } var wrapper; if (func) { wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func; } else { wrapper = stub.create(); } if (!object && !property) { return sinon.stub.create(); } if (!property && !!object && typeof object == "object") { for (var prop in object) { if (typeof object[prop] === "function") { stub(object, prop); } } return object; } return sinon.wrapMethod(object, property, wrapper); } function getChangingValue(stub, property) { var index = stub.callCount - 1; var values = stub[property]; var prop = index in values ? values[index] : values[values.length - 1]; stub[property + "Last"] = prop; return prop; } function getCallback(stub, args) { var callArgAt = getChangingValue(stub, "callArgAts"); if (callArgAt < 0) { var callArgProp = getChangingValue(stub, "callArgProps"); for (var i = 0, l = args.length; i < l; ++i) { if (!callArgProp && typeof args[i] == "function") { return args[i]; } if (callArgProp && args[i] && typeof args[i][callArgProp] == "function") { return args[i][callArgProp]; } } return null; } return args[callArgAt]; } var join = Array.prototype.join; function getCallbackError(stub, func, args) { if (stub.callArgAtsLast < 0) { var msg; if (stub.callArgPropsLast) { msg = sinon.functionName(stub) + " expected to yield to '" + stub.callArgPropsLast + "', but no object with such a property was passed." } else { msg = sinon.functionName(stub) + " expected to yield, but no callback was passed." } if (args.length > 0) { msg += " Received [" + join.call(args, ", ") + "]"; } return msg; } return "argument at index " + stub.callArgAtsLast + " is not a function: " + func; } var nextTick = (function () { if (typeof process === "object" && typeof process.nextTick === "function") { return process.nextTick; } else if (typeof setImmediate === "function") { return setImmediate; } else { return function (callback) { setTimeout(callback, 0); }; } })(); function callCallback(stub, args) { if (stub.callArgAts.length > 0) { var func = getCallback(stub, args); if (typeof func != "function") { throw new TypeError(getCallbackError(stub, func, args)); } var callbackArguments = getChangingValue(stub, "callbackArguments"); var callbackContext = getChangingValue(stub, "callbackContexts"); if (stub.callbackAsync) { nextTick(function() { func.apply(callbackContext, callbackArguments); }); } else { func.apply(callbackContext, callbackArguments); } } } var uuid = 0; sinon.extend(stub, (function () { var slice = Array.prototype.slice, proto; function throwsException(error, message) { if (typeof error == "string") { this.exception = new Error(message || ""); this.exception.name = error; } else if (!error) { this.exception = new Error("Error"); } else { this.exception = error; } return this; } proto = { create: function create() { var functionStub = function () { callCallback(functionStub, arguments); if (functionStub.exception) { throw functionStub.exception; } else if (typeof functionStub.returnArgAt == 'number') { return arguments[functionStub.returnArgAt]; } else if (functionStub.returnThis) { return this; } return functionStub.returnValue; }; functionStub.id = "stub#" + uuid++; var orig = functionStub; functionStub = sinon.spy.create(functionStub); functionStub.func = orig; functionStub.callArgAts = []; functionStub.callbackArguments = []; functionStub.callbackContexts = []; functionStub.callArgProps = []; sinon.extend(functionStub, stub); functionStub._create = sinon.stub.create; functionStub.displayName = "stub"; functionStub.toString = sinon.functionToString; return functionStub; }, resetBehavior: function () { var i; this.callArgAts = []; this.callbackArguments = []; this.callbackContexts = []; this.callArgProps = []; delete this.returnValue; delete this.returnArgAt; this.returnThis = false; if (this.fakes) { for (i = 0; i < this.fakes.length; i++) { this.fakes[i].resetBehavior(); } } }, returns: function returns(value) { this.returnValue = value; return this; }, returnsArg: function returnsArg(pos) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } this.returnArgAt = pos; return this; }, returnsThis: function returnsThis() { this.returnThis = true; return this; }, "throws": throwsException, throwsException: throwsException, callsArg: function callsArg(pos) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } this.callArgAts.push(pos); this.callbackArguments.push([]); this.callbackContexts.push(undefined); this.callArgProps.push(undefined); return this; }, callsArgOn: function callsArgOn(pos, context) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAts.push(pos); this.callbackArguments.push([]); this.callbackContexts.push(context); this.callArgProps.push(undefined); return this; }, callsArgWith: function callsArgWith(pos) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } this.callArgAts.push(pos); this.callbackArguments.push(slice.call(arguments, 1)); this.callbackContexts.push(undefined); this.callArgProps.push(undefined); return this; }, callsArgOnWith: function callsArgWith(pos, context) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAts.push(pos); this.callbackArguments.push(slice.call(arguments, 2)); this.callbackContexts.push(context); this.callArgProps.push(undefined); return this; }, yields: function () { this.callArgAts.push(-1); this.callbackArguments.push(slice.call(arguments, 0)); this.callbackContexts.push(undefined); this.callArgProps.push(undefined); return this; }, yieldsOn: function (context) { if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAts.push(-1); this.callbackArguments.push(slice.call(arguments, 1)); this.callbackContexts.push(context); this.callArgProps.push(undefined); return this; }, yieldsTo: function (prop) { this.callArgAts.push(-1); this.callbackArguments.push(slice.call(arguments, 1)); this.callbackContexts.push(undefined); this.callArgProps.push(prop); return this; }, yieldsToOn: function (prop, context) { if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAts.push(-1); this.callbackArguments.push(slice.call(arguments, 2)); this.callbackContexts.push(context); this.callArgProps.push(prop); return this; } }; // create asynchronous versions of callsArg* and yields* methods for (var method in proto) { // need to avoid creating anotherasync versions of the newly added async methods if (proto.hasOwnProperty(method) && method.match(/^(callsArg|yields|thenYields$)/) && !method.match(/Async/)) { proto[method + 'Async'] = (function (syncFnName) { return function () { this.callbackAsync = true; return this[syncFnName].apply(this, arguments); }; })(method); } } return proto; }())); if (commonJSModule) { module.exports = stub; } else { sinon.stub = stub; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend stub.js */ /*jslint eqeqeq: false, onevar: false, nomen: false*/ /*global module, require, sinon*/ /** * Mock functions. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; var push = [].push; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function mock(object) { if (!object) { return sinon.expectation.create("Anonymous mock"); } return mock.create(object); } sinon.mock = mock; sinon.extend(mock, (function () { function each(collection, callback) { if (!collection) { return; } for (var i = 0, l = collection.length; i < l; i += 1) { callback(collection[i]); } } return { create: function create(object) { if (!object) { throw new TypeError("object is null"); } var mockObject = sinon.extend({}, mock); mockObject.object = object; delete mockObject.create; return mockObject; }, expects: function expects(method) { if (!method) { throw new TypeError("method is falsy"); } if (!this.expectations) { this.expectations = {}; this.proxies = []; } if (!this.expectations[method]) { this.expectations[method] = []; var mockObject = this; sinon.wrapMethod(this.object, method, function () { return mockObject.invokeMethod(method, this, arguments); }); push.call(this.proxies, method); } var expectation = sinon.expectation.create(method); push.call(this.expectations[method], expectation); return expectation; }, restore: function restore() { var object = this.object; each(this.proxies, function (proxy) { if (typeof object[proxy].restore == "function") { object[proxy].restore(); } }); }, verify: function verify() { var expectations = this.expectations || {}; var messages = [], met = []; each(this.proxies, function (proxy) { each(expectations[proxy], function (expectation) { if (!expectation.met()) { push.call(messages, expectation.toString()); } else { push.call(met, expectation.toString()); } }); }); this.restore(); if (messages.length > 0) { sinon.expectation.fail(messages.concat(met).join("\n")); } else { sinon.expectation.pass(messages.concat(met).join("\n")); } return true; }, invokeMethod: function invokeMethod(method, thisValue, args) { var expectations = this.expectations && this.expectations[method]; var length = expectations && expectations.length || 0, i; for (i = 0; i < length; i += 1) { if (!expectations[i].met() && expectations[i].allowsCall(thisValue, args)) { return expectations[i].apply(thisValue, args); } } var messages = [], available, exhausted = 0; for (i = 0; i < length; i += 1) { if (expectations[i].allowsCall(thisValue, args)) { available = available || expectations[i]; } else { exhausted += 1; } push.call(messages, " " + expectations[i].toString()); } if (exhausted === 0) { return available.apply(thisValue, args); } messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({ proxy: method, args: args })); sinon.expectation.fail(messages.join("\n")); } }; }())); var times = sinon.timesInWords; sinon.expectation = (function () { var slice = Array.prototype.slice; var _invoke = sinon.spy.invoke; function callCountInWords(callCount) { if (callCount == 0) { return "never called"; } else { return "called " + times(callCount); } } function expectedCallCountInWords(expectation) { var min = expectation.minCalls; var max = expectation.maxCalls; if (typeof min == "number" && typeof max == "number") { var str = times(min); if (min != max) { str = "at least " + str + " and at most " + times(max); } return str; } if (typeof min == "number") { return "at least " + times(min); } return "at most " + times(max); } function receivedMinCalls(expectation) { var hasMinLimit = typeof expectation.minCalls == "number"; return !hasMinLimit || expectation.callCount >= expectation.minCalls; } function receivedMaxCalls(expectation) { if (typeof expectation.maxCalls != "number") { return false; } return expectation.callCount == expectation.maxCalls; } return { minCalls: 1, maxCalls: 1, create: function create(methodName) { var expectation = sinon.extend(sinon.stub.create(), sinon.expectation); delete expectation.create; expectation.method = methodName; return expectation; }, invoke: function invoke(func, thisValue, args) { this.verifyCallAllowed(thisValue, args); return _invoke.apply(this, arguments); }, atLeast: function atLeast(num) { if (typeof num != "number") { throw new TypeError("'" + num + "' is not number"); } if (!this.limitsSet) { this.maxCalls = null; this.limitsSet = true; } this.minCalls = num; return this; }, atMost: function atMost(num) { if (typeof num != "number") { throw new TypeError("'" + num + "' is not number"); } if (!this.limitsSet) { this.minCalls = null; this.limitsSet = true; } this.maxCalls = num; return this; }, never: function never() { return this.exactly(0); }, once: function once() { return this.exactly(1); }, twice: function twice() { return this.exactly(2); }, thrice: function thrice() { return this.exactly(3); }, exactly: function exactly(num) { if (typeof num != "number") { throw new TypeError("'" + num + "' is not a number"); } this.atLeast(num); return this.atMost(num); }, met: function met() { return !this.failed && receivedMinCalls(this); }, verifyCallAllowed: function verifyCallAllowed(thisValue, args) { if (receivedMaxCalls(this)) { this.failed = true; sinon.expectation.fail(this.method + " already called " + times(this.maxCalls)); } if ("expectedThis" in this && this.expectedThis !== thisValue) { sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " + this.expectedThis); } if (!("expectedArguments" in this)) { return; } if (!args) { sinon.expectation.fail(this.method + " received no arguments, expected " + sinon.format(this.expectedArguments)); } if (args.length < this.expectedArguments.length) { sinon.expectation.fail(this.method + " received too few arguments (" + sinon.format(args) + "), expected " + sinon.format(this.expectedArguments)); } if (this.expectsExactArgCount && args.length != this.expectedArguments.length) { sinon.expectation.fail(this.method + " received too many arguments (" + sinon.format(args) + "), expected " + sinon.format(this.expectedArguments)); } for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) + ", expected " + sinon.format(this.expectedArguments)); } } }, allowsCall: function allowsCall(thisValue, args) { if (this.met() && receivedMaxCalls(this)) { return false; } if ("expectedThis" in this && this.expectedThis !== thisValue) { return false; } if (!("expectedArguments" in this)) { return true; } args = args || []; if (args.length < this.expectedArguments.length) { return false; } if (this.expectsExactArgCount && args.length != this.expectedArguments.length) { return false; } for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { return false; } } return true; }, withArgs: function withArgs() { this.expectedArguments = slice.call(arguments); return this; }, withExactArgs: function withExactArgs() { this.withArgs.apply(this, arguments); this.expectsExactArgCount = true; return this; }, on: function on(thisValue) { this.expectedThis = thisValue; return this; }, toString: function () { var args = (this.expectedArguments || []).slice(); if (!this.expectsExactArgCount) { push.call(args, "[...]"); } var callStr = sinon.spyCall.toString.call({ proxy: this.method || "anonymous mock expectation", args: args }); var message = callStr.replace(", [...", "[, ...") + " " + expectedCallCountInWords(this); if (this.met()) { return "Expectation met: " + message; } return "Expected " + message + " (" + callCountInWords(this.callCount) + ")"; }, verify: function verify() { if (!this.met()) { sinon.expectation.fail(this.toString()); } else { sinon.expectation.pass(this.toString()); } return true; }, pass: function(message) { sinon.assert.pass(message); }, fail: function (message) { var exception = new Error(message); exception.name = "ExpectationError"; throw exception; } }; }()); if (commonJSModule) { module.exports = mock; } else { sinon.mock = mock; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend stub.js * @depend mock.js */ /*jslint eqeqeq: false, onevar: false, forin: true*/ /*global module, require, sinon*/ /** * Collections of stubs, spies and mocks. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; var push = [].push; var hasOwnProperty = Object.prototype.hasOwnProperty; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function getFakes(fakeCollection) { if (!fakeCollection.fakes) { fakeCollection.fakes = []; } return fakeCollection.fakes; } function each(fakeCollection, method) { var fakes = getFakes(fakeCollection); for (var i = 0, l = fakes.length; i < l; i += 1) { if (typeof fakes[i][method] == "function") { fakes[i][method](); } } } function compact(fakeCollection) { var fakes = getFakes(fakeCollection); var i = 0; while (i < fakes.length) { fakes.splice(i, 1); } } var collection = { verify: function resolve() { each(this, "verify"); }, restore: function restore() { each(this, "restore"); compact(this); }, verifyAndRestore: function verifyAndRestore() { var exception; try { this.verify(); } catch (e) { exception = e; } this.restore(); if (exception) { throw exception; } }, add: function add(fake) { push.call(getFakes(this), fake); return fake; }, spy: function spy() { return this.add(sinon.spy.apply(sinon, arguments)); }, stub: function stub(object, property, value) { if (property) { var original = object[property]; if (typeof original != "function") { if (!hasOwnProperty.call(object, property)) { throw new TypeError("Cannot stub non-existent own property " + property); } object[property] = value; return this.add({ restore: function () { object[property] = original; } }); } } if (!property && !!object && typeof object == "object") { var stubbedObj = sinon.stub.apply(sinon, arguments); for (var prop in stubbedObj) { if (typeof stubbedObj[prop] === "function") { this.add(stubbedObj[prop]); } } return stubbedObj; } return this.add(sinon.stub.apply(sinon, arguments)); }, mock: function mock() { return this.add(sinon.mock.apply(sinon, arguments)); }, inject: function inject(obj) { var col = this; obj.spy = function () { return col.spy.apply(col, arguments); }; obj.stub = function () { return col.stub.apply(col, arguments); }; obj.mock = function () { return col.mock.apply(col, arguments); }; return obj; } }; if (commonJSModule) { module.exports = collection; } else { sinon.collection = collection; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend collection.js * @depend util/fake_timers.js * @depend util/fake_server_with_clock.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global require, module*/ /** * Manages fake collections as well as fake utilities such as Sinon's * timers and fake XHR implementation in one convenient object. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; if (typeof module == "object" && typeof require == "function") { var sinon = require("../sinon"); sinon.extend(sinon, require("./util/fake_timers")); } (function () { var push = [].push; function exposeValue(sandbox, config, key, value) { if (!value) { return; } if (config.injectInto) { config.injectInto[key] = value; } else { push.call(sandbox.args, value); } } function prepareSandboxFromConfig(config) { var sandbox = sinon.create(sinon.sandbox); if (config.useFakeServer) { if (typeof config.useFakeServer == "object") { sandbox.serverPrototype = config.useFakeServer; } sandbox.useFakeServer(); } if (config.useFakeTimers) { if (typeof config.useFakeTimers == "object") { sandbox.useFakeTimers.apply(sandbox, config.useFakeTimers); } else { sandbox.useFakeTimers(); } } return sandbox; } sinon.sandbox = sinon.extend(sinon.create(sinon.collection), { useFakeTimers: function useFakeTimers() { this.clock = sinon.useFakeTimers.apply(sinon, arguments); return this.add(this.clock); }, serverPrototype: sinon.fakeServer, useFakeServer: function useFakeServer() { var proto = this.serverPrototype || sinon.fakeServer; if (!proto || !proto.create) { return null; } this.server = proto.create(); return this.add(this.server); }, inject: function (obj) { sinon.collection.inject.call(this, obj); if (this.clock) { obj.clock = this.clock; } if (this.server) { obj.server = this.server; obj.requests = this.server.requests; } return obj; }, create: function (config) { if (!config) { return sinon.create(sinon.sandbox); } var sandbox = prepareSandboxFromConfig(config); sandbox.args = sandbox.args || []; var prop, value, exposed = sandbox.inject({}); if (config.properties) { for (var i = 0, l = config.properties.length; i < l; i++) { prop = config.properties[i]; value = exposed[prop] || prop == "sandbox" && sandbox; exposeValue(sandbox, config, prop, value); } } else { exposeValue(sandbox, config, "sandbox", value); } return sandbox; } }); sinon.sandbox.useFakeXMLHttpRequest = sinon.sandbox.useFakeServer; if (typeof module == "object" && typeof require == "function") { module.exports = sinon.sandbox; } }()); /* @depend ../sinon.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global module, require, sinon*/ /** * Match functions * * @author Maximilian Antoni ([email protected]) * @license BSD * * Copyright (c) 2012 Maximilian Antoni */ "use strict"; (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function assertType(value, type, name) { var actual = sinon.typeOf(value); if (actual !== type) { throw new TypeError("Expected type of " + name + " to be " + type + ", but was " + actual); } } var matcher = { toString: function () { return this.message; } }; function isMatcher(object) { return matcher.isPrototypeOf(object); } function matchObject(expectation, actual) { if (actual === null || actual === undefined) { return false; } for (var key in expectation) { if (expectation.hasOwnProperty(key)) { var exp = expectation[key]; var act = actual[key]; if (match.isMatcher(exp)) { if (!exp.test(act)) { return false; } } else if (sinon.typeOf(exp) === "object") { if (!matchObject(exp, act)) { return false; } } else if (!sinon.deepEqual(exp, act)) { return false; } } } return true; } matcher.or = function (m2) { if (!isMatcher(m2)) { throw new TypeError("Matcher expected"); } var m1 = this; var or = sinon.create(matcher); or.test = function (actual) { return m1.test(actual) || m2.test(actual); }; or.message = m1.message + ".or(" + m2.message + ")"; return or; }; matcher.and = function (m2) { if (!isMatcher(m2)) { throw new TypeError("Matcher expected"); } var m1 = this; var and = sinon.create(matcher); and.test = function (actual) { return m1.test(actual) && m2.test(actual); }; and.message = m1.message + ".and(" + m2.message + ")"; return and; }; var match = function (expectation, message) { var m = sinon.create(matcher); var type = sinon.typeOf(expectation); switch (type) { case "object": if (typeof expectation.test === "function") { m.test = function (actual) { return expectation.test(actual) === true; }; m.message = "match(" + sinon.functionName(expectation.test) + ")"; return m; } var str = []; for (var key in expectation) { if (expectation.hasOwnProperty(key)) { str.push(key + ": " + expectation[key]); } } m.test = function (actual) { return matchObject(expectation, actual); }; m.message = "match(" + str.join(", ") + ")"; break; case "number": m.test = function (actual) { return expectation == actual; }; break; case "string": m.test = function (actual) { if (typeof actual !== "string") { return false; } return actual.indexOf(expectation) !== -1; }; m.message = "match(\"" + expectation + "\")"; break; case "regexp": m.test = function (actual) { if (typeof actual !== "string") { return false; } return expectation.test(actual); }; break; case "function": m.test = expectation; if (message) { m.message = message; } else { m.message = "match(" + sinon.functionName(expectation) + ")"; } break; default: m.test = function (actual) { return sinon.deepEqual(expectation, actual); }; } if (!m.message) { m.message = "match(" + expectation + ")"; } return m; }; match.isMatcher = isMatcher; match.any = match(function () { return true; }, "any"); match.defined = match(function (actual) { return actual !== null && actual !== undefined; }, "defined"); match.truthy = match(function (actual) { return !!actual; }, "truthy"); match.falsy = match(function (actual) { return !actual; }, "falsy"); match.same = function (expectation) { return match(function (actual) { return expectation === actual; }, "same(" + expectation + ")"); }; match.typeOf = function (type) { assertType(type, "string", "type"); return match(function (actual) { return sinon.typeOf(actual) === type; }, "typeOf(\"" + type + "\")"); }; match.instanceOf = function (type) { assertType(type, "function", "type"); return match(function (actual) { return actual instanceof type; }, "instanceOf(" + sinon.functionName(type) + ")"); }; function createPropertyMatcher(propertyTest, messagePrefix) { return function (property, value) { assertType(property, "string", "property"); var onlyProperty = arguments.length === 1; var message = messagePrefix + "(\"" + property + "\""; if (!onlyProperty) { message += ", " + value; } message += ")"; return match(function (actual) { if (actual === undefined || actual === null || !propertyTest(actual, property)) { return false; } return onlyProperty || sinon.deepEqual(value, actual[property]); }, message); }; } match.has = createPropertyMatcher(function (actual, property) { if (typeof actual === "object") { return property in actual; } return actual[property] !== undefined; }, "has"); match.hasOwn = createPropertyMatcher(function (actual, property) { return actual.hasOwnProperty(property); }, "hasOwn"); match.bool = match.typeOf("boolean"); match.number = match.typeOf("number"); match.string = match.typeOf("string"); match.object = match.typeOf("object"); match.func = match.typeOf("function"); match.array = match.typeOf("array"); match.regexp = match.typeOf("regexp"); match.date = match.typeOf("date"); if (commonJSModule) { module.exports = match; } else { sinon.match = match; } }(typeof sinon == "object" && sinon || null)); /*jslint eqeqeq: false, onevar: false*/ /*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/ /** * Minimal Event interface implementation * * Original implementation by Sven Fuchs: https://gist.github.com/995028 * Modifications and tests by Christian Johansen. * * @author Sven Fuchs ([email protected]) * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2011 Sven Fuchs, Christian Johansen */ "use strict"; if (typeof sinon == "undefined") { this.sinon = {}; } (function () { var push = [].push; sinon.Event = function Event(type, bubbles, cancelable, target) { this.initEvent(type, bubbles, cancelable, target); }; sinon.Event.prototype = { initEvent: function(type, bubbles, cancelable, target) { this.type = type; this.bubbles = bubbles; this.cancelable = cancelable; this.target = target; }, stopPropagation: function () {}, preventDefault: function () { this.defaultPrevented = true; } }; sinon.EventTarget = { addEventListener: function addEventListener(event, listener, useCapture) { this.eventListeners = this.eventListeners || {}; this.eventListeners[event] = this.eventListeners[event] || []; push.call(this.eventListeners[event], listener); }, removeEventListener: function removeEventListener(event, listener, useCapture) { var listeners = this.eventListeners && this.eventListeners[event] || []; for (var i = 0, l = listeners.length; i < l; ++i) { if (listeners[i] == listener) { return listeners.splice(i, 1); } } }, dispatchEvent: function dispatchEvent(event) { var type = event.type; var listeners = this.eventListeners && this.eventListeners[type] || []; for (var i = 0; i < listeners.length; i++) { if (typeof listeners[i] == "function") { listeners[i].call(this, event); } else { listeners[i].handleEvent(event); } } return !!event.defaultPrevented; } }; }()); /** * @depend ../../sinon.js * @depend event.js */ /*jslint eqeqeq: false, onevar: false*/ /*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/ /** * Fake XMLHttpRequest object * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; if (typeof sinon == "undefined") { this.sinon = {}; } sinon.xhr = { XMLHttpRequest: this.XMLHttpRequest }; // wrapper for global (function(global) { var xhr = sinon.xhr; xhr.GlobalXMLHttpRequest = global.XMLHttpRequest; xhr.GlobalActiveXObject = global.ActiveXObject; xhr.supportsActiveX = typeof xhr.GlobalActiveXObject != "undefined"; xhr.supportsXHR = typeof xhr.GlobalXMLHttpRequest != "undefined"; xhr.workingXHR = xhr.supportsXHR ? xhr.GlobalXMLHttpRequest : xhr.supportsActiveX ? function() { return new xhr.GlobalActiveXObject("MSXML2.XMLHTTP.3.0") } : false; /*jsl:ignore*/ var unsafeHeaders = { "Accept-Charset": true, "Accept-Encoding": true, "Connection": true, "Content-Length": true, "Cookie": true, "Cookie2": true, "Content-Transfer-Encoding": true, "Date": true, "Expect": true, "Host": true, "Keep-Alive": true, "Referer": true, "TE": true, "Trailer": true, "Transfer-Encoding": true, "Upgrade": true, "User-Agent": true, "Via": true }; /*jsl:end*/ function FakeXMLHttpRequest() { this.readyState = FakeXMLHttpRequest.UNSENT; this.requestHeaders = {}; this.requestBody = null; this.status = 0; this.statusText = ""; var xhr = this; var events = ["loadstart", "load", "abort", "loadend"]; function addEventListener(eventName) { xhr.addEventListener(eventName, function (event) { var listener = xhr["on" + eventName]; if (listener && typeof listener == "function") { listener(event); } }); } for (var i = events.length - 1; i >= 0; i--) { addEventListener(events[i]); } if (typeof FakeXMLHttpRequest.onCreate == "function") { FakeXMLHttpRequest.onCreate(this); } } function verifyState(xhr) { if (xhr.readyState !== FakeXMLHttpRequest.OPENED) { throw new Error("INVALID_STATE_ERR"); } if (xhr.sendFlag) { throw new Error("INVALID_STATE_ERR"); } } // filtering to enable a white-list version of Sinon FakeXhr, // where whitelisted requests are passed through to real XHR function each(collection, callback) { if (!collection) return; for (var i = 0, l = collection.length; i < l; i += 1) { callback(collection[i]); } } function some(collection, callback) { for (var index = 0; index < collection.length; index++) { if(callback(collection[index]) === true) return true; }; return false; } // largest arity in XHR is 5 - XHR#open var apply = function(obj,method,args) { switch(args.length) { case 0: return obj[method](); case 1: return obj[method](args[0]); case 2: return obj[method](args[0],args[1]); case 3: return obj[method](args[0],args[1],args[2]); case 4: return obj[method](args[0],args[1],args[2],args[3]); case 5: return obj[method](args[0],args[1],args[2],args[3],args[4]); }; }; FakeXMLHttpRequest.filters = []; FakeXMLHttpRequest.addFilter = function(fn) { this.filters.push(fn) }; var IE6Re = /MSIE 6/; FakeXMLHttpRequest.defake = function(fakeXhr,xhrArgs) { var xhr = new sinon.xhr.workingXHR(); each(["open","setRequestHeader","send","abort","getResponseHeader", "getAllResponseHeaders","addEventListener","overrideMimeType","removeEventListener"], function(method) { fakeXhr[method] = function() { return apply(xhr,method,arguments); }; }); var copyAttrs = function(args) { each(args, function(attr) { try { fakeXhr[attr] = xhr[attr] } catch(e) { if(!IE6Re.test(navigator.userAgent)) throw e; } }); }; var stateChange = function() { fakeXhr.readyState = xhr.readyState; if(xhr.readyState >= FakeXMLHttpRequest.HEADERS_RECEIVED) { copyAttrs(["status","statusText"]); } if(xhr.readyState >= FakeXMLHttpRequest.LOADING) { copyAttrs(["responseText"]); } if(xhr.readyState === FakeXMLHttpRequest.DONE) { copyAttrs(["responseXML"]); } if(fakeXhr.onreadystatechange) fakeXhr.onreadystatechange.call(fakeXhr); }; if(xhr.addEventListener) { for(var event in fakeXhr.eventListeners) { if(fakeXhr.eventListeners.hasOwnProperty(event)) { each(fakeXhr.eventListeners[event],function(handler) { xhr.addEventListener(event, handler); }); } } xhr.addEventListener("readystatechange",stateChange); } else { xhr.onreadystatechange = stateChange; } apply(xhr,"open",xhrArgs); }; FakeXMLHttpRequest.useFilters = false; function verifyRequestSent(xhr) { if (xhr.readyState == FakeXMLHttpRequest.DONE) { throw new Error("Request done"); } } function verifyHeadersReceived(xhr) { if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) { throw new Error("No headers received"); } } function verifyResponseBodyType(body) { if (typeof body != "string") { var error = new Error("Attempted to respond to fake XMLHttpRequest with " + body + ", which is not a string."); error.name = "InvalidBodyException"; throw error; } } sinon.extend(FakeXMLHttpRequest.prototype, sinon.EventTarget, { async: true, open: function open(method, url, async, username, password) { this.method = method; this.url = url; this.async = typeof async == "boolean" ? async : true; this.username = username; this.password = password; this.responseText = null; this.responseXML = null; this.requestHeaders = {}; this.sendFlag = false; if(sinon.FakeXMLHttpRequest.useFilters === true) { var xhrArgs = arguments; var defake = some(FakeXMLHttpRequest.filters,function(filter) { return filter.apply(this,xhrArgs) }); if (defake) { return sinon.FakeXMLHttpRequest.defake(this,arguments); } } this.readyStateChange(FakeXMLHttpRequest.OPENED); }, readyStateChange: function readyStateChange(state) { this.readyState = state; if (typeof this.onreadystatechange == "function") { try { this.onreadystatechange(); } catch (e) { sinon.logError("Fake XHR onreadystatechange handler", e); } } this.dispatchEvent(new sinon.Event("readystatechange")); switch (this.readyState) { case FakeXMLHttpRequest.DONE: this.dispatchEvent(new sinon.Event("load", false, false, this)); this.dispatchEvent(new sinon.Event("loadend", false, false, this)); break; } }, setRequestHeader: function setRequestHeader(header, value) { verifyState(this); if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) { throw new Error("Refused to set unsafe header \"" + header + "\""); } if (this.requestHeaders[header]) { this.requestHeaders[header] += "," + value; } else { this.requestHeaders[header] = value; } }, // Helps testing setResponseHeaders: function setResponseHeaders(headers) { this.responseHeaders = {}; for (var header in headers) { if (headers.hasOwnProperty(header)) { this.responseHeaders[header] = headers[header]; } } if (this.async) { this.readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED); } else { this.readyState = FakeXMLHttpRequest.HEADERS_RECEIVED; } }, // Currently treats ALL data as a DOMString (i.e. no Document) send: function send(data) { verifyState(this); if (!/^(get|head)$/i.test(this.method)) { if (this.requestHeaders["Content-Type"]) { var value = this.requestHeaders["Content-Type"].split(";"); this.requestHeaders["Content-Type"] = value[0] + ";charset=utf-8"; } else { this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; } this.requestBody = data; } this.errorFlag = false; this.sendFlag = this.async; this.readyStateChange(FakeXMLHttpRequest.OPENED); if (typeof this.onSend == "function") { this.onSend(this); } this.dispatchEvent(new sinon.Event("loadstart", false, false, this)); }, abort: function abort() { this.aborted = true; this.responseText = null; this.errorFlag = true; this.requestHeaders = {}; if (this.readyState > sinon.FakeXMLHttpRequest.UNSENT && this.sendFlag) { this.readyStateChange(sinon.FakeXMLHttpRequest.DONE); this.sendFlag = false; } this.readyState = sinon.FakeXMLHttpRequest.UNSENT; this.dispatchEvent(new sinon.Event("abort", false, false, this)); if (typeof this.onerror === "function") { this.onerror(); } }, getResponseHeader: function getResponseHeader(header) { if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { return null; } if (/^Set-Cookie2?$/i.test(header)) { return null; } header = header.toLowerCase(); for (var h in this.responseHeaders) { if (h.toLowerCase() == header) { return this.responseHeaders[h]; } } return null; }, getAllResponseHeaders: function getAllResponseHeaders() { if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { return ""; } var headers = ""; for (var header in this.responseHeaders) { if (this.responseHeaders.hasOwnProperty(header) && !/^Set-Cookie2?$/i.test(header)) { headers += header + ": " + this.responseHeaders[header] + "\r\n"; } } return headers; }, setResponseBody: function setResponseBody(body) { verifyRequestSent(this); verifyHeadersReceived(this); verifyResponseBodyType(body); var chunkSize = this.chunkSize || 10; var index = 0; this.responseText = ""; do { if (this.async) { this.readyStateChange(FakeXMLHttpRequest.LOADING); } this.responseText += body.substring(index, index + chunkSize); index += chunkSize; } while (index < body.length); var type = this.getResponseHeader("Content-Type"); if (this.responseText && (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) { try { this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText); } catch (e) { // Unable to parse XML - no biggie } } if (this.async) { this.readyStateChange(FakeXMLHttpRequest.DONE); } else { this.readyState = FakeXMLHttpRequest.DONE; } }, respond: function respond(status, headers, body) { this.setResponseHeaders(headers || {}); this.status = typeof status == "number" ? status : 200; this.statusText = FakeXMLHttpRequest.statusCodes[this.status]; this.setResponseBody(body || ""); if (typeof this.onload === "function"){ this.onload(); } } }); sinon.extend(FakeXMLHttpRequest, { UNSENT: 0, OPENED: 1, HEADERS_RECEIVED: 2, LOADING: 3, DONE: 4 }); // Borrowed from JSpec FakeXMLHttpRequest.parseXML = function parseXML(text) { var xmlDoc; if (typeof DOMParser != "undefined") { var parser = new DOMParser(); xmlDoc = parser.parseFromString(text, "text/xml"); } else { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(text); } return xmlDoc; }; FakeXMLHttpRequest.statusCodes = { 100: "Continue", 101: "Switching Protocols", 200: "OK", 201: "Created", 202: "Accepted", 203: "Non-Authoritative Information", 204: "No Content", 205: "Reset Content", 206: "Partial Content", 300: "Multiple Choice", 301: "Moved Permanently", 302: "Found", 303: "See Other", 304: "Not Modified", 305: "Use Proxy", 307: "Temporary Redirect", 400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 406: "Not Acceptable", 407: "Proxy Authentication Required", 408: "Request Timeout", 409: "Conflict", 410: "Gone", 411: "Length Required", 412: "Precondition Failed", 413: "Request Entity Too Large", 414: "Request-URI Too Long", 415: "Unsupported Media Type", 416: "Requested Range Not Satisfiable", 417: "Expectation Failed", 422: "Unprocessable Entity", 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout", 505: "HTTP Version Not Supported" }; sinon.useFakeXMLHttpRequest = function () { sinon.FakeXMLHttpRequest.restore = function restore(keepOnCreate) { if (xhr.supportsXHR) { global.XMLHttpRequest = xhr.GlobalXMLHttpRequest; } if (xhr.supportsActiveX) { global.ActiveXObject = xhr.GlobalActiveXObject; } delete sinon.FakeXMLHttpRequest.restore; if (keepOnCreate !== true) { delete sinon.FakeXMLHttpRequest.onCreate; } }; if (xhr.supportsXHR) { global.XMLHttpRequest = sinon.FakeXMLHttpRequest; } if (xhr.supportsActiveX) { global.ActiveXObject = function ActiveXObject(objId) { if (objId == "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId)) { return new sinon.FakeXMLHttpRequest(); } return new xhr.GlobalActiveXObject(objId); }; } return sinon.FakeXMLHttpRequest; }; sinon.FakeXMLHttpRequest = FakeXMLHttpRequest; })(this); if (typeof module == "object" && typeof require == "function") { module.exports = sinon; } /*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/ /*global module, require, window*/ /** * Fake timer API * setTimeout * setInterval * clearTimeout * clearInterval * tick * reset * Date * * Inspired by jsUnitMockTimeOut from JsUnit * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; if (typeof sinon == "undefined") { var sinon = {}; } (function (global) { var id = 1; function addTimer(args, recurring) { if (args.length === 0) { throw new Error("Function requires at least 1 parameter"); } var toId = id++; var delay = args[1] || 0; if (!this.timeouts) { this.timeouts = {}; } this.timeouts[toId] = { id: toId, func: args[0], callAt: this.now + delay, invokeArgs: Array.prototype.slice.call(args, 2) }; if (recurring === true) { this.timeouts[toId].interval = delay; } return toId; } function parseTime(str) { if (!str) { return 0; } var strings = str.split(":"); var l = strings.length, i = l; var ms = 0, parsed; if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) { throw new Error("tick only understands numbers and 'h:m:s'"); } while (i--) { parsed = parseInt(strings[i], 10); if (parsed >= 60) { throw new Error("Invalid time " + str); } ms += parsed * Math.pow(60, (l - i - 1)); } return ms * 1000; } function createObject(object) { var newObject; if (Object.create) { newObject = Object.create(object); } else { var F = function () {}; F.prototype = object; newObject = new F(); } newObject.Date.clock = newObject; return newObject; } sinon.clock = { now: 0, create: function create(now) { var clock = createObject(this); if (typeof now == "number") { clock.now = now; } if (!!now && typeof now == "object") { throw new TypeError("now should be milliseconds since UNIX epoch"); } return clock; }, setTimeout: function setTimeout(callback, timeout) { return addTimer.call(this, arguments, false); }, clearTimeout: function clearTimeout(timerId) { if (!this.timeouts) { this.timeouts = []; } if (timerId in this.timeouts) { delete this.timeouts[timerId]; } }, setInterval: function setInterval(callback, timeout) { return addTimer.call(this, arguments, true); }, clearInterval: function clearInterval(timerId) { this.clearTimeout(timerId); }, tick: function tick(ms) { ms = typeof ms == "number" ? ms : parseTime(ms); var tickFrom = this.now, tickTo = this.now + ms, previous = this.now; var timer = this.firstTimerInRange(tickFrom, tickTo); var firstException; while (timer && tickFrom <= tickTo) { if (this.timeouts[timer.id]) { tickFrom = this.now = timer.callAt; try { this.callTimer(timer); } catch (e) { firstException = firstException || e; } } timer = this.firstTimerInRange(previous, tickTo); previous = tickFrom; } this.now = tickTo; if (firstException) { throw firstException; } return this.now; }, firstTimerInRange: function (from, to) { var timer, smallest, originalTimer; for (var id in this.timeouts) { if (this.timeouts.hasOwnProperty(id)) { if (this.timeouts[id].callAt < from || this.timeouts[id].callAt > to) { continue; } if (!smallest || this.timeouts[id].callAt < smallest) { originalTimer = this.timeouts[id]; smallest = this.timeouts[id].callAt; timer = { func: this.timeouts[id].func, callAt: this.timeouts[id].callAt, interval: this.timeouts[id].interval, id: this.timeouts[id].id, invokeArgs: this.timeouts[id].invokeArgs }; } } } return timer || null; }, callTimer: function (timer) { if (typeof timer.interval == "number") { this.timeouts[timer.id].callAt += timer.interval; } else { delete this.timeouts[timer.id]; } try { if (typeof timer.func == "function") { timer.func.apply(null, timer.invokeArgs); } else { eval(timer.func); } } catch (e) { var exception = e; } if (!this.timeouts[timer.id]) { if (exception) { throw exception; } return; } if (exception) { throw exception; } }, reset: function reset() { this.timeouts = {}; }, Date: (function () { var NativeDate = Date; function ClockDate(year, month, date, hour, minute, second, ms) { // Defensive and verbose to avoid potential harm in passing // explicit undefined when user does not pass argument switch (arguments.length) { case 0: return new NativeDate(ClockDate.clock.now); case 1: return new NativeDate(year); case 2: return new NativeDate(year, month); case 3: return new NativeDate(year, month, date); case 4: return new NativeDate(year, month, date, hour); case 5: return new NativeDate(year, month, date, hour, minute); case 6: return new NativeDate(year, month, date, hour, minute, second); default: return new NativeDate(year, month, date, hour, minute, second, ms); } } return mirrorDateProperties(ClockDate, NativeDate); }()) }; function mirrorDateProperties(target, source) { if (source.now) { target.now = function now() { return target.clock.now; }; } else { delete target.now; } if (source.toSource) { target.toSource = function toSource() { return source.toSource(); }; } else { delete target.toSource; } target.toString = function toString() { return source.toString(); }; target.prototype = source.prototype; target.parse = source.parse; target.UTC = source.UTC; target.prototype.toUTCString = source.prototype.toUTCString; return target; } var methods = ["Date", "setTimeout", "setInterval", "clearTimeout", "clearInterval"]; function restore() { var method; for (var i = 0, l = this.methods.length; i < l; i++) { method = this.methods[i]; if (global[method].hadOwnProperty) { global[method] = this["_" + method]; } else { delete global[method]; } } // Prevent multiple executions which will completely remove these props this.methods = []; } function stubGlobal(method, clock) { clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(global, method); clock["_" + method] = global[method]; if (method == "Date") { var date = mirrorDateProperties(clock[method], global[method]); global[method] = date; } else { global[method] = function () { return clock[method].apply(clock, arguments); }; for (var prop in clock[method]) { if (clock[method].hasOwnProperty(prop)) { global[method][prop] = clock[method][prop]; } } } global[method].clock = clock; } sinon.useFakeTimers = function useFakeTimers(now) { var clock = sinon.clock.create(now); clock.restore = restore; clock.methods = Array.prototype.slice.call(arguments, typeof now == "number" ? 1 : 0); if (clock.methods.length === 0) { clock.methods = methods; } for (var i = 0, l = clock.methods.length; i < l; i++) { stubGlobal(clock.methods[i], clock); } return clock; }; }(typeof global != "undefined" && typeof global !== "function" ? global : this)); sinon.timers = { setTimeout: setTimeout, clearTimeout: clearTimeout, setInterval: setInterval, clearInterval: clearInterval, Date: Date }; if (typeof module == "object" && typeof require == "function") { module.exports = sinon; } /** * @depend fake_xml_http_request.js */ /*jslint eqeqeq: false, onevar: false, regexp: false, plusplus: false*/ /*global module, require, window*/ /** * The Sinon "server" mimics a web server that receives requests from * sinon.FakeXMLHttpRequest and provides an API to respond to those requests, * both synchronously and asynchronously. To respond synchronuously, canned * answers have to be provided upfront. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; if (typeof sinon == "undefined") { var sinon = {}; } sinon.fakeServer = (function () { var push = [].push; function F() {} function create(proto) { F.prototype = proto; return new F(); } function responseArray(handler) { var response = handler; if (Object.prototype.toString.call(handler) != "[object Array]") { response = [200, {}, handler]; } if (typeof response[2] != "string") { throw new TypeError("Fake server response body should be string, but was " + typeof response[2]); } return response; } var wloc = typeof window !== "undefined" ? window.location : {}; var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host); function matchOne(response, reqMethod, reqUrl) { var rmeth = response.method; var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase(); var url = response.url; var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl)); return matchMethod && matchUrl; } function match(response, request) { var requestMethod = this.getHTTPMethod(request); var requestUrl = request.url; if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) { requestUrl = requestUrl.replace(rCurrLoc, ""); } if (matchOne(response, this.getHTTPMethod(request), requestUrl)) { if (typeof response.response == "function") { var ru = response.url; var args = [request].concat(!ru ? [] : requestUrl.match(ru).slice(1)); return response.response.apply(response, args); } return true; } return false; } function log(response, request) { var str; str = "Request:\n" + sinon.format(request) + "\n\n"; str += "Response:\n" + sinon.format(response) + "\n\n"; sinon.log(str); } return { create: function () { var server = create(this); this.xhr = sinon.useFakeXMLHttpRequest(); server.requests = []; this.xhr.onCreate = function (xhrObj) { server.addRequest(xhrObj); }; return server; }, addRequest: function addRequest(xhrObj) { var server = this; push.call(this.requests, xhrObj); xhrObj.onSend = function () { server.handleRequest(this); }; if (this.autoRespond && !this.responding) { setTimeout(function () { server.responding = false; server.respond(); }, this.autoRespondAfter || 10); this.responding = true; } }, getHTTPMethod: function getHTTPMethod(request) { if (this.fakeHTTPMethods && /post/i.test(request.method)) { var matches = (request.requestBody || "").match(/_method=([^\b;]+)/); return !!matches ? matches[1] : request.method; } return request.method; }, handleRequest: function handleRequest(xhr) { if (xhr.async) { if (!this.queue) { this.queue = []; } push.call(this.queue, xhr); } else { this.processRequest(xhr); } }, respondWith: function respondWith(method, url, body) { if (arguments.length == 1 && typeof method != "function") { this.response = responseArray(method); return; } if (!this.responses) { this.responses = []; } if (arguments.length == 1) { body = method; url = method = null; } if (arguments.length == 2) { body = url; url = method; method = null; } push.call(this.responses, { method: method, url: url, response: typeof body == "function" ? body : responseArray(body) }); }, respond: function respond() { if (arguments.length > 0) this.respondWith.apply(this, arguments); var queue = this.queue || []; var request; while(request = queue.shift()) { this.processRequest(request); } }, processRequest: function processRequest(request) { try { if (request.aborted) { return; } var response = this.response || [404, {}, ""]; if (this.responses) { for (var i = 0, l = this.responses.length; i < l; i++) { if (match.call(this, this.responses[i], request)) { response = this.responses[i].response; break; } } } if (request.readyState != 4) { log(response, request); request.respond(response[0], response[1], response[2]); } } catch (e) { sinon.logError("Fake server request processing", e); } }, restore: function restore() { return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments); } }; }()); if (typeof module == "object" && typeof require == "function") { module.exports = sinon; } /** * @depend fake_server.js * @depend fake_timers.js */ /*jslint browser: true, eqeqeq: false, onevar: false*/ /*global sinon*/ /** * Add-on for sinon.fakeServer that automatically handles a fake timer along with * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead, * it polls the object for completion with setInterval. Dispite the direct * motivation, there is nothing jQuery-specific in this file, so it can be used * in any environment where the ajax implementation depends on setInterval or * setTimeout. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ "use strict"; (function () { function Server() {} Server.prototype = sinon.fakeServer; sinon.fakeServerWithClock = new Server(); sinon.fakeServerWithClock.addRequest = function addRequest(xhr) { if (xhr.async) { if (typeof setTimeout.clock == "object") { this.clock = setTimeout.clock; } else { this.clock = sinon.useFakeTimers(); this.resetClock = true; } if (!this.longestTimeout) { var clockSetTimeout = this.clock.setTimeout; var clockSetInterval = this.clock.setInterval; var server = this; this.clock.setTimeout = function (fn, timeout) { server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); return clockSetTimeout.apply(this, arguments); }; this.clock.setInterval = function (fn, timeout) { server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); return clockSetInterval.apply(this, arguments); }; } } return sinon.fakeServer.addRequest.call(this, xhr); }; sinon.fakeServerWithClock.respond = function respond() { var returnVal = sinon.fakeServer.respond.apply(this, arguments); if (this.clock) { this.clock.tick(this.longestTimeout || 0); this.longestTimeout = 0; if (this.resetClock) { this.clock.restore(); this.resetClock = false; } } return returnVal; }; sinon.fakeServerWithClock.restore = function restore() { if (this.clock) { this.clock.restore(); } return sinon.fakeServer.restore.apply(this, arguments); }; }()); // Based on seedrandom.js version 2.2. // Original author: David Bau // Date: 2013 Jun 15 // // LICENSE (BSD): // // Copyright 2013 David Bau, all rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of this module nor the names of its contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // (typeof global === "object" ? global : this).seedRandom = (function (pool, math, width, chunks, digits) { var startdenom = math.pow(width, chunks), significance = math.pow(2, digits), overflow = significance * 2, mask = width - 1; function ARC4(key) { var t, keylen = key.length, me = this, i = 0, j = me.i = me.j = 0, s = me.S = []; if (!keylen) { key = [keylen++]; } while (i < width) { s[i] = i++; } for (i = 0; i < width; i++) { s[i] = s[j = mask & (j + key[i % keylen] + (t = s[i]))]; s[j] = t; } (me.g = function(count) { var t, r = 0, i = me.i, j = me.j, s = me.S; while (count--) { t = s[i = mask & (i + 1)]; r = r * width + s[mask & ((s[i] = s[j = mask & (j + t)]) + (s[j] = t))]; } me.i = i; me.j = j; return r; })(width); } function flatten(obj, depth) { var result = [], typ = (typeof obj)[0], prop; if (depth && typ == 'o') { for (prop in obj) { try { result.push(flatten(obj[prop], depth - 1)); } catch (e) {} } } return (result.length ? result : typ == 's' ? obj : obj + '\0'); } function mixkey(seed, key) { var stringseed = seed + '', smear, j = 0; while (j < stringseed.length) { key[mask & j] = mask & ((smear ^= key[mask & j] * 19) + stringseed.charCodeAt(j++)); } return tostring(key); } function tostring(a) { return String.fromCharCode.apply(0, a); } mixkey(math.random(), pool); return function(seed, use_entropy) { var key = []; var shortseed = mixkey(flatten( use_entropy ? [seed, tostring(pool)] : typeof seed !== "undefined" ? seed : [new Date().getTime(), pool], 3), key); var arc4 = new ARC4(key); mixkey(tostring(arc4.S), pool); var random = function() { var n = arc4.g(chunks), d = startdenom, x = 0; while (n < significance) { n = (n + x) * width; d *= width; x = arc4.g(1); } while (n >= overflow) { n /= 2; d /= 2; x >>>= 1; } return (n + x) / d; }; random.seed = shortseed; return random; }; }([], Math, 256, 6, 52)); ((typeof define === "function" && define.amd && function (m) { define("buster-test/browser-env", ["lodash"], m); }) || (typeof module === "object" && typeof require === "function" && function (m) { module.exports = m(require("lodash")); }) || function (m) { this.buster = this.buster || {}; this.buster.browserEnv = m(this._); })(function (_) { "use strict"; function BrowserEnv(rootElement) { this.element = rootElement; this.originalContent = ""; } BrowserEnv.prototype = { create: function (rootElement) { return new BrowserEnv(rootElement); }, listen: function (runner) { var clear = _.bind(this.clear, this); runner.on("suite:start", _.bind(function () { this.originalContent = this.element.innerHTML; }, this)); runner.on("test:success", clear); runner.on("test:failure", clear); runner.on("test:error", clear); runner.on("test:timeout", clear); }, clear: function () { this.element.innerHTML = this.originalContent; } }; return BrowserEnv.prototype; }); ((typeof define === "function" && define.amd && function (m) { define("buster-test/test-context", ["bane", "when", "lodash"], m); }) || (typeof module === "object" && typeof require === "function" && function (m) { module.exports = m(require("bane"), require("when"), require("lodash")); }) || function (m) { this.buster = this.buster || {}; this.buster.testContext = m(this.bane, this.when, this._); })(function (bane, when, _) { "use strict"; var bctx = bane.createEventEmitter(); function empty(context) { return context.tests.length === 0 && context.contexts.length === 0; } function filterContexts(contexts, filter, prefix) { return _.reduce(contexts, function (filtered, context) { var ctx = bctx.filter(context, filter, prefix); if (ctx.tests.length > 0 || ctx.contexts.length > 0) { filtered.push(ctx); } return filtered; }, []); } function filterTests(tests, filter, prefix) { return _.reduce(tests, function (filtered, test) { if (!filter || filter.test(prefix + test.name)) { filtered.push(test); } return filtered; }, []); } function makeFilter(filter) { if (typeof filter === "string") { return new RegExp(filter, "i"); } if (Object.prototype.toString.call(filter) !== "[object Array]") { return filter; } return { test: function (string) { return filter.length === 0 || _.some(filter, function (f) { return new RegExp(f).test(string); }); } }; } function parse(context) { if (!context.tests && typeof context.parse === "function") { return context.parse(); } return context; } function compile(contexts, filter) { return _.reduce(contexts, function (compiled, ctx) { if (when.isPromise(ctx)) { var deferred = when.defer(); ctx.then(function (context) { deferred.resolve(bctx.filter(parse(context), filter)); }); deferred.promise.name = ctx.name; compiled.push(deferred.promise); } else { ctx = bctx.filter(parse(ctx), filter); if (!empty(ctx)) { compiled.push(ctx); } } return compiled; }, []); } function filter(ctx, filterContent, name) { filterContent = makeFilter(filterContent); name = (name || "") + ctx.name + " "; return _.extend({}, ctx, { tests: filterTests(ctx.tests || [], filterContent, name), contexts: filterContexts(ctx.contexts || [], filterContent, name) }); } bctx.compile = compile; bctx.filter = filter; return bctx; }); ((typeof define === "function" && define.amd && function (m) { define("buster-test/spec", ["lodash", "when", "buster-test/test-context"], m); }) || (typeof module === "object" && typeof require === "function" && function (m) { module.exports = m(require("lodash"), require("when"), require("./test-context")); }) || function (m) { this.buster.spec = m(this._, this.when, this.buster.testContext); })(function (_, when, testContext) { "use strict"; var current = []; var bspec = {}; var bddNames = { contextSetUp: "beforeAll", contextTearDown: "afterAll" }; function supportRequirement(property) { return function (requirements) { return { describe: function () { var context = bspec.describe.apply(bspec, arguments); context[property] = requirements; return context; } }; }; } bspec.ifAllSupported = supportRequirement("requiresSupportForAll"); bspec.ifAnySupported = supportRequirement("requiresSupportForAny"); bspec.ifSupported = bspec.ifAllSupported; function addContext(parent, name, spec) { var context = bspec.describe.context.create(name, spec, parent).parse(); parent.contexts.push(context); return context; } function createContext(name, spec) { return bspec.describe.context.create(name, spec).parse(); } function asyncContext(name, callback) { var d = when.defer(); callback(function (spec) { d.resolver.resolve(createContext(name, spec)); }); d.promise.name = name; testContext.emit("create", d.promise); return d.promise; } var FOCUS_ROCKET = /^\s*=>\s*/; function markFocused(block, parent) { var focused = block.focused || (parent && parent.forceFocus); block.focused = focused || FOCUS_ROCKET.test(block.name); block.name = block.name.replace(FOCUS_ROCKET, ""); while (parent) { parent.focused = parent.focused || block.focused; parent = parent.parent; } } bspec.describe = function (name, spec) { if (current.length > 0) { return addContext(current[current.length - 1], name, spec); } if (spec && spec.length > 0) { return asyncContext(name, spec); } var context = createContext(name, spec); testContext.emit("create", context); return context; }; function markDeferred(spec, func) { spec.deferred = typeof func !== "function"; if (!spec.deferred && /^\/\//.test(spec.name)) { spec.deferred = true; spec.name = spec.name.replace(/^\/\/\s*/, ""); } spec.comment = spec.deferred ? func : ""; } bspec.it = function (name, func, extra) { var context = current[current.length - 1]; var spec = { name: name, func: arguments.length === 3 ? extra : func, context: context }; markDeferred(spec, func); spec.deferred = spec.deferred || context.deferred; markFocused(spec, context); context.tests.push(spec); return spec; }; bspec.itEventually = function (name, comment, func) { if (typeof comment === "function") { func = comment; comment = ""; } return bspec.it(name, comment, func); }; bspec.before = bspec.beforeEach = function (func) { var context = current[current.length - 1]; context.setUp = func; }; bspec.after = bspec.afterEach = function (func) { var context = current[current.length - 1]; context.tearDown = func; }; bspec.beforeAll = function (func) { var context = current[current.length - 1]; context.contextSetUp = func; }; bspec.afterAll = function (func) { var context = current[current.length - 1]; context.contextTearDown = func; }; function F() {} function create(object) { F.prototype = object; return new F(); } bspec.describe.context = { create: function (name, spec, parent) { if (!name || typeof name !== "string") { throw new Error("Spec name required"); } if (!spec || typeof spec !== "function") { throw new Error("spec should be a function"); } var context = create(this); context.name = name; context.parent = parent; context.spec = spec; markDeferred(context, spec); if (parent) { context.deferred = context.deferred || parent.deferred; } markFocused(context, parent); context.forceFocus = context.focused; return context; }, parse: function () { if (!this.spec) { return this; } this.testCase = { before: bspec.before, beforeEach: bspec.beforeEach, beforeAll: bspec.beforeAll, after: bspec.after, afterEach: bspec.afterEach, afterAll: bspec.afterAll, it: bspec.it, itEventually: bspec.itEventually, describe: bspec.describe, name: function (thing) { return bddNames[thing] || thing; } }; this.tests = []; current.push(this); this.contexts = []; this.spec.call(this.testCase); current.pop(); delete this.spec; return this; } }; var g = (typeof global !== "undefined" && global) || this; bspec.expose = function (env) { env = env || g; env.describe = bspec.describe; env.it = bspec.it; env.itEventually = bspec.itEventually; env.beforeAll = bspec.beforeAll; env.before = bspec.before; env.beforeEach = bspec.beforeEach; env.afterAll = bspec.afterAll; env.after = bspec.after; env.afterEach = bspec.afterEach; }; return bspec; }); ((typeof define === "function" && define.amd && function (m) { define("buster-test/test-case", ["bane", "when", "buster-test/test-context"], m); }) || (typeof module === "object" && typeof require === "function" && function (m) { module.exports = m( require("bane"), require("when"), require("./test-context") ); }) || function (m) { this.buster.testCase = m(this.bane, this.when, this.buster.testContext); })(function (bane, when, testContext) { "use strict"; var xUnitNames = { contextSetUp: "prepare", contextTearDown: "conclude" }; var testCase = function (name, tests) { if (!name || typeof name !== "string") { throw new Error("Test case name required"); } if (!tests || (typeof tests !== "object" && typeof tests !== "function")) { throw new Error("Tests should be an object or a function"); } var context = testCase.context.create(name, tests); var d = when.defer(); when(context).then(function (ctx) { d.resolver.resolve(ctx.parse()); }); var promise = context.then ? d.promise : context; promise.name = name; testContext.emit("create", promise); return promise; }; bane.createEventEmitter(testCase); function nonTestNames(context) { return { prepare: true, conclude: true, setUp: true, tearDown: true, requiresSupportFor: true, requiresSupportForAll: true }; } var DEFERRED_PREFIX = /^\s*\/\/\s*/; var FOCUSED_PREFIX = /^\s*=>\s*/; function createContext(context, name, tests, parent) { context.name = name; context.content = tests; context.parent = parent; context.testCase = { name: function (thing) { return xUnitNames[thing] || thing; } }; return context; } function asyncContext(context, name, callback, parent) { var d = when.defer(); callback(function (tests) { d.resolver.resolve(createContext(context, name, tests, parent)); }); return d.promise; } function F() {} function create(obj) { F.prototype = obj; return new F(); } testCase.context = { create: function (name, tests, parent) { var context = create(this); if (typeof tests === "function") { return asyncContext(context, name, tests, parent); } return createContext(context, name, tests, parent); }, parse: function (forceFocus) { this.getSupportRequirements(); this.deferred = DEFERRED_PREFIX.test(this.name); if (this.parent) { this.deferred = this.deferred || this.parent.deferred; } this.focused = forceFocus || FOCUSED_PREFIX.test(this.name); this.name = this.name. replace(DEFERRED_PREFIX, ""). replace(FOCUSED_PREFIX, ""); this.tests = this.getTests(this.focused); this.contexts = this.getContexts(this.focused); this.focused = this.focused || this.contexts.focused || this.tests.focused; delete this.tests.focused; delete this.contexts.focused; this.contextSetUp = this.getContextSetUp(); this.contextTearDown = this.getContextTearDown(); this.setUp = this.getSetUp(); this.tearDown = this.getTearDown(); return this; }, getSupportRequirements: function () { this.requiresSupportForAll = this.content.requiresSupportForAll || this.content.requiresSupportFor; delete this.content.requiresSupportForAll; delete this.content.requiresSupportFor; this.requiresSupportForAny = this.content.requiresSupportForAny; delete this.content.requiresSupportForAny; }, getTests: function (focused) { var prop, isFunc, tests = []; for (prop in this.content) { isFunc = typeof this.content[prop] === "function"; if (this.isTest(prop)) { var testFocused = focused || FOCUSED_PREFIX.test(prop); tests.focused = tests.focused || testFocused; tests.push({ name: prop.replace(DEFERRED_PREFIX, ""). replace(FOCUSED_PREFIX, ""), func: this.content[prop], context: this, deferred: this.deferred || DEFERRED_PREFIX.test(prop) || !isFunc, focused: testFocused, comment: !isFunc ? this.content[prop] : "" }); } } return tests; }, getContexts: function (focused) { var ctx, prop, contexts = []; contexts.focused = focused; for (prop in this.content) { if (this.isContext(prop)) { ctx = testCase.context.create( prop, this.content[prop], this ); ctx = ctx.parse(focused); contexts.focused = contexts.focused || ctx.focused; contexts.push(ctx); } } return contexts; }, getContextSetUp: function () { return this.content.prepare; }, getContextTearDown: function () { return this.content.conclude; }, getSetUp: function () { return this.content.setUp; }, getTearDown: function () { return this.content.tearDown; }, isTest: function (prop) { var type = typeof this.content[prop]; return this.content.hasOwnProperty(prop) && (type === "function" || type === "string") && !nonTestNames(this)[prop]; }, isContext: function (prop) { return this.content.hasOwnProperty(prop) && typeof this.content[prop] === "object" && !!this.content[prop]; } }; return testCase; }); ((typeof define === "function" && define.amd && function (m) { define("buster-test/test-runner", ["bane", "when", "lodash", "async", "platform"], m); }) || (typeof module === "object" && typeof require === "function" && function (m) { require("./seedrandom"); module.exports = m( require("bane"), require("when"), require("lodash"), require("async"), require("platform"), function (cb) { process.nextTick(cb); }, true ); }) || function (m) { // In case someone overwrites/mocks out timers later on var setTimeout = window.setTimeout; this.buster = this.buster || {}; this.buster.test = this.buster.test || {}; this.buster.test.runner = m( this.bane, this.when, this._, this.async, this.platform ); })(function (bane, when, _, async, platform, nextTick, isNode) { "use strict"; var onUncaught = function () {}; var partial = function (fn) { var args = [].slice.call(arguments, 1); return function () { return fn.apply(this, args.concat([].slice.call(arguments))); }; }; function F() {} function create(obj) { F.prototype = obj; return new F(); } // Events var errorEvents = { "TimeoutError": "test:timeout", "AssertionError": "test:failure", "DeferredTestError": "test:deferred" }; function emit(runner, event, test, err, thisp) { var data = { name: test.name, runtime: runner.runtime }; if (err) { data.error = err; } if (typeof test.func === "string") { data.comment = test.func; } if (thisp) { data.testCase = thisp; } if (event === "test:success") { data.assertions = runner.assertionCount; } runner.emit(event, data); } function emitTestAsync(runner, test) { if (test && !test.async && !test.deferred) { test.async = true; emit(runner, "test:async", test); } } function testResult(runner, test, err) { if (!test) { err.runtime = runner.runtime; return runner.emit("uncaughtException", err); } if (test.complete) { return; } test.complete = true; var event = "test:success"; if (err) { event = errorEvents[err.name] || "test:error"; if (err.name === "TimeoutError") { emitTestAsync(runner, test); } } emit(runner, event, test, err); if (event === "test:error") { runner.results.errors += 1; } if (event === "test:failure") { runner.results.failures += 1; } if (event === "test:timeout") { runner.results.timeouts += 1; } if (event === "test:deferred") { runner.results.deferred += 1; } else { runner.results.assertions += runner.assertionCount; runner.results.tests += 1; } } function emitIfAsync(runner, test, isAsync) { if (isAsync) { emitTestAsync(runner, test); } } function emitUnsupported(runner, context, requirements) { runner.emit("context:unsupported", { runtime: runner.runtime, context: context, unsupported: requirements }); } // Data helper functions function setUps(context) { var setUpFns = []; while (context) { if (context.setUp) { setUpFns.unshift(context.setUp); } context = context.parent; } return setUpFns; } function tearDowns(context) { var tearDownFns = []; while (context) { if (context.tearDown) { tearDownFns.push(context.tearDown); } context = context.parent; } return tearDownFns; } function satiesfiesRequirement(requirement) { if (typeof requirement === "function") { return !!requirement(); } return !!requirement; } function unsatiesfiedRequirements(context) { var name, requirements = context.requiresSupportForAll; for (name in requirements) { if (!satiesfiesRequirement(requirements[name])) { return [name]; } } var unsatiesfied = []; requirements = context.requiresSupportForAny; for (name in requirements) { if (satiesfiesRequirement(requirements[name])) { return []; } else { unsatiesfied.push(name); } } return unsatiesfied; } function isAssertionError(err) { return err && err.name === "AssertionError"; } function prepareResults(results) { return _.extend({}, results, { ok: results.failures + results.errors + results.timeouts === 0 }); } function propWithDefault(obj, prop, defaultValue) { return obj && obj.hasOwnProperty(prop) ? obj[prop] : defaultValue; } // Async flow function promiseSeries(objects, fn) { var deferred = when.defer(); async.series(_.map(objects, function (obj) { return function (next) { var value = fn(obj); value.then(partial(next, null), next); return value; }; }), function (err) { if (err) { return deferred.reject(err); } deferred.resolve(); }); return deferred.promise; } function asyncDone(resolver) { function resolve(method, err) { try { resolver[method](err); } catch (e) { throw new Error("done() was already called"); } } return function (fn) { if (typeof fn !== "function") { return resolve("resolve"); } return function () { try { var retVal = fn.apply(this, arguments); resolve("resolve"); return retVal; } catch (up) { resolve("reject", up); } }; }; } function asyncFunction(fn, thisp) { if (fn.length > 0) { var deferred = when.defer(); fn.call(thisp, asyncDone(deferred.resolver)); return deferred.promise; } return fn.call(thisp); } function timeoutError(ms) { return { name: "TimeoutError", message: "Timed out after " + ms + "ms" }; } function timebox(promise, timeout, callbacks) { var timedout, complete, timer; function handler(method) { return function () { complete = true; clearTimeout(timer); if (!timedout) { callbacks[method].apply(this, arguments); } }; } when(promise).then(handler("resolve"), handler("reject")); var ms = typeof timeout === "function" ? timeout() : timeout; timer = setTimeout(function () { timedout = true; if (!complete) { callbacks.timeout(timeoutError(ms)); } }, ms); } function callAndWait(func, thisp, timeout, next) { var reject = function (err) { next(err || {}); }; var promise = asyncFunction(func, thisp); timebox(promise, timeout, { resolve: partial(next, null), reject: reject, timeout: reject }); return promise; } function callSerially(functions, thisp, timeout, source) { var d = when.defer(); var fns = functions.slice(); var isAsync = false; function next(err) { if (err) { err.source = source; return d.reject(err); } if (fns.length === 0) { return d.resolve(isAsync); } try { var promise = callAndWait(fns.shift(), thisp, timeout, next); isAsync = isAsync || when.isPromise(promise); } catch (e) { return d.reject(e); } } next(); return d.promise; } function asyncWhen(value) { if (when.isPromise(value)) { return value; } else { var d = when.defer(); TestRunner.prototype.nextTick(partial(d.resolve, value)); return d.promise; } } function chainPromises(fn, resolution) { var r = typeof resolution === "function" ? [resolution, resolution] : resolution; return function () { fn().then(partial(resolution, null), r[0], r[1]); }; } function rejected(deferred) { if (!deferred) { deferred = when.defer(); } deferred.reject(); return deferred.promise; } function listenForUncaughtExceptions() { var listener, listening = false; onUncaught = function (l) { listener = l; if (!listening) { listening = true; process.on("uncaughtException", function (e) { if (listener) { listener(e); } }); } }; } if (typeof process === "object") { listenForUncaughtExceptions(); } // Private runner functions function callTestFn(runner, test, thisp, next) { emit(runner, "test:start", test, null, thisp); if (test.deferred) { return next({ name: "DeferredTestError" }); } try { var promise = asyncFunction(test.func, thisp); if (when.isPromise(promise)) { emitTestAsync(runner, test); } timebox(promise, thisp.timeout || runner.timeout, { resolve: function () { // When the promise resolves, it's a success so we don't // want to propagate the resolution value. If we do, Buster // will think the value represents an error, and will fail // the test. return next.apply(this); }, reject: next, timeout: function (err) { err.source = "test function"; next(err); } }); } catch (e) { next(e); } } function checkAssertions(runner, expected) { if (runner.failOnNoAssertions && runner.assertionCount === 0) { return { name: "AssertionError", message: "No assertions!" }; } var actual = runner.assertionCount; if (typeof expected === "number" && actual !== expected) { return { name: "AssertionError", message: "Expected " + expected + " assertions, ran " + actual }; } } function triggerOnCreate(listeners, runner) { _.each(listeners, function (listener) { listener(runner); }); } function initializeResults() { return { contexts: 0, tests: 0, errors: 0, failures: 0, assertions: 0, timeouts: 0, deferred: 0 }; } function focused(items) { return _.filter(items, function (item) { return item.focused; }); } function dynamicTimeout(testCase, runner) { return function () { return testCase.timeout || runner.timeout; }; } // Craaaazy stuff // https://gist.github.com/982883 function uuid(a) { if (a) { return (a ^ Math.random() * 16 >> a/4).toString(16); } return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, uuid); } function parseRuntime(env) { if (!env) { return null; } var runtime = platform.parse(env); runtime.uuid = uuid(); return runtime; } function countTests(context) { if (!context) { return 0; } if (!_.isArray(context)) { return (context.tests || []).length + countTests(context.contexts); } return _.reduce(context, function (num, ctx) { return num + countTests(ctx); }, 0); } function emitConfiguration(runner, ctxs) { runner.emit("suite:configuration", { runtime: runner.runtime, name: runner.configuration, tests: countTests(ctxs), seed: runner.seed }); } function TestRunner(opt) { triggerOnCreate(TestRunner.prototype.onCreateListeners, this); this.results = initializeResults(); this.runtime = parseRuntime(opt.runtime); this.configuration = opt.configuration; this.clients = 1; this.concurrent = false; if (opt.random === false) { this.randomize = function (coll) { return coll; }; } else { var random = seedRandom(opt.randomSeed); this.seed = random.seed; this.randomize = function (coll) { return coll.sort(function () { return Math.round(random() * 2) - 1; }); }; } this.failOnNoAssertions = propWithDefault( opt, "failOnNoAssertions", false ); if (typeof opt.timeout === "number") { this.timeout = opt.timeout; } } TestRunner.prototype = bane.createEventEmitter({ timeout: 250, onCreateListeners: [], create: function (opt) { return new TestRunner(opt || {}); }, onCreate: function (listener) { this.onCreateListeners.push(listener); }, runSuite: function (ctxs) { this.focusMode = _.some(ctxs, function (c) { return c.focused; }); this.results = initializeResults(); onUncaught(_.bind(function (err) { testResult(this, this.currentTest, err); }, this)); var d = when.defer(); this.emit("suite:start", { runtime: this.runtime }); if (this.runtime) { emitConfiguration(this, ctxs); } if (this.focusMode) { this.emit("runner:focus", { runtime: this.runtime }); } this.results.contexts = ctxs.length; this.runContexts(ctxs).then(_.bind(function () { var res = prepareResults(this.results); res.runtime = this.runtime; this.emit("suite:end", res); d.resolve(res); }, this), d.reject); return d.promise; }, runContexts: function (contexts, thisProto) { var self = this; if (this.focusMode) { contexts = focused(contexts); } return promiseSeries( this.randomize(contexts || []), function (context) { return self.runContext(context, thisProto); } ); }, runContext: function (context, thisProto) { if (!context) { return rejected(); } var reqs = unsatiesfiedRequirements(context); if (reqs.length > 0) { return when(emitUnsupported(this, context, reqs)); } var d = when.defer(), s = this, thisp, ctx; var emitAndResolve = function () { s.emit("context:end", _.extend(context, { runtime: s.runtime })); d.resolve(); }; var end = function (err) { s.runContextUpDown(ctx, "contextTearDown", thisp).then( emitAndResolve, emitAndResolve ); }; this.emit("context:start", _.extend(context, { runtime: this.runtime })); asyncWhen(context).then(function (c) { ctx = c; thisp = create(thisProto || c.testCase); var fns = s.randomize(c.tests); var runTests = chainPromises( _.bind(s.runTests, s, fns, setUps(c), tearDowns(c), thisp), end ); s.runContextUpDown(ctx, "contextSetUp", thisp).then( function () { s.runContexts(c.contexts, thisp).then(runTests); }, end ); }); return d; }, runContextUpDown: function (context, prop, thisp) { var fn = context[prop]; if (!fn) { return when(); } var d = when.defer(); var s = this; var reject = function (err) { err = err || new Error(); err.message = context.name + " " + thisp.name(prop) + "(n) " + (/Timeout/.test(err.name) ? "timed out" : "failed") + ": " + err.message; err.runtime = s.runtime; s.emit("uncaughtException", err); d.reject(err); }; try { var timeout = dynamicTimeout(thisp, this); timebox(asyncFunction(fn, thisp), timeout, { resolve: d.resolve, reject: reject, timeout: reject }); } catch (e) { reject(e); } return d.promise; }, callSetUps: function (test, setUps, thisp) { if (test.deferred) { return when(); } emit(this, "test:setUp", test, null, thisp); var timeout = dynamicTimeout(thisp, this); var emitAsync = partial(emitIfAsync, this, test); return callSerially(setUps, thisp, timeout, "setUp").then( emitAsync ); }, callTearDowns: function (test, tearDowns, thisp) { if (test.deferred) { return when(); } emit(this, "test:tearDown", test, null, thisp); var timeout = dynamicTimeout(thisp, this); var emitAsync = partial(emitIfAsync, this, test); return callSerially(tearDowns, thisp, timeout, "tearDown").then( emitAsync ); }, runTests: function (tests, setUps, tearDowns, thisp) { if (this.focusMode) { tests = focused(tests); } return promiseSeries(tests, _.bind(function (test) { return this.runTest(test, setUps, tearDowns, create(thisp)); }, this)); }, runTest: function (test, setUps, tearDowns, thisp) { this.running = true; var d = when.defer(); test = create(test); this.assertionCount = 0; this.currentTest = test; var callSetUps = _.bind(this.callSetUps, this, test, setUps, thisp); var callTearDowns = _.bind( this.callTearDowns, this, test, tearDowns, thisp ); var callTest = partial(callTestFn, this, test, thisp); var tearDownEmitResolve = _.bind(function (err) { var resolution = _.bind(function (err2) { var e = err || err2 || this.queued; this.running = false; this.queued = null; e = e || checkAssertions(this, thisp.expectedAssertions); testResult(this, test, e); delete this.currentTest; d.resolve(); }, this); callTearDowns().then(partial(resolution, null), resolution); }, this); var callTestAndTearDowns = partial(callTest, tearDownEmitResolve); callSetUps().then(callTestAndTearDowns, tearDownEmitResolve); return d.promise; }, assertionPass: function () { this.assertionCount += 1; }, error: function (error, test) { if (this.running) { if (!this.queued) { this.queued = error; } return; } testResult(this, test || this.currentTest, error); }, // To be removed assertionFailure: function (error) { this.error(error); } }); TestRunner.prototype.nextTick = nextTick || function (cb) { setTimeout(cb, 0); }; return TestRunner.prototype; }); ((typeof define === "function" && define.amd && function (m) { define("buster-test/reporters/runtime-throttler", ["bane", "lodash"], m); }) || (typeof module === "object" && typeof require === "function" && function (m) { module.exports = m(require("bane"), require("lodash")); }) || function (m) { this.buster = this.buster || {}; this.buster.reporters = this.buster.reporters || {}; this.buster.reporters.runtimeThrottler = m(this.bane, this._); } )(function (bane, _) { "use strict"; function runtime(env) { return { uuid: env.uuid, contexts: 0, events: [], queue: function (name, data) { this.events.push({ name: name, data: data }); }, flush: function (emitter) { _.forEach(this.events, function (event) { emitter.emit(event.name, event.data); }); } }; } function getRuntime(runtimes, env) { return runtimes.filter(function (r) { return r.uuid === env.uuid; })[0]; } function proxy(name) { return function (e) { var rt = getRuntime(this.runtimes, e.runtime); if (rt && rt.contexts > 0) { rt.queue(name, e); } else { this.emit(name, e); } }; } function RuntimeThrottler() { this.runtimes = []; this.results = []; } RuntimeThrottler.prototype = bane.createEventEmitter({ create: function () { return new RuntimeThrottler(); }, listen: function (runner) { runner.bind(this); if (runner.console) { runner.console.on("log", this.log, this); } return this; }, "suite:start": function (e) { if (this.runtimes.length === 0) { this.emit("suite:start", {}); } this.runtimes.push(runtime(e.runtime)); }, "suite:configuration": function (e) { this.emit("suite:configuration", e); }, "context:unsupported": function (e) { var rt = getRuntime(this.runtimes, e.runtime); if (rt.contexts === 0) { this.emit("context:unsupported", e); } else { rt.queue("context:unsupported", e); } }, "context:start": function (e) { var rt = getRuntime(this.runtimes, e.runtime); if (this.runtimes.length > 1) { rt.queue("context:start", e); rt.contexts += 1; } else { this.emit("context:start", e); } }, "test:setUp": proxy("test:setUp"), "test:tearDown": proxy("test:tearDown"), "test:start": proxy("test:start"), "test:error": proxy("test:error"), "test:failure": proxy("test:failure"), "test:timeout": proxy("test:timeout"), "test:success": proxy("test:success"), "test:async": proxy("test:async"), "test:deferred": proxy("test:deferred"), "context:end": function (e) { var rt = getRuntime(this.runtimes, e.runtime); if (rt) { rt.queue("context:end", e); rt.contexts -= 1; if (rt.contexts <= 0) { rt.contexts = 0; rt.flush(this); } } else { this.emit("context:end", e); } }, "suite:end": function (e) { this.results.push(e); if (this.results.length === this.runtimes.length || this.runtimes.length === 0) { this.emit("suite:end", _.reduce(this.results, function (res, r) { return { contexts: (res.contexts || 0) + r.contexts, tests: (res.tests || 0) + r.tests, errors: (res.errors || 0) + r.errors, failures: (res.failures || 0) + r.failures, assertions: (res.assertions || 0) + r.assertions, timeouts: (res.timeouts || 0) + r.timeouts, deferred: (res.deferred || 0) + r.deferred, ok: res.ok && r.ok }; }, { ok: true })); } }, "runner:focus": function () { if (!this.runnerFocus) { this.emit("runner:focus"); this.runnerFocus = true; } }, uncaughtException: function (e) { this.emit("uncaughtException", e); }, log: function (e) { this.emit("log", e); } }); return RuntimeThrottler.prototype; }); ((typeof define === "function" && define.amd && function (m) { define("buster-test/reporters/html", ["buster-test/reporters/runtime-throttler"], m); }) || (typeof module === "object" && typeof require === "function" && function (m) { try { var jsdom = require("jsdom").jsdom; } catch (e) { // Is handled when someone actually tries using the HTML reporter // on node without jsdom } module.exports = m(require("./runtime-throttler"), jsdom, true); }) || function (m) { this.buster = this.buster || {}; this.buster.reporters = this.buster.reporters || {}; this.buster.reporters.html = m(this.buster.reporters.runtimeThrottler); } )(function (runtimeThrottler, jsdom, isNodeJS) { "use strict"; function filterStack(reporter, stack) { if (!stack) { return []; } if (reporter.stackFilter) { return reporter.stackFilter.filter(stack); } return stack.split("\n"); } function getDoc(options) { return options && options.document || (typeof document != "undefined" ? document : createDocument()); } function addCSS(head, cssPath) { if (isNodeJS) { var fs = require("fs"); var path = require("path"); head.appendChild(el(head.ownerDocument, "style", { type: "text/css", innerHTML: fs.readFileSync( path.join(__dirname, "../../resources/buster-test.css") ) })); } else { head.appendChild(el(document, "link", { rel: "stylesheet", type: "text/css", media: "all", href: cssPath })); } } function insertTitle(doc, body, title) { if (doc.getElementsByTagName("h1").length == 0) { body.insertBefore(el(doc, "h1", { innerHTML: "<span class=\"title\">" + title + "</span>" }), body.firstChild); } } function insertLogo(h1) { h1.innerHTML = "<span class=\"buster-logo\"></span>" + h1.innerHTML; } function createDocument() { if (!jsdom) { util.puts("Unable to load jsdom, html reporter will not work " + "for node runs. Spectacular fail coming up."); } var dom = jsdom("<!DOCTYPE html><html><head></head><body></body></html>"); return dom.createWindow().document; } function pluralize(num, phrase) { num = typeof num == "undefined" ? 0 : num; return num + " " + (num == 1 ? phrase : phrase + "s"); } function el(doc, tagName, properties) { var el = doc.createElement(tagName), value; for (var prop in properties) { value = properties[prop]; if (prop == "http-equiv") { el.setAttribute(prop, value); } if (prop == "text") { prop = "innerHTML"; } el[prop] = value; } return el; } function addListItem(tagName, test, className) { var prefix = tagName ? "<" + tagName + ">" : ""; var suffix = tagName ? "</" + tagName + ">" : ""; var item = el(this.doc, "li", { className: className, text: prefix + test.name + suffix }); this.list().appendChild(item); return item; } function addException(reporter, li, error) { if (!error) { return; } var name = error.name == "AssertionError" ? "" : error.name + ": "; li.appendChild(el(li.ownerDocument || document, "p", { innerHTML: name + error.message, className: "error-message" })); var stack = filterStack(reporter, error.stack); if (stack.length > 0) { if (stack[0].indexOf(error.message) >= 0) { stack.shift(); } li.appendChild(el(li.ownerDocument || document, "ul", { className: "stack", innerHTML: "<li>" + stack.join("</li><li>") + "</li>" })); } } function busterTestPath(document) { var scripts = document.getElementsByTagName("script"); for (var i = 0, l = scripts.length; i < l; ++i) { if (/buster-test\.js$/.test(scripts[i].src)) { return scripts[i].src.replace("buster-test.js", ""); } } return ""; } function getOutputStream(opt) { if (opt.outputStream) { return opt.outputStream; } if (isNodeJS) { var util = require("util"); return { write: function (bytes) { util.print(bytes); } }; } } function HtmlReporter(opt) { opt = opt || {}; this._listStack = []; this.doc = getDoc(opt); var cssPath = opt.cssPath; if (!cssPath && opt.detectCssPath !== false) { cssPath = busterTestPath(this.doc) + "buster-test.css"; } this.setRoot(opt.root || this.doc.body, cssPath); this.out = getOutputStream(opt); this.stackFilter = opt.stackFilter; } HtmlReporter.prototype = { create: function (opt) { return new HtmlReporter(opt); }, setRoot: function (root, cssPath) { this.root = root; this.root.className += " buster-test"; var body = this.doc.body; if (this.root == body) { var head = this.doc.getElementsByTagName("head")[0]; head.parentNode.className += " buster-test"; head.appendChild(el(this.doc, "meta", { "name": "viewport", "content": "width=device-width, initial-scale=1.0" })); head.appendChild(el(this.doc, "meta", { "http-equiv": "Content-Type", "content": "text/html; charset=utf-8" })); if (cssPath) addCSS(head, cssPath); insertTitle(this.doc, body, this.doc.title || "Buster.JS Test case"); insertLogo(this.doc.getElementsByTagName("h1")[0]); } }, listen: function (runner) { var proxy = runtimeThrottler.create(); proxy.listen(runner).bind(this); if (runner.console) { runner.console.on("log", this.log, this); } return this; }, "context:start": function (context) { var container = this.root; if (this._list) { container = el(this.doc, "li"); this._list.appendChild(container); } container.appendChild(el(this.doc, "h2", { text: context.name })); this._list = el(this.doc, "ul"); container.appendChild(this._list); this._listStack.unshift(this._list); }, "context:end": function (context) { this._listStack.shift(); this._list = this._listStack[0]; }, "test:success": function (test) { var li = addListItem.call(this, "h3", test, "success"); this.addMessages(li); }, "test:failure": function (test) { var li = addListItem.call(this, "h3", test, "failure"); this.addMessages(li); addException(this, li, test.error); }, "test:error": function (test) { var li = addListItem.call(this, "h3", test, "error"); this.addMessages(li); addException(this, li, test.error); }, "test:deferred": function (test) { var li = addListItem.call(this, "h3", test, "deferred"); }, "test:timeout": function (test) { var li = addListItem.call(this, "h3", test, "timeout"); var source = test.error && test.error.source; if (source) { li.firstChild.innerHTML += " (" + source + " timed out)"; } this.addMessages(li); }, log: function (msg) { this.messages = this.messages || []; this.messages.push(msg); }, addMessages: function (li) { var messages = this.messages || []; var html = ""; if (messages.length == 0) { return; } for (var i = 0, l = messages.length; i < l; ++i) { html += "<li class=\"" + messages[i].level + "\">"; html += messages[i].message + "</li>"; } li.appendChild(el(this.doc, "ul", { className: "messages", innerHTML: html })); this.messages = []; }, success: function (stats) { return stats.failures == 0 && stats.errors == 0 && stats.tests > 0 && stats.assertions > 0; }, startTimer: function () { this.startedAt = new Date(); }, "suite:end": function (stats) { var diff = (new Date() - this.startedAt) / 1000; var className = "stats " + (this.success(stats) ? "success" : "failure"); var statsEl = el(this.doc, "div", { className: className }); var h1 = this.doc.getElementsByTagName("h1")[0]; this.root.insertBefore(statsEl, h1.nextSibling); statsEl.appendChild(el(this.doc, "h2", { text: this.success(stats) ? "Tests OK" : "Test failures!" })); var html = ""; html += "<li>" + pluralize(stats.contexts, "test case") + "</li>"; html += "<li>" + pluralize(stats.tests, "test") + "</li>"; html += "<li>" + pluralize(stats.assertions, "assertion") + "</li>"; html += "<li>" + pluralize(stats.failures, "failure") + "</li>"; html += "<li>" + pluralize(stats.errors, "error") + "</li>"; html += "<li>" + pluralize(stats.timeouts, "timeout") + "</li>"; if (stats.deferred > 0) { html += "<li>" + stats.deferred + " deferred</li>"; } statsEl.appendChild(el(this.doc, "ul", { innerHTML: html })); statsEl.appendChild(el(this.doc, "p", { className: "time", innerHTML: "Finished in " + diff + "s" })); this.writeIO(); }, list: function () { if (!this._list) { this._list = el(this.doc, "ul", { className: "test-results" }); this._listStack.unshift(this._list); this.root.appendChild(this._list); } return this._list; }, writeIO: function () { if (!this.out) { return; } this.out.write(this.doc.doctype.toString()); this.out.write(this.doc.innerHTML); } }; return HtmlReporter.prototype; }); if (typeof module === "object" && typeof require === "function") { module.exports = { specification: require("./reporters/specification"), jsonProxy: require("./reporters/json-proxy"), xml: require("./reporters/xml"), tap: require("./reporters/tap"), brief: require("./reporters/brief"), html: require("./reporters/html"), teamcity: require("./reporters/teamcity"), load: function (reporter) { if (module.exports[reporter]) { return module.exports[reporter]; } return require(reporter); } }; module.exports.defaultReporter = module.exports.brief; } else if (typeof define === "function") { define("buster-test/reporters", ["buster-test/reporters/html"], function (html) { var reporters = { html: html, load: function (reporter) { return reporters[reporter]; } }; reporters.defaultReporter = reporters.brief; return reporters; }); } else { buster.reporters = buster.reporters || {}; buster.reporters.defaultReporter = buster.reporters.brief; buster.reporters.load = function (reporter) { return buster.reporters[reporter]; }; } ((typeof define === "function" && define.amd && function (m) { define("buster-test/auto-run", ["lodash", "buster-test/test-context", "buster-test/test-runner", "buster-test/reporters"], m); }) || (typeof module === "object" && typeof require === "function" && function (m) { module.exports = m( require("lodash"), require("./test-context"), require("./test-runner"), require("./reporters") ); }) || function (m) { this.buster.autoRun = m( this._, this.buster.testContext, this.buster.testRunner, this.buster.reporters ); })(function (_, testContext, testRunner, reporters) { "use strict"; function browserEnv() { var env = {}; var key, value, pieces, params = window.location.search.slice(1).split("&"); for (var i = 0, l = params.length; i < l; ++i) { pieces = params[i].split("="); key = pieces.shift(); value = pieces.join("=") || "1"; if (key) { key = "BUSTER_" + key.match(/(^|[A-Z])[a-z]+/g).join("_").toUpperCase(); env[key] = value; } } return env; } function env() { if (typeof process !== "undefined") { return process.env; } if (typeof window === "undefined") { return {}; } return browserEnv(); } function autoRun(opt, callbacks) { var runners = 0, contexts = [], timer; testRunner.onCreate(function (runner) { runners += 1; }); if (typeof opt === "function") { callbacks = opt; opt = {}; } if (typeof callbacks !== "object") { callbacks = { end: callbacks }; } return function (tc) { contexts.push(tc); clearTimeout(timer); timer = setTimeout(function () { if (runners === 0) { opt = _.extend(autoRun.envOptions(env()), opt); autoRun.run(contexts, opt, callbacks); } }, 10); }; } autoRun.envOptions = function (env) { return { reporter: env.BUSTER_REPORTER, filters: (env.BUSTER_FILTERS || "").split(","), color: env.BUSTER_COLOR === "false" ? false : true, bright: env.BUSTER_BRIGHT === "false" ? false : true, timeout: env.BUSTER_TIMEOUT && parseInt(env.BUSTER_TIMEOUT, 10), failOnNoAssertions: env.BUSTER_FAIL_ON_NO_ASSERTIONS === "false" ? false : true, random: env.BUSTER_RANDOM === "0" || env.BUSTER_RANDOM === "false" ? false : true, randomSeed: env.BUSTER_RANDOM_SEED }; }; function initializeReporter(runner, opt) { var reporter; if (typeof document !== "undefined" && document.getElementById) { reporter = "html"; opt.root = document.getElementById("buster") || document.body; } else { reporter = opt.reporter || "brief"; } reporter = reporters.load(reporter).create(opt); reporter.listen(runner); if (typeof reporter.log === "function" && typeof buster === "object" && typeof buster.console === "function") { buster.console.on("log", reporter.log, reporter); } } function ua() { if (typeof navigator !== "undefined") { return navigator.userAgent; } return [process.title, process.version + ",", process.platform, process.arch].join(" "); } autoRun.run = function (contexts, opt, callbacks) { callbacks = callbacks || {}; if (contexts.length === 0) { return; } opt = _.extend({ color: true, bright: true }, opt); var runner = testRunner.create(_.extend({ timeout: 750, failOnNoAssertions: false, runtime: ua(), random: typeof opt.random === "boolean" ? opt.random : true, randomSeed: opt.randomSeed }, opt)); if (typeof callbacks.start === "function") { callbacks.start(runner); } initializeReporter(runner, opt); if (typeof callbacks.end === "function") { runner.on("suite:end", callbacks.end); } runner.runSuite(testContext.compile(contexts, opt.filters)); }; return autoRun; }); ((typeof define === "function" && define.amd && function (m) { define("referee-sinon", m); }) || (typeof module === "object" && typeof require === "function" && function (m) { module.exports = m(); }) || function (m) { this.refereeSinon = m(); } )(function () { return function (referee, sinon) { sinon.expectation.pass = function (assertion) { referee.emit("pass", assertion); }; sinon.expectation.fail = function (message) { referee.fail(message); }; // Lazy bind the format method to referee's. This way, Sinon will // always format objects like referee does, even if referee is configured // after referee-sinon is loaded sinon.format = function () { return referee.format.apply(referee, arguments); }; function verifyFakes() { var method, isNot, i, l; for (i = 0, l = arguments.length; i < l; ++i) { method = arguments[i]; isNot = (method || "fake") + " is not "; if (!method) { this.fail(isNot + "a spy"); } if (typeof method !== "function") { this.fail(isNot + "a function"); } if (typeof method.getCall !== "function") { this.fail(isNot + "stubbed"); } } return true; } var sf = sinon.spy.formatters; var spyValues = function (spy) { return [spy, sf.c(spy), sf.C(spy)]; }; referee.add("called", { assert: function (spy) { verifyFakes.call(this, spy); return spy.called; }, assertMessage: "Expected ${0} to be called at least once but was " + "never called", refuteMessage: "Expected ${0} to not be called but was called ${1}${2}", expectation: "toHaveBeenCalled", values: spyValues }); function slice(arr, from, to) { return [].slice.call(arr, from, to); } referee.add("callOrder", { assert: function (spy) { var type = Object.prototype.toString.call(spy); var isArray = type === "[object Array]"; var args = isArray ? spy : arguments; verifyFakes.apply(this, args); if (sinon.calledInOrder(args)) { return true; } this.expected = [].join.call(args, ", "); this.actual = sinon.orderByFirstCall(slice(args)).join(", "); }, assertMessage: "Expected ${expected} to be called in order but " + "were called as ${actual}", refuteMessage: "Expected ${expected} not to be called in order" }); function addCallCountAssertion(count) { var c = count.toLowerCase(); referee.add("called" + count, { assert: function (spy) { verifyFakes.call(this, spy); return spy["called" + count]; }, assertMessage: "Expected ${0} to be called " + c + " but was called ${1}${2}", refuteMessage: "Expected ${0} to not be called exactly " + c + "${2}", expectation: "toHaveBeenCalled" + count, values: spyValues }); } addCallCountAssertion("Once"); addCallCountAssertion("Twice"); addCallCountAssertion("Thrice"); function valuesWithThis(spy, thisObj) { return [spy, thisObj, (spy.printf && spy.printf("%t")) || ""]; } referee.add("calledOn", { assert: function (spy, thisObj) { verifyFakes.call(this, spy); return spy.calledOn(thisObj); }, assertMessage: "Expected ${0} to be called with ${1} as this but was " + "called on ${2}", refuteMessage: "Expected ${0} not to be called with ${1} as this", expectation: "toHaveBeenCalledOn", values: valuesWithThis }); referee.add("alwaysCalledOn", { assert: function (spy, thisObj) { verifyFakes.call(this, spy); return spy.alwaysCalledOn(thisObj); }, assertMessage: "Expected ${0} to always be called with ${1} as this " + "but was called on ${2}", refuteMessage: "Expected ${0} not to always be called with ${1} " + "as this", expectation: "toHaveAlwaysBeenCalledOn", values: valuesWithThis }); function formattedArgs(args, i) { var l, result; for (l = args.length, result = []; i < l; ++i) { result.push(sinon.format(args[i])); } return result.join(", "); } function spyAndCalls(spy) { return [ spy, formattedArgs(arguments, 1), spy.printf && spy.printf("%C") ]; } referee.add("calledWith", { assert: function (spy) { verifyFakes.call(this, spy); return spy.calledWith.apply(spy, slice(arguments, 1)); }, assertMessage: "Expected ${0} to be called with arguments ${1}${2}", refuteMessage: "Expected ${0} not to be called with arguments ${1}${2}", expectation: "toHaveBeenCalledWith", values: spyAndCalls }); referee.add("alwaysCalledWith", { assert: function (spy) { verifyFakes.call(this, spy); return spy.alwaysCalledWith.apply(spy, slice(arguments, 1)); }, assertMessage: "Expected ${0} to always be called with " + "arguments ${1}${2}", refuteMessage: "Expected ${0} not to always be called with " + "arguments${1}${2}", expectation: "toHaveAlwaysBeenCalledWith", values: spyAndCalls }); referee.add("calledOnceWith", { assert: function (spy) { verifyFakes.call(this, spy); return spy.calledOnce && spy.calledWith.apply(spy, slice(arguments, 1)); }, assertMessage: "Expected ${0} to be called once with " + "arguments ${1}${2}", refuteMessage: "Expected ${0} not to be called once with " + "arguments ${1}${2}", expectation: "toHaveBeenCalledOnceWith", values: spyAndCalls }); referee.add("calledWithExactly", { assert: function (spy) { verifyFakes.call(this, spy); return spy.calledWithExactly.apply(spy, slice(arguments, 1)); }, assertMessage: "Expected ${0} to be called with exact " + "arguments ${1}${2}", refuteMessage: "Expected ${0} not to be called with exact " + "arguments${1}${2}", expectation: "toHaveBeenCalledWithExactly", values: spyAndCalls }); referee.add("alwaysCalledWithExactly", { assert: function (spy) { verifyFakes.call(this, spy); return spy.alwaysCalledWithExactly.apply(spy, slice(arguments, 1)); }, assertMessage: "Expected ${0} to always be called with exact " + "arguments ${1}${2}", refuteMessage: "Expected ${0} not to always be called with exact " + "arguments${1}${2}", expectation: "toHaveAlwaysBeenCalledWithExactly", values: spyAndCalls }); referee.add("calledWithMatch", { assert: function (spy) { verifyFakes.call(this, spy); return spy.calledWithMatch.apply(spy, slice(arguments, 1)); }, assertMessage: "Expected ${0} to be called with matching " + "arguments ${1}${2}", refuteMessage: "Expected ${0} not to be called with matching " + "arguments${1}${2}", expectation: "toHaveAlwaysBeenCalledWithExactly", values: spyAndCalls }); referee.add("alwaysCalledWithMatch", { assert: function (spy) { verifyFakes.call(this, spy); return spy.alwaysCalledWithMatch.apply(spy, slice(arguments, 1)); }, assertMessage: "Expected ${0} to always be called with matching " + "arguments ${1}${2}", refuteMessage: "Expected ${0} not to always be called with matching " + "arguments${1}${2}", expectation: "toHaveAlwaysBeenCalledWithExactly", values: spyAndCalls }); function spyAndException(spy, exception) { return [spy, spy.printf && spy.printf("%C")]; } referee.add("threw", { assert: function (spy) { verifyFakes.call(this, spy); return spy.threw(arguments[1]); }, assertMessage: "Expected ${0} to throw an exception${1}", refuteMessage: "Expected ${0} not to throw an exception${1}", expectation: "toHaveThrown", values: spyAndException }); referee.add("alwaysThrew", { assert: function (spy) { verifyFakes.call(this, spy); return spy.alwaysThrew(arguments[1]); }, assertMessage: "Expected ${0} to always throw an exception${1}", refuteMessage: "Expected ${0} not to always throw an exception${1}", expectation: "toAlwaysHaveThrown", values: spyAndException }); }; }); ((typeof define === "function" && define.amd && function (m) { define("buster-sinon", m); }) || (typeof module === "object" && typeof require === "function" && function (m) { module.exports = m(); }) || function (m) { this.busterSinon = m(); } )(function () { return function (sinon, bt, stackFilter, formatio) { if (stackFilter) { stackFilter.filters.push("lib/sinon"); } bt.testRunner.onCreate(function (runner) { runner.on("test:setUp", function (test) { var config = sinon.getConfig(sinon.config); config.useFakeServer = false; var sandbox = sinon.sandbox.create(); sandbox.inject(test.testCase); test.testCase.useFakeTimers = function () { return sandbox.useFakeTimers.apply(sandbox, arguments); }; test.testCase.useFakeServer = function () { return sandbox.useFakeServer.apply(sandbox, arguments); }; test.testCase.sandbox = sandbox; var testFunc = test.func; }); runner.on("test:tearDown", function (test) { try { test.testCase.sandbox.verifyAndRestore(); } catch (e) { runner.assertionFailure(e); } }); sinon.expectation.pass = function () { runner.assertionPass(); }; }); }; }); (function (glbl, buster, sinon) { if (typeof require == "function" && typeof module == "object") { var busterTest = require("buster-test"); var path = require("path"); var fs = require("fs"); var referee = require("referee"); var stackFilter = require("stack-filter"); sinon = require("sinon"); buster = module.exports = { testCase: busterTest.testCase, spec: busterTest.spec, testRunner: busterTest.testRunner, testContext: busterTest.testContext, reporters: busterTest.reporters, autoRun: busterTest.autoRun, referee: referee, assertions: referee, formatio: require("formatio"), eventedLogger: require("evented-logger"), frameworkExtension: require("./framework-extension"), wiringExtension: require("./wiring-extension"), sinon: require("buster-sinon"), refereeSinon: require("referee-sinon") }; Object.defineProperty(buster, "VERSION", { get: function () { if (!this.version) { var pkgJSON = path.resolve(__dirname, "..", "package.json"); var pkg = JSON.parse(fs.readFileSync(pkgJSON, "utf8")); this.version = pkg.version; } return this.version; } }); } var logFormatter = buster.formatio.configure({ quoteStrings: false }); var asciiFormat = function () { return logFormatter.ascii.apply(logFormatter, arguments); }; if (asciiFormat) { buster.console = buster.eventedLogger.create({ formatter: asciiFormat, logFunctions: true }); } buster.log = function () { return buster.console.log.apply(buster.console, arguments); }; buster.captureConsole = function () { glbl.console = buster.console; if (glbl.console !== buster.console) { glbl.console.log = buster.log; } }; if (asciiFormat) { buster.referee.format = asciiFormat; } buster.assert = buster.referee.assert; buster.refute = buster.referee.refute; buster.expect = buster.referee.expect; if (Object.defineProperty) { Object.defineProperty(buster, "assertions", { get: function () { console.log("buster.assertions is provided for backwards compatibility. Please update your code to use buster.referee"); return buster.referee; } }); Object.defineProperty(buster, "format", { get: function () { console.log("buster.format is provided for backwards compatibility. Please update your code to use buster.formatio"); return buster.formatio; } }); } else { buster.assertions = buster.referee; buster.format = buster.formatio; } buster.testRunner.onCreate(function (runner) { buster.referee.on("pass", function () { runner.assertionPass(); }); buster.referee.on("failure", function (err) { runner.assertionFailure(err); }); runner.on("test:async", function () { buster.referee.throwOnFailure = false; }); runner.on("test:setUp", function () { buster.referee.throwOnFailure = true; }); runner.on("context:start", function (context) { if (context.testCase) { context.testCase.log = buster.log; } }); }); var sf = typeof stackFilter !== "undefined" && stackFilter; buster.sinon(sinon, buster, sf, logFormatter); buster.refereeSinon(buster.referee, sinon); }(typeof global != "undefined" ? global : this, typeof buster == "object" ? buster : null, typeof sinon == "object" ? sinon : null)); (function (B) { B.env = B.env || {}; // Globally uncaught errors will be emitted as messages through // the test runner function uncaughtErrors(runner) { window.onerror = function (message, url, line) { if (arguments.length === 3) { var cp = B.env.contextPath || window.location; var index = (url || "").indexOf(cp); if (index >= 0) { url = "." + url.slice(index + cp.length); } if (line === 1 && message === "Error loading script") { message = "Unable to load script " + url; } else { message = url + ":" + line + " " + message; } } runner.emit("uncaughtException", { name: "UncaughtError", message: message }); return true; }; } // Emit messages from the evented logger buster.console through // the test runner function logger(runner) { B.console.on("log", function (msg) { runner.emit("log", msg); }); } // Collect test cases and specs created with buster.testCase // and buster.spec.describe function testContexts() { var contexts = []; B.addTestContext = function (context) { contexts.push(context); }; B.testContext.on("create", B.addTestContext); return contexts; } // Clear scripts and use the browserEnv object from buster-test to // reset the document between tests runs function documentState(runner) { var scripts = document.getElementsByTagName("script"), script; while ((script = scripts[0])) { script.parentNode.removeChild(script); } var env = B.browserEnv.create(document.body); env.listen(runner); } function shouldAutoRun(config) { var autoRunPropertyIsSet = config.hasOwnProperty("autoRun"); return config.autoRun || !autoRunPropertyIsSet; } function shouldResetDoc(config) { var resetDocumentPropertyIsSet = config.hasOwnProperty("resetDocument"); return config.resetDocument || !resetDocumentPropertyIsSet; } // Wire up the test runner. It will start running tests when // the environment is ready and when we've been told to run. // Note that run() and ready() may occur in any order, and // we cannot do anything until both have happened. // // When running tests with buster-server, we'll be ready() when // the server sends the "tests:run" message. This message is sent // by the server when it receives the "loaded all scripts" message // from the browser. We'll usually run as soon as we're ready. // However, if the autoRun option is false, we will not run // until buster.run() is explicitly called. // // For static browser runs, the environment is ready() when // ready() is called, which happens after all files have been // loaded in the browser. Tests will run immediately for autoRun: // true, and on run() otherwise. // function testRunner(runner) { var ctxts = B.wire.testContexts(); var ready, started, alreadyRunning, config; function attemptRun() { if (!ready || !started || alreadyRunning) { return; } alreadyRunning = true; if (typeof runner === "function") { runner = runner(); } if (shouldResetDoc(config)) { B.wire.documentState(runner); } if (config.captureConsole) { B.captureConsole(); } for (var prop in config) { runner[prop] = config[prop]; } runner.runSuite(B.testContext.compile(ctxts, config.filters)); } return { ready: function (options) { config = options || {}; ready = true; started = started || shouldAutoRun(config); attemptRun(); }, run: function () { started = true; attemptRun(); } }; } B.wire = function (testRunner) { var wiring = B.wire.testRunner(testRunner); B.ready = wiring.ready; B.run = wiring.run; return wiring; }; B.wire.uncaughtErrors = uncaughtErrors; B.wire.logger = logger; B.wire.testContexts = testContexts; B.wire.documentState = documentState; B.wire.testRunner = testRunner; }(buster)); // TMP Performance fix (function () { var i = 0; buster.nextTick = function (cb) { i += 1; if (i === 10) { setTimeout(function () { cb(); }, 0); i = 0; } else { cb(); } }; }()); buster.sinon = sinon; delete this.sinon; delete this.define; delete this.when; delete this.async; delete this.platform; delete this._; if (typeof module === "object" && typeof require === "function") { var buster = module.exports = require("./buster/buster-wiring"); } (function (glbl) { var tc = buster.testContext; if (tc.listeners && (tc.listeners.create || []).length > 0) { return; } tc.on("create", buster.autoRun({ cwd: typeof process != "undefined" ? process.cwd() : null })); }(typeof global != "undefined" ? global : this));
busterjs/lt-instabuster
node_modules/buster/resources/buster-test.js
JavaScript
gpl-3.0
524,225
define("view/mission", ["jquery", "laces.tie", "lodash", "view", "tmpl/joboutput", "tmpl/mission"], function($, Laces, _, View, tmpl) { "use strict"; return View.extend({ initialize: function(options) { this.mission = options.mission; this.mission.jobs.on("add", this._onNewJobs, { context: this }); this.subscribe("server-push:missions:job-output", this._onJobOutput); this.$jobs = null; }, events: { "click .action-expand-job": "_expandJob" }, remove: function() { this.mission.jobs.off("add", this._onNewJobs); }, render: function() { var lastJob = this.mission.jobs[this.mission.jobs.length - 1]; if (lastJob) { lastJob.expanded = true; lastJob.fetchResults({ context: this }).then(function() { var tie = new Laces.Tie(lastJob, tmpl.joboutput); var $jobOutput = this.$(".js-job-output[data-job-id='" + lastJob.id + "']"); $jobOutput.replaceWith(tie.render()); }); } var tie = new Laces.Tie(this.mission, tmpl.mission); this.$el.html(tie.render()); this.$jobs = this.$(".js-jobs"); _.each(this.mission.jobs, _.bind(this._renderJob, this)); return this.$el; }, _expandJob: function(event) { var jobId = this.targetData(event, "job-id"); var job = _.find(this.mission.jobs, { id: jobId }); job.expanded = !job.expanded; if (job.expanded) { job.fetchResults(); } }, _onNewJobs: function(event) { _.each(event.elements, _.bind(this._renderJob, this)); }, _onJobOutput: function(data) { if (data.missionId === this.mission.id) { var job = _.find(this.mission.jobs, { id: data.jobId }); if (job && job.expanded) { var $output = this.$(".js-job-output[data-job-id=" + $.jsEscape(data.jobId) + "] .js-output"); if ($output.length) { $output[0].innerHTML += $.colored(data.output); } } } }, _renderJob: function(job) { if (this.$jobs) { var tie = new Laces.Tie(job, tmpl.joboutput); this.$jobs.prepend(tie.render()); } } }); });
arendjr/CI-Joe
www/js/view/mission.js
JavaScript
gpl-3.0
2,619
function GCList(field, multipleSelection, uploadFile, refreshParent = false) { this.field = field; this.multipleSelection = multipleSelection; this.uploadFile = uploadFile; this.refreshParent = refreshParent; this.dialogId = 'list_dialog'; this.options = {}; this.urls = { 'ajax/dataList.php': ['data'], 'ajax/fileList.php': ['filename'], 'ajax/lookupList.php': ['lookup_table'], 'ajax/fieldList.php': ['class_text', 'label_angle', 'label_color', 'label_outlinecolor', 'label_size', 'label_font', 'label_priority', 'angle', 'color', 'outlinecolor', 'size', 'labelitem', 'labelsizeitem', 'classitem', 'classtitle', 'field_name', 'qt_field_name', 'data_field_1', 'data_field_2', 'data_field_3', 'table_field_1', 'table_field_2', 'table_field_3', 'filter_field_name'], 'ajax/dbList.php': ['field_format', 'table_name', 'symbol_ttf_name', 'symbol_name', 'symbol_user_pixmap'], 'ajax/fontList.php': ['symbol_user_font'] }; this.requireSquareBrackets = ['class_text', 'label_angle', 'label_color', 'label_outlinecolor', 'label_size', 'label_font', 'label_priority', 'angle', 'color', 'outlinecolor', 'size', 'classtitle']; this.listData = {}; this.selectedData = {}; this.currentStep = null; this.totSteps = null; this.getUrl = function() { var self = this; var requestUrl = null; $.each(self.urls, function (url, fields) { if ($.inArray(self.field, fields) > -1) { requestUrl = url; return false; } }); if (requestUrl === null) { alert('Not implemented'); return; } return requestUrl; }; this.getParams = function(data) { var params = {}; if (!$.isArray(data)) { if (data.length > 0) { data = data.split('@'); } else { data = new Array(); } } $.each(data, function (e, field) { if ($('#' + field).length > 0 && $('#' + field).val()) { params[field] = $('#' + field).val(); } }); return params; }; this.checkResponse = function(response) { var errorMsg = null; if (typeof response !== 'object') { errorMsg = 'response is not in JSON format'; } else if (response === null) { errorMsg = 'response is null'; } else if (typeof response.result === 'undefined' || response.result !== 'ok') { errorMsg = 'invalid result field'; } else if ( typeof response.fields !== 'object' || typeof response.data !== 'object' || typeof response.step === 'undefined' || typeof response.steps === 'undefined') { errorMsg = 'invalid server response format'; } else if (typeof response.error !== 'undefined') { if ($.inArray(response.error, ['catalog_id', 'layertype_id', 'data']) > -1) { errorMsg = 'invalid '.response.error; } else { errorMsg = response.error; } } return errorMsg; }; this.loadStructuredList = function (params) { $.extend(this.selectedData, params); params.selectedField = this.field; var component = $('#' + this.dialogId).find('div'); $('#' + this.dialogId).find('table').css("display", "none"); component.css("display", ""); component.empty(); component.append(ajaxBuildSelector(this, params, "main")); component.addClass("treeMenuDiv"); if(!this.uploadFile) { component.css("max-height", "95%"); $(".uploadFile_listDialog").css("display","none"); } $('#main').treeview(); createFileListBehaviour(params['selectedField'], this.multipleSelection); } this.loadList = function (params) { var self = this; var dialogId = this.dialogId; var options = this.options; var dialogElement = $('#' + dialogId); dialogElement.find('div').css("display", "none"); var resultTable = dialogElement.find('table'); resultTable.css("display", ""); var requestUrl = self.getUrl(); self.listData = {}; $.extend(self.selectedData, params); params.selectedField = self.field; if(!this.uploadFile) { dialogElement.css("max-height", "100%"); $(".uploadFile_listDialog").css("display","none"); } $.ajax({ url: requestUrl, type: 'POST', dataType: 'json', data: params, success: function (response) { var errorMsg = self.checkResponse(response); if (errorMsg !== null) { alert('Error: ' + errorMsg); dialogElement.dialog('close'); return; } resultTable.empty(); self.currentStep = response.step; self.totSteps = response.steps; // create table header var html = '<tr>'; $.each(response.fields, function (fieldName, fieldTitle) { html += '<th class="tableSelectorHeader">' + fieldTitle + '</th>'; }); html += '</tr>'; // add rows with symbols to table $.each(response.data, function (rowId, rowData) { html += '<tr data-row_id=' + rowId + '>'; $.each(response.fields, function (fieldName, foo) { if (typeof rowData[fieldName] === 'undefined' || rowData[fieldName] === null) { html += '<td class="data-' + fieldName + ' tableSelectorRow"></td>'; return; } html += '<td class="data-' + fieldName + ' tableSelectorRow">' + rowData[fieldName] + '</td>'; }); html += '</tr>'; }); resultTable.append(html); $.each(response.data_objects, function (rowId, rowData) { self.listData[rowId] = rowData; }); resultTable.find('td').hover(function () { $(this).css('cursor', 'pointer'); }, function () { $(this).css('cursor', 'default'); }); if (typeof options.handle_click === 'undefined' || options.handle_click) { resultTable.find('td').click(function (event) { var rowId = $(this).parent().attr('data-row_id'); $.extend(self.selectedData, self.listData[rowId]); if (self.currentStep == self.totSteps || typeof (self.listData[rowId].is_final_step) != 'undefined' && self.listData[rowId].is_final_step == 1) { $.each(self.selectedData, function (key, val) { if ($.inArray(key, self.requireSquareBrackets) > -1) val = '[' + val + ']'; $('#' + key).val(val); }); dialogElement.dialog('close'); //questa istruzione funziona solo nel caso openListAndRefreshEntity venga invocato //a livello di configurazione layer. Negli altri casi non ci entra... - MZ if(self.refreshParent) { var input = $("<input>").attr("type", "hidden").attr("name", "reloadFields").val("true"); $('#frm_data').append($(input)); } } else { self.currentStep += 1; if(self.selectedData.directory != undefined && self.selectedData.directory.endsWith("../")) { var navDir = self.selectedData.directory.replace("../",""); var index = (navDir.substr(0, navDir.length -1 )).lastIndexOf("/"); var back = navDir.substr(0, index + 1); self.selectedData.directory = (back != "") ? back : undefined; } self.selectedData.step = self.currentStep; self.loadList(self.selectedData); } }); } if (typeof options.events !== 'undefined' && typeof options.events.list_loaded !== 'undefined') { options.events.list_loaded(); } }, error: function () { alert('AJAX request returned with error'); } }); }; this.loadData = function(params, callback) { var self = this; var requestUrl = self.getUrl(); params.selectedField = self.field; $.ajax({ url: requestUrl, type: 'POST', dataType: 'json', data: params, success: function (response) { var errorMsg = self.checkResponse(response); if (errorMsg !== null) { alert('Error'); return; } callback(response); }, error: function () { alert('AJAX request returned with error'); } }); }; } function getSelectedField(txt_field) { var selectedField; if (txt_field.indexOf('.') > 0) { var tmp = txt_field.split('.'); selectedField = tmp[0]; } else { selectedField = txt_field; } return selectedField; } function openListAndRefreshEntity(txt_field, data) { genericOpenList(txt_field, data, true); } function openList(txt_field, data) { genericOpenList(txt_field, data); } function genericOpenList(txt_field, data, refresh = false) { var selectedField = getSelectedField(txt_field); $('#list_dialog').dialog({ width: 500, height: 350, title: '', modal: true, open: function () { var list = new GCList(selectedField, false, false, refresh); list.loadList(list.getParams(data)); } }); } function openFileTree(txt_field, data, multipleSelection = false, uploadFile = false) { var selectedField = getSelectedField(txt_field); var list = new GCList(selectedField, multipleSelection, uploadFile); $('#list_dialog').dialog({ width: 500, height: 350, title: '', modal: true, open: function () { list.loadStructuredList(list.getParams(data)); } }); $('#submitFile').click(function(event) { event.preventDefault(); var file_data = $('#fileToUpload').prop('files')[0]; var form_data = new FormData(); form_data.append('file', file_data); $.ajax({ url: 'ajax/upload.php', dataType: 'text', // what to expect back from the PHP script, if anything cache: false, contentType: false, processData: false, data: form_data, type: 'post', success: function(response){ if(response!="") alert(response); // display response from the PHP script, if any else { list.loadFileList(list.getParams(data)); $('#fileToUpload').val(""); } } }); }); } function buildSelector(response, obj, directory, id) { if(response.fields['file'] != undefined && response.fields['file'] != null) $('#' + obj.dialogId ).dialog("option", "title", response.fields['file']); var html = ""; if(response.data_objects.length > 0) { if(id != undefined) { html += "<ul id=\""+id+"\" class=\"filetree treeview-famfamfam\">"; html += "<li><span class='folder'>" html += (obj.multipleSelection ? "<input type=\"checkbox\" id=\"p_ckb_\">" : ""); html += "</span>"; } html += "<ul>"; $.each(response.data_objects, function(rowId, rowData) { obj.listData[rowId] = rowData; if(rowData['directory'] != undefined && rowData['directory']!= null && !rowData['directory'].endsWith("../")){ html += "<li><span class='folder'>"; html += (obj.multipleSelection ? "<input type=\"checkbox\" id=\"p_ckb_"+directoryForCheckbox(rowData['directory'])+"\">" : ""); html += directoryForTreeOutput(rowData['directory'])+"</span>"; html += ajaxBuildSelector(obj, $.extend({}, obj.selectedData, obj.listData[rowId])); html += "</li>"; } else if(rowData[obj.field] != undefined && rowData[obj.field]!= null) { var check = fieldContainsString($("#"+obj.field).val(), directory+rowData[obj.field]); html += "<li><span class='file'><input type=\"checkbox\" "+(check ? "checked" : "")+" id=\"ckb_" + directoryForCheckbox(directory)+rowData[obj.field]+"\" name=\"checkList\" value=\""+directory+rowData[obj.field] + "\"/>"+rowData[obj.field]+"</span></li>"; if(!directory) checkTreeConsistency("ckb_"+directoryForCheckbox(directory), check); } }); html += '</ul>'; if(id != undefined) { html += "</li></ul>"; } } else { html += "<ul id=\""+id+"\" class=\"filetree treeview-famfamfam\">"; html += "<li><span class='folder'>- no files -</span>"; html += "</li></ul>"; } return html; } function fieldContainsString(fieldVal, searchKey) { var arr = fieldVal.split(' '); var result = false $.each(arr, function(index, val) { if(val == searchKey) { result = true; return false; } }); return result; } function directoryForTreeOutput(inputDir) { var output = inputDir.substring(0, inputDir.length-1); return output.lastIndexOf("/")!=-1 ? output.substring(output.lastIndexOf("/")+1) : output; } function directoryForCheckbox(inputDir) { return inputDir.replace(/\//g,"_"); } function ajaxBuildSelector(obj, params, id){ var result = ""; $.ajax({ url: obj.getUrl(), type: 'POST', async: false, dataType: 'json', data: params, success: function (response) { var errorMsg = obj.checkResponse(response); if (errorMsg !== null) { alert('Error: ' + errorMsg); $('#' + obj.dialogId ).dialog('close'); return; } var directory = params['directory']!=undefined ? params['directory'] : ""; // create table header result = buildSelector(response, obj, directory, id); }, error: function () { alert('AJAX request returned with error'); } }); return result; } function populateTextField(field, checked, value) { //circondo stringa con spazi in modo da poter essere sicuro di beccare esattamente la stringa che mi interessa in caso di "eliminazione" var fieldText = checked ? $('#' + field).val() : " "+$('#' + field).val()+" "; fieldText = $.trim(checked ? fieldText.concat(" " + value) : fieldText.replace(new RegExp("[ ]{1}"+value+"[ ]{1}"), " ")); $('#' + field).val(fieldText.replace(/\s+/g, " ")); } function updateExtent(txt_field) { var selectedField = getSelectedField(txt_field); var data = ["catalog_id", "layertype_id", "layergroup", "project", "data", "data_geom", "data_type", "data_srid"]; var list = new GCList(selectedField); var params = list.getParams(data); // skip step params.step = 1; // force request for data_extent params.data_extent = null; list.loadData(params, function(response) { $.each(response.data_objects, function (rowId, rowData) { if (rowData.data_unique === $('#data_unique').val()) { $('#data_extent').val(rowData.data_extent); } }); }); } function createFileListBehaviour(field, multipleSelection) { $('[id^=p_ckb_]').change(function() { var newstate = $(this).is(":checked") ? ":not(:checked)" : ":checked"; var id_leaf = $(this).attr("id").substring(2); $('[id^='+$(this).attr("id")+']'+newstate).click(); $('[id^='+id_leaf+']'+newstate).click(); }); $('[id^=ckb_]').change(function() { var checked = $(this).is(":checked"); var currentId = $(this).attr("id"); var currentFile = $(this).val().substring($(this).val().lastIndexOf("/")+1); if(!multipleSelection) { var group = "input:checkbox[name='checkList']"; $(group).prop("checked", false); $(this).prop("checked", checked); $("#" + field).val(""); } populateTextField(field, checked, $(this).val()); var dirId = currentId.replace(currentFile, ""); checkTreeConsistency(dirId, checked); }); } function checkTreeConsistency(parentDir, check) { var workingDir = parentDir; var allSelected = ($('[id^='+workingDir+']').length == $('[id^='+workingDir+']:checked').length); if((check && allSelected) || !check) { $("#p_"+workingDir).attr("checked", check); workingDir = workingDir.substring(0, workingDir.length -1); if (workingDir.indexOf("_") != -1) checkTreeConsistency(workingDir.substring(0, workingDir.lastIndexOf("_") + 1), check); } }
OldSnapo/gisclient-3
public/admin/js/list.js
JavaScript
gpl-3.0
17,763
// QChartGallery.js --- // // Author: Julien Wintz // Created: Thu Feb 13 23:43:13 2014 (+0100) // Version: // Last-Updated: // By: // Update #: 13 // // Change Log: // // // ///////////////////////////////////////////////////////////////// // Line Chart Data Sample // ///////////////////////////////////////////////////////////////// var ChartLineData = { labels: [], datasets: [{ fillColor: "rgba(151,187,205,0.5)", strokeColor: "grey", pointColor: "rgba(151,187,205,1)", pointStrokeColor: "grey", data: [] }/**, { fillColor: "rgba(151,187,205,0.5)", strokeColor: "rgba(151,187,205,1)", pointColor: "rgba(151,187,205,1)", pointStrokeColor: "#ffffff", data: [] }**/] } // ///////////////////////////////////////////////////////////////// // Polar Chart Data Sample // ///////////////////////////////////////////////////////////////// var ChartPolarData = [{ value: 30, color: "#D97041" }, { value: 90, color: "#C7604C" }, { value: 24, color: "#21323D" }, { value: 58, color: "#9D9B7F" }, { value: 82, color: "#7D4F6D" }, { value: 8, color: "#584A5E" }] // ///////////////////////////////////////////////////////////////// // Radar Chart Data Sample // ///////////////////////////////////////////////////////////////// var ChartRadarData = { labels: ["Eating","Drinking","Sleeping","Designing","Coding","Partying","Running"], datasets: [{ fillColor: "rgba(220,220,220,0.5)", strokeColor: "rgba(220,220,220,1)", pointColor: "rgba(220,220,220,1)", pointStrokeColor: "#fff", data: [65,59,90,81,56,55,40] }, { fillColor: "rgba(151,187,205,0.5)", strokeColor: "rgba(151,187,205,1)", pointColor: "rgba(151,187,205,1)", pointStrokeColor: "#fff", data: [28,48,40,19,96,27,100] }] } // ///////////////////////////////////////////////////////////////// // Pie Chart Data Sample // ///////////////////////////////////////////////////////////////// var ChartPieData = [{ value: 30, color: "#F38630" }, { value: 50, color: "#E0E4CC" }, { value: 100, color: "#69D2E7" }] // ///////////////////////////////////////////////////////////////// // Doughnut Chart Data Sample // ///////////////////////////////////////////////////////////////// var ChartDoughnutData = [{ value: 30, color: "#F7464A" }, { value: 50, color: "#E2EAE9" }, { value: 100, color: "#D4CCC5" }, { value: 40, color: "#949FB1" }, { value: 120, color: "#4D5360" }] // ///////////////////////////////////////////////////////////////// // Bar Chart Data Sample // ///////////////////////////////////////////////////////////////// var ChartBarData = { labels: ["January","February","March","April","May","June","July"], datasets: [{ fillColor: "rgba(220,220,220,0.5)", strokeColor: "rgba(220,220,220,1)", data: [65,59,90,81,56,55,40] }, { fillColor: "rgba(151,187,205,0.5)", strokeColor: "rgba(151,187,205,1)", data: [28,48,40,19,96,27,100] }] }
SensorNet-UFAL/environmentMonitoring
laccansense/jbQuick/QChartGallery.js
JavaScript
gpl-3.0
3,346
/* * jQuery Fast Confirm * version: 2.1.1 (2011-03-23) * @requires jQuery v1.3.2 or later * * Examples and documentation at: http://blog.pierrejeanparra.com/jquery-plugins/fast-confirm/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function ($) { var methods = { init: function (options) { var params; if (!this.length) { return this; } $.fastConfirm = { defaults: { position: 'bottom', offset: {top: 0, left: 0}, zIndex: 10000, eventToBind: false, questionText: "Are you sure?", proceedText: "Yes", cancelText: "No", targetElement: null, unique: false, fastConfirmClass: "fast_confirm", onProceed: function ($trigger) { $trigger.fastConfirm('close'); return true; }, onCancel: function ($trigger) { $trigger.fastConfirm('close'); return false; } } }; params = $.extend($.fastConfirm.defaults, options || {}); return this.each(function () { var trigger = this, $trigger = $(this), $confirmYes = $('<button class="' + params.fastConfirmClass + '_proceed">' + params.proceedText + '</button>'), $confirmNo = $('<button class="' + params.fastConfirmClass + '_cancel">' + params.cancelText + '</button>'), $confirmBox = $('<div class="' + params.fastConfirmClass + '"><div class="' + params.fastConfirmClass + '_arrow_border"></div><div class="' + params.fastConfirmClass + '_arrow"></div>' + params.questionText + '<br/></div>'), $arrow = $('div.' + params.fastConfirmClass + '_arrow', $confirmBox), $arrowBorder = $('div.' + params.fastConfirmClass + '_arrow_border', $confirmBox), confirmBoxArrowClass, confirmBoxArrowBorderClass, $target = params.targetElement ? $(params.targetElement, $trigger) : $trigger, offset = $target.offset(), topOffset, leftOffset, displayBox = function () { if (!$trigger.data('fast_confirm.box')) { $trigger.data('fast_confirm.params.fastConfirmClass', params.fastConfirmClass); // Close all other confirm boxes if necessary if (params.unique) { $('.' + params.fastConfirmClass + '_trigger').fastConfirm('close'); } // Register actions $confirmYes.bind('click.fast_confirm', function () { // In case the DOM has been refreshed in the meantime or something... $trigger.data('fast_confirm.box', $confirmBox).addClass(params.fastConfirmClass + '_trigger'); params.onProceed($trigger); // If the user wants us to handle events if (params.eventToBind) { trigger[params.eventToBind](); } }); $confirmNo.bind('click.fast_confirm', function () { // In case the DOM has been refreshed in the meantime or something... $trigger.data('fast_confirm.box', $confirmBox).addClass(params.fastConfirmClass + '_trigger'); params.onCancel($trigger); }); $confirmBox // Makes the confirm box focusable .attr("tabIndex", -1) // Bind Escape key to close the confirm box .bind('keydown.fast_confirm', function (event) { if (event.keyCode && event.keyCode === 27) { $trigger.fastConfirm('close'); } }); // Append the confirm box to the body. It will not be visible as it is off-screen by default. Positionning will be done at the last time $confirmBox.append($confirmYes).append($confirmNo); $('body').append($confirmBox); // Calculate absolute positionning depending on the trigger-relative position switch (params.position) { case 'top': confirmBoxArrowClass = params.fastConfirmClass + '_bottom'; confirmBoxArrowBorderClass = params.fastConfirmClass + '_bottom'; $arrow.addClass(confirmBoxArrowClass).css('left', $confirmBox.outerWidth() / 2 - $arrow.outerWidth() / 2); $arrowBorder.addClass(confirmBoxArrowBorderClass).css('left', $confirmBox.outerWidth() / 2 - $arrowBorder.outerWidth() / 2); topOffset = offset.top - $confirmBox.outerHeight() - $arrowBorder.outerHeight() + params.offset.top; leftOffset = offset.left - $confirmBox.outerWidth() / 2 + $target.outerWidth() / 2 + params.offset.left; break; case 'right': confirmBoxArrowClass = params.fastConfirmClass + '_left'; confirmBoxArrowBorderClass = params.fastConfirmClass + '_left'; $arrow.addClass(confirmBoxArrowClass).css('top', $confirmBox.outerHeight() / 2 - $arrow.outerHeight() / 2); $arrowBorder.addClass(confirmBoxArrowBorderClass).css('top', $confirmBox.outerHeight() / 2 - $arrowBorder.outerHeight() / 2); topOffset = offset.top + $target.outerHeight() / 2 - $confirmBox.outerHeight() / 2 + params.offset.top; leftOffset = offset.left + $target.outerWidth() + $arrowBorder.outerWidth() + params.offset.left; break; case 'bottom': confirmBoxArrowClass = params.fastConfirmClass + '_top'; confirmBoxArrowBorderClass = params.fastConfirmClass + '_top'; $arrow.addClass(confirmBoxArrowClass).css('left', $confirmBox.outerWidth() / 2 - $arrow.outerWidth() / 2); $arrowBorder.addClass(confirmBoxArrowBorderClass).css('left', $confirmBox.outerWidth() / 2 - $arrowBorder.outerWidth() / 2); topOffset = offset.top + $target.outerHeight() + $arrowBorder.outerHeight() + params.offset.top; leftOffset = offset.left - $confirmBox.outerWidth() / 2 + $target.outerWidth() / 2 + params.offset.left; break; case 'left': confirmBoxArrowClass = params.fastConfirmClass + '_right'; confirmBoxArrowBorderClass = params.fastConfirmClass + '_right'; $arrow.addClass(confirmBoxArrowClass).css('top', $confirmBox.outerHeight() / 2 - $arrow.outerHeight() / 2); $arrowBorder.addClass(confirmBoxArrowBorderClass).css('top', $confirmBox.outerHeight() / 2 - $arrowBorder.outerHeight() / 2); topOffset = offset.top + $target.outerHeight() / 2 - $confirmBox.outerHeight() / 2 + params.offset.top; leftOffset = offset.left - $confirmBox.outerWidth() - $arrowBorder.outerWidth() + params.offset.left; break; } // Make the confirm box appear right where it belongs $confirmBox.css({ top: topOffset, left: leftOffset, zIndex: params.zIndex }).focus(); // Link trigger and confirm box $trigger.data('fast_confirm.box', $confirmBox).addClass(params.fastConfirmClass + '_trigger'); } }; // If the user wants to give us complete control over event handling if (params.eventToBind) { $trigger.bind(params.eventToBind + '.fast_confirm', function () { displayBox(); return false; }); } else { // Let event handling to the user, just display the confirm box displayBox(); } }); }, // Close the confirm box close: function () { return this.each(function () { var $this = $(this); $this.data('fast_confirm.box').remove(); $this.removeData('fast_confirm.box').removeClass($this.data('fast_confirm.params.fastConfirmClass') + '_trigger'); }); } }; $.fn.fastConfirm = function (method) { if (!this.length) { return this; } // Method calling logic if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.fastConfirm'); } }; })(jQuery);
apiary/apiary-project
src/workflow/assets/js/jquery.fastconfirm.js
JavaScript
gpl-3.0
7,913
OJ.extendClass( 'NwEvent', [OjEvent], { '_get_props_' : { 'data' : null }, '_constructor' : function(type/*, bubbles = false, cancelable = false, data = null*/){ var ln = arguments.length; this._super(OjEvent, '_constructor', ln > 3 ? [].slice.call(arguments, 0, 3) : arguments); if(ln > 3){ this._data = arguments[3]; } } } );
NuAge-Solutions/NW
src/js/events/NwEvent.js
JavaScript
gpl-3.0
361
'use strict'; angular.module('MainConsole') .factory('WebSocketService', ['$rootScope', '$q', '$filter', '$location', function ($rootScope, $q, $filter, $location) { var service = {}; service.wsConnect = function() { // Websocket is at wss://hostname:port/ws var host = $location.host(); var port = $location.port(); var wsUrl = $rootScope.urlscheme.websocket + '/ws'; var ws = new WebSocket(wsUrl); ws.onopen = function(){ $rootScope.connected = 1; console.log("Socket has been opened!"); }; ws.onerror = function(){ $rootScope.connected = 0; console.log("Socket received an error!"); }; ws.onclose = function(){ $rootScope.connected = 0; console.log("Socket has been closed!"); } ws.onmessage = function(message) { //listener(JSON.parse(message.data)); service.callback(JSON.parse(message.data)); }; service.ws = ws; console.log('WebSocket Initialized'); }; service.listener = function(callback) { service.callback = callback; }; service.send = function(message) { service.ws.send(message); }; service.close = function(){ service.ws.close(); $rootScope.connected = 0; console.log("Socket has been closed!"); }; return service; }]);
bammv/sguil
server/html/sguilclient/websocketService.js
JavaScript
gpl-3.0
1,652
var webpack = require('webpack'); var path = require('path'); const ExtractTextPlugin = require("extract-text-webpack-plugin"); const extractLess = new ExtractTextPlugin({ filename: "[name].[contenthash].css", disable: process.env.NODE_ENV === "development" }); module.exports = { context: path.join(__dirname, "src"), devtool: "source-map", entry: "./app/index.jsx", module: { loaders: [{ test: /(\.js|\.jsx)$/, exclude: /(node_modules|dist)/, loader: 'babel-loader', query: { presets: ['react', 'es2015'] } }, { test: /\.svg$/, use: [{ loader: 'babel-loader' }, { loader: 'react-svg-loader', options: { svgo: { plugins: [{ removeTitle: false }], floatPrecision: 2 } } } ] }, { test: /\.scss$/, loader: "style-loader!css-loader!sass-loader" }, { test: /\.jpg$/, use: ["file-loader"] }, { test: /\.png$/, use: ["url-loader?mimetype=image/png"] }, { test: /\.(html)$/, use: { loader: 'html-loader', options: { attrs: [':data-src'] } } } ] }, output: { path: __dirname + "/dist/", filename: "bundle.js" }, plugins: [ new webpack.ProvidePlugin({ 'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch' }), extractLess ], };
shimmy568/SlickPhotoGallery
webpack.config.js
JavaScript
gpl-3.0
2,072
// Make screen : lists different control activities and allows to select which to use var MakeScreen = Screen.extend({ enter: function(){ // Display this screen this.display('make_screen'); // Setup button clicks this.html.find(".btn-play").off().click(function(){ fabrica.navigation.go("/make/play"); }); this.html.find(".btn-upload").off().click(function(){ fabrica.navigation.go("/make/upload"); }); }, }); screens.make = new MakeScreen();
arthurwolf/fabrica
src/interfaces/fabrica/make/make.js
JavaScript
gpl-3.0
503
const chart = { format: '{point.name}: {point.y:,.2f}', colorNames: [ 'success', 'info', 'warning', 'danger', 'primary', 'highlight', 'default' ], colors: [], patterns: [], style: {}, plotOptions: function () { return { series: { animation: false, dataLabels: { enabled: true, format: this.format }, cursor: 'pointer', borderWidth: 3, } } }, responsivePlotOptions: function () { return { series: { animation: false, dataLabels: { format: this.format } } } }, rule: function () { return { condition: { maxWidth: 500 }, chartOptions: { plotOptions: this.responsivePlotOptions() } } }, getPattern: function(index, colors) { const p = index % Highcharts.patterns.length; return { pattern: Highcharts.merge( Highcharts.patterns[p], { color: colors[index] } ) } }, cssVar: function(name) { return this.style.getPropertyValue(`--${name}`) }, init: function(decimal, thousand) { this.style = getComputedStyle(document.documentElement) for (let p = 0; p < 4; p++) { for (let n = 0; n < this.colorNames.length; n++) { const color = this.cssVar( `${this.colorNames[n]}-${p}` ) this.colors.push(color) } } this.patterns = this.colors.map( (_, index, array) => this.getPattern(index, array) ) Highcharts.setOptions({ chart: { style: { fontFamily: this.cssVar('--font-general'), }, }, lang: { decimalPoint: decimal, thousandsSep: thousand, }, }); }, draw: function(id, title, seriesName, data) { const chart = Highcharts.chart( id, { chart: { type: 'pie' }, title: { text: title, style: { color: this.cssVar('primary-0'), } }, colors: this.patterns, plotOptions: this.plotOptions(), series: [{ name: seriesName, data: data }], responsive: { rules: [this.rule()] }, } ) const that = this $('#patterns-enabled').click(function () { chart.update({ colors: this.checked ? that.patterns : that.colors }) }) }, }
darakeon/dfm
site/MVC/Assets/scripts/chart.js
JavaScript
gpl-3.0
2,100
if (Meteor.isClient) { Session.setDefault('degF',-40); Session.setDefault('degC',-40); Template.temperatureBoxes.helpers({ degF: function(){ return Session.get('degF'); }, degC: function(){ return Session.get('degC'); } }); Template.temperatureBoxes.events({ 'keyup #c': function(e){ if(e.which === 13) { var degC = e.target.value; var degF = Math.round(degC*9/5 + 32); Session.set('degF',degF); } }, 'keyup #f': function(e){ if(e.which === 13) { var degF = e.target.value; var degC = Math.round((degF-32)* 5/9); Session.set('degC',degC); } } }); } if (Meteor.isServer) { Meteor.startup(function () { // code to run on server at startup }); }
a2life/meteor-temp-converter
tempconv.js
JavaScript
gpl-3.0
786
function handleDialogRequest(dialogName, xhr, status, args) { if (!args.success) { PF(dialogName).jq.effect("shake", {times : 5}, 100); } else { PF(dialogName).hide(); } }
matjaz99/DTools
WebContent/resources/default/1_0/js/dtools.js
JavaScript
gpl-3.0
180
var __v=[ { "Id": 2056, "Panel": 1052, "Name": "array", "Sort": 0, "Str": "" }, { "Id": 2057, "Panel": 1052, "Name": "相關接口", "Sort": 0, "Str": "" }, { "Id": 2058, "Panel": 1052, "Name": "Example", "Sort": 0, "Str": "" } ]
zuiwuchang/king-document
data/panels/1052.js
JavaScript
gpl-3.0
287
/* * Copyright (C) 2020 Graylog, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. */ import Reflux from 'reflux'; import URLUtils from 'util/URLUtils'; import ApiRoutes from 'routing/ApiRoutes'; import fetch from 'logic/rest/FetchProvider'; import MessageFormatter from 'logic/message/MessageFormatter'; import ObjectUtils from 'util/ObjectUtils'; import CombinedProvider from 'injection/CombinedProvider'; const { SimulatorActions } = CombinedProvider.get('Simulator'); const SimulatorStore = Reflux.createStore({ listenables: [SimulatorActions], simulate(stream, messageFields, inputId) { const url = URLUtils.qualifyUrl(ApiRoutes.SimulatorController.simulate().url); const simulation = { stream_id: stream.id, message: messageFields, input_id: inputId, }; let promise = fetch('POST', url, simulation); promise = promise.then((response) => { const formattedResponse = ObjectUtils.clone(response); formattedResponse.messages = response.messages.map((msg) => MessageFormatter.formatMessageSummary(msg)); return formattedResponse; }); SimulatorActions.simulate.promise(promise); }, }); export default SimulatorStore;
Graylog2/graylog2-server
graylog2-web-interface/src/stores/simulator/SimulatorStore.js
JavaScript
gpl-3.0
1,756
app .service('LanguageService', function LanguageService(ExchangeService) { this.translate = (label) => ExchangeService.i18n().__(label); });
Kagurame/LuaSB
src/app/ui/services/LanguageService.js
JavaScript
gpl-3.0
150
/** * Created by ken_kilgore1 on 1/11/2015. */ jQuery(document).ready(function ($) { $("#spouse_info").hide(); $("#spouse_spacer").hide(); $("#family_info").hide(); $("#family_spacer").hide(); $("input:radio[name$='memb_type']").click(function () { if ($("input[name$='memb_type']:checked").val() === 1) { $("#spouse_info").hide(); $("#spouse_spacer").hide(); $("#family_info").hide(); $("#family_spacer").hide(); } else if ($("input[name$='memb_type']:checked").val() === 2) { $("#spouse_info").hide(); $("#spouse_spacer").hide(); $("#family_info").show(); $("#family_spacer").show(); } else if ($("input[name$='memb_type']:checked").val() === 3) { $("#spouse_spacer").show(); $("#spouse_info").show(); $("#family_info").hide(); $("#family_spacer").hide(); } else if ($("input[name$='memb_type']:checked").val() === 4) { $("#spouse_info").show(); $("#spouse_spacer").show(); $("#family_info").show(); $("#family_spacer").show(); } }); });
ctxphc/beach-holiday
includes/js/mp-show-hide-script.js
JavaScript
gpl-3.0
1,199
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Sebastian Werner (wpbasti) * Andreas Ecker (ecker) ************************************************************************ */ /** * This class is used to define interfaces (similar to Java interfaces). * * See the description of the {@link #define} method how an interface is * defined. */ qx.Bootstrap.define("qx.Interface", { statics : { /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ /** * Define a new interface. Interface definitions look much like class definitions. * * The main difference is that the bodies of functions defined in <code>members</code> * and <code>statics</code> are called before the original function with the * same arguments. This can be used to check the passed arguments. If the * checks fail, an exception should be thrown. It is convenient to use the * method defined in {@link qx.core.MAssert} to check the arguments. * * In the <code>build</code> version the checks are omitted. * * For properties only the names are required so the value of the properties * can be empty maps. * * Example: * <pre class='javascript'> * qx.Interface.define("name", * { * extend: [SuperInterfaces], * * statics: * { * PI : 3.14 * }, * * properties: {"color": {}, "name": {} }, * * members: * { * meth1: function() {}, * meth2: function(a, b) { this.assertArgumentsCount(arguments, 2, 2); }, * meth3: function(c) { this.assertInterface(c.constructor, qx.some.Interface); } * }, * * events : * { * keydown : "qx.event.type.KeySequence" * } * }); * </pre> * * @param name {String} name of the interface * @param config {Map ? null} Interface definition structure. The configuration map has the following keys: * <table> * <tr><th>Name</th><th>Type</th><th>Description</th></tr> * <tr><th>extend</th><td>Interface |<br>Interface[]</td><td>Single interface or array of interfaces this interface inherits from.</td></tr> * <tr><th>members</th><td>Map</td><td>Map of members of the interface.</td></tr> * <tr><th>statics</th><td>Map</td><td> * Map of statics of the interface. The statics will not get copied into the target class. * This is the same behaviour as statics in mixins ({@link qx.Mixin#define}). * </td></tr> * <tr><th>properties</th><td>Map</td><td>Map of properties and their definitions.</td></tr> * <tr><th>events</th><td>Map</td><td>Map of event names and the corresponding event class name.</td></tr> * </table> */ define : function(name, config) { if (config) { // Normalize include if (config.extend && !(qx.Bootstrap.getClass(config.extend) === "Array")) { config.extend = [config.extend]; } // Validate incoming data if (qx.core.Environment.get("qx.debug")) { this.__validateConfig(name, config); } // Create interface from statics var iface = config.statics ? config.statics : {}; // Attach configuration if (config.extend) { iface.$$extends = config.extend; } if (config.properties) { iface.$$properties = config.properties; } if (config.members) { iface.$$members = config.members; } if (config.events) { iface.$$events = config.events; } } else { // Create empty interface var iface = {}; } // Add Basics iface.$$type = "Interface"; iface.name = name; // Attach toString iface.toString = this.genericToString; // Assign to namespace iface.basename = qx.Bootstrap.createNamespace(name, iface); // Add to registry qx.Interface.$$registry[name] = iface; // Return final interface return iface; }, /** * Returns an interface by name * * @param name {String} class name to resolve * @return {Class} the class */ getByName : function(name) { return this.$$registry[name]; }, /** * Determine if interface exists * * @param name {String} Interface name to check * @return {Boolean} true if interface exists */ isDefined : function(name) { return this.getByName(name) !== undefined; }, /** * Determine the number of interfaces which are defined * * @return {Number} the number of interfaces */ getTotalNumber : function() { return qx.Bootstrap.objectGetLength(this.$$registry); }, /** * Generates a list of all interfaces including their super interfaces * (resolved recursively) * * @param ifaces {Interface[] ? []} List of interfaces to be resolved * @return {Array} List of all interfaces */ flatten : function(ifaces) { if (!ifaces) { return []; } // we need to create a copy and not to modify the existing array var list = ifaces.concat(); for (var i=0, l=ifaces.length; i<l; i++) { if (ifaces[i].$$extends) { list.push.apply(list, this.flatten(ifaces[i].$$extends)); } } return list; }, /** * Assert members * * @param object {qx.core.Object} The object, which contains the methods * @param clazz {Class} class of the object * @param iface {Interface} the interface to verify * @param wrap {Boolean ? false} wrap functions required by interface to * check parameters etc. */ __assertMembers : function(object, clazz, iface, wrap) { // Validate members var members = iface.$$members; if (members) { for (var key in members) { if (qx.Bootstrap.isFunction(members[key])) { var isPropertyMethod = this.__isPropertyMethod(clazz, key); var hasMemberFunction = isPropertyMethod || qx.Bootstrap.isFunction(object[key]); if (!hasMemberFunction) { throw new Error( 'Implementation of method "' + key + '" is missing in class "' + clazz.classname + '" required by interface "' + iface.name + '"' ); } // Only wrap members if the interface was not been applied yet. This // can easily be checked by the recursive hasInterface method. var shouldWrapFunction = wrap === true && !isPropertyMethod && !qx.util.OOUtil.hasInterface(clazz, iface); if (shouldWrapFunction) { object[key] = this.__wrapInterfaceMember( iface, object[key], key, members[key] ); } } else { // Other members are not checked more detailed because of // JavaScript's loose type handling if (typeof object[key] === undefined) { if (typeof object[key] !== "function") { throw new Error( 'Implementation of member "' + key + '" is missing in class "' + clazz.classname + '" required by interface "' + iface.name + '"' ); } } } } } }, /** * Internal helper to detect if the method will be generated by the * property system. * * @param clazz {Class} The current class. * @param methodName {String} The name of the method. * * @return {Boolean} true, if the method will be generated by the property * system. */ __isPropertyMethod: function(clazz, methodName) { var match = methodName.match(/^(is|toggle|get|set|reset)(.*)$/); if (!match) { return false; } var propertyName = qx.Bootstrap.firstLow(match[2]); var isPropertyMethod = qx.util.OOUtil.getPropertyDefinition(clazz, propertyName); if (!isPropertyMethod) { return false; } var isBoolean = match[0] == "is" || match[0] == "toggle"; if (isBoolean) { return qx.util.OOUtil.getPropertyDefinition(clazz, propertyName).check == "Boolean"; } return true; }, /** * Assert properties * * @param clazz {Class} class to check interface for * @param iface {Interface} the interface to verify */ __assertProperties : function(clazz, iface) { if (iface.$$properties) { for (var key in iface.$$properties) { if (!qx.util.OOUtil.getPropertyDefinition(clazz, key)) { throw new Error( 'The property "' + key + '" is not supported by Class "' + clazz.classname + '"!' ); } } } }, /** * Assert events * * @param clazz {Class} class to check interface for * @param iface {Interface} the interface to verify */ __assertEvents : function(clazz, iface) { if (iface.$$events) { for (var key in iface.$$events) { if (!qx.util.OOUtil.supportsEvent(clazz, key)) { throw new Error( 'The event "' + key + '" is not supported by Class "' + clazz.classname + '"!' ); } } } }, /** * Asserts that the given object implements all the methods defined in the * interface. This method throws an exception if the object does not * implement the interface. * * @param object {qx.core.Object} Object to check interface for * @param iface {Interface} The interface to verify */ assertObject : function(object, iface) { var clazz = object.constructor; this.__assertMembers(object, clazz, iface, false); this.__assertProperties(clazz, iface); this.__assertEvents(clazz, iface); // Validate extends, recursive var extend = iface.$$extends; if (extend) { for (var i=0, l=extend.length; i<l; i++) { this.assertObject(object, extend[i]); } } }, /** * Checks if an interface is implemented by a class * * @param clazz {Class} class to check interface for * @param iface {Interface} the interface to verify * @param wrap {Boolean ? false} wrap functions required by interface to * check parameters etc. */ assert : function(clazz, iface, wrap) { this.__assertMembers(clazz.prototype, clazz, iface, wrap); this.__assertProperties(clazz, iface); this.__assertEvents(clazz, iface); // Validate extends, recursive var extend = iface.$$extends; if (extend) { for (var i=0, l=extend.length; i<l; i++) { this.assert(clazz, extend[i], wrap); } } }, /* --------------------------------------------------------------------------- PRIVATE/INTERNAL API --------------------------------------------------------------------------- */ /** * This method will be attached to all interface to return * a nice identifier for them. * * @internal * @return {String} The interface identifier */ genericToString : function() { return "[Interface " + this.name + "]"; }, /** Registry of all defined interfaces */ $$registry : {}, /** * Wrap a method with a precondition check. * * @signature function(iface, origFunction, functionName, preCondition) * @param iface {String} Name of the interface, where the pre condition * was defined. (Used in error messages). * @param origFunction {Function} function to wrap. * @param functionName {String} name of the function. (Used in error messages). * @param preCondition {Function}. This function gets called with the arguments of the * original function. If this function return true the original function is called. * Otherwise an exception is thrown. * @return {Function} wrapped function */ __wrapInterfaceMember : qx.core.Environment.select("qx.debug", { "true": function(iface, origFunction, functionName, preCondition) { function wrappedFunction() { // call precondition preCondition.apply(this, arguments); // call original function return origFunction.apply(this, arguments); } origFunction.wrapper = wrappedFunction; return wrappedFunction; }, "default" : function() {} }), /** {Map} allowed keys in interface definition */ __allowedKeys : qx.core.Environment.select("qx.debug", { "true": { "extend" : "object", // Interface | Interface[] "statics" : "object", // Map "members" : "object", // Map "properties" : "object", // Map "events" : "object" // Map }, "default" : null }), /** * Validates incoming configuration and checks keys and values * * @signature function(name, config) * @param name {String} The name of the class * @param config {Map} Configuration map */ __validateConfig : qx.core.Environment.select("qx.debug", { "true": function(name, config) { if (qx.core.Environment.get("qx.debug")) { // Validate keys var allowed = this.__allowedKeys; for (var key in config) { if (allowed[key] === undefined) { throw new Error('The configuration key "' + key + '" in class "' + name + '" is not allowed!'); } if (config[key] == null) { throw new Error("Invalid key '" + key + "' in interface '" + name + "'! The value is undefined/null!"); } if (allowed[key] !== null && typeof config[key] !== allowed[key]) { throw new Error('Invalid type of key "' + key + '" in interface "' + name + '"! The type of the key must be "' + allowed[key] + '"!'); } } // Validate maps var maps = [ "statics", "members", "properties", "events" ]; for (var i=0, l=maps.length; i<l; i++) { var key = maps[i]; if (config[key] !== undefined && ([ "Array", "RegExp", "Date" ].indexOf(qx.Bootstrap.getClass(config[key])) != -1 || config[key].classname !== undefined)) { throw new Error('Invalid key "' + key + '" in interface "' + name + '"! The value needs to be a map!'); } } // Validate extends if (config.extend) { for (var i=0, a=config.extend, l=a.length; i<l; i++) { if (a[i] == null) { throw new Error("Extends of interfaces must be interfaces. The extend number '" + i+1 + "' in interface '" + name + "' is undefined/null!"); } if (a[i].$$type !== "Interface") { throw new Error("Extends of interfaces must be interfaces. The extend number '" + i+1 + "' in interface '" + name + "' is not an interface!"); } } } // Validate statics if (config.statics) { for (var key in config.statics) { if (key.toUpperCase() !== key) { throw new Error('Invalid key "' + key + '" in interface "' + name + '"! Static constants must be all uppercase.'); } switch(typeof config.statics[key]) { case "boolean": case "string": case "number": break; default: throw new Error('Invalid key "' + key + '" in interface "' + name + '"! Static constants must be all of a primitive type.') } } } } }, "default" : function() {} }) } });
09zwcbupt/undergrad_thesis
ext/poxdesk/qx/framework/source/class/qx/Interface.js
JavaScript
gpl-3.0
16,949
var __v=[ { "Id": 2329, "Chapter": 746, "Name": "nodejs", "Sort": 0 } ]
zuiwuchang/king-document
data/chapters/746.js
JavaScript
gpl-3.0
88
function content($slide) { return $slide.children().first().nextAll(); } function addReplToSlide($, deck, $slide) { var endpoint = $[deck]('getOptions').repl.endpoint; content($slide).wrapAll('<div class="repl-slide-column repl-text-column"></div>'); var replHtmlId = "console-" + $slide[0].id; $('<div/>', { id: replHtmlId, class: 'repl-slide-column repl-console-column' }) .appendTo($slide); $('<script></script>') .append("$(function () { newConsole('" + endpoint + "', $('#" + replHtmlId + "')); });") .appendTo($slide); content($slide).wrapAll('<div class="repl-slide-columns"></div>'); } function protocol() { switch (location.protocol) { case 'https:': return 'wss:'; default: return 'ws:'; } } function url(endpoint) { return protocol() + endpoint; } function getContext(element) { return element.attr('data-repl-context') || element.parents('[data-repl-context]').attr('data-repl-context'); } function hasContext(element) { var ctx = getContext(element); return ctx !== undefined && ctx !== ""; } function newConsole(endpoint, element) { var replContext = getContext(element); var jqconsole = element.jqconsole("", "> "); var startPrompt; var writeText = function(text) { jqconsole.Write(text, 'jqconsole-output'); startPrompt(); }; var writeError = function(text) { jqconsole.Write(text, 'jqconsole-error'); startPrompt(); } jqconsole.Disable(); addFullscreenHint(element); if (endpoint) { var connect = function () { var ws = new WebSocket(url(endpoint)); ws.onmessage = function(event) { jqconsole.Enable(); writeText(event.data); }; ws.onerror = function(event) { writeError("Connection error\n"); }; ws.onopen = function(event) { ws.send("/load " + replContext); }; return ws; } var ws = connect(); startPrompt = function () { jqconsole.Prompt(true, function (input) { if (input === '/reconnect') { ws = connect(); } else if (input !== '') { if (ws.readyState === WebSocket.OPEN) { ws.send(input); } else { writeError("Not connected."); } } }); }; var setup = function() { jqconsole.RegisterShortcut('L', reset); startPrompt(); }; var reset = function() { var history = jqconsole.GetHistory(); jqconsole.Reset(); jqconsole.SetHistory(history); setup(); }; setup(); } else { startPrompt = function() {}; writeText("REPL offline.\n" + "No livecoding for you :-("); jqconsole.Prompt(true, function() {}); } }; function addFullscreenHint(element) { $('<div/>', { class: 'repl-fullscreen-hint', text: 'Fullscreen — Hit F to quit' }).appendTo(element); } function toggleOrder(i, order) { switch (order) { case '0': return '1'; default: return '0'; } } function isKey(e, keyValue) { return e.which === keyValue || $.inArray(e.which, keyValue) > -1; } (function($, deck, window, undefined) { var $d = $(document); /* Extends defaults/options. options.keys.replPositionToggle Key to toggle REPL position between left and right (right by default). Default key is 'T'. options.keys.replFullscreenToggle Key to toggle REPL to fullscreen, hiding the other column and slide title. Default key is 'F'. options.repl.endpoint URL of the websocket endpoint to use for REPL without the protocol part. */ $.extend(true, $[deck].defaults, { classes: { repl: 'deck-repl' }, keys: { replPositionToggle: 84, // t replFullscreenToggle: 70 // f }, repl: { endpoint: '' } }); $d.bind('deck.beforeInit', function() { if ($[deck]('getOptions').repl.endpoint) { warnAgainstCtrlW($); } $.each($[deck]('getSlides'), function(i, $slide) { if ($slide.hasClass('repl') && hasContext($slide)) { addReplToSlide($, deck, $slide); } }); }); /* jQuery.deck('toggleReplPosition') Toggles REPL position (right column first). */ $[deck]('extend', 'toggleReplPosition', function() { $('.repl-console-column').css('order', toggleOrder); }); $[deck]('extend', 'toggleReplFullscreen', function() { $('.deck-current .repl-slide-columns').siblings().toggle(); $('.deck-current .repl-text-column').toggle(); $('.deck-current .repl-console-column').toggleClass('repl-console-column-fullscreen'); }); $d.bind('deck.init', function() { var opts = $[deck]('getOptions'); // Bind key events $d.unbind('keydown.deckrepl').bind('keydown.deckrepl', function(e) { if (isKey(e, opts.keys.replPositionToggle)) { $[deck]('toggleReplPosition'); e.preventDefault(); } if (isKey(e, opts.keys.replFullscreenToggle)) { $[deck]('toggleReplFullscreen'); e.preventDefault(); } }); }); })(jQuery, 'deck', this); function warnAgainstCtrlW($) { $(window).on('beforeunload', function(e) { return 'Bad habit of deleting words with Ctrl-W? ESC to stay here.'; }); }
ptitfred/slidecoding
web/deckjs/extensions/repl/deck.repl.js
JavaScript
gpl-3.0
5,193
var searchData= [ ['sdio_5fisr',['sdio_isr',['../group__CM3__nvic__isrprototypes__STM32F2.html#gab47b4803bd30546e2635832b5fdb92fe',1,'nvic.h']]], ['spi1_5fisr',['spi1_isr',['../group__CM3__nvic__isrprototypes__STM32F2.html#gad680d21d3e734ad7ce84e5a9dce5af5c',1,'nvic.h']]], ['spi2_5fisr',['spi2_isr',['../group__CM3__nvic__isrprototypes__STM32F2.html#gabe80c6cda580ec6a1e915e9f7e192879',1,'nvic.h']]], ['spi3_5fisr',['spi3_isr',['../group__CM3__nvic__isrprototypes__STM32F2.html#ga433dae627c4694ab9055540a7694248d',1,'nvic.h']]], ['spi_5fclean_5fdisable',['spi_clean_disable',['../group__spi__defines.html#gaf76785dab1741f75d4fc2f03793b57d9',1,'spi_clean_disable(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gaf76785dab1741f75d4fc2f03793b57d9',1,'spi_clean_disable(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fdisable',['spi_disable',['../group__spi__defines.html#ga3a67a664d96e95e80d3308b7d53736e6',1,'spi_disable(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga3a67a664d96e95e80d3308b7d53736e6',1,'spi_disable(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fdisable_5fcrc',['spi_disable_crc',['../group__spi__defines.html#ga168934fcc518d617447514ca06a48b3c',1,'spi_disable_crc(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga168934fcc518d617447514ca06a48b3c',1,'spi_disable_crc(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fdisable_5ferror_5finterrupt',['spi_disable_error_interrupt',['../group__spi__defines.html#gaa84513c1f4d95c7de20b9416447c2148',1,'spi_disable_error_interrupt(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gaa84513c1f4d95c7de20b9416447c2148',1,'spi_disable_error_interrupt(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fdisable_5frx_5fbuffer_5fnot_5fempty_5finterrupt',['spi_disable_rx_buffer_not_empty_interrupt',['../group__spi__defines.html#gada77b72d4924b55840e73ed14a325978',1,'spi_disable_rx_buffer_not_empty_interrupt(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gada77b72d4924b55840e73ed14a325978',1,'spi_disable_rx_buffer_not_empty_interrupt(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fdisable_5frx_5fdma',['spi_disable_rx_dma',['../group__spi__defines.html#ga010e94503b79a98060a9920fd8f50806',1,'spi_disable_rx_dma(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga010e94503b79a98060a9920fd8f50806',1,'spi_disable_rx_dma(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fdisable_5fsoftware_5fslave_5fmanagement',['spi_disable_software_slave_management',['../group__spi__defines.html#ga4cf9bda5fa58c220e6d45d6a809737c4',1,'spi_disable_software_slave_management(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga4cf9bda5fa58c220e6d45d6a809737c4',1,'spi_disable_software_slave_management(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fdisable_5fss_5foutput',['spi_disable_ss_output',['../group__spi__defines.html#ga8cd024f5b5f4806bbeeec58e8e79162b',1,'spi_disable_ss_output(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga8cd024f5b5f4806bbeeec58e8e79162b',1,'spi_disable_ss_output(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fdisable_5ftx_5fbuffer_5fempty_5finterrupt',['spi_disable_tx_buffer_empty_interrupt',['../group__spi__defines.html#gac803fac4d999f49c7ecbda22aa5b7221',1,'spi_disable_tx_buffer_empty_interrupt(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gac803fac4d999f49c7ecbda22aa5b7221',1,'spi_disable_tx_buffer_empty_interrupt(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fdisable_5ftx_5fdma',['spi_disable_tx_dma',['../group__spi__defines.html#gafc90aaa52298179b5190ee677ac5d4cc',1,'spi_disable_tx_dma(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gafc90aaa52298179b5190ee677ac5d4cc',1,'spi_disable_tx_dma(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fenable',['spi_enable',['../group__spi__defines.html#ga33fbdd2e4f6b876273a2b3f0e05eb6b4',1,'spi_enable(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga33fbdd2e4f6b876273a2b3f0e05eb6b4',1,'spi_enable(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fenable_5fcrc',['spi_enable_crc',['../group__spi__defines.html#ga3993016e02c92b696c8661840e602a00',1,'spi_enable_crc(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga3993016e02c92b696c8661840e602a00',1,'spi_enable_crc(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fenable_5ferror_5finterrupt',['spi_enable_error_interrupt',['../group__spi__defines.html#gaedf50e8ee8ec6f033231a2c49b4ac1a1',1,'spi_enable_error_interrupt(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gaedf50e8ee8ec6f033231a2c49b4ac1a1',1,'spi_enable_error_interrupt(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fenable_5frx_5fbuffer_5fnot_5fempty_5finterrupt',['spi_enable_rx_buffer_not_empty_interrupt',['../group__spi__defines.html#gad05d3885fad620fc84d284fc9b42554e',1,'spi_enable_rx_buffer_not_empty_interrupt(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gad05d3885fad620fc84d284fc9b42554e',1,'spi_enable_rx_buffer_not_empty_interrupt(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fenable_5frx_5fdma',['spi_enable_rx_dma',['../group__spi__defines.html#gac860af47e3356336e01495554de5e506',1,'spi_enable_rx_dma(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gac860af47e3356336e01495554de5e506',1,'spi_enable_rx_dma(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fenable_5fsoftware_5fslave_5fmanagement',['spi_enable_software_slave_management',['../group__spi__defines.html#gab3cb4176148e6f3602a0b238f32eb83b',1,'spi_enable_software_slave_management(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gab3cb4176148e6f3602a0b238f32eb83b',1,'spi_enable_software_slave_management(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fenable_5fss_5foutput',['spi_enable_ss_output',['../group__spi__defines.html#gada533027af13ff16aceb7daad049c4e4',1,'spi_enable_ss_output(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gada533027af13ff16aceb7daad049c4e4',1,'spi_enable_ss_output(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fenable_5ftx_5fbuffer_5fempty_5finterrupt',['spi_enable_tx_buffer_empty_interrupt',['../group__spi__defines.html#ga4c552fab799a9009bc541a3fb41061fe',1,'spi_enable_tx_buffer_empty_interrupt(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga4c552fab799a9009bc541a3fb41061fe',1,'spi_enable_tx_buffer_empty_interrupt(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fenable_5ftx_5fdma',['spi_enable_tx_dma',['../group__spi__defines.html#ga74726047b7cad9c11465a3cf4d0fd090',1,'spi_enable_tx_dma(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga74726047b7cad9c11465a3cf4d0fd090',1,'spi_enable_tx_dma(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5finit_5fmaster',['spi_init_master',['../group__spi__defines.html#gaa963b02acbae0939ec4537a8136873ed',1,'spi_init_master(uint32_t spi, uint32_t br, uint32_t cpol, uint32_t cpha, uint32_t dff, uint32_t lsbfirst):&#160;spi_common_l1f124.c'],['../group__spi__file.html#gaa963b02acbae0939ec4537a8136873ed',1,'spi_init_master(uint32_t spi, uint32_t br, uint32_t cpol, uint32_t cpha, uint32_t dff, uint32_t lsbfirst):&#160;spi_common_l1f124.c']]], ['spi_5fread',['spi_read',['../group__spi__defines.html#ga1bfe6bd4512dc398cb7f680feec01b20',1,'spi_read(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga1bfe6bd4512dc398cb7f680feec01b20',1,'spi_read(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5freset',['spi_reset',['../group__spi__defines.html#gaae815897f2f548556dde9fa8ecb13058',1,'spi_reset(uint32_t spi_peripheral):&#160;spi_common_all.c'],['../group__spi__file.html#gaae815897f2f548556dde9fa8ecb13058',1,'spi_reset(uint32_t spi_peripheral):&#160;spi_common_all.c']]], ['spi_5fsend',['spi_send',['../group__spi__defines.html#ga1fcf7661af69bcf8999ae3f6d102fd8b',1,'spi_send(uint32_t spi, uint16_t data):&#160;spi_common_all.c'],['../group__spi__file.html#ga1fcf7661af69bcf8999ae3f6d102fd8b',1,'spi_send(uint32_t spi, uint16_t data):&#160;spi_common_all.c']]], ['spi_5fsend_5flsb_5ffirst',['spi_send_lsb_first',['../group__spi__defines.html#ga9f834ea1e68b2c23a4b0866f96f38578',1,'spi_send_lsb_first(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga9f834ea1e68b2c23a4b0866f96f38578',1,'spi_send_lsb_first(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fsend_5fmsb_5ffirst',['spi_send_msb_first',['../group__spi__defines.html#gae19e92c8051fe49e4eac918ee51feeac',1,'spi_send_msb_first(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gae19e92c8051fe49e4eac918ee51feeac',1,'spi_send_msb_first(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fbaudrate_5fprescaler',['spi_set_baudrate_prescaler',['../group__spi__defines.html#ga69a60fb0cd832d3b9a16ce4411328e64',1,'spi_set_baudrate_prescaler(uint32_t spi, uint8_t baudrate):&#160;spi_common_all.c'],['../group__spi__file.html#ga69a60fb0cd832d3b9a16ce4411328e64',1,'spi_set_baudrate_prescaler(uint32_t spi, uint8_t baudrate):&#160;spi_common_all.c']]], ['spi_5fset_5fbidirectional_5fmode',['spi_set_bidirectional_mode',['../group__spi__defines.html#gaf0088037e6a1aa78a9ed4c4e261a55ac',1,'spi_set_bidirectional_mode(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gaf0088037e6a1aa78a9ed4c4e261a55ac',1,'spi_set_bidirectional_mode(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fbidirectional_5freceive_5fonly_5fmode',['spi_set_bidirectional_receive_only_mode',['../group__spi__defines.html#gaf27f88063c2cb644a2935490d61202c5',1,'spi_set_bidirectional_receive_only_mode(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gaf27f88063c2cb644a2935490d61202c5',1,'spi_set_bidirectional_receive_only_mode(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fbidirectional_5ftransmit_5fonly_5fmode',['spi_set_bidirectional_transmit_only_mode',['../group__spi__defines.html#ga8ad1268a257456a854b960f8aa73b1ce',1,'spi_set_bidirectional_transmit_only_mode(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga8ad1268a257456a854b960f8aa73b1ce',1,'spi_set_bidirectional_transmit_only_mode(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fclock_5fphase_5f0',['spi_set_clock_phase_0',['../group__spi__defines.html#gac01452c132ec4c5ffc5d281d43d975d7',1,'spi_set_clock_phase_0(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gac01452c132ec4c5ffc5d281d43d975d7',1,'spi_set_clock_phase_0(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fclock_5fphase_5f1',['spi_set_clock_phase_1',['../group__spi__defines.html#gacd6b278668088bce197d6401787c4e62',1,'spi_set_clock_phase_1(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gacd6b278668088bce197d6401787c4e62',1,'spi_set_clock_phase_1(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fclock_5fpolarity_5f0',['spi_set_clock_polarity_0',['../group__spi__defines.html#ga683b0840af6f7bee227ccb31d57dc36a',1,'spi_set_clock_polarity_0(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga683b0840af6f7bee227ccb31d57dc36a',1,'spi_set_clock_polarity_0(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fclock_5fpolarity_5f1',['spi_set_clock_polarity_1',['../group__spi__defines.html#ga379382439ed44f061ab6fd4232d47319',1,'spi_set_clock_polarity_1(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga379382439ed44f061ab6fd4232d47319',1,'spi_set_clock_polarity_1(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fdff_5f16bit',['spi_set_dff_16bit',['../group__spi__defines.html#ga6665731fd5d37e5dfb00f29f859e6c9c',1,'spi_set_dff_16bit(uint32_t spi):&#160;spi_common_l1f124.c'],['../group__spi__file.html#ga6665731fd5d37e5dfb00f29f859e6c9c',1,'spi_set_dff_16bit(uint32_t spi):&#160;spi_common_l1f124.c']]], ['spi_5fset_5fdff_5f8bit',['spi_set_dff_8bit',['../group__spi__defines.html#ga715bcb5541f2908d16a661b0a6a07014',1,'spi_set_dff_8bit(uint32_t spi):&#160;spi_common_l1f124.c'],['../group__spi__file.html#ga715bcb5541f2908d16a661b0a6a07014',1,'spi_set_dff_8bit(uint32_t spi):&#160;spi_common_l1f124.c']]], ['spi_5fset_5ffull_5fduplex_5fmode',['spi_set_full_duplex_mode',['../group__spi__defines.html#ga714f48c6586abf8ce6e3e118f6303708',1,'spi_set_full_duplex_mode(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga714f48c6586abf8ce6e3e118f6303708',1,'spi_set_full_duplex_mode(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fmaster_5fmode',['spi_set_master_mode',['../group__spi__defines.html#gafca8671510322b29ef82b291dec68dc7',1,'spi_set_master_mode(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gafca8671510322b29ef82b291dec68dc7',1,'spi_set_master_mode(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fnext_5ftx_5ffrom_5fbuffer',['spi_set_next_tx_from_buffer',['../group__spi__defines.html#ga0f70abf18588bb5bbe24da6457cb9ff7',1,'spi_set_next_tx_from_buffer(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga0f70abf18588bb5bbe24da6457cb9ff7',1,'spi_set_next_tx_from_buffer(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fnext_5ftx_5ffrom_5fcrc',['spi_set_next_tx_from_crc',['../group__spi__defines.html#gaabd95475b2fe0fab2a7c22c5ae50aa14',1,'spi_set_next_tx_from_crc(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gaabd95475b2fe0fab2a7c22c5ae50aa14',1,'spi_set_next_tx_from_crc(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fnss_5fhigh',['spi_set_nss_high',['../group__spi__defines.html#gad86076b9c51c2ce18f844d42053ed8cc',1,'spi_set_nss_high(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gad86076b9c51c2ce18f844d42053ed8cc',1,'spi_set_nss_high(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fnss_5flow',['spi_set_nss_low',['../group__spi__defines.html#ga47838ebf43d91e96b65338b6b0a50786',1,'spi_set_nss_low(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga47838ebf43d91e96b65338b6b0a50786',1,'spi_set_nss_low(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5freceive_5fonly_5fmode',['spi_set_receive_only_mode',['../group__spi__defines.html#gaacdf55f39a2de0f53ac356233cc34cbb',1,'spi_set_receive_only_mode(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gaacdf55f39a2de0f53ac356233cc34cbb',1,'spi_set_receive_only_mode(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fslave_5fmode',['spi_set_slave_mode',['../group__spi__defines.html#gae9700a3a5f8301b5b3a8442d257d75dd',1,'spi_set_slave_mode(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#gae9700a3a5f8301b5b3a8442d257d75dd',1,'spi_set_slave_mode(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fset_5fstandard_5fmode',['spi_set_standard_mode',['../group__spi__defines.html#gacebc47030a2733da436142828f0c9fa4',1,'spi_set_standard_mode(uint32_t spi, uint8_t mode):&#160;spi_common_all.c'],['../group__spi__file.html#gacebc47030a2733da436142828f0c9fa4',1,'spi_set_standard_mode(uint32_t spi, uint8_t mode):&#160;spi_common_all.c']]], ['spi_5fset_5funidirectional_5fmode',['spi_set_unidirectional_mode',['../group__spi__defines.html#ga25ed748ce16f85c263594198b702d949',1,'spi_set_unidirectional_mode(uint32_t spi):&#160;spi_common_all.c'],['../group__spi__file.html#ga25ed748ce16f85c263594198b702d949',1,'spi_set_unidirectional_mode(uint32_t spi):&#160;spi_common_all.c']]], ['spi_5fwrite',['spi_write',['../group__spi__defines.html#ga6c3dfa86916c2c38d4a1957f4704bb47',1,'spi_write(uint32_t spi, uint16_t data):&#160;spi_common_all.c'],['../group__spi__file.html#ga6c3dfa86916c2c38d4a1957f4704bb47',1,'spi_write(uint32_t spi, uint16_t data):&#160;spi_common_all.c']]], ['spi_5fxfer',['spi_xfer',['../group__spi__defines.html#gae453ac946166bc51a42c35738d9d005b',1,'spi_xfer(uint32_t spi, uint16_t data):&#160;spi_common_all.c'],['../group__spi__file.html#gae453ac946166bc51a42c35738d9d005b',1,'spi_xfer(uint32_t spi, uint16_t data):&#160;spi_common_all.c']]] ];
Aghosh993/TARS_codebase
libopencm3/doc/stm32f2/html/search/functions_c.js
JavaScript
gpl-3.0
15,984
/** * * @author xedushx */ $(document).bind("touchmove", function (event) { event.preventDefault(); }); /* * Función que permite bloquear la pantalla mientras esta procesando */ $(function () { $(document).ajaxStart($.blockUI).ajaxStop($.unblockUI); }); /* * Función que bloquea la tecla F5 y Enter de la pagina y detectar tecla arriba y abajo */ $(function () { $(document).keydown(function (e) { if ($('#formulario\\:menu').length) { var code = (e.keyCode ? e.keyCode : e.which); //if(code == 116 || code == 13) { if (code == 13) { e.preventDefault(); } if (code == 40) { teclaAbajo(); e.preventDefault(); } if (code == 38) { teclaArriba(); e.preventDefault(); } } }); }); /* *Función Desabilitar el clik derecho */ //$(function() { // $(document).ready(function(){ // $(document).bind("contextmenu",function(e){ // return false; // }); // }); //}); /* * Funcion que calcula y asigna el ancho y el alto del navegador */ function dimiensionesNavegador() { var na = $(window).height(); document.getElementById('formulario:alto').value = na; var ancho = $(window).width(); document.getElementById('formulario:ancho').value = ancho; } /* * Funcion que calcula y asigna el ancho y el alto disponible sin la barra de menu */ function dimensionesDisponibles() { var na = $(window).height(); var me = $('#formulario\\:menu').height(); var alto = na - me - 45; alto = parseInt(alto); document.getElementById('formulario:ith_alto').value = alto; document.getElementById('formulario:alto').value = na; var ancho = $(window).width(); document.getElementById('formulario:ancho').value = ancho; } /* * Para poner los calendarios, las horas en español */ PrimeFaces.locales['es'] = { closeText: 'Cerrar', prevText: 'Anterior', nextText: 'Siguiente', monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'], monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'], dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'], dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sab'], dayNamesMin: ['D', 'L', 'M', 'M', 'J', 'V', 'S'], weekHeader: 'Semana', firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: '', timeOnlyTitle: 'Sólo hora', timeText: 'Tiempo', hourText: 'Hora', minuteText: 'Minuto', secondText: 'Segundo', currentText: 'Hora actual', ampm: false, month: 'Mes', week: 'Semana', day: 'Día', allDayText: 'Todo el día' }; function abrirPopUp(dir) { var w = window.open(dir, "sistemadj", "width=" + screen.availWidth + ", height=" + screen.availHeight + ", screenX=0,screenY=0, top=0, left=0, status=0 , resizable=yes, scrollbars=yes"); w.focus(); } function abrirNuevoPopUp(dir) { var w = window.open(dir, "", "width=" + screen.availWidth + ", height=" + screen.availHeight + ", screenX=0,screenY=0, top=0, left=0, status=0 , resizable=yes, scrollbars=yes"); w.focus(); }
xedushx/erpxprime
erpxprime/web/resources/sistema/sistema.js
JavaScript
gpl-3.0
3,385
// CodeMirror2 mode/perl/perl.js (text/x-perl) beta 0.10 (2011-11-08) // This is a part of CodeMirror from https://github.com/sabaca/CodeMirror_mode_perl ([email protected]) (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("perl",function(){ // http://perldoc.perl.org var PERL={ // null - magic touch // 1 - keyword // 2 - def // 3 - atom // 4 - operator // 5 - variable-2 (predefined) // [x,y] - x=1,2,3; y=must be defined if x{...} // PERL operators '->' : 4, '++' : 4, '--' : 4, '**' : 4, // ! ~ \ and unary + and - '=~' : 4, '!~' : 4, '*' : 4, '/' : 4, '%' : 4, 'x' : 4, '+' : 4, '-' : 4, '.' : 4, '<<' : 4, '>>' : 4, // named unary operators '<' : 4, '>' : 4, '<=' : 4, '>=' : 4, 'lt' : 4, 'gt' : 4, 'le' : 4, 'ge' : 4, '==' : 4, '!=' : 4, '<=>' : 4, 'eq' : 4, 'ne' : 4, 'cmp' : 4, '~~' : 4, '&' : 4, '|' : 4, '^' : 4, '&&' : 4, '||' : 4, '//' : 4, '..' : 4, '...' : 4, '?' : 4, ':' : 4, '=' : 4, '+=' : 4, '-=' : 4, '*=' : 4, // etc. ??? ',' : 4, '=>' : 4, '::' : 4, // list operators (rightward) 'not' : 4, 'and' : 4, 'or' : 4, 'xor' : 4, // PERL predefined variables (I know, what this is a paranoid idea, but may be needed for people, who learn PERL, and for me as well, ...and may be for you?;) 'BEGIN' : [5,1], 'END' : [5,1], 'PRINT' : [5,1], 'PRINTF' : [5,1], 'GETC' : [5,1], 'READ' : [5,1], 'READLINE' : [5,1], 'DESTROY' : [5,1], 'TIE' : [5,1], 'TIEHANDLE' : [5,1], 'UNTIE' : [5,1], 'STDIN' : 5, 'STDIN_TOP' : 5, 'STDOUT' : 5, 'STDOUT_TOP' : 5, 'STDERR' : 5, 'STDERR_TOP' : 5, '$ARG' : 5, '$_' : 5, '@ARG' : 5, '@_' : 5, '$LIST_SEPARATOR' : 5, '$"' : 5, '$PROCESS_ID' : 5, '$PID' : 5, '$$' : 5, '$REAL_GROUP_ID' : 5, '$GID' : 5, '$(' : 5, '$EFFECTIVE_GROUP_ID' : 5, '$EGID' : 5, '$)' : 5, '$PROGRAM_NAME' : 5, '$0' : 5, '$SUBSCRIPT_SEPARATOR' : 5, '$SUBSEP' : 5, '$;' : 5, '$REAL_USER_ID' : 5, '$UID' : 5, '$<' : 5, '$EFFECTIVE_USER_ID' : 5, '$EUID' : 5, '$>' : 5, '$a' : 5, '$b' : 5, '$COMPILING' : 5, '$^C' : 5, '$DEBUGGING' : 5, '$^D' : 5, '${^ENCODING}' : 5, '$ENV' : 5, '%ENV' : 5, '$SYSTEM_FD_MAX' : 5, '$^F' : 5, '@F' : 5, '${^GLOBAL_PHASE}' : 5, '$^H' : 5, '%^H' : 5, '@INC' : 5, '%INC' : 5, '$INPLACE_EDIT' : 5, '$^I' : 5, '$^M' : 5, '$OSNAME' : 5, '$^O' : 5, '${^OPEN}' : 5, '$PERLDB' : 5, '$^P' : 5, '$SIG' : 5, '%SIG' : 5, '$BASETIME' : 5, '$^T' : 5, '${^TAINT}' : 5, '${^UNICODE}' : 5, '${^UTF8CACHE}' : 5, '${^UTF8LOCALE}' : 5, '$PERL_VERSION' : 5, '$^V' : 5, '${^WIN32_SLOPPY_STAT}' : 5, '$EXECUTABLE_NAME' : 5, '$^X' : 5, '$1' : 5, // - regexp $1, $2... '$MATCH' : 5, '$&' : 5, '${^MATCH}' : 5, '$PREMATCH' : 5, '$`' : 5, '${^PREMATCH}' : 5, '$POSTMATCH' : 5, "$'" : 5, '${^POSTMATCH}' : 5, '$LAST_PAREN_MATCH' : 5, '$+' : 5, '$LAST_SUBMATCH_RESULT' : 5, '$^N' : 5, '@LAST_MATCH_END' : 5, '@+' : 5, '%LAST_PAREN_MATCH' : 5, '%+' : 5, '@LAST_MATCH_START' : 5, '@-' : 5, '%LAST_MATCH_START' : 5, '%-' : 5, '$LAST_REGEXP_CODE_RESULT' : 5, '$^R' : 5, '${^RE_DEBUG_FLAGS}' : 5, '${^RE_TRIE_MAXBUF}' : 5, '$ARGV' : 5, '@ARGV' : 5, 'ARGV' : 5, 'ARGVOUT' : 5, '$OUTPUT_FIELD_SEPARATOR' : 5, '$OFS' : 5, '$,' : 5, '$INPUT_LINE_NUMBER' : 5, '$NR' : 5, '$.' : 5, '$INPUT_RECORD_SEPARATOR' : 5, '$RS' : 5, '$/' : 5, '$OUTPUT_RECORD_SEPARATOR' : 5, '$ORS' : 5, '$\\' : 5, '$OUTPUT_AUTOFLUSH' : 5, '$|' : 5, '$ACCUMULATOR' : 5, '$^A' : 5, '$FORMAT_FORMFEED' : 5, '$^L' : 5, '$FORMAT_PAGE_NUMBER' : 5, '$%' : 5, '$FORMAT_LINES_LEFT' : 5, '$-' : 5, '$FORMAT_LINE_BREAK_CHARACTERS' : 5, '$:' : 5, '$FORMAT_LINES_PER_PAGE' : 5, '$=' : 5, '$FORMAT_TOP_NAME' : 5, '$^' : 5, '$FORMAT_NAME' : 5, '$~' : 5, '${^CHILD_ERROR_NATIVE}' : 5, '$EXTENDED_OS_ERROR' : 5, '$^E' : 5, '$EXCEPTIONS_BEING_CAUGHT' : 5, '$^S' : 5, '$WARNING' : 5, '$^W' : 5, '${^WARNING_BITS}' : 5, '$OS_ERROR' : 5, '$ERRNO' : 5, '$!' : 5, '%OS_ERROR' : 5, '%ERRNO' : 5, '%!' : 5, '$CHILD_ERROR' : 5, '$?' : 5, '$EVAL_ERROR' : 5, '$@' : 5, '$OFMT' : 5, '$#' : 5, '$*' : 5, '$ARRAY_BASE' : 5, '$[' : 5, '$OLD_PERL_VERSION' : 5, '$]' : 5, // PERL blocks 'if' :[1,1], elsif :[1,1], 'else' :[1,1], 'while' :[1,1], unless :[1,1], 'for' :[1,1], foreach :[1,1], // PERL functions 'abs' :1, // - absolute value function accept :1, // - accept an incoming socket connect alarm :1, // - schedule a SIGALRM 'atan2' :1, // - arctangent of Y/X in the range -PI to PI bind :1, // - binds an address to a socket binmode :1, // - prepare binary files for I/O bless :1, // - create an object bootstrap :1, // 'break' :1, // - break out of a "given" block caller :1, // - get context of the current subroutine call chdir :1, // - change your current working directory chmod :1, // - changes the permissions on a list of files chomp :1, // - remove a trailing record separator from a string chop :1, // - remove the last character from a string chown :1, // - change the owership on a list of files chr :1, // - get character this number represents chroot :1, // - make directory new root for path lookups close :1, // - close file (or pipe or socket) handle closedir :1, // - close directory handle connect :1, // - connect to a remote socket 'continue' :[1,1], // - optional trailing block in a while or foreach 'cos' :1, // - cosine function crypt :1, // - one-way passwd-style encryption dbmclose :1, // - breaks binding on a tied dbm file dbmopen :1, // - create binding on a tied dbm file 'default' :1, // defined :1, // - test whether a value, variable, or function is defined 'delete' :1, // - deletes a value from a hash die :1, // - raise an exception or bail out 'do' :1, // - turn a BLOCK into a TERM dump :1, // - create an immediate core dump each :1, // - retrieve the next key/value pair from a hash endgrent :1, // - be done using group file endhostent :1, // - be done using hosts file endnetent :1, // - be done using networks file endprotoent :1, // - be done using protocols file endpwent :1, // - be done using passwd file endservent :1, // - be done using services file eof :1, // - test a filehandle for its end 'eval' :1, // - catch exceptions or compile and run code 'exec' :1, // - abandon this program to run another exists :1, // - test whether a hash key is present exit :1, // - terminate this program 'exp' :1, // - raise I to a power fcntl :1, // - file control system call fileno :1, // - return file descriptor from filehandle flock :1, // - lock an entire file with an advisory lock fork :1, // - create a new process just like this one format :1, // - declare a picture format with use by the write() function formline :1, // - internal function used for formats getc :1, // - get the next character from the filehandle getgrent :1, // - get next group record getgrgid :1, // - get group record given group user ID getgrnam :1, // - get group record given group name gethostbyaddr :1, // - get host record given its address gethostbyname :1, // - get host record given name gethostent :1, // - get next hosts record getlogin :1, // - return who logged in at this tty getnetbyaddr :1, // - get network record given its address getnetbyname :1, // - get networks record given name getnetent :1, // - get next networks record getpeername :1, // - find the other end of a socket connection getpgrp :1, // - get process group getppid :1, // - get parent process ID getpriority :1, // - get current nice value getprotobyname :1, // - get protocol record given name getprotobynumber :1, // - get protocol record numeric protocol getprotoent :1, // - get next protocols record getpwent :1, // - get next passwd record getpwnam :1, // - get passwd record given user login name getpwuid :1, // - get passwd record given user ID getservbyname :1, // - get services record given its name getservbyport :1, // - get services record given numeric port getservent :1, // - get next services record getsockname :1, // - retrieve the sockaddr for a given socket getsockopt :1, // - get socket options on a given socket given :1, // glob :1, // - expand filenames using wildcards gmtime :1, // - convert UNIX time into record or string using Greenwich time 'goto' :1, // - create spaghetti code grep :1, // - locate elements in a list test true against a given criterion hex :1, // - convert a string to a hexadecimal number 'import' :1, // - patch a module's namespace into your own index :1, // - find a substring within a string 'int' :1, // - get the integer portion of a number ioctl :1, // - system-dependent device control system call 'join' :1, // - join a list into a string using a separator keys :1, // - retrieve list of indices from a hash kill :1, // - send a signal to a process or process group last :1, // - exit a block prematurely lc :1, // - return lower-case version of a string lcfirst :1, // - return a string with just the next letter in lower case length :1, // - return the number of bytes in a string 'link' :1, // - create a hard link in the filesytem listen :1, // - register your socket as a server local : 2, // - create a temporary value for a global variable (dynamic scoping) localtime :1, // - convert UNIX time into record or string using local time lock :1, // - get a thread lock on a variable, subroutine, or method 'log' :1, // - retrieve the natural logarithm for a number lstat :1, // - stat a symbolic link m :null, // - match a string with a regular expression pattern map :1, // - apply a change to a list to get back a new list with the changes mkdir :1, // - create a directory msgctl :1, // - SysV IPC message control operations msgget :1, // - get SysV IPC message queue msgrcv :1, // - receive a SysV IPC message from a message queue msgsnd :1, // - send a SysV IPC message to a message queue my : 2, // - declare and assign a local variable (lexical scoping) 'new' :1, // next :1, // - iterate a block prematurely no :1, // - unimport some module symbols or semantics at compile time oct :1, // - convert a string to an octal number open :1, // - open a file, pipe, or descriptor opendir :1, // - open a directory ord :1, // - find a character's numeric representation our : 2, // - declare and assign a package variable (lexical scoping) pack :1, // - convert a list into a binary representation 'package' :1, // - declare a separate global namespace pipe :1, // - open a pair of connected filehandles pop :1, // - remove the last element from an array and return it pos :1, // - find or set the offset for the last/next m//g search print :1, // - output a list to a filehandle printf :1, // - output a formatted list to a filehandle prototype :1, // - get the prototype (if any) of a subroutine push :1, // - append one or more elements to an array q :null, // - singly quote a string qq :null, // - doubly quote a string qr :null, // - Compile pattern quotemeta :null, // - quote regular expression magic characters qw :null, // - quote a list of words qx :null, // - backquote quote a string rand :1, // - retrieve the next pseudorandom number read :1, // - fixed-length buffered input from a filehandle readdir :1, // - get a directory from a directory handle readline :1, // - fetch a record from a file readlink :1, // - determine where a symbolic link is pointing readpipe :1, // - execute a system command and collect standard output recv :1, // - receive a message over a Socket redo :1, // - start this loop iteration over again ref :1, // - find out the type of thing being referenced rename :1, // - change a filename require :1, // - load in external functions from a library at runtime reset :1, // - clear all variables of a given name 'return' :1, // - get out of a function early reverse :1, // - flip a string or a list rewinddir :1, // - reset directory handle rindex :1, // - right-to-left substring search rmdir :1, // - remove a directory s :null, // - replace a pattern with a string say :1, // - print with newline scalar :1, // - force a scalar context seek :1, // - reposition file pointer for random-access I/O seekdir :1, // - reposition directory pointer select :1, // - reset default output or do I/O multiplexing semctl :1, // - SysV semaphore control operations semget :1, // - get set of SysV semaphores semop :1, // - SysV semaphore operations send :1, // - send a message over a socket setgrent :1, // - prepare group file for use sethostent :1, // - prepare hosts file for use setnetent :1, // - prepare networks file for use setpgrp :1, // - set the process group of a process setpriority :1, // - set a process's nice value setprotoent :1, // - prepare protocols file for use setpwent :1, // - prepare passwd file for use setservent :1, // - prepare services file for use setsockopt :1, // - set some socket options shift :1, // - remove the first element of an array, and return it shmctl :1, // - SysV shared memory operations shmget :1, // - get SysV shared memory segment identifier shmread :1, // - read SysV shared memory shmwrite :1, // - write SysV shared memory shutdown :1, // - close down just half of a socket connection 'sin' :1, // - return the sine of a number sleep :1, // - block for some number of seconds socket :1, // - create a socket socketpair :1, // - create a pair of sockets 'sort' :1, // - sort a list of values splice :1, // - add or remove elements anywhere in an array 'split' :1, // - split up a string using a regexp delimiter sprintf :1, // - formatted print into a string 'sqrt' :1, // - square root function srand :1, // - seed the random number generator stat :1, // - get a file's status information state :1, // - declare and assign a state variable (persistent lexical scoping) study :1, // - optimize input data for repeated searches 'sub' :1, // - declare a subroutine, possibly anonymously 'substr' :1, // - get or alter a portion of a stirng symlink :1, // - create a symbolic link to a file syscall :1, // - execute an arbitrary system call sysopen :1, // - open a file, pipe, or descriptor sysread :1, // - fixed-length unbuffered input from a filehandle sysseek :1, // - position I/O pointer on handle used with sysread and syswrite system :1, // - run a separate program syswrite :1, // - fixed-length unbuffered output to a filehandle tell :1, // - get current seekpointer on a filehandle telldir :1, // - get current seekpointer on a directory handle tie :1, // - bind a variable to an object class tied :1, // - get a reference to the object underlying a tied variable time :1, // - return number of seconds since 1970 times :1, // - return elapsed time for self and child processes tr :null, // - transliterate a string truncate :1, // - shorten a file uc :1, // - return upper-case version of a string ucfirst :1, // - return a string with just the next letter in upper case umask :1, // - set file creation mode mask undef :1, // - remove a variable or function definition unlink :1, // - remove one link to a file unpack :1, // - convert binary structure into normal perl variables unshift :1, // - prepend more elements to the beginning of a list untie :1, // - break a tie binding to a variable use :1, // - load in a module at compile time utime :1, // - set a file's last access and modify times values :1, // - return a list of the values in a hash vec :1, // - test or set particular bits in a string wait :1, // - wait for any child process to die waitpid :1, // - wait for a particular child process to die wantarray :1, // - get void vs scalar vs list context of current subroutine call warn :1, // - print debugging info when :1, // write :1, // - print a picture record y :null}; // - transliterate a string var RXstyle="string-2"; var RXmodifiers=/[goseximacplud]/; // NOTE: "m", "s", "y" and "tr" need to correct real modifiers for each regexp type function tokenChain(stream,state,chain,style,tail){ // NOTE: chain.length > 2 is not working now (it's for s[...][...]geos;) state.chain=null; // 12 3tail state.style=null; state.tail=null; state.tokenize=function(stream,state){ var e=false,c,i=0; while(c=stream.next()){ if(c===chain[i]&&!e){ if(chain[++i]!==undefined){ state.chain=chain[i]; state.style=style; state.tail=tail;} else if(tail) stream.eatWhile(tail); state.tokenize=tokenPerl; return style;} e=!e&&c=="\\";} return style;}; return state.tokenize(stream,state);} function tokenSOMETHING(stream,state,string){ state.tokenize=function(stream,state){ if(stream.string==string) state.tokenize=tokenPerl; stream.skipToEnd(); return "string";}; return state.tokenize(stream,state);} function tokenPerl(stream,state){ if(stream.eatSpace()) return null; if(state.chain) return tokenChain(stream,state,state.chain,state.style,state.tail); if(stream.match(/^\-?[\d\.]/,false)) if(stream.match(/^(\-?(\d*\.\d+(e[+-]?\d+)?|\d+\.\d*)|0x[\da-fA-F]+|0b[01]+|\d+(e[+-]?\d+)?)/)) return 'number'; if(stream.match(/^<<(?=\w)/)){ // NOTE: <<SOMETHING\n...\nSOMETHING\n stream.eatWhile(/\w/); return tokenSOMETHING(stream,state,stream.current().substr(2));} if(stream.sol()&&stream.match(/^\=item(?!\w)/)){// NOTE: \n=item...\n=cut\n return tokenSOMETHING(stream,state,'=cut');} var ch=stream.next(); if(ch=='"'||ch=="'"){ // NOTE: ' or " or <<'SOMETHING'\n...\nSOMETHING\n or <<"SOMETHING"\n...\nSOMETHING\n if(prefix(stream, 3)=="<<"+ch){ var p=stream.pos; stream.eatWhile(/\w/); var n=stream.current().substr(1); if(n&&stream.eat(ch)) return tokenSOMETHING(stream,state,n); stream.pos=p;} return tokenChain(stream,state,[ch],"string");} if(ch=="q"){ var c=look(stream, -2); if(!(c&&/\w/.test(c))){ c=look(stream, 0); if(c=="x"){ c=look(stream, 1); if(c=="("){ eatSuffix(stream, 2); return tokenChain(stream,state,[")"],RXstyle,RXmodifiers);} if(c=="["){ eatSuffix(stream, 2); return tokenChain(stream,state,["]"],RXstyle,RXmodifiers);} if(c=="{"){ eatSuffix(stream, 2); return tokenChain(stream,state,["}"],RXstyle,RXmodifiers);} if(c=="<"){ eatSuffix(stream, 2); return tokenChain(stream,state,[">"],RXstyle,RXmodifiers);} if(/[\^'"!~\/]/.test(c)){ eatSuffix(stream, 1); return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers);}} else if(c=="q"){ c=look(stream, 1); if(c=="("){ eatSuffix(stream, 2); return tokenChain(stream,state,[")"],"string");} if(c=="["){ eatSuffix(stream, 2); return tokenChain(stream,state,["]"],"string");} if(c=="{"){ eatSuffix(stream, 2); return tokenChain(stream,state,["}"],"string");} if(c=="<"){ eatSuffix(stream, 2); return tokenChain(stream,state,[">"],"string");} if(/[\^'"!~\/]/.test(c)){ eatSuffix(stream, 1); return tokenChain(stream,state,[stream.eat(c)],"string");}} else if(c=="w"){ c=look(stream, 1); if(c=="("){ eatSuffix(stream, 2); return tokenChain(stream,state,[")"],"bracket");} if(c=="["){ eatSuffix(stream, 2); return tokenChain(stream,state,["]"],"bracket");} if(c=="{"){ eatSuffix(stream, 2); return tokenChain(stream,state,["}"],"bracket");} if(c=="<"){ eatSuffix(stream, 2); return tokenChain(stream,state,[">"],"bracket");} if(/[\^'"!~\/]/.test(c)){ eatSuffix(stream, 1); return tokenChain(stream,state,[stream.eat(c)],"bracket");}} else if(c=="r"){ c=look(stream, 1); if(c=="("){ eatSuffix(stream, 2); return tokenChain(stream,state,[")"],RXstyle,RXmodifiers);} if(c=="["){ eatSuffix(stream, 2); return tokenChain(stream,state,["]"],RXstyle,RXmodifiers);} if(c=="{"){ eatSuffix(stream, 2); return tokenChain(stream,state,["}"],RXstyle,RXmodifiers);} if(c=="<"){ eatSuffix(stream, 2); return tokenChain(stream,state,[">"],RXstyle,RXmodifiers);} if(/[\^'"!~\/]/.test(c)){ eatSuffix(stream, 1); return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers);}} else if(/[\^'"!~\/(\[{<]/.test(c)){ if(c=="("){ eatSuffix(stream, 1); return tokenChain(stream,state,[")"],"string");} if(c=="["){ eatSuffix(stream, 1); return tokenChain(stream,state,["]"],"string");} if(c=="{"){ eatSuffix(stream, 1); return tokenChain(stream,state,["}"],"string");} if(c=="<"){ eatSuffix(stream, 1); return tokenChain(stream,state,[">"],"string");} if(/[\^'"!~\/]/.test(c)){ return tokenChain(stream,state,[stream.eat(c)],"string");}}}} if(ch=="m"){ var c=look(stream, -2); if(!(c&&/\w/.test(c))){ c=stream.eat(/[(\[{<\^'"!~\/]/); if(c){ if(/[\^'"!~\/]/.test(c)){ return tokenChain(stream,state,[c],RXstyle,RXmodifiers);} if(c=="("){ return tokenChain(stream,state,[")"],RXstyle,RXmodifiers);} if(c=="["){ return tokenChain(stream,state,["]"],RXstyle,RXmodifiers);} if(c=="{"){ return tokenChain(stream,state,["}"],RXstyle,RXmodifiers);} if(c=="<"){ return tokenChain(stream,state,[">"],RXstyle,RXmodifiers);}}}} if(ch=="s"){ var c=/[\/>\]})\w]/.test(look(stream, -2)); if(!c){ c=stream.eat(/[(\[{<\^'"!~\/]/); if(c){ if(c=="[") return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers); if(c=="{") return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers); if(c=="<") return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers); if(c=="(") return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers); return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}} if(ch=="y"){ var c=/[\/>\]})\w]/.test(look(stream, -2)); if(!c){ c=stream.eat(/[(\[{<\^'"!~\/]/); if(c){ if(c=="[") return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers); if(c=="{") return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers); if(c=="<") return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers); if(c=="(") return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers); return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}} if(ch=="t"){ var c=/[\/>\]})\w]/.test(look(stream, -2)); if(!c){ c=stream.eat("r");if(c){ c=stream.eat(/[(\[{<\^'"!~\/]/); if(c){ if(c=="[") return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers); if(c=="{") return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers); if(c=="<") return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers); if(c=="(") return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers); return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}}} if(ch=="`"){ return tokenChain(stream,state,[ch],"variable-2");} if(ch=="/"){ if(!/~\s*$/.test(prefix(stream))) return "operator"; else return tokenChain(stream,state,[ch],RXstyle,RXmodifiers);} if(ch=="$"){ var p=stream.pos; if(stream.eatWhile(/\d/)||stream.eat("{")&&stream.eatWhile(/\d/)&&stream.eat("}")) return "variable-2"; else stream.pos=p;} if(/[$@%]/.test(ch)){ var p=stream.pos; if(stream.eat("^")&&stream.eat(/[A-Z]/)||!/[@$%&]/.test(look(stream, -2))&&stream.eat(/[=|\\\-#?@;:&`~\^!\[\]*'"$+.,\/<>()]/)){ var c=stream.current(); if(PERL[c]) return "variable-2";} stream.pos=p;} if(/[$@%&]/.test(ch)){ if(stream.eatWhile(/[\w$\[\]]/)||stream.eat("{")&&stream.eatWhile(/[\w$\[\]]/)&&stream.eat("}")){ var c=stream.current(); if(PERL[c]) return "variable-2"; else return "variable";}} if(ch=="#"){ if(look(stream, -2)!="$"){ stream.skipToEnd(); return "comment";}} if(/[:+\-\^*$&%@=<>!?|\/~\.]/.test(ch)){ var p=stream.pos; stream.eatWhile(/[:+\-\^*$&%@=<>!?|\/~\.]/); if(PERL[stream.current()]) return "operator"; else stream.pos=p;} if(ch=="_"){ if(stream.pos==1){ if(suffix(stream, 6)=="_END__"){ return tokenChain(stream,state,['\0'],"comment");} else if(suffix(stream, 7)=="_DATA__"){ return tokenChain(stream,state,['\0'],"variable-2");} else if(suffix(stream, 7)=="_C__"){ return tokenChain(stream,state,['\0'],"string");}}} if(/\w/.test(ch)){ var p=stream.pos; if(look(stream, -2)=="{"&&(look(stream, 0)=="}"||stream.eatWhile(/\w/)&&look(stream, 0)=="}")) return "string"; else stream.pos=p;} if(/[A-Z]/.test(ch)){ var l=look(stream, -2); var p=stream.pos; stream.eatWhile(/[A-Z_]/); if(/[\da-z]/.test(look(stream, 0))){ stream.pos=p;} else{ var c=PERL[stream.current()]; if(!c) return "meta"; if(c[1]) c=c[0]; if(l!=":"){ if(c==1) return "keyword"; else if(c==2) return "def"; else if(c==3) return "atom"; else if(c==4) return "operator"; else if(c==5) return "variable-2"; else return "meta";} else return "meta";}} if(/[a-zA-Z_]/.test(ch)){ var l=look(stream, -2); stream.eatWhile(/\w/); var c=PERL[stream.current()]; if(!c) return "meta"; if(c[1]) c=c[0]; if(l!=":"){ if(c==1) return "keyword"; else if(c==2) return "def"; else if(c==3) return "atom"; else if(c==4) return "operator"; else if(c==5) return "variable-2"; else return "meta";} else return "meta";} return null;} return{ startState:function(){ return{ tokenize:tokenPerl, chain:null, style:null, tail:null};}, token:function(stream,state){ return (state.tokenize||tokenPerl)(stream,state);}, electricChars:"{}"};}); CodeMirror.registerHelper("wordChars", "perl", /[\\w$]/); CodeMirror.defineMIME("text/x-perl", "perl"); // it's like "peek", but need for look-ahead or look-behind if index < 0 function look(stream, c){ return stream.string.charAt(stream.pos+(c||0)); } // return a part of prefix of current stream from current position function prefix(stream, c){ if(c){ var x=stream.pos-c; return stream.string.substr((x>=0?x:0),c);} else{ return stream.string.substr(0,stream.pos-1); } } // return a part of suffix of current stream from current position function suffix(stream, c){ var y=stream.string.length; var x=y-stream.pos+1; return stream.string.substr(stream.pos,(c&&c<y?c:x)); } // eating and vomiting a part of stream from current position function eatSuffix(stream, c){ var x=stream.pos+c; var y; if(x<=0) stream.pos=0; else if(x>=(y=stream.string.length-1)) stream.pos=y; else stream.pos=x; } });
soliton4/promiseLand-website
src/codemirror4/mode/perl/perl.js
JavaScript
gpl-3.0
56,018
/** * Standalone Window. * * A window in standalone display mode. */ /** * Standalone Window Constructor. * * @extends BaseWindow. * @param {number} id Window ID to give standalone window. * @param {string} url URL to navigate to. * @param {Object} webApp WebApp with metadata to generate window from. */ var StandaloneWindow = function(id, url, webApp) { this.currentUrl = url; if (webApp && webApp.name) { this.name = webApp.name; } else if (webApp && webApp.shortName) { this.name = webApp.shortName; } else { try { this.name = new URL(url).hostname; } catch(e) { this.name = ''; } } if (webApp && webApp.themeColor) { this.themeColor = webApp.themeColor; } BaseWindow.call(this, id); return this; }; StandaloneWindow.prototype = Object.create(BaseWindow.prototype); /** * Window View. */ StandaloneWindow.prototype.view = function() { var titleBarStyle = ''; var titleBarClass = 'standalone-window-title-bar'; if (this.themeColor) { titleBarStyle = 'background-color: ' + this.themeColor + ';'; var rgb = this.hexToRgb(this.themeColor); backgroundBrightness = this.darkOrLight(rgb); titleBarClass += ' ' + backgroundBrightness; } return '<div id="window' + this.id + '"class="standalone-window">' + '<div class="' + titleBarClass + '" style="' + titleBarStyle + '">' + '<span id="standalone-window-title' + this.id + '" class="standalone-window-title">' + this.name + '</span>' + '<button type="button" id="close-window-button' + this.id + '" ' + 'class="close-window-button">' + '</div>' + '<webview src="' + this.currentUrl + '" id="standalone-window-frame' + this.id + '" class="standalone-window-frame">' + '</div>'; }; /** * Render the window. */ StandaloneWindow.prototype.render = function() { this.container.insertAdjacentHTML('beforeend', this.view()); this.element = document.getElementById('window' + this.id); this.title = document.getElementById('standalone-window-title' + this.id); this.closeButton = document.getElementById('close-window-button' + this.id); this.closeButton.addEventListener('click', this.close.bind(this)); this.frame = document.getElementById('standalone-window-frame' + this.id); this.frame.addEventListener('did-navigate', this.handleLocationChange.bind(this)); this.frame.addEventListener('did-navigate-in-page', this.handleLocationChange.bind(this)); this.frame.addEventListener('new-window', this.handleOpenWindow.bind(this)); }; /** * Show the Window. */ StandaloneWindow.prototype.show = function() { this.element.classList.remove('hidden'); }; /** * Hide the window. */ StandaloneWindow.prototype.hide = function() { this.element.classList.add('hidden'); }; /** * Handle location change. * * @param {Event} e mozbrowserlocationchange event. */ StandaloneWindow.prototype.handleLocationChange = function(e) { this.currentUrl = e.url; }; /** * Convert hex color value to rgb. * * @argument {String} hex color string e.g. #ff0000 * @returns {Object} RGB object with separate r, g and b properties */ StandaloneWindow.prototype.hexToRgb = function(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; }; /** * Measure whether color is dark or light. * * @param {Object} RGB object with r, g, b properties. * @return {String} 'dark' or 'light'. */ StandaloneWindow.prototype.darkOrLight = function(rgb) { if ((rgb.r*0.299 + rgb.g*0.587 + rgb.b*0.114) > 186) { return 'light'; } else { return 'dark'; } };
webianproject/shell
chrome/desktop/js/StandaloneWindow.js
JavaScript
gpl-3.0
3,719
/* * Copyright 2016(c) The Ontario Institute for Cancer Research. All rights reserved. * * This program and the accompanying materials are made available under the terms of the GNU Public * License v3.0. You should have received a copy of the GNU General Public License along with this * program. If not, see <http://www.gnu.org/licenses/>. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import _ from 'lodash'; import moment from 'moment'; const dummyUsers = [ 'Jeff', 'Ryan', 'Brad', 'Alex', 'Matt', ]; const projectIds = [ 'project_1', 'project_2', 'project_3', 'project_4', 'project_5', 'project_6', ]; const DATE_FORMAT = 'YYYY-MM-DD'; const bucketMaps = { DAILY: { interval: [1, 'd'], multiplier: 1, }, WEEKLY: { interval: [1, 'w'], multiplier: 7, }, MONTHLY: { interval: [1, 'm'], multiplier: 30, }, YEARLY: { interval: [1, 'y'], multiplier: 365, }, } function randomDate(start, end) { return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime())); } export default function makeDummyReport({number, bucketSize, fromDate, toDate}) { const startDate = moment(fromDate, DATE_FORMAT); const endDate = moment(toDate, DATE_FORMAT); const bucketVars = bucketMaps[bucketSize]; return { fromDate: startDate.format(DATE_FORMAT), toDate: endDate.format(DATE_FORMAT), bucket: bucketSize, entries: _.sortBy(_.range(number).map((x, i) => { const bucketStartDate = moment(randomDate(startDate.toDate(), endDate.toDate())); const bucketEndDate = bucketStartDate.add(bucketMaps[bucketSize].interval[0], bucketMaps[bucketSize].interval[1]); return { fromDate: bucketStartDate.format(DATE_FORMAT), toDate: bucketEndDate.format(DATE_FORMAT), user: _.sample(dummyUsers), projectId: _.sample(projectIds), cpu: _.random(1, 50 * bucketVars.multiplier), volume: _.random(10 * bucketVars.multiplier, 60 * bucketVars.multiplier), image: _.random(1, 40 * bucketVars.multiplier), }; }), 'fromDate') } };
CancerCollaboratory/billing
billing-ui/src/services/reports/makeDummyReport.js
JavaScript
gpl-3.0
2,843
import React, { Component } from 'react' import { Button, Dropdown, Icon, Image, Form, Modal, Segment } from 'semantic-ui-react' import tr from '../app/utils/Translation'; const verticallyCenteredTextStyle = { display: 'inline-flex', alignItems: 'center' } const verticallyCenteredContainerStyle = { display: 'flex', justifyContent: 'space-between' } class ActiveDictionarySelector extends Component { static propTypes = { dictionaries: React.PropTypes.array.isRequired, activeDictionaryIds: React.PropTypes.array.isRequired, onActiveDictionariesChanged: React.PropTypes.func }; render() { if (!this.props.dictionaries.length) { return ( // <main className="ui container"> <Segment> <Segment basic style={verticallyCenteredContainerStyle}> <span style={verticallyCenteredTextStyle}>{tr('You have no dictionaries')}</span> <Button content={tr('Add a dictionary')} icon='plus' floated='right' /> </Segment> </Segment> // </main> ); } return ( // <main className="ui container"> <Segment> <Form> <Form.Select label={tr('Active Dictionaries')} name='activeDictionaries' options={this.props.dictionaries} fluid multiple search selection /> <Button content={tr('Clear All')} icon='trash'/> <Button content={tr('Select All')} icon='checkmark'/> </Form> </Segment> // </main> ) } } export default ActiveDictionarySelector;
sedooe/cevirgec
stories/ActiveDictionarySelector.js
JavaScript
gpl-3.0
1,527
/** ***** BEGIN LICENSE BLOCK ***** * * Copyright (C) 2019 Marc Ruiz Altisent. All rights reserved. * * This file is part of FoxReplace. * * FoxReplace is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * FoxReplace is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with FoxReplace. If not, see <http://www.gnu.org/licenses/>. * * ***** END LICENSE BLOCK ***** */ function onLoad() { document.removeEventListener("DOMContentLoaded", onLoad); document.getElementById("form").addEventListener("submit", onSubmit); } function onUnload() { document.removeEventListener("unload", onUnload); document.getElementById("form").removeEventListener("submit", onSubmit); } function onSubmit(event) { event.preventDefault(); // we just want to get the values, we don't want to submit anything let serialized = $('#form').serializeArray(); let formValues = {}; for (let item of serialized) { formValues[item.name] = item.value; } // Checkbox values are returned as 'on' when checked and missing (thus undefined) when unchecked. This works well when converted to Boolean. let substitutionList = [new SubstitutionGroup("", [], [new Substitution(formValues.input, formValues.output, formValues.caseSensitive, formValues.inputType)], formValues.html, true)]; browser.runtime.sendMessage({ key: "replace", list: substitutionListToJSON(substitutionList) }); } document.addEventListener("DOMContentLoaded", onLoad); document.addEventListener("unload", onUnload);
Woundorf/foxreplace
sidebar/sidebar.js
JavaScript
gpl-3.0
1,985
var searchData= [ ['unbancategories',['unbanCategories',['../classunban_categories.html',1,'']]], ['unbancategorieshandler',['unbanCategoriesHandler',['../classunban_categories_handler.html',1,'']]], ['unbanformrecaptcha',['unbanFormRecaptcha',['../classunban_form_recaptcha.html',1,'']]], ['unbanformselectcategory',['unbanFormSelectCategory',['../classunban_form_select_category.html',1,'']]], ['unbanformselectmember',['unbanFormSelectMember',['../classunban_form_select_member.html',1,'']]], ['unbanmembers',['unbanMembers',['../classunban_members.html',1,'']]], ['unbanmembershandler',['unbanMembersHandler',['../classunban_members_handler.html',1,'']]] ];
labscoop/xortify
azure/docs/html/search/classes_75.js
JavaScript
gpl-3.0
676
Meteor.methods({ 'deviceId/isClaimed': function(deviceId) { check(deviceId, String); return isClaimed(deviceId) }, 'deviceId/gen': function() { return gen(); }, 'deviceId/store': function(deviceId) { check(deviceId, String); return store(deviceId); }, }); var isClaimed = function(deviceId) { return !!DeviceIds.findOne({deviceId: deviceId}) } var gen = function() { var deviceId = Random.id(); if(isClaimed(deviceId)) return gen(); store(deviceId); return deviceId; } var store = function(deviceId) { if(isClaimed(deviceId)) throw new Meteor.Error('device-already-exists', "That deviceId already exists.") return !!DeviceIds.insert({deviceId: deviceId}) } _.extend(DeviceId, { isClaimed: isClaimed })
marvinmarnold/meteor-cordova-device-id
device-id-server.js
JavaScript
gpl-3.0
767
var direccion = '/api/Usuarios/' + sessionStorage.userId + '?access_token=' + sessionStorage.userToken; var nombre; /* Eliminar los valores de sesión */ function eliminarStorage(){ sessionStorage.removeItem("userToken"); sessionStorage.removeItem("userId"); sessionStorage.removeItem("userTtl"); sessionStorage.removeItem("userCreated"); sessionStorage.removeItem("userNombre"); sessionStorage.removeItem("userApellidos"); sessionStorage.removeItem("userDni"); sessionStorage.removeItem("userTelefono"); sessionStorage.removeItem("userCurso"); sessionStorage.removeItem("userUsername"); sessionStorage.removeItem("userEmail"); sessionStorage.removeItem("userObjetivoId"); sessionStorage.removeItem("userCentroId"); sessionStorage.removeItem("NombreCentro"); sessionStorage.removeItem("CodigoCentro"); sessionStorage.removeItem("LocalidadCentro"); sessionStorage.removeItem("userIdAlumnado"); sessionStorage.removeItem("NombreObjetivo"); } conexion('GET','',direccion); function conexion(metodo,datos,url){ $.ajax({ async: true, dataType: 'json', data: datos, method: metodo, url: url, }).done(function (respuesta){ if(typeof(respuesta.id) !== undefined){ sessionStorage.userNombre = respuesta.Nombre; sessionStorage.userApellidos = respuesta.Apellidos; sessionStorage.userDni = respuesta.DNI; sessionStorage.userTelefono = respuesta.Telefono; sessionStorage.userCurso = respuesta.Curso; sessionStorage.userUsername = respuesta.username; sessionStorage.userEmail = respuesta.email; sessionStorage.userCentroId = respuesta.centroId; sessionStorage.userObjetivoId = respuesta.objetivo; nombre = "<i class='fa fa-user-circle' aria-hidden='true'></i> " + sessionStorage.userNombre; $("#botonPerfil").html(nombre); $("#botonPerfilAdmin").html(nombre); $('#mensajeInicio').html("BIENVENIDO " + sessionStorage.userNombre + " A LA APLICACIÓN DE GESTIÓN DEL VIAJE DE ESTUDIOS"); }else{ console.log("Error Inicio"); eliminarStorage(); window.location.href = "../index.html"; } }).fail(function (xhr){ console.log("Error Inicio"); eliminarStorage(); window.location.href = "../index.html"; }); } $(document).ready(function() { $("#botonSalir").click(function(){ eliminarStorage(); window.location.href = "../index.html"; }); $("#botonPerfil").click(function(){ window.location.href = "perfil.html"; }); })
Salva79/ProyectoViaje
client/js/usuario.js
JavaScript
gpl-3.0
2,438
/* * Add a new ingredient form to the bottom of the formset */ function add_ingredient() { // Find the empty form var empty_form = $("#uses-formset .ingredient.empty-form"); // Clone it and remove the unneeded classes to get a new form var new_form = empty_form.clone(); new_form.removeClass('empty-form'); new_form.removeClass('sorting-disabled'); // Update the new forms number var total_forms = $("#id_ingredients-ingredients-TOTAL_FORMS"); var new_form_number = parseInt(total_forms.val()); updateFormNumber(new_form, new_form_number); // Update total forms counter total_forms.val(new_form_number + 1); // Insert after the last ingredient form var last_not_empty_form = $('#uses-formset li.ingredient:not(".empty-form"), #uses-formset li.group:not(".empty-form")').last(); new_form.insertAfter(last_not_empty_form); // Fix the ingredient list fix_ingredient_list(); return false; } /* * Add a new ingredient group to the bottom of the formset */ function add_group() { // Find the empty group var empty_group = $("#uses-formset .group.empty-form"); // Clone it and remove the unneeded classes to get a new group var new_group = empty_group.clone(); new_group.removeClass("empty-form"); new_group.removeClass("sorting-disabled"); // Insert after the last ingredient form var last_not_empty_form = $('#uses-formset li.ingredient:not(".empty-form"), #uses-formset li.group:not(".empty-form")').last(); new_group.insertAfter(last_not_empty_form); // Fix the ingredient list fix_ingredient_list(); return false; } /** * This function fixes the ingredient list. It handles the following cases: * - Hides or show the first label, depending on wether there is a group that already provides labels at the top * - Assigns the correct group to every ingredient form and indent them if needed * - Make sure this function is called again when a group has changed * - Add delete functionality to the delete buttons * - Add autocomplete functionality to ingredient forms */ function fix_ingredient_list() { // Get all ingredient forms and groups (except the empty ones) var lis = $("#uses-formset #sortable-ingredients li:not('.column-labels, .empty-form')"); // Hide the labels at the start if they are redundant because of group labels if (lis.first().hasClass("group")) { $("#uses-formset #sortable-ingredients .column-labels").hide(); } else { $("#uses-formset #sortable-ingredients .column-labels").show(); } // Assign a group to every ingredient form var group_name = ""; var found_group = false; lis.each(function() { if ($(this).hasClass("group")) { // This is a group li, all ingredients between this li and the next group li should belong to this group group_name = $(this).find(".group-name").val(); found_group = true; } else if ($(this).hasClass("ingredient")) { // Assign the current group to this ingredient $(this).find("input.group").val(group_name); // If this ingredient is in a group, indent the form if (found_group) { $(this).css('padding-left', '50px'); } else { $(this).css('padding-left', '30px'); } } }); // Change a group name when the user presses enter while editing it $("#sortable-ingredients .group input").pressEnter(function() { $(this).blur(); }); // When a group name has changed, fix the ingredient list $("#sortable-ingredients .group input").blur(function() { fix_ingredient_list(); }); // Add delete functionality to ingredient forms $("#sortable-ingredients .ingredient .delete-button").click(function() { var delete_checkbox = $(this).children("input"); if (delete_checkbox.length) { $(this).parents("li").hide() } else { $(this).parents("li").remove(); } delete_checkbox.val("True"); return false; }); // Add delete functionality to group forms $("#sortable-ingredients .group .delete-button").click(function() { $(this).parents("li").remove(); fix_ingredient_list(); return false; }); // Add autocomplete functionality to ingredient forms $("input.keywords-searchbar").each(function() { $(this).autocomplete({ source: "/ingredients/ing_list/", minLength: 2 }); $(this).blur(function() { $.ajax({ url: '/recipes/ingunits/', type: "POST", data: {ingredient_name: $(this).val()}, context: this, success: function(data) { var $options = $(this).closest('li').find('select'); var selected_id = $options.find('option:selected').val(); $options.empty(); $("<option value=\"\">---------</option>").appendTo($options); $.each($.parseJSON(data), function(id, val) { var option_string = "<option value=\"" + id.toString() + "\""; if (selected_id == id) { option_string = option_string + " selected=\"selected\""; } option_string = option_string + ">" + val + "</option>"; $(option_string).appendTo($options); }); } }); }) }); } $(document).ready(function() { // Make the ingredients and groups sortable $( "#sortable-ingredients" ).sortable({ stop: fix_ingredient_list, items: "li:not(.sorting-disabled)", handle: ".move-handle" }); $( "#sortable" ).disableSelection(); // Fix the list fix_ingredient_list(); // Add functionality to the add buttons $(".add-ingredient-button").click(add_ingredient); $(".add-ingredientgroup-button").click(add_group); });
Gargamel1989/Seasoning-old
Seasoning/recipes/static/js/edit_recipe_ingredients.js
JavaScript
gpl-3.0
5,602
intelli = { /** * Name of the current page */ pageName: '', securityTokenKey: '__st', lang: {}, /** * Check if value exists in array * * @param {Array} val value to be checked * @param {String} arr array * * @return {Boolean} */ inArray: function (val, arr) { if (typeof arr === 'object' && arr) { for (var i = 0; i < arr.length; i++) { if (arr[i] == val) { return true; } } } return false; }, cookie: { /** * Returns the value of cookie * * @param {String} name cookie name * * @return {String} */ read: function (name) { var nameEQ = name + '='; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length); } return null; }, /** * Creates new cookie * * @param {String} name cookie name * @param {String} value cookie value * @param {Integer} days number of days to keep cookie value for * @param {String} value path value */ write: function (name, value, days, path) { var expires = ''; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = '; expires=' + date.toGMTString(); } path = path || '/'; document.cookie = name + '=' + value + expires + '; path=' + path; }, /** * Clear cookie value * * @param {String} name cookie name */ clear: function (name) { intelli.cookie.write(name, '', -1); } }, urlVal: function (name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'); var results = regex.exec(window.location.href); return (null === results) ? null : decodeURIComponent(results[1]); }, notifBox: function (opt) { var msg = opt.msg; var type = opt.type || 'info'; var autohide = opt.autohide || (type == 'notification' || type == 'success' || type == 'error' ? true : false); var pause = opt.pause || 10; var html = ''; if ('notif' == type || type == 'notification') { type = 'success'; } var boxid = 'notification'; if (opt.boxid) { boxid = opt.boxid; } var obj = $('#' + boxid); if ($.isArray(msg)) { html += '<ul class="unstyled">'; for (var i = 0; i < msg.length; i++) { if ('' != msg[i]) { html += '<li>' + msg[i] + '</li>'; } } html += '</ul>'; } else { html += ['<div>', msg, '</div>'].join(''); } obj.attr('class', 'alert alert-' + type).html(html).show(); if (autohide) { obj.delay(pause * 1000).fadeOut('slow'); } $('html, body').animate({scrollTop: obj.offset().top}, 'slow'); return obj; }, notifFloatBox: function (options) { var msg = options.msg, type = options.type || 'info', pause = options.pause || 3000, autohide = options.autohide, html = ''; // building message box html += '<div id="notifFloatBox" class="notifFloatBox notifFloatBox--' + type + '"><a href="#" class="close">&times;</a>'; if ($.isArray(msg)) { html += '<ul>'; for (var i = 0; i < msg.length; i++) { if ('' != msg[i]) { html += '<li>' + msg[i] + '</li>'; } } html += '</ul>'; } else { html += '<ul><li>' + msg + '</li></ul>'; } html += '</div>'; // placing message box if (!$('#notifFloatBox').length > 0) { $(html).appendTo('body').css('display', 'block').addClass('animated bounceInDown'); if (autohide) { setTimeout(function () { $('#notifFloatBox').fadeOut(function () { $(this).remove(); }); }, pause); } $('.close', '#notifFloatBox').on('click', function (e) { e.preventDefault(); $('#notifFloatBox').fadeOut(function () { $(this).remove(); }); }); } }, is_email: function (email) { return (email.search(/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z]{2,3})+$/) > -1); }, ckeditor: function (name, params) { if (CKEDITOR.instances[name]) { return false; } params = params || {}; params.baseHref = intelli.config.clear_url; CKEDITOR.replace(name, params); }, add_tab: function (name, text) { var $tab = $('<li>').append($('<a>').attr({'data-toggle': 'tab', href: '#' + name}).text(text)); var $content = $('<div>').attr('id', name).addClass('tab-pane'); if ($('.nav-tabs', '.tabbable').children().length == 0) { $tab.addClass('active'); $content.addClass('active'); } $('.nav-tabs', '.tabbable').append($tab); $('.tab-content', '.tabbable').append($content); }, sortable: function (elem, params) { /*! Sortable 1.0.1 - MIT | git://github.com/rubaxa/Sortable.git */ !function (a) { "use strict"; "function" == typeof define && define.amd ? define(a) : "undefined" != typeof module && "undefined" != typeof module.exports ? module.exports = a() : "undefined" != typeof Package ? Sortable = a() : window.Sortable = a() }(function () { "use strict"; function a(a, b) { this.el = a, this.options = b = b || {}; var d = { group: Math.random(), sort: !0, disabled: !1, store: null, handle: null, scroll: !0, scrollSensitivity: 30, scrollSpeed: 10, draggable: /[uo]l/i.test(a.nodeName) ? "li" : ">*", ghostClass: "sortable-ghost", ignore: "a, img", filter: null, animation: 0, setData: function (a, b) { a.setData("Text", b.textContent) }, dropBubble: !1, dragoverBubble: !1 }; for (var e in d)!(e in b) && (b[e] = d[e]); var g = b.group; g && "object" == typeof g || (g = b.group = {name: g}), ["pull", "put"].forEach(function (a) { a in g || (g[a] = !0) }), L.forEach(function (d) { b[d] = c(this, b[d] || M), f(a, d.substr(2).toLowerCase(), b[d]) }, this), a[E] = g.name + " " + (g.put.join ? g.put.join(" ") : ""); for (var h in this)"_" === h.charAt(0) && (this[h] = c(this, this[h])); f(a, "mousedown", this._onTapStart), f(a, "touchstart", this._onTapStart), I && f(a, "selectstart", this._onTapStart), f(a, "dragover", this._onDragOver), f(a, "dragenter", this._onDragOver), P.push(this._onDragOver), b.store && this.sort(b.store.get(this)) } function b(a) { s && s.state !== a && (i(s, "display", a ? "none" : ""), !a && s.state && t.insertBefore(s, q), s.state = a) } function c(a, b) { var c = O.call(arguments, 2); return b.bind ? b.bind.apply(b, [a].concat(c)) : function () { return b.apply(a, c.concat(O.call(arguments))) } } function d(a, b, c) { if (a) { c = c || G, b = b.split("."); var d = b.shift().toUpperCase(), e = new RegExp("\\s(" + b.join("|") + ")\\s", "g"); do if (">*" === d && a.parentNode === c || ("" === d || a.nodeName.toUpperCase() == d) && (!b.length || ((" " + a.className + " ").match(e) || []).length == b.length))return a; while (a !== c && (a = a.parentNode)) } return null } function e(a) { a.dataTransfer.dropEffect = "move", a.preventDefault() } function f(a, b, c) { a.addEventListener(b, c, !1) } function g(a, b, c) { a.removeEventListener(b, c, !1) } function h(a, b, c) { if (a)if (a.classList) a.classList[c ? "add" : "remove"](b); else { var d = (" " + a.className + " ").replace(/\s+/g, " ").replace(" " + b + " ", ""); a.className = d + (c ? " " + b : "") } } function i(a, b, c) { var d = a && a.style; if (d) { if (void 0 === c)return G.defaultView && G.defaultView.getComputedStyle ? c = G.defaultView.getComputedStyle(a, "") : a.currentStyle && (c = a.currentStyle), void 0 === b ? c : c[b]; b in d || (b = "-webkit-" + b), d[b] = c + ("string" == typeof c ? "" : "px") } } function j(a, b, c) { if (a) { var d = a.getElementsByTagName(b), e = 0, f = d.length; if (c)for (; f > e; e++)c(d[e], e); return d } return [] } function k(a) { a.draggable = !1 } function l() { J = !1 } function m(a, b) { var c = a.lastElementChild, d = c.getBoundingClientRect(); return b.clientY - (d.top + d.height) > 5 && c } function n(a) { for (var b = a.tagName + a.className + a.src + a.href + a.textContent, c = b.length, d = 0; c--;)d += b.charCodeAt(c); return d.toString(36) } function o(a) { for (var b = 0; a && (a = a.previousElementSibling) && "TEMPLATE" !== a.nodeName.toUpperCase();)b++; return b } function p(a, b) { var c, d; return function () { void 0 === c && (c = arguments, d = this, setTimeout(function () { 1 === c.length ? a.call(d, c[0]) : a.apply(d, c), c = void 0 }, b)) } } var q, r, s, t, u, v, w, x, y, z, A, B, C, D = {}, E = "Sortable" + (new Date).getTime(), F = window, G = F.document, H = F.parseInt, I = !!G.createElement("div").dragDrop, J = !1, K = function (a, b, c, d, e, f) { var g = G.createEvent("Event"); g.initEvent(b, !0, !0), g.item = c || a, g.from = d || a, g.clone = s, g.oldIndex = e, g.newIndex = f, a.dispatchEvent(g) }, L = "onAdd onUpdate onRemove onStart onEnd onFilter onSort".split(" "), M = function () { }, N = Math.abs, O = [].slice, P = []; return a.prototype = { constructor: a, _dragStarted: function () { h(q, this.options.ghostClass, !0), a.active = this, K(t, "start", q, t, y) }, _onTapStart: function (a) { var b = a.type, c = a.touches && a.touches[0], e = (c || a).target, g = e, h = this.options, i = this.el, l = h.filter; if (!("mousedown" === b && 0 !== a.button || h.disabled)) { if (h.handle && (e = d(e, h.handle, i)), e = d(e, h.draggable, i), y = o(e), "function" == typeof l) { if (l.call(this, a, e, this))return K(g, "filter", e, i, y), void a.preventDefault() } else if (l && (l = l.split(",").some(function (a) { return a = d(g, a.trim(), i), a ? (K(a, "filter", e, i, y), !0) : void 0 })))return void a.preventDefault(); if (e && !q && e.parentNode === i) { "selectstart" === b && e.dragDrop(), B = a, t = this.el, q = e, v = q.nextSibling, A = this.options.group, q.draggable = !0, h.ignore.split(",").forEach(function (a) { j(e, a.trim(), k) }), c && (B = { target: e, clientX: c.clientX, clientY: c.clientY }, this._onDragStart(B, !0), a.preventDefault()), f(G, "mouseup", this._onDrop), f(G, "touchend", this._onDrop), f(G, "touchcancel", this._onDrop), f(q, "dragend", this), f(t, "dragstart", this._onDragStart), f(G, "dragover", this); try { G.selection ? G.selection.empty() : window.getSelection().removeAllRanges() } catch (m) { } } } }, _emulateDragOver: function () { if (C) { i(r, "display", "none"); var a = G.elementFromPoint(C.clientX, C.clientY), b = a, c = this.options.group.name, d = P.length; if (b)do { if ((" " + b[E] + " ").indexOf(c) > -1) { for (; d--;)P[d]({clientX: C.clientX, clientY: C.clientY, target: a, rootEl: b}); break } a = b } while (b = b.parentNode); i(r, "display", "") } }, _onTouchMove: function (a) { if (B) { var b = a.touches[0], c = b.clientX - B.clientX, d = b.clientY - B.clientY, e = "translate3d(" + c + "px," + d + "px,0)"; C = b, i(r, "webkitTransform", e), i(r, "mozTransform", e), i(r, "msTransform", e), i(r, "transform", e), this._onDrag(b), a.preventDefault() } }, _onDragStart: function (a, b) { var c = a.dataTransfer, d = this.options; if (this._offUpEvents(), "clone" == A.pull && (s = q.cloneNode(!0), i(s, "display", "none"), t.insertBefore(s, q)), b) { var e, g = q.getBoundingClientRect(), h = i(q); r = q.cloneNode(!0), i(r, "top", g.top - H(h.marginTop, 10)), i(r, "left", g.left - H(h.marginLeft, 10)), i(r, "width", g.width), i(r, "height", g.height), i(r, "opacity", "0.8"), i(r, "position", "fixed"), i(r, "zIndex", "100000"), t.appendChild(r), e = r.getBoundingClientRect(), i(r, "width", 2 * g.width - e.width), i(r, "height", 2 * g.height - e.height), f(G, "touchmove", this._onTouchMove), f(G, "touchend", this._onDrop), f(G, "touchcancel", this._onDrop), this._loopId = setInterval(this._emulateDragOver, 150) } else c && (c.effectAllowed = "move", d.setData && d.setData.call(this, c, q)), f(G, "drop", this); if (u = d.scroll, u === !0) { u = t; do if (u.offsetWidth < u.scrollWidth || u.offsetHeight < u.scrollHeight)break; while (u = u.parentNode) } setTimeout(this._dragStarted, 0) }, _onDrag: p(function (a) { if (t && this.options.scroll) { var b, c, d = this.options, e = d.scrollSensitivity, f = d.scrollSpeed, g = a.clientX, h = a.clientY, i = window.innerWidth, j = window.innerHeight, k = (e >= i - g) - (e >= g), l = (e >= j - h) - (e >= h); k || l ? b = F : u && (b = u, c = u.getBoundingClientRect(), k = (N(c.right - g) <= e) - (N(c.left - g) <= e), l = (N(c.bottom - h) <= e) - (N(c.top - h) <= e)), (D.vx !== k || D.vy !== l || D.el !== b) && (D.el = b, D.vx = k, D.vy = l, clearInterval(D.pid), b && (D.pid = setInterval(function () { b === F ? F.scrollTo(F.scrollX + k * f, F.scrollY + l * f) : (l && (b.scrollTop += l * f), k && (b.scrollLeft += k * f)) }, 24))) } }, 30), _onDragOver: function (a) { var c, e, f, g = this.el, h = this.options, j = h.group, k = j.put, n = A === j, o = h.sort; if (void 0 !== a.preventDefault && (a.preventDefault(), !h.dragoverBubble && a.stopPropagation()), !J && A && (n ? o || (f = !t.contains(q)) : A.pull && k && (A.name === j.name || k.indexOf && ~k.indexOf(A.name))) && (void 0 === a.rootEl || a.rootEl === this.el)) { if (c = d(a.target, h.draggable, g), e = q.getBoundingClientRect(), f)return b(!0), void(s || v ? t.insertBefore(q, s || v) : o || t.appendChild(q)); if (0 === g.children.length || g.children[0] === r || g === a.target && (c = m(g, a))) { if (c) { if (c.animated)return; u = c.getBoundingClientRect() } b(n), g.appendChild(q), this._animate(e, q), c && this._animate(u, c) } else if (c && !c.animated && c !== q && void 0 !== c.parentNode[E]) { w !== c && (w = c, x = i(c)); var p, u = c.getBoundingClientRect(), y = u.right - u.left, z = u.bottom - u.top, B = /left|right|inline/.test(x.cssFloat + x.display), C = c.offsetWidth > q.offsetWidth, D = c.offsetHeight > q.offsetHeight, F = (B ? (a.clientX - u.left) / y : (a.clientY - u.top) / z) > .5, G = c.nextElementSibling; J = !0, setTimeout(l, 30), b(n), p = B ? c.previousElementSibling === q && !C || F && C : G !== q && !D || F && D, p && !G ? g.appendChild(q) : c.parentNode.insertBefore(q, p ? G : c), this._animate(e, q), this._animate(u, c) } } }, _animate: function (a, b) { var c = this.options.animation; if (c) { var d = b.getBoundingClientRect(); i(b, "transition", "none"), i(b, "transform", "translate3d(" + (a.left - d.left) + "px," + (a.top - d.top) + "px,0)"), b.offsetWidth, i(b, "transition", "all " + c + "ms"), i(b, "transform", "translate3d(0,0,0)"), clearTimeout(b.animated), b.animated = setTimeout(function () { i(b, "transition", ""), b.animated = !1 }, c) } }, _offUpEvents: function () { g(G, "mouseup", this._onDrop), g(G, "touchmove", this._onTouchMove), g(G, "touchend", this._onDrop), g(G, "touchcancel", this._onDrop) }, _onDrop: function (b) { var c = this.el, d = this.options; clearInterval(this._loopId), clearInterval(D.pid), g(G, "drop", this), g(G, "dragover", this), g(c, "dragstart", this._onDragStart), this._offUpEvents(), b && (b.preventDefault(), !d.dropBubble && b.stopPropagation(), r && r.parentNode.removeChild(r), q && (g(q, "dragend", this), k(q), h(q, this.options.ghostClass, !1), t !== q.parentNode ? (z = o(q), K(q.parentNode, "sort", q, t, y, z), K(t, "sort", q, t, y, z), K(q, "add", q, t, y, z), K(t, "remove", q, t, y, z)) : (s && s.parentNode.removeChild(s), q.nextSibling !== v && (z = o(q), K(t, "update", q, t, y, z), K(t, "sort", q, t, y, z))), a.active && K(t, "end", q, t, y, z)), t = q = r = v = s = B = C = w = x = A = a.active = null, this.save()) }, handleEvent: function (a) { var b = a.type; "dragover" === b ? (this._onDrag(a), e(a)) : ("drop" === b || "dragend" === b) && this._onDrop(a) }, toArray: function () { for (var a, b = [], c = this.el.children, e = 0, f = c.length; f > e; e++)a = c[e], d(a, this.options.draggable, this.el) && b.push(a.getAttribute("data-id") || n(a)); return b }, sort: function (a) { var b = {}, c = this.el; this.toArray().forEach(function (a, e) { var f = c.children[e]; d(f, this.options.draggable, c) && (b[a] = f) }, this), a.forEach(function (a) { b[a] && (c.removeChild(b[a]), c.appendChild(b[a])) }) }, save: function () { var a = this.options.store; a && a.set(this) }, closest: function (a, b) { return d(a, b || this.options.draggable, this.el) }, option: function (a, b) { var c = this.options; return void 0 === b ? c[a] : void(c[a] = b) }, destroy: function () { var a = this.el, b = this.options; L.forEach(function (c) { g(a, c.substr(2).toLowerCase(), b[c]) }), g(a, "mousedown", this._onTapStart), g(a, "touchstart", this._onTapStart), g(a, "selectstart", this._onTapStart), g(a, "dragover", this._onDragOver), g(a, "dragenter", this._onDragOver), Array.prototype.forEach.call(a.querySelectorAll("[draggable]"), function (a) { a.removeAttribute("draggable") }), P.splice(P.indexOf(this._onDragOver), 1), this._onDrop(), this.el = null } }, a.utils = { on: f, off: g, css: i, find: j, bind: c, is: function (a, b) { return !!d(a, b, a) }, throttle: p, closest: d, toggleClass: h, dispatchEvent: K, index: o }, a.version = "1.0.1", a.create = function (b, c) { return new a(b, c) }, a }); var el = document.getElementById(elem); Sortable.create(el, params); }, confirm: function (text, options, callback) { bootbox.confirm(text, function (result) { if (result) { if (typeof options === 'object' && options) { if ('' != options.url) { window.location = options.url; } } } if (typeof callback === 'function') { callback(result); } }); }, includeSecurityToken: function(params) { if ('object' === typeof params) { params[this.securityTokenKey] = intelli.securityToken; } return params; }, post: function(url, data, success, dataType) { return $.post(url, this.includeSecurityToken(data), success, dataType); }, getLocale: function() { if ('function' === typeof moment) { var existLocales = moment.locales(); var locales = [ intelli.languages[intelli.config.lang].locale.replace('_', '-'), intelli.config.lang ]; var map = { zh: 'zh-cn' }; for (var i in locales) { var locale = locales[i]; if (typeof map[locale] !== 'undefined') { locale = map[locale]; } if (-1 !== $.inArray(locale, existLocales)) { return locale; } } } return 'en'; } }; function _t(key, def) { if (intelli.admin && intelli.admin.lang[key]) { return intelli.admin.lang[key]; } return _f(key, def); } function _f(key, def) { if (intelli.lang[key]) { return intelli.lang[key]; } return (def ? (def === true ? key : def) : '{' + key + '}'); }
intelliants/subrion
js/intelli/intelli.js
JavaScript
gpl-3.0
24,710
/** * Exports lists of modules to be bundled as external "dynamic" libraries * * (@see webpack DllPlugin and DllReferencePlugin) */ module.exports = { 'angular_dll': [ 'angular', 'angular/angular.min', 'angular-animate', 'angular-bootstrap', 'angular-bootstrap-colorpicker', 'angular-breadcrumb', 'angular-daterangepicker', 'angular-datetime', 'angular-data-table/release/dataTable.helpers.min', 'angular-dragula', 'angular-loading-bar', 'angular-resource', 'angular-route', 'angular-sanitize', 'angular-strap', 'angular-toArrayFilter', 'angular-touch', 'angular-ui-router', 'angular-ui-select', 'angular-ui-tinymce', 'angular-ui-translation', 'angular-ui-tree', 'angular-ui-pageslide', 'ng-file-upload', 'at-table/dist/angular-table', 'angular-dragula' ] }
stefk/Distribution
main/core/Resources/server/webpack/libraries.js
JavaScript
gpl-3.0
870
'use strict'; const { expect } = require('chai'); const kadence = require('..'); const network = require('./fixtures/node-generator'); const trust = require('../lib/plugin-trust'); const sinon = require('sinon'); const async = require('async'); describe('@module kadence/trust + @class UDPTransport', function() { let clock = null; let [node1, node2, node3, node4] = network(4, kadence.UDPTransport); before(function(done) { this.timeout(12000); clock = sinon.useFakeTimers(0); async.eachSeries([node1, node2, node3, node4], (node, next) => { node.listen(node.contact.port, next); }, done); }); after(function() { clock.restore(); process._getActiveHandles().forEach((h) => h.unref()); }) it('should allow the whitelisted contact', function(done) { node2.trust = node2.plugin(trust([ { identity: node1.identity, methods: ['PING'] } ], trust.MODE_WHITELIST)); node1.trust = node1.plugin(trust([ { identity: node2.identity, methods: ['PING'] } ], trust.MODE_WHITELIST)); node1.send('PING', [], [ node2.identity.toString('hex'), node2.contact ], done); }); it('should prevent the blacklisted contact', function(done) { node3.trust = node3.plugin(trust([ { identity: node1.identity, methods: ['PING'] } ], trust.MODE_BLACKLIST)); node1.trust.addTrustPolicy({ identity: node3.identity, methods: ['*'] }) node1.send('PING', [], [ node3.identity.toString('hex'), node3.contact ], err => { expect(err.message.includes('Refusing')).to.equal(true); done(); }); }); it('should allow the non-blacklisted contact', function(done) { node2.trust.addTrustPolicy({ identity: node3.identity.toString('hex'), methods: ['PING'] }) node2.send('PING', [], [ node3.identity.toString('hex'), node3.contact ], done); }); it('should prevent the non-whitelisted contact', function(done) { node4.send('PING', [], [ node2.identity.toString('hex'), node2.contact ], err => { expect(err.message.includes('Refusing')).to.equal(true); done(); }); }); it('should blacklist all nodes from using PING', function(done) { node3.trust.addTrustPolicy({ identity: '*', methods: ['PING'] }); node2.send('PING', [], [ node3.identity.toString('hex'), node3.contact ], err => { expect(err.message.includes('Refusing')).to.equal(true); node2.send('PING', [], [ node3.identity.toString('hex'), node3.contact ], err => { expect(err.message.includes('Refusing')).to.equal(true); done(); }); }); }); it('should refuse send to node with missing trust policy', function(done) { node1.trust.removeTrustPolicy(node2.identity); node1.send('PING', [], [ node2.identity.toString('hex'), node2.contact ], err => { expect(err.message.includes('Refusing')).to.equal(true); done(); }); }); it('should allow if method is not blacklisted', function(done) { node2.trust.addTrustPolicy({ identity: node3.identity, methods: ['PING'] }); node3.trust.addTrustPolicy({ identity: node2.identity, methods: ['FIND_NODE'] }); node2.send('PING', [], [ node3.identity, node3.contact ], done); }); it('should reject if method is not whitelisted', function(done) { node4.trust = node4.plugin(trust([ { identity: node2.identity, methods: ['FIND_NODE'] } ], trust.MODE_WHITELIST)); node2.trust.addTrustPolicy({ identity: node4.identity, methods: ['PING'] }); node4.send('FIND_NODE', [], [ node2.identity.toString('hex'), node2.contact ], err => { expect(err.message.includes('Refusing')).to.equal(true); done(); }); }); });
gordonwritescode/kad
test/plugin-trust.e2e.js
JavaScript
gpl-3.0
3,986
(function (tree) { tree.mixin = {}; tree.mixin.Call = function (elements, args, index) { this.selector = new(tree.Selector)(elements); this.arguments = args; this.index = index; }; tree.mixin.Call.prototype = { eval: function (env) { var mixins, rules = [], match = false; for (var i = 0; i < env.frames.length; i++) { if ((mixins = env.frames[i].find(this.selector)).length > 0) { for (var m = 0; m < mixins.length; m++) { if (mixins[m].match(this.arguments, env)) { try { Array.prototype.push.apply( rules, mixins[m].eval(env, this.arguments).rules); match = true; } catch (e) { throw { message: e.message, index: e.index, stack: e.stack, call: this.index }; } } } if (match) { return rules; } else { throw { message: 'No matching definition was found for `' + this.selector.toCSS().trim() + '(' + this.arguments.map(function (a) { return a.toCSS(); }).join(', ') + ")`", index: this.index }; } } } throw { message: this.selector.toCSS().trim() + " is undefined", index: this.index }; } }; tree.mixin.Definition = function (name, params, rules) { this.name = name; this.selectors = [new(tree.Selector)([new(tree.Element)(null, name)])]; this.params = params; this.arity = params.length; this.rules = rules; this._lookups = {}; this.required = params.reduce(function (count, p) { if (p.name && !p.value) { return count + 1 } else { return count } }, 0); this.parent = tree.Ruleset.prototype; this.frames = []; }; tree.mixin.Definition.prototype = { toCSS: function () { return "" }, variable: function (name) { return this.parent.variable.call(this, name) }, variables: function () { return this.parent.variables.call(this) }, find: function () { return this.parent.find.apply(this, arguments) }, rulesets: function () { return this.parent.rulesets.apply(this) }, eval: function (env, args) { var frame = new(tree.Ruleset)(null, []), context; for (var i = 0, val; i < this.params.length; i++) { if (this.params[i].name) { if (val = (args && args[i]) || this.params[i].value) { frame.rules.unshift(new(tree.Rule)(this.params[i].name, val.eval(env))); } else { throw { message: "wrong number of arguments for " + this.name + ' (' + args.length + ' for ' + this.arity + ')' }; } } } return new(tree.Ruleset)(null, this.rules.slice(0)).eval({ frames: [this, frame].concat(this.frames, env.frames) }); }, match: function (args, env) { var argsLength = (args && args.length) || 0, len; if (argsLength < this.required) { return false } len = Math.min(argsLength, this.arity); for (var i = 0; i < len; i++) { if (!this.params[i].name) { if (args[i].eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) { return false; } } } return true; } }; })(require('less/tree'));
tfe/cloud9
support/connect/support/less/lib/less/tree/mixin.js
JavaScript
gpl-3.0
3,761
dojo.provide("tests.currency"); dojo.require("dojo.currency"); tests.register("tests.currency", [ { // Test formatting and parsing of currencies in various locales pre-built in dojo.cldr // NOTE: we can't set djConfig.extraLocale before bootstrapping unit tests, so directly // load resources here for specific locales: name: "currency", setUp: function(){ var partLocaleList = ["en-us", "en-ca", "de-de"]; for(var i = 0 ; i < partLocaleList.length; i ++){ dojo.requireLocalization("dojo.cldr","currency",partLocaleList[i]); dojo.requireLocalization("dojo.cldr","number",partLocaleList[i]); } }, runTest: function(t){ t.is("\u20ac123.45", dojo.currency.format(123.45, {currency: "EUR", locale: "en-us"})); t.is("$123.45", dojo.currency.format(123.45, {currency: "USD", locale: "en-us"})); t.is("$1,234.56", dojo.currency.format(1234.56, {currency: "USD", locale: "en-us"})); t.is("US$123.45", dojo.currency.format(123.45, {currency: "USD", locale: "en-ca"})); t.is("$123.45", dojo.currency.format(123.45, {currency: "CAD", locale: "en-ca"})); t.is("Can$123.45", dojo.currency.format(123.45, {currency: "CAD", locale: "en-us"})); t.is("123,45 \u20ac", dojo.currency.format(123.45, {currency: "EUR", locale: "de-de"})); t.is("1.234,56 \u20ac", dojo.currency.format(1234.56, {currency: "EUR", locale: "de-de"})); // There is no special currency symbol for ADP, so expect the ISO code instead t.is("ADP123", dojo.currency.format(123, {currency: "ADP", locale: "en-us"})); t.is(123.45, dojo.currency.parse("$123.45", {currency: "USD", locale: "en-us"})); t.is(1234.56, dojo.currency.parse("$1,234.56", {currency: "USD", locale: "en-us"})); t.is(123.45, dojo.currency.parse("123,45 \u20ac", {currency: "EUR", locale: "de-de"})); t.is(1234.56, dojo.currency.parse("1.234,56 \u20ac", {currency: "EUR", locale: "de-de"})); t.is(1234.56, dojo.currency.parse("1.234,56\u20ac", {currency: "EUR", locale: "de-de"})); t.is(1234, dojo.currency.parse("$1,234", {currency: "USD", locale: "en-us"})); t.is(1234, dojo.currency.parse("$1,234", {currency: "USD", fractional: false, locale: "en-us"})); t.t(isNaN(dojo.currency.parse("$1,234", {currency: "USD", fractional: true, locale: "en-us"}))); } } ] );
NESCent/plhdb
WebRoot/js/dojo/tests/currency.js
JavaScript
gpl-3.0
2,317
import Struct from "ref-struct-napi"; const Registers = Struct({ "r15": "int64", "r14": "int64", "r13": "int64", "r12": "int64", "rbp": "int64", "rbx": "int64", "r11": "int64", "r10": "int64", "r9": "int64", "r8": "int64", "rax": "int64", "rcx": "int64", "rdx": "int64", "rsi": "int64", "rdi": "int64", "orig_rax": "int64", "rip": "int64", "cs": "int64", "eflags": "int64", "rsp": "int64", "ss": "int64", "fs_base": "int64", "gs_base": "int64", "ds": "int64", "es": "int64", "fs": "int64", "gs": "int64", }); export default { Registers };
k13-engineering/unix-ptrace
lib/arch/x86_64.js
JavaScript
gpl-3.0
597
var searchData= [ ['img',['IMG',['../define_8h.html#a116f6464c8184676310301dc13ed1dd5',1,'define.h']]], ['items',['ITEMS',['../define_8h.html#a8e3d0b04841186d4f38b7880a9e4b5c6',1,'define.h']]] ];
philipgraf/Dr_mad_daemon
doc/html/search/defines_69.js
JavaScript
gpl-3.0
200
/** * Iniciar panel de navegación (menú) */ function initSideBar(nav) { //-------------- Declaraciones ------------// let addMenuItem = function(menu, icon, label, click){ let li = $('<li><a href="javascript:void(0)"><i class="fa '+icon+' fa-fw"></i> '+label+'</a></li>'); if(click) li.on('click', click); menu.append(li); } let addSubMenu = function(id, menu, icon, label, filler){ let li = $('<li><a href="javascript:void(0)"><i class="fa '+icon+' fa-fw"></i> '+label+'<span class="fa arrow"></span></a></li>'); let ul = $('<ul class="nav nav-second-level"></ul>'); filler(ul); li.append(ul); menu.append(li); } let addSubMenuItem = function(menu, label, click){ let li = $('<li><a href="javascript:void(0)">'+label+'</a></li>'); if(click) li.on('click', click); menu.append(li); } let sidebar = $(` <div class="navbar-default sidebar" role="navigation"> <div class="sidebar-nav navbar-collapse"> <ul class="nav" id="side-menu"> </ul> </div> </div>`); let menu = sidebar.find('#side-menu'); //-------------- Ejecución -------------// // Agregar item "Inicio" addMenuItem(menu, 'fa-home', 'Inicio', function() { initHomePanel(); }); // Agregar item "Perfil" addMenuItem(menu, 'fa-user', 'Perfil', function() { initProfilePanel(); }); // Agregar item "Marcas" addMenuItem(menu, 'fa-bookmark', 'Marcas', function() { api.getAllBrands(function(data) { initContentPanel('Marcas', function(container) { createTable ( container, columnas = [ {title: "#", data: "id"}, {title: "Nombre", data: "name"} ], 'brands', data.brands ); }); }); }); // Agregar item "Categorías" addMenuItem(menu, 'fa-tags', 'Categorías', function() { api.getAllCategories(function(data) { initContentPanel('Categorías', function(container) { createTable ( container, columnas = [ {title: "#", data: "id"}, {title: "Descripción", data: "description"} ], 'categories', data.categories ); }); }); }); // Agregar item "Clientes" addMenuItem(menu, 'fa-users', 'Clientes', function() { api.getAllClients(function(data) { initContentPanel('Clientes', function(container) { createTable ( container, columnas = [ {title: "#", data: "id"}, {title: "Nombre", data: "name"}, {title: "CUIT", data: "cuit"}, {title: "Correo electrónico", data: "email"}, {title: "Teléfono", data:"phone"}, {title: "Dirección", data: "location"}, ], 'clients', data.clients ); }); }); }); // Agregar item "Productos" addMenuItem(menu, 'fa-th-list', 'Productos', function() { api.getAllProducts(function(data) { initContentPanel('Products', function(container) { createTable ( container, columnas = [ {title: "#", data: "id"}, {title: "Nombre", data: "name"}, {title: "Marca", data: "brand"}, {title: "Proveedor", data: "provider"}, {title: "Precio minorista", data:"retail_price"}, {title: "Precio mayorista", data: "wholesale_price"}, ], 'products', data.products ); let btnSubmit = $('<button type="button" id="submit-products" class="btn btn-success">Success</button>'); container.append(btnSubmit); }); }); }); // Agregar item "Proveedores" addMenuItem(menu, 'fa-truck', 'Proveedores', function() { api.getAllProviders(function(data) { initContentPanel('Providers', function(container) { createTable ( container, columnas = [ {title: "#", data: "id"}, {title: "Nombre", data: "name"}, {title: "Correo electrónico", data: "email"}, {title: "Teléfono", data:"phone"}, {title: "Compañía", data: "company"}, ], 'providers', data.providers ); }); }); }); // Agregar item "Ventas" addMenuItem(menu, 'fa-shopping-cart', 'Ventas', function() { api.getAllSales(function(data) { initContentPanel('Ventas', function(container) { createTable( container, columnas = [ {title: "#", data: "id"}, {title: "Usuario", data: "user"}, {title: "Cliente", data: "client"}, {title: "Total", data: "total"}, {title: "Fecha", data:"timestamp"}, ], 'sales', data.sales ); }); }); }); // Agregar item "Entregas" addSubMenu("deliveries", menu, 'fa-car', 'Entregas', function(submenu) { addSubMenuItem(submenu, "Hoy", function() { initDeliveriesPanel('today'); }); addSubMenuItem(submenu, "Atrasadas", function() { initDeliveriesPanel('delayed'); }); addSubMenuItem(submenu, "Pendientes", function() { initDeliveriesPanel('pending'); }); }); // Agregar item "Deudores" addMenuItem(menu, 'fa-warning', 'Deudores', function() { initDebtorsPanel(); }); nav.append(sidebar); }
germix/canawa
front2/admin/sidebar.js
JavaScript
gpl-3.0
4,973
$(document).ready(function () { // Open contact modal $('.contact').click(function(){ $('#contactModal').modal('toggle', { keyboard: false }).on('shown.bs.modal', function(){ var form = $('#ContactForm'); var submitButton = $('.submitContactForm'); submitButton.click(function(){ var email = $('#id_email'); var message = $('#id_message'); if(validateEmail(email.val()) && message.val() != ""){ //Valid information $.post( "/frontpage/contact/", form.serialize(), function(data){ if (data == 'True'){ $('#contactFormContainer').hide(); $('.submitContactForm').hide(); $('.contactformWarning').hide(); $('.contactformSuccess').show(); } else { $('.contactformWarning').show(); } }).fail(function() { $('.contactformWarning').show(); }); } else { //Not valid information $('.contactformWarning').show(); } }); }); }); // Validate email. function validateEmail($email) { var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; if( !emailReg.test( $email ) ) { return false; } else { return true; } } // Mobile messages var mobileUser = jQuery.browser.mobile; if (mobileUser){ $('.mobile-show').show(); $('.mobile-hide').hide(); } else { $('.mobile-show').hide(); $('.mobile-hide').show(); } });
Tacnet/Tacnet
tacnet/apps/base/static/js/base.js
JavaScript
gpl-3.0
1,991
/** * @fileOverview scripts about the frontpage. */ var calendarth = require('calendarth'); var util = require('./util'); var Front = module.exports = function() { this.$agendaContainer = null; this.$agendaItem = null; this.$error = null; }; /** @const {number} Maximum events to display, use an even number */ Front.MAX_EVENTS_SHOW = 10; /** * Initialize the frontpage view. * */ Front.prototype.init = function() { this.$agendaContainer = $('#agenda-items'); this.$agendaItem = $('#agenda-tpl'); this.$error = $('#agenda-error'); this.calendarth = calendarth({ apiKey: window.serv.calendarApiKey, calendarId: window.serv.callendarId, maxResults: 12 }); this.calendarth.fetch(this._handleCalResult.bind(this)); this._fixPanels(); }; /** * A temp fix for panels height. * * @private */ Front.prototype._fixPanels = function() { var max = 0; $('.panel-info').each(function() { var currentHeight = $(this).height(); if (currentHeight > max) { max = currentHeight; } }); $('.panel-info').height(max); }; /** * Handle incoming calendarth data. * * @param {?string|Error} err Possible error message. * @param {Object=} data The calendar data object. * @private */ Front.prototype._handleCalResult = function(err, data) { this.$agendaContainer.empty(); if (err) { this.$agendaContainer.append(this.$error.clone().removeClass('hide')); return; } var meetups = []; var displayed = 0; var elements = '<div class="row">'; data.items.forEach(function(item) { if (displayed >= Front.MAX_EVENTS_SHOW) { return; } if (meetups.indexOf(item.summary) > -1) { return; } else { meetups.push(item.summary); } if (displayed && displayed % 2 === 0) { // rows elements += '</div><div class="row">'; } elements += this._assignValues(this.$agendaItem.clone(), item); displayed++; }, this); elements += '</div>'; this.$agendaContainer.append(elements); }; /** * Assign the Calendar item values to the Calendar item element. * * @param {jQuery} $item A jquery item we will manipulate. * @param {Object} item [description] * @return {string} The html representation. * @private */ Front.prototype._assignValues = function($item, item) { $item.removeClass('hide'); $item.find('.panel-title').text(item.summary); var data = this._parseDesc(item.description); $item.find('.agenda-tpl-when span').text(util.formatDate(item.start, item.end)); var location = ''; if (data.mapUrl) { location = '<a href="' + data.mapUrl + '" target="_blank">'; location += item.location; location += '</a>'; } else { location = item.location; } $item.find('.agenda-tpl-address span').html(location); if (data.venue) { $item.find('.agenda-tpl-venue span').text(data.venue); } else { $item.find('.agenda-tpl-venue').addClass('hide'); } if (data.infoUrl) { var infoUrl = ''; if (data.infoUrl.length > 25) { infoUrl = data.infoUrl.substr(0, 25) + '...'; } else { infoUrl = data.infoUrl; } $item.find('.agenda-tpl-info a').attr('href', data.infoUrl).text(infoUrl); } else { $item.find('.agenda-tpl-info').addClass('hide'); } if (data.about) { $item.find('.agenda-tpl-about span').html(data.about); } else { $item.find('.agenda-tpl-about').addClass('hide'); } if (data.language) { $item.find('.agenda-tpl-language span').html(data.language); } else { $item.find('.agenda-tpl-language').addClass('hide'); } var eventUrl = this.calendarth.getEventUrl(item); $item.find('.addcal').attr('href', eventUrl); $item.find('.viewcal').attr('href', item.htmlLink); return $item.html(); }; /** * Parse the description and generated info. * * @param {string} descr The description * @return {Object} An object containing the following properties: * venue {?string} The venue where the event happens or null. * info {?string} The informational url or null. * map {?string} The map url or null. * language {?string} The event language. * @private */ Front.prototype._parseDesc = function(descr) { var out = { venue: null, infoUrl: null, mapUrl: null, about: null, language: null, rest: '' }; if (!descr) { return out; } var lines = descr.split('\n'); lines.forEach(function(line) { if (!line.length) { return; } var splitPos = line.indexOf(':'); if (splitPos === -1) { return; } var key = line.substr(0, splitPos).toLowerCase().trim(); var value = line.substr(splitPos + 1).trim(); switch(key) { case 'venue': out.venue = value; break; case 'info': out.infoUrl = value; break; case 'map': out.mapUrl = value; break; case 'about': out.about = value; break; case 'language': out.language = value; break; default: out.rest += line + '<br />'; break; } }, this); return out; };
WeAreTech/wearetech.io
front/js-city/frontpage.js
JavaScript
mpl-2.0
5,035
// DO NOT EDIT! This test has been generated by tools/gentest.py. // OffscreenCanvas test in a worker:2d.fillStyle.parse.hsl-clamp-4 // Description: // Note:<p class="notes"> importScripts("/resources/testharness.js"); importScripts("/2dcontext/resources/canvas-tests.js"); var t = async_test(""); var t_pass = t.done.bind(t); var t_fail = t.step_func(function(reason) { throw reason; }); t.step(function() { var offscreenCanvas = new OffscreenCanvas(100, 50); var ctx = offscreenCanvas.getContext('2d'); ctx.fillStyle = '#f00'; ctx.fillStyle = 'hsl(120, 100%, -200%)'; ctx.fillRect(0, 0, 100, 50); _assertPixel(offscreenCanvas, 50,25, 0,0,0,255, "50,25", "0,0,0,255"); t.done(); }); done();
DominoTree/servo
tests/wpt/web-platform-tests/offscreen-canvas/fill-and-stroke-styles/2d.fillStyle.parse.hsl-clamp-4.worker.js
JavaScript
mpl-2.0
702
/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * * Date: 05 June 2003 * SUMMARY: Testing |with (f)| inside the definition of |function f()| * * See http://bugzilla.mozilla.org/show_bug.cgi?id=208496 * */ //----------------------------------------------------------------------------- var gTestfile = 'regress-208496-001.js'; var UBound = 0; var BUGNUMBER = 208496; var summary = 'Testing |with (f)| inside the definition of |function f()|'; var status = ''; var statusitems = []; var actual = '(TEST FAILURE)'; var actualvalues = []; var expect= ''; var expectedvalues = []; /* * GLOBAL SCOPE */ function f(par) { var a = par; with(f) { var b = par; actual = b; } } status = inSection(1); f('abc'); // this sets |actual| expect = 'abc'; addThis(); status = inSection(2); f(111 + 222); // sets |actual| expect = 333; addThis(); /* * EVAL SCOPE */ var s = ''; s += 'function F(par)'; s += '{'; s += ' var a = par;'; s += ' with(F)'; s += ' {'; s += ' var b = par;'; s += ' actual = b;'; s += ' }'; s += '}'; s += 'status = inSection(3);'; s += 'F("abc");'; // sets |actual| s += 'expect = "abc";'; s += 'addThis();'; s += 'status = inSection(4);'; s += 'F(111 + 222);'; // sets |actual| s += 'expect = 333;'; s += 'addThis();'; eval(s); /* * FUNCTION SCOPE */ function g(par) { // Add outer variables to complicate the scope chain - var a = '(TEST FAILURE)'; var b = '(TEST FAILURE)'; h(par); function h(par) { var a = par; with(h) { var b = par; actual = b; } } } status = inSection(5); g('abc'); // sets |actual| expect = 'abc'; addThis(); status = inSection(6); g(111 + 222); // sets |actual| expect = 333; addThis(); //----------------------------------------------------------------------------- test(); //----------------------------------------------------------------------------- function addThis() { statusitems[UBound] = status; actualvalues[UBound] = actual; expectedvalues[UBound] = expect; UBound++; } function test() { enterFunc('test'); printBugNumber(BUGNUMBER); printStatus(summary); for (var i=0; i<UBound; i++) { reportCompare(expectedvalues[i], actualvalues[i], statusitems[i]); } exitFunc ('test'); }
mozilla/rhino
testsrc/tests/js1_5/Scope/regress-208496-001.js
JavaScript
mpl-2.0
2,507
/** * @class PrettyJSON.view.Leaf * @extends Backbone.View * * @author #rbarriga * @version 0.1 * */ PrettyJSON.view.Leaf = Backbone.View.extend({ tagName:'span', data:null, level:0, path:'', type:'string', isLast: true, events: { "mouseover .leaf-container": "mouseover", "mouseout .leaf-container": "mouseout" }, initialize: function(){ this.data = this.options.data; this.level = this.options.level; this.path = this.options.path; this.type = this.getType(); this.isLast = _.isUndefined(this.options.isLast) ? this.isLast : this.options.isLast; this.render(); }, getType: function(){ var m = 'string'; var d = this.data; if(_.isNumber(d)) m = 'number'; else if(_.isBoolean(d)) m = 'boolean'; else if(_.isDate(d)) m = 'date'; return m; }, getState:function(){ var coma = this.isLast ? '': ','; var state = { data: this.data, level: this.level, path: this.path, type: this.type, coma: coma }; return state; }, render: function(){ var state = this.getState(); this.tpl = _.template(PrettyJSON.tpl.Leaf, state); $(this.el).html(this.tpl); return this; }, mouseover:function(e){ e.stopPropagation(); this.toggleTdPath(true); var path = this.path + '&nbsp;:&nbsp;<span class="' + this.type +'"><b>' + this.data + '</b></span>'; this.trigger("mouseover",e, path); }, mouseout:function(e){ e.stopPropagation(); this.toggleTdPath(false); this.trigger("mouseout",e); }, getTds:function(){ this.tds = []; var view = this; while (view){ var td = view.parentTd; if(td) this.tds.push(td); view = view.parent; } }, toggleTdPath:function(show){ this.getTds(); _.each(this.tds,function(td){ show ? td.addClass('node-hgl-path'): td.removeClass('node-hgl-path'); },this); } });
SmartSearch/Mashups
Event_Billboard-portlet/docroot/js/pretty-json-master/src/leaf.js
JavaScript
mpl-2.0
2,216
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * Copyright (c) 2015, Joyent, Inc. */ /* * CollectorStream: transform that collects all input and makes it available as * a single string */ var readable = require('readable-stream'); var util = require('util'); module.exports = CollectorStream; function CollectorStream(options) { readable.Transform.call(this, options); this.data = ''; } util.inherits(CollectorStream, readable.Transform); CollectorStream.prototype._transform = function (chunk, encoding, done) { this.data += chunk; done(); }; CollectorStream.prototype._flush = function (callback) { callback(); };
davepacheco/sdc-manta
test/CollectorStream.js
JavaScript
mpl-2.0
799
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // @flow import * as React from 'react'; import { Provider } from 'react-redux'; import copy from 'copy-to-clipboard'; import { render } from 'firefox-profiler/test/fixtures/testing-library'; import { CallNodeContextMenu } from '../../components/shared/CallNodeContextMenu'; import { storeWithProfile } from '../fixtures/stores'; import { getProfileFromTextSamples } from '../fixtures/profiles/processed-profile'; import { changeRightClickedCallNode, changeExpandedCallNodes, setContextMenuVisibility, } from '../../actions/profile-view'; import { selectedThreadSelectors } from '../../selectors/per-thread'; import { ensureExists } from '../../utils/flow'; import { fireFullClick } from '../fixtures/utils'; describe('calltree/CallNodeContextMenu', function () { // Provide a store with a useful profile to assert context menu operations off of. function createStore() { // Create a profile that every transform can be applied to. const { profile, funcNamesDictPerThread: [{ A, B }], } = getProfileFromTextSamples(` A A A B[lib:XUL] B[lib:XUL] B[lib:XUL] B[lib:XUL] B[lib:XUL] B[lib:XUL] B[lib:XUL] B[lib:XUL] B[lib:XUL] C C H D F I E E `); const store = storeWithProfile(profile); store.dispatch(changeExpandedCallNodes(0, [[A]])); store.dispatch(changeRightClickedCallNode(0, [A, B])); return store; } function setup(store = createStore(), openMenuState = true) { store.dispatch(setContextMenuVisibility(openMenuState)); const renderResult = render( <Provider store={store}> <CallNodeContextMenu /> </Provider> ); return { ...renderResult, getState: store.getState }; } describe('basic rendering', function () { it('does not render the context menu when it is closed', () => { const isContextMenuOpen = false; const { container } = setup(createStore(), isContextMenuOpen); expect(container.querySelector('.react-contextmenu')).toBeNull(); }); it('renders a full context menu when open, with many nav items', () => { const isContextMenuOpen = true; const { container } = setup(createStore(), isContextMenuOpen); expect( ensureExists( container.querySelector('.react-contextmenu'), `Couldn't find the context menu root component .react-contextmenu` ).children.length > 1 ).toBeTruthy(); expect(container.firstChild).toMatchSnapshot(); }); }); describe('clicking on call tree transforms', function () { // Iterate through each transform slug, and click things in it. const fixtures = [ { matcher: /Merge function/, type: 'merge-function' }, { matcher: /Merge node only/, type: 'merge-call-node' }, { matcher: /Focus on subtree only/, type: 'focus-subtree' }, { matcher: /Focus on function/, type: 'focus-function' }, { matcher: /Collapse function/, type: 'collapse-function-subtree' }, { matcher: /XUL/, type: 'collapse-resource' }, { matcher: /Collapse direct recursion/, type: 'collapse-direct-recursion', }, { matcher: /Drop samples/, type: 'drop-function' }, ]; fixtures.forEach(({ matcher, type }) => { it(`adds a transform for "${type}"`, function () { const { getState, getByText } = setup(); fireFullClick(getByText(matcher)); expect( selectedThreadSelectors.getTransformStack(getState())[0].type ).toBe(type); }); }); }); describe('clicking on the rest of the menu items', function () { it('can expand all call nodes in the call tree', function () { const { getState, getByText } = setup(); expect( selectedThreadSelectors.getExpandedCallNodeIndexes(getState()) ).toHaveLength(1); fireFullClick(getByText('Expand all')); // This test only asserts that a bunch of call nodes were actually expanded. expect( selectedThreadSelectors.getExpandedCallNodeIndexes(getState()) ).toHaveLength(11); }); it('can look up functions on SearchFox', function () { const { getByText } = setup(); jest.spyOn(window, 'open').mockImplementation(() => {}); fireFullClick(getByText(/Searchfox/)); expect(window.open).toBeCalledWith( 'https://searchfox.org/mozilla-central/search?q=B', '_blank' ); }); it('can copy a function name', function () { const { getByText } = setup(); // Copy is a mocked module, clear it both before and after. fireFullClick(getByText('Copy function name')); expect(copy).toBeCalledWith('B'); }); it('can copy a script URL', function () { // Create a new profile that has JavaScript in it. const { profile, funcNamesPerThread: [funcNames], } = getProfileFromTextSamples(` A.js `); const funcIndex = funcNames.indexOf('A.js'); const [thread] = profile.threads; thread.funcTable.fileName[funcIndex] = thread.stringTable.indexForString( 'https://example.com/script.js' ); const store = storeWithProfile(profile); store.dispatch(changeRightClickedCallNode(0, [funcIndex])); const { getByText } = setup(store); // Copy is a mocked module, clear it both before and after. fireFullClick(getByText('Copy script URL')); expect(copy).toBeCalledWith('https://example.com/script.js'); }); it('can copy a stack', function () { const { getByText } = setup(); // Copy is a mocked module, clear it both before and after. fireFullClick(getByText('Copy stack')); expect(copy).toBeCalledWith(`B\nA\n`); }); }); });
mstange/cleopatra
src/test/components/CallNodeContextMenu.test.js
JavaScript
mpl-2.0
6,012
/*global getAccessToken*/ function notifyUser(user) { browser.notifications.create({ "type": "basic", "title": "Google info", "message": `Hi ${user.name}` });} function logError(error) { console.error(`Error: ${error}`); } /** When the button's clicked: - get an access token using the identity API - use it to get the user's info - show a notification containing some of it */ browser.browserAction.onClicked.addListener(() => { getAccessToken() .then(getUserInfo) .then(notifyUser) .catch(logError); });
mdn/webextensions-examples
google-userinfo/background/main.js
JavaScript
mpl-2.0
541
/* @flow */ /* global Navigator, navigator */ import config from 'config'; import * as React from 'react'; import { Helmet } from 'react-helmet'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import NestedStatus from 'react-nested-status'; import { compose } from 'redux'; // We have to import these styles first to have them listed first in the final // CSS file. See: https://github.com/mozilla/addons-frontend/issues/3565 // The order is important: font files need to be first, with the subset after // the full font file. import 'fonts/inter.scss'; import 'fonts/inter-subset.scss'; import 'normalize.css/normalize.css'; import './styles.scss'; /* eslint-disable import/first */ import Routes from 'amo/components/Routes'; import ScrollToTop from 'amo/components/ScrollToTop'; import NotAuthorizedPage from 'amo/pages/ErrorPages/NotAuthorizedPage'; import NotFoundPage from 'amo/pages/ErrorPages/NotFoundPage'; import ServerErrorPage from 'amo/pages/ErrorPages/ServerErrorPage'; import { getClientAppAndLangFromPath, isValidClientApp } from 'amo/utils'; import { addChangeListeners } from 'amo/addonManager'; import { setClientApp as setClientAppAction, setUserAgent as setUserAgentAction, } from 'amo/reducers/api'; import { setInstallState } from 'amo/reducers/installations'; import { CLIENT_APP_ANDROID } from 'amo/constants'; import ErrorPage from 'amo/components/ErrorPage'; import translate from 'amo/i18n/translate'; import log from 'amo/logger'; import type { AppState } from 'amo/store'; import type { DispatchFunc } from 'amo/types/redux'; import type { InstalledAddon } from 'amo/reducers/installations'; import type { I18nType } from 'amo/types/i18n'; import type { ReactRouterLocationType } from 'amo/types/router'; /* eslint-enable import/first */ interface MozNavigator extends Navigator { mozAddonManager?: Object; } type PropsFromState = {| clientApp: string, lang: string, userAgent: string | null, |}; type DefaultProps = {| _addChangeListeners: (callback: Function, mozAddonManager: Object) => any, _navigator: typeof navigator | null, mozAddonManager: $PropertyType<MozNavigator, 'mozAddonManager'>, userAgent: string | null, |}; type Props = {| ...PropsFromState, ...DefaultProps, handleGlobalEvent: () => void, i18n: I18nType, location: ReactRouterLocationType, setClientApp: (clientApp: string) => void, setUserAgent: (userAgent: string) => void, |}; export function getErrorPage(status: number | null): () => React.Node { switch (status) { case 401: return NotAuthorizedPage; case 404: return NotFoundPage; case 500: default: return ServerErrorPage; } } export class AppBase extends React.Component<Props> { scheduledLogout: TimeoutID; static defaultProps: DefaultProps = { _addChangeListeners: addChangeListeners, _navigator: typeof navigator !== 'undefined' ? navigator : null, mozAddonManager: config.get('server') ? {} : (navigator: MozNavigator).mozAddonManager, userAgent: null, }; componentDidMount() { const { _addChangeListeners, _navigator, handleGlobalEvent, mozAddonManager, setUserAgent, userAgent, } = this.props; // Use addonManager.addChangeListener to setup and filter events. _addChangeListeners(handleGlobalEvent, mozAddonManager); // If userAgent isn't set in state it could be that we couldn't get one // from the request headers on our first (server) request. If that's the // case we try to load them from navigator. if (!userAgent && _navigator && _navigator.userAgent) { log.info( 'userAgent not in state on App load; using navigator.userAgent.', ); setUserAgent(_navigator.userAgent); } } componentDidUpdate() { const { clientApp, location, setClientApp } = this.props; const { clientApp: clientAppFromURL } = getClientAppAndLangFromPath( location.pathname, ); if (isValidClientApp(clientAppFromURL) && clientAppFromURL !== clientApp) { setClientApp(clientAppFromURL); } } render(): React.Node { const { clientApp, i18n, lang } = this.props; const i18nValues = { locale: lang, }; let defaultTitle = i18n.sprintf( i18n.gettext('Add-ons for Firefox (%(locale)s)'), i18nValues, ); let titleTemplate = i18n.sprintf( i18n.gettext('%(title)s – Add-ons for Firefox (%(locale)s)'), // We inject `%s` as a named argument to avoid localizer mistakes. Helmet // will replace `%s` by the title supplied in other pages. { ...i18nValues, title: '%s' }, ); if (clientApp === CLIENT_APP_ANDROID) { defaultTitle = i18n.sprintf( i18n.gettext('Add-ons for Firefox Android (%(locale)s)'), i18nValues, ); titleTemplate = i18n.sprintf( i18n.gettext('%(title)s – Add-ons for Firefox Android (%(locale)s)'), // We inject `%s` as a named argument to avoid localizer mistakes. // Helmet will replace `%s` by the title supplied in other pages. { ...i18nValues, title: '%s' }, ); } return ( <NestedStatus code={200}> <ScrollToTop> <Helmet defaultTitle={defaultTitle} titleTemplate={titleTemplate} /> <ErrorPage getErrorComponent={getErrorPage}> <Routes /> </ErrorPage> </ScrollToTop> </NestedStatus> ); } } export const mapStateToProps = (state: AppState): PropsFromState => ({ clientApp: state.api.clientApp, lang: state.api.lang, userAgent: state.api.userAgent, }); export function mapDispatchToProps(dispatch: DispatchFunc): {| handleGlobalEvent: (payload: InstalledAddon) => void, setClientApp: (clientApp: string) => void, setUserAgent: (userAgent: string) => void, |} { return { handleGlobalEvent(payload: InstalledAddon) { dispatch(setInstallState(payload)); }, setClientApp(clientApp: string) { dispatch(setClientAppAction(clientApp)); }, setUserAgent(userAgent: string) { dispatch(setUserAgentAction(userAgent)); }, }; } const App: React.ComponentType<Props> = compose( withRouter, connect(mapStateToProps, mapDispatchToProps), translate(), )(AppBase); export default App;
mozilla/addons-frontend
src/amo/components/App/index.js
JavaScript
mpl-2.0
6,317
var tipuesearch={"pages": [{"title":"Changelog","text":"","tags":"","category":"","url":globals.prefix+"changelog.html"},{"title":"Version Catalogue","text":"\nPrevious versions of Doctran are listed below.","tags":"","category":"","url":globals.prefix+"index.html"}]};
CPardi/Doctran
Documentation/doc/version-catalogue/base/Shared/Search/tipuesearch/tipuesearch_content.js
JavaScript
mpl-2.0
269
var le__audio__interface_8h = [ [ "LE_AUDIO_DTMF_MAX_BYTES", "le__audio__interface_8h.html#aafdf655a188e290502c2a909c3b37104", null ], [ "LE_AUDIO_DTMF_MAX_LEN", "le__audio__interface_8h.html#a33201f88acf34e8c5cb612ac9f4a8bb6", null ], [ "LE_AUDIO_GAIN_NAME_MAX_BYTES", "le__audio__interface_8h.html#a4711f6c5e075efd984c81713479e5434", null ], [ "LE_AUDIO_GAIN_NAME_MAX_LEN", "le__audio__interface_8h.html#a92688388540a067fe0a3c5b5d096363b", null ], [ "LE_AUDIO_NO_FD", "le__audio__interface_8h.html#a374c2f62ec5b8a92dd1de6fcb449fafe", null ], [ "le_audio_ConnectorRef_t", "le__audio__interface_8h.html#ab819480f4ce3f36e62b6a4e327668304", null ], [ "le_audio_DtmfDetectorHandlerFunc_t", "le__audio__interface_8h.html#a3c6bc837c07ecf1545eadc7f1813bddb", null ], [ "le_audio_DtmfDetectorHandlerRef_t", "le__audio__interface_8h.html#a2db60899cdaa84759075a7955ed24511", null ], [ "le_audio_MediaHandlerFunc_t", "le__audio__interface_8h.html#aa1176ea658084237635f4e7e437f1f7b", null ], [ "le_audio_MediaHandlerRef_t", "le__audio__interface_8h.html#a390b011cbb6f745c46e861d315af0bbe", null ], [ "le_audio_StreamRef_t", "le__audio__interface_8h.html#a9a46ff5a5afa61f1bc76120ab9e4da0a", null ], [ "le_audio_AmrMode_t", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7", [ [ "LE_AUDIO_AMR_NONE", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7a51d289424c42c53aff800659871cbe3f", null ], [ "LE_AUDIO_AMR_NB_4_75_KBPS", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7a757a18a9f17e6152f77645bcc05c8dfb", null ], [ "LE_AUDIO_AMR_NB_5_15_KBPS", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7a4c4726438b37dd61e090707c6bd060b3", null ], [ "LE_AUDIO_AMR_NB_5_9_KBPS", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7aa8375f69558e2ac515b5a74e336ad78c", null ], [ "LE_AUDIO_AMR_NB_6_7_KBPS", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7a4a5f21fde04b81e01474d289a31ae169", null ], [ "LE_AUDIO_AMR_NB_7_4_KBPS", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7a70510d805a435c524dbe16bb52836914", null ], [ "LE_AUDIO_AMR_NB_7_95_KBPS", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7a785a7b08f33e1cad391a229a8638bc02", null ], [ "LE_AUDIO_AMR_NB_10_2_KBPS", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7a9a067aec590278814137733cc91ddf00", null ], [ "LE_AUDIO_AMR_NB_12_2_KBPS", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7aba8db156fffb89bcb98e6a2cb762d04c", null ], [ "LE_AUDIO_AMR_WB_6_6_KBPS", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7a8056bae72d2abccfa4a3df9f5250fc3f", null ], [ "LE_AUDIO_AMR_WB_8_85_KBPS", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7aa7129e4022538c178641bddab468e955", null ], [ "LE_AUDIO_AMR_WB_12_65_KBPS", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7ac9a2144d8bc2842e4fa16e5d80633ac2", null ], [ "LE_AUDIO_AMR_WB_14_25_KBPS", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7a0e68d866b1cf9e0fe13884efe3d2b4f0", null ], [ "LE_AUDIO_AMR_WB_15_85_KBPS", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7ae5850c4d2022d20fa09436c9efb943ee", null ], [ "LE_AUDIO_AMR_WB_18_25_KBPS", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7ad227fd120289c6d2c0b711e31dbfbae1", null ], [ "LE_AUDIO_AMR_WB_19_85_KBPS", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7a53fad07cad340900588ee1b68b959260", null ], [ "LE_AUDIO_AMR_WB_23_05_KBPS", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7ae846f84f4c7c11645a0a5690370c020c", null ], [ "LE_AUDIO_AMR_WB_23_85_KBPS", "le__audio__interface_8h.html#accd7fae61b50dcd68bf722e243bc5cb7a27cfc7c374b62900edfea1393091cd00", null ] ] ], [ "le_audio_Companding_t", "le__audio__interface_8h.html#a5b07d59ec1067a4d81250a46f93715b8", [ [ "LE_AUDIO_COMPANDING_ALAW", "le__audio__interface_8h.html#a5b07d59ec1067a4d81250a46f93715b8a271c71620c5ea0a607c5372f4c650519", null ], [ "LE_AUDIO_COMPANDING_ULAW", "le__audio__interface_8h.html#a5b07d59ec1067a4d81250a46f93715b8ad8a49ed29e9bf3077127ec237c742753", null ], [ "LE_AUDIO_COMPANDING_NONE", "le__audio__interface_8h.html#a5b07d59ec1067a4d81250a46f93715b8ae40f3183883d0e0e3c35733326ac9733", null ] ] ], [ "le_audio_Format_t", "le__audio__interface_8h.html#a0ad2f5012ed700af1892f82e4af5989d", [ [ "LE_AUDIO_WAVE", "le__audio__interface_8h.html#a0ad2f5012ed700af1892f82e4af5989daacfeef297c63db7626c586ebe4d5e1c2", null ], [ "LE_AUDIO_AMR", "le__audio__interface_8h.html#a0ad2f5012ed700af1892f82e4af5989da51bd6de676a1d6a82923c7383b047893", null ], [ "LE_AUDIO_FORMAT_MAX", "le__audio__interface_8h.html#a0ad2f5012ed700af1892f82e4af5989da01a473ed90682482fc2d409e04986cea", null ] ] ], [ "le_audio_I2SChannel_t", "le__audio__interface_8h.html#a94794180ed71a84bd26a1f525858f252", [ [ "LE_AUDIO_I2S_LEFT", "le__audio__interface_8h.html#a94794180ed71a84bd26a1f525858f252a0a0279115b994448752f8a7ca03a9d08", null ], [ "LE_AUDIO_I2S_RIGHT", "le__audio__interface_8h.html#a94794180ed71a84bd26a1f525858f252a346b13f5c03c3c6337f70adedbe99e4c", null ], [ "LE_AUDIO_I2S_MONO", "le__audio__interface_8h.html#a94794180ed71a84bd26a1f525858f252aac9b211c4afe16b4db9e9f437eab0a5d", null ], [ "LE_AUDIO_I2S_STEREO", "le__audio__interface_8h.html#a94794180ed71a84bd26a1f525858f252a6ce77f5f956b203e15f662900a5103dd", null ], [ "LE_AUDIO_I2S_REVERSE", "le__audio__interface_8h.html#a94794180ed71a84bd26a1f525858f252a32b9663e69f498538708a913476b26f2", null ] ] ], [ "le_audio_MediaEvent_t", "le__audio__interface_8h.html#aaf870f5f30f4f6f65efb873c5d0cb5f1", [ [ "LE_AUDIO_MEDIA_ENDED", "le__audio__interface_8h.html#aaf870f5f30f4f6f65efb873c5d0cb5f1a7dbc0c9a2c3839d3db974c5aa5be344d", null ], [ "LE_AUDIO_MEDIA_NO_MORE_SAMPLES", "le__audio__interface_8h.html#aaf870f5f30f4f6f65efb873c5d0cb5f1a06883432159e9e69637fbe5eefd59159", null ], [ "LE_AUDIO_MEDIA_ERROR", "le__audio__interface_8h.html#aaf870f5f30f4f6f65efb873c5d0cb5f1a5f7de6714ea54f09d036a87dd1c63a50", null ], [ "LE_AUDIO_MEDIA_MAX", "le__audio__interface_8h.html#aaf870f5f30f4f6f65efb873c5d0cb5f1a0d7192558212ce592db643ee43bd1054", null ] ] ], [ "le_audio_Profile_t", "le__audio__interface_8h.html#a3d396e4c3ed914277e81c39f3c423ed5", [ [ "LE_AUDIO_HANDSFREE", "le__audio__interface_8h.html#a3d396e4c3ed914277e81c39f3c423ed5a0b2baa1a1db29f3ef78d31e6ca9b7648", null ], [ "LE_AUDIO_HANDSET", "le__audio__interface_8h.html#a3d396e4c3ed914277e81c39f3c423ed5aed17351c74da18eea646b52432621bbf", null ], [ "LE_AUDIO_HEADSET", "le__audio__interface_8h.html#a3d396e4c3ed914277e81c39f3c423ed5a28b615e66b45a58709c6389f905f606e", null ], [ "LE_AUDIO_TTY", "le__audio__interface_8h.html#a3d396e4c3ed914277e81c39f3c423ed5a7de255a63a21334b4b792c33bfdfa8a9", null ], [ "LE_AUDIO_USB", "le__audio__interface_8h.html#a3d396e4c3ed914277e81c39f3c423ed5a3fbcc52b25d4c6053f687bb155b30abd", null ] ] ], [ "le_audio_AddDtmfDetectorHandler", "le__audio__interface_8h.html#a6e65275798c0db287fc1b540cdc0db8b", null ], [ "le_audio_AddMediaHandler", "le__audio__interface_8h.html#a9996ac9d23333cf8219f28b69cac4f81", null ], [ "le_audio_Close", "le__audio__interface_8h.html#abafeb411da7b1a14b2d5777fc1d3e394", null ], [ "le_audio_Connect", "le__audio__interface_8h.html#a338df65b2fb1ae0140d86880adbcf0de", null ], [ "le_audio_ConnectService", "le__audio__interface_8h.html#a65a8844fc6d2e1b7ed78f33bef1b9990", null ], [ "le_audio_CreateConnector", "le__audio__interface_8h.html#a570aaf85086f00aca592acfbaaa237be", null ], [ "le_audio_DeleteConnector", "le__audio__interface_8h.html#a3f40b13ff980040503927f59bb3e86a9", null ], [ "le_audio_DisableAutomaticGainControl", "le__audio__interface_8h.html#a364cdff3d9fa7b2ced00ef92c0c4e9f7", null ], [ "le_audio_DisableEchoCanceller", "le__audio__interface_8h.html#afc413a569b1e7eb877a3f98c2b52b05d", null ], [ "le_audio_DisableFirFilter", "le__audio__interface_8h.html#ae5be820a7a167c307d64ea2c15b0abb4", null ], [ "le_audio_DisableIirFilter", "le__audio__interface_8h.html#af7958cd14c83c479ede6ae7a7953461b", null ], [ "le_audio_DisableNoiseSuppressor", "le__audio__interface_8h.html#a3d3d52002fe6bf95271db1a16b1573f7", null ], [ "le_audio_Disconnect", "le__audio__interface_8h.html#a6b88df9301038375701e4c15a4c8aaf0", null ], [ "le_audio_DisconnectService", "le__audio__interface_8h.html#af72a5338e5fd23d17e0274e43642c77a", null ], [ "le_audio_EnableAutomaticGainControl", "le__audio__interface_8h.html#ac4978d8d632269730c67e27d66fba818", null ], [ "le_audio_EnableEchoCanceller", "le__audio__interface_8h.html#a54df27e4ab733a1f50e17903d7a9ae88", null ], [ "le_audio_EnableFirFilter", "le__audio__interface_8h.html#adedb3bb7e372fffa406f001bdb353e96", null ], [ "le_audio_EnableIirFilter", "le__audio__interface_8h.html#ad5eee81a34cc554ddef8a29c64bcd498", null ], [ "le_audio_EnableNoiseSuppressor", "le__audio__interface_8h.html#ac1af23c9febed1378620370a6961ce89", null ], [ "le_audio_Flush", "le__audio__interface_8h.html#a7a5855b7be77110eaca1846b17792597", null ], [ "le_audio_GetDefaultI2sMode", "le__audio__interface_8h.html#a0b727e15c16fffe10cdd5d345b297194", null ], [ "le_audio_GetDefaultPcmTimeSlot", "le__audio__interface_8h.html#a3f87e41dabde5bfb1170df527c380b9d", null ], [ "le_audio_GetEncodingFormat", "le__audio__interface_8h.html#a62e45a441a7d7ab5b7d20b41849331a2", null ], [ "le_audio_GetGain", "le__audio__interface_8h.html#a51a86829cdd6f27234f482e5dbb6c933", null ], [ "le_audio_GetPcmCompanding", "le__audio__interface_8h.html#aab9a28f3c695b90f8b9f622eb401f6cf", null ], [ "le_audio_GetPcmSamplingRate", "le__audio__interface_8h.html#a36779982278d3f965286582f38917247", null ], [ "le_audio_GetPcmSamplingResolution", "le__audio__interface_8h.html#a70fbe5e1ae02033e89ad04bbf1ed2b39", null ], [ "le_audio_GetPlatformSpecificGain", "le__audio__interface_8h.html#a56269b13844a1e90be4e4c86f50bed5a", null ], [ "le_audio_GetProfile", "le__audio__interface_8h.html#a1bf9091e0068a75a34fdf638ce0f2bc3", null ], [ "le_audio_GetSampleAmrDtx", "le__audio__interface_8h.html#ab26d633ee83aed52dae838cb9d721f87", null ], [ "le_audio_GetSampleAmrMode", "le__audio__interface_8h.html#aa293e15d41f7c1c384053947b5a4dbea", null ], [ "le_audio_GetSamplePcmChannelNumber", "le__audio__interface_8h.html#a40bf3633c3050a7526a100562edc97f9", null ], [ "le_audio_GetSamplePcmSamplingRate", "le__audio__interface_8h.html#a80fb48632ce8f638cea4a3e5d333d66f", null ], [ "le_audio_GetSamplePcmSamplingResolution", "le__audio__interface_8h.html#a70b9f904ce225aad4fb80b8b24a1f92a", null ], [ "le_audio_GetSamples", "le__audio__interface_8h.html#a9c55a59849afcbb2ccef88cd4265782e", null ], [ "le_audio_Mute", "le__audio__interface_8h.html#a147e97c49dbc003f63df78f97d5fca32", null ], [ "le_audio_OpenI2sRx", "le__audio__interface_8h.html#a9e7d0042c4f422554eb10d64535608e5", null ], [ "le_audio_OpenI2sTx", "le__audio__interface_8h.html#a2633c1368adf60e342d7cadbbfa6278b", null ], [ "le_audio_OpenMic", "le__audio__interface_8h.html#a74f1ef979329f6c2bd56ea622f4d05b2", null ], [ "le_audio_OpenModemVoiceRx", "le__audio__interface_8h.html#ae3ed568ba4d2763ea77e17e77b20ff02", null ], [ "le_audio_OpenModemVoiceTx", "le__audio__interface_8h.html#ad745f008bb04873c817da7af3daf783d", null ], [ "le_audio_OpenPcmRx", "le__audio__interface_8h.html#aa0f0b5fcab8844c67a936d88fa050cf5", null ], [ "le_audio_OpenPcmTx", "le__audio__interface_8h.html#a5e112543e8525775aa670dc71b320766", null ], [ "le_audio_OpenPlayer", "le__audio__interface_8h.html#a92eb1b6377f50ff07b97c5b8546f01ec", null ], [ "le_audio_OpenRecorder", "le__audio__interface_8h.html#aeac35459c36748a4471b6d45f1ebeb24", null ], [ "le_audio_OpenSpeaker", "le__audio__interface_8h.html#a5c19afce44021c4abf6193707317f8de", null ], [ "le_audio_OpenUsbRx", "le__audio__interface_8h.html#acd8be89289067cef9441a8ed1d891146", null ], [ "le_audio_OpenUsbTx", "le__audio__interface_8h.html#adb38f11ac78cf99160c19f69b4db0eb8", null ], [ "le_audio_Pause", "le__audio__interface_8h.html#a80343ca9800ab80f818bbe0361bb226b", null ], [ "le_audio_PlayDtmf", "le__audio__interface_8h.html#a8b1546842a6e917db9a9458aceb77c82", null ], [ "le_audio_PlayFile", "le__audio__interface_8h.html#aea2c5d0b394cfab87503639c534300c9", null ], [ "le_audio_PlaySamples", "le__audio__interface_8h.html#afd37d59ab8207338da197554f49d7ff0", null ], [ "le_audio_PlaySignallingDtmf", "le__audio__interface_8h.html#a852728586cacfcbf63ae59b6f80847eb", null ], [ "le_audio_RecordFile", "le__audio__interface_8h.html#a393a26f6cff7fe05c1813fcafeef50f3", null ], [ "le_audio_RemoveDtmfDetectorHandler", "le__audio__interface_8h.html#a7fd6191ed6ff512407bfe01d20a51459", null ], [ "le_audio_RemoveMediaHandler", "le__audio__interface_8h.html#a60442c840a69155110ae878e03e16059", null ], [ "le_audio_Resume", "le__audio__interface_8h.html#a1dba6618bd8fc9835869ee72c3fbd850", null ], [ "le_audio_SetEncodingFormat", "le__audio__interface_8h.html#aead87ec16d317bb4e4a8e7e9ea37550b", null ], [ "le_audio_SetGain", "le__audio__interface_8h.html#ad62587dacf0cb087697a62fb9f41d938", null ], [ "le_audio_SetPcmCompanding", "le__audio__interface_8h.html#a593682daa95aec349e48144f5b46c658", null ], [ "le_audio_SetPcmSamplingRate", "le__audio__interface_8h.html#ae7c9d76c5377ad5fae13b24477827f45", null ], [ "le_audio_SetPcmSamplingResolution", "le__audio__interface_8h.html#ab3678e77c8d69f248cd339042bd824cc", null ], [ "le_audio_SetPlatformSpecificGain", "le__audio__interface_8h.html#ad9235b668cc80f33bc5045327be8bffb", null ], [ "le_audio_SetProfile", "le__audio__interface_8h.html#ae2e6553f8125a30676d31f5cbd43a3b8", null ], [ "le_audio_SetSampleAmrDtx", "le__audio__interface_8h.html#a5932f51fb1398cc2442c8bb765ca4071", null ], [ "le_audio_SetSampleAmrMode", "le__audio__interface_8h.html#a18600cdbd3995c9c2ca24f9b15991f7d", null ], [ "le_audio_SetSamplePcmChannelNumber", "le__audio__interface_8h.html#aae7db9f0933119fb5a61162722b3274a", null ], [ "le_audio_SetSamplePcmSamplingRate", "le__audio__interface_8h.html#a04adfcc0e8f5796eca53c31cd5dd6528", null ], [ "le_audio_SetSamplePcmSamplingResolution", "le__audio__interface_8h.html#aae37b46c13f76144dd94c48bfe94998b", null ], [ "le_audio_Stop", "le__audio__interface_8h.html#a4aebc6e8cdc4389c375e93418823af71", null ], [ "le_audio_Unmute", "le__audio__interface_8h.html#adad24547293481964039efe56bc14e2b", null ] ];
legatoproject/legato-docs
15_10/le__audio__interface_8h.js
JavaScript
mpl-2.0
14,872
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; // The panel module currently supports only Firefox. // See: https://bugzilla.mozilla.org/show_bug.cgi?id=jetpack-panel-apps module.metadata = { "stability": "stable", "engines": { "Firefox": "*" } }; const { Ci } = require("chrome"); const { Class } = require("sdk/core/heritage"); const { merge } = require("sdk/util/object"); const { WorkerHost } = require("sdk/content/utils"); const { Worker } = require("sdk/deprecated/sync-worker"); const { Disposable } = require("sdk/core/disposable"); const { WeakReference } = require('sdk/core/reference'); const { contract: loaderContract } = require("sdk/content/loader"); const { contract } = require("sdk/util/contract"); const { on, off, emit, setListeners } = require("sdk/event/core"); const { EventTarget } = require("sdk/event/target"); const domPanel = require("./panel/utils"); const { events } = require("./panel/events"); const systemEvents = require("sdk/system/events"); const { filter, pipe, stripListeners } = require("sdk/event/utils"); const { getNodeView, getActiveView } = require("sdk/view/core"); const { isNil, isObject, isNumber } = require("sdk/lang/type"); const { getAttachEventType } = require("sdk/content/utils"); const { number, boolean, object } = require('sdk/deprecated/api-utils'); const { Style } = require("sdk/stylesheet/style"); const { attach, detach } = require("sdk/content/mod"); let isRect = ({top, right, bottom, left}) => [top, right, bottom, left]. some(value => isNumber(value) && !isNaN(value)); let isSDKObj = obj => obj instanceof Class; let rectContract = contract({ top: number, right: number, bottom: number, left: number }); let position = { is: object, map: v => (isNil(v) || isSDKObj(v) || !isObject(v)) ? v : rectContract(v), ok: v => isNil(v) || isSDKObj(v) || (isObject(v) && isRect(v)), msg: 'The option "position" must be a SDK object registered as anchor; ' + 'or an object with one or more of the following keys set to numeric ' + 'values: top, right, bottom, left.' } let displayContract = contract({ width: number, height: number, focus: boolean, autohide: boolean, position: position, opacity: number }); let panelContract = contract(merge({ // contentStyle* / contentScript* are sharing the same validation constraints, // so they can be mostly reused, except for the messages. contentStyle: merge(Object.create(loaderContract.rules.contentScript), { msg: 'The `contentStyle` option must be a string or an array of strings.' }), contentStyleFile: merge(Object.create(loaderContract.rules.contentScriptFile), { msg: 'The `contentStyleFile` option must be a local URL or an array of URLs' }) }, displayContract.rules, loaderContract.rules)); function isDisposed(panel) { return !views.has(panel) } let panels = new WeakMap(); let models = new WeakMap(); let views = new WeakMap(); let workers = new WeakMap(); let styles = new WeakMap(); const viewFor = (panel) => views.get(panel); const modelFor = (panel) => models.get(panel); const panelFor = (view) => panels.get(view); const workerFor = (panel) => workers.get(panel); const styleFor = (panel) => styles.get(panel); // Utility function takes `panel` instance and makes sure it will be // automatically hidden as soon as other panel is shown. let setupAutoHide = new function() { let refs = new WeakMap(); return function setupAutoHide(panel) { // Create system event listener that reacts to any panel showing and // hides given `panel` if it's not the one being shown. function listener({subject}) { // It could be that listener is not GC-ed in the same cycle as // panel in such case we remove listener manually. let view = viewFor(panel); if (!view) systemEvents.off("popupshowing", listener); else if (subject !== view) panel.hide(); } // system event listener is intentionally weak this way we'll allow GC // to claim panel if it's no longer referenced by an add-on code. This also // helps minimizing cleanup required on unload. systemEvents.on("popupshowing", listener); // To make sure listener is not claimed by GC earlier than necessary we // associate it with `panel` it's associated with. This way it won't be // GC-ed earlier than `panel` itself. refs.set(panel, listener); } } const Panel = Class({ implements: [ // Generate accessors for the validated properties that update model on // set and return values from model on get. panelContract.properties(modelFor), EventTarget, Disposable, WeakReference ], extends: WorkerHost(workerFor), setup: function setup(options) { let model = merge({ defaultWidth: 320, defaultHeight: 220, focus: true, position: Object.freeze({}), }, panelContract(options)); models.set(this, model); if (model.contentStyle || model.contentStyleFile) { styles.set(this, Style({ uri: model.contentStyleFile, source: model.contentStyle })); } // Setup view let view = domPanel.make(); panels.set(view, this); views.set(this, view); // Load panel content. domPanel.setURL(view, model.contentURL); setupAutoHide(this); // Setup listeners. setListeners(this, options); let worker = new Worker(stripListeners(options)); workers.set(this, worker); // pipe events from worker to a panel. pipe(worker, this); }, dispose: function dispose() { this.hide(); off(this); workerFor(this).destroy(); detach(styleFor(this)); domPanel.dispose(viewFor(this)); // Release circular reference between view and panel instance. This // way view will be GC-ed. And panel as well once all the other refs // will be removed from it. views.delete(this); }, /* Public API: Panel.width */ get width() { return modelFor(this).width; }, set width(value) { return this.resize(value, this.height); }, /* Public API: Panel.height */ get height() { return modelFor(this).height; }, set height(value) { return this.resize(this.width, value); }, /* Public API: Panel.focus */ get focus() { return modelFor(this).focus; }, /* Public API: Panel.position */ get position() { return modelFor(this).position; }, get contentURL() { modelFor(this).contentURL; }, set contentURL(value) { let model = modelFor(this); model.contentURL = panelContract({ contentURL: value }).contentURL; domPanel.setURL(viewFor(this), model.contentURL); // Detach worker so that messages send will be queued until it's // reatached once panel content is ready. workerFor(this).detach(); }, /* Public API: Panel.isShowing */ get isShowing() { return !isDisposed(this) && domPanel.isOpen(viewFor(this)); }, /* Public API: Panel.show */ show: function show(options={}, anchor) { if (options instanceof Ci.nsIDOMElement) { [anchor, options] = [options, null]; } if (anchor instanceof Ci.nsIDOMElement) { console.warn( "Passing a DOM node to Panel.show() method is an unsupported " + "feature that will be soon replaced. " + "See: https://bugzilla.mozilla.org/show_bug.cgi?id=878877" ); } let model = modelFor(this); let view = viewFor(this); let anchorView = getNodeView(anchor || options.position || model.position); options = merge({ position: model.position, width: model.width, height: model.height, defaultWidth: model.defaultWidth, defaultHeight: model.defaultHeight, focus: model.focus, autohide: model.autohide, opacity: model.opacity }, displayContract(options)); if (!isDisposed(this)) domPanel.show(view, options, anchorView); return this; }, /* Public API: Panel.hide */ hide: function hide() { // Quit immediately if panel is disposed or there is no state change. domPanel.close(viewFor(this)); return this; }, /* Public API: Panel.resize */ resize: function resize(width, height) { let model = modelFor(this); let view = viewFor(this); let change = panelContract({ width: width || model.width || model.defaultWidth, height: height || model.height || model.defaultHeight }); model.width = change.width; model.height = change.height; domPanel.resize(view, model.width, model.height); return this; }, fadeOut: function fadeOut() { let view = viewFor(this); domPanel.fadeOut(view); } }); exports.Panel = Panel; // Note must be defined only after value to `Panel` is assigned. getActiveView.define(Panel, viewFor); // Filter panel events to only panels that are create by this module. let panelEvents = filter(events, ({target}) => panelFor(target)); // Panel events emitted after panel has being shown. let shows = filter(panelEvents, ({type}) => type === "popupshown"); // Panel events emitted after panel became hidden. let hides = filter(panelEvents, ({type}) => type === "popuphidden"); // Panel events emitted after content inside panel is ready. For different // panels ready may mean different state based on `contentScriptWhen` attribute. // Weather given event represents readyness is detected by `getAttachEventType` // helper function. let ready = filter(panelEvents, ({type, target}) => getAttachEventType(modelFor(panelFor(target))) === type); // Panel event emitted when the contents of the panel has been loaded. let readyToShow = filter(panelEvents, ({type}) => type === "DOMContentLoaded"); // Styles should be always added as soon as possible, and doesn't makes them // depends on `contentScriptWhen` let start = filter(panelEvents, ({type}) => type === "document-element-inserted"); // Forward panel show / hide events to panel's own event listeners. on(shows, "data", ({target}) => { let panel = panelFor(target); if (modelFor(panel).ready) emit(panel, "show"); }); on(hides, "data", ({target}) => { let panel = panelFor(target); if (modelFor(panel).ready) emit(panel, "hide"); }); on(ready, "data", ({target}) => { let panel = panelFor(target); let window = domPanel.getContentDocument(target).defaultView; workerFor(panel).attach(window); }); on(readyToShow, "data", ({target}) => { let panel = panelFor(target); if (!modelFor(panel).ready) { modelFor(panel).ready = true; if (viewFor(panel).state == "open") emit(panel, "show"); } }); on(start, "data", ({target}) => { let panel = panelFor(target); let window = domPanel.getContentDocument(target).defaultView; attach(styleFor(panel), window); });
raymak/contextualfeaturerecommender
phase2/addon/lib/panel.js
JavaScript
mpl-2.0
10,892
(function (badges, $, undefined) { "use strict"; var options = {}, geocoder, map, marker; badges.options = function (o) { $.extend(options, o); }; badges.init = function () { initializeTypeahead(); initializeImagePreview(); $(".datepicker").datepicker({ format: 'm/d/yyyy', autoclose: true }); initializeMap(); }; function initializeTypeahead() { $("#Experience_Name").typeahead({ name: 'title', prefetch: options.TitlesUrl, limit: 10 }); $("#Experience_Organization").typeahead({ name: 'orgs', prefetch: options.OrganizationsUrl, limit: 10 }); } function initializeImagePreview() { $("#cover-image").change(function () { var filesToUpload = this.files; if (filesToUpload.length !== 1) return; var file = filesToUpload[0]; if (!file.type.match(/image.*/)) { alert("only images, please"); } var img = document.getElementById("cover-preview"); img.src = window.URL.createObjectURL(file); img.onload = function(e) { window.URL.revokeObjectURL(this.src); }; //img.height = 500; }); } function initializeMap() { var davisLatLng = new google.maps.LatLng(38.5449065, -121.7405167); geocoder = new google.maps.Geocoder(); var mapOptions = { center: davisLatLng, zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); marker = new google.maps.Marker({ map: map, position: davisLatLng }); $("#Experience_Location").blur(function () { var address = this.value; geocoder.geocode({ 'address': address }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { if (marker) marker.setMap(null); //clear existing marker map.setCenter(results[0].geometry.location); marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); if (results[0].geometry.viewport) map.fitBounds(results[0].geometry.viewport); } else { alert('Geocode was not successful for the following reason: ' + status); } }); }); } }(window.Badges = window.Badges || {}, jQuery));
ucdavis/Badges
Badges/Scripts/public/modifyexperience.js
JavaScript
mpl-2.0
2,851
export default (collection, clickable, text) => () => { return collection('.consul-auth-method-list [data-test-list-row]', { authMethod: clickable('a'), name: text('[data-test-auth-method]'), displayName: text('[data-test-display-name]'), type: text('[data-test-type]'), }); };
hashicorp/consul
ui/packages/consul-ui/app/components/consul/auth-method/list/pageobject.js
JavaScript
mpl-2.0
298
'use strict'; require('should'); describe('index.html', () => { beforeEach(() => { browser.url('/'); // browser.localStorage('DELETE') does not work in PhantomJS browser.execute(function() { delete window.localStorage; window.localStorage = {}; }); browser.url('/'); $('#default-username').waitForEnabled(); $('#default-username').setValue('test'); $('#shared-secret').setValue('test'); $('.save-settings').click(); $('#domain').waitForEnabled(); // wait for .modal-bg to be hidden browser.waitUntil(() => $('.modal-bg').getCssProperty('z-index').value == -1 ); }); it('should generate a password', () => { $('#domain').setValue('example.com'); browser.waitUntil(() => $('#password').getValue() == 'z<u9N_[c"R' ); }); it('should generate a password at a given index', () => { $('#index').selectByVisibleText('1'); $('#domain').setValue('example.com'); browser.waitUntil(() => $('#password').getValue() == 'g:3WGYj0}~' ); }); it('should generate a password of a given length', () => { $('#length').selectByVisibleText('8'); $('#domain').setValue('example.com'); browser.waitUntil(() => $('#password').getValue() == 'u9N_[c"R' ); }); it('should open settings menu', () => { $('#open-settings').click(); browser.waitUntil(() => $('#settings').getLocation('y') >= 0 ); }); it('should change the algorithm', () => { $('#open-settings').click(); $('#algorithm').waitForEnabled(); $('#algorithm').selectByVisibleText('SHA-512'); $('.save-settings').click(); $('#domain').waitForEnabled(); $('#domain').setValue('example.com'); browser.waitUntil(() => $('#password').getValue() == 'V{fvC^YRi(' ); }); });
chameleoid/telepathy-web
test/telepathy-web.js
JavaScript
mpl-2.0
1,829
"use strict"; var myTable = require("../data/myTables.json"); // Dictionaries to modify/extend the original dictionaries var devanagari_dict_mod = {}; var telugu_dict_mod = {}; var kannada_dict_mod = {}; var gujarati_dict_mod = {}; var tamil_dict_mod = {}; var bengali_dict_mod = {}; var gurmukhi_dict_mod = {}; var malayalam_dict_mod = {}; var oriya_dict_mod = {}; var english_dict_mod = {}; var devanagari_dict_rev = {}; var telugu_dict_rev = {}; var kannada_dict_rev = {}; var gujarati_dict_rev = {}; var tamil_dict_rev = {}; var bengali_dict_rev = {}; var gurmukhi_dict_rev = {}; var malayalam_dict_rev = {}; var oriya_dict_rev = {}; var english_dict_rev = {}; var katapayadi_dict = myTable.katapayadi_dict; function init() { // new modified/extended dictionaries devanagari_dict_mod = extend(myTable.devanagari_dict); telugu_dict_mod = extend(myTable.telugu_dict); kannada_dict_mod = extend(myTable.kannada_dict); gujarati_dict_mod = extend(myTable.gujarati_dict); tamil_dict_mod = extend(myTable.tamil_dict); bengali_dict_mod = extend(myTable.bengali_dict); gurmukhi_dict_mod = extend(myTable.gurmukhi_dict); malayalam_dict_mod = extend(myTable.malayalam_dict); oriya_dict_mod = extend(myTable.oriya_dict); english_dict_mod = extend(myTable.english_dict); // reverse dictionaries devanagari_dict_rev = reverse(myTable.devanagari_dict); telugu_dict_rev = reverse(myTable.telugu_dict); kannada_dict_rev = reverse(myTable.kannada_dict); gujarati_dict_rev = reverse(myTable.gujarati_dict); tamil_dict_rev = reverse(myTable.tamil_dict); bengali_dict_rev = reverse(myTable.bengali_dict); gurmukhi_dict_rev = reverse(myTable.gurmukhi_dict); malayalam_dict_rev = reverse(myTable.malayalam_dict); oriya_dict_rev = reverse(myTable.oriya_dict); english_dict_rev = reverse(myTable.english_dict); } function detectLanguage(inp_txt){ var indx; var chr; for (indx = 0; indx < inp_txt.length; indx++){ chr = inp_txt.charAt(indx); if(chr == "\u0950") { // skip Devanagari 'AUM', since it is used across all Indian languages continue; } else if((array_key_exists(chr, devanagari_dict_rev["Independent_vowels"])) || (array_key_exists(chr, devanagari_dict_rev["Consonants"]))) { return "Devanagari"; } else if((array_key_exists(chr, telugu_dict_rev["Independent_vowels"])) || (array_key_exists(chr, telugu_dict_rev["Consonants"]))) { return "Telugu"; } else if((array_key_exists(chr, kannada_dict_rev["Independent_vowels"])) || (array_key_exists(chr, kannada_dict_rev["Consonants"]))) { return "Kannada"; } else if((array_key_exists(chr, gujarati_dict_rev["Independent_vowels"])) || (array_key_exists(chr, gujarati_dict_rev["Consonants"]))) { return "Gujarati"; } else if((array_key_exists(chr, tamil_dict_rev["Independent_vowels"])) || (array_key_exists(chr, tamil_dict_rev["Consonants"]))) { return "Tamil"; } else if((array_key_exists(chr, bengali_dict_rev["Independent_vowels"])) || (array_key_exists(chr, bengali_dict_rev["Consonants"]))) { return "Bengali"; } else if((array_key_exists(chr, gurmukhi_dict_rev["Independent_vowels"])) || (array_key_exists(chr, gurmukhi_dict_rev["Consonants"]))) { return "Gurmukhi"; } else if((array_key_exists(chr, malayalam_dict_rev["Independent_vowels"])) || (array_key_exists(chr, malayalam_dict_rev["Consonants"]))) { return "Malayalam"; } else if((array_key_exists(chr, oriya_dict_rev["Independent_vowels"])) || (array_key_exists(chr, oriya_dict_rev["Consonants"]))) { return "Oriya"; } } return "English"; // default } function convert2IndicScript(inp_txt, encoding_type, indicScript, modeStrict, reverse, preferASCIIDigits) { var indx=0; var out = ""; var vovel_needed_p = false; var word_start_p = true; var prev_Type = "NoMatch"; var insideTag_p = false; var blk, blkLen, Type; // Assigning the dictionary var lang_dict; if(reverse){ if(indicScript == "Devanagari"){lang_dict = devanagari_dict_rev;} else if(indicScript == "Telugu"){lang_dict = telugu_dict_rev;} else if(indicScript == "Kannada"){lang_dict = kannada_dict_rev;} else if(indicScript == "Gujarati"){lang_dict = gujarati_dict_rev;} else if(indicScript == "Tamil"){lang_dict = tamil_dict_rev;} else if(indicScript == "Bengali"){lang_dict = bengali_dict_rev;} else if(indicScript == "Gurmukhi"){lang_dict = gurmukhi_dict_rev;} else if(indicScript == "Malayalam"){lang_dict = malayalam_dict_rev;} else if(indicScript == "Oriya"){lang_dict = oriya_dict_rev;} else {lang_dict = english_dict_rev;} } else if(modeStrict){ // orignal dictionaries if modeStrict if(indicScript == "Devanagari"){lang_dict = myTable.devanagari_dict;} else if(indicScript == "Telugu"){lang_dict = myTable.telugu_dict;} else if(indicScript == "Kannada"){lang_dict = myTable.kannada_dict;} else if(indicScript == "Gujarati"){lang_dict = myTable.gujarati_dict;} else if(indicScript == "Tamil"){lang_dict = myTable.tamil_dict;} else if(indicScript == "Bengali"){lang_dict = myTable.bengali_dict;} else if(indicScript == "Gurmukhi"){lang_dict = myTable.gurmukhi_dict;} else if(indicScript == "Malayalam"){lang_dict = myTable.malayalam_dict;} else if(indicScript == "Oriya"){lang_dict = myTable.oriya_dict;} else {lang_dict = myTable.english_dict;} } else { // modified/extended dictionaries if not modeStrict if(indicScript == "Devanagari"){lang_dict = devanagari_dict_mod;} else if(indicScript == "Telugu"){lang_dict = telugu_dict_mod;} else if(indicScript == "Kannada"){lang_dict = kannada_dict_mod;} else if(indicScript == "Gujarati"){lang_dict = gujarati_dict_mod;} else if(indicScript == "Tamil"){lang_dict = tamil_dict_mod;} else if(indicScript == "Bengali"){lang_dict = bengali_dict_mod;} else if(indicScript == "Gurmukhi"){lang_dict = gurmukhi_dict_mod;} else if(indicScript == "Malayalam"){lang_dict = malayalam_dict_mod;} else if(indicScript == "Oriya"){lang_dict = oriya_dict_mod;} else {lang_dict = english_dict_mod;} } // convert to ITRANS if((!reverse) && ((encoding_type == "ISO") || (encoding_type == "IAST"))) { inp_txt = convert2ITRANS(inp_txt, encoding_type); } while (indx < inp_txt.length){ // skip space charecter "&nbsp;" if(inp_txt.substring(indx,indx+6) == "&nbsp;"){ if(vovel_needed_p){ out += lang_dict["VIRAMA"]; } out += "&nbsp;"; indx += 6; word_start_p = true; vovel_needed_p=0; continue; } [blk, blkLen, Type, vovel_needed_p, insideTag_p] = getNxtIndicChr(lang_dict, inp_txt.substring(indx), modeStrict, word_start_p, vovel_needed_p, insideTag_p, reverse, preferASCIIDigits); out += blk; if(Type == "NoMatch"){ //document.write( inp_txt.substring(indx, indx+blkLen)+": ***** NoMatch (blkLen)<br>"); indx += 1; word_start_p = true; } else{ //document.write( inp_txt.substring(indx, indx+blkLen)+": "+blk+" Match (blkLen)<br>"); indx += blkLen; word_start_p = false; } } if(vovel_needed_p){ out += lang_dict["VIRAMA"]; } vovel_needed_p=0; //document.getElementById("out_txt").value=out; return out; } function convert2ITRANS(inp_txt, encoding_type) { var insideTag_p = false; var indx=0; var out = ""; var blk, blkLen, Type, insideTag_p; var decoding_dict; // selecting appropriate dict to convert to ITRANS if(encoding_type == "ISO") { decoding_dict = myTable.iso2itrans_dict; } else if(encoding_type == "IAST") { decoding_dict = myTable.iast2itrans_dict; } else { return inp_txt; } while (indx < inp_txt.length){ [blk, blkLen, Type, insideTag_p] = convertNextBlk2ITRANS(decoding_dict, inp_txt.substring(indx), insideTag_p); out += blk; if(Type == "NoMatch"){ indx += 1; } else{ indx += blkLen; } } return out; } function convertNextBlk2ITRANS(trans_dict, inp_txt, insideTag_p){ var MAX=2; // *** set this var debug=0; var insideTag = insideTag_p; var Type = "NoMatch"; //default var out = ""; var blk = ""; var blkLen=MAX; while(blkLen > 0){ //if(debug){document.write( inp_txt.substring(0, blkLen)+" <br>");} // selecting block, skip it its a TAG i.e., inside < > if( (!insideTag) && (inp_txt.charAt(0) == "<") ){ insideTag = true; break; } else if( (insideTag) && (inp_txt.charAt(0) == ">") ){ insideTag = false; break; } else if(insideTag){ break; } blk= inp_txt.substring(0, blkLen); //if(debug){document.write( "<br>blk...:"+blk+" "+word_start+" "+vovel_needed+"<br>");} if( array_key_exists(blk, trans_dict) ){ Type = "Match"; out += trans_dict[blk]; //if(debug){document.write( "5: "+"-"+blk+" "+trans_dict[blk]);} break; } // No match for the taken block else{ blkLen -= 1; } } if(Type == "NoMatch"){// no match found out += inp_txt[0]; } else{ //if(debug){document.write( "Match "+vovel_needed+"<br>");} } //if(debug){document.write( "<br>returning "+out+" "+blkLen+"<br>");} return [out, blkLen, Type, insideTag]; }; function getNxtIndicChr(lang_dict, inp_txt, modeStrict, word_start_p, vovel_needed_p, insideTag_p, reverse, preferASCIIDigits){ var MAX=4; // *** set this var debug=0; var out = ""; var Type = "NoMatch"; //default var vovel_needed = vovel_needed_p; var word_start = word_start_p; var insideTag = insideTag_p; var blk = ""; var blkLen=MAX; var iteration = 1; // first time // decoding charecter-by-charecter in reverse convertion if(reverse){ blkLen=1; } while(blkLen > 0){ //if(debug){document.write( inp_txt.substring(0, blkLen)+" <br>");} // selecting block, skip it its a TAG i.e., inside < > if( (!insideTag) && (inp_txt.charAt(0) == "<") ){ insideTag = true; break; } else if( (insideTag) && (inp_txt.charAt(0) == ">") ){ insideTag = false; break; } else if(insideTag){ break; } else if(inp_txt.length >= blkLen){ // string is longer than or equal to blkLen blk= inp_txt.substring(0, blkLen); } else if(inp_txt.length > 0){ // string is shorter than blkLen blk = inp_txt.substring(0); } else{ // string is of zero length break; } //if(debug){document.write( "<br>blk...:"+blk+" "+word_start+" "+vovel_needed+"<br>");} // if not modeStrict, convert the 1st letter of every word to lower-case if((!modeStrict) && (word_start == true)){ blk = blk.substring(0,1).toLowerCase() + blk.substring(1); } // 2nd iteration ==> working case-insensitive if((!modeStrict) && (iteration == 2)){ blk = blk.toLowerCase(); } // Accent marks : Do not change any flags for this case, except "Type" if(array_key_exists(blk, lang_dict["Accent_marks"])){ Type = "Accent"; out += lang_dict["Accent_marks"][blk]; //if(debug){document.write( "0: "+blk+" "+lang_dict["Accent_marks"][blk]+"<br>");} break; } // Independent vowels /*else if( (reverse || !vovel_needed) // for reverse convertion, vovel_needed condition is not required // *** This will be lossy translation *** // e.g., रई -> rii -> री */ else if( (vovel_needed == false) && (array_key_exists(blk, lang_dict["Independent_vowels"])) ){ Type = "Independent"; vovel_needed=0; out += lang_dict["Independent_vowels"][blk]; //if(debug){document.write( "5: "+"-"+blk+" "+lang_dict["Independent_vowels"][blk]);} break; } // Dependent vowels else if((vovel_needed) && (array_key_exists(blk, lang_dict["Dependent_vowel"])) ){ Type = "Vowel"; vovel_needed=0; out += lang_dict["Dependent_vowel"][blk]; //if(debug){document.write( "7: "+blk+" "+lang_dict["Dependent_vowel"][blk]);} break; } // Consonants else if(array_key_exists((blk), lang_dict["Consonants"])){ if(vovel_needed){ out += lang_dict["VIRAMA"]; } Type = "Consonants"; vovel_needed=1; out += lang_dict["Consonants"][blk]; //if(debug){document.write( "8: "+blk+" "+lang_dict["Consonants"][blk]);} break; } // Others [Do not convert ASCII Digits if option is selected] else if( !((isASCIIDigit(blk) == true) && (preferASCIIDigits == true)) && array_key_exists(blk, lang_dict["Others"])){ if(vovel_needed){ out += lang_dict["VIRAMA"]; } Type = "Other"; vovel_needed = 0; // nullify "a"+".h" in reverse conversion if(lang_dict["Others"][blk] == ".h"){ out = out.substring(0, out.length-1); } else { out += lang_dict["Others"][blk]; } //if(debug){document.write( "9: "+blk+" "+lang_dict["Others"][blk]+"<br>");} break; } // No match for the taken block else{ // 2nd iteration ==> repeat as case-insensitive if((!modeStrict) && (iteration == 1)){ iteration += 1; continue; } blkLen -= 1; } } if(Type == "NoMatch"){ // no match found if(vovel_needed){ out += lang_dict["VIRAMA"]; } //if(debug){document.write( "No match "+vovel_needed+"<br>");} out += inp_txt[0]; word_start = true; vovel_needed=0; } else{ //if(debug){document.write( "Match "+vovel_needed+"<br>");} word_start = false; } //if(debug){document.write( "<br>returning "+out+" "+blkLen+" "+Type+" "+vovel_needed+"<br>");} return [out, blkLen, Type, vovel_needed, insideTag]; }; function array_key_exists(key, dict) { if (key in dict) return true; else return false; } // to extend dictionaries function extend(org_dict) { var ext_dict = { "Independent_vowels" : { "ee" : org_dict['Independent_vowels']["E"] }, "Dependent_vowel" : { "ee" : org_dict['Dependent_vowel']["E"] }, "Consonants" : { "c" : org_dict['Consonants']["k"], "f" : org_dict['Consonants']["ph"], "z" : org_dict['Consonants']["j"], // Modifications eto IAST/ITRANS "t" : org_dict['Consonants']["T"], "tt" : org_dict['Consonants']["Th"], "th" : org_dict['Consonants']["t"], "tth" : org_dict['Consonants']["th"], "d" : org_dict['Consonants']["D"], "dd" : org_dict['Consonants']["Dh"], "dh" : org_dict['Consonants']["d"], "ddh" : org_dict['Consonants']["dh"] } }; var new_dict = cloneDict(org_dict); for (var property in ext_dict) { for(var key in ext_dict[property]){ if (ext_dict[property][key]) { new_dict[property][key] = ext_dict[property][key]; } } } return new_dict; }; // clone dictionaries function cloneDict(dict) { if(typeof(dict) != 'object') return dict; if(dict == null) return dict; var new_dict = new Object(); for(var property in dict){ new_dict[property] = cloneDict(dict[property]); } return new_dict; } // to extend dictionaries function reverse(org_dict) { var new_dict = new Object(); for (var property in org_dict) { new_dict[property] = cloneRevDict(org_dict[property]); } // nullify the adding of "VIRAMA" new_dict["VIRAMA"] = "a"; return new_dict; }; // clone dictionaries function cloneRevDict(dict) { if(typeof(dict) != 'object') return dict; if(dict == null) return dict; var new_dict = new Object(); for(var property in dict){ new_dict[dict[property]] = property; } return new_dict; } function isASCIIDigit(n) { return ((n>=0) && (n<=9)); } function convert2Katapayadi(inp_txt) { var indx=0, dict_indx; var out = ""; var insideTag = false; while (indx < inp_txt.length){ // skip space charecter "&nbsp;" if(inp_txt.substring(indx,indx+6) == "&nbsp;"){ out += "&nbsp;"; indx += 6; continue; } else if( (!insideTag) && (inp_txt.charAt(indx) == "<") ){ insideTag = true; out += inp_txt.charAt(indx); ++indx; } else if( (insideTag) && (inp_txt.charAt(indx) == ">") ){ insideTag = false; out += inp_txt.charAt(indx); ++indx; } else if(insideTag){ out += inp_txt.charAt(indx); ++indx; } else{ for(dict_indx=0; dict_indx<=9; ++dict_indx) { // if next charecter is VIRAMA, this char should be neglected if((katapayadi_dict[dict_indx].indexOf(inp_txt.charAt(indx)) >= 0) && (katapayadi_dict[10].indexOf(inp_txt.charAt(indx+1)) == -1)){ out += dict_indx.toString(); break; } } ++indx; } } return out; } exports.init = init; exports.detectLanguage = detectLanguage; exports.convert2IndicScript = convert2IndicScript; exports.convert2Katapayadi = convert2Katapayadi;
mohancloudworld/Parivartan
src/lib/myModule.js
JavaScript
mpl-2.0
18,889
/** * API for paddock information * * Copyright (c) 2015. Elec Research. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ * * Author: Tim Miller. * **/ var express = require('express'); var Paddock = agquire('ag/db/models-mongo/paddock'); var Reading = agquire('ag/db/models-mongo/reading'); var permissions = require('../../utils/permissions'); var responder = agquire('ag/routes/utils/responder'); var PaddockController = agquire('ag/db/controllers/PaddockController'); var router = express.Router(); /* Route HTTP Verb Description ===================================================== /api/paddocks GET Get paddocks. /api/paddocks/:object_id GET Get single paddock. /api/paddocks POST Create a paddock. /api/paddocks/:object_id PUT Update a paddock. /api/paddocks/:object_id DELETE Delete a paddock. */ /** * @api {post} /spatial/paddocks/ Create a Paddock * @apiName PostPaddocks * @apiGroup Paddocks * * @apiParam {String} name Name of new paddock. * @apiParam {Number} farm_id Id of farm that this paddock belongs to. * @apiParam {Object} loc contains coordinates of paddock. Must be a GeoJSON Polygon (see example). * @apiParam {String} [created] Timestamp of paddock creation time. * * * @apiParamExample {json} Request-Example: * { * "name": "Demo Paddock" * "farm_id": 1 * "loc": { * "coordinates":[ * [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] * ] * } * "created": "2015-04-19" * } * * @apiSuccessExample Success-Response * HTTP/1.1 200 OK * { * "paddock": * { * "_id": "primary_key_string", * "name": "Demo Paddock", * "farm_id": 1, * "created": "2015-04-19", * "updated": "2015-04-19", * "loc" { * "type": "Polygon", * "coordinates": [ * [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] * ] * } * } * } * * @apiError IncompleteRequest Request body is missing required fields. * @apiErrorExample IncompleteRequest * HTTP/1.1 422 Unprocessable Entity * { * error: "Missing field response message" * } */ router.post('/', function(req, res) { var paddockDetails = req.body; var access = {}; access.requiredPermissions = [permissions.kEditFarmPermissions]; access.farm = {id: paddockDetails.farm_id}; responder.authAndRespond(req, res, access, function() { return { paddock: PaddockController.createPaddock(paddockDetails) } }); }); /** * @api {put} /spatial/paddocks/:id Update a Paddock * @apiName PutPaddocks * @apiGroup Paddocks * * @apiParam {string} id Primary key of updated paddock. * @apiParam (paddock) {String} [name] Name of updated paddock. * @apiParam (paddock) {Object} [loc] Corners of updated paddock. Must be a GeoJSON Polygon (see example). * @apiParam (paddock) {Object} [updated] Timestamp of update time. * * @apiSuccessExample Success-Response * HTTP/1.1 200 OK * { * "paddock": * { * "_id": "primary_key_string", * "name": "Demo Paddock", * "farm_id": 1, * "created": "2015-04-19" * "loc" * { * "type": "Polygon", * "coordinates": * [ * [ * [0, 0], [0, 1], [1, 1], [1, 0], [0, 0] * ] * ] * } * } * } * * @apiError PaddockNotFound could find paddock with object_id parameter. * @apiErrorExample PaddockNotFound * HTTP/1.1 422 Unprocessable Entity * { * error: "Paddock Not Found" * } */ router.put('/:object_id', function(req, res) { var id = req.params.object_id; var paddockDetails = req.body; // get paddock first for purpose of checking farm permissions return PaddockController.getOnePaddock(id) .then(function(paddock) { var access = {}; access.requiredPermissions = [permissions.kEditFarmPermissions]; access.farm = {id: paddockDetails.farm_id}; responder.authAndRespond(req, res, access, function() { return { paddock: PaddockController.updatePaddock(id, paddockDetails) } }); }) .catch(function(err) { return res.status(422).send({error: err.message}); }); }); /** * Delete paddock */ /** * @api {delete} /spatial/paddocks/:id Delete a Paddock * @apiName DeletePaddocks * @apiGroup Paddocks * * @apiParam {string} id Primary key of paddock to delete. * * @apiError PaddockNotFound could find paddock with object_id parameter. * @apiErrorExample PaddockNotFound * HTTP/1.1 422 Unprocessable Entity * { * error: "Paddock Not Found" * } * * @apiError RemovePastureMeasurementError couldn't remove pasture measurements that belong to paddock. * @apiErrorExample RemovePastureMeasurementError * HTTP/1.1 422 Unprocessable Entity * { * error: "Couldn't remove pasture measurements, operation aborted" * } * * @apiSuccessExample * HTTP/1.1 200 OK * { * "result": 1 * } */ router.delete('/:object_id', function(req, res) { var id = req.params.object_id; // get paddock first for purpose of checking farm permissions return PaddockController.getOnePaddock(id) .then(function(paddock) { var access = {}; access.requiredPermissions = [permissions.kEditFarmPermissions]; access.farm = {id: paddock.farm_id}; responder.authAndRespond(req, res, access, function() { return { result: PaddockController.deletePaddock(id) } }); }) .catch(function(err) { return res.status(422).send({error: err.message}); }); /* return PaddockController.deletePaddock(id).then(function() { return res.send({message: 'Paddock Deleted'}); }) .catch(function(err){ return res.status(422).send({error: err.message}); }); */ }); /** * Get paddocks. */ /** * @api {get} /spatial/paddocks/ Get Paddocks * @apiName GetPaddocks * @apiGroup Paddocks * * @apiParam {Number} [include] List of objects to include in response (farm). * @apiParam {Number} [farm_id] Id of farm that contains requested paddocks. * @apiParam {Number} [limit] Maximum number of results that the query should return. The AgBase API cannot return more than 1000 results. * @apiParam {Number} [offset] The offset from the start of the query result. * @apiParam {String} [id] Id of paddock to return. * * @apiErrorExample Error-Response * HTTP/1.1 422 Unprocessable Entity * { * "error": "error message" * } * * @apiSuccessExample * HTTP/1.1 200 OK * { * "paddocks": * [ * { * "_id": "primary_key_string", * "name": "Demo Paddock", * "farm_id": 1, * "created": "2015-04-19" * "loc": * { * "type": "Polygon", * "coordinates": * [ * [ * [0, 0], [0, 1], [1, 1], [1, 0], [0, 0] * ] * ] * } * } * ] * } */ router.get('/', function(req, res) { var params = req.query; var access = {}; access.requiredPermissions = [permissions.kViewFarmPermissions]; if(params.id) { responder.authAndRespond(req, res, access, function() { return { paddock: PaddockController.getOnePaddock(params.id) } }); } else { var farms; var limit; var offset; var includeFarms = params.include === "farm"; if(params.farm_id) { farms = params.farm_id.split(','); access.farm = {id: farms}; } if(params.limit) { limit = params.limit; } if(params.offset) { offset = params.offset; } responder.authAndRespond(req, res, access, function() { return { paddocks: PaddockController.getPaddocks(includeFarms, farms, limit, offset) } }); } }); /** * countPaddocks(farms) * @api {get} /spatial/paddocks/count/ Get a count of Paddocks * @apiName CountPaddocks * @apiGroup Paddocks * * @apiParam {Number} [farm_id] Return paddocks that belong to farms defined by farm_id. * * @apiSuccessExample Success-Response * { * "count": <number of paddocks> * } */ router.get('/count/', function(req, res) { var params = req.query; var farms; if(params.farm_id) { farms = params.farm_id.split(','); } return PaddockController.countPaddocks(farms) .then(function(count) { return res.send({count: count}); }) .catch(function(err) { return res.status(422).send({error: err.message}); }); }); module.exports = router;
elec-otago/agbase
server/routes/api-authenticated/spatial/paddocks.js
JavaScript
mpl-2.0
9,912
import React from 'react'; import cn from 'classnames'; import keyboardJS from 'keyboardjs'; import ReactTooltip from 'react-tooltip'; import sendToAddon from '../client-lib/send-to-addon'; export default class PrevButton extends React.Component { constructor(props) { super(props); this.state = {historyIndex: 0}; } componentDidMount() { // previous track keyboardJS.bind('<', () => this.prevTrack()); } prevTrack() { let index; // if clicked more than once within // 5 seconds increment the index so // the user can get to further back // in history. Resets when timeout wears out. if (this.searchingHistory) { if (this.props.history.length > this.state.historyIndex + 1) { this.setState({historyIndex: this.state.historyIndex + 1}); } index = this.state.historyIndex; } else { index = 0; this.searchingHistory = true; setTimeout(() => { this.searchingHistory = false; this.setState({historyIndex: 0}); }, 5000); } sendToAddon({ action: 'track-added-from-history', index }); } render() { return ( <div className={cn('prev-wrapper', {hidden: (!this.props.hovered && !this.props.minimized) || this.props.confirm || !this.props.history.length})}> <a onClick={this.prevTrack.bind(this)} className='prev' data-tip data-for='prev' /> <ReactTooltip id='prev' effect='solid' place='right'>{this.props.strings.ttPrev}</ReactTooltip> </div> ); } }
meandavejustice/min-vid
frontend/components/prev-button.js
JavaScript
mpl-2.0
1,552
#!/usr/bin/env node process.chdir(__dirname) var crypto = require('crypto'), fs = require('fs'), config = require('../config.js') var newPasswordSha1 = crypto.createHash('sha1').update('').digest('hex') var content = '// auto-generated\n' + 'exports.port = ' + config.port + '\n' + 'exports.host = ' + JSON.stringify(config.host) + '\n' + 'exports.keySha1 = ' + JSON.stringify(newPasswordSha1) + '\n' fs.writeFileSync('../config.js', content) console.log('New key is an empty string')
aimnadze/audio-player-server
scripts/disable-key.js
JavaScript
agpl-3.0
515
MetaclicUtils.Templates = {}; MetaclicUtils.Templates.datasets = [ ' {{#ifCond sort "!=" false}}', ' <div class="result-sort"><label>Trier par</label>', ' <select name="sort" class="form-control">', ' {{#each sortTypes}}', ' {{#ifCond id "==" ../sort}}', ' <option value="{{id}}" selected>{{name}}</option>', ' {{else}}', ' <option value="{{id}}">{{name}}</option>', ' {{/ifCond}}', ' {{/each}}', ' </select>', ' <a href="#" class="sortdirection">', ' {{#ifCond sortDesc "==" true}}', ' <i class="fa fa-sort-alpha-desc"></i>', ' {{else}}', ' <i class="fa fa-sort-alpha-asc"></i>', ' {{/ifCond}}', ' </a>', '</div>', '{{/ifCond}}', '<div class="result-count">{{ total }} résultat(s)</div>', '<div class="metaclic-row">', '{{#ifCond facets "!=" undefined}}', '<div class="Metaclic-results">', '{{else}}', '<div class="Metaclic-results Metaclic-results-full">', '{{/ifCond}}', ' <ul class="search-results">', ' {{#each data}}', ' <li class="search-result dataset-result" data-dataset="{{id}}">', ' <a href="{{ page }}" title="{{ organization.name }}" data-dataset="{{id}}">', '', ' <div class="result-logo">', ' <img alt="" src="{{organization.logo}}" >', ' </div>', ' {{#if organization.public_service }}', ' <img alt="certified"', ' class="certified" rel="popover"', ' data-title="{{_ \'certified_public_service\'}}"', ' data-content="{{_ \'the_identity_of_this_public_service_public_is_certified_by_etalab\'}}"', ' data-container="body" data-trigger="hover"/>', ' {{/if}}', ' <div class="result-body">', ' <h4 class="result-title">{{title}}</h4>', '', ' <div class="result-description">', ' {{mdshort description 128}}</div></div>', '', ' </a><ul class="result-infos">', '', ' {{#if temporal_coverage }}', ' <li>', ' <span rel="tooltip"', ' data-placement="top" data-container="body"', ' title="{{_ \'temporal_coverage\'}}">', ' <span class="fa fa-calendar fa-fw"></span>', ' {{dt temporal_coverage.start format=\'L\' }} {{_ \'to\'}} {{dt temporal_coverage.end format=\'L\' }}', ' </span>', ' </li>', ' {{/if}}', '', ' {{#if frequency }}', ' <li>', ' <span rel="tooltip"', ' data-placement="top" data-container="body"', ' title="{{_ \'Update frequency\' }}">', ' <span class="fa fa-clock-o fa-fw"></span>', ' {{_ frequency }}', ' </span>', ' </li>', ' {{/if}}', '', ' {{#if spatial.territories }}', ' <li>', ' <span rel="tooltip"', ' data-placement="top" data-container="body"', ' title="{{_ \'Spatial coverage\'}}">', ' <span class="fa fa-map-marker fa-fw"></span>', ' {{_ spatial.territories.0.name }}', ' </span>', ' </li>', ' {{/if}}', '', ' {{#if spatial.granularity }}', ' <li>', ' <span rel="tooltip"', ' data-placement="top" data-container="body"', ' title="{{_ \'Spatial granularity\'}}">', ' <span class="fa fa-bullseye fa-fw"></span>', ' {{_ spatial.granularity }}', ' </span>', ' </li>', ' {{/if}}', '', ' <li>', ' <span rel="tooltip"', ' data-placement="top" data-container="body"', ' title="{{_ \'Reuses\'}}">', ' <span class="fa fa-retweet fa-fw"></span>', ' {{default metrics.reuses 0 }}', ' </span>', ' </li>', '', ' <li>', ' <span rel="tooltip"', ' data-placement="top" data-container="body"', ' title="{{_ \'Followers\'}}">', ' <span class="fa fa-star fa-fw"></span>', ' {{default metrics.followers 0 }}', ' </span>', ' </li>', '', ' </ul>', ' </li>', ' {{/each}}', ' </ul>', '</div>', '{{#ifCond facets "!=" undefined}}', '<div class="Metaclic-facets">', '{{#ifCond facets.organization "!=" undefined}}', '{{#if facets.organization}}', '<div class="facet-panel">', ' <div class="facet-panel-heading"><i class="fa fa-tags fa-fw"></i> Organisme</div>', ' <ul data-limitlist=5>', ' {{#each facets.organization}}', ' <a href="#" data-addID="{{this.[0]._id.$oid}}">', ' <span>{{this.[1]}}</span>', ' {{this.[0].name}}', ' </a>', ' {{/each}}', ' </ul>', '</div>', '{{/if}}', '{{/ifCond}}', '{{#ifCond facets.tag "!=" undefined}}', '{{#if facets.tag}}', '<div class="facet-panel">', ' <div class="facet-panel-heading"><i class="fa fa-tags fa-fw"></i> Tags</div>', ' <ul data-limitlist=5>', ' {{#each facets.tag}}', ' <a href="#" data-addTag="{{this.[0]}}">', ' <span>{{this.[1]}}</span>', ' {{this.[0]}}', ' </a>', ' {{/each}}', ' </ul>', '</div>', '{{/if}}', '{{/ifCond}}', '{{#ifCond facets.license "!=" undefined}}', '{{#if facets.license}}', '<div class="facet-panel">', ' <div class="facet-panel-heading"><i class="fa fa-copyright fa-fw"></i> Licences</div>', ' <ul data-limitlist=5>', ' {{#each facets.license}}', ' <a href="#" data-addLicense="{{this.[0]._id}}">', ' <span>{{this.[1]}}</span>', ' {{this.[0].title}}', ' </a>', ' {{/each}}', ' </ul>', '</div>', '{{/if}}', '{{/ifCond}}', //couverture temporelle '{{#ifCond facets.geozone "!=" undefined}}', '{{#if facets.geozone}}', '<div class="facet-panel">', ' <div class="facet-panel-heading"><i class="fa fa-map-marker fa-fw"></i> Couverture spatiale</div>', ' <ul data-limitlist=5>', ' {{#each facets.geozone}}', ' <a class="geozone-to-load" href="#" data-addGeozone="{{this.[0]._id}}">', ' <span>{{this.[1]}}</span>', ' {{this.[0]._id}} ({{this.[0].code}})', ' </a>', ' {{/each}}', ' </ul>', '</div>', '{{/if}}', '{{/ifCond}}', '{{#ifCond facets.granularity "!=" undefined}}', '{{#if facets.granularity}}', '<div class="facet-panel">', ' <div class="facet-panel-heading"><i class="fa fa-bullseye fa-fw"></i> Granularité territoriale</div>', ' <ul data-limitlist=5>', ' {{#each facets.granularity}}', ' <a href="#" data-addGranularity="{{this.[0]}}">', ' <span>{{this.[1]}}</span>', ' {{_ this.[0]}}', ' </a>', ' {{/each}}', ' </ul>', '</div>', '{{/if}}', '{{/ifCond}}', '{{#ifCond facets.format "!=" undefined}}', '{{#if facets.format}}', '<div class="facet-panel">', ' <div class="facet-panel-heading"><i class="fa fa-file fa-fw"></i> Formats</div>', ' <ul data-limitlist=5>', ' {{#each facets.format}}', ' <a href="#" data-addFormat="{{this.[0]}}">', ' <span>{{this.[1]}}</span>', ' {{_ this.[0]}}', ' </a>', ' {{/each}}', ' </ul>', '</div>', '{{/if}}', '{{/ifCond}}', // reuse '</div>', '{{/ifCond}}', '</div>', ' <div class="metaclic-pagination">', ' {{{ paginate page total page_size }}}', ' </div>', ]; MetaclicUtils.Templates.dataset = [ '<div class="dataset" data-dataset="{{id}}">', '', ' <div class=\'dataset-info\'>', ' <blockquote>{{md description }}</blockquote>', ' {{#if extras.remote_url}}', ' <a class="site_link" href="{{extras.remote_url}}" target=_blank>', ' Voir le site original', ' </a>', ' {{/if}}', ' <p class="published_on">', ' {{_ \'published_on\' }} {{dt created_at}}', ' {{_ \'and_modified_on\'}} {{dt last_modified}}', ' {{_ \'by\'}} <a title="{{organization.name}}" href="{{organization.page}}">{{organization.name}}</a>', ' </p>', ' </div>', '', ' <div class="resources-list">', ' <h3>{{_ \'Resources\'}}</h3>', ' {{#each resources}}', ' <div data-checkurl="/api/1/datasets/checkurl/" itemtype="http://schema.org/DataDownload" itemscope="itemscope" id="resource-{{id}}">', '', ' <a href="{{url}}" data-size="{{filesize}}" data-format="{{uppercase format}}" data-map_title="{{../title}}" data-title="{{title}}" data-id="{{id}}" itemprop="url" target=_blank>', ' <h4>', ' <span data-format="{{uppercase format}}">', ' {{uppercase format}}', ' </span>', ' {{title}}', ' <p>', ' Dernière modification le {{dt last_modified}}', ' </p>', ' </h4>', ' </a>', '', ' </div>', ' {{/each}}', ' </div>', '', ' <div class="meta">', '', ' <div class="producer">', ' <h3>{{_ \'Producer\'}}</h3>', ' <a title="{{organization.name}}" href="{{organization.page}}">', ' <img class="organization-logo producer" alt="{{organization.name}}" src="{{fulllogo organization.logo}}"><br>', ' <span class="name">', ' {{organization.name}}', ' </span>', ' </a>', ' </div>', '', '', ' <div class="info">', ' <h3>{{_ \'Informations\'}}</h3>', ' <ul>', ' <li title="{{_ \'License\'}}" rel="tooltip">', ' <i class="fa fa-copyright"></i>', ' <!--a href="http://opendatacommons.org/licenses/odbl/summary/"-->', ' {{_ license}}', ' <!--/a-->', ' </li>', ' <li title="{{_ \'Frequency\'}}" rel="tooltip">', ' <span class="fa fa-clock-o"></span>', ' {{_ frequency}}', ' </li>', ' <li title="{{_ \'Spatial granularity\'}}" rel="tooltip">', ' <span class="fa fa-bullseye"></span>', ' {{_ spatial.granularity}}', ' </li>', ' </ul>', ' <ul class="spatial_zones">', ' {{#each spatial.zones}}', ' <li data-zone="{{.}}">{{.}}</li>', ' {{/each}}', ' </ul>', ' <ul class="tags">', ' {{#each tags}}', ' <li><a title="{{.}}" href="https://www.data.gouv.fr/fr/search/?tag={{.}}">', ' {{.}}', ' </a>', ' </li>', ' {{/each}}', ' </ul>', ' <div class="Metaclic-clear">', ' </div>', ' </div>', ' </div>', '', '', ' </div>' ]; MetaclicUtils.Templates.organizationAdd = [ '{{#if generator}}', '<div class="organization_add">', '<h1>Générateur de code metaClic</h1></br>', '<i>Ajoutez des organismes en saisissant leur nom et en les sélectionnant dans la liste</i></br>', ' <input type="text" name="research" list="metaclic-autocomplete-list" class="form-control" placeholder="Organisation">', ' <datalist id="metaclic-autocomplete-list">', ' </datalist>', '</div>', ' <ul class="tags">', ' {{#if orgs}}', ' {{#each orgs}}', ' {{#if name}}', ' <li><a title="Fermer" href="#" class="facet-remove facet-organization" data-removeorganizationtoorigin="organization" data-id="{{id}}"> {{name}} ×</a></li>', ' {{/if}}', ' {{/each}}', ' {{/if}}', ' </ul>', ' <div class="Metaclic-clear"></div>', '{{/if}}', ]; MetaclicUtils.Templates.datasetsForm = [ '<div class="datasetsForm">', ' <form action="" method="get">', ' <input type="hidden" name="option" value="com_metaclic"></input>', ' <input type="hidden" name="view" value="metaclic"></input>', ' <div><label>&nbsp;</label><input type="text" name="q" value="{{q}}" placeholder="Rechercher des données" class="form-control"></input></div>', ' {{#ifCount orgs ">" 1 }}', ' <div>', ' {{else}}', ' <div class="hidden">', ' {{/ifCount}}', ' </div>', ' </form>', ' <div class="selected_facets">', '<ul class="tags">', ' {{#if organization}}', ' {{#if organization_name}}', ' {{#ifNotall organization "|"}}', ' <li><a title="{{_ \'fermer\'}}" href="#" class="facet-remove facet-organization" data-removeOrganization="organization"> {{organization_name}} &times;</a></li>', ' {{/ifNotall}}', ' {{/if}}', ' {{/if}}', ' {{#if tags}}', ' {{#each tags}}', ' <li><a title="{{_ \'fermer\'}}" href="#" class="facet-remove facet-tag" data-removeTag="{{.}}"><i class="fa fa-tags fa-fw"></i> {{.}} &times;</a></li>', ' {{/each}}', ' {{/if}}', ' {{#if license}}', ' <li><a title="{{_ \'fermer\'}}" href="#" class="facet-remove facet-license" data-removeParam="license"><i class="fa fa-copyright fa-fw"></i> {{license}} &times;</a></li>', ' {{/if}}', ' {{#if geozone}}', ' <li><a title="{{_ \'fermer\'}}" href="#" class="facet-remove facet-geozone" data-removeParam="geozone"><i class="fa fa-map-marker fa-fw"></i> {{geozone}} &times;</a></li>', ' {{/if}}', ' {{#if granularity}}', ' <li><a title="{{_ \'fermer\'}}" href="#" class="facet-remove facet-granularity" data-removeParam="granularity"><i class="fa fa-bullseye fa-fw"></i> {{granularity}} &times;</a></li>', ' {{/if}}', ' {{#if format}}', ' <li><a title="{{_ \'fermer\'}}" href="#" class="facet-remove facet-format" data-removeParam="format"><i class="fa fa-file fa-fw"></i> {{format}} &times;</a></li>', ' {{/if}}', ' </div>', ' </ul>', '</div>', ' <br>' ]; MetaclicUtils.Templates.lastdatasets = [ '<div class="Metaclic-lastdatasets">', ' {{#each data}}', ' <div class="card dataset-card">', ' <a class="card-logo" href="{{ organization.uri }}" target="datagouv">', ' <img alt="{{ organization.name }}" src="{{ organization.logo }}" width="70" height="70">', ' </a>', ' <div class="card-body">', ' <h4>', ' <a href="{{ url }}" title="{{title}}">', ' {{title}}', ' </a>', ' </h4>', ' </div>', ' <footer>', ' <ul>', ' <li>', ' <a rel="tooltip" data-placement="top" data-container="body" title="" data-original-title="Réutilisations">', ' <span class="fa fa-retweet fa-fw"></span>', ' {{default metrics.reuses 0 }}', ' </a>', ' </li>', ' <li>', ' <a rel="tooltip" data-placement="top" data-container="body" title="" data-original-title="Favoris">', ' <span class="fa fa-star fa-fw"></span>', ' {{default metrics.followers 0 }}', ' </a>', ' </li>', ' </ul>', ' </footer>', ' <a href="{{ url }}" title="{{title}}">', ' {{trimString description}}', ' </a>', ' <footer>', ' <ul>', ' {{#if temporal_coverage }}', ' <li>', ' <a rel="tooltip"', ' data-placement="top" data-container="body"', ' title="{{_ \'Temporal coverage\' }}">', ' <span class="fa fa-calendar fa-fw"></span>', ' {{dt temporal_coverage.start format=\'L\' }} {{_ \'to\'}} {{dt temporal_coverage.end format=\'L\' }}', ' </a>', ' </li>', ' {{/if}}', '', ' {{#if spatial.granularity }}', ' <li>', ' <a rel="tooltip"', ' data-placement="top" data-container="body"', ' title="{{_ \'Territorial coverage granularity\' }}">', ' <span class="fa fa-bullseye fa-fw"></span>', ' {{_ spatial.granularity }}', ' </a>', ' </li>', ' {{/if}}', '', ' {{#if frequency }}', ' <li>', ' <a rel="tooltip"', ' data-placement="top" data-container="body"', ' title="{{_ \'Frequency\' }}">', ' <span class="fa fa-clock-o fa-fw"></span>', ' {{_ frequency }}', ' </a>', ' </li>', ' {{/if}}', ' </ul>', ' </footer>', ' </div>', ' {{/each}}', ' </div>' ]; MetaclicUtils.Templates.shareCode = [ '{{#if generator}}', '{{#if organizationList}}', '<div class="Metaclic-shareCode">', '<div>', ' Code à intégrer dans votre site Internet :', ' <pre>', '&lt;script&gt;window.jQuery || document.write("&lt;script src=\'https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js\'&gt;&lt;\\\/script&gt;")&lt;/script&gt;', '', '&lt;!-- chargement feuille de style font-awesome --&gt;', '&lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css"&gt;', '', '&lt;script src="https://unpkg.com/metaclic/dist/metaclic.js"&gt;&lt;/script&gt;', '&lt;div class="Metaclic-data"', ' data-q="{{q}}"', ' data-organizations="{{organizationList}}"', ' data-background_layers="{{background_layers}}"', ' data-facets="all"', ' data-page_size="{{page_size}}"', '&gt&lt;/div&gt', ' </pre>', " <p>Plus de paramétrage disponible dans la documentation: <a href='https://github.com/datakode/metaclic/wiki/Personnalisation' target='_blank'>https://github.com/datakode/metaclic/wiki/Personnalisation</a></p>", " <p><h1>Prévisualisation : </h1></p>", '</div>', '</div>', '{{/if}}', '{{/if}}', ]; MetaclicUtils.Templates.shareLinkMap = [ '<div class="MetaclicMap-shareLink">', '<div class="linkDiv"><a href="#">intégrez cette carte à votre site&nbsp;<i class="fa fa-share-alt"></i></a></div>', '<div class="hidden">', ' <h4>Vous pouvez intégrer cet carte sur votre site</h4>', ' <p>Pour ceci collez le code suivant dans le code HTML de votre page</p>', ' <pre>', '&lt;script&gt;window.jQuery || document.write("&lt;script src=\'https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js\'&gt;&lt;\\\/script&gt;")&lt;/script&gt;', '', '&lt;script src="{{baseUrl}}metaclic.js"&gt;&lt;/script&gt;', '&lt;div class="Metaclic-map"', " data-resources='{{jsonencode resources}}'", //" data-leaflet_map_options='{{jsonencode leaflet_map_options}}'", " data-title='{{title}}'", '&gt&lt;/div&gt', ' </pre>', " <p>vous pouvez trouver plus d'info sur cet outil et son paramétrage à cette adresse: <a href='https://github.com/datakode/metaclic' target='_blank'>https://github.com/datakode/metaclic</a></p>", '</div>', '</div>', ]; MetaclicUtils.Templates.li_resource = [ '<li data-id="{{id}}">', '<a href="{{metadata_url}}">{{title}}</a>', '<i class="fa fa-copyright"></i> {{_ license}}', '<p class="organization" data-id="{{organization.id}}" data-slug="{{organization.slug}}">', '<img alt="{{ organization.name }}" src="{{ organization.logo }}">', '<span>{{organization.name}}</span>', '</p>', '</li>' ];
datakode/metaclic
js/templates.js
JavaScript
agpl-3.0
22,464
"use strict"; var types = require('./types'); var Tree = require('./tree'); var Rule = require('./rule'); var Principle = require('./principle'); var Lexicon = require('./lexicon'); var Nothing = types.Nothing; var eq = types.eq; var normalize = types.normalize; function Parser ( grammar ) { return { borjes: 'parser', rules: grammar.rules, principles: grammar.principles, lexicon: grammar.lexicon, table: [], n: 0 } } function all_matches ( p, a_x, a_y, b_x, b_y ) { var a = p.table[a_x][a_y]; var b = p.table[b_x][b_y]; var matches = []; for (var i = 0; i<a.length; i++) { for (var j = 0; j<b.length; j++) { matches.push([a[i], b[j]]); } } return matches; } function all_legs ( p, from, to, n ) { if (n!=2) { throw "Non-binary rules not supported"; } var legs = []; for (var i = to-1; i >= 0; i--) { legs = legs.concat(all_matches(p, from, i, from+i+1, to-(i+1))); } return legs; }; function apply_principles ( p, ms, success, i ) { i = i || 0; if (i>=p.principles.length) { for (var j=0; j<ms.length; j++) { success(ms[j]); } } else { var prin = p.principles[i]; for (var j=0; j<ms.length; j++) { var r = Principle.apply(prin, ms[j]); apply_principles(p, r, success, i+1); } } } function exhaust ( p, from, to ) { p.table[from][to] = []; var cell = p.table[from][to]; for (var i = 0; i<p.rules.length; i++) { var rule = p.rules[i]; var legs = all_legs(p, from, to, rule.arity); for (var j = 0; j<legs.length; j++) { var mothers = Rule.apply(rule, legs[j].map(function(t) { return t.node; })); apply_principles(p, mothers, function(x) { cell.push(Tree(normalize(x), legs[j])); }); } } }; function input ( p, word ) { var w = Lexicon.get(p.lexicon, word); if (w === undefined) { w = Nothing; } var wordt = Tree(word); if (!w.length) { p.table[p.n] = [[ Tree(w, wordt) ]]; } else { p.table[p.n] = []; p.table[p.n][0] = w.map(function(x) { return Tree(x, wordt); }); } for (var i = p.n-1; i>=0; i--) { exhaust(p, i, p.n-i); } p.n++; }; function parse ( p, sentence ) { if (p.borjes !== 'parser') { p = Parser(p); } else { reset(p); } for (var i = 0; i<sentence.length; i++) { input(p, sentence[i]); } var top = p.table[0][p.n-1]; if (top.length === 0) { return Nothing; } else { return top; } }; function reset ( p ) { p.table = []; p.n = 0; }; Parser.reset = reset; Parser.input = input; Parser.parse = parse; module.exports = Parser;
agarsev/borjes
src/parser.js
JavaScript
agpl-3.0
2,855