code
stringlengths
2
1.05M
// jshint esversion: 6, globalstrict: true, strict: true 'use strict'; var FW = require('../index'); //pipe:0 = stdin, pipe:1 = stdout, pipe:2 = stderr, all pipes can be used to stream data from ffmpeg, -loglevel should be set to "quiet" to utilize stderr var params = [ '-loglevel', 'quiet', '-max_delay', '0', '-f', 'rtsp', '-rtsp_transport', 'udp', '-stimeout', '10000000', '-i', 'rtsp://50.73.56.89:554/axis-media/media.amp', /*stdin*/ '-c:v', 'copy', '-f', 'mpegts', 'pipe:0', /*stdout*/ '-c:v', 'copy', '-f', 'mp4', '-movflags', '+empty_moov', 'pipe:1', /*stderr*/ '-c:v', 'copy', '-f', 'flv', 'pipe:2' ]; var options = { name : 'video1',//name of video, helps to identify ffmpeg process when logging data to console retry : 10,//how many times watchdog should attempt to restart ffmpeg process that has exited wait : 2,//how many seconds should the watchdog wait to attempt to restart ffmpeg reset : 20//how many seconds should ffmpeg be running to be considered good, used for resetting watchdog attempts }; //create new instance and attach listeners and call .init() to start var video1 = new FW(params, options) .on(FW.ERROR, (type, code, signal, message, target) => handleError(type, code, signal, message, target)) .on(FW.STDOUT_DATA, function (data) { console.log(video1.getName(), FW.STDOUT_DATA, data.length); }) .on(FW.STDERR_DATA, function (data) { console.log(video1.getName(), FW.STDERR_DATA, data.length); }) .on(FW.STDIN_DATA, function (data) { console.log(video1.getName(), FW.STDIN_DATA, data.length); }) .init(); //check which type of error we have, ffmpegExit or watchdogFail function handleError(type, code, signal, message, target) { console.log(`Error handled for ${target.getName()}`); console.log(`Command: ffmpeg ${target.getParams()}`); console.log('type:', type, '\ncode:', code, '\nsignal:', signal, '\nmessage:', message); switch (type) { case FW.FFMPEG_EXIT: //ffmpeg exited, check code or signal or message break; case FW.WATCHDOG_FAIL: //watchDog is reporting that all attempts at respawning ffmpeg have failed break; } }
// Karma configuration // Generated on Mon Mar 06 2017 11:02:37 GMT-0500 (EST) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: './', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'app/**/*.test.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: [], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity }) }
/** * @fileoverview Vitals model, will aggregate and compute the vital information. */ var _ = require('underscore'); var kickq = require('kickq'); var log = kickq.logg.getLogger('kickq-vitals.model.Vitals'); var VitalsItem = require('./vitals.item'); /** * Will aggregate and compute the vital information. * * @constructor */ var Vitals = module.exports = function() { log.fine('Ctor() :: Init'); /** * Contains arrays of the kickq metric events * @type {Object} * @private */ this._container = { create: [], queued: [], success: [], fail: [] }; }; kickq.util.addSingletonGetter(Vitals); /** * Clear counters * */ Vitals.prototype.clear = function() { this._container.create = []; this._container.queued = []; this._container.success = []; this._container.fail = []; }; /** * A kickq metrics event occured, store it. * * @param {string} eventType metrics event type. * @param {kickq.JobItem} publicJobItem the public job item */ Vitals.prototype.feed = function(eventType, publicJobItem) { log.finest('feed() :: Init. eventType, jobId: ', eventType, publicJobItem.id); if (!Array.isArray(this._container[eventType])) { return; } this._container[eventType].push(publicJobItem); }; /** * Marks an interval and forces computation of vitals. * * Resets the counters * * @param {number} startTime JS timestamp, the starting time of this period. * @param {number} period The interval period. * @return {kickq-vitals.model.VitalItem} A vital item. */ Vitals.prototype.interval = function(startTime, period) { log.fine('interval() :: Init.'); var vitalsItem = new VitalsItem(period); var createLen = this._container.create.length; var successLen = this._container.success.length; var failLen = this._container.fail.length; var successProcessTimes = this.successProcessTimes(startTime); var failProcess = this.failProcess(startTime); // calculate total processing time function sum(a, b){return a+b;} var totalProcessItems = successProcessTimes.processTimes.length; var totalProcessTime = 0; if (totalProcessItems) { totalProcessTime = successProcessTimes.processTimes.reduce(sum); } vitalsItem.jobStats.created = createLen; vitalsItem.jobStats.processed = successLen + failLen; vitalsItem.jobStats.success = successLen; vitalsItem.jobStats.failed = failProcess.processFails; vitalsItem.jobStats.ghosts = failProcess.processGhosts; vitalsItem.jobStats.avgProcessingTime = Math.floor( (totalProcessTime / totalProcessItems) * 100) / 100; vitalsItem.jobQueues = this.jobQueues(successProcessTimes, failProcess); this.clear(); return vitalsItem; }; /** * Returns the processing times of successful jobs. * * @param {number} startTime JS timestamp, the starting time of this period. * @return {Object.<{processTimes:Array, queueProcessTimes:Object.<Array>}>} * An object containing the keys "processTimes" an array of processing * times, and queueProcessTimes (Object of arrays). */ Vitals.prototype.successProcessTimes = function(startTime) { var processTimes = []; var queueProcessTimes = {}; // collect processing times var successJobIds = []; this._container.success.forEach(function(publicJobItem) { // only handle unique job ids if (0 <= successJobIds.indexOf(publicJobItem.id)) { return; } successJobIds.push(publicJobItem.id); publicJobItem.runs.forEach(function(processItem) { // only care about the period if ( startTime > processItem.startTime ){ return; } processTimes.push(processItem.processTime); queueProcessTimes[publicJobItem.name] = queueProcessTimes[publicJobItem.name] || []; queueProcessTimes[publicJobItem.name].push(processItem.processTime); }, this); }, this); return { processTimes: processTimes, queueProcessTimes: queueProcessTimes }; }; /** * Returns the processing times of successful jobs. * * @param {number} startTime JS timestamp, the starting time of this period. * @return {Object} * An object containing the keys: * "processTimes": {Array} of process times for all failed jobs * (ghosts excluded). * "queueProcessTimes": {Object.<Array>} An object with the job names * as keys and array of processing time as values. * "processGhosts": {number} Count of ghosts. * "processFails": {number} Count of fails. * "queueProcessGhosts": {Object.<number>} per queue count of ghosts. * "queueProcessFails": {Object.<number>} per queue count of fails. */ Vitals.prototype.failProcess = function(startTime) { var processTimes = []; var queueProcessTimes = {}; var processGhosts = 0; var processFails = 0; var queueProcessGhosts = {}; var queueProcessFails = {}; // collect processing times and failure reasons var failJobIds = []; this._container.fail.forEach(function(publicJobItem) { // only handle unique job ids if (0 <= failJobIds.indexOf(publicJobItem.id)) { return; } failJobIds.push(publicJobItem.id); publicJobItem.runs.forEach(function(processItem) { // only care about the period if ( startTime > processItem.startTime ){ return; } // check if ghost if (kickq.states.Process.GHOST === processItem.state) { processGhosts++; queueProcessGhosts[publicJobItem.name] = queueProcessGhosts[publicJobItem.name] || 0; queueProcessGhosts[publicJobItem.name]++; // next loop return; } // only care for failed items if (kickq.states.Process.FAIL !== processItem.state) { return; } processTimes.push(processItem.processTime); queueProcessTimes[publicJobItem.name] = queueProcessTimes[publicJobItem.name] || []; queueProcessTimes[publicJobItem.name].push(processItem.processTime); processFails++; queueProcessFails[publicJobItem.name] = queueProcessFails[publicJobItem.name] || 0; queueProcessFails[publicJobItem.name]++; }, this); }, this); return { processTimes: processTimes, queueProcessTimes: queueProcessTimes, processGhosts: processGhosts, processFails: processFails, queueProcessGhosts: queueProcessGhosts, queueProcessFails: queueProcessFails }; }; /** * Calculate stats per queue (job name). * * @param {Object} successProcessTimes As see on "successProcessTimes" method. * @param {Object} failProcess As seen on "failProcess" method. * @return {Object.<kickq-vitals.model.VitalItem.QueueStats>} The complete * struct for the "jobQueues" vitals item key. */ Vitals.prototype.jobQueues = function(successProcessTimes, failProcess) { var jobQueues = {}; function sum(a, b){return a+b;} this._container.create.forEach(function(publicJobItem) { jobQueues[publicJobItem.name] = jobQueues[publicJobItem.name] || new VitalsItem.QueueStats(); jobQueues[publicJobItem.name].created++; }, this); _.forEach(successProcessTimes.queueProcessTimes, function(processTimes, queue) { jobQueues[queue] = jobQueues[queue] || new VitalsItem.QueueStats(); var len = processTimes.length; jobQueues[queue].processed += len; jobQueues[queue].success += len; var totalProcessItems = processTimes.length; var totalProcessTime = 0; if (totalProcessItems) { totalProcessTime = processTimes.reduce(sum); } jobQueues[queue].avgProcessingTime = Math.floor( (totalProcessTime / totalProcessItems) * 100) / 100; }, this); _.forEach(failProcess.queueProcessGhosts, function(processCount, queue) { jobQueues[queue] = jobQueues[queue] || new VitalsItem.QueueStats(); jobQueues[queue].ghosts += processCount; jobQueues[queue].processed += processCount; }, this); _.forEach(failProcess.queueProcessFails, function(processCount, queue) { jobQueues[queue] = jobQueues[queue] || new VitalsItem.QueueStats(); jobQueues[queue].failed += processCount; jobQueues[queue].processed += processCount; }, this); return jobQueues; };
io(); io.connect("/messages");
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), babel: { options: { sourceMap: true }, dist: { files: { 'web/dist/app.js': 'web/src/app.js', 'web/dist/camera.js': 'web/src/camera.js', 'web/dist/model.js': 'web/src/model.js', 'web/dist/user_input.js': 'web/src/user_input.js', 'web/dist/util.js': 'web/src/util.js', 'web/dist/view.js': 'web/src/view.js', } } }, watch: { scripts: { files: ['**/*.js', '**/*.scss', '**/*.html'], tasks: ['default'], options: { spawn: false, livereload: true } } }, sass: { dist: { files: { 'web/style/style.css': 'web/style/style.scss' } } }, browserify: { dist: { files: { 'web/dist/main.js': 'web/dist/app.js' } } } }); grunt.loadNpmTasks('grunt-babel'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-browserify'); grunt.registerTask('default', ['babel', 'sass', 'browserify']); };
import { Serializer } from 'ember-cli-mirage'; import { isArray } from '@ember/array'; import { assign } from '@ember/polyfills'; export default Serializer.extend({ serialize(object) { if (isArray(object.models)) { return { '@type': 'features', '@href': '/features', '@representation': 'standard', features: object.models.map(feature => feature.attrs) }; } else { let metadata = { '@type': 'features', '@href': '/features', '@representation': 'standard' }; return assign(metadata, object.attrs); } } });
/** * Policy Mappings * (sails.config.policies) * * Policies are simple functions which run **before** your controllers. * You can apply one or more policies to a given controller, or protect * its actions individually. * * Any policy file (e.g. `api/policies/authenticated.js`) can be accessed * below by its filename, minus the extension, (e.g. "authenticated") * * For more information on how policies work, see: * http://sailsjs.org/#!/documentation/concepts/Policies * * For more information on configuring policies, check out: * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.policies.html */ module.exports.policies = { /*************************************************************************** * * * Default policy for all controllers and actions (`true` allows public * * access) * * * ***************************************************************************/ // '*': true, /*************************************************************************** * * * Here's an example of mapping some policies to run before a controller * * and its actions * * * ***************************************************************************/ RutasController: { home: true,//para todos error: true,//sin ninguna politica, todos pueden acceder listarUsuarios: ['autenticado'], //crearUsuario: ['autenticado'], editarUsuario: ['autenticado','mismoUsuario'], } };
(function() { var Ajax, CodeViewInterface, DesignViewInterface, Dialog, Dropdown, Editor, Form, FullscreenToggle, ImageEditor, MainNav, Notification, PreviewInterface, ProgressBar, Slider, SplitViewInterface, TabSwitcher, Toggle, Upload, base64Encode, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; window.Oxygen || (window.Oxygen = {}); window.Oxygen.Ajax = Ajax = (function() { function Ajax() {} Ajax.handleErrorCallback = (function() {}); Ajax.handleSuccessCallback = (function() {}); Ajax.sendAjax = function(type, url, data) { $.ajax({ dataType: "json", type: type, url: url, data: data, success: this.handleSuccess, error: this.handleError }); }; Ajax.fireLink = function(event) { event.preventDefault(); this.sendAjax("GET", $(event.target).attr("href"), null); }; Ajax.handleSuccess = function(data) { if (data.redirect) { window.location.replace(data.redirect); } else { new Notification(data); } Ajax.handleSuccessCallback(data); }; Ajax.handleError = function(response, textStatus, errorThrown) { var content, e; try { content = $.parseJSON(response.responseText); console.error(content); new Notification({ content: "Exception of type <code class=\"no-wrap\">" + content.error.type + "</code>with message <code class=\"no-wrap\">" + content.error.message + "</code>thrown at <code class=\"no-wrap\">" + content.error.file + ":" + content.error.line + "</code>", status: "failed" }); } catch (_error) { e = _error; console.error(response.responseText); new Notification({ content: "Whoops, looks like something went wrong.", status: "failed" }); } Ajax.handleErrorCallback(response, textStatus, errorThrown); }; return Ajax; })(); window.Oxygen || (window.Oxygen = {}); window.Oxygen.Form = Form = (function() { Form.list = []; Form.messages = { confirmation: "You have made changes to this form.<br>Are you sure you want to exit?" }; Form.classes = { warnBeforeExit: "Form--warnBeforeExit", submitOnKeydown: "Form--submitOnKeydown", sendAjax: "Form--sendAjax", sendAjaxOnChange: "Form--sendAjaxOnChange", autoSubmit: "Form--autoSubmit", taggableInput: ".Form-taggable" }; Form.findAll = function() { $("form").each(function() { return Form.list.push(new Form($(this))); }); }; function Form(element) { this.handleKeydown = __bind(this.handleKeydown, this); this.sendAjax = __bind(this.sendAjax, this); this.handleExit = __bind(this.handleExit, this); this.handleSave = __bind(this.handleSave, this); this.handleChange = __bind(this.handleChange, this); this.form = element; this.registerEvents(); } Form.prototype.registerEvents = function() { if (this.form.hasClass(Form.classes.warnBeforeExit)) { this.form.find(":input").on("input change", this.handleChange); this.form.on("submit", this.handleSave); $("a, button[type=\"submit\"]").on("click", this.handleExit); } if (this.form.hasClass(Form.classes.sendAjax)) { this.form.on("submit", this.sendAjax); } if (this.form.hasClass(Form.classes.sendAjaxOnChange)) { this.form.on("change", this.sendAjax); } if (this.form.hasClass(Form.classes.submitOnKeydown)) { $(document.body).on("keydown", this.handleKeydown); } if (this.form.hasClass(Form.classes.autoSubmit)) { this.form.find('button[type="submit"]')[0].click(); } }; Form.prototype.handleChange = function(event) { this.form.attr("data-changed", true); console.log("Form Changed"); }; Form.prototype.handleSave = function(event) { this.form.attr("data-changed", false); console.log("Form Saved"); }; Form.prototype.handleExit = function(event) { if (this.form.attr("data-changed") === "true") { if ($(event.currentTarget).hasClass("Form-submit")) { return; } Dialog.handleConfirmClick(event, { message: Form.messages.confirmation, buttons: [ $.extend({}, vex.dialog.buttons.YES, { text: 'Discard Changes' }), $.extend({}, vex.dialog.buttons.NO, { text: 'Cancel' }) ] }); } }; Form.prototype.sendAjax = function(event) { event.preventDefault(); Ajax.sendAjax(this.form.attr("method"), this.form.attr("action"), Form.getFormData(this.form)); }; Form.prototype.handleKeydown = function(event) { if ((event.ctrlKey || event.metaKey) && event.which === 83) { this.form.submit(); event.preventDefault(); } }; Form.getFormData = function(form) { var data; data = {}; form.find("[name]").each(function() { var name, value; name = $(this).attr("name"); value = $(this).val(); if ($(this).is("[type=\"checkbox\"]")) { if ($(this).is(":checked")) { return data[name] = value; } } else { return data[name] = value; } }); return data; }; Form.getFormDataObject = function(form) { var data; data = new FormData(); form.find("[name]").each(function() { var name, value; name = $(this).attr("name"); value = $(this).val(); if ($(this).is("[type=\"checkbox\"]")) { if ($(this).is(":checked")) { return data.append(name, value); } } else { return data.append(name, value); } }); return data; }; return Form; })(); window.Oxygen || (window.Oxygen = {}); window.Oxygen.Toggle = Toggle = (function() { Toggle.classes = { ifEnabled: "Toggle--ifEnabled", ifDisabled: "Toggle--ifDisabled" }; function Toggle(toggle, enableCallback, disableCallback) { this.toggle = toggle; this.enableCallback = enableCallback; this.disableCallback = disableCallback; this.registerEvents(); } Toggle.prototype.registerEvents = function() { this.toggle.on("click", this.handleToggle.bind(this)); return this.toggle.attr("data-enabled", "false"); }; Toggle.prototype.handleToggle = function() { if (this.toggle.attr("data-enabled") === "true") { this.toggle.attr("data-enabled", "false"); return this.disableCallback(); } else { this.toggle.attr("data-enabled", "true"); return this.enableCallback(); } }; return Toggle; })(); window.Oxygen || (window.Oxygen = {}); window.Oxygen.FullscreenToggle = FullscreenToggle = (function(_super) { __extends(FullscreenToggle, _super); function FullscreenToggle(toggle, fullscreenElement, enterFullscreenCallback, exitFullscreenCallback) { this.exitFullscreen = __bind(this.exitFullscreen, this); this.enterFullscreen = __bind(this.enterFullscreen, this); this.toggle = toggle; this.fullscreenElement = fullscreenElement; this.enableCallback = this.enterFullscreen; this.disableCallback = this.exitFullscreen; this.enterFullscreenCallback = enterFullscreenCallback; this.exitFullscreenCallback = exitFullscreenCallback; this.registerEvents(); } FullscreenToggle.prototype.enterFullscreen = function() { var e; this.fullscreenElement.addClass("FullscreenToggle--isFullscreen"); $(document.body).addClass("Body--noScroll"); e = document.body; if (e.requestFullscreen) { e.requestFullscreen(); } else if (e.mozRequestFullScreen) { e.mozRequestFullScreen(); } else if (e.webkitRequestFullscreen) { e.webkitRequestFullscreen(); } else if (e.msRequestFullscreen) { e.msRequestFullscreen(); } this.enterFullscreenCallback(); }; FullscreenToggle.prototype.exitFullscreen = function() { this.fullscreenElement.removeClass("FullscreenToggle--isFullscreen"); $(document.body).removeClass("Body--noScroll"); if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if (document.webkitExitFullscreen) { document.webkitExitFullscreen(); } this.exitFullscreenCallback(); }; return FullscreenToggle; })(Toggle); window.Oxygen || (window.Oxygen = {}); window.Oxygen.ProgressBar = ProgressBar = (function() { ProgressBar.classes = { container: "ProgressBar", fill: "ProgressBar-fill", noTransition: "ProgressBar-fill--jump", message: "ProgressBar-message", itemMessage: "ProgressBar-message-item", sectionCount: "ProgressBar-message-section-count", sectionMessage: "ProgressBar-message-section-message" }; function ProgressBar(element) { this.container = element; this.fill = this.container.find("." + ProgressBar.classes.fill); this.message = this.container.parent().find("." + ProgressBar.classes.message); this.itemMessage = this.message.find("." + ProgressBar.classes.itemMessage); this.sectionCount = this.message.find("." + ProgressBar.classes.sectionCount); this.sectionMessage = this.message.find("." + ProgressBar.classes.sectionMessage); this.setup(); } ProgressBar.prototype.setup = function() { return this.fill.css("opacity", "1"); }; ProgressBar.prototype.transitionTo = function(value, total) { var percentage; percentage = Math.round(value / total * 100); if (percentage > 100) { percentage = 100; } this.fill.css("width", percentage + "%"); }; ProgressBar.prototype.setMessage = function(message) { this.message.show(); this.itemMessage.html(message); }; ProgressBar.prototype.setSectionCount = function(count) { this.message.show(); this.sectionCount.html(count); }; ProgressBar.prototype.setSectionMessage = function(message) { this.message.show(); this.sectionMessage.html(message); }; ProgressBar.prototype.reset = function(callback) { var fill; if (callback == null) { callback = (function() {}); } this.message.hide(); fill = this.fill; fill.addClass(ProgressBar.classes.noTransition); return setTimeout(function() { fill.css("width", "0"); return setTimeout(function() { fill.removeClass(ProgressBar.classes.noTransition); return callback(); }, 5); }, 5); }; ProgressBar.prototype.resetAfter = function(time) { return setTimeout(this.reset.bind(this), time); }; return ProgressBar; })(); window.Oxygen || (window.Oxygen = {}); window.Oxygen.Dropdown = Dropdown = (function() { function Dropdown() {} Dropdown.classes = { dropdownToggle: "Dropdown-container", dropdownList: "Dropdown", isActive: "is-active" }; Dropdown.registerEvents = function() { $("." + this.classes.dropdownToggle).on("click", this.handleClick.bind(this)); return $(document).on("click", this.handleGlobalClick.bind(this)); }; Dropdown.handleClick = function(event) { var container, dropdown; container = $(event.target); while (!container.hasClass(this.classes.dropdownToggle)) { if (container.is("a[href], form")) { return; } container = container.parent(); } dropdown = container.find("." + this.classes.dropdownList); if (dropdown.hasClass(this.classes.isActive)) { return dropdown.removeClass(this.classes.isActive); } else { $("." + this.classes.dropdownList).removeClass(this.classes.isActive); return dropdown.addClass(this.classes.isActive); } }; Dropdown.handleGlobalClick = function(event) { var ancestorExists, parentHasClass, target, targetHasClass; target = $(event.target); targetHasClass = target.hasClass(this.classes.dropdownToggle); parentHasClass = target.parent().hasClass(this.classes.dropdownToggle); ancestorExists = target.parents("." + this.classes.dropdownToggle).length; if (!targetHasClass && !parentHasClass && !ancestorExists) { return $("." + this.classes.dropdownList).removeClass(this.classes.isActive); } }; return Dropdown; })(); window.Oxygen || (window.Oxygen = {}); window.Oxygen.Notification = Notification = (function() { Notification.classes = { container: "Notification-container", item: "Notification" }; Notification.initializeExistingMessages = function() { $("." + Notification.classes.container).find("." + Notification.classes.item).each(function(index, value) { new Notification({ message: $(this) }); }); }; function Notification(options) { if (options.log) { console.log(options.log); } if (options.message) { this.message = options.message; this.message.removeClass("is-hidden"); this.registerHide(); } else if (options.status && options.content) { this.message = $("<div class=\"" + Notification.classes.item + " Notification--" + options.status + "\">" + options.content + "<span class=\"Notification-dismiss Icon Icon-times\"></span></div>"); this.show(); } else { console.error("Invalid Arguments For New Notification"); console.error(options); } return; } Notification.prototype.show = function() { this.message.appendTo("." + Notification.classes.container); this.registerHide(); }; Notification.prototype.registerHide = function() { this.message.click(this.hide.bind(this)); setTimeout(this.hide.bind(this), 20000); }; Notification.prototype.hide = function() { this.message.addClass("is-sliding-up"); setTimeout(this.remove.bind(this), 500); }; Notification.prototype.remove = function() { this.message.remove(); }; return Notification; })(); window.Oxygen || (window.Oxygen = {}); window.Oxygen.TabSwitcher = TabSwitcher = (function() { TabSwitcher.classes = { tabs: "TabSwitcher-tabs", content: "TabSwitcher-content", active: "TabSwitcher--isActive" }; TabSwitcher.list = []; TabSwitcher.findAll = function() { return $("." + TabSwitcher.classes.tabs).each(function() { var container, tabs; tabs = $(this); if (tabs.hasClass(TabSwitcher.classes.content)) { container = tabs; } else { container = tabs.siblings("." + TabSwitcher.classes.content); } if (container.length === 0) { container = tabs.parent().siblings("." + TabSwitcher.classes.content); } return TabSwitcher.list.push(new TabSwitcher(tabs, container)); }); }; function TabSwitcher(tabs, container) { this.handleClick = __bind(this.handleClick, this); this.tabs = tabs; this.container = container; this.findDefault(); this.registerEvents(); } TabSwitcher.prototype.findDefault = function() { var tab; tab = this.tabs.children("[data-default-tab]").attr("data-switch-to-tab"); return this.setTo(tab); }; TabSwitcher.prototype.registerEvents = function() { return this.tabs.children("[data-switch-to-tab]").on("click", this.handleClick); }; TabSwitcher.prototype.handleClick = function(event) { var tab; tab = $(event.currentTarget).attr("data-switch-to-tab"); return this.setTo(tab); }; TabSwitcher.prototype.setTo = function(tab) { this.current = tab; this.container.children("[data-tab]").removeClass(TabSwitcher.classes.active); this.container.children("[data-tab=\"" + tab + "\"]").addClass(TabSwitcher.classes.active); this.tabs.children("[data-switch-to-tab]").removeClass(TabSwitcher.classes.active); return this.tabs.children("[data-switch-to-tab=\"" + tab + "\"]").addClass(TabSwitcher.classes.active); }; return TabSwitcher; })(); window.Oxygen || (window.Oxygen = {}); window.Oxygen.Upload = Upload = (function() { Upload.selectors = { uploadElement: ".FileUpload", progressBarElement: ".ProgressBar", progressBarFill: ".ProgressBar-fill" }; Upload.states = { onDragOver: "FileUpload--onDragOver" }; Upload.registerEvents = function() { return $(Upload.selectors.uploadElement).on("dragover", Upload.handleDragOver).on("dragleave", Upload.handleDragLeave).on("drop", Upload.handleDrop).find("input[type=file]").on("change", Upload.handleChange); }; Upload.handleDragOver = function(event) { return $(event.currentTarget).addClass(Upload.states.onDragOver); }; Upload.handleDragLeave = function(event) { return $(event.currentTarget).removeClass(Upload.states.onDragOver); }; Upload.handleDrop = function(event) { var file, files, form, formData, input, upload, _i, _len; event.preventDefault(); $(event.currentTarget).removeClass(Upload.states.onDragOver); files = event.originalEvent.dataTransfer.files; form = $(event.currentTarget).parents("form"); input = $(event.currentTarget).find("input")[0]; formData = Form.getFormDataObject(form); for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; formData.append(input.name, file); } upload = new Upload($(event.currentTarget).parent().find(Upload.selectors.progressBarElement), form, formData); upload.send(); }; Upload.handleChange = function(event) { event.target.form.submit(); }; function Upload(progressBar, form, data) { this.progressBar = new ProgressBar(progressBar); this.form = form; this.data = data; } Upload.prototype.send = function() { return $.ajax({ dataType: "json", type: this.form.attr("method"), url: this.form.attr("action"), data: this.data, contentType: false, processData: false, success: this.handleSuccess.bind(this), error: Ajax.handleError, xhr: this.createCustomRequest.bind(this) }); }; Upload.prototype.createCustomRequest = function() { var object; object = window.ActiveXObject ? new ActiveXObject("XMLHttp") : new XMLHttpRequest(); object.upload.addEventListener("progress", this.handleProgress.bind(this)); return object; }; Upload.prototype.handleProgress = function(event) { if (event.lengthComputable) { return this.progressBar.transitionTo(event.loaded, event.total); } }; Upload.prototype.handleSuccess = function(data) { Ajax.handleSuccess(data); return this.progressBar.reset(); }; return Upload; })(); window.Oxygen || (window.Oxygen = {}); window.Oxygen.MainNav = MainNav = (function() { function MainNav() {} MainNav.headroom = function() { var header, headroom; header = $(".MainNav"); if (header.length > 0) { if ($(window).width() > 768) { headroom = new Headroom(header[0], { "tolerance": 20, "offset": 50, "classes": { "initial": "Headroom", "pinned": "Headroom--pinned", "unpinned": "Headroom--unpinned", "top": "Headroom--top", "notTop": "Headroom--not-top" } }); headroom.init(); } } }; return MainNav; })(); window.Oxygen || (window.Oxygen = {}); window.Oxygen.Slider = Slider = (function() { Slider.selectors = { slider: ".Slider", list: ".Slider-list", item: ".Slider-item", back: ".Slider-back", forward: ".Slider-forward" }; Slider.classes = { item: "Slider-item", isCurrent: "Slider-item--current", isHidden: "Slider-item--hidden", slideInLeft: "Slider-item--slideInLeft", slideInRight: "Slider-item--slideInRight", slideOutLeft: "Slider-item--slideOutLeft", slideOutRight: "Slider-item--slideOutRight", isAfter: "Slider-item--after", noTransition: "Slider--noTransition" }; Slider.list = []; Slider.findAll = function() { return $(Slider.selectors.slider).each(function() { return Slider.list.push(new Slider($(this))); }); }; function Slider(container) { this.container = container; this.list = this.container.find(Slider.selectors.list); this.items = this.container.find(Slider.selectors.item); this.total = this.items.length; this.interval = this.container.attr("data-interval") || 5000; this.previousId = 0; this.currentId = 0; this.nextId = 0; this.animating = false; this.animationTime = 1000; this.registerEvents(); this.hideAll(); this.next(); if (this.container.attr("data-autoplay") === "true") { this.play(); } } Slider.prototype.registerEvents = function() { this.container.find(Slider.selectors.back).on("click", this.previous.bind(this)); this.container.find(Slider.selectors.forward).on("click", this.next.bind(this)); }; Slider.prototype.play = function() { var callback; callback = this.container.attr("data-direction") === "reverse" ? this.previous.bind(this) : this.next.bind(this); this.timer = setInterval(callback, this.interval); }; Slider.prototype.pause = function() { clearInterval(this.timer); }; Slider.prototype.getItem = function(id) { return this.list.children(":nth-child(" + id + ")"); }; Slider.prototype.hideAll = function() { this.items.removeClass(); this.items.addClass(Slider.classes.item + " " + Slider.classes.isHidden); }; Slider.prototype.allClasses = function() { return Slider.classes.isHidden + " " + Slider.classes.slideInLeft + " " + Slider.classes.slideInRight + " " + Slider.classes.slideOutLeft + " " + Slider.classes.slideOutRight; }; Slider.prototype.next = function() { var current, previous; if (!this.shouldAnimate()) { return false; } this.previousId = this.currentId; this.currentId += 1; if (this.currentId > this.total) { this.currentId = 1; } this.nextId = this.currentId + 1; if (this.nextId > this.total) { this.nextId = 1; } current = this.getItem(this.currentId); previous = this.getItem(this.previousId); this.hideAll; previous.removeClass(this.allClasses()).addClass(Slider.classes.slideOutLeft); current.removeClass(this.allClasses()).addClass(Slider.classes.slideInRight); }; Slider.prototype.previous = function() { var current, next; if (!this.shouldAnimate()) { return false; } this.nextId = this.currentId; this.currentId -= 1; if (this.currentId < 1) { this.currentId = this.total; } this.previousId = this.currentId - 1; if (this.nextId < 1) { this.nextId = this.total; } current = this.getItem(this.currentId); next = this.getItem(this.nextId); this.hideAll; next.removeClass(this.allClasses()).addClass(Slider.classes.slideOutRight); current.removeClass(this.allClasses()).addClass(Slider.classes.slideInLeft); }; Slider.prototype.shouldAnimate = function() { if (this.animating) { return false; } this.animating = true; setTimeout((function(_this) { return function() { _this.animating = false; }; })(this), this.animationTime); return true; }; return Slider; })(); window.Oxygen || (window.Oxygen = {}); window.Oxygen.Dialog = Dialog = (function() { function Dialog() {} Dialog.registerEvents = function() { $("[data-dialog-type=\"confirm\"]").on("click", this.handleConfirmClick); return $("[data-dialog-type=\"alert\"]").on("click", this.handleAlertClick); }; Dialog.handleAlertClick = function(event) { var target; target = $(event.currentTarget); return vex.dialog.alert(target.attr("data-dialog-message")); }; Dialog.handleConfirmClick = function(event, customConfig) { var attribute, defaultConfig, target; target = $(event.currentTarget); if (target.attr("data-dialog-disabled") !== "true") { event.preventDefault(); event.stopPropagation(); event.stopImmediatePropagation(); defaultConfig = { message: target.attr("data-dialog-message"), callback: function(value) { if (value) { target.attr("data-dialog-disabled", "true"); return target[0].click(); } } }; for (attribute in customConfig) { defaultConfig[attribute] = customConfig[attribute]; } return vex.dialog.confirm(defaultConfig); } }; return Dialog; })(); window.Oxygen || (window.Oxygen = {}); window.Oxygen.Editor = Editor = (function() { Editor.list = []; Editor.createEditors = function(editors) { var editor, textarea, _i, _len; for (_i = 0, _len = editors.length; _i < _len; _i++) { editor = editors[_i]; textarea = $("textarea[name=\"" + editor.name + "\"]"); if (textarea.length) { console.log("Editor found"); if (editor.mode == null) { editor.mode = user.editor.defaultMode; } console.log(editor); new Editor(editor.name, editor.language, editor.mode, editor.readOnly, editor.stylesheets); } else { console.log("Editor not found"); console.log(editor); } } }; Editor.classes = { editor: { container: "Editor", header: "Editor-header", content: "Editor-content", footer: "Editor-footer", preview: "Editor-preview" }, state: { isHidden: "Editor--hidden", contentIsSplit: "Editor-content--isSplit" }, button: { switchEditor: "Editor--switchEditor", fullscreenToggle: "Editor--toggleFullscreen" } }; function Editor(name, language, currentMode, readOnly, stylesheets) { if (stylesheets == null) { stylesheets = []; } this.handleFormSubmit = __bind(this.handleFormSubmit, this); this.handleSwitchEditor = __bind(this.handleSwitchEditor, this); this.exitFullscreen = __bind(this.exitFullscreen, this); this.enterFullscreen = __bind(this.enterFullscreen, this); this.name = name; this.language = language; this.currentMode = currentMode; this.readOnly = readOnly; this.stylesheets = stylesheets; this.modes = {}; this.textarea = $("textarea[name=\"" + this.name + "\"]"); this.container = this.textarea.parents("." + Editor.classes.editor.container); this.fullscreenToggle = new FullscreenToggle(this.container.find("." + Editor.classes.button.fullscreenToggle), this.container, this.enterFullscreen, this.exitFullscreen); this.show(); this.resizeToContent(); this.registerEvents(); Editor.list.push(this); } Editor.prototype.getMode = function(mode) { if (mode == null) { return this.currentMode; } else { return mode; } }; Editor.prototype.registerEvents = function() { this.container.find("." + Editor.classes.button.switchEditor).on("click", this.handleSwitchEditor); $(this.container).parents("form").on("submit", this.handleFormSubmit); }; Editor.prototype.create = function(m) { var mode; mode = this.getMode(m); switch (mode) { case "code": this.modes.code = new CodeViewInterface(this); break; case "design": this.modes.design = new DesignViewInterface(this); break; case "preview": this.modes.preview = new PreviewInterface(this); break; case "split": this.modes.split = new SplitViewInterface(this); } this.modes[mode].create(); }; Editor.prototype.show = function(m, full) { var mode; if (full == null) { full = true; } mode = this.getMode(m); if (this.modes[mode] == null) { this.create(mode); } this.modes[mode].show(full); this.currentMode = mode; this.valueFromForm(mode); }; Editor.prototype.hide = function(m) { var mode; mode = this.getMode(m); this.modes[mode].hide(); this.valueToForm(mode); }; Editor.prototype.valueFromForm = function(m) { var mode; mode = this.getMode(m); this.modes[mode].valueFromForm(); }; Editor.prototype.valueToForm = function(m) { var mode; mode = this.getMode(m); this.modes[mode].valueToForm(); }; Editor.prototype.resizeToContainer = function() { if (this.modes.code) { this.modes.code.resize(); } }; Editor.prototype.resizeToContent = function() { this.container.find("." + Editor.classes.editor.content).css("height", this.textarea.attr("rows") * 1.5 + "em"); if (this.modes.code) { this.modes.code.resize(); } }; Editor.prototype.enterFullscreen = function() { this.resizeToContainer(); }; Editor.prototype.exitFullscreen = function() { this.resizeToContent(); }; Editor.prototype.handleSwitchEditor = function(event) { var editorToSwitch; console.log("Editor.handleSwitchEditor"); editorToSwitch = $(event.target).attr("data-editor"); this.hide(); return this.show(editorToSwitch); }; Editor.prototype.handleFormSubmit = function() { return this.valueToForm(); }; return Editor; })(); window.Oxygen || (window.Oxygen = {}); window.Oxygen.Editor.CodeViewInterface = CodeViewInterface = (function() { function CodeViewInterface(editor) { this.editor = editor; this.view = null; } CodeViewInterface.prototype.create = function() { var object; console.log("CodeViewInterface.create"); object = ace.edit(this.editor.name + "-ace-editor"); object.getSession().setMode("ace/mode/" + this.editor.language); object.setTheme(user.editor.ace.theme); object.getSession().setUseWrapMode(user.editor.ace.wordWrap); object.setHighlightActiveLine(user.editor.ace.highlightActiveLine); object.setShowPrintMargin(user.editor.ace.showPrintMargin); object.setShowInvisibles(user.editor.ace.showInvisibles); object.setReadOnly(this.editor.readOnly); $("#" + this.editor.name + "-ace-editor").css("font-size", user.editor.ace.fontSize); return this.view = object; }; CodeViewInterface.prototype.show = function(full) { console.log("CodeViewInterface.show"); $("#" + this.editor.name + "-ace-editor").removeClass(Editor.classes.state.isHidden); if (full) { $("#" + this.editor.name + "-ace-editor").css("width", "100%"); } return this.resize(); }; CodeViewInterface.prototype.hide = function() { console.log("CodeViewInterface.hide"); return $("#" + this.editor.name + "-ace-editor").addClass(Editor.classes.state.isHidden); }; CodeViewInterface.prototype.valueFromForm = function() { console.log("CodeViewInterface.valueFromForm"); return this.view.setValue(this.editor.textarea.val(), -1); }; CodeViewInterface.prototype.valueToForm = function() { console.log("CodeViewInterface.valueToForm"); return this.editor.textarea.val(this.view.getValue()); }; CodeViewInterface.prototype.resize = function() { return this.view.resize(); }; return CodeViewInterface; })(); window.Oxygen || (window.Oxygen = {}); window.Oxygen.Editor.DesignViewInterface = DesignViewInterface = (function() { function DesignViewInterface(editor) { this.editor = editor; this.view = null; } DesignViewInterface.prototype.create = function() { var config, object, _ref; config = user.editor.ckeditor; config.customConfig = (_ref = config.customConfig) != null ? _ref : ''; config.contentsCss = this.editor.stylesheets; console.log(config); object = CKEDITOR.replace(this.editor.name + "-editor", config); return this.view = object; }; DesignViewInterface.prototype.show = function(full) { $("#cke_" + this.editor.name + "-editor").show(); if (full) { $("#" + this.editor.name + "-ace-editor").css("width", "100%"); } }; DesignViewInterface.prototype.hide = function() { $("#cke_" + this.editor.name + "-editor").hide(); }; DesignViewInterface.prototype.valueFromForm = function() { return this.view.setData(this.editor.textarea.val()); }; DesignViewInterface.prototype.valueToForm = function() { return $("textarea[name=\"" + this.editor.name + "\"]").val(this.view.getData()); }; return DesignViewInterface; })(); window.Oxygen || (window.Oxygen = {}); window.Oxygen.Editor.PreviewInterface = PreviewInterface = (function() { function PreviewInterface(editor) { this.editor = editor; this.view = null; } PreviewInterface.prototype.create = function() { var element, preview; console.log("PreviewInterface.create"); element = "<iframe id=\"" + this.editor.name + "-preview\" class=\"" + Editor.classes.editor.preview + "\"></iframe>"; preview = $(element); preview.appendTo(this.editor.container.find(".Editor-content")); return this.view = preview; }; PreviewInterface.prototype.show = function(full) { var head, stylesheet, _i, _len, _ref; console.log("PreviewInterface.show"); $("#" + this.editor.name + "-preview").removeClass(Editor.classes.state.isHidden); if (full) { $("#" + this.editor.name + "-preview").css("width", "100%"); } head = ""; _ref = this.editor.stylesheets; for (_i = 0, _len = _ref.length; _i < _len; _i++) { stylesheet = _ref[_i]; head += "<link rel=\"stylesheet\" href=\"" + stylesheet + "\">"; } this.view.contents().find("head").html(head); return this.view.contents().find("html").addClass("no-js " + $("html").attr("class").replace("js ", "")); }; PreviewInterface.prototype.hide = function() { console.log("PreviewInterface.hide"); return $("#" + this.editor.name + "-preview").addClass(Editor.classes.state.isHidden); }; PreviewInterface.prototype.valueFromForm = function() { console.log("PreviewInterface.valueFromForm"); return this.view.contents().find("body").html(this.editor.textarea.val()); }; PreviewInterface.prototype.valueToForm = function() {}; return PreviewInterface; })(); window.Oxygen || (window.Oxygen = {}); window.Oxygen.Editor.SplitViewInterface = SplitViewInterface = (function() { function SplitViewInterface(editor) { this.editor = editor; this.view = null; } SplitViewInterface.prototype.create = function() { return console.log("SplitViewInterface.create"); }; SplitViewInterface.prototype.show = function() { console.log("SplitViewInterface.show"); this.editor.container.find("." + Editor.classes.editor.content).addClass(Editor.classes.state.contentIsSplit); this.editor.show("code", false); this.editor.show("preview", false); $("#" + this.editor.name + "-ace-editor, #" + this.editor.name + "-preview").css("width", "50%"); return this.editor.modes.code.view.on("change", this.synchronize.bind(this)); }; SplitViewInterface.prototype.hide = function() { console.log("SplitViewInterface.hide"); this.editor.container.find("." + Editor.classes.editor.content).removeClass(Editor.classes.state.contentIsSplit); this.editor.hide("code"); return this.editor.hide("preview"); }; SplitViewInterface.prototype.valueFromForm = function() {}; SplitViewInterface.prototype.valueToForm = function() {}; SplitViewInterface.prototype.onChange = function() { return this.hasChanged = true; }; SplitViewInterface.prototype.synchronize = function() { if (this.editor.currentMode === "split") { console.log("SplitViewInterface.synchronize"); this.editor.valueToForm("code"); this.editor.valueFromForm("preview"); return this.hasChanged = false; } }; return SplitViewInterface; })(); window.Oxygen || (window.Oxygen = {}); window.Oxygen.ImageEditor = ImageEditor = (function() { function ImageEditor(container) { this.handleResizeInputChange = __bind(this.handleResizeInputChange, this); this.handleCropRelease = __bind(this.handleCropRelease, this); this.handleCropInputChange = __bind(this.handleCropInputChange, this); this.handleCropSelect = __bind(this.handleCropSelect, this); this.handleCropDisable = __bind(this.handleCropDisable, this); this.handleCropEnable = __bind(this.handleCropEnable, this); this.onRequestProgress = __bind(this.onRequestProgress, this); this.onRequestEnd = __bind(this.onRequestEnd, this); this.handleSave = __bind(this.handleSave, this); this.handlePreview = __bind(this.handlePreview, this); var that; this.container = container; this.image = this.container.find("." + ImageEditor.classes.layout.image); if (!this.image.length) { throw new Error("<img> element doesn't exist"); } this.forms = { simple: this.image.parent().parent().find("." + ImageEditor.classes.form.simple), advanced: this.image.parent().parent().find("." + ImageEditor.classes.form.advanced) }; this.fields = { crop: { x: this.container.find('[name="crop[x]"]'), y: this.container.find('[name="crop[y]"]'), width: this.container.find('[name="crop[width]"]'), height: this.container.find('[name="crop[height]"]') }, resize: { width: this.container.find('[name="resize[width]"]'), height: this.container.find('[name="resize[height]"]'), keepAspectRatio: this.container.find('[name="resize[keepAspectRatio]"][value="true"]') }, macro: this.container.find('[name="macro"]'), name: this.container.find('[name="name"]'), slug: this.container.find('[name="slug"]') }; that = this; this.image[0].onload = function() { console.log('Image Loaded'); if (that.imageDimensions == null) { that.imageDimensions = { cropX: 0, cropY: 0 }; } that.imageDimensions.width = this.clientWidth; that.imageDimensions.height = this.clientHeight; that.imageDimensions.naturalWidth = this.naturalWidth; that.imageDimensions.naturalHeight = this.naturalHeight; that.imageDimensions.ratio = this.naturalWidth / this.naturalHeight; that.fields.resize.width.val(that.imageDimensions.naturalWidth); that.fields.resize.height.val(that.imageDimensions.naturalHeight); return that.handleCropEnable(); }; this.progressBar = new ProgressBar(this.container.find("." + ImageEditor.classes.form.progressBar)); this.fullscreenToggle = new FullscreenToggle(this.container.find("." + ImageEditor.classes.button.toggleFullscreen), this.container, (function() {}), (function() {})); this.container.find("." + ImageEditor.classes.button.apply).on("click", this.handlePreview); this.container.find("." + ImageEditor.classes.button.save).on("click", this.handleSave); this.container.find("." + ImageEditor.classes.form.crop).on("change", this.handleCropInputChange); this.container.find("." + ImageEditor.classes.form.resize).on("change", this.handleResizeInputChange); this.jCropApi = null; this.cropDisableCounter = 2; } ImageEditor.prototype.handlePreview = function() { this.applyChanges(this.gatherData()); return this.progressNotification = new Notification({ content: "Processing Image", status: "success" }); }; ImageEditor.prototype.handleSave = function() { var data; data = this.gatherData(); data.save = true; data.name = this.fields.name.val(); data.slug = this.fields.slug.val(); this.applyChanges(data); return this.progressNotification = new Notification({ content: "Saving Image", status: "success" }); }; ImageEditor.prototype.gatherData = function() { var mode; mode = TabSwitcher.list[0].current; switch (mode) { case "simple": return this.getSimpleData(); case "advanced": return this.getAdvancedData(); default: return {}; } }; ImageEditor.prototype.getSimpleData = function() { return this.removeDefaultFields(Form.getFormData(this.forms.simple)); }; ImageEditor.prototype.removeDefaultFields = function(formData) { var defaults, item, key, resize; resize = (function(_this) { return function(formData) { return (!formData["resize[width]"] || formData["resize[width]"] === _this.imageDimensions.naturalWidth.toString()) && (!formData["resize[height]"] || formData["resize[height]"] === _this.imageDimensions.naturalHeight.toString()); }; })(this); defaults = { "fit[position]": (function(_this) { return function(item) { return item === "center"; }; })(this), "resize[width]": (function(_this) { return function(item, formData) { return resize(formData); }; })(this), "resize[height]": (function(_this) { return function(item, formData) { return resize(formData); }; })(this), "resize[keepAspectRatio]": (function(_this) { return function(item, formData) { return resize(formData); }; })(this), "gamma": (function(_this) { return function(item) { return item === "1"; }; })(this), "greyscale": (function(_this) { return function(item) { return item === "false"; }; })(this), "invert": (function(_this) { return function(item) { return item === "false"; }; })(this), "rotate[backgroundColor]": (function(_this) { return function(item) { return item === "#ffffff"; }; })(this), "crop[x]": (function(_this) { return function(item) { return _this.imageDimensions.cropX = item === "" ? 0 : parseInt(item); }; })(this), "crop[y]": (function(_this) { return function(item) { return _this.imageDimensions.cropY = item === "" ? 0 : parseInt(item); }; })(this) }; for (key in formData) { item = formData[key]; if (defaults[key] && defaults[key](item, formData)) { delete formData[key]; } else if (item === "0" || item === "") { delete formData[key]; } } return formData; }; ImageEditor.prototype.getAdvancedData = function() { return JSON.parse(this.fields.macro.val()); }; ImageEditor.prototype.applyChanges = function(data) { var i, that; if (this.progressTimer != null) { new Notification({ content: "Already Processing", status: "failed" }); return; } $.ajax({ type: "GET", url: this.image.attr("data-root"), data: data, contentType: false, success: this.onRequestEnd, error: (function(_this) { return function() { _this.progressNotification.hide(); return Ajax.handleError(); }; })(this), xhr: (function(_this) { return function() { var object; object = window.ActiveXObject ? new ActiveXObject("XMLHttp") : new XMLHttpRequest(); object.addEventListener("progress", _this.onRequestProgress); object.overrideMimeType("text/plain; charset=x-user-defined"); return object; }; })(this) }); i = 0; that = this; return this.progressTimer = setInterval(function() { if (i < 75) { i++; } return that.progressBar.transitionTo(i, 100); }, 50); }; ImageEditor.prototype.onRequestEnd = function(response, status, request) { clearInterval(this.progressTimer); this.progressTimer = null; this.progressNotification.hide(); if (this.jCropApi != null) { this.jCropApi.destroy(); } this.jCropApi = null; this.forms.simple.attr("data-changed", false); this.forms.advanced.attr("data-changed", false); this.image[0].src = "data:image/jpeg;base64," + base64Encode(response); this.progressBar.transitionTo(1, 1); return this.progressBar.resetAfter(1000); }; ImageEditor.prototype.onRequestProgress = function(e) { clearInterval(this.progressTimer); if (e.lengthComputable) { return this.progressBar.transitionTo(Math.round(e.loaded / e.total * 25) + 75, 100); } }; ImageEditor.prototype.handleCropEnable = function() { var that; if ((this.jCropApi != null)) { return this.jCropApi.enable(); } else { that = this; return this.image.Jcrop({ onChange: this.handleCropSelect, onSelect: this.handleCropSelect, onRelease: this.handleCropRelease }, function() { return that.jCropApi = this; }); } }; ImageEditor.prototype.handleCropDisable = function() { return this.jCropApi.disable(); }; ImageEditor.prototype.handleCropSelect = function(c) { if (this.cropDisableCounter > 1) { this.fields.crop.x.val(Math.round(c.x / this.imageDimensions.width * this.imageDimensions.naturalWidth + this.imageDimensions.cropX)); this.fields.crop.y.val(Math.round(c.y / this.imageDimensions.height * this.imageDimensions.naturalHeight + this.imageDimensions.cropY)); this.fields.crop.width.val(Math.round(c.w / this.imageDimensions.width * this.imageDimensions.naturalWidth)); return this.fields.crop.height.val(Math.round(c.h / this.imageDimensions.height * this.imageDimensions.naturalHeight)); } else { return this.cropDisableCounter++; } }; ImageEditor.prototype.handleCropInputChange = function() { var x, y; if (this.jCropApi == null) { return; } x = this.fields.crop.x.val() / this.imageDimensions.naturalWidth * this.imageDimensions.width - this.imageDimensions.cropX; y = this.fields.crop.y.val() / this.imageDimensions.naturalHeight * this.imageDimensions.height - this.imageDimensions.cropY; this.cropDisableCounter = 0; return this.jCropApi.setSelect([x, y, x + this.fields.crop.width.val() / this.imageDimensions.naturalWidth * this.imageDimensions.width, y + this.fields.crop.height.val() / this.imageDimensions.naturalHeight * this.imageDimensions.height]); }; ImageEditor.prototype.handleCropRelease = function() { this.fields.crop.x.val(0); this.fields.crop.y.val(0); this.fields.crop.width.val(0); return this.fields.crop.height.val(0); }; ImageEditor.prototype.handleResizeInputChange = function(e) { var name, value; if (this.fields.resize.keepAspectRatio[0].checked) { name = e.target.name; value = $(e.target).val(); console.log(name, value); if (name === 'resize[width]') { return this.fields.resize.height.val(Math.round(value / this.imageDimensions.ratio)); } else { return this.fields.resize.width.val(Math.round(value * this.imageDimensions.ratio)); } } }; ImageEditor.list = []; ImageEditor.initialize = function() { return $("." + ImageEditor.classes.layout.container).each(function() { return ImageEditor.list.push(new ImageEditor($(this))); }); }; ImageEditor.classes = { layout: { container: "ImageEditor", image: "ImageEditor-image" }, button: { toggleFullscreen: "ImageEditor-toggleFullscreen", save: "ImageEditor-save", apply: "ImageEditor-apply" }, form: { simple: "ImageEditor-form--simple", advanced: "ImageEditor-form--advanced", progressBar: "ImageEditor-progress", crop: "ImageEditor-crop-input", resize: "ImageEditor-resize-input" } }; return ImageEditor; })(); Oxygen.initLogin = function() { var loginForm; loginForm = $(".Login-form").addClass("Login--noTransition").addClass("Login--slideDown"); loginForm[0].offsetHeight; loginForm.removeClass("Login--noTransition"); setTimeout(function() { $("body").removeClass("Login--isHidden"); }, 500); $(".Login-scrollDown").on("click", function() { $(".Login-message").addClass("Login--slideUp"); loginForm.removeClass("Login--slideDown"); $(".Login-background--blur").addClass("Login--isHidden"); }); loginForm.on("submit", function() { loginForm.addClass("Login--slideUp"); }); Ajax.handleErrorCallback = function() { loginForm.removeClass("Login--slideUp"); }; Ajax.handleSuccessCallback = function(data) { console.log(data); if (data.status === "failed") { loginForm.removeClass("Login--slideUp"); } }; }; base64Encode = function(inputStr) { var b64, byte1, byte2, byte3, enc1, enc2, enc3, enc4, i, outputStr; b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; outputStr = ""; i = 0; while (i < inputStr.length) { byte1 = inputStr.charCodeAt(i++) & 0xff; byte2 = inputStr.charCodeAt(i++) & 0xff; byte3 = inputStr.charCodeAt(i++) & 0xff; enc1 = byte1 >> 2; enc2 = ((byte1 & 3) << 4) | (byte2 >> 4); enc3 = void 0; enc4 = void 0; if (isNaN(byte2)) { enc3 = enc4 = 64; } else { enc3 = ((byte2 & 15) << 2) | (byte3 >> 6); if (isNaN(byte3)) { enc4 = 64; } else { enc4 = byte3 & 63; } } outputStr += b64.charAt(enc1) + b64.charAt(enc2) + b64.charAt(enc3) + b64.charAt(enc4); } return outputStr; }; MainNav.headroom(); Oxygen.init = function() { setTimeout(Notification.initializeExistingMessages, 250); Dialog.registerEvents(); if (typeof editors !== "undefined" && editors !== null) { Editor.createEditors(editors); } ImageEditor.initialize(); if ($(".Login-form").length > 0) { Oxygen.initLogin(); } Dropdown.registerEvents(); Form.findAll(); Upload.registerEvents(); TabSwitcher.findAll(); Slider.findAll(); }; Oxygen.init(); /*Oxygen.smoothState = $("#page").smoothState({ anchors: ".Link--smoothState" onStart: { duration: 250 render: (url, container) -> Oxygen.smoothState.toggleAnimationClass('Page--isExiting') $("html, body").animate({ scrollTop: 0 }) return }, onEnd: { duration: 0 render: (url, container, content) -> $("html, body").css('cursor', 'auto'); $("html, body").find('a').css('cursor', 'auto'); container.html(content); return *Oxygen.init() } }).data('smoothState'); */ }).call(this);
/* * PLUGIN LookAt * * Ukrainian language file. * * Author: */ theUILang.lookAtDesc = "Find at (Format: name|url)"; theUILang.lookAt = "Find at"; thePlugins.get("lookat").langLoaded();
// @flow /* eslint-disable no-use-before-define */ import type { ChildProcess } from 'child_process' import type { Chalk } from 'chalk' export type PackageVersions = { [string]: string } export type PackageWatcher = { start: () => void, stop: () => void, } export type PackagePaths = { monoRepoRoot: string, monoRepoRootNodeModules: string, packageBuildOutput: string, packageEntryFile: string, packageJson: string, packageLockJson: string, packageNodeModules: string, packageRoot: string, packageSrc: string, packageWebpackCache: string, } export type BuildPlugin = { name: string, clean: () => Promise<mixed>, build: () => Promise<mixed>, } export type DeployPath = string export type DeployPlugin = { name: string, deploy: DeployPath => Promise<mixed>, } export type DevelopInstance = { kill: () => Promise<void>, } export type DevelopPlugin = { name: string, develop: PackageWatcher => Promise<DevelopInstance>, } export type PackagePlugins = { buildPlugin: ?BuildPlugin, deployPlugin: ?DeployPlugin, developPlugin: ?DevelopPlugin, } export type Package = { config: Object, color: Chalk, dependants: Array<string>, dependencies: Array<string>, devDependencies: Array<string>, maxPackageNameLength: number, name: string, packageJson: Object, packageName: string, paths: PackagePaths, plugins: PackagePlugins, version: string, } export type PackageMap = { [string]: Package } declare module 'execa' { declare type ExecaChildProcess = ChildProcess & Promise<string, Error> declare type Execa = ( cmd: string, args: ?Array<string>, opts: ?Object, ) => ExecaChildProcess declare type ExecaStatics = { spawn: Execa, sync: ChildProcess, } declare type ExecaWithStatics = Execa & ExecaStatics declare module.exports: ExecaWithStatics }
'use strict'; /** * Test function. */ function foo() { } // end FUNCTION foo() // EXPORTS // module.exports = foo;
// Agent Class //====================================== class Agent { constructor(i, x, y, creator) { this.i = i; this.x = x; this.y = y; this.Xpos, this.Ypos; // set random direction 0-5 this.dir = Math.floor(random(0, 6)); // set its morality this.creator = creator; } update() { // get current triangle by x, y var curTriangle = grid[this.x][this.y]; this.Xpos = curTriangle.posX; this.Ypos = curTriangle.posY; // increment or decrement activity // if creator and not double active if (this.creator) { if (!curTriangle.active) { curTriangle.active = true; } } // if destroyer and active else { if (curTriangle.active) { curTriangle.active = false; } } // randomly chose direction -1 to 1 this.dir += -1 + Math.floor(random(4)); // make direction wrap around 0-5 this.dir = wrap3(this.dir); // get next triangle from current's neighbours var nextTriangle = curTriangle.neighbours[this.dir]; // if next triangle doesn't exist turn around if (nextTriangle === false) { this.dir = wrap3(this.dir+1); nextTriangle = curTriangle.neighbours[this.dir]; // if that doesn't work it's a corner // return and try again next round if (nextTriangle === false) return; } // update x and y from next triangle this.x = nextTriangle.pos.x; this.y = nextTriangle.pos.y; } draw() { if(!this.creator){ fill('darkred'); }else { fill('azure'); } ellipse(this.Xpos,this.Ypos,radius/6,radius/6); } } function wrap3(num) { // -1 => 5 // 0 => 0 // 5 => 5 // 6 => 0 // 7 => 1 return (num+4) % 4; }
/* |-------------------------------------------------------------------------- | Browser-sync config file |-------------------------------------------------------------------------- | | For up-to-date information about the options: | http://www.browsersync.io/docs/options/ | | There are more options than you see here, these are just the ones that are | set internally. See the website for more info. | | */ module.exports = { "ui": { "port": 3001, "weinre": { "port": 8080 } }, "files": false, "watchEvents": [ "change" ], "watchOptions": { "ignoreInitial": true }, "server": { "baseDir": "./build", "index": "index.html" }, "proxy": false, "port": 5678, "middleware": false, "serveStatic": [], "ghostMode": { "clicks": true, "scroll": true, "forms": { "submit": true, "inputs": true, "toggles": true } }, "logLevel": "info", "logPrefix": "BS", "logConnections": false, "logFileChanges": true, "logSnippet": true, "rewriteRules": [], "open": "local", "browser": "default", "cors": false, "xip": false, "hostnameSuffix": false, "reloadOnRestart": false, "notify": true, "scrollProportionally": true, "scrollThrottle": 0, "scrollRestoreTechnique": "window.name", "scrollElements": [], "scrollElementMapping": [], "reloadDelay": 0, "reloadDebounce": 0, "reloadThrottle": 0, "plugins": [], "injectChanges": true, "startPath": null, "minify": true, "host": null, "localOnly": false, "codeSync": true, "timestamps": true, "clientEvents": [ "scroll", "scroll:element", "input:text", "input:toggles", "form:submit", "form:reset", "click" ], "socket": { "socketIoOptions": { "log": false }, "socketIoClientConfig": { "reconnectionAttempts": 50 }, "path": "/browser-sync/socket.io", "clientPath": "/browser-sync", "namespace": "/browser-sync", "clients": { "heartbeatTimeout": 5000 } }, "tagNames": { "less": "link", "scss": "link", "css": "link", "jpg": "img", "jpeg": "img", "png": "img", "svg": "img", "gif": "img", "js": "script" } };
let React = require('react'); React.render();
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h10v-2H4v-6h18V6c0-1.11-.89-2-2-2zm0 4H4V6h16v2zm4 9v2h-3v3h-2v-3h-3v-2h3v-3h2v3h3z" }), 'AddCardOutlined');
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M6 17.59 7.41 19 12 14.42 16.59 19 18 17.59l-6-6z" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "m6 11 1.41 1.41L12 7.83l4.59 4.58L18 11l-6-6z" }, "1")], 'KeyboardDoubleArrowUpOutlined'); exports.default = _default;
"use strict" // Module for running a tutorial introducing a user to Context // This tutorial shows popups on whatever page they're on to show them // how context can be used var context = context || {}; context.runTutorial = (function($) { // we can't return the funtion directly, because we need jQuery return function() { var autoshowEnabled = true; // TUTORIAL PROGRESS ====================================================== // These functions are not automatically run, rather they are called as // the tutorial progresses var startTutorial = function() { // center pane var xPos = ($(window).width() - context.TUTORIAL_WIDTH)/2; var yPos = ($(window).height() - context.TUTORIAL_HEIGHT)/3; tutorialPane.moveCustom(xPos, yPos, context.TUTORIAL_WIDTH, 'animate'); var iframe = $('<iframe src="' + chrome.extension.getURL('/templates/tutorial1.html') + '" width="' + context.TUTORIAL_WIDTH + '" height="' + context.TUTORIAL_HEIGHT + 'px"></iframe>'); tutorialPane.empty(); tutorialPane.appendContent(iframe); } var runTutorialStep = function(stepNum) { if(stepNum === 3) { // Disable autoshow for the tutorial about disabling autoshowEnabled = false; } else { autoshowEnabled = true; } var iframe = $('<iframe src="' + chrome.extension.getURL('/templates/tutorial' + stepNum + '.html') + '" width="' + context.TUTORIAL_WIDTH + '" height="' + context.TUTORIAL_HEIGHT + 'px"></iframe>'); tutorialPane.empty({ fade: true, callAfter: function() { tutorialPane.appendContent(iframe, context.TUTORIAL_HEIGHT, {fade: true}); } }); } // INITIALIZE AND DISPLAY PANE ============================================ // If the user is in the middle of the tutorial, some things behave // differently // first, get the appropriate location for tutorial popup var window_width = $(window).width(); var width = context.TUTORIAL_WIDTH; var xPos = window_width - (context.PANE_PADDING_WIDTH*2) - width; var yPos = context.PANE_PADDING_HEIGHT*3; var tutorialBranding = $('<iframe src="' + chrome.extension.getURL('/templates/tutorial-branding.html') + '" width="' + context.TUTORIAL_WIDTH + '" height="' + context.BRANDING_HEIGHT + '"></iframe>'); var tutorialPane = new context.HoverPane({ sticky: true, brandingContent: tutorialBranding, fixed: true }); // tutorial pane must have Z dialed back so that other messages can pop up // over the pane (such as error messages) tutorialPane.setZ(tutorialPane.getZ() - 5); tutorialPane.moveCustom(xPos, yPos, width, 0); var iframe = $('<iframe src="' + chrome.extension.getURL('/templates/tutorial-intro.html') + '" width="' + tutorialPane.getWidth() + '" height="' + context.TUTORIAL_INTRO_HEIGHT + '"></iframe>'); tutorialPane.appendContent(iframe); // SET UP DEMO PANE ======================================================= // Rather than interfering with the default hoverpane that the main content // script manages, create a 'demo pane' that will be hovered next to the // tutorial pane var demoBranding = $('<iframe src="' + chrome.extension.getURL('/templates/demo-branding.html') + '" width="' + context.MAX_WIDTH + '" height="' + context.BRANDING_HEIGHT + '"></iframe>'); var demoPane = new context.HoverPane({ brandingContent: demoBranding }); // SET UP LISTENERS ======================================================= window.addEventListener(context.TUTORIAL_CLOSE_MESSAGE, function(event) { tutorialPane.hide(); }, false); chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if(sender.id !== chrome.runtime.id) { return; } // Listen for a message to kill the tutorial // When the user interacts with a tutorial on one page, all other // tutorials are killed (for example, if the user opens five tabs in // quick sequence, the tutorials on all pages but the one the user is actively using should // be killed as quickly as possible) if(request.action === 'killTutorial') { tutorialPane.hide(); } // Listeners for messages coming from the tutorial iframes if(request.action === 'tutorial-close') { tutorialPane.hide(); } if(request.action === 'tutorial-start') { startTutorial(); } if(request.action === 'tutorial-step1') { runTutorialStep(1); } if(request.action === 'tutorial-step2') { runTutorialStep(2); } if(request.action === 'tutorial-step3') { runTutorialStep(3); } if(request.action === 'tutorial-end') { tutorialPane.hide(); } if(request.action === 'tutorial-create-hoverpane') { // Check if user has banned autoshow if(request.autoshow === true && !autoshowEnabled) { return; } context.contentRetriever.insertDataIntoPane(request.query, demoPane, tutorialPane.pane); } if(request.action === 'tutorial-close-demo') { demoPane.hide(); } if(request.action === 'blacklist-demo') { autoshowEnabled = false; demoPane.hide(); } } ); }; })(jQuery);
// @flow import type { PlayerDescriptor } from "./PlayerDescriptor"; export type PlayerState = { // The player's immutable descriptor descriptor: PlayerDescriptor, // The UUID of the player id: string, // The ID of the zone of this player's hand handZone: string, // The ID of the zone of this player's library libraryZone: string };
/** * 命名空间构造器 * @returns {Function} * @constructor * @require System,Object; */ function Namespace(prefix, uri) { this.__prefix__ = prefix || ''; this.__uri__ = uri || ''; } Namespace.valueOf=Namespace.toString=function () {return '[object Namespace]'}; Namespace.prototype = Object.create( Object.prototype ); Namespace.prototype.__prefix__=''; Namespace.prototype.__uri__=''; Namespace.prototype.constructor = Namespace; Namespace.prototype.toString=function (){return '[object Namespace]'}; Namespace.prototype.valueOf =function valueOf() { return this.__prefix__+this.__uri__; }; System.Namespace = Namespace;
import React, {Component} from 'react'; import {render} from 'react-dom'; import Switch from 'react-toggle-switch'; import 'styles/styles.scss'; class Example extends Component { constructor(props) { super(props); this.state = { on: true } } render() { return ( <div className="row"> <div className="card col-sm"> <div className="card-body"> <p>Basic</p> <Switch onClick={() => this.setState({on: !this.state.on})} on={this.state.on}/> </div> </div> <div className="card col-sm"> <div className="card-body"> <p>With Children</p> <Switch onClick={() => this.setState({on: !this.state.on})} on={this.state.on}> <i className="fa fa-bolt" style={{position: 'relative', left: '8px', top: '-1px'}}></i> </Switch> </div> </div> <div className="card col-sm"> <div className="card-body"> <p>Disabled</p> <Switch onClick={() => this.setState({on: !this.state.on})} on={this.state.on} enabled={false}/> </div> </div> <div className="card col-sm"> <div className="card-body"> <p>Custom Classnames</p> <Switch onClick={() => this.setState({on: !this.state.on})} on={this.state.on} className="other-class"/> </div> </div> </div> ); } } render(<Example/>, document.getElementById('app'));
import express from 'express'; import { twitterService } from '../service'; import createCachedRouterCallback from '../helper/routerHelper'; const router = express.Router(); router.get('/feed', createCachedRouterCallback(twitterService.getLatestTweetForHashtag.bind(twitterService))); export default router;
/* eslint-env mocha */ /* eslint-disable padded-blocks, no-unused-expressions */ import React from 'react'; import chaiEnzyme from 'chai-enzyme' import chai, { expect } from 'chai'; import { render } from 'enzyme'; chai.use(chaiEnzyme()); import App from '../App'; import Layout from '../Layout'; import ImageToolbar from './ImageToolbar'; describe('ImageToolbar', () => { it('renders images correctly', () => { let imageUrls = [ 'assets/img/cooperglasses.jpg', 'assets/img/rainbowcoat.jpg', 'assets/img/yellowtoyscruffy.jpg', ]; const renderImageToolbar = render( <App context={{ insertCss: () => {}, fetch: () => {} }}> <Layout> <ImageToolbar images={imageUrls} /> </Layout> </App>, ); let imageToolbar = renderImageToolbar.find('.image-toolbar'); let images = imageToolbar.find('img'); // Check all images are rendered expect(images.length).to.eq(3); // Check all image URLs appear in toolbar for(let i = 0; i < imageUrls.length; i++) { expect(renderImageToolbar.html()).to.contain(imageUrls[i]); } }); });
// Variable wrapper (function (require, module) { 'use strict'; var logger = require('./logger.js'); var Ref = function (val) { var that = this; this.internalValue = val; this.internalType = typeof (val); Object.defineProperty(this, 'value', { get: function () { return that.internalValue; }, set: function (value) { if (that.internalType !== typeof (value)) { logger.warn('Type of value: ' + typeof (value) + ' does not match type of reference: ' + that.internalType ); } that.internalValue = value; } }); }; module.exports = Ref; })(require, module);
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.5-4-133 description: > Object.create - 'configurable' property of one property in 'Properties' is a positive number (8.10.5 step 4.b) includes: [runTestCase.js] ---*/ function testcase() { var newObj = Object.create({}, { prop: { configurable: 123 } }); var beforeDeleted = newObj.hasOwnProperty("prop"); delete newObj.prop; var afterDeleted = newObj.hasOwnProperty("prop"); return beforeDeleted === true && afterDeleted === false; } runTestCase(testcase);
/* * Copyright (c) 2014 Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ define(function (require, exports) { "use strict"; var Promise = require("bluebird"), _ = require("lodash"); var textLayerLib = require("adapter/lib/textLayer"), descriptor = require("adapter/ps/descriptor"), documentLib = require("adapter/lib/document"), layerLib = require("adapter/lib/layer"); var layerActions = require("./layers"), events = require("../events"), locks = require("js/locks"), collection = require("js/util/collection"), locking = require("js/util/locking"), math = require("js/util/math"), strings = require("i18n!nls/strings"), layerActionsUtil = require("js/util/layeractions"); /** * Minimum and maximum Photoshop-supported font sizes * * @const * @type {number} */ var PS_MIN_FONT_SIZE = 0.04, PS_MAX_FONT_SIZE = 5400; /** * play/batchPlay options that allow the canvas to be continually updated, * and history state to be consolidated * * @private * @param {number} documentID * @param {string} name localized name to put into the history state * @param {boolean} modal is the app in a modal state * @param {boolean=} coalesce Whether to coalesce this operations history state * @param {object=} options Inherited into the type options returned, if present * @return {object} options */ var _getTypeOptions = function (documentID, name, modal, coalesce, options) { var typeOptions = { paintOptions: { immediateUpdate: true, quality: "draft" }, canExecuteWhileModal: true, ignoreTargetWhenModal: true }; if (!modal) { typeOptions.historyStateInfo = { name: name, target: documentLib.referenceBy.id(documentID), coalesce: !!coalesce, suppressHistoryStateNotification: !!coalesce }; } return _.merge({}, options, typeOptions); }; /** * Update the post script (in terms of a type family and type style) of the given * layers in the given document. * * @param {Document} document * @param {Immutable.Iterable.<Layers>} layers * @param {string} postscript Post script name of the described typeface * @param {string} family The type face family name, e.g., "Helvetica Neue" * @param {string} style The type face style name, e.g., "Oblique" * @return {Promise} */ var updatePostScript = function (document, layers, postscript, family, style) { var layerIDs = collection.pluck(layers, "id"), payload = { documentID: document.id, layerIDs: layerIDs, postscript: postscript, family: family, style: style }; return this.dispatchAsync(events.document.TYPE_FACE_CHANGED, payload); }; updatePostScript.reads = []; updatePostScript.writes = [locks.JS_DOC]; updatePostScript.modal = true; /** * Set the post script (in terms of a type family and type style) of the given * layers in the given document. This triggers a layer bounds update. * * @param {Document} document * @param {Immutable.Iterable.<Layers>} layers * @param {string} postscript Post script name of the described typeface * @param {string} family The type face family name, e.g., "Helvetica Neue" * @param {string} style The type face style name, e.g., "Oblique" * @return {Promise} */ var setPostScript = function (document, layers, postscript, family, style) { var layerIDs = collection.pluck(layers, "id"), layerRefs = layerIDs.map(textLayerLib.referenceBy.id).toArray(), modal = this.flux.store("tool").getModalToolState(); var setFacePlayObject = textLayerLib.setPostScript(layerRefs, postscript), typeOptions = _getTypeOptions(document.id, strings.ACTIONS.SET_TYPE_FACE, modal), setFacePromise = locking.playWithLockOverride(document, layers, setFacePlayObject, typeOptions), updatePromise = this.transfer(updatePostScript, document, layers, postscript, family, style); return Promise.join(updatePromise, setFacePromise).bind(this).then(function () { if (!modal) { return this.transfer(layerActions.resetBounds, document, layers); } }); }; setPostScript.reads = [locks.JS_DOC]; setPostScript.writes = [locks.PS_DOC, locks.JS_UI]; setPostScript.transfers = [updatePostScript, layerActions.resetBounds]; setPostScript.modal = true; /** * Update the type face (in terms of a type family and type style) of the given * layers in the given document. * * @param {Document} document * @param {Immutable.Iterable.<Layers>} layers * @param {string} family The type face family name, e.g., "Helvetica Neue" * @param {string} style The type face style name, e.g., "Oblique" * @return {Promise} */ var updateFace = function (document, layers, family, style) { var layerIDs = collection.pluck(layers, "id"), payload = { documentID: document.id, layerIDs: layerIDs, family: family, style: style }; return this.dispatchAsync(events.document.TYPE_FACE_CHANGED, payload); }; updateFace.reads = []; updateFace.writes = [locks.JS_DOC]; updateFace.modal = true; /** * Set the type face (in terms of a type family and type style) of the given * layers in the given document. This triggers a layer bounds update. * * @param {Document} document * @param {Immutable.Iterable.<Layers>} layers * @param {string} family The type face family name, e.g., "Helvetica Neue" * @param {string} style The type face style name, e.g., "Oblique" * @return {Promise} */ var setFace = function (document, layers, family, style) { var layerIDs = collection.pluck(layers, "id"), layerRefs = layerIDs.map(textLayerLib.referenceBy.id).toArray(), modal = this.flux.store("tool").getModalToolState(); var setFacePlayObject = textLayerLib.setFace(layerRefs, family, style), typeOptions = _getTypeOptions(document.id, strings.ACTIONS.SET_TYPE_FACE, modal), setFacePromise = locking.playWithLockOverride(document, layers, setFacePlayObject, typeOptions), updatePromise = this.transfer(updateFace, document, layers, family, style); return Promise.join(updatePromise, setFacePromise).bind(this).then(function () { if (!modal) { return this.transfer(layerActions.resetBounds, document, layers); } }); }; setFace.reads = [locks.JS_DOC]; setFace.writes = [locks.JS_UI, locks.PS_DOC]; setFace.transfers = [updateFace, layerActions.resetBounds]; setFace.modal = true; /** * Update the type of the given layers in the given document. The alpha value of * the color is used to adjust the opacity of the given layers. * * @param {Document} document * @param {Immutable.Iterable.<Layers>} layers * @param {Color} color * @param {boolean} modal is the app in a modal state, which effects history * @param {object} options * @param {boolean=} options.coalesce Whether to coalesce this operation's history state * @param {boolean=} options.ignoreAlpha * @return {Promise} */ var updateColor = function (document, layers, color, modal, options) { var layerIDs = collection.pluck(layers, "id"), normalizedColor = null; if (color !== null) { normalizedColor = color.normalizeAlpha(); } var payload = { documentID: document.id, layerIDs: layerIDs, color: normalizedColor, coalesce: options.coalesce, ignoreAlpha: options.ignoreAlpha }; if (!modal) { return this.dispatchAsync(events.document.history.optimistic.TYPE_COLOR_CHANGED, payload); } else { return this.dispatchAsync(events.document.TYPE_COLOR_CHANGED, payload); } }; updateColor.reads = []; updateColor.writes = [locks.JS_DOC]; updateColor.modal = true; /** * Set the type of the given layers in the given document. The alpha value of * the color is used to adjust the opacity of the given layers. * * @param {Document} document * @param {Immutable.Iterable.<Layers>} layers * @param {Color} color * @param {object} options * @param {boolean=} options.coalesce Whether to coalesce this operation's history state * @param {boolean=} options.ignoreAlpha Whether to ignore the alpha value of the * given color and only update the opaque color value. * @return {Promise} */ var setColor = function (document, layers, color, options) { var layerIDs = collection.pluck(layers, "id"), layerRefs = layerIDs.map(textLayerLib.referenceBy.id).toArray(), normalizedColor = color.normalizeAlpha(), opaqueColor = normalizedColor.opaque(), playObject = textLayerLib.setColor(layerRefs, opaqueColor), modal = this.flux.store("tool").getModalToolState(), typeOptions = _getTypeOptions(document.id, strings.ACTIONS.SET_TYPE_COLOR, modal, options.coalesce, options); if (!options.ignoreAlpha) { var opacity = Math.round(normalizedColor.opacity), setOpacityPlayObjects = layers.map(function (layer) { var layerRef = [ documentLib.referenceBy.id(document.id), layerLib.referenceBy.id(layer.id) ]; return layerLib.setOpacity(layerRef, opacity); }).toArray(); playObject = [playObject].concat(setOpacityPlayObjects); } var updatePromise = this.transfer(updateColor, document, layers, color, modal, options), setColorPromise = layerActionsUtil.playSimpleLayerActions(document, layers, playObject, true, typeOptions); return Promise.join(updatePromise, setColorPromise); }; setColor.reads = [locks.JS_DOC]; setColor.writes = [locks.PS_DOC]; setColor.transfers = [updateColor]; setColor.modal = true; /** * Update our type size to reflect the type size of the given layers in the given document. * * @param {Document} document * @param {Immutable.Iterable.<Layers>} layers * @param {number} size The type size in pixels, e.g., 72 * @return {Promise} */ var updateSize = function (document, layers, size) { var layerIDs = collection.pluck(layers, "id"), payload = { documentID: document.id, layerIDs: layerIDs, size: size }; return this.dispatchAsync(events.document.TYPE_SIZE_CHANGED, payload); }; updateSize.reads = []; updateSize.writes = [locks.JS_DOC]; updateSize.modal = true; /** * Set the type size of the given layers in the given document. This triggers * a layer bounds update. * * @param {Document} document * @param {Immutable.Iterable.<Layers>} layers * @param {number} size The type size in pixels, e.g., 72 * @return {Promise} */ var setSize = function (document, layers, size) { var layerIDs = collection.pluck(layers, "id"), layerRefs = layerIDs.map(textLayerLib.referenceBy.id).toArray(), modal = this.flux.store("tool").getModalToolState(); // Ensure that size does not exceed PS font size bounds size = math.clamp(size, PS_MIN_FONT_SIZE, PS_MAX_FONT_SIZE); var setSizePlayObject = textLayerLib.setSize(layerRefs, size, "px"), typeOptions = _getTypeOptions(document.id, strings.ACTIONS.SET_TYPE_SIZE, modal), setSizePromise = locking.playWithLockOverride(document, layers, setSizePlayObject, typeOptions), updatePromise = this.transfer(updateSize, document, layers, size); return Promise.join(updatePromise, setSizePromise).bind(this).then(function () { if (!modal) { return this.transfer(layerActions.resetBounds, document, layers); } }); }; setSize.reads = [locks.JS_DOC]; setSize.writes = [locks.JS_UI, locks.PS_DOC]; setSize.transfers = [updateSize, layerActions.resetBounds]; setSize.modal = true; /** * Update the tracking value (aka letter-spacing) of the given layers in the given document. * * @param {Document} document * @param {Immutable.Iterable.<Layers>} layers * @param {number} tracking The tracking value * @return {Promise} */ var updateTracking = function (document, layers, tracking) { var layerIDs = collection.pluck(layers, "id"), payload = { documentID: document.id, layerIDs: layerIDs, tracking: tracking }; return this.dispatchAsync(events.document.TYPE_TRACKING_CHANGED, payload); }; updateTracking.reads = []; updateTracking.writes = [locks.JS_DOC]; updateTracking.modal = true; /** * Set the tracking value (aka letter-spacing) of the given layers in the given document. * This triggers a layer bounds update. * * @param {Document} document * @param {Immutable.Iterable.<Layers>} layers * @param {number} tracking The tracking value * @return {Promise} */ var setTracking = function (document, layers, tracking) { var layerIDs = collection.pluck(layers, "id"), layerRefs = layerIDs.map(textLayerLib.referenceBy.id).toArray(), modal = this.flux.store("tool").getModalToolState(), psTracking = tracking / 1000; // PS expects tracking values that are 1/1000 what is shown in the UI var setTrackingPlayObject = textLayerLib.setTracking(layerRefs, psTracking), typeOptions = _getTypeOptions(document.id, strings.ACTIONS.SET_TYPE_TRACKING, modal), setTrackingPromise = locking.playWithLockOverride(document, layers, setTrackingPlayObject, typeOptions), updatePromise = this.transfer(updateTracking, document, layers, tracking); return Promise.join(updatePromise, setTrackingPromise).bind(this).then(function () { if (!modal) { return this.transfer(layerActions.resetBounds, document, layers); } }); }; setTracking.reads = [locks.JS_DOC]; setTracking.writes = [locks.PS_DOC, locks.JS_UI]; setTracking.transfers = [updateTracking, layerActions.resetBounds]; setTracking.modal = true; /** * Update the leading value (aka line-spacing) of the given layers in the given document. * * @param {Document} document * @param {Immutable.Iterable.<Layers>} layers * @param {number} leading The leading value in pixels, or if null then auto. * @return {Promise} */ var updateLeading = function (document, layers, leading) { var layerIDs = collection.pluck(layers, "id"), payload = { documentID: document.id, layerIDs: layerIDs, leading: leading }; return this.dispatchAsync(events.document.TYPE_LEADING_CHANGED, payload); }; updateLeading.reads = []; updateLeading.writes = [locks.JS_DOC]; updateLeading.modal = true; /** * Set the leading value (aka line-spacing) of the given layers in the given document. * This triggers a layer bounds update. * * @param {Document} document * @param {Immutable.Iterable.<Layers>} layers * @param {number} leading The leading value in pixels, or if null then auto. * @return {Promise} */ var setLeading = function (document, layers, leading) { var layerIDs = collection.pluck(layers, "id"), layerRefs = layerIDs.map(textLayerLib.referenceBy.id).toArray(), modal = this.flux.store("tool").getModalToolState(), autoLeading = leading === -1; if (!autoLeading && leading < 0.1) { leading = 0.1; } var setLeadingPlayObject = textLayerLib.setLeading(layerRefs, autoLeading, leading, "px"), typeOptions = _getTypeOptions(document.id, strings.ACTIONS.SET_TYPE_LEADING, modal), setLeadingPromise = locking.playWithLockOverride(document, layers, setLeadingPlayObject, typeOptions), updatePromise = this.transfer(updateLeading, document, layers, leading); return Promise.join(updatePromise, setLeadingPromise).bind(this).then(function () { if (!modal) { return this.transfer(layerActions.resetBounds, document, layers); } }); }; setLeading.reads = [locks.JS_DOC]; setLeading.writes = [locks.PS_DOC, locks.JS_UI]; setLeading.transfers = [updateLeading, layerActions.resetBounds]; setLeading.modal = true; /** * Update the paragraph alignment of the given layers in the given document. * * @param {Document} document * @param {Immutable.Iterable.<Layers>} layers * @param {string} alignment The alignment kind * @return {Promise} */ var updateAlignment = function (document, layers, alignment) { var layerIDs = collection.pluck(layers, "id"), payload = { documentID: document.id, layerIDs: layerIDs, alignment: alignment }; return this.dispatchAsync(events.document.TYPE_ALIGNMENT_CHANGED, payload); }; updateAlignment.reads = []; updateAlignment.writes = [locks.JS_DOC]; updateAlignment.modal = true; /** * Set the paragraph alignment of the given layers in the given document. * This triggers a layer bounds update. * * @param {Document} document * @param {Immutable.Iterable.<Layers>} layers * @param {string} alignment The alignment kind * @param {object} options Batch play options * @return {Promise} */ var setAlignment = function (document, layers, alignment, options) { var layerIDs = collection.pluck(layers, "id"), layerRefs = layerIDs.map(textLayerLib.referenceBy.id).toArray(), modal = this.flux.store("tool").getModalToolState(); var setAlignmentPlayObject = textLayerLib.setAlignment(layerRefs, alignment), typeOptions = _getTypeOptions(document.id, strings.ACTIONS.SET_TYPE_ALIGNMENT, modal, false, options), setAlignmentPromise = locking.playWithLockOverride(document, layers, setAlignmentPlayObject, typeOptions), transferPromise = this.transfer(updateAlignment, document, layers, alignment); return Promise.join(transferPromise, setAlignmentPromise).bind(this).then(function () { if (!modal) { return this.transfer(layerActions.resetBounds, document, layers); } }); }; setAlignment.reads = [locks.JS_DOC]; setAlignment.writes = [locks.PS_DOC, locks.JS_UI]; setAlignment.transfers = [updateAlignment, layerActions.resetBounds]; setAlignment.modal = true; /** * Update the given layer models with all the provided text properties. * TODO: Ideally, this would subsume all the other type update actions. * Note: this is action does NOT update history * * @param {Document} document * @param {Immutable.Iterable.<Layer>} layers * @param {object} properties May contain properties found in CharacterStyle and ParagraphStyle models * @return {Promise} */ var updateProperties = function (document, layers, properties) { var payload = { documentID: document.id, layerIDs: collection.pluck(layers, "id"), properties: properties }; return this.dispatchAsync(events.document.TYPE_PROPERTIES_CHANGED, payload); }; updateProperties.reads = []; updateProperties.writes = [locks.JS_DOC]; updateProperties.transfers = []; updateProperties.modal = true; /** * Duplicates the layer effects of the source layer on all the target layers * * @param {Document} document * @param {Immutable.Iterable.<Layer>} targetLayers * @param {Layer} source * @return {Promise} */ var duplicateTextStyle = function (document, targetLayers, source) { var layerIDs = collection.pluck(targetLayers, "id"), layerRefs = layerIDs.map(textLayerLib.referenceBy.id).toArray(), fontStore = this.flux.store("font"), typeObject = fontStore.getTypeObjectFromLayer(source), applyObj = textLayerLib.applyTextStyle(layerRefs, typeObject); return descriptor.playObject(applyObj) .bind(this) .then(function () { return this.transfer(layerActions.resetLayers, document, targetLayers); }); }; duplicateTextStyle.reads = [locks.JS_TYPE, locks.JS_DOC]; duplicateTextStyle.writes = [locks.PS_DOC]; duplicateTextStyle.transfers = [layerActions.resetLayers]; /** * Applies the given text style to target layers * * @param {Document} document * @param {?Immutable.Iterable.<Layer>} targetLayers Default is selected layers * @param {object} style Style object * @param {object} options Batch play options * @return {Promise} */ var applyTextStyle = function (document, targetLayers, style, options) { targetLayers = targetLayers || document.layers.selected; var layerIDs = collection.pluck(targetLayers, "id"), layerRefs = layerIDs.map(textLayerLib.referenceBy.id).toArray(), applyObj = textLayerLib.applyTextStyle(layerRefs, style); this.dispatchAsync(events.style.HIDE_HUD); return layerActionsUtil.playSimpleLayerActions(document, targetLayers, applyObj, true, options) .bind(this) .then(function () { return this.transfer(layerActions.resetLayers, document, targetLayers); }); }; applyTextStyle.reads = [locks.JS_DOC]; applyTextStyle.writes = [locks.PS_DOC]; applyTextStyle.transfers = [layerActions.resetLayers]; /** * Initialize the list of installed fonts from Photoshop. * * @private * @return {Promise} */ var initFontList = function () { return descriptor.getProperty("application", "fontList") .bind(this) .then(this.dispatch.bind(this, events.font.INIT_FONTS)); }; initFontList.reads = [locks.PS_APP]; initFontList.writes = [locks.JS_TYPE]; initFontList.modal = true; exports.setPostScript = setPostScript; exports.updatePostScript = updatePostScript; exports.setFace = setFace; exports.updateFace = updateFace; exports.setColor = setColor; exports.updateColor = updateColor; exports.setSize = setSize; exports.updateSize = updateSize; exports.setTracking = setTracking; exports.updateTracking = updateTracking; exports.setLeading = setLeading; exports.updateLeading = updateLeading; exports.setAlignment = setAlignment; exports.initFontList = initFontList; exports.updateAlignment = updateAlignment; exports.updateProperties = updateProperties; exports.duplicateTextStyle = duplicateTextStyle; exports.applyTextStyle = applyTextStyle; });
var Configuration = {}; Configuration.configuration_file = 'config.json'; Configuration.load = function() { if (!fs.existsSync(this.configuration_file)) { this.data = {}; } else { var data = fs.readFileSync(this.configuration_file, {encoding: 'utf8'}); this.data = JSON.parse(data); } return this.data; }; Configuration.save = function(redmine_site, redmine_key) { var data = { redmine_site: redmine_site, redmine_key: redmine_key, }; if (this.data && this.data.redmine_key === data.redmine_key && this.data.redmine_site === data.redmine_site) { console.log('same!'); return; } fs.writeFileSync(this.configuration_file, JSON.stringify(data, null, "\t")); };
(function(JsSIP) { var Logger = function(logger, category, label) { this.logger = logger; this.category = category; this.label = label; }; Logger.prototype.debug = function(content) { this.logger.debug(this.category, this.label, content); }; Logger.prototype.log = function(content) { this.logger.log(this.category, this.label, content); }; Logger.prototype.warn = function(content) { this.logger.warn(this.category, this.label, content); }; Logger.prototype.error = function(content) { this.logger.error(this.category, this.label, content); }; JsSIP.Logger = Logger; }(JsSIP));
/** * @module batcher * @summary: Provides batcher.chunk to chunk a collection and do something with each chunk. * * @description: * * Author: justin * Created On: 2015-03-27. * @license Apache-2.0 */ module.exports = (function construct() { var m = {}; m.chunk = function(collection, chunkSize, func) { var results = []; for(var i=0; i<collection.length; i+=chunkSize) { var chunk = collection.slice(i, i+chunkSize); results.push(func(chunk)); } return results; }; m.retry = function(options, details) { var details = details || { retryAttemptsSoFar: 0, errors: [], deferred: p.defer() }; options.action().then(function(result) { details.deferred.resolve(result); }).then(null, function(err) { details.errors.push(err); if (details.retryAttemptsSoFar >= options.maxRetryCount) { if (options.onError) options.onError(err); details.deferred.reject(details); return; } details.retryAttemptsSoFar++; setTimeout(function() { m.retry(options, details); }, options.timeoutMS); }); return details.deferred.promise; }; return m; })();
var chai = require('chai'), expect = chai.expect, sinon = require('sinon'), sinonPromise = require('sinon-promise'), proxyquire = require('proxyquire'); chai.use(require('sinon-chai')); describe('lib/bowerDependencies', function () { var bwd, exec, log, spinner, fs, installLog; beforeEach(function () { exec = sinon.stub(); log = { info: sinon.spy(), bower: sinon.spy() }; spinner = { start: sinon.stub(), stop: sinon.spy() }; fs = { readFileSync: sinon.stub() }; fs.readFileSync .withArgs(sinon.match(/bower_components\/angular\/bower.json$/)) .returns('{"main": "./angular.js"}'); fs.readFileSync .withArgs(sinon.match(/bower_components\/node-libspotify\/bower.json$/)) .returns('{"main": "./lib/spotify.js"}'); spinner.start.returns(spinner); installLog = [ 'bower angular#* cached git://github.com/angular/bower-angular.git#1.3.9', 'bower angular#* validate 1.3.9 against git://github.com/angular/bower-angular.git#*', 'bower node-libspotify#* cached git://github.com/JohanObrink/node-libspotify.git#0.1.0', 'bower node-libspotify#* validate 0.1.0 against git://github.com/JohanObrink/node-libspotify.git#*', 'bower angular#~1.3.9 install angular#1.3.9', 'bower node-libspotify#~0.1.0 install node-libspotify#0.1.0', '', 'angular#1.3.9 bower_components/angular', '', 'node-libspotify#0.1.0 bower_components/node-libspotify' ].join('\n'); bwd = proxyquire(process.cwd() + '/lib/bowerDependencies', { 'child_process': { exec: exec }, 'q': sinonPromise.Q, 'fs': fs, './log': log, './spinner': spinner }); }); describe('#install', function () { var success, fail; beforeEach(function () { success = sinon.spy(); fail = sinon.spy(); bwd.install('-D', 'angular', 'git://github.com/JohanObrink/node-libspotify.git#0.1.0').then(success).catch(fail); }); it('logs what is being installed', function () { expect(log.info).calledOnce.calledWith('bower install -D angular git://github.com/JohanObrink/node-libspotify.git#0.1.0'); }); it('starts the spinner', function () { expect(spinner.start).calledOnce; }); it('calls exec with the correct parameters', function () { expect(exec).calledOnce.calledWith('bower install -D angular git://github.com/JohanObrink/node-libspotify.git#0.1.0'); }); it('stops spinner when install is done', function () { exec.yield(null, '', ''); expect(spinner.stop).calledOnce; }); it('resolves promise when exec is done without errors', function () { exec.yield(null, '', ''); expect(fail).not.called; expect(success).calledOnce; }); it('rejects promise when exec is done with errors', function () { exec.yield('Err!', '', ''); expect(success).not.called; expect(fail).calledOnce.calledWith('Err!'); }); describe('resolve with path from packet', function () { it('tries to load bower.json', function () { exec.yield(null, installLog, ''); expect(fs.readFileSync).calledTwice; expect(fs.readFileSync).calledWithMatch(/bower_components\/angular\/bower.json$/); expect(fs.readFileSync).calledWithMatch(/bower_components\/node-libspotify\/bower.json$/); }); it('gets the main from bower.json', function () { exec.yield(null, installLog, ''); expect(success).calledWith(['bower_components/angular/angular.js', 'bower_components/node-libspotify/lib/spotify.js']); }); }); }); });
// All symbols in the `Osmanya` script as per Unicode v6.2.0: [ '\uD801\uDC80', '\uD801\uDC81', '\uD801\uDC82', '\uD801\uDC83', '\uD801\uDC84', '\uD801\uDC85', '\uD801\uDC86', '\uD801\uDC87', '\uD801\uDC88', '\uD801\uDC89', '\uD801\uDC8A', '\uD801\uDC8B', '\uD801\uDC8C', '\uD801\uDC8D', '\uD801\uDC8E', '\uD801\uDC8F', '\uD801\uDC90', '\uD801\uDC91', '\uD801\uDC92', '\uD801\uDC93', '\uD801\uDC94', '\uD801\uDC95', '\uD801\uDC96', '\uD801\uDC97', '\uD801\uDC98', '\uD801\uDC99', '\uD801\uDC9A', '\uD801\uDC9B', '\uD801\uDC9C', '\uD801\uDC9D', '\uD801\uDCA0', '\uD801\uDCA1', '\uD801\uDCA2', '\uD801\uDCA3', '\uD801\uDCA4', '\uD801\uDCA5', '\uD801\uDCA6', '\uD801\uDCA7', '\uD801\uDCA8', '\uD801\uDCA9' ];
// LICENSE : MIT "use strict"; import React from "react" import {Table} from "reactable" import moment from "moment"; export default class DataTableView extends React.Component { _calc(data) { if (!data) { return []; } let keywords = Object.keys(data); if (keywords.length === 0) { return []; } // yyyy-mm-dd let dateKeyList = data[keywords[0]].map(({date}) => date); let results = dateKeyList.map(dateKey => { var dateString = moment(dateKey, "YYYY-MM-DD").format("YYYY-MM"); let result = {"Date": dateString}; keywords.forEach(keyword => { let dataList = data[keyword]; let hitObject = dataList.filter(({date}) => date === dateKey)[0]; result[keyword] = hitObject.count; }); return result; }); return results; } render() { let data = this._calc(this.props.data); return <div className="DataTableView"> <Table className="table" data={data}/> </div> } }
'use strict' const { MessageEmbed } = require('discord.js'); const Matcher = require('did-you-mean'); const stripIndents = require('common-tags').stripIndents; const config = require('config.json')('./config.json'); const abilities = require("../data/abilities.js"); const aliases = require("../data/aliases.js"); const items = require("../data/items.js"); const learnsets = require("../data/learnsets.js"); const moves = require("../data/moves.js"); const pokedex = require("../data/pokedex.js"); const typechart = require("../data/typechart.js"); const spriteoverrides = require("../data/spriteoverrides.js"); let dtextrender = function(data) { let keys = Object.keys(data), length = keys.length; let dtext, ptext = ''; for (let i=0; i<length; i++) { let curKey = keys[i]; if (data[curKey] === '') { ptext += `**✓** ${curKey}\n`; } else { dtext += `**${curKey}:** ${data[curKey]}\n`; } } return {dtext: dtext, ptext: ptext}; } let getSprite = function(pkmn, dir='xyani', format='gif') { let pngName = function(str) { return str.toLowerCase().replace(" ", "").replace('-', ''); } let text; if (pkmn.hasOwnProperty('forme')) { text = pngName(pkmn.baseSpecies) + '-' + pngName(pkmn.forme); } else { text = pngName(pkmn.species); } if (spriteoverrides.hasOwnProperty(text)) { return spriteoverrides[text]; } return `http://play.pokemonshowdown.com/sprites/${dir}/${text}.${format}`; } class EmbedGenerator { constructor(parser) { this.parser = parser; } quick(title, text) { return new MessageEmbed() .setDescription(text) .setTitle(title) .setColor(config.embedColor) .setTimestamp(); } generateAbilityEmbed(ability, parser) { return new MessageEmbed() .setDescription(ability.desc ? ability.desc : ability.shortDesc) .setAuthor(ability.name) .setColor(config.embedColor) .setTimestamp(); } generatePokemonEmbed(pokemon, parser) { let weakChart = parser.weak(pokemon); console.log(getSprite(pokemon)); return new MessageEmbed() .setAuthor(`${pokemon.num.toString()} - ${pokemon.species}`) .setColor(config.embedColor) .setThumbnail(getSprite(pokemon)) .setTimestamp() .addField('Stats', stripIndents` **HP:** ${pokemon.baseStats.hp} **Atk:** ${pokemon.baseStats.atk} **Def:** ${pokemon.baseStats.def} **SpA:** ${pokemon.baseStats.spa} **SpD:** ${pokemon.baseStats.spd} **Spe:** ${pokemon.baseStats.spe} **BST:** ${Object.values(pokemon.baseStats).reduce((a, b) => a + b, 0)}`) .addField(`Types`, `${pokemon.types.join(", ")}`) .addField(`Abilities`, `${Object.values(pokemon.abilities).join(", ")}`) .addField(`Weakness & Resistance`,`${weakChart["Bug"] != 1 ? `\n**Bug**: ${weakChart["Bug"]}`: ""}` + `${weakChart["Dark"] != 1 ? `\n**Dark**: ${weakChart["Dark"]}`: ""}` + `${weakChart["Dragon"] != 1 ? `\n**Dragon**: ${weakChart["Dragon"]}`: ""}` + `${weakChart["Electric"] != 1 ? `\n**Electric**: ${weakChart["Electric"]}`: ""}` + `${weakChart["Fairy"] != 1 ? `\n**Fairy**: ${weakChart["Fairy"]}`: ""}` + `${weakChart["Fighting"] != 1 ? `\n**Fighting**: ${weakChart["Fighting"]}`: ""}` + `${weakChart["Fire"] != 1 ? `\n**Fire**: ${weakChart["Fire"]}`: ""}` + `${weakChart["Flying"] != 1 ? `\n**Flying**: ${weakChart["Flying"]}`: ""}` + `${weakChart["Ghost"] != 1 ? `\n**Ghost**: ${weakChart["Ghost"]}`: ""}` + `${weakChart["Grass"] != 1 ? `\n**Grass**: ${weakChart["Grass"]}`: ""}` + `${weakChart["Ground"] != 1 ? `\n**Ground**: ${weakChart["Ground"]}`: ""}` + `${weakChart["Ice"] != 1 ? `\n**Ice**: ${weakChart["Ice"]}`: ""}` + `${weakChart["Normal"] != 1 ? `\n**Normal**: ${weakChart["Normal"]}`: ""}` + `${weakChart["Poison"] != 1 ? `\n**Poison**: ${weakChart["Poison"]}`: ""}` + `${weakChart["Psychic"] != 1 ? `\n**Psychic**: ${weakChart["Psychic"]}`: ""}` + `${weakChart["Rock"] != 1 ? `\n**Rock**: ${weakChart["Rock"]}`: ""}` + `${weakChart["Steel"] != 1 ? `\n**Steel**: ${weakChart["Steel"]}`: ""}` + `${weakChart["Water"] != 1 ? `\n**Water**: ${weakChart["Water"]}`: ""}`) .addField(`Misc`, stripIndents`**Height (M):** ${pokemon.heightm} **Weight (KG):** ${pokemon.weightkg} **Color:** ${pokemon.color}`) } generateItemEmbed(item, parser) { return new MessageEmbed() .setDescription(`${item.desc}`) .setAuthor(item.name) .setColor(config.embedColor) .setThumbnail(`https://www.serebii.net/itemdex/sprites/pgl/${item.id}.png`) .setTimestamp(); } generateMoveEmbed(move, parser) { let details = { "Priority": move.priority, "Gen": move.gen || 'CAP', }; if (move.secondary || move.secondaries) details["Secondary effect"] = ""; if (move.flags['contact']) details["Contact"] = ""; if (move.flags['sound']) details["Sound"] = ""; if (move.flags['bullet']) details["Bullet"] = ""; if (move.flags['pulse']) details["Pulse"] = ""; if (!move.flags['protect'] && !/(ally|self)/i.test(move.target)) details["Bypasses Protect"] = ""; if (move.flags['authentic']) details["Bypasses Substitutes"] = ""; if (move.flags['defrost']) details["Thaws user"] = ""; if (move.flags['bite']) details["Bite"] = ""; if (move.flags['punch']) details["Punch"] = ""; if (move.flags['powder']) details["Powder"] = ""; if (move.flags['reflectable']) details["Bounceable"] = ""; if (move.flags['gravity']) details["Suppressed by Gravity"] = ""; if (move.zMovePower) { details["Z-Power"] = move.zMovePower; } else if (move.zMoveEffect) { details["Z-Effect"] = { 'clearnegativeboost': "Restores negative stat stages to 0", 'crit2': "Crit ratio +2", 'heal': "Restores HP 100%", 'curse': "Restores HP 100% if user is Ghost type, otherwise Attack +1", 'redirect': "Redirects opposing attacks to user", 'healreplacement': "Restores replacement's HP 100%", }[move.zMoveEffect]; } else if (move.zMoveBoost) { details["Z-Effect"] = ""; let boost = move.zMoveBoost; let stats = {atk: 'Attack', def: 'Defense', spa: 'Sp. Atk', spd: 'Sp. Def', spe: 'Speed', accuracy: 'Accuracy', evasion: 'Evasiveness'}; for (let i in boost) { details["Z-Effect"] += " " + stats[i] + " +" + boost[i]; } } else { details["Z-Effect"] = "None"; } details["Target"] = { 'normal': "One Adjacent Pokmon", 'self': "User", 'adjacentAlly': "One Ally", 'adjacentAllyOrSelf': "User or Ally", 'adjacentFoe': "One Adjacent Opposing Pokmon", 'allAdjacentFoes': "All Adjacent Opponents", 'foeSide': "Opposing Side", 'allySide': "User's Side", 'allyTeam': "User's Side", 'allAdjacent': "All Adjacent Pokmon", 'any': "Any Pokmon", 'all': "All Pokmon", }[move.target] || "Unknown"; if (move.id === 'mirrormove') { details['https://pokemonshowdown.com/dex/moves/mirrormove'] = ''; } const { dtext, ptext } = dtextrender(details); return new MessageEmbed() .setAuthor(`${move.name}`) .setColor(config.embedColor) .setDescription(stripIndents` ${move.desc}`) .setTimestamp() .addField(`Info`, stripIndents` **Type:** ${move.type} **Category:** ${move.category} **Base Power:** ${move.hasOwnProperty('basePower') ? move.basePower : 'N/A'} ${dtext}`, true) .addField('Properties', ptext ? ptext : 'No special properties', true); } generateWeakEmbed(weakChart, full) { if (full) { return new MessageEmbed() .setDescription(stripIndents` \n*Damage multiplyers for ${weakChart.pokemon}* **Bug**: ${weakChart["Bug"]} **Dark**: ${weakChart["Dark"]} **Dragon**: ${weakChart["Dragon"]} **Electric**: ${weakChart["Electric"]} **Fairy**: ${weakChart["Fairy"]} **Fighting**: ${weakChart["Fighting"]} **Fire**: ${weakChart["Fire"]} **Flying**: ${weakChart["Flying"]} **Ghost**: ${weakChart["Ghost"]} **Grass**: ${weakChart["Grass"]} **Ground**: ${weakChart["Ground"]} **Ice**: ${weakChart["Ice"]} **Normal**: ${weakChart["Normal"]} **Poison**: ${weakChart["Poison"]} **Psychic**: ${weakChart["Psychic"]} **Rock**: ${weakChart["Rock"]} **Steel**: ${weakChart["Steel"]} **Water**: ${weakChart["Water"]} `) .setAuthor(weakChart.pokemon) .setColor(config.embedColor) .setTimestamp(); } else { return new MessageEmbed() .setDescription(stripIndents` \n*Damage multiplyers for ${weakChart.pokemon}* *1x values are ommited use \`weak ${weakChart.pokemon} true\` to show.*` + `${weakChart["Bug"] != 1 ? `\n**Bug**: ${weakChart["Bug"]}`: ""}` + `${weakChart["Dark"] != 1 ? `\n**Dark**: ${weakChart["Dark"]}`: ""}` + `${weakChart["Dragon"] != 1 ? `\n**Dragon**: ${weakChart["Dragon"]}`: ""}` + `${weakChart["Electric"] != 1 ? `\n**Electric**: ${weakChart["Electric"]}`: ""}` + `${weakChart["Fairy"] != 1 ? `\n**Fairy**: ${weakChart["Fairy"]}`: ""}` + `${weakChart["Fighting"] != 1 ? `\n**Fighting**: ${weakChart["Fighting"]}`: ""}` + `${weakChart["Fire"] != 1 ? `\n**Fire**: ${weakChart["Fire"]}`: ""}` + `${weakChart["Flying"] != 1 ? `\n**Flying**: ${weakChart["Flying"]}`: ""}` + `${weakChart["Ghost"] != 1 ? `\n**Ghost**: ${weakChart["Ghost"]}`: ""}` + `${weakChart["Grass"] != 1 ? `\n**Grass**: ${weakChart["Grass"]}`: ""}` + `${weakChart["Ground"] != 1 ? `\n**Ground**: ${weakChart["Ground"]}`: ""}` + `${weakChart["Ice"] != 1 ? `\n**Ice**: ${weakChart["Ice"]}`: ""}` + `${weakChart["Normal"] != 1 ? `\n**Normal**: ${weakChart["Normal"]}`: ""}` + `${weakChart["Poison"] != 1 ? `\n**Poison**: ${weakChart["Poison"]}`: ""}` + `${weakChart["Psychic"] != 1 ? `\n**Psychic**: ${weakChart["Psychic"]}`: ""}` + `${weakChart["Rock"] != 1 ? `\n**Rock**: ${weakChart["Rock"]}`: ""}` + `${weakChart["Steel"] != 1 ? `\n**Steel**: ${weakChart["Steel"]}`: ""}` + `${weakChart["Water"] != 1 ? `\n**Water**: ${weakChart["Water"]}`: ""}` ) .setAuthor(weakChart.pokemon) .setColor(config.embedColor) .setTimestamp(); } } generateLearnEmbed(learn) { let { pokemon, move, ret, suc } = learn; if (suc) { let final = ""; for (let i=1; i<=ret.length; i++) { final = final + `** **- gen ${ret[i-1].generation} ${ret[i-1].source} \n` } return new MessageEmbed() .setAuthor(`${pokedex.BattlePokedex[pokemon].species} can learn ${moves.BattleMovedex[move].name}!`) .setColor(config.embedColor) .setDescription(final) .setTimestamp() } else { return new MessageEmbed() .setAuthor(`${pokemon} can't learn ${move}!`) .setColor(config.embedColor) .setDescription(ret) .setTimestamp() } } } class Parser { constructor(client) { this.client = client; this.EmbedGenerator = new EmbedGenerator(this); this.types = ["ability", "pokemon", "item", "move"]; this.generators = { "ability": this.EmbedGenerator.generateAbilityEmbed, "pokemon": this.EmbedGenerator.generatePokemonEmbed, "item": this.EmbedGenerator.generateItemEmbed, "move": this.EmbedGenerator.generateMoveEmbed, } this.dataArrays = { "ability": abilities.BattleAbilities, "pokemon": pokedex.BattlePokedex, "item": items.BattleItems, "move": moves.BattleMovedex } let match = Object.keys(this.dataArrays[this.types[0]]); for (let i=1; i<this.types.length; i++) { match = match.concat(Object.keys(this.dataArrays[this.types[i]])); } this.match = match; } getAliasOf(alias) { alias = alias.toLowerCase(); if (aliases.BattleAliases.hasOwnProperty(alias)) return aliases.BattleAliases[alias]; else return false; } parseAbility(name) { let m = new Matcher(Object.keys(abilities.BattleAbilities).join(" ")); m.setThreshold(3); if (!abilities.BattleAbilities.hasOwnProperty(name) && m.get(name)) name = m.get(name); name = name.toLowerCase().replace(" ", ""); if (abilities.BattleAbilities.hasOwnProperty(name)) return abilities.BattleAbilities[name]; else throw new ReferenceError(`${name} is not an ability!`, 'dataparser.js', 102); } parsePokemon(name) { let m = new Matcher(Object.keys(pokedex.BattlePokedex).join(" ")); m.setThreshold(3); if (!pokedex.BattlePokedex.hasOwnProperty(name) && m.get(name)) name = m.get(name); name = name.toLowerCase().replace(" ", ""); if (pokedex.BattlePokedex.hasOwnProperty(name)) return pokedex.BattlePokedex[name]; else return false; } parseItem(name) { let m = new Matcher(Object.keys(items.BattleItems).join(" ")); m.setThreshold(3); if (!items.BattleItems.hasOwnProperty(name) && m.get(name)) name = m.get(name); name = name.toLowerCase().replace(" ", ""); if (items.BattleItems.hasOwnProperty(name)) return items.BattleItems[name]; else throw new ReferenceError(`${name} is not an item!`, 'dataparser.js', 102); } parseMove(name) { let m = new Matcher(Object.keys(items.BattleItems).join(" ")); m.setThreshold(3); if (!moves.BattleMovedex.hasOwnProperty(name) && m.get(name)) name = m.get(name); name = name.toLowerCase().replace(" ", ""); if (moves.BattleMovedex.hasOwnProperty(name)) return moves.BattleMovedex[name]; else throw new ReferenceError(`${name} is not a move!`, 'dataparser.js', 102); } parse(name) { let m = new Matcher(this.match.join(" ")); m.setThreshold(3); for (let i=0; i<this.types.length; i++) { let type = this.types[i]; if (this.dataArrays[type].hasOwnProperty(name)) { // If the name is in the array return this.generators[type](this.dataArrays[type][name], this); } else if (m.get(name)){ name = m.get(name); if (this.dataArrays[type].hasOwnProperty(name)) return this.generators[type](this.dataArrays[type][name], this); } } return false; } getSprite(pkmn, dir='xyani', format='gif') { pkmn = this.parsePokemon(pkmn); return getSprite(pkmn, dir, format); } shuffle(array) { let currentIndex = array.length, temporaryValue, randomIndex; // While there remain elements to shuffle... while (0 !== currentIndex) { // Pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; // And swap it with the current element. temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; } learn(pokemon, move) { let { BattleLearnsets } = learnsets; let moveMatcher = new Matcher(Object.keys(moves.BattleMovedex).join(" ")); moveMatcher.setThreshold(3); if (!moves.BattleMovedex.hasOwnProperty(move) && moveMatcher.get(move)) move = moveMatcher.get(move); move = move.toLowerCase().replace(" ", ""); if (!moves.BattleMovedex.hasOwnProperty(move)) return {ret: `${move} is not a move!`, pokemon: pokemon, suc: false, move: move}; let monMatcher = new Matcher(Object.keys(pokedex.BattlePokedex).join(" ")); monMatcher.setThreshold(3); if (!pokedex.BattlePokedex.hasOwnProperty(pokemon) && monMatcher.get(pokemon)) pokemon = monMatcher.get(pokemon); pokemon = pokemon.toLowerCase().replace(" ", ""); if (!BattleLearnsets[pokemon]) return {ret: `${pokemon} is not a pokemon!`, pokemon: pokemon, suc: false, move: move}; let pokemonLearnsets = BattleLearnsets[pokemon].learnset; if (!Object.keys(pokemonLearnsets).includes(move)) return {ret: `${move} not found in ${pokemon}'s learnset!`, pokemon: pokemon, suc: false, move: move}; // Pokemon can learn move let sourceNames = {E:"egg", S:"event", D:"dream world", M: "technical or hidden machine", L: "level [level]", T: "tutor", V:"virtual console transfer from gen 1", E:"egg", Y:"event, traded back"}; let souceID = Object.keys(sourceNames); let learnMethod = BattleLearnsets[pokemon].learnset[move]; let ret = []; for (let i=1; i<=learnMethod.length; i++) { let gen = parseInt(learnMethod[i-1].charAt()); let source = sourceNames[learnMethod[i-1].charAt(1)].replace("[level]", learnMethod[i-1].substring(2)); ret.push({ generation: gen, source, source }); } return {ret: ret, pokemon: pokemon,suc: true, move: move}; } weak(pokemon) { let types = Object.keys(typechart.BattleTypeChart); let weakChart = { pokemon: pokemon.species, "Bug": 1, "Dark": 1, "Dragon": 1, "Electric": 1, "Fairy": 1, "Fighting": 1, "Fire": 1, "Flying": 1, "Ghost": 1, "Grass": 1, "Ground": 1, "Ice": 1, "Normal": 1, "Poison": 1, "Psychic": 1, "Rock": 1, "Steel": 1, "Water": 1, }; for (let i=0; i<pokemon.types.length; i++) { let current = typechart.BattleTypeChart[pokemon.types[i]]; for (let x=0; x<types.length; x++) { let dmg = weakChart[types[x]]; switch (current.damageTaken[types[x]]) { case 3: weakChart[types[x]] = 0; break; case 2: weakChart[types[x]] = dmg / 2; break; case 1: weakChart[types[x]] = dmg * 2; break; } } } return weakChart; } } module.exports.Parser = Parser;
export default { today: 'Сьогодні', now: 'Зараз', backToToday: 'Поточна дата', ok: 'Ok', clear: 'Очистити', month: 'Місяць', year: 'Рік', timeSelect: 'Обрати час', dateSelect: 'Обрати дату', monthSelect: 'Обрати місяць', yearSelect: 'Обрати рік', decadeSelect: 'Обрати десятиріччя', yearFormat: 'YYYY', dateFormat: 'D-M-YYYY', dayFormat: 'D', dateTimeFormat: 'D-M-YYYY HH:mm:ss', monthBeforeYear: true, previousMonth: 'Попередній місяць (PageUp)', nextMonth: 'Наступний місяць (PageDown)', previousYear: 'Попередній рік (Control + left)', nextYear: 'Наступний рік (Control + right)', previousDecade: 'Попереднє десятиріччя', nextDecade: 'Наступне десятиріччя', previousCentury: 'Попереднє століття', nextCentury: 'Наступне століття', };
const Processor = require("./"), {date} = require('../util'), extend = require('extend'), jsexpr = require("jsexpr"); const DEF_CONF = { input : '${timestamp}', format : 'YYYY-MM-DD HH:mm:ss', output : 'date', fields : [] }; class DateformatProcessor extends Processor { constructor(id,type) { super(id,type); } configure(config, callback) { this.config = extend(true,{},DEF_CONF,config); this.field = jsexpr.expr(this.config.field || this.config.input); this.format = this.config.format; this.output = jsexpr.assign(this.config.output); this.fields = this.config.fields.map(f=>{ return { format : f.format, output : jsexpr.assign(f.output) }; }); this.flen = this.fields.length; callback(); } process(entry,callback) { let ts = date(this.field(entry)); let res = ts.format(this.format); this.output(entry,res); // extra fields let fields = this.fields, flen = this.flen; for(let i=0;i<flen;i++) { let f = fields[i]; f.output(entry,ts.format(f.format)); } callback(null,entry); } } module.exports = DateformatProcessor;
'use strict'; angular.module('services.config', []) .constant('configuration', { backend: '@@backend' });
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ const ssri = require("ssri"); const fs = require("fs"); const { version } = require("./package.json"); const readmeMdFilePath = "./README.md"; const cdnUsageFilePath = "./docs/cdn-usage.md"; const sriTableMarker = "<!-- SRI_TABLE_START -->"; const sriTableMarkerOffset = 3; const latestVersionMarker = "<!-- CDN_LATEST -->"; const latestVersionMarkerOffset = 2; const latestVersionString = `<script type="text/javascript" src="https://alcdn.msauth.net/lib/${version}/js/msal.min.js"></script>`; async function generateSris() { // Read contents of README md file const readmeMd = await fs.promises.readFile(readmeMdFilePath, "utf8"); const readMeMdLines = readmeMd.toString().split(/\r?\n/); // Update REAMDE const readmeInsertLineIndex = readMeMdLines.indexOf(latestVersionMarker); const readMeInsertIndex = readmeInsertLineIndex + latestVersionMarkerOffset; readMeMdLines.splice(readMeInsertIndex, 1, latestVersionString); // Write new README to disk const newReadMd = readMeMdLines.join("\n"); await fs.promises.writeFile(readmeMdFilePath, newReadMd); // Read contents of cdn md file const cdnMd = await fs.promises.readFile(cdnUsageFilePath, "utf8"); const cdnMdLines = cdnMd.toString().split(/\r?\n/); // Update basic usage const latestVersionInsertLineIndex = cdnMdLines.indexOf(latestVersionMarker); const latestVersionInsertIndex = latestVersionInsertLineIndex + latestVersionMarkerOffset; cdnMdLines.splice(latestVersionInsertIndex, 1, latestVersionString); // Generate entries for each file const unminifiedVersionSri = await generateSriTableEntry("msal.js", " "); const minifiedVersionSri = await generateSriTableEntry("msal.min.js", ""); // Add entries to table const sriInsertLineIndex = cdnMdLines.indexOf(sriTableMarker); const tableInsertIndex = sriInsertLineIndex + sriTableMarkerOffset; cdnMdLines.splice(tableInsertIndex, 0, minifiedVersionSri); cdnMdLines.splice(tableInsertIndex, 0, unminifiedVersionSri); // Write new file to disk const newCdnMd = cdnMdLines.join("\n"); await fs.promises.writeFile(cdnUsageFilePath, newCdnMd); } async function generateSriTableEntry(file, padding) { const filePath = `./dist/${file}`; const fileStream = fs.createReadStream(filePath); const sri = await ssri.fromStream(fileStream, { algorithms: [ "sha384" ] }); return `${version} | ${file}${padding} | \`${sri.toString()}\``; } generateSris() .then(() => { process.exit(0); }) .catch(error => { console.error(error); process.exit(1); });
'use strict'; const resourcePath = 'node_modules/'; const normalizeCssResource = resourcePath + 'normalize.css/normalize.css'; let destBase = 'build/'; let dest = { base: destBase, css: destBase + 'css/', js: destBase + 'js/', views: destBase + 'views/', static: destBase }; let appBase = 'app/'; let clientBase = appBase + 'client/'; let serverBase = appBase + 'server/'; module.exports = { build: { dest: dest }, assets: { client: { sass: [ { assets: [ clientBase + 'scss/main.scss', clientBase + 'scss/main_mq.scss' ] } ], css: [ { assets: [ normalizeCssResource, clientBase + 'css/main.css', clientBase + 'css/main_mq.css' ], dist: dest.css + 'main.css' } ], js: [ { entry: clientBase + 'js/index.js', dist: dest.js + 'main.js' } ], views: [ { assets: [ clientBase + 'views/slide.njk' ], dist: dest.views + 'main.js' } ], static: [ { assets: [ clientBase + 'fonts/*' ], dist: dest.base + 'fonts/' }, { assets: [ clientBase + 'images/*' ], dist: dest.base + 'images/' }, { assets: [ clientBase + 'root/*' ], dist: dest.base + '' } ] }, server: { allJS: ['config/**/*.js'], gulpConfig: 'gulpfile.js', views: [ { assets: [ serverBase + 'views/main.njk' ], dist: dest.base + 'index.html' } ] } } };
'use strict'; describe('Function Expressions', function () { /*Function Expressions*/ /*We can build functions within code execution rather than at program load time*/ it('Normal functions are built in memory when the program loads', function () { expect(typeof addTwoNumbers).toBe("function"); }); function addTwoNumbers(numberOne,numberTwo){ return numberOne+numberTwo; } it('Assigning functions to variables allows them to only load them when the runtime executes that line', function () { var subtract = function subtractTwoNumbers(numberOne,numberTwo){ //In Js we can assign a function to a variable return numberOne-numberTwo; }; expect(typeof subtract).toBe("function"); //The variable is still considered a function expect(subtract(3,2)).toBe(1);// Then we can call the function variable by name }); it('We can create Anonymous Functions without a name', function () { var multiply = function (numberOne,numberTwo){ //The function is being assigned to variable, therefore, we don't need a name return numberOne*numberTwo; }; expect(multiply(3,2)).toBe(6); }); it('A variable that holds a function can be passed into other functions', function () { var divideTenByTwo = function (){ return 10/2; }; var divideTenByFive = function (){ return 10/5; }; expect(executeOperation(divideTenByTwo)).toBe(5); expect(executeOperation(divideTenByFive)).toBe(2); }); function executeOperation(operation){//You can encapsulate common functionality in a function return operation(); } });
"use strict"; var fs = require('fs'); var path = require('path'); var errh = require('ncbt').errh; var Canvas = require('canvas'); var Image = Canvas.Image; var async = require('async'); var Grid = require('./grid'); var Abc = require('./abc'); var Page = function (data, opt_outPath) { this.data = data; this.outPath = opt_outPath || '.'; this.abc = null; this.grid = null; }; Page.prototype.name = null; Page.prototype.getAbc = function (cb) { return new Abc(this.img, this.grid, [ { chars: 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ', row: 0 }, { chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', row: 1 }, { chars: '0123456789', row: 1, serie: 1 } ]); }; Page.prototype.fill = function (cb) { this.render(false, cb); }; Page.prototype.test = function (cb) { this.render(true, cb); }; Page.prototype.render = function (isTest, cb) { var self = this; async.waterfall([ function (cb) { self.readImg(cb); }, function (cb) { self.grid = new Grid(self.img); self.abc = self.getAbc(); self.drawImg(); if (isTest) { self.grid.draw(self.ctx); } else { self.fillData(); } self.saveImg(isTest, cb); }], cb); }; Page.prototype.readImg = function (cb) { var self = this; fs.readFile( path.join(__dirname, '..', 'blanks', this.name+'.png'), errh(function(src, cb) { self.img = new Image(); self.img.onload = function () { cb(); }; self.img.onerror = function (err) { cb(err); }; self.img.src = src; }, cb)); }; Page.prototype.drawImg = function () { this.canvas = new Canvas(this.img.width, this.img.height); this.ctx = this.canvas.getContext('2d'); this.ctx.drawImage(this.img, 0, 0); }; Page.prototype.saveImg = function (isTest, cb) { var out = fs.createWriteStream(path.join(this.outPath, this.name+(isTest?'-test':'')+'.png')); var stream = this.canvas.createPNGStream(); stream.on('data', function (chunk){ out.write(chunk); }); stream.on('error', function (err){ cb(err); }); stream.on('end', function (){ cb(); }); }; Page.prototype.fillData = function () { }; Page.prototype.getTillDate = function () { var result = this.data['Срок пребывания']; if (result == 'default') { result = this.toDate(this.data['Дата въезда']); if (result.length === 0) { return null; } // 90 days by default var d = new Date(Date.UTC(result[2], result[1], result[0]) + 90 * 24 * 60 * 60 * 1000); result = [ this.zero2(d.getUTCDate()), this.zero2(d.getUTCMonth()), d.getUTCFullYear() ].join('.'); } return result; }; Page.prototype.zero2 = function (v) { v = '' + v; if (v.length == 1) { v = '0' + v; } return v; }; Page.prototype.toDate = function (v) { return v ? v.split('.') : []; }; Page.prototype.drawDateData = function (row, serie, dataKey) { this.drawDate(row, serie, this.data[dataKey]); }; Page.prototype.drawDate = function (row, serie, date) { if (date) { date = this.toDate(date); for (var i = 0; i < 3; i++) { this.draw(row, serie + i, date[i]); } } }; Page.prototype.drawGender = function (rowM, serieM, rowF, serieF, gender) { if (gender) { switch (gender) { case 'М': this.draw(rowM, serieM, 'X'); break; case 'Ж': this.draw(rowF, serieF, 'X'); break; default: console.log('WARN unknown Пол:', gender); } } }; Page.prototype.drawData = function (row, serie, dataKey, opt_offset) { this.draw(row, serie, this.data[dataKey], opt_offset); }; Page.prototype.draw = function (row, serie, str, opt_offset) { if (str) { str = str.toUpperCase(); this.abc.draw(this.ctx, this.grid.rows[row].series[serie], str, opt_offset); } }; module.exports = Page;
///////////////////////////////////////////////// // Map // Initialise the map, set center, zoom, etc. ///////////////////////////////////////////////// var map = L.map('map').setView(mobilesConfig.mapInitialView, 12); var filterLibrariesMap = function () { }; L.tileLayer('http://{s}.tiles.mapbox.com/v3/librarieshacked.jefmk67b/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); ////////////////////////////////////////////////////// // Autocomplete address search // Initial code to set up the autocomplete search box ////////////////////////////////////////////////////// var placeSearch, autocomplete; function initAutocomplete() { autocomplete = new google.maps.places.Autocomplete((document.getElementById('txtAddressSearch')), { types: ['geocode'] }); autocomplete.addListener('place_changed', populateNearest); } function populateNearest() { $('#divNearest').show(); $('#divNearest').empty(); $('#divNearestAdditional').empty(); var place = autocomplete.getPlace(); SomersetMobiles.setCurrentDistances(place.geometry.location.lat(), place.geometry.location.lng()); var nearest = SomersetMobiles.getNearest(); var nearestRoute = SomersetMobiles.routes[nearest[0]]; var nearestStop = nearestRoute.stops[nearest[1]]; $('#divNearest').html('<span class="lead">Nearest stop ' + nearestStop.location + ', ' + nearestStop.town + '. ' + 'Arriving ' + nearestStop.due + ' (' + moment(nearestStop.dueSystem).format('Do MMM hh:mma') + '). ' + nearestStop.currentDistance + ' miles away.</span>'); } ///////////////////////////// // Extend Leaflet Polyline. ///////////////////////////// L.Polyline = L.Polyline.extend({ getDistance: function (system) { // distance in meters var mDistance = 0; var length = this._latlngs.length; for (var i = 1; i < length; i++) { mDistance += this._latlngs[i].distanceTo(this._latlngs[i - 1]); } // optional if (system === 'imperial') { return Math.round(mDistance / 1609.34); } else { return Math.round(mDistance / 1000); } } }); ////////////////////////////////////////////////// // Following relies on jQuery etc so wait for page to complete ////////////////////////////////////////////////// $(function () { // Load data SomersetMobiles.loadData(function () { // First get how many mobile libraries we have. var libraries = SomersetMobiles.getLibraries(); $('#btnAllStops').on('click', function () { filterLibrariesMap('All'); return false; }); // Set up the HTML departure for each library $.each(libraries, function (key, lib) { $('#divDepartures').append('<div class="col col-lg-4 col-md-4">' + '<div class="alert alert-' + mobilesConfig.libBootswatchClass[lib] + '">' + lib + '<br />' + '<span id="sp' + lib + 'CurrentPosition"></span>' + '</div></div>'); $('#divMapFilters').append('<div class="btn-group">' + '<a href="#" id="btnAllStops' + lib + '" class="btn btn-sm btn-' + mobilesConfig.libBootswatchClass[lib] + '">' + lib + ' Stops <span class="badge" id="sp' + lib + 'StopCount"></span></a>' + '<a href="#" class="btn btn-sm btn-' + mobilesConfig.libBootswatchClass[lib] + ' dropdown-toggle" data-toggle="dropdown" aria-expanded="false"><span class="caret"></span></a>' + '<ul class="dropdown-menu" id="ul' + lib + 'Filter">' + '<li><a href="#" id="aAllStops' + lib + '">All ' + lib + ' stops</a></li>' + '<li class="divider"></li>' + '</ul></div> '); $('#btnAllStops' + lib + ',' + '#aAllStops' + lib).on('click', function () { filterLibrariesMap(lib); return false; }); }); ///////////////////////////////////////////// // Function: SetCurrentPositions // Sets the current positions for each library on the // departures board. //////////////////////////////////////////////// var setCurrentPositions = function () { $.each(libraries, function (key, lib) { // Get current and next positions. var current = SomersetMobiles.getCurrentLocation(lib); if (current) var currentRoute = SomersetMobiles.routes[current[0]]; if (current) var currentStop = currentRoute.stops[current[1]]; var next = SomersetMobiles.getNextLocation(lib); var nextRoute = SomersetMobiles.routes[next[0]]; var nextStop = nextRoute.stops[next[1]]; if (current != null) { $('#sp' + lib + 'CurrentPosition').html('<span class="lead">Currently at ' + currentStop.location + ', ' + currentStop.town + ' for another ' + moment(currentStop.departingSystem).diff(moment(), 'minutes') + ' minutes</span>'); } else { $('#sp' + lib + 'CurrentPosition').html('<span class="lead">Expected at ' + nextStop.location + ', ' + nextStop.town + ' ' + nextStop.due + '</span>'); } }); }; setCurrentPositions(); var markersArrays = {}; var markerGroups = {}; var markersBounds = {}; var routes = {}; $.each(SomersetMobiles.routes, function (key, val) { $.each(val.stops, function (k, v) { // Add items to the map. if (v.lat) { var popup = L.popup({ maxWidth: 160, maxHeight: 140, closeButton: false, className: '' }).setContent('<h4>' + v.location + ', ' + v.town + '</h4>' + moment(v.dueSystem).format('Do MMM hh:mma') + '<br/>' + 'Route ' + val.route + '<br/>' + v.duration + ' minute stop'); // Set up the associative arrays for layers and bounds if (!markersArrays[key]) markersArrays[key] = []; if (!markersBounds[key]) markersBounds[key] = []; var stopIcon = L.divIcon({ html: '<div><span>' + val.route + '</span></div>', className: "marker-cluster marker-cluster-" + val.library.toLowerCase(), iconSize: new L.Point(15, 15) }); markersArrays[key].push(L.marker([v.lat, v.lng], { icon: stopIcon }).bindPopup(popup, { className: val.library.toLowerCase() + '-popup' })); markersBounds[key].push([v.lat, v.lng]); } }); }); // Add marker groups for all the routes (and overall library) $.each(SomersetMobiles.routes, function (key, val) { // Add the library marker group if (!markerGroups[val.library]) { markerGroups[val.library] = L.featureGroup($.map(markersArrays, function (x, y) { if (y.indexOf(val.library) != -1) return x; })); } // Add the route marker group if (!markerGroups[val.library + val.route]) { markerGroups[val.library + val.route] = L.featureGroup($.map(markersArrays, function (x, y) { if (y == (val.library + val.route)) return x; })); } $('#ul' + val.library + 'Filter').append('<li><a href="#" id="aFilter' + val.library + val.route + '")">Route ' + val.route + '</a></li>'); $('#aFilter' + val.library + val.route).on('click', function () { filterLibrariesMap(val.library + val.route); $('body').trigger('click'); return false; }); }); // Initial setup - Add all libraries and the overall bounds $.each(libraries, function (key, lib) { map.addLayer(markerGroups[lib]); $('#sp' + lib + 'StopCount').text($.map(markersArrays, function (v, k) { if (k.indexOf(lib) != -1) return v; }).length); }); $('#spStopCount').text($.map(markersArrays, function (v, k) { return v; }).length); map.fitBounds($.map(markersBounds, function (val, key) { return val; })); var currentFilter = 'All'; // Set up the option to show either set of library stops filterLibrariesMap = function (filter) { $('#spQuickStats').html(''); if (currentFilter == filter) return false; if (currentFilter == 'All') { $.each(libraries, function (key, lib) { map.removeLayer(markerGroups[lib]); }); } else if (libraries.indexOf(currentFilter) != -1){ map.removeLayer(markerGroups[currentFilter]); } else { map.removeLayer(markerGroups[currentFilter]); // Only the individual routes have route lines on map.removeLayer(routes[currentFilter]); } if (filter == 'All') { $.each(libraries, function (key, lib) { map.addLayer(markerGroups[lib]); }); map.fitBounds($.map(markersBounds, function (val, key) { return val; })); } else { map.addLayer(markerGroups[filter]); var updateQuickStats = function (filter) { var className = mobilesConfig.libBootswatchClass[filter.substring(0, filter.length - 1)]; $('#spQuickStats').html('<span class="text-' + className + '">' + SomersetMobiles.routes[filter].library + ' Route ' + SomersetMobiles.routes[filter].route + ' quick stats.</span> ' + 'Distance travelled: <span class="text-' + className + '">' + routes[filter].getDistance('imperial') + ' miles</span>. ' + 'Number of stops: <span class="text-' + className + '">' + markersArrays[filter].length + '</span>'); }; if (libraries.indexOf(filter) != -1) { map.fitBounds($.map(markersBounds, function (val, key) { if (key.indexOf(filter) != -1) return val; })); var className = mobilesConfig.libBootswatchClass[filter]; var stopCount = 0; $.each(markersArrays, function (key,val) { if (key.indexOf(filter) != -1) stopCount += val.length; }); var duration = SomersetMobiles.getLibraryTotalHours(filter); $('#spQuickStats').html('<span class="text-' + className + '">' + filter + ' Mobile Library quick stats.</span> ' + 'Number of stops: <span class="text-' + className + '">' + stopCount + '</span> ' + 'Total duration: ' + duration); } else { // We also want to add the route lines if (!routes[filter]) { var routeLatLngs = []; var lineColour = mobilesConfig.routeColour[filter.substring(0, filter.length -1)]; SomersetMobiles.loadRoute(filter, function () { $.each(SomersetMobiles.routes[filter].routeLine, function (i, latlng) { routeLatLngs.push(L.latLng(latlng[0], latlng[1])); }); var routeLine = L.polyline(routeLatLngs, { color: lineColour, dashArray: '20,15', opacity: 0.4 }); routes[filter] = routeLine; map.addLayer(routes[filter]); // Update the quick stats bar updateQuickStats(filter); }); } else { map.addLayer(routes[filter]); } map.fitBounds($.map(markersBounds, function (val, key) { if (key == filter) return val; })); } } currentFilter = filter; return false; }; // Set up DataTable var table = $('#tblFullTimetable').dataTable( { processing: true, responsive: true, dom: 'Bfrtip', buttons: [ { extend: 'print', text: 'Print', className: 'btn-sm' }, { extend: 'excelHtml5', text: 'Export Excel', className: 'btn-sm' } ], deferRender: true, data: SomersetMobiles.getDataTable(), // We're expecting Mobile,Route,Day,Town,Location,Postcode,Due,Duration columns: [ { title: "Library" }, { title: "RouteID", visible: false }, { title: "Route" }, { title: "Day" }, { title: "Town" }, { title: "Location" }, { title: "Postcode" }, { title: "Due", iDataSort: 8 }, { title: "DueSystem", visible: false }, { title: "Duration" } ], order: [[8, 'asc']], drawCallback: function (settings) { var api = this.api(); var rows = api.rows({ page: 'current' }).nodes(); var last = null; api.column(7, { page: 'current' }).data().each(function (group, i) { if (group != '' && last !== group) { $(rows).eq(i).before( '<tr class="grouping"><td colspan="8">Due ' + group + '</td></tr>' ); last = group; } }); } }); // Page refresh setInterval(function () { setCurrentPositions(); }, 5000); }); });
import { inject as service } from '@ember/service'; import Mixin from '@ember/object/mixin'; import { assert } from '@ember/debug'; import { computed } from '@ember/object'; import { getOwner } from '@ember/application'; import Configuration from './../configuration'; /** __This mixin is used to make routes accessible only if the session is not authenticated__ (e.g., login and registration routes). It defines a `beforeModel` method that aborts the current transition and instead transitions to the {{#crossLink "Configuration/routeIfAlreadyAuthenticated:property"}}{{/crossLink}} if the session is authenticated. ```js // app/routes/login.js import UnauthenticatedRouteMixin from 'ember-simple-auth/mixins/unauthenticated-route-mixin'; export default Ember.Route.extend(UnauthenticatedRouteMixin); ``` @class UnauthenticatedRouteMixin @module ember-simple-auth/mixins/unauthenticated-route-mixin @extends Ember.Mixin @public */ export default Mixin.create({ /** The session service. @property session @readOnly @type SessionService @public */ session: service('session'), _isFastBoot: computed(function() { const fastboot = getOwner(this).lookup('service:fastboot'); return fastboot ? fastboot.get('isFastBoot') : false; }), /** The route to transition to if a route that implements the {{#crossLink "UnauthenticatedRouteMixin"}}{{/crossLink}} is accessed when the session is authenticated. @property routeIfAlreadyAuthenticated @type String @default 'index' @public */ routeIfAlreadyAuthenticated: computed(function() { return Configuration.routeIfAlreadyAuthenticated; }), /** Checks whether the session is authenticated and if it is aborts the current transition and instead transitions to the {{#crossLink "Configuration/routeIfAlreadyAuthenticated:property"}}{{/crossLink}}. __If `beforeModel` is overridden in a route that uses this mixin, the route's implementation must call `this._super(...arguments)`__ so that the mixin's `beforeModel` method is actually executed. @method beforeModel @param {Transition} transition The transition that lead to this route @public */ beforeModel() { if (this.get('session').get('isAuthenticated')) { let routeIfAlreadyAuthenticated = this.get('routeIfAlreadyAuthenticated'); assert('The route configured as Configuration.routeIfAlreadyAuthenticated cannot implement the UnauthenticatedRouteMixin mixin as that leads to an infinite transitioning loop!', this.get('routeName') !== routeIfAlreadyAuthenticated); this.transitionTo(routeIfAlreadyAuthenticated); } else { return this._super(...arguments); } } });
var WILL = { backgroundColor: Module.color.WHITE, color: Module.color.from(204, 204, 204), strokes: new Array(), init: function(width, height) { this.initInkEngine(width, height); this.initEvents(); }, initInkEngine: function(width, height) { this.canvas = new Module.InkCanvas(width, height); this.strokesLayer = this.canvas.createLayer(); this.clear(); this.brush = new Module.SolidColorBrush(); this.pathBuilder = new Module.SpeedPathBuilder(); this.pathBuilder.setNormalizationConfig(5, 210); this.pathBuilder.setPropertyConfig(Module.PropertyName.Width, 1, 3.2, NaN, NaN, Module.PropertyFunction.Sigmoid, 0.6, true); this.smoothener = new Module.MultiChannelSmoothener(this.pathBuilder.stride); this.strokeRenderer = new Module.StrokeRenderer(this.canvas); this.strokeRenderer.configure({brush: this.brush, color: this.color}); }, initEvents: function() { var self = this; $(Module.canvas).on("mousedown", function(e) {self.beginStroke(e);}); $(Module.canvas).on("mousemove", function(e) {self.moveStroke(e);}); $(document).on("mouseup", function(e) {self.endStroke(e);}); }, beginStroke: function(e) { if (e.button != 0) return; this.inputPhase = Module.InputPhase.Begin; this.buildPath({x: e.clientX, y: e.clientY}); this.strokeRenderer.draw(this.pathPart, false); this.strokeRenderer.blendUpdatedArea(); }, moveStroke: function(e) { if (!this.inputPhase) return; var self = this; this.pointerPos = {x: e.clientX, y: e.clientY}; this.inputPhase = Module.InputPhase.Move; if (this.intervalID) return; var lastPointerPos = this.pointerPos; this.drawPoint(); this.intervalID = setInterval(function() { if (self.inputPhase && lastPointerPos != self.pointerPos) { self.drawPoint(); lastPointerPos = self.pointerPos; } }, 16); }, drawPoint: function() { this.buildPath(this.pointerPos); this.strokeRenderer.draw(this.pathPart, false); this.strokeRenderer.drawPreliminary(this.preliminaryPathPart); this.canvas.clearArea(this.strokeRenderer.updatedArea, this.backgroundColor); this.canvas.blendWithRect(this.strokesLayer, this.strokeRenderer.updatedArea, Module.BlendMode.NORMAL); this.strokeRenderer.blendUpdatedArea(); }, endStroke: function(e) { if (!this.inputPhase) return; this.inputPhase = Module.InputPhase.End; clearInterval(this.intervalID); delete this.intervalID; this.buildPath({x: e.clientX, y: e.clientY}); this.strokeRenderer.draw(this.pathPart, true); this.strokeRenderer.blendStroke(this.strokesLayer, Module.BlendMode.NORMAL); this.canvas.clearArea(this.strokeRenderer.updatedArea, this.backgroundColor); this.canvas.blendWithRect(this.strokesLayer, this.strokeRenderer.updatedArea, Module.BlendMode.NORMAL); var stroke = new Module.Stroke(this.brush, this.path, NaN, this.color, 0, 1); this.strokes.push(stroke); delete this.inputPhase; }, buildPath: function(pos) { if (this.inputPhase == Module.InputPhase.Begin) this.smoothener.reset(); var pathPart = this.pathBuilder.addPoint(this.inputPhase, pos, Date.now()/1000); var smoothedPathPart = this.smoothener.smooth(pathPart, this.inputPhase == Module.InputPhase.End); var pathContext = this.pathBuilder.addPathPart(smoothedPathPart); this.pathPart = pathContext.getPathPart(); this.path = pathContext.getPath(); var preliminaryPathPart = this.pathBuilder.createPreliminaryPath(); var preliminarySmoothedPathPart = this.smoothener.smooth(preliminaryPathPart, true); this.preliminaryPathPart = this.pathBuilder.finishPreliminaryPath(preliminarySmoothedPathPart); }, redraw: function(dirtyArea) { if (!dirtyArea) dirtyArea = this.canvas.bounds; dirtyArea = RectTools.ceil(dirtyArea); this.strokesLayer.clearArea(dirtyArea, Module.color.TRANSPERENT); this.strokes.forEach(function(stroke) { var affectedArea = RectTools.intersect(stroke.bounds, dirtyArea); if (affectedArea) { this.strokeRenderer.draw(stroke); this.strokeRenderer.blendStroke(this.strokesLayer, stroke.blendMode); } }, this); this.refresh(dirtyArea); }, refresh: function(dirtyArea) { if (dirtyArea) this.canvas.blendWithRect(this.strokesLayer, RectTools.ceil(dirtyArea), Module.BlendMode.NORMAL); else this.canvas.blendWithMode(this.strokesLayer, Module.BlendMode.NORMAL); }, clear: function() { this.strokes = new Array(); this.strokesLayer.clear(this.backgroundColor); this.canvas.clear(this.backgroundColor); }, load: function(e) { var input = e.currentTarget; var file = input.files[0]; var reader = new FileReader(); reader.onload = function(e) { WILL.clear(); var strokes = Module.InkDecoder.decode(new Uint8Array(e.target.result)); WILL.strokes.pushArray(strokes); WILL.redraw(strokes.dirtyArea); }; reader.readAsArrayBuffer(file); }, save: function() { var data = Module.InkEncoder.encode(this.strokes); saveAs(data, "export.data", "application/octet-stream"); } }; Module.addPostScript(function() { Module.InkDecoder.getStrokeBrush = function(paint) { return WILL.brush; } WILL.init(1600, 600); });
/** * lark - log.js * Copyright(c) 2014 mdemo(https://github.com/demohi) * MIT Licensed */ 'use strict'; module.exports.log = { files: { debug: { path: './examples/logs/debug.log', options: { encoding: 'utf8' } } } };
var React = require('react'); var Firebase = require('firebase'); var gameConfig = require('../../game-constants'); var Game = require('../../game'); var Board = require('../board/board'); var FirebaseIntegration = require('../../firebase-integration'); var GameContainer = React.createClass({ getInitialState: function() { return new Game().data; }, componentWillReceiveProps: function(nextProps) { if (this.props.gameId !== nextProps.gameId) { FirebaseIntegration.bindFirebaseGame(this, nextProps.gameId); } }, componentDidMount: function() { FirebaseIntegration.bindFirebaseGame(this, this.props.gameId); }, /** * Play in the specified space on the game board. * @param {Number} colIndex Index of column in which to play * @param {Number} rowIndex Index of row in which to play */ play: function(colIndex, rowIndex) { var state = this.state; // Only play in blank spaces if (state.board[rowIndex][colIndex] === '') { state.board[rowIndex][colIndex] = state.player; // Update current player state.player = (state.player === gameConfig.players.X) ? gameConfig.players.O : gameConfig.players.X; this.gameRef.set(state); } }, /** * Reset game to initial state */ resetGame: function() { this.gameRef.set(new Game().data); }, render: function() { return ( <div> <span>Current player: {this.state.player}</span> <Board grid={this.state.board} playFn={this.play}/> </div> ); } }); module.exports = GameContainer;
const asyncAdd = (a,b)=>{ return new Promise((resolve,reject)=>{ if(typeof a==='number' && typeof b=== 'number'){ resolve(`Your result is ${a+b}`); }else{ reject('Your input arguments is not correct'); } }); }; asyncAdd(10,20).then((data)=>{ console.log(data); },(err)=>{ console.log(err); }) const somePromise = new Promise((resolve,reject)=>{ setTimeout(function() { // resolve('Hey, it works'); // reject('reject'); try{ throw new Error('Error Message'); }catch(err){ reject(err) } }, 2000); }); somePromise.then((data)=>{ console.log('Success:',data); },(rejectdata)=>{ throw new Error('e'); console.log('Failure:'); }).catch((err)=>{ console.log('Error') });
'use strict'; module.exports = { multiplayerLobby: [ {name: 'matchId', type: 'int16'}, {name: 'inProgress', type: 'boolean'}, {name: 'matchType', type: 'byte'}, {name: 'activeMods', type: 'uint32'}, {name: 'gameName', type: 'string'}, {name: 'gamePassword', type: 'string', nullable: true}, {name: 'beatmapName', type: 'string'}, {name: 'beatmapId', type: 'int32'}, {name: 'beatmapChecksum', type: 'string'}, {name: 'slots', type: 'multislots'}, {name: 'host', type: 'int32'}, {name: 'playMode', type: 'byte'}, {name: 'matchScoringType', type: 'byte'}, {name: 'matchTeamType', type: 'byte'}, {name: 'specialModes', type: 'byte'}, {name: 'slotMods', type: 'multislotmods', requires: 'specialModes', uses: 'slots'}, {name: 'seed', type: 'int32'} ], multiplayerJoin: [ {name: 'matchId', type: 'int32'}, {name: 'gamePassword', type: 'string'} ], message: [ {name: 'sendingClient', type: 'string'}, {name: 'message', type: 'string'}, {name: 'target', type: 'string'}, {name: 'senderId', type: 'int32'} ], userStatus: [ {name: 'status', type: 'byte'}, {name: 'statusText', type: 'string'}, {name: 'beatmapChecksum', type: 'string'}, {name: 'currentMods', type: 'uint32'}, {name: 'playMode', type: 'byte'}, {name: 'beatmapId', type: 'int32'} ], userStats: [ {name: 'userId', type: 'int32'}, {name: 'status', type: 'byte'}, {name: 'statusText', type: 'string'}, {name: 'beatmapChecksum', type: 'string'}, {name: 'currentMods', type: 'uint32'}, {name: 'playMode', type: 'byte'}, {name: 'beatmapId', type: 'int32'}, {name: 'rankedScore', type: 'int64'}, {name: 'accuracy', type: 'float'}, {name: 'playCount', type: 'int32'}, {name: 'totalScore', type: 'int64'}, {name: 'rank', type: 'int32'}, {name: 'performance', type: 'int16'} ], userPresence: [ {name: 'userId', type: 'int32'}, {name: 'username', type: 'string'}, {name: 'timezone', type: 'byte'}, {name: 'countryId', type: 'byte'}, {name: 'permissions', type: 'byte'}, {name: 'longitude', type: 'float'}, {name: 'latitude', type: 'float'}, {name: 'rank', type: 'int32'} ], userQuit: [ {name: 'userId', type: 'int32'}, {name: 'state', type: 'byte'} ], spectateFrames: [ {name: 'extra', type: 'int32'}, {name: 'replayFrames', type: 'replayframes'}, {name: 'action', type: 'byte'}, {name: 'scoreFrame', type: 'scoreframe'} ], channel: [ {name: 'channelName', type: 'string'}, {name: 'channelTopic', type: 'string'}, {name: 'channelUserCount', type: 'int16'} ] };
function getSum(...values) { // Sequentially sum all elements in 'values' // Initial total = 0 return values.reduce((x, y) => x + y, 0); } console.log(getSum(1,2,3)); // 6
/** * This file is part of vue-boilerplate. * @link : https://zhaiyiming.com/ * @author : Emil Zhai (root@derzh.com) * @modifier : Emil Zhai (root@derzh.com) * @copyright: Copyright (c) 2018 TINYMINS. */ /* eslint no-param-reassign: ["error", { "props": false }] */ import rateModule from './rate'; import listModule from './list'; export default { namespaced: true, modules: { rate: rateModule, list: listModule, }, state: {}, getters: {}, actions: {}, mutations: {}, };
/** @namespace Nehan.BoxCorner */ Nehan.BoxCorner = (function(){ var __sort = function(dir1, dir2){ var order = {top:0, bottom:1, left:2, right:3}; return [dir1, dir2].sort(function (c1, c2){ return order[c1] - order[c2]; }); }; return { /** get normalized(and camel-cased) corner property name @memberof Nehan.BoxCorner @param dir1 {string} @param dir2 {string} @return {string} @example * BoxCorner.getCornerName("right", "top"); // => "topRight" */ getCornerName : function(dir1, dir2){ var dirs = __sort(dir1, dir2); return [dirs[0], Nehan.Utils.capitalize(dirs[1])].join(""); } }; })();
import React from 'react'; import { ServicesSection } from '~/components/services'; export default ({className, data}) => { const services = data ? data.services.edges.map(x => ({...x.node.frontmatter, id:x.node.id, slug: x.node.fields.slug })) : []; return (<ServicesSection services={services}> </ServicesSection> ) }; export const pageQuery = graphql` query ServicesQuery { services: allMarkdownRemark( limit: 2000 filter:{ fields: { area: { eq: "services"} }} sort: { fields: [frontmatter___order], order: ASC } ){ edges { node{ fields{ area, slug }, id, frontmatter{ title, caption, extract, image, thumb, tags, thumbPosition } } } } } `
'use strict'; const fs = require('mz/fs'); const path = require('path'); const assert = require('assert'); const mock = require('egg-mock'); describe('test/app/service/images.test.js', () => { let app; let ctx; before(async function() { app = mock.app(); await app.ready(); ctx = app.mockContext(); }); afterEach(async function() { mock.restore(); }); describe('save()', () => { it('should return image url with md5', async () => { const mock_image_buffer = new Buffer([ 0x0, 0x1, 0x2, 0x3 ]); const url = await ctx.service.images.save(mock_image_buffer); const filename = `${await ctx.helper.md5(mock_image_buffer)}.png`; const file_path = path.join(app.config.images.dir, filename); const expect_url = `/${file_path}`; const is_existing = await fs.exists(file_path); if (is_existing) await fs.unlink(file_path); (() => { assert(url === expect_url); assert(is_existing); })(); }); }); });
/** * Demo.js * * Released under LGPL License. * Copyright (c) 1999-2016 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /*eslint no-console:0 */ define("tinymce.media.Demo", [ "tinymce.media.Plugin", "global!tinymce" ], function (Plugin, tinymce) { return function () { tinymce.init({ selector: "textarea.tinymce", theme: "modern", plugins: "media preview", toolbar: "media preview", // media_live_embeds: false, // media_url_resolver: function (data, resolve) { // resolve({ // html: '<iframe src="' + data.url + '" width="560" height="314" allowfullscreen="allowfullscreen"></iframe>'}); // }, height: 600 }); }; });
module.exports = function centreColourCollator(data) { const dataPerPixel = 4; const length = data.data.length; const i = Math.floor(length / dataPerPixel / 2) * dataPerPixel; return { r: data.data[i], g: data.data[i + 1], b: data.data[i + 2] }; };
var test = require('tape'); var omit = require('./omit'); test('amp-omit', function (t) { var result; result = omit({a: 1, b: 2, c: 3}, 'b'); t.deepEqual(result, {a: 1, c: 3}, 'can omit a single named property'); result = omit({a: 1, b: 2, c: 3}, 'a', 'c'); t.deepEqual(result, {b: 2}, 'can omit several named properties'); result = omit({a: 1, b: 2, c: 3}, ['b', 'c']); t.deepEqual(result, {a: 1}, 'can omit properties named in an array'); result = omit(['a', 'b'], 0); t.deepEqual(result, {1: 'b'}, 'can omit numeric properties'); t.deepEqual(omit(null, 'a', 'b'), {}, 'non objects return empty object'); t.deepEqual(omit(undefined, 'toString'), {}, 'null/undefined return empty object'); t.deepEqual(omit(5, 'toString', 'b'), {}, 'returns empty object for primitives'); var data = {a: 1, b: 2, c: 3}; var callback = function(value, key, object) { t.strictEqual(key, {1: 'a', 2: 'b', 3: 'c'}[value]); t.strictEqual(object, data); return value !== this.value; }; result = omit(data, callback, {value: 2}); t.deepEqual(result, {b: 2}, 'can accept a predicate'); var Obj = function(){}; Obj.prototype = {a: 1, b: 2, c: 3}; var instance = new Obj(); t.deepEqual(omit(instance, 'b'), {a: 1, c: 3}, 'include prototype props'); t.deepEqual(omit(data, function(val, key) { return this[key] === 3 && this === instance; }, instance), {a: 1, b: 2}, 'function is given context'); t.end(); });
/** * 对话框 * @author Brian Li * @email lbxxlht@163.com * @version 0.0.2.1 */ define(function (require) { var React = require('react'); var ReactDOM = require('react-dom'); var AlertContent = require('./components/dialog/Alert.jsx'); var ConfirmContent = require('./components/dialog/Confirm.jsx'); var TitleWindow = require('./TitleWindow.jsx'); var ShojiScreen = require('./ShojiScreen.jsx'); var util = require('./core/util'); /** * @constructor * @name Dialog */ function Dialog() { this.___tempContainer___ = document.createElement('div'); } /** * 弹出窗体 * * @name pop * @className Dialog * @param {Object} param 弹出配置 * @param {String} param.popType 弹窗类型,目前支持普通弹窗和侧拉门 * @param {ReactClass} param.content Dialog内部组件 * @param {Object} param.contentProps Dialog内部组件初始化时的属性集 * @param {String} param.className 挂在到Dialog窗体DOM上的class * @param {Object} param.style 挂在Dialog窗体DOM上的样式表 * @param {String} param.skin Dialog皮肤 * @param {String} param.appSkin Dialog初始化时,传入的系统级皮肤 * @param {String} param.title Dialog标题栏中显示的标题 * @param {Object} param.size Dialog窗体的尺寸,与isFullScreen互斥 * @param {Number} param.size.width Dialog渲染后的宽度 * @param {Number} param.size.height Dialog渲染后的高度 * @param {Number} param.zIndex Dialog渲染后的z-index(层次) * @param {Boolean} param.isFullScreen Dialog弹出后时候直接全屏显示 * @param {Boolean} param.showCloseButton 是否显示Dialog标题栏中的关闭按钮 * @param {Function} param.onBeforeClose 同TitleWindow props.onBeforeClose * @param {Function} param.onClose 同TitleWindow props.onClose */ Dialog.prototype.pop = function (param) { var me = this; var ReactElement; if (param.popType === 'shoji') { ReactElement = React.createElement(shojiComponentFactory(param, me), {}); } else { ReactElement = React.createElement(dialogComponentFactory(param, me), {}); } me.___ui___ = ReactDOM.render( ReactElement, me.___tempContainer___, function () { if (this) me.___ui___ = this; } ); }; /** * 关闭窗体 * * @name close * @className Dialog * @attention 此方法直接无条件关闭并销毁窗体,不会触发任何回调函数 */ Dialog.prototype.close = function () { if (!this.___ui___) return; this.___ui___ = null; ReactDOM.unmountComponentAtNode(this.___tempContainer___); }; /** * 更新content属性集 * * @param {Object} props Dialog content初始化所需要的属性集 * @name updatePopContentProps * @className Dialog * @attention 此方法支持刷新param.contentProps的部分属性和新增属性,不支持删除原有属性 */ Dialog.prototype.updatePopContentProps = function (props) { if (!this.___ui___) return; var oldProps = this.___ui___.state.contentProps; var newProps = {}; for (var key in oldProps) { if (!oldProps.hasOwnProperty(key)) continue; newProps[key] = oldProps[key]; } props = props || {}; for (var key in props) { if (!props.hasOwnProperty(key)) continue; newProps[key] = props[key]; } this.___ui___.setState({contentProps: newProps}); }; /** * 弹出Alert提示框 * * @param {Object} param 对话框属性集 * @param {String} param.title 提示框标题 * @param {String} param.message 提示内容 * @param {Function} param.onClose 关闭后的回调 * @name alert * @className Dialog * @attention 此方法内部调用了dialog.pop */ Dialog.prototype.alert = function (param) { param = param || {}; var contentProps ={ message: param.message, labels: param.labels }; var dialogProp = util.extend({}, param, { content: AlertContent, contentProps: contentProps }); this.pop(dialogProp); }; /** * 弹出Confirm确认框 * * @param {Object} param 对话框属性集 * @param {String} param.title 提示框标题 * @param {String} param.message 提示内容 * @param {Function} param.onClose 关闭后的回调 * @param {Function} param.onEnter 点击确定后的回调 * @param {Function} param.onCancel 点击取消后的回调 * @name confirm * @className Dialog * @attention 此方法内部调用了dialog.pop */ Dialog.prototype.confirm = function (param) { param = param || {}; var contentProps = { message: param.message, labels: param.labels, onEnter: typeof param.onEnter === 'function' ? param.onEnter : util.noop, onCancel: typeof param.onCancel === 'function' ? param.onCancel : util.noop }; var dialogProp = util.extend({}, param, { content: ConfirmContent, contentProps: contentProps }); this.pop(dialogProp); }; /** * Shoji Component Factory * * @param {Object} param Dialog配置,见Dialog.pop注释 * @param {Object} dialog 弹出此component的dialog实例 */ function shojiComponentFactory(param, dialog) { return React.createClass({ // @override childContextTypes: { appSkin: React.PropTypes.string }, // @override getChildContext: function () { return { appSkin: typeof param.appSkin === 'string' && param.appSkin ? param.appSkin : '' }; }, // @override getDefaultProps: function () { return {}; }, // @override getInitialState: function () { return { isOpen: true, contentProps: param.contentProps || {} }; }, close: function () { this.setState({isOpen: false}); typeof param.onClose === 'function' && param.onClose(); dialog.close(); }, onAction: function (actionType) { if (actionType === 'HideButtonClick') { this.close(); } }, contentFactory: function () { if (typeof param.content !== 'function') { return (<div>No Content</div>); } var Content = param.content; var contentProps = {}; // 潜克隆一次 for (var key in this.state.contentProps) { if (!this.state.contentProps.hasOwnProperty(key)) continue; contentProps[key] = this.state.contentProps[key]; } // 挂content窗体回调 contentProps.close = this.close; return (<Content {...contentProps}/>); }, render: function () { var ShojiScreenProp = { className: param.className, skin: param.skin, workspaceWidth: param.workspaceWidth, isOpen: this.state.isOpen, showFootBar: false, buttonLabels: { hide: '关闭' }, onAction: this.onAction, onBeforeClose: (typeof param.onBeforeClose === 'function') ? param.onBeforeClose : util.noop, onClose: this.close }; return ( <ShojiScreen {...ShojiScreenProp}> {this.contentFactory()} </ShojiScreen> ); } }); } /* * Dialog Component Factory * * @param {Object} param Dialog配置,见Dialog.pop注释 * @param {Object} dialog 弹出此component的dialog实例 */ function dialogComponentFactory(param, dialog) { return React.createClass({ // @override childContextTypes: { appSkin: React.PropTypes.string }, // @override getChildContext: function () { return { appSkin: typeof param.appSkin === 'string' && param.appSkin ? param.appSkin : '' }; }, // @override getDefaultProps: function () { return {}; }, // @override getInitialState: function () { return { isOpen: true, contentProps: param.contentProps || {} }; }, close: function () { this.setState({isOpen: false}); typeof param.onClose === 'function' && param.onClose(); dialog.close(); }, resize: function () { if (this.refs.window && typeof this.refs.window.resize === 'function') { this.refs.window.resize(); } return true; }, contentFactory: function () { if (typeof param.content !== 'function') { return (<div>No Content</div>); } var Content = param.content; var contentProps = {}; // 潜克隆一次 for (var key in this.state.contentProps) { if (!this.state.contentProps.hasOwnProperty(key)) continue; contentProps[key] = this.state.contentProps[key]; } // 挂content窗体回调 contentProps.resize = this.resize; contentProps.close = this.close; return (<Content {...contentProps}/>); }, render: function () { var TitleWindowProp = { ref: 'window', className: param.className, style: param.style, skin: param.skin, isOpen: this.state.isOpen, title: param.title, size: param.size, zIndex: param.zIndex, isFullScreen: param.isFullScreen, showCloseButton: param.hasOwnProperty('showCloseButton') ? param.showCloseButton : true, onBeforeClose: (typeof param.onBeforeClose === 'function') ? param.onBeforeClose : util.noop, onClose: this.close }; return ( <TitleWindow {...TitleWindowProp}> {this.contentFactory()} </TitleWindow> ); } }); } return Dialog; });
import React, { Component } from 'react' import { Link } from 'react-router' export default class ChildInfoQuestion extends Component { constructor(props) { super(props) this.state = { indexOfActive: 0 } } render() { let question = this.props.question let heading = this.props.heading let onYesClick = (e, i) => { if (this.state.indexOfActive !== this.props.names.length - 1 ) { e.preventDefault() } this.props.onYesClick(i) this.setState({indexOfActive: this.state.indexOfActive + 1 }) } let onNoClick = (e, i) => { if (this.state.indexOfActive !== this.props.names.length - 1 ) { e.preventDefault() } this.props.onNoClick(i) this.setState({indexOfActive: this.state.indexOfActive + 1 }) } let nextPath = Number.parseInt(window.location.hash.match(/children\/?([0-9])/)[1]) + 1 let nextSection ="assistance" return ( <div> <h5>{heading}:</h5> {this.props.names.map((el, i)=> { return (<div style={ this.state.indexOfActive === i ? {display: 'block'} : {display: 'none'}} > <p>{question(el)}</p> <Link to={nextPath === 7 ? "assistance" : "children/" + nextPath} onClick={ (e) => { onYesClick(e, i) } }> <button>Yes</button> </Link> <Link to={nextPath === 7 ? "assistance" : "children/" + nextPath} onClick={ (e) => { onNoClick(e, i) } }> <button>NO</button> </Link> </div> ) })} </div> ) } } //TODO: Link to =="" doesn't work... what should it link to if we don't want it to be alink...? hmm..mm..mm.m.m.m.m. //also children/4 , 4 needs to be dynamic number so we go to the next question in the list!
angular.module("TestService", []).factory("Test", ["$http", function ($http) { return { get: function () { return $http.get("/api/test"); }, create: function (testData) { return $http.post("/api/test", testData); }, delete: function (id) { return $http.delete("api/test/" + id); } } }]);
module.exports = function(grunt) { // Configure Grunt grunt.initConfig({ requirejs: { compile: { options: { mainConfigFile: "build.js" } } }, // minify the optimized library file min: { "dist/sheep.min.js": "dist/sheep.js" }, // kick off jasmine, showing results at the cli jasmine: { all: ['test/runner.html'] }, // run jasmine tests any time watched files change watch: { files: ['lib/**/*','test/spec/**/*'], tasks: ['jasmine'] } }); // Load external tasks grunt.loadNpmTasks('grunt-contrib-requirejs'); grunt.loadNpmTasks('grunt-jasmine-task'); // Make task shortcuts grunt.registerTask('default', 'jasmine requirejs min'); grunt.registerTask('test', 'jasmine'); };
$(document).ready(function () { $('#shellcatch_timeliner').timeliner({ containerwidth: 450, containerheight: 450, timelinewidth: 370, timelineheight: 5, timelineverticalmargin: 0, autoplay: false, showtooltiptime: true, repeat: false, showtotaltime: true, timedisplayposition: 'below', transition: 'fade' }); $('#id_mac').on('change', function () { var value = $(this).val(); var url_group_date = URL_DATE.replace(/identifier_mac/, value.toString()); var $select = $('#id_trip'); $.ajax({ url: url_group_date, dataType: 'json' }).done(function (data) { $select.html(''); $select.append("<option value='0'>--Seleccione--</option>"); $.each(data, function (key, val) { $select.append('<option value="' + val + '">' + val + '</option>'); }) }).fail(function () { $select.html(''); $select.append("<option value='0'>No hay registros</option>"); }) }); });
module.exports = function(sequelize, DataTypes) { var JQueryDoc = sequelize.define("JQueryDoc", { name: { type: DataTypes.STRING, // AllowNull is a flag that restricts a todo from being entered if it doesn't // have a text value allowNull: false, defaultValue: "test", // len is a validation that checks that our todo is between 1 and 140 characters validate: { len: [1, 255] } }, data_url: { type: DataTypes.STRING }, detail: { type: DataTypes.TEXT }, examples: { type: DataTypes.TEXT, get: function() { return JSON.parse(this.getDataValue('examples')); }, set: function(val) { return this.setDataValue('examples', JSON.stringify(val)); } }, description : { type: DataTypes.TEXT } }, { indexes: [ // add a FULLTEXT index { type: 'FULLTEXT', name: 'text_idx', fields: ['detail', 'name', 'description'] } ] }); return JQueryDoc; };
'use strict'; const logger = require('./log'); const pph = require('./pseudopattern_hunter'); // This is now solely for analysis; loading of the pattern file is // above, in loadPatternIterative() module.exports = function (pattern, patternlab) { //look for a pseudo pattern by checking if there is a file //containing same name, with ~ in it, ending in .json return pph .find_pseudopatterns(pattern, patternlab) .then(() => { //find any stylemodifiers that may be in the current pattern pattern.stylePartials = pattern.findPartialsWithStyleModifiers(); //find any pattern parameters that may be in the current pattern pattern.parameteredPartials = pattern.findPartialsWithPatternParameters(); return Promise.resolve(pattern); }) .catch( logger.reportError('There was an error in processPatternIterative():') ); };
module.exports = { yellow: { r: 255, g: 226, b: 108 }, red: { r: 255, g: 85, b: 83 }, green: { r: 136, g: 233, b: 128 }, blue: { r: 055, g: 180, b: 255 }, purple: { r: 190, g: 112, b: 255 }, black: { r: 0, g: 0, b: 0 }, white: { r: 255, g: 255, b: 255 }, gray: { r: 50, g: 50, b: 50 } };
#!/usr/bin/nodejs //process.env.NODE_ENV = process.env.NODE_ENV || 'development' var config=require('./config/config.json')['development'] var simplify=require('vis-why') var _ = require('underscore') var CSV = require('csv-string') var sprintf = require("sprintf-js").sprintf Promise=require("bluebird") var fs = require("fs") var readFile=Promise.promisify(fs.readFile) var writeFile=Promise.promisify(fs.writeFile) var parse = Promise.promisify(require('csv-parse')) var stringify = require('csv-stringify'); var sleep=require("sleep-promise") const cheerio = require('cheerio') const axios = require('axios') var axiosRetry = require('axios-retry') var commandLineArgs= require("command-line-args") var SHAPEFILE="shapes.txt" var polyline = require('google-polyline' ) var Sequelize = require("./lib/gemini-sequelize.js") const Op = Sequelize.Op; var MAX_BUFFER=1000 var mysql = require('mysql'); var connection = mysql.createConnection({ host : config.host, user : config.username, password : config.password, database : config.database }); var query=Promise.promisify(connection.query) connection.connect(); sequelize = new Sequelize(config.database, config.username, config.password, config); var cli = commandLineArgs([ { name: "route", alias: "r", type: String, defaultValue:"MORADABAD,DELHI",multiple: true, }, { name: "stops", alias: "s", type: Boolean, defaultValue:false }, { name: "simplify", alias: "S", type: Boolean, defaultValue:false }, ]) var options = cli.parse(); if (options.help){ console.log(cli.getUsage()); process.exit(); } var colours="red blue green yellow orange navy lime cyan olive teal purple".split(/\s+/) sequelize = new Sequelize(config.database, config.username, config.password, config); sequelize.loadModels(options).then(Main); function Main(){ return get_features() .then(function(geojson){ console.log("GOT JSON") fs.writeFileSync("buzmap.json",JSON.stringify(geojson,null,2)) process.exit(0) }) } function get_features(){ console.log("GET FEATURES") var s={ type : "FeatureCollection", features :[] } console.log("GET FEATURES more") return sequelize.models.PeuckPoint.count() .then(function(count){ console.log("PeuckPoints "+count) return sequelize.models.PeuckLine.findAll({ order:'id' }) }) .then(function(peucks){ var jobs=[] _.each(peucks,function(peuck){ jobs.push( get_feature(peuck.get('id')) .then(function(feature){ console.log("DONE FEATURE") if (feature) s.features.push(feature) return feature }) ) }) return Promise.all(jobs) }) .then(function(){ return s }) .catch(function(error){ console.error("ERROR "+error) }) } function get_feature(peuck_id){ console.log("GET FEATURE "+peuck_id) var routes return sequelize.models.PeuckPoint.findAll({ where:{ PeuckLineId:peuck_id } }) .then(function(graph_points){ console.log("GOT POINTS "+graph_points.length) if (graph_points.length < 2) return undefined var coords= graph_points.map(function(graph_point){ return [ parseFloat(graph_point.lon), parseFloat(graph_point.lat) ] }) if (options.simplify && coords.length>10){ coords=simplify(coords,Math.max(10,coords.length/10)) } var feature={ properties:{ graph_id:peuck_id }, type: "Feature", geometry:{ type: "LineString", coordinates: graph_points.map(function(graph_point){ return [ parseFloat(graph_point.lon), parseFloat(graph_point.lat) ] }) } } // console.error("ROUTES LENGTH="+routes.length) feature.properties['stroke']= 'red'//colours[ peuck_id%colours.length ] feature.properties['stroke-width']= 2//3+peuck_id%8//routes.length // feature.properties['stroke']= colours[ count%colours.lengcth ] // feature.properties['stroke-width']= count feature.properties['fill-opacity']=1 return feature }) }
'use strict'; angular.module('myApp.service', []) //product service data pulling from json .service('productReview', [ function(){ var reviewList = []; var addReview = function(newObj) { reviewList.push(newObj); }; var getReview = function(){ return reviewList; }; return { addReview: addReview, getReview: getReview }; }]) .service('productList', ['$http', '$filter', function($http, $filter){ /*var promise; var getProducts = function() { if(!promise){ promise = $http.get('/json/products.json'); } return promise; }; return { getProducts: getProducts };*/ this.getProducts = function(callback){ $http.get('/json/products.json',{ cache: true }).then(function(response){ callback(response.data); }, function(error){ console.log('error')}); } this.filterProducts = function(f, value, callback){ this.getProducts(function(response){ var products = $filter('filter')(response, function(pro){ if(pro.hasOwnProperty(f) && pro[f] == value) { return pro; } }); callback(products); }); } }]) //category service data pulling from json and category functions .factory('categoryTree', ['$http', '$filter', function($http, $filter){ /*var promise; var getCategories = function() { if(!promise){ promise = $http.get('/json/categories.json'); } return promise; }; return { getCategories: getCategories };*/ var categories = {}; categories.getCategories = function(callback){ $http.get('/json/categories.json', { cache: true }).then(function(response){ callback(response.data); }, function(error){ console.log('error')}); } categories.getCatName = function(id, callback){ categories.getCategories(function(response){ var catname = $filter('filter')(response, { id: id })[0].name; callback(catname); }); } return categories; }]); /*.service('categoryTree', ['$http', function($http) { var catTree = { categories: null, //get all categories from json getCategories: function(){ if(!promise){} return $http.get("/json/categories.json").then(function(response){ catTree.categories = response.data; }); }, //get category value from ref id getCatName:function(id){ var a = this.categories.filter(function(cat){ return (cat.id == id); }) return a ; } }; catTree.getCategories(); return catTree; }]);*/
import {Map} from 'immutable' import composeFields from '../src/composeFields' import expect from 'expect' import fieldType from '../src/fieldCreators/fieldType' describe(`redux-uniform`, () => { describe(`composeFields`, () => { it(`should compose fields`, () => { const fields = { foo: fieldType() } const fieldPaths = [ `fields` ] const state = Map({ fields: Map({ map: Map({ foo: Map({ value: `bar` }) }) }) }) const result = composeFields(fields, fieldPaths, state) expect(result.getIn([ `map`, `foo`, `value` ])).toEqual(`bar`) expect(result.get(`valid`)).toBeTruthy() }) it(`should invalidate form if at least one of the fields is invalid`, () => { const validate = expect .createSpy() .andReturn(false) const fields = { foo: fieldType(validate) } const fieldPaths = [ `fields` ] const state = Map({ map: Map({ foo: Map({ value: `bar` }) }) }) const result = composeFields(fields, fieldPaths, state) expect(result.get(`valid`)).toBeFalsy() }) }) })
var gulp = require("gulp4"), concat = require("gulp-concat"), size = require("gulp-filesize"), tap = require("gulp-tap"); //merge all files in /dist/js to dist/bundle.js gulp.task("merge", function() { return gulp.src([config.path.dist_js+config.select.js]) .pipe(tap(function(file){ console.log("\t\t", "Merging", file.path.slice(file.path.lastIndexOf("/")+1)) })) .pipe(concat(config.select.bundle)) .pipe(size()) .pipe(gulp.dest(config.path.dist)) });
$(function () { if (!Modernizr.inputtypes.date) { $.datepicker.regional["cs"] = { closeText: "Zavřít", prevText: "&#x3c;Dříve", nextText: "Později&#x3e;", currentText: "Dnes", monthNames: ["leden", "únor", "březen", "duben", "květen", "červen", "červenec", "srpen", "září", "říjen", "listopad", "prosinec"], monthNamesShort: ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII"], dayNames: ["neděle", "pondělí", "úterý", "středa", "čtvrtek", "pátek", "sobota"], dayNamesShort: ["ne", "po", "út", "st", "čt", "pá", "so"], dayNamesMin: ["ne", "po", "út", "st", "čt", "pá", "so"], weekHeader: "Týd", dateFormat: "yy-mm-dd", firstDay: 1, isRTL: false, showMonthAfterYear: false, yearSuffix: "" }; $.datepicker.setDefaults($.datepicker.regional["cs"]); $("input[type=date]").datepicker(); } if (!Modernizr.inputtypes.time) { $("input[type=time]").timepicker({ showPeriodLabels: false, hourText: "Hodina", minuteText: "Minuta" }); } });
const EventEmitter = require('events') const pg = require('pg') class Db extends EventEmitter { constructor (config) { super() config.application_name = config.application_name || 'pgboss' this.config = config } async open () { this.pool = new pg.Pool(this.config) this.pool.on('error', error => this.emit('error', error)) this.opened = true } async close () { if (!this.pool.ending) { this.opened = false await this.pool.end() } } async executeSql (text, values) { if (this.opened) { return await this.pool.query(text, values) } } } module.exports = Db
'use strict'; /* Services */ // Demonstrate how to register services // In this case it is a simple value service. angular.module('jiraNow.services', ['ngResource']) .factory('Week', function($resource) { return $resource('api/changes?user=:users&since=:since', {}, { query: {method:'GET', params:{}, isArray:true} }); }) .factory('Worklog', function($resource) { return $resource('api/changes?user=:users&since=:since&until=:until', {}, { query: {method:'GET', params:{}, isArray:true} }); }) .factory('List', function($resource) { return $resource('api/list/?id=:id', {}, { query: {method:'GET', params:{}, isArray:true} }); }) .factory('Sprint', function($resource) { return $resource('api/sprint/?id=:id', {}, { query: {method: 'GET', params: {}, isArray: true} }); }) ; angular.module('developmentProcess', []). factory('sprintSchedule', function() { return { // Return the nearest date that falls on specified day // and hour. getPreviousDate: function(date, day, hour) { var d = new Date(date), now = new Date(); d.setDate(d.getDate() - (d.getDay() + 7 - day) % 7); d.setHours(hour); d.setMinutes(0); d.setSeconds(0); d.setMilliseconds(0); if (d.getTime() > now.getTime()) { d.setDate(d.getDate() - 7); } return d; }, getMonday: function() { // Return previous monday, 5 am, local time return this.getPreviousDate(new Date(), 1, 5) }, getPreviousMonday: function() { var d = this.getMonday(); d.setDate(d.getDate() - 7); return d; }, getTeamCall: function() { // Current date, local time. var d = new Date(); // Translate to Moscow time, (GMT+4) var moscowOffset = -4*60; var localToMoscowMillis = (d.getTimezoneOffset() - moscowOffset) * 60 * 1000; d.setTime(d.getTime() + localToMoscowMillis); // Previous Tuesday, 21:00, Moscow time d = this.getPreviousDate(d, 2, 21); // And back to local timezone d.setTime(d.getTime() - localToMoscowMillis); return d; }, getPreviousTeamCall: function() { var d = this.getTeamCall(); d.setDate(d.getDate() - 7); return d; } } });
export default { Goods: 'Goods', 'Cart Item': 'Cart Item', Quantity: 'Quantity', Price: 'Price', Discount: 'Discount', Currency: 'Currency', 'SKU Desc': 'SKU Desc' };
/* eslint-env node */ /* eslint camelcase: 0, no-process-env: 0, no-var: 0 */ var funnel = require('broccoli-funnel'), mergeTrees = require('broccoli-merge-trees'), renameFiles = require('broccoli-rename-files'), uglify = require('broccoli-uglify-js'), babel = require('broccoli-babel-transpiler'), browserify = require('broccoli-fast-browserify'), sourceMap = require('broccoli-source-map'), fileSize = require('broccoli-file-size'); var name = 'elementjs'; var jsTree = funnel('src', { include: ['**/*.js'] }); jsTree = babel(jsTree, { modules: 'common', sourceMaps: 'inline' }); jsTree = browserify(jsTree, { bundles: { 'elements.js': { entryPoints: ['elements.js'] } }, browserify: { standalone: name, debug: true } }); jsTree = mergeTrees([ sourceMap.extract(jsTree), renameFiles(uglify(jsTree), { append: '.min' }) ]); jsTree = mergeTrees([ funnel(jsTree, { exclude: ['**/*.js'] }), fileSize(funnel(jsTree, { include: ['**/*.js'] })) ]); module.exports = jsTree;
/* Highmaps JS v1.1.9 (2015-10-07) Highmaps as a plugin for Highcharts 4.1.x or Highstock 2.1.x (x being the patch version of this file) (c) 2011-2014 Torstein Honsi License: www.highcharts.com/license */ (function (l) { function J(a, b) { var c, d, e, f, g = !1, h = a.x, i = a.y; for (c = 0, d = b.length - 1; c < b.length; d = c++)e = b[c][1] > i, f = b[d][1] > i, e !== f && h < (b[d][0] - b[c][0]) * (i - b[c][1]) / (b[d][1] - b[c][1]) + b[c][0] && (g = !g); return g } function K(a, b, c, d, e, f, g, h) { return ["M", a + e, b, "L", a + c - f, b, "C", a + c - f / 2, b, a + c, b + f / 2, a + c, b + f, "L", a + c, b + d - g, "C", a + c, b + d - g / 2, a + c - g / 2, b + d, a + c - g, b + d, "L", a + h, b + d, "C", a + h / 2, b + d, a, b + d - h / 2, a, b + d - h, "L", a, b + e, "C", a, b + e / 2, a + e / 2, b, a + e, b, "Z"] } var p = l.Axis, s = l.Chart, x = l.Color, t = l.Point, F = l.Pointer, C = l.Legend, G = l.LegendSymbolMixin, O = l.Renderer, y = l.Series, H = l.SVGRenderer, L = l.VMLRenderer, I = l.addEvent, j = l.each, D = l.error, o = l.extend, u = l.extendClass, n = l.merge, k = l.pick, z = l.getOptions(), m = l.seriesTypes, w = z.plotOptions, v = l.wrap, q = function () { }; v(p.prototype, "getSeriesExtremes", function (a) { var b = this.isXAxis, c, d, e = [], f; b && j(this.series, function (a, b) { if (a.useMapGeometry)e[b] = a.xData, a.xData = [] }); a.call(this); if (b && (c = k(this.dataMin, Number.MAX_VALUE), d = k(this.dataMax, -Number.MAX_VALUE), j(this.series, function (a, b) { if (a.useMapGeometry)c = Math.min(c, k(a.minX, c)), d = Math.max(d, k(a.maxX, c)), a.xData = e[b], f = !0 }), f))this.dataMin = c, this.dataMax = d }); v(p.prototype, "setAxisTranslation", function (a) { var b = this.chart, c = b.plotWidth / b.plotHeight, b = b.xAxis[0], d; a.call(this); this.coll === "yAxis" && b.transA !== void 0 && j(this.series, function (a) { a.preserveAspectRatio && (d = !0) }); if (d && (this.transA = b.transA = Math.min(this.transA, b.transA), a = c / ((b.max - b.min) / (this.max - this.min)), a = a < 1 ? this : b, c = (a.max - a.min) * a.transA, a.pixelPadding = a.len - c, a.minPixelPadding = a.pixelPadding / 2, c = a.fixTo)) { c = c[1] - a.toValue(c[0], !0); c *= a.transA; if (Math.abs(c) > a.minPixelPadding || a.min === a.dataMin && a.max === a.dataMax)c = 0; a.minPixelPadding -= c } }); v(p.prototype, "render", function (a) { a.call(this); this.fixTo = null }); var B = l.ColorAxis = function () { this.isColorAxis = !0; this.init.apply(this, arguments) }; o(B.prototype, p.prototype); o(B.prototype, { defaultColorAxisOptions: { lineWidth: 0, minPadding: 0, maxPadding: 0, gridLineWidth: 1, tickPixelInterval: 72, startOnTick: !0, endOnTick: !0, offset: 0, marker: { animation: {duration: 50}, color: "gray", width: 0.01 }, labels: {overflow: "justify"}, minColor: "#EFEFFF", maxColor: "#003875", tickLength: 5 }, init: function (a, b) { var c = a.options.legend.layout !== "vertical", d; d = n(this.defaultColorAxisOptions, {side: c ? 2 : 1, reversed: !c}, b, { opposite: !c, showEmpty: !1, title: null, isColor: !0 }); p.prototype.init.call(this, a, d); b.dataClasses && this.initDataClasses(b); this.initStops(b); this.horiz = c; this.zoomEnabled = !1 }, tweenColors: function (a, b, c) { var d; !b.rgba.length || !a.rgba.length ? a = b.raw || "none" : (a = a.rgba, b = b.rgba, d = b[3] !== 1 || a[3] !== 1, a = (d ? "rgba(" : "rgb(") + Math.round(b[0] + (a[0] - b[0]) * (1 - c)) + "," + Math.round(b[1] + (a[1] - b[1]) * (1 - c)) + "," + Math.round(b[2] + (a[2] - b[2]) * (1 - c)) + (d ? "," + (b[3] + (a[3] - b[3]) * (1 - c)) : "") + ")"); return a }, initDataClasses: function (a) { var b = this, c = this.chart, d, e = 0, f = this.options, g = a.dataClasses.length; this.dataClasses = d = []; this.legendItems = []; j(a.dataClasses, function (a, i) { var r, a = n(a); d.push(a); if (!a.color)f.dataClassColor === "category" ? (r = c.options.colors, a.color = r[e++], e === r.length && (e = 0)) : a.color = b.tweenColors(x(f.minColor), x(f.maxColor), g < 2 ? 0.5 : i / (g - 1)) }) }, initStops: function (a) { this.stops = a.stops || [[0, this.options.minColor], [1, this.options.maxColor]]; j(this.stops, function (a) { a.color = x(a[1]) }) }, setOptions: function (a) { p.prototype.setOptions.call(this, a); this.options.crosshair = this.options.marker; this.coll = "colorAxis" }, setAxisSize: function () { var a = this.legendSymbol, b = this.chart, c, d, e; if (a)this.left = c = a.attr("x"), this.top = d = a.attr("y"), this.width = e = a.attr("width"), this.height = a = a.attr("height"), this.right = b.chartWidth - c - e, this.bottom = b.chartHeight - d - a, this.len = this.horiz ? e : a, this.pos = this.horiz ? c : d }, toColor: function (a, b) { var c, d = this.stops, e, f = this.dataClasses, g, h; if (f)for (h = f.length; h--;) { if (g = f[h], e = g.from, d = g.to, (e === void 0 || a >= e) && (d === void 0 || a <= d)) { c = g.color; if (b)b.dataClass = h; break } } else { this.isLog && (a = this.val2lin(a)); c = 1 - (this.max - a) / (this.max - this.min || 1); for (h = d.length; h--;)if (c > d[h][0])break; e = d[h] || d[h + 1]; d = d[h + 1] || e; c = 1 - (d[0] - c) / (d[0] - e[0] || 1); c = this.tweenColors(e.color, d.color, c) } return c }, getOffset: function () { var a = this.legendGroup, b = this.chart.axisOffset[this.side]; if (a) { this.axisParent = a; p.prototype.getOffset.call(this); if (!this.added)this.added = !0, this.labelLeft = 0, this.labelRight = this.width; this.chart.axisOffset[this.side] = b } }, setLegendColor: function () { var a, b = this.options; a = this.reversed; a = this.horiz ? [+a, 0, +!a, 0] : [0, +!a, 0, +a]; this.legendColor = { linearGradient: {x1: a[0], y1: a[1], x2: a[2], y2: a[3]}, stops: b.stops || [[0, b.minColor], [1, b.maxColor]] } }, drawLegendSymbol: function (a, b) { var c = a.padding, d = a.options, e = this.horiz, f = k(d.symbolWidth, e ? 200 : 12), g = k(d.symbolHeight, e ? 12 : 200), h = k(d.labelPadding, e ? 16 : 30), d = k(d.itemDistance, 10); this.setLegendColor(); b.legendSymbol = this.chart.renderer.rect(0, a.baseline - 11, f, g).attr({zIndex: 1}).add(b.legendGroup); b.legendSymbol.getBBox(); this.legendItemWidth = f + c + (e ? d : h); this.legendItemHeight = g + c + (e ? h : 0) }, setState: q, visible: !0, setVisible: q, getSeriesExtremes: function () { var a; if (this.series.length)a = this.series[0], this.dataMin = a.valueMin, this.dataMax = a.valueMax }, drawCrosshair: function (a, b) { var c = b && b.plotX, d = b && b.plotY, e, f = this.pos, g = this.len; if (b)e = this.toPixels(b[b.series.colorKey]), e < f ? e = f - 2 : e > f + g && (e = f + g + 2), b.plotX = e, b.plotY = this.len - e, p.prototype.drawCrosshair.call(this, a, b), b.plotX = c, b.plotY = d, this.cross && this.cross.attr({fill: this.crosshair.color}).add(this.legendGroup) }, getPlotLinePath: function (a, b, c, d, e) { return typeof e === "number" ? this.horiz ? ["M", e - 4, this.top - 6, "L", e + 4, this.top - 6, e, this.top, "Z"] : ["M", this.left, e, "L", this.left - 6, e + 6, this.left - 6, e - 6, "Z"] : p.prototype.getPlotLinePath.call(this, a, b, c, d) }, update: function (a, b) { var c = this.chart, d = c.legend; j(this.series, function (a) { a.isDirtyData = !0 }); if (a.dataClasses && d.allItems)j(d.allItems, function (a) { a.isDataClass && a.legendGroup.destroy() }), c.isDirtyLegend = !0; c.options[this.coll] = n(this.userOptions, a); p.prototype.update.call(this, a, b); this.legendItem && (this.setLegendColor(), d.colorizeItem(this, !0)) }, getDataClassLegendSymbols: function () { var a = this, b = this.chart, c = this.legendItems, d = b.options.legend, e = d.valueDecimals, f = d.valueSuffix || "", g; c.length || j(this.dataClasses, function (d, i) { var r = !0, A = d.from, k = d.to; g = ""; A === void 0 ? g = "< " : k === void 0 && (g = "> "); A !== void 0 && (g += l.numberFormat(A, e) + f); A !== void 0 && k !== void 0 && (g += " - "); k !== void 0 && (g += l.numberFormat(k, e) + f); c.push(o({ chart: b, name: g, options: {}, drawLegendSymbol: G.drawRectangle, visible: !0, setState: q, isDataClass: !0, setVisible: function () { r = this.visible = !r; j(a.series, function (a) { j(a.points, function (a) { a.dataClass === i && a.setVisible(r) }) }); b.legend.colorizeItem(this, r) } }, d)) }); return c }, name: "" }); j(["fill", "stroke"], function (a) { HighchartsAdapter.addAnimSetter(a, function (b) { b.elem.attr(a, B.prototype.tweenColors(x(b.start), x(b.end), b.pos)) }) }); v(s.prototype, "getAxes", function (a) { var b = this.options.colorAxis; a.call(this); this.colorAxis = []; b && new B(this, b) }); v(C.prototype, "getAllItems", function (a) { var b = [], c = this.chart.colorAxis[0]; c && (c.options.dataClasses ? b = b.concat(c.getDataClassLegendSymbols()) : b.push(c), j(c.series, function (a) { a.options.showInLegend = !1 })); return b.concat(a.call(this)) }); var C = { setVisible: function (a) { var b = this, c = a ? "show" : "hide"; j(["graphic", "dataLabel"], function (a) { if (b[a])b[a][c]() }) } }, M = { pointAttrToOptions: { stroke: "borderColor", "stroke-width": "borderWidth", fill: "color", dashstyle: "dashStyle" }, pointArrayMap: ["value"], axisTypes: ["xAxis", "yAxis", "colorAxis"], optionalAxis: "colorAxis", trackerGroups: ["group", "markerGroup", "dataLabelsGroup"], getSymbol: q, parallelArrays: ["x", "y", "value"], colorKey: "value", translateColors: function () { var a = this, b = this.options.nullColor, c = this.colorAxis, d = this.colorKey; j(this.data, function (e) { var f = e[d]; if (f = e.options.color || (f === null ? b : c && f !== void 0 ? c.toColor(f, e) : e.color || a.color))e.color = f }) } }; o(s.prototype, { renderMapNavigation: function () { var a = this, b = this.options.mapNavigation, c = b.buttons, d, e, f, g, h = function (a) { if (a)a.preventDefault && a.preventDefault(), a.stopPropagation && a.stopPropagation(), a.cancelBubble = !0 }, i = function (b) { this.handler.call(a, b); h(b) }; if (k(b.enableButtons, b.enabled) && !a.renderer.forExport)for (d in c)if (c.hasOwnProperty(d))f = n(b.buttonOptions, c[d]), e = f.theme, e.style = n(f.theme.style, f.style), g = e.states, e = a.renderer.button(f.text, 0, 0, i, e, g && g.hover, g && g.select, 0, d === "zoomIn" ? "topbutton" : "bottombutton").attr({ width: f.width, height: f.height, title: a.options.lang[d], zIndex: 5 }).add(), e.handler = f.onclick, e.align(o(f, { width: e.width, height: 2 * e.height }), null, f.alignTo), I(e.element, "dblclick", h) }, fitToBox: function (a, b) { j([["x", "width"], ["y", "height"]], function (c) { var d = c[0], c = c[1]; a[d] + a[c] > b[d] + b[c] && (a[c] > b[c] ? (a[c] = b[c], a[d] = b[d]) : a[d] = b[d] + b[c] - a[c]); a[c] > b[c] && (a[c] = b[c]); a[d] < b[d] && (a[d] = b[d]) }); return a }, mapZoom: function (a, b, c, d, e) { var f = this.xAxis[0], g = f.max - f.min, h = k(b, f.min + g / 2), i = g * a, g = this.yAxis[0], j = g.max - g.min, A = k(c, g.min + j / 2); j *= a; h = this.fitToBox({ x: h - i * (d ? (d - f.pos) / f.len : 0.5), y: A - j * (e ? (e - g.pos) / g.len : 0.5), width: i, height: j }, {x: f.dataMin, y: g.dataMin, width: f.dataMax - f.dataMin, height: g.dataMax - g.dataMin}); if (d)f.fixTo = [d - f.pos, b]; if (e)g.fixTo = [e - g.pos, c]; a !== void 0 ? (f.setExtremes(h.x, h.x + h.width, !1), g.setExtremes(h.y, h.y + h.height, !1)) : (f.setExtremes(void 0, void 0, !1), g.setExtremes(void 0, void 0, !1)); this.redraw() } }); v(s.prototype, "render", function (a) { var b = this, c = b.options.mapNavigation; b.renderMapNavigation(); a.call(b); (k(c.enableDoubleClickZoom, c.enabled) || c.enableDoubleClickZoomTo) && I(b.container, "dblclick", function (a) { b.pointer.onContainerDblClick(a) }); k(c.enableMouseWheelZoom, c.enabled) && I(b.container, document.onmousewheel === void 0 ? "DOMMouseScroll" : "mousewheel", function (a) { b.pointer.onContainerMouseWheel(a); return !1 }) }); o(F.prototype, { onContainerDblClick: function (a) { var b = this.chart, a = this.normalize(a); b.options.mapNavigation.enableDoubleClickZoomTo ? b.pointer.inClass(a.target, "highcharts-tracker") && b.hoverPoint.zoomTo() : b.isInsidePlot(a.chartX - b.plotLeft, a.chartY - b.plotTop) && b.mapZoom(0.5, b.xAxis[0].toValue(a.chartX), b.yAxis[0].toValue(a.chartY), a.chartX, a.chartY) }, onContainerMouseWheel: function (a) { var b = this.chart, c, a = this.normalize(a); c = a.detail || -(a.wheelDelta / 120); b.isInsidePlot(a.chartX - b.plotLeft, a.chartY - b.plotTop) && b.mapZoom(Math.pow(2, c), b.xAxis[0].toValue(a.chartX), b.yAxis[0].toValue(a.chartY), a.chartX, a.chartY) } }); v(F.prototype, "init", function (a, b, c) { a.call(this, b, c); if (k(c.mapNavigation.enableTouchZoom, c.mapNavigation.enabled))this.pinchX = this.pinchHor = this.pinchY = this.pinchVert = this.hasZoom = !0 }); v(F.prototype, "pinchTranslate", function (a, b, c, d, e, f, g) { a.call(this, b, c, d, e, f, g); this.chart.options.chart.type === "map" && this.hasZoom && (a = d.scaleX > d.scaleY, this.pinchTranslateDirection(!a, b, c, d, e, f, g, a ? d.scaleX : d.scaleY)) }); var E = document.documentElement.style.vectorEffect !== void 0; w.map = n(w.scatter, { allAreas: !0, animation: !1, nullColor: "#F8F8F8", borderColor: "silver", borderWidth: 1, marker: null, stickyTracking: !1, dataLabels: { formatter: function () { return this.point.value }, inside: !0, verticalAlign: "middle", crop: !1, overflow: !1, padding: 0 }, turboThreshold: 0, tooltip: {followPointer: !0, pointFormat: "{point.name}: {point.value}<br/>"}, states: {normal: {animation: !0}, hover: {brightness: 0.2, halo: null}} }); var N = u(t, o({ applyOptions: function (a, b) { var c = t.prototype.applyOptions.call(this, a, b), d = this.series, e = d.joinBy; if (d.mapData)if (e = c[e[1]] !== void 0 && d.mapMap[c[e[1]]]) { if (d.xyFromShape)c.x = e._midX, c.y = e._midY; o(c, e) } else c.value = c.value || null; return c }, onMouseOver: function (a) { clearTimeout(this.colorInterval); if (this.value !== null)t.prototype.onMouseOver.call(this, a); else this.series.onMouseOut(a) }, onMouseOut: function () { var a = this, b = +new Date, c = x(a.color), d = x(a.pointAttr.hover.fill), e = a.series.options.states.normal.animation, f = e && (e.duration || 500), g; if (f && c.rgba.length === 4 && d.rgba.length === 4 && a.state !== "select")g = a.pointAttr[""].fill, delete a.pointAttr[""].fill, clearTimeout(a.colorInterval), a.colorInterval = setInterval(function () { var e = (new Date - b) / f, g = a.graphic; e > 1 && (e = 1); g && g.attr("fill", B.prototype.tweenColors.call(0, d, c, e)); e >= 1 && clearTimeout(a.colorInterval) }, 13); t.prototype.onMouseOut.call(a); if (g)a.pointAttr[""].fill = g }, zoomTo: function () { var a = this.series; a.xAxis.setExtremes(this._minX, this._maxX, !1); a.yAxis.setExtremes(this._minY, this._maxY, !1); a.chart.redraw() } }, C)); m.map = u(m.scatter, n(M, { type: "map", pointClass: N, supportsDrilldown: !0, getExtremesFromAll: !0, useMapGeometry: !0, forceDL: !0, searchPoint: q, directTouch: !0, preserveAspectRatio: !0, getBox: function (a) { var b = Number.MAX_VALUE, c = -b, d = b, e = -b, f = b, g = b, h = this.xAxis, i = this.yAxis, r; j(a || [], function (a) { if (a.path) { if (typeof a.path === "string")a.path = l.splitPath(a.path); var h = a.path || [], i = h.length, j = !1, m = -b, n = b, o = -b, p = b, q = a.properties; if (!a._foundBox) { for (; i--;)typeof h[i] === "number" && !isNaN(h[i]) && (j ? (m = Math.max(m, h[i]), n = Math.min(n, h[i])) : (o = Math.max(o, h[i]), p = Math.min(p, h[i])), j = !j); a._midX = n + (m - n) * (a.middleX || q && q["hc-middle-x"] || 0.5); a._midY = p + (o - p) * (a.middleY || q && q["hc-middle-y"] || 0.5); a._maxX = m; a._minX = n; a._maxY = o; a._minY = p; a.labelrank = k(a.labelrank, (m - n) * (o - p)); a._foundBox = !0 } c = Math.max(c, a._maxX); d = Math.min(d, a._minX); e = Math.max(e, a._maxY); f = Math.min(f, a._minY); g = Math.min(a._maxX - a._minX, a._maxY - a._minY, g); r = !0 } }); if (r) { this.minY = Math.min(f, k(this.minY, b)); this.maxY = Math.max(e, k(this.maxY, -b)); this.minX = Math.min(d, k(this.minX, b)); this.maxX = Math.max(c, k(this.maxX, -b)); if (h && h.options.minRange === void 0)h.minRange = Math.min(5 * g, (this.maxX - this.minX) / 5, h.minRange || b); if (i && i.options.minRange === void 0)i.minRange = Math.min(5 * g, (this.maxY - this.minY) / 5, i.minRange || b) } }, getExtremes: function () { y.prototype.getExtremes.call(this, this.valueData); this.chart.hasRendered && this.isDirtyData && this.getBox(this.options.data); this.valueMin = this.dataMin; this.valueMax = this.dataMax; this.dataMin = this.minY; this.dataMax = this.maxY }, translatePath: function (a) { var b = !1, c = this.xAxis, d = this.yAxis, e = c.min, f = c.transA, c = c.minPixelPadding, g = d.min, h = d.transA, d = d.minPixelPadding, i, j = []; if (a)for (i = a.length; i--;)typeof a[i] === "number" ? (j[i] = b ? (a[i] - e) * f + c : (a[i] - g) * h + d, b = !b) : j[i] = a[i]; return j }, setData: function (a, b) { var c = this.options, d = c.mapData, e = c.joinBy, f = e === null, g = [], h, i, k; f && (e = "_i"); e = this.joinBy = l.splat(e); e[1] || (e[1] = e[0]); a && j(a, function (b, c) { typeof b === "number" && (a[c] = {value: b}); if (f)a[c]._i = c }); this.getBox(a); if (d) { if (d.type === "FeatureCollection") { if (d["hc-transform"])for (h in this.chart.mapTransforms = i = d["hc-transform"], i)if (i.hasOwnProperty(h) && h.rotation)h.cosAngle = Math.cos(h.rotation), h.sinAngle = Math.sin(h.rotation); d = l.geojson(d, this.type, this) } this.getBox(d); this.mapData = d; this.mapMap = {}; for (k = 0; k < d.length; k++)h = d[k], i = h.properties, h._i = k, e[0] && i && i[e[0]] && (h[e[0]] = i[e[0]]), this.mapMap[h[e[0]]] = h; c.allAreas && (a = a || [], e[1] && j(a, function (a) { g.push(a[e[1]]) }), g = "|" + g.join("|") + "|", j(d, function (b) { (!e[0] || g.indexOf("|" + b[e[0]] + "|") === -1) && a.push(n(b, {value: null})) })) } y.prototype.setData.call(this, a, b) }, drawGraph: q, drawDataLabels: q, doFullTranslate: function () { return this.isDirtyData || this.chart.isResizing || this.chart.renderer.isVML || !this.baseTrans }, translate: function () { var a = this, b = a.xAxis, c = a.yAxis, d = a.doFullTranslate(); a.generatePoints(); j(a.data, function (e) { e.plotX = b.toPixels(e._midX, !0); e.plotY = c.toPixels(e._midY, !0); if (d)e.shapeType = "path", e.shapeArgs = {d: a.translatePath(e.path)}, E && (e.shapeArgs["vector-effect"] = "non-scaling-stroke") }); a.translateColors() }, drawPoints: function () { var a = this, b = a.xAxis, c = a.yAxis, d = a.group, e = a.chart, f = e.renderer, g, h = this.baseTrans; if (!a.transformGroup)a.transformGroup = f.g().attr({ scaleX: 1, scaleY: 1 }).add(d), a.transformGroup.survive = !0; a.doFullTranslate() ? (e.hasRendered && a.pointAttrToOptions.fill === "color" && j(a.points, function (a) { if (a.shapeArgs)a.shapeArgs.fill = a.pointAttr[k(a.state, "")].fill }), E || j(a.points, function (b) { b = b.pointAttr[""]; b["stroke-width"] === a.pointAttr[""]["stroke-width"] && (b["stroke-width"] = "inherit") }), a.group = a.transformGroup, m.column.prototype.drawPoints.apply(a), a.group = d, j(a.points, function (a) { a.graphic && (a.name && a.graphic.addClass("highcharts-name-" + a.name.replace(" ", "-").toLowerCase()), a.properties && a.properties["hc-key"] && a.graphic.addClass("highcharts-key-" + a.properties["hc-key"].toLowerCase()), E || (a.graphic["stroke-widthSetter"] = q)) }), this.baseTrans = { originX: b.min - b.minPixelPadding / b.transA, originY: c.min - c.minPixelPadding / c.transA + (c.reversed ? 0 : c.len / c.transA), transAX: b.transA, transAY: c.transA }, this.transformGroup.animate({ translateX: 0, translateY: 0, scaleX: 1, scaleY: 1 })) : (g = b.transA / h.transAX, d = c.transA / h.transAY, b = b.toPixels(h.originX, !0), c = c.toPixels(h.originY, !0), g > 0.99 && g < 1.01 && d > 0.99 && d < 1.01 && (d = g = 1, b = Math.round(b), c = Math.round(c)), this.transformGroup.animate({ translateX: b, translateY: c, scaleX: g, scaleY: d })); E || a.group.element.setAttribute("stroke-width", a.options.borderWidth / (g || 1)); this.drawMapDataLabels() }, drawMapDataLabels: function () { y.prototype.drawDataLabels.call(this); this.dataLabelsGroup && this.dataLabelsGroup.clip(this.chart.clipRect) }, render: function () { var a = this, b = y.prototype.render; a.chart.renderer.isVML && a.data.length > 3E3 ? setTimeout(function () { b.call(a) }) : b.call(a) }, animate: function (a) { var b = this.options.animation, c = this.group, d = this.xAxis, e = this.yAxis, f = d.pos, g = e.pos; if (this.chart.renderer.isSVG)b === !0 && (b = {duration: 1E3}), a ? c.attr({ translateX: f + d.len / 2, translateY: g + e.len / 2, scaleX: 0.001, scaleY: 0.001 }) : (c.animate({translateX: f, translateY: g, scaleX: 1, scaleY: 1}, b), this.animate = null) }, animateDrilldown: function (a) { var b = this.chart.plotBox, c = this.chart.drilldownLevels[this.chart.drilldownLevels.length - 1], d = c.bBox, e = this.chart.options.drilldown.animation; if (!a)a = Math.min(d.width / b.width, d.height / b.height), c.shapeArgs = { scaleX: a, scaleY: a, translateX: d.x, translateY: d.y }, j(this.points, function (a) { a.graphic && a.graphic.attr(c.shapeArgs).animate({ scaleX: 1, scaleY: 1, translateX: 0, translateY: 0 }, e) }), this.animate = null }, drawLegendSymbol: G.drawRectangle, animateDrillupFrom: function (a) { m.column.prototype.animateDrillupFrom.call(this, a) }, animateDrillupTo: function (a) { m.column.prototype.animateDrillupTo.call(this, a) } })); w.mapline = n(w.map, {lineWidth: 1, fillColor: "none"}); m.mapline = u(m.map, { type: "mapline", pointAttrToOptions: {stroke: "color", "stroke-width": "lineWidth", fill: "fillColor", dashstyle: "dashStyle"}, drawLegendSymbol: m.line.prototype.drawLegendSymbol }); w.mappoint = n(w.scatter, { dataLabels: { enabled: !0, formatter: function () { return this.point.name }, crop: !1, defer: !1, overflow: !1, style: {color: "#000000"} } }); m.mappoint = u(m.scatter, { type: "mappoint", forceDL: !0, pointClass: u(t, { applyOptions: function (a, b) { var c = t.prototype.applyOptions.call(this, a, b); a.lat !== void 0 && a.lon !== void 0 && (c = o(c, this.series.chart.fromLatLonToPoint(c))); return c } }) }); if (m.bubble)w.mapbubble = n(w.bubble, { animationLimit: 500, tooltip: {pointFormat: "{point.name}: {point.z}"} }), m.mapbubble = u(m.bubble, { pointClass: u(t, { applyOptions: function (a, b) { var c; a && a.lat !== void 0 && a.lon !== void 0 ? (c = t.prototype.applyOptions.call(this, a, b), c = o(c, this.series.chart.fromLatLonToPoint(c))) : c = N.prototype.applyOptions.call(this, a, b); return c }, ttBelow: !1 }), xyFromShape: !0, type: "mapbubble", pointArrayMap: ["z"], getMapData: m.map.prototype.getMapData, getBox: m.map.prototype.getBox, setData: m.map.prototype.setData }); z.plotOptions.heatmap = n(z.plotOptions.scatter, { animation: !1, borderWidth: 0, nullColor: "#F8F8F8", dataLabels: { formatter: function () { return this.point.value }, inside: !0, verticalAlign: "middle", crop: !1, overflow: !1, padding: 0 }, marker: null, pointRange: null, tooltip: {pointFormat: "{point.x}, {point.y}: {point.value}<br/>"}, states: { normal: {animation: !0}, hover: {halo: !1, brightness: 0.2} } }); m.heatmap = u(m.scatter, n(M, { type: "heatmap", pointArrayMap: ["y", "value"], hasPointSpecificOptions: !0, pointClass: u(t, C), supportsDrilldown: !0, getExtremesFromAll: !0, directTouch: !0, init: function () { var a; m.scatter.prototype.init.apply(this, arguments); a = this.options; this.pointRange = a.pointRange = k(a.pointRange, a.colsize || 1); this.yAxis.axisPointRange = a.rowsize || 1 }, translate: function () { var a = this.options, b = this.xAxis, c = this.yAxis, d = function (a, b, c) { return Math.min(Math.max(b, a), c) }; this.generatePoints(); j(this.points, function (e) { var f = (a.colsize || 1) / 2, g = (a.rowsize || 1) / 2, h = d(Math.round(b.len - b.translate(e.x - f, 0, 1, 0, 1)), 0, b.len), f = d(Math.round(b.len - b.translate(e.x + f, 0, 1, 0, 1)), 0, b.len), i = d(Math.round(c.translate(e.y - g, 0, 1, 0, 1)), 0, c.len), g = d(Math.round(c.translate(e.y + g, 0, 1, 0, 1)), 0, c.len); e.plotX = e.clientX = (h + f) / 2; e.plotY = (i + g) / 2; e.shapeType = "rect"; e.shapeArgs = {x: Math.min(h, f), y: Math.min(i, g), width: Math.abs(f - h), height: Math.abs(g - i)} }); this.translateColors(); this.chart.hasRendered && j(this.points, function (a) { a.shapeArgs.fill = a.options.color || a.color }) }, drawPoints: m.column.prototype.drawPoints, animate: q, getBox: q, drawLegendSymbol: G.drawRectangle, getExtremes: function () { y.prototype.getExtremes.call(this, this.valueData); this.valueMin = this.dataMin; this.valueMax = this.dataMax; y.prototype.getExtremes.call(this) } })); s.prototype.transformFromLatLon = function (a, b) { if (window.proj4 === void 0)return D(21), {x: 0, y: null}; var c = window.proj4(b.crs, [a.lon, a.lat]), d = b.cosAngle || b.rotation && Math.cos(b.rotation), e = b.sinAngle || b.rotation && Math.sin(b.rotation), c = b.rotation ? [c[0] * d + c[1] * e, -c[0] * e + c[1] * d] : c; return { x: ((c[0] - (b.xoffset || 0)) * (b.scale || 1) + (b.xpan || 0)) * (b.jsonres || 1) + (b.jsonmarginX || 0), y: (((b.yoffset || 0) - c[1]) * (b.scale || 1) + (b.ypan || 0)) * (b.jsonres || 1) - (b.jsonmarginY || 0) } }; s.prototype.transformToLatLon = function (a, b) { if (window.proj4 === void 0)D(21); else { var c = { x: ((a.x - (b.jsonmarginX || 0)) / (b.jsonres || 1) - (b.xpan || 0)) / (b.scale || 1) + (b.xoffset || 0), y: ((-a.y - (b.jsonmarginY || 0)) / (b.jsonres || 1) + (b.ypan || 0)) / (b.scale || 1) + (b.yoffset || 0) }, d = b.cosAngle || b.rotation && Math.cos(b.rotation), e = b.sinAngle || b.rotation && Math.sin(b.rotation), c = window.proj4(b.crs, "WGS84", b.rotation ? { x: c.x * d + c.y * -e, y: c.x * e + c.y * d } : c); return {lat: c.y, lon: c.x} } }; s.prototype.fromPointToLatLon = function (a) { var b = this.mapTransforms, c; if (b) { for (c in b)if (b.hasOwnProperty(c) && b[c].hitZone && J({ x: a.x, y: -a.y }, b[c].hitZone.coordinates[0]))return this.transformToLatLon(a, b[c]); return this.transformToLatLon(a, b["default"]) } else D(22) }; s.prototype.fromLatLonToPoint = function (a) { var b = this.mapTransforms, c, d; if (!b)return D(22), {x: 0, y: null}; for (c in b)if (b.hasOwnProperty(c) && b[c].hitZone && (d = this.transformFromLatLon(a, b[c]), J({ x: d.x, y: -d.y }, b[c].hitZone.coordinates[0])))return d; return this.transformFromLatLon(a, b["default"]) }; l.geojson = function (a, b, c) { var d = [], e = [], f = function (a) { var b = 0, c = a.length; for (e.push("M"); b < c; b++)b === 1 && e.push("L"), e.push(a[b][0], -a[b][1]) }, b = b || "map"; j(a.features, function (a) { var c = a.geometry, i = c.type, c = c.coordinates, a = a.properties, k; e = []; b === "map" || b === "mapbubble" ? (i === "Polygon" ? (j(c, f), e.push("Z")) : i === "MultiPolygon" && (j(c, function (a) { j(a, f) }), e.push("Z")), e.length && (k = {path: e})) : b === "mapline" ? (i === "LineString" ? f(c) : i === "MultiLineString" && j(c, f), e.length && (k = {path: e})) : b === "mappoint" && i === "Point" && (k = { x: c[0], y: -c[1] }); k && d.push(o(k, {name: a.name || a.NAME, properties: a})) }); if (c && a.copyrightShort)c.chart.mapCredits = '<a href="http://www.highcharts.com">Highcharts</a> \u00a9 <a href="' + a.copyrightUrl + '">' + a.copyrightShort + "</a>", c.chart.mapCreditsFull = a.copyright; return d }; v(s.prototype, "showCredits", function (a, b) { if (z.credits.text === this.options.credits.text && this.mapCredits)b.text = this.mapCredits, b.href = null; a.call(this, b); this.credits && this.credits.attr({title: this.mapCreditsFull}) }); o(z.lang, {zoomIn: "Zoom in", zoomOut: "Zoom out"}); z.mapNavigation = { buttonOptions: { alignTo: "plotBox", align: "left", verticalAlign: "top", x: 0, width: 18, height: 18, style: {fontSize: "15px", fontWeight: "bold", textAlign: "center"}, theme: {"stroke-width": 1} }, buttons: { zoomIn: { onclick: function () { this.mapZoom(0.5) }, text: "+", y: 0 }, zoomOut: { onclick: function () { this.mapZoom(2) }, text: "-", y: 28 } } }; l.splitPath = function (a) { var b, a = a.replace(/([A-Za-z])/g, " $1 "), a = a.replace(/^\s*/, "").replace(/\s*$/, ""), a = a.split(/[ ,]+/); for (b = 0; b < a.length; b++)/[a-zA-Z]/.test(a[b]) || (a[b] = parseFloat(a[b])); return a }; l.maps = {}; H.prototype.symbols.topbutton = function (a, b, c, d, e) { return K(a - 1, b - 1, c, d, e.r, e.r, 0, 0) }; H.prototype.symbols.bottombutton = function (a, b, c, d, e) { return K(a - 1, b - 1, c, d, 0, 0, e.r, e.r) }; O === L && j(["topbutton", "bottombutton"], function (a) { L.prototype.symbols[a] = H.prototype.symbols[a] }); l.Map = function (a, b) { var c = { endOnTick: !1, gridLineWidth: 0, lineWidth: 0, minPadding: 0, maxPadding: 0, startOnTick: !1, title: null, tickPositions: [] }, d; d = a.series; a.series = null; a = n({chart: {panning: "xy", type: "map"}, xAxis: c, yAxis: n(c, {reversed: !0})}, a, { chart: { inverted: !1, alignTicks: !1 } }); a.series = d; return new s(a, b) } })(Highcharts);
var class_symp_1_1_sound_manager = [ [ "clearSoundArray", "class_symp_1_1_sound_manager.html#af80ac26864c4c5ce194ba9a83c8c77eb", null ], [ "deleteSound", "class_symp_1_1_sound_manager.html#a698683e6aba812834d9a9e08cadd2587", null ], [ "errCheck", "class_symp_1_1_sound_manager.html#aa82b83dfbd0b594da8373304e9b414ce", null ], [ "getSoundsCount", "class_symp_1_1_sound_manager.html#ab96e94d7739ae86a580417fc19a88037", null ], [ "loadSound", "class_symp_1_1_sound_manager.html#a972352cbe24f1c8b0d7565947bb7a57c", null ], [ "loop", "class_symp_1_1_sound_manager.html#a7f80b283b003d17f63e3a456f1a7c595", null ], [ "playSound", "class_symp_1_1_sound_manager.html#ac2468cc62d82609a0b40c0fc762e41ad", null ], [ "removeLoop", "class_symp_1_1_sound_manager.html#a57f819ab0ef3f5afabe93f79fdedf9b7", null ], [ "setVolume", "class_symp_1_1_sound_manager.html#af34876657adc807356d0de9afda2b3e9", null ], [ "stopSound", "class_symp_1_1_sound_manager.html#a8c9c583fca013bd40de6727dd9e73f8f", null ], [ "toggleLoop", "class_symp_1_1_sound_manager.html#a69c7f20fb91625fb90e9930bf1df5832", null ], [ "Singleton< SoundManager >", "class_symp_1_1_sound_manager.html#a0caa66cbb01357370233dc2bd5fdb585", null ] ];
//PageBlock Directive //Requires: jQuery, jQueryUI //Scope is controllers schedulerWebApp.directive('availableBlock', [function() { return { restrict: 'A', link: function(scope, element, attrs){ //console.log(attrs); element.draggable({ //revert:true, helper: function(){ return '<div id="ui-helper-page"><i class="fa fa-file-o"></i><div class="block-name">New Page</div></div>'; }, start: function(){ $('.scBar-page-block') .addClass('suppressed-for-new-item'); }, drag: function(event, ui){ //Rest Supress $('.scBar-page-block').removeClass('suppressed-for-new-item'); $(this) .addClass('minimised'); $(ui.helper) .find('.block-name') .html($(this).find('.block-name').text()+'('+ui.position.left+')'); }, stop: function(){ $(this) .removeClass('minimised'); $('.scBar-page-block') .removeClass('suppressed-for-new-item'); } }); } } }]);
// @flow import { type Position } from "../util/location"; import { tokenIsLiteralPropertyName, tokenLabelName, tt, type TokenType, } from "../tokenizer/types"; import Tokenizer from "../tokenizer"; import State from "../tokenizer/state"; import type { Node } from "../types"; import { lineBreak, skipWhiteSpaceToLineBreak } from "../util/whitespace"; import { isIdentifierChar } from "../util/identifier"; import ClassScopeHandler from "../util/class-scope"; import ExpressionScopeHandler from "../util/expression-scope"; import { SCOPE_PROGRAM } from "../util/scopeflags"; import ProductionParameterHandler, { PARAM_AWAIT, PARAM, } from "../util/production-parameter"; import { Errors, type ErrorTemplate, ErrorCodes } from "./error"; import type { ParsingError } from "./error"; import type { PluginConfig } from "./base"; /*:: import type ScopeHandler from "../util/scope"; */ type TryParse<Node, Error, Thrown, Aborted, FailState> = { node: Node, error: Error, thrown: Thrown, aborted: Aborted, failState: FailState, }; // ## Parser utilities export default class UtilParser extends Tokenizer { // Forward-declaration: defined in parser/index.js /*:: +getScopeHandler: () => Class<ScopeHandler<*>>; */ // TODO addExtra( node: Node, key: string, value: any, enumerable: boolean = true, ): void { if (!node) return; const extra = (node.extra = node.extra || {}); if (enumerable) { extra[key] = value; } else { Object.defineProperty(extra, key, { enumerable, value }); } } // Tests whether parsed token is a contextual keyword. isContextual(token: TokenType): boolean { return this.state.type === token && !this.state.containsEsc; } isUnparsedContextual(nameStart: number, name: string): boolean { const nameEnd = nameStart + name.length; if (this.input.slice(nameStart, nameEnd) === name) { const nextCh = this.input.charCodeAt(nameEnd); return !( isIdentifierChar(nextCh) || // check if `nextCh is between 0xd800 - 0xdbff, // if `nextCh` is NaN, `NaN & 0xfc00` is 0, the function // returns true (nextCh & 0xfc00) === 0xd800 ); } return false; } isLookaheadContextual(name: string): boolean { const next = this.nextTokenStart(); return this.isUnparsedContextual(next, name); } // Consumes contextual keyword if possible. eatContextual(token: TokenType): boolean { if (this.isContextual(token)) { this.next(); return true; } return false; } // Asserts that following token is given contextual keyword. expectContextual(token: TokenType, template?: ErrorTemplate): void { if (!this.eatContextual(token)) { if (template != null) { /* eslint-disable @babel/development-internal/dry-error-messages */ throw this.raise(template, { at: this.state.startLoc }); } throw this.unexpected(null, token); } } // Test whether a semicolon can be inserted at the current position. canInsertSemicolon(): boolean { return ( this.match(tt.eof) || this.match(tt.braceR) || this.hasPrecedingLineBreak() ); } hasPrecedingLineBreak(): boolean { return lineBreak.test( this.input.slice(this.state.lastTokEndLoc.index, this.state.start), ); } hasFollowingLineBreak(): boolean { skipWhiteSpaceToLineBreak.lastIndex = this.state.end; return skipWhiteSpaceToLineBreak.test(this.input); } // TODO isLineTerminator(): boolean { return this.eat(tt.semi) || this.canInsertSemicolon(); } // Consume a semicolon, or, failing that, see if we are allowed to // pretend that there is a semicolon at this position. semicolon(allowAsi: boolean = true): void { if (allowAsi ? this.isLineTerminator() : this.eat(tt.semi)) return; this.raise(Errors.MissingSemicolon, { at: this.state.lastTokEndLoc }); } // Expect a token of a given type. If found, consume it, otherwise, // raise an unexpected token error at given pos. expect(type: TokenType, loc?: ?Position): void { this.eat(type) || this.unexpected(loc, type); } // Throws if the current token and the prev one are separated by a space. assertNoSpace(message: string = "Unexpected space."): void { if (this.state.start > this.state.lastTokEndLoc.index) { /* eslint-disable @babel/development-internal/dry-error-messages */ this.raise( { code: ErrorCodes.SyntaxError, reasonCode: "UnexpectedSpace", template: message, }, { at: this.state.lastTokEndLoc }, /* eslint-enable @babel/development-internal/dry-error-messages */ ); } } // Raise an unexpected token error. Can take the expected token type // instead of a message string. unexpected(loc?: ?Position, type?: ?TokenType): empty { /* eslint-disable @babel/development-internal/dry-error-messages */ throw this.raise( { code: ErrorCodes.SyntaxError, reasonCode: "UnexpectedToken", template: type != null ? `Unexpected token, expected "${tokenLabelName(type)}"` : "Unexpected token", }, { at: loc != null ? loc : this.state.startLoc }, ); /* eslint-enable @babel/development-internal/dry-error-messages */ } getPluginNamesFromConfigs(pluginConfigs: Array<PluginConfig>): Array<string> { return pluginConfigs.map(c => { if (typeof c === "string") { return c; } else { return c[0]; } }); } expectPlugin(pluginConfig: PluginConfig, loc?: ?Position): true { if (!this.hasPlugin(pluginConfig)) { throw this.raiseWithData( loc != null ? loc : this.state.startLoc, { missingPlugin: this.getPluginNamesFromConfigs([pluginConfig]) }, `This experimental syntax requires enabling the parser plugin: ${JSON.stringify( pluginConfig, )}.`, ); } return true; } expectOnePlugin(pluginConfigs: Array<PluginConfig>): void { if (!pluginConfigs.some(c => this.hasPlugin(c))) { throw this.raiseWithData( this.state.startLoc, { missingPlugin: this.getPluginNamesFromConfigs(pluginConfigs) }, `This experimental syntax requires enabling one of the following parser plugin(s): ${pluginConfigs .map(c => JSON.stringify(c)) .join(", ")}.`, ); } } // tryParse will clone parser state. // It is expensive and should be used with cautions tryParse<T: Node | $ReadOnlyArray<Node>>( fn: (abort: (node?: T) => empty) => T, oldState: State = this.state.clone(), ): | TryParse<T, null, false, false, null> | TryParse<T | null, ParsingError, boolean, false, State> | TryParse<T | null, null, false, true, State> { const abortSignal: { node: T | null } = { node: null }; try { const node = fn((node = null) => { abortSignal.node = node; throw abortSignal; }); if (this.state.errors.length > oldState.errors.length) { const failState = this.state; this.state = oldState; // tokensLength should be preserved during error recovery mode // since the parser does not halt and will instead parse the // remaining tokens this.state.tokensLength = failState.tokensLength; return { node, error: (failState.errors[oldState.errors.length]: ParsingError), thrown: false, aborted: false, failState, }; } return { node, error: null, thrown: false, aborted: false, failState: null, }; } catch (error) { const failState = this.state; this.state = oldState; if (error instanceof SyntaxError) { return { node: null, error, thrown: true, aborted: false, failState }; } if (error === abortSignal) { return { node: abortSignal.node, error: null, thrown: false, aborted: true, failState, }; } throw error; } } checkExpressionErrors( refExpressionErrors: ?ExpressionErrors, andThrow: boolean, ) { if (!refExpressionErrors) return false; const { shorthandAssignLoc, doubleProtoLoc, privateKeyLoc, optionalParametersLoc, } = refExpressionErrors; const hasErrors = !!shorthandAssignLoc || !!doubleProtoLoc || !!optionalParametersLoc || !!privateKeyLoc; if (!andThrow) { return hasErrors; } if (shorthandAssignLoc != null) { this.raise(Errors.InvalidCoverInitializedName, { at: shorthandAssignLoc, }); } if (doubleProtoLoc != null) { this.raise(Errors.DuplicateProto, { at: doubleProtoLoc }); } if (privateKeyLoc != null) { this.raise(Errors.UnexpectedPrivateField, { at: privateKeyLoc }); } if (optionalParametersLoc != null) { this.unexpected(optionalParametersLoc); } } /** * Test if current token is a literal property name * https://tc39.es/ecma262/#prod-LiteralPropertyName * LiteralPropertyName: * IdentifierName * StringLiteral * NumericLiteral * BigIntLiteral */ isLiteralPropertyName(): boolean { return tokenIsLiteralPropertyName(this.state.type); } /* * Test if given node is a PrivateName * will be overridden in ESTree plugin */ isPrivateName(node: Node): boolean { return node.type === "PrivateName"; } /* * Return the string value of a given private name * WITHOUT `#` * @see {@link https://tc39.es/ecma262/#sec-static-semantics-stringvalue} */ getPrivateNameSV(node: Node): string { return node.id.name; } /* * Return whether the given node is a member/optional chain that * contains a private name as its property * It is overridden in ESTree plugin */ hasPropertyAsPrivateName(node: Node): boolean { return ( (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && this.isPrivateName(node.property) ); } isOptionalChain(node: Node): boolean { return ( node.type === "OptionalMemberExpression" || node.type === "OptionalCallExpression" ); } isObjectProperty(node: Node): boolean { return node.type === "ObjectProperty"; } isObjectMethod(node: Node): boolean { return node.type === "ObjectMethod"; } initializeScopes( inModule: boolean = this.options.sourceType === "module", ): () => void { // Initialize state const oldLabels = this.state.labels; this.state.labels = []; const oldExportedIdentifiers = this.exportedIdentifiers; this.exportedIdentifiers = new Set(); // initialize scopes const oldInModule = this.inModule; this.inModule = inModule; const oldScope = this.scope; const ScopeHandler = this.getScopeHandler(); this.scope = new ScopeHandler(this.raise.bind(this), this.inModule); const oldProdParam = this.prodParam; this.prodParam = new ProductionParameterHandler(); const oldClassScope = this.classScope; this.classScope = new ClassScopeHandler(this.raise.bind(this)); const oldExpressionScope = this.expressionScope; this.expressionScope = new ExpressionScopeHandler(this.raise.bind(this)); return () => { // Revert state this.state.labels = oldLabels; this.exportedIdentifiers = oldExportedIdentifiers; // Revert scopes this.inModule = oldInModule; this.scope = oldScope; this.prodParam = oldProdParam; this.classScope = oldClassScope; this.expressionScope = oldExpressionScope; }; } enterInitialScopes() { let paramFlags = PARAM; if (this.inModule) { paramFlags |= PARAM_AWAIT; } this.scope.enter(SCOPE_PROGRAM); this.prodParam.enter(paramFlags); } checkDestructuringPrivate(refExpressionErrors: ExpressionErrors) { const { privateKeyLoc } = refExpressionErrors; if (privateKeyLoc !== null) { this.expectPlugin("destructuringPrivate", privateKeyLoc); } } } /** * The ExpressionErrors is a context struct used to track ambiguous patterns * When we are sure the parsed pattern is a RHS, which means it is not a pattern, * we will throw on this position on invalid assign syntax, otherwise it will be reset to -1 * * Types of ExpressionErrors: * * - **shorthandAssignLoc**: track initializer `=` position * - **doubleProtoLoc**: track the duplicate `__proto__` key position * - **privateKey**: track private key `#p` position * - **optionalParametersLoc**: track the optional paramter (`?`). * It's only used by typescript and flow plugins */ export class ExpressionErrors { shorthandAssignLoc: ?Position = null; doubleProtoLoc: ?Position = null; privateKeyLoc: ?Position = null; optionalParametersLoc: ?Position = null; }
var LEVEL = { panic: 0, emerg: 0, alert: 1, crit: 2, err: 3, error: 3, warning: 4, warn: 4, notice: 5, info: 6, debug: 7 } function Acceptor (accept, chain) { this._root = {} this._append([{ path: '.', accept: !! accept }]) this._append(chain) } function select (entry, path) { var objects = [ entry ] for (var i = 0, I = path.length; i < I; i++) { var expanded = [] for (var j = 0, J = objects.length; j < J; j++) { var value = objects[j][path[i]] if (value != null) { if (Array.isArray(value)) { Array.prototype.push.apply(expanded, value) } else { expanded.push(value) } } } objects = expanded } return objects } Acceptor.prototype.accept = function (entry) { var path = ('.' + entry.qualifier + '.').split('.'), accept = false var i = 0 var node = this._root var links = [] for (;;) { var child = node[path[i]] if (child == null) { break } Array.prototype.push.apply(links, child['.links']) node = child i++ } ACCEPT: for (;;) { var link = links.pop() if (link.level == null || LEVEL[entry.level] <= LEVEL[link.level]) { if (link.test == null) { accept = !! link.accept break ACCEPT } TEST: for (var i = 0, I = link.test.length; i < I; i++) { var test = link.test[i] var values = select(entry, test.path) if (values.length == 0) { } switch (test.type) { case 'equals': for (var j = 0, J = values.length; j < J; j++) { if (values[j] == test.equals) { continue TEST } } continue ACCEPT case 'regex': for (var j = 0, J = values.length; j < J; j++) { if (test.regex.test(values[j])) { continue TEST } } continue ACCEPT } } accept = !! link.accept break ACCEPT } } return accept } Acceptor.prototype._append = function (chain) { for (var i = 0, I = chain.length; i < I; i++) { var link = chain[i] var path = link.path == '.' ? [ '' ] : link.path.split('.') var node = this._root for (var j = 0, J = path.length; j < J; j++) { if (!node[path[j]]) { node[path[j]] = { '.links': [] } } node = node[path[j]] } if (link.test != null) { link.test.forEach(function (condition) { condition.path = condition.path.split('.') if (condition.equals) { condition.type = 'equals' } else if (condition.regex) { var regex = /^\/(.*)\/(?!.*(.).*\2)([gimuy]*)$/.exec(condition.regex) condition.type = 'regex' condition.regex = new RegExp(regex[1], regex[3]) } else { throw new Error('invalid test') } }) } node['.links'].push(link) } } module.exports = Acceptor
/* * Scroller * http://github.com/zynga/scroller * * Copyright 2011, Zynga Inc. * Licensed under the MIT License. * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt * * Based on the work of: Unify Project (unify-project.org) * http://unify-project.org * Copyright 2011, Deutsche Telekom AG * License: MIT + Apache (V2) */ var Scroller; (function() { var NOOP = function(){}; /** * A pure logic 'component' for 'virtual' scrolling/zooming. */ Scroller = function(callback, options) { this.__callback = callback; this.options = { /** Enable scrolling on x-axis */ scrollingX: true, /** Enable scrolling on y-axis */ scrollingY: true, /** Enable animations for deceleration, snap back, zooming and scrolling */ animating: true, /** duration for animations triggered by scrollTo/zoomTo */ animationDuration: 250, /** Enable bouncing (content can be slowly moved outside and jumps back after releasing) */ bouncing: true, /** Enable locking to the main axis if user moves only slightly on one of them at start */ locking: true, /** Enable pagination mode (switching between full page content panes) */ paging: false, /** Enable snapping of content to a configured pixel grid */ snapping: false, /** Enable zooming of content via API, fingers and mouse wheel */ zooming: false, /** Minimum zoom level */ minZoom: 0.5, /** Maximum zoom level */ maxZoom: 3, /** Multiply or decrease scrolling speed **/ speedMultiplier: 1, /** Callback that is fired on the later of touch end or deceleration end, provided that another scrolling action has not begun. Used to know when to fade out a scrollbar. */ scrollingComplete: NOOP, /** This configures the amount of change applied to deceleration when reaching boundaries **/ penetrationDeceleration : 0.03, /** This configures the amount of change applied to acceleration when reaching boundaries **/ penetrationAcceleration : 0.08 }; for (var key in options) { this.options[key] = options[key]; } }; // Easing Equations (c) 2003 Robert Penner, all rights reserved. // Open source under the BSD License. /** * @param pos {Number} position between 0 (start of effect) and 1 (end of effect) **/ var easeOutCubic = function(pos) { return (Math.pow((pos - 1), 3) + 1); }; /** * @param pos {Number} position between 0 (start of effect) and 1 (end of effect) **/ var easeInOutCubic = function(pos) { if ((pos /= 0.5) < 1) { return 0.5 * Math.pow(pos, 3); } return 0.5 * (Math.pow((pos - 2), 3) + 2); }; var members = { /* --------------------------------------------------------------------------- INTERNAL FIELDS :: STATUS --------------------------------------------------------------------------- */ /** {Boolean} Whether only a single finger is used in touch handling */ __isSingleTouch: false, /** {Boolean} Whether a touch event sequence is in progress */ __isTracking: false, /** {Boolean} Whether a deceleration animation went to completion. */ __didDecelerationComplete: false, /** * {Boolean} Whether a gesture zoom/rotate event is in progress. Activates when * a gesturestart event happens. This has higher priority than dragging. */ __isGesturing: false, /** * {Boolean} Whether the user has moved by such a distance that we have enabled * dragging mode. Hint: It's only enabled after some pixels of movement to * not interrupt with clicks etc. */ __isDragging: false, /** * {Boolean} Not touching and dragging anymore, and smoothly animating the * touch sequence using deceleration. */ __isDecelerating: false, /** * {Boolean} Smoothly animating the currently configured change */ __isAnimating: false, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: DIMENSIONS --------------------------------------------------------------------------- */ /** {Integer} Available outer left position (from document perspective) */ __clientLeft: 0, /** {Integer} Available outer top position (from document perspective) */ __clientTop: 0, /** {Integer} Available outer width */ __clientWidth: 0, /** {Integer} Available outer height */ __clientHeight: 0, /** {Integer} Outer width of content */ __contentWidth: 0, /** {Integer} Outer height of content */ __contentHeight: 0, /** {Integer} Snapping width for content */ __snapWidth: 100, /** {Integer} Snapping height for content */ __snapHeight: 100, /** {Integer} Height to assign to refresh area */ __refreshHeight: null, /** {Boolean} Whether the refresh process is enabled when the event is released now */ __refreshActive: false, /** {Function} Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release */ __refreshActivate: null, /** {Function} Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled */ __refreshDeactivate: null, /** {Function} Callback to execute to start the actual refresh. Call {@link #refreshFinish} when done */ __refreshStart: null, /** {Number} Zoom level */ __zoomLevel: 1, /** {Number} Scroll position on x-axis */ __scrollLeft: 0, /** {Number} Scroll position on y-axis */ __scrollTop: 0, /** {Integer} Maximum allowed scroll position on x-axis */ __maxScrollLeft: 0, /** {Integer} Maximum allowed scroll position on y-axis */ __maxScrollTop: 0, /* {Number} Scheduled left position (final position when animating) */ __scheduledLeft: 0, /* {Number} Scheduled top position (final position when animating) */ __scheduledTop: 0, /* {Number} Scheduled zoom level (final scale when animating) */ __scheduledZoom: 0, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: LAST POSITIONS --------------------------------------------------------------------------- */ /** {Number} Left position of finger at start */ __lastTouchLeft: null, /** {Number} Top position of finger at start */ __lastTouchTop: null, /** {Date} Timestamp of last move of finger. Used to limit tracking range for deceleration speed. */ __lastTouchMove: null, /** {Array} List of positions, uses three indexes for each state: left, top, timestamp */ __positions: null, /* --------------------------------------------------------------------------- INTERNAL FIELDS :: DECELERATION SUPPORT --------------------------------------------------------------------------- */ /** {Integer} Minimum left scroll position during deceleration */ __minDecelerationScrollLeft: null, /** {Integer} Minimum top scroll position during deceleration */ __minDecelerationScrollTop: null, /** {Integer} Maximum left scroll position during deceleration */ __maxDecelerationScrollLeft: null, /** {Integer} Maximum top scroll position during deceleration */ __maxDecelerationScrollTop: null, /** {Number} Current factor to modify horizontal scroll position with on every step */ __decelerationVelocityX: null, /** {Number} Current factor to modify vertical scroll position with on every step */ __decelerationVelocityY: null, /* --------------------------------------------------------------------------- PUBLIC API --------------------------------------------------------------------------- */ /** * Configures the dimensions of the client (outer) and content (inner) elements. * Requires the available space for the outer element and the outer size of the inner element. * All values which are falsy (null or zero etc.) are ignored and the old value is kept. * * @param clientWidth {Integer ? null} Inner width of outer element * @param clientHeight {Integer ? null} Inner height of outer element * @param contentWidth {Integer ? null} Outer width of inner element * @param contentHeight {Integer ? null} Outer height of inner element */ setDimensions: function(clientWidth, clientHeight, contentWidth, contentHeight) { var self = this; // Only update values which are defined if (clientWidth === +clientWidth) { self.__clientWidth = clientWidth; } if (clientHeight === +clientHeight) { self.__clientHeight = clientHeight; } if (contentWidth === +contentWidth) { self.__contentWidth = contentWidth; } if (contentHeight === +contentHeight) { self.__contentHeight = contentHeight; } // Refresh maximums self.__computeScrollMax(); // Refresh scroll position self.scrollTo(self.__scrollLeft, self.__scrollTop, true); }, /** * Sets the client coordinates in relation to the document. * * @param left {Integer ? 0} Left position of outer element * @param top {Integer ? 0} Top position of outer element */ setPosition: function(left, top) { var self = this; self.__clientLeft = left || 0; self.__clientTop = top || 0; }, /** * Configures the snapping (when snapping is active) * * @param width {Integer} Snapping width * @param height {Integer} Snapping height */ setSnapSize: function(width, height) { var self = this; self.__snapWidth = width; self.__snapHeight = height; }, /** * Activates pull-to-refresh. A special zone on the top of the list to start a list refresh whenever * the user event is released during visibility of this zone. This was introduced by some apps on iOS like * the official Twitter client. * * @param height {Integer} Height of pull-to-refresh zone on top of rendered list * @param activateCallback {Function} Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release. * @param deactivateCallback {Function} Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled. * @param startCallback {Function} Callback to execute to start the real async refresh action. Call {@link #finishPullToRefresh} after finish of refresh. */ activatePullToRefresh: function(height, activateCallback, deactivateCallback, startCallback) { var self = this; self.__refreshHeight = height; self.__refreshActivate = activateCallback; self.__refreshDeactivate = deactivateCallback; self.__refreshStart = startCallback; }, /** * Starts pull-to-refresh manually. */ triggerPullToRefresh: function() { // Use publish instead of scrollTo to allow scrolling to out of boundary position // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled this.__publish(this.__scrollLeft, -this.__refreshHeight, this.__zoomLevel, true); if (this.__refreshStart) { this.__refreshStart(); } }, /** * Signalizes that pull-to-refresh is finished. */ finishPullToRefresh: function() { var self = this; self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } self.scrollTo(self.__scrollLeft, self.__scrollTop, true); }, /** * Returns the scroll position and zooming values * * @return {Map} `left` and `top` scroll position and `zoom` level */ getValues: function() { var self = this; return { left: self.__scrollLeft, top: self.__scrollTop, zoom: self.__zoomLevel }; }, /** * Returns the maximum scroll values * * @return {Map} `left` and `top` maximum scroll values */ getScrollMax: function() { var self = this; return { left: self.__maxScrollLeft, top: self.__maxScrollTop }; }, /** * Zooms to the given level. Supports optional animation. Zooms * the center when no coordinates are given. * * @param level {Number} Level to zoom to * @param animate {Boolean ? false} Whether to use animation * @param originLeft {Number ? null} Zoom in at given left coordinate * @param originTop {Number ? null} Zoom in at given top coordinate * @param callback {Function ? null} A callback that gets fired when the zoom is complete. */ zoomTo: function(level, animate, originLeft, originTop, callback) { var self = this; if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } // Add callback if exists if(callback) { self.__zoomComplete = callback; } // Stop deceleration if (self.__isDecelerating) { core.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } var oldLevel = self.__zoomLevel; // Normalize input origin to center of viewport if not defined if (originLeft == null) { originLeft = self.__clientWidth / 2; } if (originTop == null) { originTop = self.__clientHeight / 2; } // Limit level according to configuration level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom); // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(level); // Recompute left and top coordinates based on new zoom level var left = ((originLeft + self.__scrollLeft) * level / oldLevel) - originLeft; var top = ((originTop + self.__scrollTop) * level / oldLevel) - originTop; // Limit x-axis if (left > self.__maxScrollLeft) { left = self.__maxScrollLeft; } else if (left < 0) { left = 0; } // Limit y-axis if (top > self.__maxScrollTop) { top = self.__maxScrollTop; } else if (top < 0) { top = 0; } // Push values out self.__publish(left, top, level, animate); }, /** * Zooms the content by the given factor. * * @param factor {Number} Zoom by given factor * @param animate {Boolean ? false} Whether to use animation * @param originLeft {Number ? 0} Zoom in at given left coordinate * @param originTop {Number ? 0} Zoom in at given top coordinate * @param callback {Function ? null} A callback that gets fired when the zoom is complete. */ zoomBy: function(factor, animate, originLeft, originTop, callback) { var self = this; self.zoomTo(self.__zoomLevel * factor, animate, originLeft, originTop, callback); }, /** * Scrolls to the given position. Respect limitations and snapping automatically. * * @param left {Number?null} Horizontal scroll position, keeps current if value is <code>null</code> * @param top {Number?null} Vertical scroll position, keeps current if value is <code>null</code> * @param animate {Boolean?false} Whether the scrolling should happen using an animation * @param zoom {Number?null} Zoom level to go to */ scrollTo: function(left, top, animate, zoom) { var self = this; // Stop deceleration if (self.__isDecelerating) { core.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; } // Correct coordinates based on new zoom level if (zoom != null && zoom !== self.__zoomLevel) { if (!self.options.zooming) { throw new Error("Zooming is not enabled!"); } left *= zoom; top *= zoom; // Recompute maximum values while temporary tweaking maximum scroll ranges self.__computeScrollMax(zoom); } else { // Keep zoom when not defined zoom = self.__zoomLevel; } if (!self.options.scrollingX) { left = self.__scrollLeft; } else { if (self.options.paging) { left = Math.round(left / self.__clientWidth) * self.__clientWidth; } else if (self.options.snapping) { left = Math.round(left / self.__snapWidth) * self.__snapWidth; } } if (!self.options.scrollingY) { top = self.__scrollTop; } else { if (self.options.paging) { top = Math.round(top / self.__clientHeight) * self.__clientHeight; } else if (self.options.snapping) { top = Math.round(top / self.__snapHeight) * self.__snapHeight; } } // Limit for allowed ranges left = Math.max(Math.min(self.__maxScrollLeft, left), 0); top = Math.max(Math.min(self.__maxScrollTop, top), 0); // Don't animate when no change detected, still call publish to make sure // that rendered position is really in-sync with internal data if (left === self.__scrollLeft && top === self.__scrollTop) { animate = false; } // Publish new values if (!self.__isTracking) { self.__publish(left, top, zoom, animate); } }, /** * Scroll by the given offset * * @param left {Number ? 0} Scroll x-axis by given offset * @param top {Number ? 0} Scroll x-axis by given offset * @param animate {Boolean ? false} Whether to animate the given change */ scrollBy: function(left, top, animate) { var self = this; var startLeft = self.__isAnimating ? self.__scheduledLeft : self.__scrollLeft; var startTop = self.__isAnimating ? self.__scheduledTop : self.__scrollTop; self.scrollTo(startLeft + (left || 0), startTop + (top || 0), animate); }, /* --------------------------------------------------------------------------- EVENT CALLBACKS --------------------------------------------------------------------------- */ /** * Mouse wheel handler for zooming support */ doMouseZoom: function(wheelDelta, timeStamp, pageX, pageY) { var self = this; var change = wheelDelta > 0 ? 0.97 : 1.03; return self.zoomTo(self.__zoomLevel * change, false, pageX - self.__clientLeft, pageY - self.__clientTop); }, /** * Touch start handler for scrolling support */ doTouchStart: function(touches, timeStamp) { // Array-like check is enough here if (touches.length == null) { throw new Error("Invalid touch list: " + touches); } if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { throw new Error("Invalid timestamp value: " + timeStamp); } var self = this; // Reset interruptedAnimation flag self.__interruptedAnimation = true; // Stop deceleration if (self.__isDecelerating) { core.effect.Animate.stop(self.__isDecelerating); self.__isDecelerating = false; self.__interruptedAnimation = true; } // Stop animation if (self.__isAnimating) { core.effect.Animate.stop(self.__isAnimating); self.__isAnimating = false; self.__interruptedAnimation = true; } // Use center point when dealing with two fingers var currentTouchLeft, currentTouchTop; var isSingleTouch = touches.length === 1; if (isSingleTouch) { currentTouchLeft = touches[0].pageX; currentTouchTop = touches[0].pageY; } else { currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2; currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2; } // Store initial positions self.__initialTouchLeft = currentTouchLeft; self.__initialTouchTop = currentTouchTop; // Store current zoom level self.__zoomLevelStart = self.__zoomLevel; // Store initial touch positions self.__lastTouchLeft = currentTouchLeft; self.__lastTouchTop = currentTouchTop; // Store initial move time stamp self.__lastTouchMove = timeStamp; // Reset initial scale self.__lastScale = 1; // Reset locking flags self.__enableScrollX = !isSingleTouch && self.options.scrollingX; self.__enableScrollY = !isSingleTouch && self.options.scrollingY; // Reset tracking flag self.__isTracking = true; // Reset deceleration complete flag self.__didDecelerationComplete = false; // Dragging starts directly with two fingers, otherwise lazy with an offset self.__isDragging = !isSingleTouch; // Some features are disabled in multi touch scenarios self.__isSingleTouch = isSingleTouch; // Clearing data structure self.__positions = []; }, /** * Touch move handler for scrolling support */ doTouchMove: function(touches, timeStamp, scale) { // Array-like check is enough here if (touches.length == null) { throw new Error("Invalid touch list: " + touches); } if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { throw new Error("Invalid timestamp value: " + timeStamp); } var self = this; // Ignore event when tracking is not enabled (event might be outside of element) if (!self.__isTracking) { return; } var currentTouchLeft, currentTouchTop; // Compute move based around of center of fingers if (touches.length === 2) { currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2; currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2; } else { currentTouchLeft = touches[0].pageX; currentTouchTop = touches[0].pageY; } var positions = self.__positions; // Are we already is dragging mode? if (self.__isDragging) { // Compute move distance var moveX = currentTouchLeft - self.__lastTouchLeft; var moveY = currentTouchTop - self.__lastTouchTop; // Read previous scroll position and zooming var scrollLeft = self.__scrollLeft; var scrollTop = self.__scrollTop; var level = self.__zoomLevel; // Work with scaling if (scale != null && self.options.zooming) { var oldLevel = level; // Recompute level based on previous scale and new scale level = level / self.__lastScale * scale; // Limit level according to configuration level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom); // Only do further compution when change happened if (oldLevel !== level) { // Compute relative event position to container var currentTouchLeftRel = currentTouchLeft - self.__clientLeft; var currentTouchTopRel = currentTouchTop - self.__clientTop; // Recompute left and top coordinates based on new zoom level scrollLeft = ((currentTouchLeftRel + scrollLeft) * level / oldLevel) - currentTouchLeftRel; scrollTop = ((currentTouchTopRel + scrollTop) * level / oldLevel) - currentTouchTopRel; // Recompute max scroll values self.__computeScrollMax(level); } } if (self.__enableScrollX) { scrollLeft -= moveX * this.options.speedMultiplier; var maxScrollLeft = self.__maxScrollLeft; if (scrollLeft > maxScrollLeft || scrollLeft < 0) { // Slow down on the edges if (self.options.bouncing) { scrollLeft += (moveX / 2 * this.options.speedMultiplier); } else if (scrollLeft > maxScrollLeft) { scrollLeft = maxScrollLeft; } else { scrollLeft = 0; } } } // Compute new vertical scroll position if (self.__enableScrollY) { scrollTop -= moveY * this.options.speedMultiplier; var maxScrollTop = self.__maxScrollTop; if (scrollTop > maxScrollTop || scrollTop < 0) { // Slow down on the edges if (self.options.bouncing) { scrollTop += (moveY / 2 * this.options.speedMultiplier); // Support pull-to-refresh (only when only y is scrollable) if (!self.__enableScrollX && self.__refreshHeight != null) { if (!self.__refreshActive && scrollTop <= -self.__refreshHeight) { self.__refreshActive = true; if (self.__refreshActivate) { self.__refreshActivate(); } } else if (self.__refreshActive && scrollTop > -self.__refreshHeight) { self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } } } } else if (scrollTop > maxScrollTop) { scrollTop = maxScrollTop; } else { scrollTop = 0; } } } // Keep list from growing infinitely (holding min 10, max 20 measure points) if (positions.length > 60) { positions.splice(0, 30); } // Track scroll movement for decleration positions.push(scrollLeft, scrollTop, timeStamp); // Sync scroll position self.__publish(scrollLeft, scrollTop, level); // Otherwise figure out whether we are switching into dragging mode now. } else { var minimumTrackingForScroll = self.options.locking ? 3 : 0; var minimumTrackingForDrag = 5; var distanceX = Math.abs(currentTouchLeft - self.__initialTouchLeft); var distanceY = Math.abs(currentTouchTop - self.__initialTouchTop); self.__enableScrollX = self.options.scrollingX && distanceX >= minimumTrackingForScroll; self.__enableScrollY = self.options.scrollingY && distanceY >= minimumTrackingForScroll; positions.push(self.__scrollLeft, self.__scrollTop, timeStamp); self.__isDragging = (self.__enableScrollX || self.__enableScrollY) && (distanceX >= minimumTrackingForDrag || distanceY >= minimumTrackingForDrag); if (self.__isDragging) { self.__interruptedAnimation = false; } } // Update last touch positions and time stamp for next event self.__lastTouchLeft = currentTouchLeft; self.__lastTouchTop = currentTouchTop; self.__lastTouchMove = timeStamp; self.__lastScale = scale; }, /** * Touch end handler for scrolling support */ doTouchEnd: function(timeStamp) { if (timeStamp instanceof Date) { timeStamp = timeStamp.valueOf(); } if (typeof timeStamp !== "number") { throw new Error("Invalid timestamp value: " + timeStamp); } var self = this; // Ignore event when tracking is not enabled (no touchstart event on element) // This is required as this listener ('touchmove') sits on the document and not on the element itself. if (!self.__isTracking) { return; } // Not touching anymore (when two finger hit the screen there are two touch end events) self.__isTracking = false; // Be sure to reset the dragging flag now. Here we also detect whether // the finger has moved fast enough to switch into a deceleration animation. if (self.__isDragging) { // Reset dragging flag self.__isDragging = false; // Start deceleration // Verify that the last move detected was in some relevant time frame if (self.__isSingleTouch && self.options.animating && (timeStamp - self.__lastTouchMove) <= 100) { // Then figure out what the scroll position was about 100ms ago var positions = self.__positions; var endPos = positions.length - 1; var startPos = endPos; // Move pointer to position measured 100ms ago for (var i = endPos; i > 0 && positions[i] > (self.__lastTouchMove - 100); i -= 3) { startPos = i; } // If start and stop position is identical in a 100ms timeframe, // we cannot compute any useful deceleration. if (startPos !== endPos) { // Compute relative movement between these two points var timeOffset = positions[endPos] - positions[startPos]; var movedLeft = self.__scrollLeft - positions[startPos - 2]; var movedTop = self.__scrollTop - positions[startPos - 1]; // Based on 50ms compute the movement to apply for each render step self.__decelerationVelocityX = movedLeft / timeOffset * (1000 / 60); self.__decelerationVelocityY = movedTop / timeOffset * (1000 / 60); // How much velocity is required to start the deceleration var minVelocityToStartDeceleration = self.options.paging || self.options.snapping ? 4 : 1; // Verify that we have enough velocity to start deceleration if (Math.abs(self.__decelerationVelocityX) > minVelocityToStartDeceleration || Math.abs(self.__decelerationVelocityY) > minVelocityToStartDeceleration) { // Deactivate pull-to-refresh when decelerating if (!self.__refreshActive) { self.__startDeceleration(timeStamp); } } } else { self.options.scrollingComplete(); } } else if ((timeStamp - self.__lastTouchMove) > 100) { self.options.scrollingComplete(); } } // If this was a slower move it is per default non decelerated, but this // still means that we want snap back to the bounds which is done here. // This is placed outside the condition above to improve edge case stability // e.g. touchend fired without enabled dragging. This should normally do not // have modified the scroll positions or even showed the scrollbars though. if (!self.__isDecelerating) { if (self.__refreshActive && self.__refreshStart) { // Use publish instead of scrollTo to allow scrolling to out of boundary position // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled self.__publish(self.__scrollLeft, -self.__refreshHeight, self.__zoomLevel, true); if (self.__refreshStart) { self.__refreshStart(); } } else { if (self.__interruptedAnimation || self.__isDragging) { self.options.scrollingComplete(); } self.scrollTo(self.__scrollLeft, self.__scrollTop, true, self.__zoomLevel); // Directly signalize deactivation (nothing todo on refresh?) if (self.__refreshActive) { self.__refreshActive = false; if (self.__refreshDeactivate) { self.__refreshDeactivate(); } } } } // Fully cleanup list self.__positions.length = 0; }, /* --------------------------------------------------------------------------- PRIVATE API --------------------------------------------------------------------------- */ /** * Applies the scroll position to the content element * * @param left {Number} Left scroll position * @param top {Number} Top scroll position * @param animate {Boolean?false} Whether animation should be used to move to the new coordinates */ __publish: function(left, top, zoom, animate) { var self = this; // Remember whether we had an animation, then we try to continue based on the current "drive" of the animation var wasAnimating = self.__isAnimating; if (wasAnimating) { core.effect.Animate.stop(wasAnimating); self.__isAnimating = false; } if (animate && self.options.animating) { // Keep scheduled positions for scrollBy/zoomBy functionality self.__scheduledLeft = left; self.__scheduledTop = top; self.__scheduledZoom = zoom; var oldLeft = self.__scrollLeft; var oldTop = self.__scrollTop; var oldZoom = self.__zoomLevel; var diffLeft = left - oldLeft; var diffTop = top - oldTop; var diffZoom = zoom - oldZoom; var step = function(percent, now, render) { if (render) { self.__scrollLeft = oldLeft + (diffLeft * percent); self.__scrollTop = oldTop + (diffTop * percent); self.__zoomLevel = oldZoom + (diffZoom * percent); // Push values out if (self.__callback) { self.__callback(self.__scrollLeft, self.__scrollTop, self.__zoomLevel); } } }; var verify = function(id) { return self.__isAnimating === id; }; var completed = function(renderedFramesPerSecond, animationId, wasFinished) { if (animationId === self.__isAnimating) { self.__isAnimating = false; } if (self.__didDecelerationComplete || wasFinished) { self.options.scrollingComplete(); } if (self.options.zooming) { self.__computeScrollMax(); if(self.__zoomComplete) { self.__zoomComplete(); self.__zoomComplete = null; } } }; // When continuing based on previous animation we choose an ease-out animation instead of ease-in-out self.__isAnimating = core.effect.Animate.start(step, verify, completed, self.options.animationDuration, wasAnimating ? easeOutCubic : easeInOutCubic); } else { self.__scheduledLeft = self.__scrollLeft = left; self.__scheduledTop = self.__scrollTop = top; self.__scheduledZoom = self.__zoomLevel = zoom; // Push values out if (self.__callback) { self.__callback(left, top, zoom); } // Fix max scroll ranges if (self.options.zooming) { self.__computeScrollMax(); if(self.__zoomComplete) { self.__zoomComplete(); self.__zoomComplete = null; } } } }, /** * Recomputes scroll minimum values based on client dimensions and content dimensions. */ __computeScrollMax: function(zoomLevel) { var self = this; if (zoomLevel == null) { zoomLevel = self.__zoomLevel; } self.__maxScrollLeft = Math.max((self.__contentWidth * zoomLevel) - self.__clientWidth, 0); self.__maxScrollTop = Math.max((self.__contentHeight * zoomLevel) - self.__clientHeight, 0); }, /* --------------------------------------------------------------------------- ANIMATION (DECELERATION) SUPPORT --------------------------------------------------------------------------- */ /** * Called when a touch sequence end and the speed of the finger was high enough * to switch into deceleration mode. */ __startDeceleration: function(timeStamp) { var self = this; if (self.options.paging) { var scrollLeft = Math.max(Math.min(self.__scrollLeft, self.__maxScrollLeft), 0); var scrollTop = Math.max(Math.min(self.__scrollTop, self.__maxScrollTop), 0); var clientWidth = self.__clientWidth; var clientHeight = self.__clientHeight; // We limit deceleration not to the min/max values of the allowed range, but to the size of the visible client area. // Each page should have exactly the size of the client area. self.__minDecelerationScrollLeft = Math.floor(scrollLeft / clientWidth) * clientWidth; self.__minDecelerationScrollTop = Math.floor(scrollTop / clientHeight) * clientHeight; self.__maxDecelerationScrollLeft = Math.ceil(scrollLeft / clientWidth) * clientWidth; self.__maxDecelerationScrollTop = Math.ceil(scrollTop / clientHeight) * clientHeight; } else { self.__minDecelerationScrollLeft = 0; self.__minDecelerationScrollTop = 0; self.__maxDecelerationScrollLeft = self.__maxScrollLeft; self.__maxDecelerationScrollTop = self.__maxScrollTop; } // Wrap class method var step = function(percent, now, render) { self.__stepThroughDeceleration(render); }; // How much velocity is required to keep the deceleration running var minVelocityToKeepDecelerating = self.options.snapping ? 4 : 0.001; // Detect whether it's still worth to continue animating steps // If we are already slow enough to not being user perceivable anymore, we stop the whole process here. var verify = function() { var shouldContinue = Math.abs(self.__decelerationVelocityX) >= minVelocityToKeepDecelerating || Math.abs(self.__decelerationVelocityY) >= minVelocityToKeepDecelerating; if (!shouldContinue) { self.__didDecelerationComplete = true; } return shouldContinue; }; var completed = function(renderedFramesPerSecond, animationId, wasFinished) { self.__isDecelerating = false; if (self.__didDecelerationComplete) { self.options.scrollingComplete(); } // Animate to grid when snapping is active, otherwise just fix out-of-boundary positions self.scrollTo(self.__scrollLeft, self.__scrollTop, self.options.snapping); }; // Start animation and switch on flag self.__isDecelerating = core.effect.Animate.start(step, verify, completed); }, /** * Called on every step of the animation * * @param inMemory {Boolean?false} Whether to not render the current step, but keep it in memory only. Used internally only! */ __stepThroughDeceleration: function(render) { var self = this; // // COMPUTE NEXT SCROLL POSITION // // Add deceleration to scroll position var scrollLeft = self.__scrollLeft + self.__decelerationVelocityX; var scrollTop = self.__scrollTop + self.__decelerationVelocityY; // // HARD LIMIT SCROLL POSITION FOR NON BOUNCING MODE // if (!self.options.bouncing) { var scrollLeftFixed = Math.max(Math.min(self.__maxDecelerationScrollLeft, scrollLeft), self.__minDecelerationScrollLeft); if (scrollLeftFixed !== scrollLeft) { scrollLeft = scrollLeftFixed; self.__decelerationVelocityX = 0; } var scrollTopFixed = Math.max(Math.min(self.__maxDecelerationScrollTop, scrollTop), self.__minDecelerationScrollTop); if (scrollTopFixed !== scrollTop) { scrollTop = scrollTopFixed; self.__decelerationVelocityY = 0; } } // // UPDATE SCROLL POSITION // if (render) { self.__publish(scrollLeft, scrollTop, self.__zoomLevel); } else { self.__scrollLeft = scrollLeft; self.__scrollTop = scrollTop; } // // SLOW DOWN // // Slow down velocity on every iteration if (!self.options.paging) { // This is the factor applied to every iteration of the animation // to slow down the process. This should emulate natural behavior where // objects slow down when the initiator of the movement is removed var frictionFactor = 0.95; self.__decelerationVelocityX *= frictionFactor; self.__decelerationVelocityY *= frictionFactor; } // // BOUNCING SUPPORT // if (self.options.bouncing) { var scrollOutsideX = 0; var scrollOutsideY = 0; // This configures the amount of change applied to deceleration/acceleration when reaching boundaries var penetrationDeceleration = self.options.penetrationDeceleration; var penetrationAcceleration = self.options.penetrationAcceleration; // Check limits if (scrollLeft < self.__minDecelerationScrollLeft) { scrollOutsideX = self.__minDecelerationScrollLeft - scrollLeft; } else if (scrollLeft > self.__maxDecelerationScrollLeft) { scrollOutsideX = self.__maxDecelerationScrollLeft - scrollLeft; } if (scrollTop < self.__minDecelerationScrollTop) { scrollOutsideY = self.__minDecelerationScrollTop - scrollTop; } else if (scrollTop > self.__maxDecelerationScrollTop) { scrollOutsideY = self.__maxDecelerationScrollTop - scrollTop; } // Slow down until slow enough, then flip back to snap position if (scrollOutsideX !== 0) { if (scrollOutsideX * self.__decelerationVelocityX <= 0) { self.__decelerationVelocityX += scrollOutsideX * penetrationDeceleration; } else { self.__decelerationVelocityX = scrollOutsideX * penetrationAcceleration; } } if (scrollOutsideY !== 0) { if (scrollOutsideY * self.__decelerationVelocityY <= 0) { self.__decelerationVelocityY += scrollOutsideY * penetrationDeceleration; } else { self.__decelerationVelocityY = scrollOutsideY * penetrationAcceleration; } } } } }; // Copy over members to prototype for (var key in members) { Scroller.prototype[key] = members[key]; } })();
/** * dependencies */ var express = require('express'), async = require('async'), Search = require('./book/book-search.js').Search, DataProvider = require('./book/book-data-provider.js').BookProvider, LOG = require('./lib/log.js'), _config = require('./configuration'), config = _config.getConfiguration(), httpsConfig = _config.getHTTPSConfiguration(), https = require('https'), fs = require('fs'), validator = require('./lib/validator'), path = require('path'), mongoStore = require('connect-mongo')(express), storeConfig = _config.getStoreConfig(), _ = require('underscore'), routes = require('./routes'); /** * The Application * * @constructor */ function Application() { this.app = express(); } /** * init Application * * @param {Function} cb Callback function */ Application.prototype.init = function (cb) { var self = this; async.series({ "auth": self.authInit.bind(self), "configure": self.configure.bind(self), "initDatabase": DataProvider.init.bind(DataProvider), "initSearchProvider": Search.init.bind(Search), "mountAPI": self.mountAPI.bind(self) }, function (err, callback) { if (err) { LOG('Error starting up the application. Exiting.'); LOG(err); process.exit(1); } if (cb) { cb(err); } }) }; /** * init all features required for authentication * * there are: * - valid user allowed to use application, * - session settings, * - basic authentication middleware with logout possibilities, * - protectWithAuth() method is used for protecting `secret` routes * * @this {Application} * @param {Function} cb Callback function */ Application.prototype.authInit = function (cb) { //the only one user exists in the system for now var validUser = { name: "valid", pass: "user" }; var self = this; //we need to use session here this.app.use(express.cookieParser(config.cookieParser.secret)); // it is required to use external storage for session //we opt to use mongoDb this.app.use( express.session(_.extend( {}, config.session, {store: new mongoStore(storeConfig)}))); //we use basic auth var preAuth = function(req, res, next) { if (req.session.userLogOut) { delete req.headers.authorization; req.session.userLogOut = false; } next(); }; var message = ["****Use 'User Name':", validUser.name, "and Password:", validUser.pass].join(" "); var auth = express.basicAuth(function (user, pass) { return user === validUser.name && pass === validUser.pass; }, message); //define protectWithAuth method //it helps to protect different routes with auth this.protectWithAuth = function(route){ self.app.all(route, preAuth, auth); }; cb(); }; /** * mount book API routes * * @this {Application} * @param {Function} cb Callback function */ Application.prototype.mountAPI = function (cb) { var BookRestApi = require('./book/book-rest-api.js').BookRestApi; var bookRestApi = new BookRestApi(); var bookValidationSchemas = require('./book/book-validation-schemas'); //protect with auth if(this.protectWithAuth){ this.protectWithAuth('/rest/*'); } // mounting REST endpoints. All the other urls would be handled by static (coming from public folder). this.app.get('/rest/allBooks', validator.getMiddleware(bookValidationSchemas.findAllBooks), bookRestApi.findAllBooks); this.app.post('/rest/newBook', validator.getMiddleware(bookValidationSchemas.newBook), bookRestApi.newBook); this.app.get('/rest/search', validator.getMiddleware(bookValidationSchemas.searchForBooks), bookRestApi.searchForBooks); this.app.post('/rest/update', validator.getMiddleware(bookValidationSchemas.update), bookRestApi.update); cb(); }; /** * configure Application: * * bind middlewares: * - json parse * - static routes * - error handlers in different environments * * bind logout route * * @this {Application} * @param {Function} cb Callback function */ Application.prototype.configure = function (cb) { //Configuration for errorHandler and others. var self = this; this.app.set('views', path.join(__dirname, 'views')); this.app.set('view engine', 'jade'); this.app.use(express.favicon(path.join(__dirname, 'favicon.ico'))); this.app.use(express.json()); this.app.configure("development", "production", function () { //mount secure point //it forces all request to be redirected on HTTPS self.app.use(function (req, res, next) { if (!config.isHTTPS(req)) { var host = (config.https && config.https.port) ? [config.host, ':', config.https.port] : [config.host]; return res.redirect(['https://'].concat(host, [req.url]).join('')); } next(); }); }); //protect static route if(this.protectWithAuth){ this.protectWithAuth('/secret.html'); } //map static routes routes.static(this.app); this.app.use(this.app.router); //map static sources this.app.use(express.static(path.join(__dirname, 'public'))); //mount logout point this.app.get('/logout', function (req, res) { req.session.userLogOut = true; res.redirect('/'); }); //bind route404 as middleware //if we pass here - no routes were found this.app.use(routes.route404); this.app.configure('development', function () { self.app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); }); this.app.configure('production', function () { self.app.use(express.errorHandler()); }); cb(); }; /** * bind server to listening on defined port * * @this {Application} * @param cb */ Application.prototype.bindServer = function (cb) { // Binding to port provided by Heroku, or to the default one. this.app.listen(config.port, function (err) { LOG(['Application started on ULR http://', config.host, ':', config.port].join('')); if (cb) { cb(err); } }); }; /** * run secure server * this is only required when running https on the local server * on Heroku it is redundant * * @this {Application} * @param {Function} cb Callback function */ Application.prototype.bindSecureServerIfNeeded = function(cb){ if (!httpsConfig){ if(cb){ async.nextTick(cb); } return; } //create secure server var self = this; var certData = { key: fs.readFileSync(httpsConfig.key), cert: fs.readFileSync(httpsConfig.cert) }; //create server var secureServer = https.createServer(certData, self.app); //run server secureServer.listen(httpsConfig.port, function(err){ LOG(['Secure server up and running on port: https://', config.host, ':', httpsConfig.port].join('')); if(cb){ cb(err); } }); }; module.exports = Application;
var _noArgsException = require('./internal/_noArgsException'); var _slice = require('./internal/_slice'); /** * Calls the specified function on the supplied object. Any additional arguments * after `fn` and `obj` are passed in to `fn`. If no additional arguments are passed to `func`, * `fn` is invoked with no arguments. * * @func * @memberOf R * @category Object * @sig k -> {k : v} -> v(*) * @param {String} funcName The name of the property mapped to the function to invoke * @param {Object} obj The object * @return {*} The value of invoking `obj.fn`. * @example * * R.func('add', R, 1, 2); //=> 3 * * var obj = { f: function() { return 'f called'; } }; * R.func('f', obj); //=> 'f called' */ module.exports = function func(funcName, obj) { switch (arguments.length) { case 0: throw _noArgsException(); case 1: return function(obj) { return obj[funcName].apply(obj, _slice(arguments, 1)); }; default: return obj[funcName].apply(obj, _slice(arguments, 2)); } };
// # Task automation for Ghost // // Run various tasks when developing for and working with Ghost. // // **Usage instructions:** can be found in the [Custom Tasks](#custom%20tasks) section or by running `grunt --help`. // // **Debug tip:** If you have any problems with any Grunt tasks, try running them with the `--verbose` command var _ = require('lodash'), colors = require('colors'), fs = require('fs-extra'), getTopContribs = require('top-gh-contribs'), path = require('path'), Promise = require('bluebird'), request = require('request'), escapeChar = process.platform.match(/^win/) ? '^' : '\\', cwd = process.cwd().replace(/( |\(|\))/g, escapeChar + '$1'), buildDirectory = path.resolve(cwd, '.build'), distDirectory = path.resolve(cwd, '.dist'), // ## Build File Patterns // A list of files and patterns to include when creating a release zip. // This is read from the `.npmignore` file and all patterns are inverted as the `.npmignore` // file defines what to ignore, whereas we want to define what to include. buildGlob = (function () { /*jslint stupid:true */ return fs.readFileSync('.npmignore', {encoding: 'utf8'}).split('\n').map(function (pattern) { if (pattern[0] === '!') { return pattern.substr(1); } return '!' + pattern; }); }()), // ## List of files we want to lint through jshint and jscs to make sure // they conform to our desired code styles. lintFiles = { // Linting files for server side or shared javascript code. server: { files: { src: [ '*.js', '!config*.js', // note: i added this, do we want this linted? 'core/*.js', 'core/server/**/*.js', 'core/shared/**/*.js', '!core/shared/vendor/**/*.js' ] } }, // Linting files for client side javascript code. client: { files: { src: [ 'core/client/**/*.js', '!core/client/docs/js/*.js', '!core/client/assets/vendor/**/*.js', '!core/client/tpl/**/*.js' ] } }, // Linting files for test code. test: { files: { src: [ 'core/test/**/*.js' ] } } }, // ## Grunt configuration configureGrunt = function (grunt) { // *This is not useful but required for jshint* colors.setTheme({silly: 'rainbow'}); // #### Load all grunt tasks // // Find all of the task which start with `grunt-` and load them, rather than explicitly declaring them all require('matchdep').filterDev(['grunt-*', '!grunt-cli']).forEach(grunt.loadNpmTasks); var cfg = { // #### Common paths used by tasks paths: { build: buildDirectory, releaseBuild: path.join(buildDirectory, 'release'), dist: distDirectory, releaseDist: path.join(distDirectory, 'release') }, // Standard build type, for when we have nightlies again. buildType: 'Build', // Load package.json so that we can create correctly versioned releases. pkg: grunt.file.readJSON('package.json'), // ### grunt-contrib-watch // Watch files and livereload in the browser during development. // See the [grunt dev](#live%20reload) task for how this is used. watch: { shared: { files: ['core/shared/**/*.js'], tasks: ['concat:dev'] }, emberTemplates: { files: ['core/client/**/*.hbs'], tasks: ['emberTemplates:dev'] }, ember: { files: ['core/client/**/*.js'], tasks: ['clean:tmp', 'transpile', 'concat_sourcemap:dev'] }, sass: { files: [ 'core/client/assets/sass/**/*.scss' ], tasks: ['css'] }, livereload: { files: [ 'content/themes/casper/assets/css/*.css', 'content/themes/casper/assets/js/*.js', 'core/client/assets/css/*.css', 'core/built/scripts/*.js' ], options: { livereload: true } }, express: { files: ['core/server.js', 'core/server/**/*.js'], tasks: ['express:dev'], options: { // **Note:** Without this option specified express won't be reloaded nospawn: true } } }, // ### grunt-express-server // Start a Ghost expess server for use in development and testing express: { options: { script: 'index.js', output: 'Ghost is running' }, dev: { options: {} }, test: { options: { node_env: 'testing' } } }, // ### grunt-contrib-jshint // Linting rules, run as part of `grunt validate`. See [grunt validate](#validate) and its subtasks for // more information. jshint: (function () { return _.merge({ server: { options: { jshintrc: '.jshintrc' } }, client: { options: { jshintrc: 'core/client/.jshintrc' } }, test: { options: { jshintrc: 'core/test/.jshintrc' } } }, lintFiles); })(), // ### grunt-jscs // Code style rules, run as part of `grunt validate`. See [grunt validate](#validate) and its subtasks for // more information. jscs: (function () { var jscsConfig = _.merge({ server: { options: { config: '.jscsrc' } }, client: { options: { config: '.jscsrc', esnext: true } }, test: { options: { config: '.jscsrc' } } }, lintFiles); return jscsConfig; })(), // ### grunt-mocha-cli // Configuration for the mocha test runner, used to run unit, integration and route tests as part of // `grunt validate`. See [grunt validate](#validate) and its sub tasks for more information. mochacli: { options: { ui: 'bdd', reporter: grunt.option('reporter') || 'spec', timeout: '15000', save: grunt.option('reporter-output') }, // #### All Unit tests unit: { src: [ 'core/test/unit/**/*_spec.js' ] }, // ##### Groups of unit tests server: { src: ['core/test/unit/**/server*_spec.js'] }, helpers: { src: ['core/test/unit/server_helpers/*_spec.js'] }, showdown: { src: ['core/test/unit/**/showdown*_spec.js'] }, perm: { src: ['core/test/unit/**/permissions_spec.js'] }, migrate: { src: [ 'core/test/unit/**/export_spec.js', 'core/test/unit/**/import_spec.js' ] }, storage: { src: ['core/test/unit/**/storage*_spec.js'] }, // #### All Integration tests integration: { src: [ 'core/test/integration/**/model*_spec.js', 'core/test/integration/**/api*_spec.js', 'core/test/integration/*_spec.js' ] }, // ##### Model integration tests model: { src: ['core/test/integration/**/model*_spec.js'] }, // ##### API integration tests api: { src: ['core/test/integration/**/api*_spec.js'] }, // #### All Route tests routes: { src: [ 'core/test/functional/routes/**/*_test.js' ] }, // #### All Module tests module: { src: [ 'core/test/functional/module/**/*_test.js' ] } }, // ### grunt-shell // Command line tools where it's easier to run a command directly than configure a grunt plugin shell: { // #### Run bower install // Used as part of `grunt init`. See the section on [Building Assets](#building%20assets) for more // information. bower: { command: path.resolve(cwd + '/node_modules/.bin/bower --allow-root install'), options: { stdout: true, stdin: false } }, // #### Generate coverage report // See the `grunt test-coverage` task in the section on [Testing](#testing) for more information. coverage: { command: path.resolve(cwd + '/node_modules/mocha/bin/mocha --timeout 15000 --reporter' + ' html-cov > coverage.html ./core/test/blanket_coverage.js'), execOptions: { env: 'NODE_ENV=' + process.env.NODE_ENV } } }, // ### grunt-sass // compile sass to css sass: { compress: { options: { outputStyle: 'nested', sourceMap: true }, files: [ {dest: path.resolve('core/client/assets/css/<%= pkg.name %>.min.css'), src: path.resolve('core/client/assets/sass/screen.scss')}, {dest: path.resolve('core/client/docs/dist/css/<%= pkg.name %>.min.css'), src: path.resolve('core/client/assets/sass/screen.scss')} ] } }, // ### grunt-autoprefixer // Autoprefix all the things, for the last 2 versions of major browsers autoprefixer: { options: { silent: true, // suppress logging map: true, // Use and update the sourcemap browsers: ['last 2 versions', '> 1%', 'Explorer 10'] }, ghost: { src: 'core/client/assets/css/<%= pkg.name %>.min.css', dest: 'core/client/assets/css/<%= pkg.name %>.min.css' }, docs: { src: 'core/client/docs/dist/css/<%= pkg.name %>.min.css', dest: 'core/client/docs/dist/css/<%= pkg.name %>.min.css' } }, // ### grunt-ember-templates // Compiles handlebar templates for ember emberTemplates: { dev: { options: { templateBasePath: /core\/client\//, templateFileExtensions: /\.hbs/, templateRegistration: function (name, template) { return grunt.config.process('define(\'ghost/') + name + '\', [\'exports\'], function(__exports__){ __exports__[\'default\'] = ' + template + '; });'; } }, files: { 'core/built/scripts/templates-dev.js': 'core/client/templates/**/*.hbs' } }, prod: { options: { templateBasePath: /core\/client\//, templateFileExtensions: /\.hbs/, templateRegistration: function (name, template) { return grunt.config.process('define(\'ghost/') + name + '\', [\'exports\'], function(__exports__){ __exports__[\'default\'] = ' + template + '; });'; } }, files: { 'core/built/scripts/templates.js': 'core/client/templates/**/*.hbs' } } }, // ### grunt-es6-module-transpiler // Compiles Ember es6 modules transpile: { client: { type: 'amd', moduleName: function (path) { return 'ghost/' + path; }, files: [{ expand: true, cwd: 'core/client/', src: ['**/*.js', '!loader.js', '!config-*.js'], dest: '.tmp/ember-transpiled/' }] } }, // ### grunt-concat-sourcemap // Concatenates transpiled ember app concat_sourcemap: { dev: { src: ['.tmp/ember-transpiled/**/*.js', 'core/client/loader.js'], dest: 'core/built/scripts/ghost-dev.js', options: { sourcesContent: true } }, prod: { src: ['.tmp/ember-transpiled/**/*.js', 'core/built/scripts/templates.js', 'core/client/loader.js'], dest: 'core/built/scripts/ghost.js', options: { sourcesContent: true } } }, // ### grunt-docker // Generate documentation from code docker: { docs: { dest: 'docs', src: ['.'], options: { onlyUpdated: true, exclude: 'node_modules,.git,.tmp,bower_components,content,*built,*test,*doc*,*vendor,' + 'config.js,coverage.html,.travis.yml,*.min.css,screen.css', extras: ['fileSearch'] } } }, // ### grunt-contrib-clean // Clean up files as part of other tasks clean: { built: { src: [ 'core/built/**', 'core/client/assets/img/contributors/**', 'core/client/templates/-contributors.hbs' ] }, release: { src: ['<%= paths.releaseBuild %>/**'] }, css: { src: [ 'core/client/assets/css/**', 'core/client/docs/dist/css/**' ] }, test: { src: ['content/data/ghost-test.db'] }, tmp: { src: ['.tmp/**'] } }, // ### grunt-contrib-copy // Copy files into their correct locations as part of building assets, or creating release zips copy: { dev: { files: [{ cwd: 'bower_components/jquery/dist/', src: 'jquery.js', dest: 'core/built/public/', expand: true }, { src: 'core/client/config-dev.js', dest: 'core/client/config.js' }] }, prod: { files: [{ cwd: 'bower_components/jquery/dist/', src: 'jquery.js', dest: 'core/built/public/', expand: true }, { src: 'core/client/config-prod.js', dest: 'core/client/config.js' }] }, release: { files: [{ cwd: 'bower_components/jquery/dist/', src: 'jquery.js', dest: 'core/built/public/', expand: true }, { src: 'core/client/config-prod.js', dest: 'core/client/config.js' }, { expand: true, src: buildGlob, dest: '<%= paths.releaseBuild %>/' }] } }, // ### grunt-contrib-compress // Zip up files for builds / releases compress: { release: { options: { archive: '<%= paths.releaseDist %>/Ghost-<%= pkg.version %>.zip' }, expand: true, cwd: '<%= paths.releaseBuild %>/', src: ['**'] } }, // ### grunt-contrib-concat // concatenate multiple JS files into a single file ready for use concat: { dev: { nonull: true, dest: 'core/built/scripts/vendor-dev.js', src: [ 'bower_components/loader.js/loader.js', 'bower_components/jquery/dist/jquery.js', 'bower_components/handlebars/handlebars.js', 'bower_components/ember/ember.js', 'bower_components/ember-data/ember-data.js', 'bower_components/ember-resolver/dist/ember-resolver.js', 'bower_components/ic-ajax/dist/globals/main.js', 'bower_components/ember-load-initializers/ember-load-initializers.js', 'bower_components/validator-js/validator.js', 'bower_components/codemirror/lib/codemirror.js', 'bower_components/codemirror/addon/mode/overlay.js', 'bower_components/codemirror/mode/markdown/markdown.js', 'bower_components/codemirror/mode/gfm/gfm.js', 'bower_components/showdown-ghost/src/showdown.js', 'bower_components/moment/moment.js', 'bower_components/keymaster/keymaster.js', 'bower_components/device/lib/device.js', 'bower_components/jquery-ui/ui/jquery-ui.js', 'bower_components/jquery-file-upload/js/jquery.fileupload.js', 'bower_components/fastclick/lib/fastclick.js', 'bower_components/nprogress/nprogress.js', 'bower_components/ember-simple-auth/simple-auth.js', 'bower_components/ember-simple-auth/simple-auth-oauth2.js', 'bower_components/google-caja/html-css-sanitizer-bundle.js', 'bower_components/nanoscroller/bin/javascripts/jquery.nanoscroller.js', 'core/shared/lib/showdown/extensions/ghostimagepreview.js', 'core/shared/lib/showdown/extensions/ghostgfm.js' ] }, prod: { nonull: true, dest: 'core/built/scripts/vendor.js', src: [ 'bower_components/loader.js/loader.js', 'bower_components/jquery/dist/jquery.js', 'bower_components/handlebars/handlebars.runtime.js', 'bower_components/ember/ember.prod.js', 'bower_components/ember-data/ember-data.prod.js', 'bower_components/ember-resolver/dist/ember-resolver.js', 'bower_components/ic-ajax/dist/globals/main.js', 'bower_components/ember-load-initializers/ember-load-initializers.js', 'bower_components/validator-js/validator.js', 'bower_components/codemirror/lib/codemirror.js', 'bower_components/codemirror/addon/mode/overlay.js', 'bower_components/codemirror/mode/markdown/markdown.js', 'bower_components/codemirror/mode/gfm/gfm.js', 'bower_components/showdown-ghost/src/showdown.js', 'bower_components/moment/moment.js', 'bower_components/keymaster/keymaster.js', 'bower_components/device/lib/device.js', 'bower_components/jquery-ui/ui/jquery-ui.js', 'bower_components/jquery-file-upload/js/jquery.fileupload.js', 'bower_components/fastclick/lib/fastclick.js', 'bower_components/nprogress/nprogress.js', 'bower_components/ember-simple-auth/simple-auth.js', 'bower_components/ember-simple-auth/simple-auth-oauth2.js', 'bower_components/google-caja/html-css-sanitizer-bundle.js', 'bower_components/nanoscroller/bin/javascripts/jquery.nanoscroller.js', 'core/shared/lib/showdown/extensions/ghostimagepreview.js', 'core/shared/lib/showdown/extensions/ghostgfm.js' ] } }, // ### grunt-contrib-uglify // Minify concatenated javascript files ready for production uglify: { prod: { options: { sourceMap: true }, files: { 'core/built/public/jquery.min.js': 'core/built/public/jquery.js', 'core/built/scripts/vendor.min.js': 'core/built/scripts/vendor.js', 'core/built/scripts/ghost.min.js': 'core/built/scripts/ghost.js' } }, release: { options: { sourceMap: false }, files: { 'core/built/public/jquery.min.js': 'core/built/public/jquery.js', 'core/built/scripts/vendor.min.js': 'core/built/scripts/vendor.js', 'core/built/scripts/ghost.min.js': 'core/built/scripts/ghost.js' } } }, // ### grunt-update-submodules // Grunt task to update git submodules update_submodules: { default: { options: { params: '--init' } } } }; // Load the configuration grunt.initConfig(cfg); // ## Utilities // // ### Spawn Casper.js // Custom test runner for our Casper.js functional tests // This really ought to be refactored into a separate grunt task module grunt.registerTask('spawnCasperJS', function (target) { target = _.contains(['client', 'setup'], target) ? target + '/' : undefined; var done = this.async(), options = ['host', 'noPort', 'port', 'email', 'password'], args = ['test'] .concat(grunt.option('target') || target || ['client/']) .concat(['--includes=base.js', '--log-level=debug', '--port=2369']); // Forward parameters from grunt to casperjs _.each(options, function processOption(option) { if (grunt.option(option)) { args.push('--' + option + '=' + grunt.option(option)); } }); if (grunt.option('fail-fast')) { args.push('--fail-fast'); } // Show concise logs in Travis as ours are getting too long if (grunt.option('concise') || process.env.TRAVIS) { args.push('--concise'); } else { args.push('--verbose'); } grunt.util.spawn({ cmd: 'casperjs', args: args, opts: { cwd: path.resolve('core/test/functional'), stdio: 'inherit' } }, function (error, result, code) { /*jshint unused:false*/ if (error) { grunt.fail.fatal(result.stdout); } grunt.log.writeln(result.stdout); done(); }); }); // # Custom Tasks // Ghost has a number of useful tasks that we use every day in development. Tasks marked as *Utility* are used // by grunt to perform current actions, but isn't useful to developers. // // Skip ahead to the section on: // // * [Building assets](#building%20assets): // `grunt init`, `grunt` & `grunt prod` or live reload with `grunt dev` // * [Testing](#testing): // `grunt validate`, the `grunt test-*` sub-tasks or generate a coverage report with `grunt test-coverage`. // ### Help // Run `grunt help` on the commandline to get a print out of the available tasks and details of // what each one does along with any available options. This is an alias for `grunt --help` grunt.registerTask('help', 'Outputs help information if you type `grunt help` instead of `grunt --help`', function () { console.log('Type `grunt --help` to get the details of available grunt tasks, ' + 'or alternatively visit https://github.com/TryGhost/Ghost/wiki/Grunt-Toolkit'); }); // ### Documentation // Run `grunt docs` to generate annotated source code using the documentation described in the code comments. grunt.registerTask('docs', 'Generate Docs', ['docker']); // ## Testing // Ghost has an extensive set of test suites. The following section documents the various types of tests // and how to run them. // // TLDR; run `grunt validate` // #### Set Test Env *(Utility Task)* // Set the NODE_ENV to 'testing' unless the environment is already set to TRAVIS. // This ensures that the tests get run under the correct environment, using the correct database, and // that they work as expected. Trying to run tests with no ENV set will throw an error to do with `client`. grunt.registerTask('setTestEnv', 'Use "testing" Ghost config; unless we are running on travis (then show queries for debugging)', function () { process.env.NODE_ENV = process.env.TRAVIS ? process.env.NODE_ENV : 'testing'; cfg.express.test.options.node_env = process.env.NODE_ENV; }); // #### Ensure Config *(Utility Task)* // Make sure that we have a `config.js` file when running tests // Ghost requires a `config.js` file to specify the database settings etc. Ghost comes with an example file: // `config.example.js` which is copied and renamed to `config.js` by the bootstrap process grunt.registerTask('ensureConfig', function () { var config = require('./core/server/config'), done = this.async(); config.load().then(function () { done(); }).catch(function (err) { grunt.fail.fatal(err.stack); }); }); // #### Reset Database to "New" state *(Utility Task)* // Drops all database tables and then runs the migration process to put the database // in a "new" state. grunt.registerTask('cleanDatabase', function () { var done = this.async(), models = require('./core/server/models'), migration = require('./core/server/data/migration'); migration.reset().then(function () { return models.init(); }).then(function () { return migration.init(); }).then(function () { done(); }).catch(function (err) { grunt.fail.fatal(err.stack); }); }); // ### Validate // **Main testing task** // // `grunt validate` will build, lint and test your local Ghost codebase. // // `grunt validate` is one of the most important and useful grunt tasks that we have available to use. It // manages the build of your environment and then calls `grunt test` // // `grunt validate` is called by `npm test` and is used by Travis. grunt.registerTask('validate', 'Run tests and lint code', ['init', 'test']); // ### Test // **Main testing task** // // `grunt test` will lint and test your pre-built local Ghost codebase. // // `grunt test` runs jshint and jscs as well as the 4 test suites. See the individual sub tasks below for // details of each of the test suites. // grunt.registerTask('test', 'Run tests and lint code', ['jshint', 'jscs', 'test-routes', 'test-module', 'test-unit', 'test-integration', 'test-functional']); // ### Lint // // `grunt lint` will run the linter and the code style checker so you can make sure your code is pretty grunt.registerTask('lint', 'Run the code style checks and linter', ['jshint', 'jscs']); // ### Unit Tests *(sub task)* // `grunt test-unit` will run just the unit tests // // Provided you already have a `config.js` file, you can run individual sections from // [mochacli](#grunt-mocha-cli) by running: // // `NODE_ENV=testing grunt mochacli:section` // // If you need to run an individual unit test file, you can do so, providing you have mocha installed globally // by using a command in the form: // // `NODE_ENV=testing mocha --timeout=15000 --ui=bdd --reporter=spec core/test/unit/config_spec.js` // // Unit tests are run with [mocha](http://visionmedia.github.io/mocha/) using // [should](https://github.com/visionmedia/should.js) to describe the tests in a highly readable style. // Unit tests do **not** touch the database. // A coverage report can be generated for these tests using the `grunt test-coverage` task. grunt.registerTask('test-unit', 'Run unit tests (mocha)', ['clean:test', 'setTestEnv', 'ensureConfig', 'mochacli:unit']); // ### Integration tests *(sub task)* // `grunt test-integration` will run just the integration tests // // Provided you already have a `config.js` file, you can run just the model integration tests by running: // // `NODE_ENV=testing grunt mochacli:model` // // Or just the api integration tests by running: // // `NODE_ENV=testing grunt mochacli:api` // // Integration tests are run with [mocha](http://visionmedia.github.io/mocha/) using // [should](https://github.com/visionmedia/should.js) to describe the tests in a highly readable style. // Integration tests are different to the unit tests because they make requests to the database. // // If you need to run an individual integration test file you can do so, providing you have mocha installed // globally, by using a command in the form (replace path to api_tags_spec.js with the test file you want to // run): // // `NODE_ENV=testing mocha --timeout=15000 --ui=bdd --reporter=spec core/test/integration/api/api_tags_spec.js` // // Their purpose is to test that both the api and models behave as expected when the database layer is involved. // These tests are run against sqlite3, mysql and pg on travis and ensure that differences between the databases // don't cause bugs. At present, pg often fails and is not officially supported. // // A coverage report can be generated for these tests using the `grunt test-coverage` task. grunt.registerTask('test-integration', 'Run integration tests (mocha + db access)', ['clean:test', 'setTestEnv', 'ensureConfig', 'mochacli:integration']); // ### Route tests *(sub task)* // `grunt test-routes` will run just the route tests // // If you need to run an individual route test file, you can do so, providing you have a `config.js` file and // mocha installed globally by using a command in the form: // // `NODE_ENV=testing mocha --timeout=15000 --ui=bdd --reporter=spec core/test/functional/routes/admin_test.js` // // Route tests are run with [mocha](http://visionmedia.github.io/mocha/) using // [should](https://github.com/visionmedia/should.js) and [supertest](https://github.com/visionmedia/supertest) // to describe and create the tests. // // Supertest enables us to describe requests that we want to make, and also describe the response we expect to // receive back. It works directly with express, so we don't have to run a server to run the tests. // // The purpose of the route tests is to ensure that all of the routes (pages, and API requests) in Ghost // are working as expected, including checking the headers and status codes received. It is very easy and // quick to test many permutations of routes / urls in the system. grunt.registerTask('test-routes', 'Run functional route tests (mocha)', ['clean:test', 'setTestEnv', 'ensureConfig', 'mochacli:routes']); // ### Module tests *(sub task)* // `grunt test-module` will run just the module tests // // The purpose of the module tests is to ensure that Ghost can be used as an npm module and exposes all // required methods to interact with it. grunt.registerTask('test-module', 'Run functional module tests (mocha)', ['clean:test', 'setTestEnv', 'ensureConfig', 'mochacli:module']); // ### Functional tests for the setup process // `grunt test-functional-setup will run just the functional tests for the setup page. // // Setup only works with a brand new database, so it needs to run isolated from the rest of // the functional tests. grunt.registerTask('test-functional-setup', 'Run functional tests for setup', ['clean:test', 'setTestEnv', 'ensureConfig', 'cleanDatabase', 'express:test', 'spawnCasperJS:setup', 'express:test:stop'] ); // ### Functional tests *(sub task)* // `grunt test-functional` will run just the functional tests // // You can use the `--target` argument to run any individual test file, or the admin or frontend tests: // // `grunt test-functional --target=client/editor_test.js` - run just the editor tests // // `grunt test-functional --target=client/` - run all of the tests in the client directory // // Functional tests are run with [phantom.js](http://phantomjs.org/) and defined using the testing api from // [casper.js](http://docs.casperjs.org/en/latest/testing.html). // // An express server is started with the testing environment set, and then a headless phantom.js browser is // used to make requests to that server. The Casper.js API then allows us to describe the elements and // interactions we expect to appear on the page. // // The purpose of the functional tests is to ensure that Ghost is working as is expected from a user perspective // including buttons and other important interactions in the admin UI. grunt.registerTask('test-functional', 'Run functional interface tests (CasperJS)', ['clean:test', 'setTestEnv', 'ensureConfig', 'cleanDatabase', 'express:test', 'spawnCasperJS', 'express:test:stop', 'test-functional-setup'] ); // ### Coverage // `grunt test-coverage` will generate a report for the Unit and Integration Tests. // // This is not currently done as part of CI or any build, but is a tool we have available to keep an eye on how // well the unit and integration tests are covering the code base. // Ghost does not have a minimum coverage level - we're more interested in ensuring important and useful areas // of the codebase are covered, than that the whole codebase is covered to a particular level. // // Key areas for coverage are: helpers and theme elements, apps / GDK, the api and model layers. grunt.registerTask('test-coverage', 'Generate unit and integration (mocha) tests coverage report', ['clean:test', 'setTestEnv', 'ensureConfig', 'shell:coverage']); // ## Building assets // // Ghost's GitHub repository contains the un-built source code for Ghost. If you're looking for the already // built release zips, you can get these from the [release page](https://github.com/TryGhost/Ghost/releases) on // GitHub or from https://ghost.org/download. These zip files are created using the [grunt release](#release) // task. // // If you want to work on Ghost core, or you want to use the source files from GitHub, then you have to build // the Ghost assets in order to make them work. // // There are a number of grunt tasks available to help with this. Firstly after fetching an updated version of // the Ghost codebase, after running `npm install`, you will need to run [grunt init](#init%20assets). // // For production blogs you will need to run [grunt prod](#production%20assets). // // For updating assets during development, the tasks [grunt](#default%20asset%20build) and // [grunt dev](#live%20reload) are available. // // #### Master Warning *(Utility Task)* // Warns git users not ot use the `master` branch in production. // `master` is an unstable branch and shouldn't be used in production as you run the risk of ending up with a // database in an unrecoverable state. Instead there is a branch called `stable` which is the equivalent of the // release zip for git users. grunt.registerTask('master-warn', 'Outputs a warning to runners of grunt prod, that master shouldn\'t be used for live blogs', function () { console.log('>', 'Always two there are, no more, no less. A master and a'.red, 'stable'.red.bold + '.'.red); console.log('Use the', 'stable'.bold, 'branch for live blogs.', 'Never'.bold, 'master!'); }); // ### Ember Build *(Utility Task)* // All tasks related to building the Ember client code including transpiling ES6 modules and building templates grunt.registerTask('emberBuildDev', 'Build Ember JS & templates for development', ['clean:tmp', 'buildAboutPage', 'emberTemplates:dev', 'transpile', 'concat_sourcemap:dev']); // ### Ember Build *(Utility Task)* // All tasks related to building the Ember client code including transpiling ES6 modules and building templates grunt.registerTask('emberBuildProd', 'Build Ember JS & templates for production', ['clean:tmp', 'buildAboutPage', 'emberTemplates:prod', 'transpile', 'concat_sourcemap:prod']); // ### CSS Build *(Utility Task)* // Build the CSS files from the SCSS files grunt.registerTask('css', 'Build Client CSS', ['sass', 'autoprefixer']); // ### Build About Page *(Utility Task)* // Builds the github contributors partial template used on the Settings/About page, // and downloads the avatar for each of the users. // Run by any task that compiles the ember assets (emberBuildDev, emberBuildProd) // or manually via `grunt buildAboutPage`. // Change which version you're working against by setting the "releaseTag" below. // // Only builds if the contributors template does not exist. // To force a build regardless, supply the --force option. // `grunt buildAboutPage --force` grunt.registerTask('buildAboutPage', 'Compile assets for the About Ghost page', function () { var done = this.async(), templatePath = 'core/client/templates/-contributors.hbs', ninetyDaysAgo = Date.now() - (1000 * 60 * 60 * 24 * 90); if (fs.existsSync(templatePath) && !grunt.option('force')) { grunt.log.writeln('Contributors template already exists.'); grunt.log.writeln('Skipped'.bold); return done(); } grunt.verbose.writeln('Downloading release and contributor information from GitHub'); getTopContribs({ user: 'tryghost', repo: 'ghost', releaseDate: ninetyDaysAgo, count: 20 }).then(function makeContributorTemplate(contributors) { var contributorTemplate = '<li>\n <a href="<%githubUrl%>" title="<%name%>">\n' + ' <img src="{{gh-path "admin" "/img/contributors"}}/<%name%>" alt="<%name%>">\n' + ' </a>\n</li>'; grunt.verbose.writeln('Creating contributors template.'); grunt.file.write(templatePath, // Map contributors to the template. _.map(contributors, function (contributor) { return contributorTemplate .replace(/<%githubUrl%>/g, contributor.githubUrl) .replace(/<%name%>/g, contributor.name); }).join('\n') ); grunt.verbose.writeln('Downloading images for top contributors'); return Promise.promisify(fs.mkdirs)('core/client/assets/img/contributors').then(function () { return contributors; }); }).then(function downloadContributorImages(contributors) { var downloadImagePromise = function (url, name) { return new Promise(function (resolve, reject) { request(url) .pipe(fs.createWriteStream('core/client/assets/img/contributors/' + name)) .on('close', resolve) .on('error', reject); }); }; return Promise.all(_.map(contributors, function (contributor) { return downloadImagePromise(contributor.avatarUrl + '&s=60', contributor.name); })); }).catch(function (error) { grunt.log.error(error); }).finally(done); }); // ### Init assets // `grunt init` - will run an initial asset build for you // // Grunt init runs `bower install` as well as the standard asset build tasks which occur when you run just // `grunt`. This fetches the latest client side dependencies, and moves them into their proper homes. // // This task is very important, and should always be run and when fetching down an updated code base just after // running `npm install`. // // `bower` does have some quirks, such as not running as root. If you have problems please try running // `grunt init --verbose` to see if there are any errors. grunt.registerTask('init', 'Prepare the project for development', ['shell:bower', 'update_submodules', 'default']); // ### Production assets // `grunt prod` - will build the minified assets used in production. // // It is otherwise the same as running `grunt`, but is only used when running Ghost in the `production` env. grunt.registerTask('prod', 'Build JS & templates for production', ['concat:prod', 'copy:prod', 'emberBuildProd', 'uglify:prod', 'master-warn']); // ### Default asset build // `grunt` - default grunt task // // Compiles concatenates javascript files for the admin UI into a handful of files instead // of many files, and makes sure the bower dependencies are in the right place. grunt.registerTask('default', 'Build JS & templates for development', ['concat:dev', 'copy:dev', 'css', 'emberBuildDev']); // ### Live reload // `grunt dev` - build assets on the fly whilst developing // // If you want Ghost to live reload for you whilst you're developing, you can do this by running `grunt dev`. // This works hand-in-hand with the [livereload](http://livereload.com/) chrome extension. // // `grunt dev` manages starting an express server and restarting the server whenever core files change (which // require a server restart for the changes to take effect) and also manage reloading the browser whenever // frontend code changes. // // Note that the current implementation of watch only works with casper, not other themes. grunt.registerTask('dev', 'Dev Mode; watch files and restart server on changes', ['default', 'express:dev', 'watch']); // ### Release // Run `grunt release` to create a Ghost release zip file. // Uses the files specified by `.npmignore` to know what should and should not be included. // Runs the asset generation tasks for both development and production so that the release can be used in // either environment, and packages all the files up into a zip. grunt.registerTask('release', 'Release task - creates a final built zip\n' + ' - Do our standard build steps \n' + ' - Copy files to release-folder/#/#{version} directory\n' + ' - Clean out unnecessary files (travis, .git*, etc)\n' + ' - Zip files in release-folder to dist-folder/#{version} directory', ['init', 'concat:prod', 'copy:prod', 'emberBuildProd', 'uglify:release', 'clean:release', 'copy:release', 'compress:release']); }; // Export the configuration module.exports = configureGrunt;
module.exports = function(){ var express = require('express'), authenticate = require('../lib/auth/authenticate'), signup = require('../lib/auth/signup'), logout = require('../lib/auth/logout'), app = express(); app.post('/signup', signup, function(req,res){ res.send({ status: 'ok', token: req.user.local.token.value, user: req.user }); } ); app.post('/login', authenticate('login'), function(req,res){ res.send({ status: 'ok', token: req.user.local.token.value, user: req.user }); } ); app.post('/logout', authenticate(), logout, function(req,res){ res.send({ status: 'ok' }); } ); app.post('/check', authenticate(), function(req, res){ res.send({ status: 'ok', token: req.user.local.token.value, user: req.user }); } ); return app; };
import V3Adapter from 'travis/adapters/v3'; export default V3Adapter.extend({ includes: 'owner.installation', pathForType: function () { return 'orgs'; }, });
module.exports = (function(win) { var eveData = [], eveUUID = 1, EventObj, Event = {}, fixpara, fixevent; fixpara = ("target type pageX pageY clientX clientY keyCode keyChar "+ "offsetX offsetY path timeStamp screenX screenY touches "+ "altKey ctrlKey shiftKey changedTouches targetTouches").split(" "); fixevent = { transitionend: (function() { if (win.onwebkitTransitionEnd !== null) { return "webkitTransitionEnd"; } else if (win.onwebkitanimationend !== null) { return "webkitanimationend"; } else if (win.ontransitionend !== null) { return "transitionend"; } })(), animationend: (function() { if (win.onwebkitAnimationEnd !== null) { return "webkitAnimationEnd"; } else if (win.onwebkitanimationend !== null) { return "webkitanimationend"; } else if (win.onanimationend !== null) { return "animationend"; } })(), }; // 转换 keycode 为相关字符 function transKey(code) { var keyChar = undefined; if ((code >= 65 && code <= 90) || (code >= 48 && code <= 57)) { keyChar = String.fromCharCode(code); } else { switch (code) { case 8: keyChar = "DEL"; break; case 9: keyChar = "TAB"; break; case 13: keyChar = "Enter"; break; case 16: keyChar = "SHIFT"; break; case 17: keyChar = "CTRL"; break; case 18: keyChar = "ALT"; break; case 20: keyChar = "CAPS"; break; case 27: keyChar = "ESC"; break; case 32: keyChar = "SPACE"; break; case 91: keyChar = "WIN"; break; case 110: keyChar = "."; break; } } return keyChar; } function transEvent(name) { return fixevent[name] || name; } EventObj = function (src, porp) { this.originalEvent = src; this.originalData = src.originalData || []; /* 从原事件对象复制属性 */ for (var i=0; i<fixpara.length; i++) { var key = fixpara[i]; if (src[key] !== undefined) { this[key] = src[key]; } } /* 尝试使用修正对象修正属性 */ for (var key in porp) { this[key] = porp[key]; } /* 修正 keyChar 对象 */ if (!src.keyChar) { this.keyChar = transKey(src.keyCode || src.which); } /* 修正 target 对象 */ if (!this.target && src.originalTarget) { this.target = src.originalTarget } /* 修复 path 对象,无则自己模拟一个出来 */ if (!(this.path instanceof Array)) { var target = this.target, arr = []; while (target && target.parentNode) { arr.push(target); // 当前存下来 target = target.parentNode; } this.path = arr; // 设置对象 } this.isDefaultPrevented = false; this.isPropagationStopped = false; this.isImmediatePropagationStopped = false; return this; } EventObj.prototype.preventDefault = function () { var e = this.originalEvent; if (e) e.preventDefault(); this.isDefaultPrevented = true; return this; } EventObj.prototype.stopPropagation = function () { var e = this.originalEvent; if (e) e.stopPropagation(); this.isPropagationStopped = true; return this; } EventObj.prototype.stopImmediatePropagation = function () { var e = this.originalEvent; if (e) e.stopImmediatePropagation(); this.isPropagationStopped = true; this.isImmediatePropagationStopped = true; return this; } /* 返回命名空间的指定位置 */ function getfix(name, last) { var left, right; right = name.match(/\.+.*$/); right = right?right[0]:""; left = name.replace(right, ""); return last?right.replace(".", ""):left; } /* 检测指定元素是符合查询条件,相对其父元素 */ function checkIn(ele, find) { if (find === "") return true; var ret = false, items; items = ele.parentNode; items = items ? items : document; items = items.querySelectorAll(find); for(var i=0; i<items.length; i++) { if (items[i] === ele) { ret = true; break; } } return ret; // 返回检测结果 } /* 手动执行绑定的回掉事件 */ function triggerCall(ele, calls, event, porp) { if (!ele || !calls || !event) return false; var eve = event instanceof EventObj ? event : new EventObj(event, porp); /* 修复 target 对象 */ if (!eve.target) { eve.target = event.target || event.originalTarget || ele; } /* 复制执行数组,修复once事件导致length异常问题 */ var data = eve.originalData || [], clone = calls.slice(0); if (!(data[0] instanceof EventObj)) { data.unshift(eve); // 修正执行参数数组 } for(var i = 0; i < clone.length; i++) { var item = clone[i]; // 当前事件对象 if (item.name.search(eve.type) === 0 && checkIn(eve.target, item.select)) { data[0].originalType = item.name; item.call.apply(ele, data); } if (eve.isImmediatePropagationStopped) break; } } /** * 对指定对象绑定事件 * @param ele 要绑定的对象 * @param types 事件名,可为多个,支持自定义 * @param select 过滤器参数 * @param call 绑定的要执行的回调函数 * @param capture 是否绑定到传播阶段 * * TODO: 优化性能,所有事件都委托在 document 对象上 * */ Event.bind = function (ele, types, select, call, capture) { var handle, events, eveName, evePre, eveOld; if (ele.nodeType === 3 || ele.nodeType === 8 || arguments.length < 3) { return false; // 参数不齐全直接退出后续执行 } /* 省略过滤器的时候,自动修复参数 call */ if (typeof select == "function") { capture = call; call = select; select = ""; } if (!ele.$_uuid /* 第一次绑定时初始化对象 */) { ele.$_uuid = eveUUID++; eveData[ele.$_uuid] = {}; } handle = eveData[ele.$_uuid]; // 获得事件操作句柄 events = types.split(" "); // 尝试分割事件列表 for (var i = 0; i < events.length; i++) { eveName = events[i]; eveOld = getfix(eveName); evePre = transEvent(eveOld); eveName = eveName.replace(eveOld, evePre); var handleNow = handle[evePre]; if (!handle[evePre] /* 第一次添加 */) { handleNow = handle[evePre] = { handle : null, // 事件句柄 calls : [] // 事件回掉数组 }; handleNow.handle = (function (ele, call) { /* 使用事件触发方法触发绑定的函数 */ return function(e) { triggerCall(ele, call, e); } })(ele, handleNow.calls); ele.addEventListener(evePre, handleNow.handle, !!capture); } handleNow.calls.push({ name : eveName, // 事件全名 call : call, // 回调事件 select: select || '' // 过滤器 }); } } /** * 移除对象的指定事件 * @param ele 要操作的对象 * @param types 要移除的事件名 */ Event.unbind = function (ele, types, capture) { var handle, events, eveName, evePre, eveOld, typeRun; if (!ele || !ele.$_uuid || !types || !(handle = eveData[ele.$_uuid])) return false; events = types.split(" "); for (var i = 0; i < events.length; i++) { eveName = events[i]; eveOld = getfix(eveName); evePre = transEvent(eveOld); eveName = eveName.replace(eveOld, evePre); /* 如果事件不存在,直接跳过 */ if (!handle || !handle[evePre]) continue; typeRun = handle[evePre].calls; for(var j=0; j<typeRun.length; j++) { if (typeRun[j].name.search(eveName) === 0) { typeRun.splice(j--, 1); } } if (typeRun.length === 0) { ele.removeEventListener(evePre, handle[evePre].handle, !!capture); delete handle[evePre]; // 删除对应的事件 } } } /** * 手动触发对象的指定时间 * @param ele 要操作的对象 * @param types 要触发的事件名 * @param event 原来的event事件 * @param data 触发时传递的参数,可多个 */ Event.trigger = function (ele, types /* event data... */) { var handle, events, eveName, evePre, oldEvent = {}, args = arguments, creEvent, data = [], pos = 2; if (!ele || ele.nodeType === 3 || ele.nodeType === 8 || !types) { return false; // 参数不正确则直接退出后续执行 } events = types.split(" "); handle = eveData[ele.$_uuid]; /* 创建传递的参数列表 */ if (args[2] && args[2].target) { args[2].target = "_CheckEvent_"; // 利用event对象只能读值来判断 if (args[2].target != "_CheckEvent_") { oldEvent = args[2]; pos = 3; } } for(; pos<args.length; pos++) { data.push(arguments[pos]); } for (var i = 0; i < events.length; i++) { eveName = events[i]; evePre = getfix(eveName); creEvent = document.createEvent('Event'); creEvent.initEvent(evePre, true, true); creEvent.originalData = data; creEvent.originalTarget = ele; for(var key in oldEvent) { creEvent[key] = oldEvent[key]; } /* 如果当前元素绑定了句柄,且有事件空间,则手动冒泡 */ if (handle && handle[evePre] && eveName.indexOf(".") > 0) { var runEle = ele, handleNow, newEvent = new EventObj(creEvent, {type: eveName}); /* 带命名空间的事件手动执行和模拟冒泡 */ while (runEle && runEle !== document) { handleNow = eveData[runEle.$_uuid]; handleNow = handleNow ? handleNow[evePre] : {}; triggerCall(runEle, handleNow.calls, newEvent) if (newEvent.isPropagationStopped) break; runEle = runEle.parentNode; // 递归到父类 } } else { ele.dispatchEvent(creEvent); } } } /** * 给对象绑定只执行一次的方法 * @param ele 要绑定的对象 * @param types 事件名,可为多个,支持自定义 * @param call 绑定的要执行的回调函数 * @param select 过滤器参数 * */ Event.once = function (ele, types, call, select) { if (!ele || !types || !call) return false; var key = ".once_"+(''+Math.random()).replace(/\D/g, ''), match = types.split(" "), ftypes ; /* 添加once标记后缀,用于后面自移除 */ for(var i=0; i<match.length; i++) { match[i] += key; } ftypes = match.join(" "); Event.bind(ele, ftypes, function() { var argv = arguments, type = argv[0].originalType; call.apply(this, argv); Event.unbind(ele, type); }, select); } return Event; })(window);
/*! * jQuery JavaScript Library v2.1.3 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-12-18T15:11Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Support: Firefox 18+ // Can't be in strict mode, several libs including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // var arr = []; var slice = arr.slice; var concat = arr.concat; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var support = {}; var // Use the correct document accordingly with window argument (sandbox) document = window.document, version = "2.1.3", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android<4.1 // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // Skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // Extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN // adding 1 corrects loss of precision from parseFloat (#15100) return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } if ( obj.constructor && !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android<4.0, iOS<6 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Support: IE9-11+ // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Support: Android<4.1 trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.2.0-pre * http://sizzlejs.com/ * * Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-12-16 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // http://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + characterEncoding + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; nodeType = context.nodeType; if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } if ( !seed && documentIsHTML ) { // Try to shortcut find operations when possible (e.g., not under DocumentFragment) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document (jQuery #6963) if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType !== 1 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, parent, doc = node ? node.ownerDocument || node : preferredDoc; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; parent = doc.defaultView; // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", unloadHandler, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", unloadHandler ); } } /* Support tests ---------------------------------------------------------------------- */ documentIsHTML = !isXML( doc ); /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( doc.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [ m ] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\f]' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+ if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibing-combinator selector` fails if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (oldCache = outerCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements outerCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context !== document && context; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is no seed and only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, len = this.length, ret = [], self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // Option to run scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Support: Blackberry 4.6 // gEBID returns nodes no longer in the document (#6963) if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // Methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); jQuery.fn.extend({ has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within the set index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // Index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); var rnotwhite = (/\S+/g); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an command callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // Add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // If we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready command fires. See #6781 readyWait: 1, // Hold (or release) the ready command holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready command fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); jQuery( document ).off( "ready" ); } } }); /** * The ready command handler and self cleanup method */ function completed() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser command has already occurred. // We once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy command callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Kick off the DOM ready check even if the user does not jQuery.ready.promise(); // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : len ? fn( elems[0], key ) : emptyGet; }; /** * Determines whether an object can have data */ jQuery.acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any /* jshint -W018 */ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { // Support: Android<4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Data.uid++; } Data.uid = 1; Data.accepts = jQuery.acceptData; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android<4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; var data_priv = new Data(); var data_user = new Data(); // Implementation Summary // // 1. Enforce API surface and semantic compatibility with 1.9.x branch // 2. Improve the module's maintainability by reducing the storage // paths to a single mechanism. // 3. Use the same single mechanism to support "private" and "user" data. // 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) // 5. Avoid exposing implementation details on user objects (eg. expando properties) // 6. Provide a clear path for implementation upgrade to WeakMap in 2014 var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE11+ // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // Clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // Not public - generate a queueHooks object, or return the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // Ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // Support: Safari<=5.1 // Check state lost if the name is set (#11217) // Support: Windows Web Apps (WWA) // `name` and `type` must use .setAttribute for WWA (#14901) input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Safari<=5.1, Android<4.2 // Older WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<=11+ // Make sure textarea (and checkbox) defaultValue is properly cloned div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; })(); var strundefined = typeof undefined; support.focusinBubbles = "onfocusin" in window; var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's command structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second command of a jQuery.command.trigger() and // when an command is called after a page has unloaded return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If command changes its type, use the special command handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special command api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all command handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the command handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for command optimization jQuery.event.global[ type ] = true; } }, // Detach an command or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic command handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special command handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match command type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an command type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the command in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the command, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine command propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the command path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the command. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO command when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same command, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native command object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native command args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered command must either 1) have no namespace, or 2) have namespace(s) // a subset or equal to those in the bound command (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some command props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the command object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome<28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native command if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native command so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor command to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated command prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: Android<4.0 src.returnValue === false ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the command object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming command doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && e.stopImmediatePropagation ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and command-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // Support: Firefox, Chrome, Safari // Create "bubbling" focus and blur events if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } data_priv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = data_priv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); data_priv.remove( doc, fix ); } else { data_priv.access( doc, fix, attaches ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since command contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( command ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Fix IE bugs, see support tests function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Fix IE cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit, PhantomJS // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit, PhantomJS // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Ensure the created nodes are orphaned (#12392) tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, type, key, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( jQuery.acceptData( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.command.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each(function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } }); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because push.apply(_, arraylike) throws push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var style, elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? // Use of this method is a temporary fix (more like optimization) until something better comes along, // since it was removed from specification and supported only in FF style.display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = iframe[ 0 ].contentDocument; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { // Support: IE<=11+, Firefox<=30+ (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" if ( elem.ownerDocument.defaultView.opener ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); } return window.getComputedStyle( elem, null ); }; function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // Support: IE9 // getPropertyValue is only needed for .css('filter') (#12537) if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; } if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: iOS < 6 // A tribute to the "awesome hack by Dean Edwards" // iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due // to missing dependency), remove it. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; } (function() { var pixelPositionVal, boxSizingReliableVal, docElem = document.documentElement, container = document.createElement( "div" ), div = document.createElement( "div" ); if ( !div.style ) { return; } // Support: IE9-11+ // Style of cloned element affects source element cloned (#8908) div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" + "position:absolute"; container.appendChild( div ); // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computePixelPositionAndBoxSizingReliable() { div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" + "box-sizing:border-box;display:block;margin-top:1%;top:1%;" + "border:1px;padding:1px;width:4px;position:absolute"; div.innerHTML = ""; docElem.appendChild( container ); var divStyle = window.getComputedStyle( div, null ); pixelPositionVal = divStyle.top !== "1%"; boxSizingReliableVal = divStyle.width === "4px"; docElem.removeChild( container ); } // Support: node.js jsdom // Don't assume that getComputedStyle is a property of the global object if ( window.getComputedStyle ) { jQuery.extend( support, { pixelPosition: function() { // This test is executed only once but we still do memoizing // since we can use the boxSizingReliable pre-computing. // No need to check if the test was already performed, though. computePixelPositionAndBoxSizingReliable(); return pixelPositionVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computePixelPositionAndBoxSizingReliable(); } return boxSizingReliableVal; }, reliableMarginRight: function() { // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // This support function is only executed once so no memoizing is needed. var ret, marginDiv = div.appendChild( document.createElement( "div" ) ); // Reset CSS: box-sizing; display; margin; border; padding marginDiv.style.cssText = div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;padding:0"; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; docElem.appendChild( container ); ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight ); docElem.removeChild( container ); div.removeChild( marginDiv ); return ret; } }); } })(); // A method for quickly swapping in/out CSS properties to get correct calculations. jQuery.swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var // Swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // Return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // Shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // Check for vendor prefixed names var capName = name[0].toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // Both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // At this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // At this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // At this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // Some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // Check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // Use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = data_priv.get( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { hidden = isHidden( elem ); if ( display !== "none" || !hidden ) { data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // Gets hook for the prefixed version, then unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Convert "+=" or "-=" to relative numbers (#7345) if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set (#7116) if ( value == null || value !== value ) { return; } // If a number, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Support: IE9-11+ // background-* props affect original clone's values if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { style[ name ] = value; } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // Try prefixed name followed by the unprefixed name hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } // Convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Make numeric if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // Certain elements can have dimension info if we invisibly show them // but it must have a current display style that would benefit return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); // Support: Android 2.3 jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // Assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // Passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails. // Simple values such as "10px" are parsed to Float; // complex values such as "rotate(1rad)" are returned as-is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // Use step hook for back compat. // Use cssHook if its there. // Use .style if available and use plain properties where available. if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; } }; jQuery.fx = Tween.prototype.init; // Back Compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something*. // Use string for doubling so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur(), // break the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; } ] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // If we include width, step value is 1 to do all cssExpand values, // otherwise step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // We're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = data_priv.get( elem, "fxshow" ); // Handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // Ensure the complete handler is called before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // Height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE9-10 do not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated display = jQuery.css( elem, "display" ); // Test default display if display is currently "none" checkDisplay = display === "none" ? data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { style.display = "inline-block"; } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); // Any non-fx value stops us from restoring the original display value } else { display = undefined; } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = data_priv.access( elem, "fxshow", {} ); } // Store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; data_priv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } // If this is a noop like .hide().hide(), restore an overwritten display value } else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) { style.display = display; } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // Not quite $.extend, this won't overwrite existing keys. // Reusing 'index' because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // Don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // Support: Android 2.3 // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // If we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // Resolve when we played the last frame; otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // Normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // Show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // Animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || data_priv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = data_priv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // Start the next in the queue if the last step wasn't forced. // Timers currently will call their complete callbacks, which // will dequeue but only if they were gotoEnd. if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = data_priv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // Enable finishing flag on private data data.finish = true; // Empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // Look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // Look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // Turn off finishing flag delete data.finish; }); } }); jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }; (function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: iOS<=5.1, Android<=4.2+ // Default value for a checkbox should be "on" support.checkOn = input.value !== ""; // Support: IE<=11+ // Must access selectedIndex to make default options select support.optSelected = opt.selected; // Support: Android<=2.3 // Options inside disabled selects are incorrectly marked as disabled select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<=11+ // An input loses its value after becoming a radio input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; })(); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend({ attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); } }); jQuery.extend({ attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName( elem, "input" ) ) { var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; }; }); var rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); } }); jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // Don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, proceed = arguments.length === 0 || typeof value === "string" && value, i = 0, len = this.length; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // Only assign if different to avoid unneeded rendering. finalValue = value ? jQuery.trim( cur ) : ""; if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // Toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // Check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed `false`, // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; } }); var rreturn = /\r/g; jQuery.fn.extend({ val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // Handle most common string cases ret.replace(rreturn, "") : // Handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE10-11+ // option.text throws exceptions (#14686, #14858) jQuery.trim( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( option.value, values ) >= 0) ) { optionSet = true; } } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); // Return jQuery for attributes-only inclusion jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle command binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var nonce = jQuery.now(); var rquery = (/\?/); // Support: Android 2.3 // Workaround failure to string-cast null input jQuery.parseJSON = function( data ) { return JSON.parse( data + "" ); }; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data, "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat( "*" ), // Document location ajaxLocation = window.location.href, // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ) .replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to // Don't fire events if jQuery.command is undefined in an AMD-usage scenario (#15118) fireGlobals = jQuery.event && s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + nonce++ ) : // Otherwise add one to the end cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // Aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // Extract error from statusText and normalize for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // Shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); jQuery._evalUrl = function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); }; jQuery.fn.extend({ wrapAll: function( html ) { var wrap; if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapAll( html.call(this, i) ); }); } if ( this[ 0 ] ) { // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map(function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function( i ) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); }) .map(function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); jQuery.ajaxSettings.xhr = function() { try { return new XMLHttpRequest(); } catch( e ) {} }; var xhrId = 0, xhrCallbacks = {}, xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); // Support: IE9 // Open requests must be manually aborted on unload (#5280) // See https://support.microsoft.com/kb/2856746 for more info if ( window.attachEvent ) { window.attachEvent( "onunload", function() { for ( var key in xhrCallbacks ) { xhrCallbacks[ key ](); } }); } support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport(function( options ) { var callback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(), id = ++xhrId; xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { delete xhrCallbacks[ id ]; callback = xhr.onload = xhr.onerror = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { complete( // file: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 // Accessing binary-data responseText throws an exception // (#11426) typeof xhr.responseText === "string" ? { text: xhr.responseText } : undefined, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); xhr.onerror = callback("error"); // Create the abort callback callback = xhrCallbacks[ id ] = callback("abort"); try { // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); } catch ( e ) { // #14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } } }, abort: function() { if ( callback ) { callback(); } } }; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery("<script>").prop({ async: true, charset: s.scriptCharset, src: s.url }).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; // Keep a copy of the old load method var _load = jQuery.fn.load; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = jQuery.trim( url.slice( off ) ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; }); jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; var docElem = window.document.documentElement; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -1; // Need to be able to calculate position if either // top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, elem = this[ 0 ], box = { top: 0, left: 0 }, doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // Support: BlackBerry 5, iOS 3 (original iPhone) // If we don't have gBCR, just use 0,0 rather than error if ( typeof elem.getBoundingClientRect !== strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // Assume getBoundingClientRect is there when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : window.pageXOffset, top ? val : window.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); // Support: Safari<7+, Chrome<37+ // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // Blink bug: https://code.google.com/p/chromium/issues/detail?id=229280 // getComputedStyle returns percent when specified for top/left/bottom/right; // rather than make the css module depend on the offset module, just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // If curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); }); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // Margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], // whichever is greatest return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in AMD // (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; }));
var express = require('express'); var app = express(); var routes = express(); var bodyParser = require('body-parser'); var morgan = require('morgan'); var mongoose = require('mongoose'); var server = require('http').Server(app); var io = require('socket.io')(server); var allClients = []; var config = require('./config'); var Task = require('./models/task'); // Configuration var port = process.env.PORT || 8080; mongoose.connect(config.database); app.use(express.static('./public')); // use body parser so we can get info from POST and/or URL parameters app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // use morgan to log requests to the console app.use(morgan('dev')); app.use(function(req, res, next) { req.io = io; next(); }); // List all tasks routes.get('/', function(req, res) { Task.find({}).sort('-created').exec(function(err, tasks) { if (err) throw err; res.jsonp(tasks); }); }); // Create Task routes.post('/', function(req, res) { var task = new Task(req.body); task.save(function(err) { if (err) throw err; req.io.emit('new-task', task); res.jsonp(task); }); }); // Update Task routes.put('/:id', function(req, res) { var id = req.params.id; Task.findById(id, function(err, task) { if ('task' in req.body) { task.task = req.body.task; } if ('completed' in req.body) { task.completed = req.body.completed; } task.updated = new Date(); task.save(function(err, task) { if (err) throw err; req.io.emit('edited-task', task); res.jsonp(task); }); }); }); // Delete task routes.delete('/:id', function(req, res) { Task.findOneAndRemove({ _id: req.params.id }, function(err) { req.io.emit('remove-task'); res.jsonp({ message: "Deleted!" }); }); }); app.use('/api/v1', routes); // catch 404 and forwarding to error handler app.use(function(req, res, next) { res.status(404).json({ error: "Url inválida" }); }); io.on('connection', function(socket) { // add new user allClients.push(socket); // send total all users socket.broadcast.emit('new connection', { total: allClients.length }); // send total current user socket.emit('new connection', { total: allClients.length }); // user disconnect socket.on('disconnect', function() { // remove user allClients.splice(allClients.indexOf(socket), 1); // send new total all users socket.broadcast.emit('close connection', { total: allClients.length }); }); }); server.listen(port, function() { console.log('Server running on port ' + port + '!'); });
(function () { /** * Directive * * @returns {object} directive definition object */ function contentfulEntryDirective() { return { restrict: 'EA', scope: true, controller: 'ContentfulDirectiveCtrl' }; } // Inject directive dependencies contentfulEntryDirective.$inject = []; // Export angular .module('contentful') .directive('contentfulEntry', contentfulEntryDirective); })();
/** * Created by luiz.alberto on 11/11/2014. */ $(function () { /*$('[data-toggle="popover"]').popover();*/ $('[data-toggle="tooltip"]').tooltip(); adjustLayout(); $(window).resize(adjustLayout); }); function adjustLayout(){ var nav = $('.navbar'); var con = $('#content'); $(window).scroll(function () { //console.log($(this).scrollTop()); var scroll = $(this).scrollTop(); if (scroll > 100) { nav.addClass("nav-fixed"); con.addClass("adjust"); } else { nav.removeClass("nav-fixed"); con.removeClass("adjust"); } }); if(document.documentElement.scrollHeight <= document.documentElement.clientHeight){ $('#footer').addClass('footer-fixed').removeClass('hidden'); }else{ $('#footer').removeClass('footer-fixed hidden'); } } function createWaitModal(){ var waitModal = $('<div class="modal static" id="pleaseWaitDialog" tabindex="-1" role="dialog" aria-hidden="true"><div class="modal-dialog modal-sm"><div class="modal-content"><div class="modal-header"><h4>Aguarde...</h4></div><div class="modal-body"><div class="progress progress-striped active"><div class="progress-bar progress-bar-primary" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%">Carregando...</div></div></div></div></div></div>'); var dialogEx = $.extend(waitModal, { show: function() { waitModal.modal({ backdrop: 'static', keyboard: false }); }, hide: function(){ waitModal.modal('hide'); } }); return dialogEx; } function createModal(fnExecute, params, size){ var dialog = $('<div class="modal fade" id="modalComponent" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"><div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h3 class="modal-title text-primary"></h3></div><div class="modal-body"></div><div class="modal-footer"><button type="button" class="btn btn-primary btn-sim"><span class="glyphicon glyphicon-ok-circle"></span> <span class="confirm_button">Sim</span></button><button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove-circle"></span> <span class="negative_button">Não</span></button></div></div></div></div>').appendTo('body'); var params = params; if(size == undefined ) size = 'sm'; dialog.find('.modal-dialog').addClass("modal-"+size); dialog.addClass("bs-example-modal-"+size); var dialogEx = $.extend(dialog, { setTitle: function(title) { dialog.find('.modal-title').text(title); return dialog;}, setMessage: function(message) { dialog.find('.modal-body').text(message); return dialog;}, setContent: function(content) { dialog.find('.modal-body').html(content); return dialog; }, setConfirmText: function(text) { dialog.find('.confirm_button').text(text); return dialog;}, setNegativeText: function(text) { dialog.find('.negative_button').text(text); return dialog;}, hideConfirmButton: function(hide) { dialog.find('.btn-sim').hide(); return dialog;}, show: function() { dialog.modal('show'); return dialog;}, hide: function(){ dialog.modal('hide'); return dialog;} }); dialog.find('.btn-sim').click(function(){fnExecute(params);}); return dialogEx; }; $.fn.ShowAsModal = function(obj){ var component = $(this); var modal = createModal(obj.execute, obj.size); modal.setContent(component); modal.setTitle(obj.title); component.show(); return modal; }; function growAlert(title, text, type, icon, timer){ if(title =='') title = "Alerta:"; var template = $('<div class="alert alert-'+type+'" role="alert"><button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button><i class="fa fa-'+icon+' fa-lg"></i> <strong>'+title+'</strong><br/> '+text+'</div>'); $("#alert-position").prepend(template); template.hide().slideDown(); if(timer!=null){ setTimeout(function(){ template.slideUp('slow'); }, timer); } $(document).find("html, body").animate({ scrollTop: 0 }, "slow"); }
Package.describe({ name: "aldeed:autoform", summary: "Easily create forms with automatic insert and update, and automatic reactive validation.", git: "https://github.com/aldeed/meteor-autoform.git", version: "4.2.2" }); Package.on_use(function(api) { // Dependencies api.versionsFrom(['METEOR@0.9.3', 'METEOR@0.9.4', 'METEOR@1.0']); // common api.use('aldeed:simple-schema@1.1.0'); api.use('check'); // client api.use(['livedata', 'underscore', 'deps', 'templating', 'ui', 'blaze', 'ejson', 'reactive-var'], 'client'); api.use('momentjs:moment@2.8.4', 'client'); api.use('mrt:moment-timezone@0.2.1', 'client', {weak: true}); api.use(['aldeed:collection2@2.0.0', 'reload'], 'client', {weak: true}); // Imply SS to make sure SimpleSchema object is available to app api.imply('aldeed:simple-schema'); // Exports api.export('AutoForm', 'client'); api.export('Utility', 'client', {testOnly: true}); // Common Files api.add_files(['autoform-common.js']); // Client Files api.add_files([ // utilities and general init 'utility.js', 'form-preserve.js', 'autoform-hooks.js', 'autoform-formdata.js', 'autoform-arrays.js', 'autoform.js', // global helpers 'autoform-helpers.js', // validation 'autoform-validation.js', // inputs 'autoform-inputs.js', // public API 'autoform-api.js', // input types 'inputTypes/boolean-checkbox/boolean-checkbox.html', 'inputTypes/boolean-checkbox/boolean-checkbox.js', 'inputTypes/boolean-radios/boolean-radios.html', 'inputTypes/boolean-radios/boolean-radios.js', 'inputTypes/boolean-select/boolean-select.html', 'inputTypes/boolean-select/boolean-select.js', 'inputTypes/button/button.html', 'inputTypes/button/button.js', 'inputTypes/color/color.html', 'inputTypes/color/color.js', 'inputTypes/contenteditable/contenteditable.html', 'inputTypes/contenteditable/contenteditable.js', 'inputTypes/date/date.html', 'inputTypes/date/date.js', 'inputTypes/datetime/datetime.html', 'inputTypes/datetime/datetime.js', 'inputTypes/datetime-local/datetime-local.html', 'inputTypes/datetime-local/datetime-local.js', 'inputTypes/email/email.html', 'inputTypes/email/email.js', 'inputTypes/file/file.html', 'inputTypes/file/file.js', 'inputTypes/hidden/hidden.html', 'inputTypes/hidden/hidden.js', 'inputTypes/image/image.html', 'inputTypes/image/image.js', 'inputTypes/month/month.html', 'inputTypes/month/month.js', 'inputTypes/number/number.html', 'inputTypes/number/number.js', 'inputTypes/password/password.html', 'inputTypes/password/password.js', 'inputTypes/radio/radio.html', 'inputTypes/radio/radio.js', 'inputTypes/range/range.html', 'inputTypes/range/range.js', 'inputTypes/reset/reset.html', 'inputTypes/reset/reset.js', 'inputTypes/search/search.html', 'inputTypes/search/search.js', 'inputTypes/select/select.html', 'inputTypes/select/select.js', 'inputTypes/select-checkbox/select-checkbox.html', 'inputTypes/select-checkbox/select-checkbox.js', 'inputTypes/select-checkbox-inline/select-checkbox-inline.html', 'inputTypes/select-checkbox-inline/select-checkbox-inline.js', 'inputTypes/select-multiple/select-multiple.html', 'inputTypes/select-multiple/select-multiple.js', 'inputTypes/select-radio/select-radio.html', 'inputTypes/select-radio/select-radio.js', 'inputTypes/select-radio-inline/select-radio-inline.html', 'inputTypes/select-radio-inline/select-radio-inline.js', 'inputTypes/submit/submit.html', 'inputTypes/submit/submit.js', 'inputTypes/tel/tel.html', 'inputTypes/tel/tel.js', 'inputTypes/text/text.html', 'inputTypes/text/text.js', 'inputTypes/textarea/textarea.html', 'inputTypes/textarea/textarea.js', 'inputTypes/time/time.html', 'inputTypes/time/time.js', 'inputTypes/url/url.html', 'inputTypes/url/url.js', 'inputTypes/week/week.html', 'inputTypes/week/week.js', // components that render a form 'components/autoForm/autoForm.html', 'components/autoForm/autoForm.js', 'components/quickForm/quickForm.html', 'components/quickForm/quickForm.js', // components that render controls within a form 'components/afArrayField/afArrayField.html', 'components/afArrayField/afArrayField.js', 'components/afArrayField/afArrayField.css', 'components/afEachArrayItem/afEachArrayItem.html', 'components/afEachArrayItem/afEachArrayItem.js', 'components/afFieldInput/afFieldInput.html', 'components/afFieldInput/afFieldInput.js', 'components/afFormGroup/afFormGroup.html', 'components/afFormGroup/afFormGroup.js', 'components/afObjectField/afObjectField.html', 'components/afQuickField/afQuickField.html', 'components/afQuickField/afQuickField.js', 'components/afQuickFields/afQuickFields.html', 'components/afQuickFields/afQuickFields.js', // event handling 'autoform-events.js', // bootstrap3 Template 'templates/bootstrap3/bootstrap3.html', 'templates/bootstrap3/bootstrap3.js', // bootstrap3-horizontal Template 'templates/bootstrap3-horizontal/bootstrap3-horizontal.html', 'templates/bootstrap3-horizontal/bootstrap3-horizontal.js', 'templates/bootstrap3-horizontal/bootstrap3-horizontal.css', // bootstrap3-inline Template 'templates/bootstrap3-inline/bootstrap3-inline.html', 'templates/bootstrap3-inline/bootstrap3-inline.js', 'templates/bootstrap3-inline/bootstrap3-inline.css', // plain Template 'templates/plain/plain.html', 'templates/plain/plain.js', // plain-fieldset Template 'templates/plain-fieldset/plain-fieldset.html', 'templates/plain-fieldset/plain-fieldset.js', ], 'client'); }); Package.on_test(function (api) { api.use(['aldeed:autoform', 'tinytest', 'underscore']); api.add_files(['tests/utility-tests.js', 'tests/autoform-tests.js']); });
import database from './database' import search from './search' module.exports = { 'database': database, 'search': search };
LAN.RenderableFace = function (points, c) { this.type = 'RenderableFace'; this.id = 0; this.color = c; this.points = points; this.frame = false; this.renderOrder = 0; this.z = 0; } LAN.RenderableLine = function (p1, p2, c) { this.type = 'RenderableLine'; this.id = 0; this.lineColor = c; this.p1 = p1; this.p2 = p2; this.renderOrder = 0; this.z = 0; } LAN.RenderableText = function (content, p) { this.type = 'RenderableText'; this.id = 0; this.content = content; this.p = p; this.font = 'Serif'; this.textColor = '#333'; this.fontSize = '17px'; this.renderOrder = 100; this.z = 0; } LAN.Projector = function () { var renderData; this.projectScene = function (scene, camera) { renderData = []; var sight = camera.position.sub(camera.target); sight.normal(); var positionCamera = camera.position; var w = camera.width; var h = camera.height; var nodes = scene.childNodes; var i = -1; while (++i < nodes.length) { var node = nodes[i]; node.update(); node.renderToCam(camera); if (node.type == 'CanvasMesh') { var vectors = []; var normals = []; var j = -1; while ( ++j < node.vectors.length ) { var v = node.vectors[j]; var vp = node.transform.apply(v); vectors.push( vp ); } if ( node.normals ) { var j = -1; while (++j < node.normals.length ) { var n = node.normals[j]; var np = node.transform.world.apply(n); normals.push( np.normal() ); } } var k = -1; while ( ++k < node.faceIndices.length ) { var fi = node.faceIndices[k]; var faceDataLength = fi.data.length; var points = []; var n = -1; var zSum = 0; var pSum = new LAN.Vector(0, 0, 0); while (++n < faceDataLength) { var p = vectors[fi.data[n] - 1]; zSum += p.z pSum.add(p); points.push(p); } if ( !normals[k] ) { normals[k] = LAN.Vector.VecsGetNormal(points[0], points[1], points[2]); } var center = pSum.divide(faceDataLength); var sight = center.sub(camera.position).normal(); var c = LAN.shade(node.colors[k], center, normals[k], scene); var face = new LAN.RenderableFace(points, c); face.normal = normals[k]; face.frame = node.frame; face.renderOrder = node.renderOrder; face.updatable = node.updatable; face.z = zSum / faceDataLength; if ( sight.dot(face.normal) > -0.5) renderData.push(face); } } if (node.type == 'Text') { var p = node.transform.apply(node.position); var content = node.content; var text = new LAN.RenderableText(content, p); text.fontStyle = node.fontSize + " " + node.font; text.textColor = node.textColor.colorStyle(); renderData.push(text); } } return renderData.sort(sortFunc); } function sortFunc(a, b){ if ( a.renderOrder !== b.renderOrder ) { return a.renderOrder - b.renderOrder; } else if ( a.z !== b.z ) { return b.z - a.z; } else { return 0; } } }
var $M = require("@effectful/debugger"), $x = $M.context, $ret = $M.ret, $unhandled = $M.unhandled, $raise = $M.raise, $brk = $M.brk, $mcall = $M.mcall, $m = $M.module("file.js", null, typeof module === "undefined" ? null : module, null, "$", { __webpack_require__: typeof __webpack_require__ !== "undefined" && __webpack_require__ }, null), $s$1 = [{ a: [1, "1:9-1:10"] }, null, 0], $s$2 = [{}, $s$1, 1], $m$0 = $M.fun("m$0", "file.js", null, null, [], 0, 2, "1:0-10:0", 32, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $l[1] = $m$1($); $.goto = 2; continue; case 1: $.goto = 2; return $unhandled($.error); case 2: return $ret($.result); default: throw new Error("Invalid state"); } }, null, null, 0, [[0, "1:0-9:1", $s$1], [16, "10:0-10:0", $s$1], [16, "10:0-10:0", $s$1]]), $m$1 = $M.fun("m$1", "a", null, $m$0, [], 0, 3, "1:0-9:1", 0, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $.goto = 1; $brk(); $.state = 1; case 1: $.goto = 2; $brk(); $.state = 2; case 2: $.goto = 3; ($x.call = eff)(1); $.state = 3; case 3: $l[1] = 13; $.goto = 5; $brk(); continue; case 4: return $raise($l[2]); case 5: $.goto = 6; $brk(); $.state = 6; case 6: $.goto = 7; $mcall("log", console, 1); $.state = 7; case 7: $.goto = 8; $brk(); $.state = 8; case 8: $.goto = 9; ($x.call = eff)(2); $.state = 9; case 9: $.goto = 10; $brk(); $.state = 10; case 10: $.goto = 11; $mcall("log", console, 2); $.state = 11; case 11: $.goto = 12; $brk(); $.state = 12; case 12: $.goto = $l[1]; continue; case 13: $.goto = 15; $brk(); continue; case 14: $.goto = 15; return $unhandled($.error); case 15: return $ret($.result); default: throw new Error("Invalid state"); } }, function ($, $l) { switch ($.state) { case 3: case 2: case 1: $.goto = 5; $l[1] = 4; $l[2] = $.error; break; default: $.goto = 14; } }, function ($, $l) { switch ($.state) { case 3: case 2: case 1: $l[1] = 15; $.goto = 5; break; default: $.goto = 15; break; } }, 1, [[4, "2:2-8:3", $s$2], [4, "3:4-3:11", $s$2], [2, "3:4-3:10", $s$2], [36, "4:3-4:3", $s$2], [0, null, $s$2], [4, "5:4-5:19", $s$2], [2, "5:4-5:18", $s$2], [4, "6:4-6:11", $s$2], [2, "6:4-6:10", $s$2], [4, "7:4-7:19", $s$2], [2, "7:4-7:18", $s$2], [36, "8:3-8:3", $s$2], [0, null, $s$2], [36, "9:1-9:1", $s$2], [16, "9:1-9:1", $s$2], [16, "9:1-9:1", $s$2]]); $M.moduleExports();
import {List, Map, fromJS} from 'immutable' import { FETCH_SPELLBOOKS_STARTED, FETCH_SPELLBOOKS_SUCCESS, FETCH_SPELLBOOKS_FAILURE, CREATE_NEW_SPELLBOOK_STARTED, CREATE_NEW_SPELLBOOK_SUCCESS, CREATE_NEW_SPELLBOOK_FAILURE, } from '../actions/action-types' const initialState = fromJS({ fetching: false, creating: false, ready: false, fail: false, filter: { limit: 10, searchText: "" }, result: [] }) const spellbooksReducer = (state = initialState, action) => { switch (action.type){ case FETCH_SPELLBOOKS_STARTED: return state.set('fetching', true) case FETCH_SPELLBOOKS_SUCCESS: return state.withMutations(state => { state.set('fetching', false) state.set('ready', true) state.set('result', fromJS(action.result)) }) case FETCH_SPELLBOOKS_FAILURE: return state.withMutations(state => { state.set('fetching', false) state.set('fail', true) }) case CREATE_NEW_SPELLBOOK_STARTED: return state.withMutations(state => { return state.set('creating', true) }) case CREATE_NEW_SPELLBOOK_SUCCESS: return state.withMutations(state => { state.set('creating', false) state.set('result', state.get('result').push(action.result)) }) case CREATE_NEW_SPELLBOOK_FAILURE: return state.withMutations(state => { state.set('creating', false) state.set('fail', true) }) } return state } export default spellbooksReducer
import React from 'react'; import { SizeMeasurer } from './SizeMeasurer'; /** * Wrap the given component to make it expandable. * @param {React.Component} Component - The component to be wrapped. * @return {React.Component} The wrapped component. */ export default function beExpandable(Component) { const componentName = Component.displayName || Component.name; return React.createClass({ getDefaultProps() { return { size: { width: 100, height: 100 } }; }, displayName: `BeExpandable(${componentName})`, getInitialState() { const { width, height } = this.props.size; return { width, height, isExpanding: false }; }, render() { const { size, expander, expanders, ...props } = this.props; if (! (expander || expanders)) { throw new Error('beExpandable: Please set expander as a prop'); } return ( <Component {...props} width={this.state.width} height={this.state.height} > {props.children} {this.renderExpanders()} </Component> ); }, getExpanders() { const { expander, expanders } = this.props; return expander ? [expander] : expanders; }, normalizeExpanders(expanders) { return expanders.map(expander => { if (typeof expander === 'function') { return expander(); } return expander; }); }, renderExpanders() { const expanders = this.getExpanders(); return this.normalizeExpanders(expanders) .map(exp => this.renderExpander(exp.key, exp.props)); }, renderExpander(key, allProps = {}) { const { defaultStyle, className, expandTo, ...props } = allProps; const style = defaultStyle ? this.makeDefaultExpanderStyle() : []; const connector = this.makeConnector(); const stateClass = this.state.isExpanding ? 're-expanding' : ''; return ( <div draggable key={key} onMouseDown={ e => this.startResizing(e, expandTo, connector) } style={style} className={(className || '') + ` ${stateClass}`} {...props} /> ); }, makeDefaultExpanderStyle() { return { position: 'absolute', right: 0, bottom: 0, width: '10px', height: '10px', cursor: 'move' }; }, startResizing(e, directions = 'bottom right', connector) { const { width, height } = this.state; this._measurer = new SizeMeasurer({ width, height, clientX: e.clientX, clientY: e.clientY, directions }); this.props.expander.startResizing(connector); }, stopResizing() { this._measurer = undefined; this.setState({ isExpanding: false }); }, expand(e) { const width = this._measurer.measureWidth(e.clientX); const height = this._measurer.measureHeight(e.clientY); this.setState({ width, height, isExpanding: true }); }, makeConnector() { return { expand: this.expand, stopResizing: this.stopResizing }; }, isExpanding() { return !! this._measurer; } }); }
'use strict'; module.exports = function random(length) { var randomLength = length || 1; var randomCollection = this.slice().shuffle().take(randomLength); if (randomLength === 1) { return randomCollection.first(); } return randomCollection; };
(function fyUIModalFramer(){}).subClass(fyFrame, function(application,$,isClass) { this.initializeInstanceWith( function(application,$) { var thisProtected; this.defineConstructor( function Create() { thisProtected=this.protectedData; this.inherited(arguments); this.zIndex=-1; this.position={x:0,y:0}; this.opacity=0; this.visible=false; this.display=this.animate.inSeconds(0.3).fade.in; var lid=fyPanel.Create(this); lid.position={x:0,y:0}; lid.background="gray"; lid.opacity=0.5; lid.zIndex=998; lid.id="modalLid"; lid.onClick(this.modalLidClicked); thisProtected.lid=lid; }); this.defineMethod( function showModal() { this.zIndex=997; var d=this.parent.dimensions; this.dimensions=d; thisProtected.lid.dimensions=d; this.display.run.forward(); }); this.defineMethod( function endModal(after) { var that=this; this.display.run.reverse.then( function() { that.zIndex=-1; if(after) after(); }); }); this.defineMethod( function modalLidClicked() { //alert("lid click"); }); }); }); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// (function fyMessageBox(){}).subClass(fyFrame, function(application,$,isClass) { application.defineEnumeration( "fyModalResult", [ {name:"mrCancel",text:"Cancel"}, {name:"mrOK",text:"OK"}, {name:"mrYes",text:"Yes"}, {name:"mrNo",text:"No"}, {name:"mrRetry",text:"Retry"}, {name:"mrContinue",text:"Continue"} ]); this.initializeInstanceWith( function(application,$) { var thisProtected; this.defineConstructor( function Create() { thisProtected=this.protectedData; this.inherited(application.modalFrame); thisProtected.dontAskAgain=false; this.zIndex=999; this.align="center"; this.visible=false; }); this.defineProperties({ modalResult:{ get:function(){return thisProtected.modalResult;}, set: function(value) { that=this; thisProtected.modalResult=value; if(value!==0) { this.parent.endModal( function() { that.visible=false; thisProtected.modalComplete.resolve(); }); } } } }); this.defineMethod( function showModal(messageInfo) { thisProtected.modalResult=0; var modalComplete=(thisProtected.modalComplete=$.Deferred()); if(messageInfo.onComplete) $.when(modalComplete).then( function() { messageInfo.modalResult=thisProtected.modalResult; messageInfo.dontAskAgain=thisProtected.dontAskAgain; messageInfo.onComplete(messageInfo); }); this.visible=true; this.parent.showModal(); }); }); });
'use strict' const globby = require('globby') const fs = require('fs') const matchTime = (file) => new Promise((resolve, reject) => { let currentLogs try { let content = fs.readFileSync('watermill.json') currentLogs = JSON.parse(content) } catch(err) { console.log('errored') reject() } if (!currentLogs[file]) { reject('Path not in watermill.json') } let stats try { stats = fs.statSync(file) } catch(err) { reject() } const time = stats.mtime.getTime() if (currentLogs[file].time === time) { console.log('Time matched for ' + file) resolve() } else { reject('Time did not match for ' + file) } }) module.exports = matchTime
'use strict'; // Declare app level module which depends on views, and components angular.module('myApp', [ 'ngRoute', 'myApp.view1', 'myApp.view2', 'myApp.version' ]).config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) { $routeProvider.otherwise({redirectTo: '/view1'}); //$httpProvider.defaults.headers.post['X-CSRF-Token'] = $('meta[name="csrf-token"]').attr("content"); $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest'; $httpProvider.defaults.headers.common['Accept'] = 'application/json, text/javascript'; $httpProvider.defaults.headers.common['Content-Type'] = 'application/json; charset=utf-8'; console.log("ready!"); }]).factory("chatFactory", function ($http) { var factory = {}; factory.ajaxPost = function (url, data, success, error) { return $.ajax({ url: url, type: "POST", data: data, dataType: "json", headers: {'Content-Type': 'application/x-www-form-urlencoded'}, success: success, error: error }); }; return factory; });
angular.module("leaflet-directive") .factory('leafletEventsHelpers', function ($rootScope, $q, $log, leafletHelpers) { var safeApply = leafletHelpers.safeApply, isDefined = leafletHelpers.isDefined; var _fire = function(scope, broadcastName, logic, event, lObject, model, modelName, layerName){ // Safely broadcast the event safeApply(scope, function(){ var toSend = { leafletEvent: event, leafletObject: lObject, modelName: modelName, model: model }; if (isDefined(layerName)) angular.extend(toSend, {layerName: layerName}); if (logic === "emit") { scope.$emit(broadcastName, toSend); } else { $rootScope.$broadcast(broadcastName, toSend); } }); }; return { fire: _fire } });
/*Simple socket based server Author: Ketan Bhardwaj */ var net = require('net'); var fs = require('fs'); var buffer = require('buffer'); var settings = {}; try { settings = require("konphyg")(__dirname)("config"); } catch (e) { console.error(e); } var debug = settings.debug; var verbose = settings.verbose; var send_code = function(sock,code) { buf = new Buffer(1); buf[0] =code; sock.write(buf); } var send_size = function(sock,size) { //var tosend = parseInt(size); var buf = new Buffer(4); //bytes[0] = tosend & 24; //bytes[1] = tosend >> 16; //bytes[2] = tosend >> 8; //bytes[3] = tosend; //buf = new Buffer(bytes); buf.writeInt32LE(size, 0); if(verbose) console.log("send_size size: "+ size ); sock.write(buf); } var lookup_class = function(sock,class_name) { //TODO Check var class_path = settings.xrepo + class_name.toString().replace('.apk.classes','/classes.dex'); if(verbose) console.log("lookup_class() class path: "+ class_path); try { stat = fs.statSync(class_path); if (!stat.isFile()) { if(verbose) console.log("lookup_class(): unable to stat file " + class_path); return false; } else { send_size(sock,stat.size); } } catch (e) { if(debug) console.log("lookup_class(): FS STAT ERROR"); return false; } if(verbose) console.log("lookup_class() : Found "); return true; } var lookup_asset = function(sock,asset_name) { //TODO Check var asset_path = settings.xrepo + asset_name.toString().replace('.apk',''); if(verbose) console.log("lookup_asset() asset path: "+ asset_path); try { stat = fs.statSync(asset_path); if (!stat.isFile()) { if(verbose) console.log("lookup_asset(): unable to stat file " + asset_path); return false; } else { send_size(sock,stat.size); } } catch (e) { if(debug) console.log("lookup_asset(): FS STAT ERROR"); return false; } if(verbose) console.log("lookup_asset() : Found "); return true; } var send_class_byte_code = function(sock,class_name) { //TODO Check var class_path = settings.xrepo + class_name.toString().replace('.apk.classes','/classes.dex'); if(verbose) console.log("send_class_byte_code() Class path: "+class_path); readable = fs.createReadStream(class_path, { flags: "r"}); readable.pipe(sock,{end:false}); readable.on('end',function(){ // readable.unpipe(sock); if(verbose) console.log("send_class_byte_code(): Sending <EOC>"); // send_code(sock,0xFC); }); } var send_asset = function(sock,asset_name) { //TODO Check var asset_path = settings.xrepo + asset_name.toString().replace('.apk',''); if(verbose) console.log("send_asset() asset path: "+asset_path); readable = fs.createReadStream(asset_path, { flags: "r"}); readable.pipe(sock,{end:false}); readable.on('end',function(){ // readable.unpipe(sock); if(verbose) console.log("send_asset_byte_code(): Sending <EOC>"); // send_code(sock,0xFC); }); } var server = net.createServer(function(c) { //'connection' listener if(verbose) console.log("c.on(connected)"); // class name is strings c.setEncoding('hex'); c.on('end', function() { if(verbose) console.log('c.on(end): disconnected'); }); c.on('data', function(data){ raw = new Buffer(data,'hex'); if(verbose) console.log("c.on(data): request for: " + raw.toString()); send_code(c,0xFF); if(raw.toString().indexOf(".classes") > -1) { if(lookup_class(c,raw.toString().substring(0, raw.toString().length - 1))) { // send class from here asynchronously send_class_byte_code(c,raw.toString().substring(0, raw.toString().length - 1));/*,function(err){ if(err) { console.log(" Error sending class"); c.write(0xE4); } });*/ } else { if(debug) console.log(" c.on(data): unable to locate class -- Sending <CNS>") ; send_code(c,0xE3); } } else { if(lookup_asset(c,raw.toString().substring(0, raw.toString().length - 1))) { send_asset(c,raw.toString().substring(0, raw.toString().length - 1)); } else { if(debug) console.log(" c.on(data): unable to locate asset -- Sending <CNFC>") ; send_code(c,0xE3); } } }); c.on('error', function(e) { console.log("socket " + e); }); }); server.on('error', function (e) { if (e.code == 'EADDRINUSE') { if(debug) console.log("TCP server.on(error): Address in use, retrying..."); setTimeout(function () { server.close(); server.listen(PORT, HOST); }, 1000); } }); server.listen(3000,"192.168.1.204",function() { //'listening' listener address = server.address(); console.log(" Famulous listening on %j", address); });
var dir_7d66b2a9f733c5300d1bf1bda6559cfd = [ [ "RoleWidget.php", "_role_widget_8php_source.html", null ], [ "WidgetBase.php", "_widget_base_8php_source.html", null ], [ "WidgetManager.php", "_widget_manager_8php_source.html", null ] ];