code
stringlengths 2
1.05M
|
|---|
var fs=require("fs");
module.exports=function(opt){
opt=opt||{};
opt.path=opt.path||process.env.PWD+'/log/';
opt.logname=opt.logname||'error.'+new Date().getTime()+'.txt';
var errStream=fs.createWriteStream(opt.path+opt.logname,{flags:'a'});
var logError=function(e){
console.log('Error: '+e);
var E={};
E.time=new Date().toISOString();
E.msg='ERR: '+e;
errStream.write(JSON.stringify(E)+'\n');
};
process.on('uncaughtException',function(err){
// this is a really dirty way to keep your server alive
// but it's preferable to letting it die
// in the future there will be a domain based solution
logError(err);
});
return logError;
};
|
var x = document.getElementById("get-location")
function getCurrentPosition() {
return new Promise(function (accept, reject) {
navigator.geolocation.getCurrentPosition(accept, reject)
})
}
function getDeviceFromUrl() {
var obj = {}
var params = location.search.slice(1).split('&')
.forEach(function (param) {
var key = param.split('=')[0]
var value = param.split('=')[1]
obj[key] = value
})
return parseInt(obj.device, 10) || -1
}
// IIFE
(function() {
// Set the value
$('input[name=sensor_id][value=' + getDeviceFromUrl() + ']')
.prop('checked', true)
$('#location-not-available').attr('hidden', navigator.geolocation)
$('#get-location').attr('disabled', !navigator.geolocation)
})()
x.addEventListener('click', function() {
// Disable the button
$('#get-location').attr('disabled', true)
if (navigator.geolocation) {
$('#get-location').text('Getting permissions...')
getCurrentPosition()
.then(function showPosition(position) {
var lat = position.coords.latitude
var lon = position.coords.longitude
$('#latitude').val(lat)
$('#longitude').val(lon)
// Fetch to the API
$('#get-location').text('Searching a sensor...')
return $.ajax({
url: 'https://api.smartcitizen.me/v0/devices',
data: {
near: [lat, lon].join(',')
}
})
})
.then(function (data, textStatus, jqXHR) {
$('#get-location')
.text('Done!')
.removeClass('btn-primary')
.addClass('btn-success')
// Take the first one
var nearSensor = data[0]
$('#sensor-id-calc').val(nearSensor.id)
$('#nearest-sensor').attr('hidden', false)
$('#nearest-sensor-text').text(nearSensor.name)
console.log(nearSensor.id)
})
.catch(function (error) {
$('#get-location').attr('disabled', false)
$('#get-location').text('Detect automatically')
$('#location-not-available').attr('hidden', false)
if (error.message && error.message === 'User denied Geolocation') {
$('#location-not-available').text('You have to allow geolocation')
} else {
$('#location-not-available').text('Not available')
}
})
}
})
|
describe("Render scheme", function () {
let mainPage
let schemeContainer
beforeEach(function (client, done) {
mainPage = client
.url("localhost:3200")
.page.main()
schemeContainer = mainPage.section.schemeContainer
client.waitForElementVisible(".download-url-input", 5000)
.pause(5000)
.clearValue(".download-url-input")
.setValue(".download-url-input", "http://localhost:3200/test-specs/petstore.json")
.click("button.download-url-button")
.pause(1000)
done()
})
it("render section", function (client) {
mainPage.expect.section("@schemeContainer").to.be.visible.before(5000)
client.end()
})
it("render scheme option", function (client) {
schemeContainer.waitForElementVisible("@httpOption", 5000)
.expect.element("@httpOption").to.be.selected
client.end()
})
it("render authorized button", function (client) {
schemeContainer.waitForElementVisible("@btnAuthorize", 5000)
.expect.element("@btnAuthorize").to.be.visible
client.end()
})
it("render click event", function(client) {
schemeContainer.waitForElementVisible("@btnAuthorize", 5000)
.click("@btnAuthorize")
.assert.visible("@authorizationModal")
.assert.containsText("@appName", "Application: your-app-name")
.assert.containsText("@authorizationUrl", "http://petstore.swagger.io/oauth/dialog")
.assert.containsText("@flow", "implicit")
.assert.value("@inputClientID", "your-client-id")
client.end()
})
})
|
'use strict';
module.exports = {
db: 'mongodb://localhost/mean-test',
port: 3001,
app: {
title: 'Wello Fridge [Test]'
},
trello: {
clientID: process.env.TRELLO_KEY,
clientSecret: process.env.TRELLO_SECRET,
callbackURL: 'http://localhost:3000/auth/trello/callback'
}
};
|
var PUBNUB = require('pubnub') ;
require('dotenv').config();
var pubnub = PUBNUB({
publish_key : process.env.publish_key,
subscribe_key : process.env.subscribe_key
});
pubnub.subscribe({
channel: 'log_channel',
// connect: play,
callback: function(m) {
console.log ( m) ;
},
error: function(err) {
console.log(err);
}
});
|
var nf = sm("do_Notification");
var app = sm("do_App");
var me=ui("me");
me.on("touch",function(data, e){
app.openPage({source:"source://view/me.ui", data:"", animationType:"", isFullScreen:false, keyboardMode:"default", scriptType:""}, function(data, e){});
});
|
import expect from 'expect';
import * as actions from '../actions';
import {
LOAD_DATA_INITIATION,
LOAD_DATA_SUCCESS,
LOAD_DATA_FAILURE,
CLEAR_DATA_ERROR,
} from '../constants';
// Testing actions is as easy as validating that the actions are dispatched
// The way you think they are being dispatched.
// Just test that your expected Action object is what is actually dispatched.
// If you need help,
// See here: http://redux.js.org/docs/recipes/WritingTests.html
describe('FeatureFirstContainer actions', () => {
it('should dispatch an action to initiate the loading process', () => {
const expectedAction = {
type: LOAD_DATA_INITIATION,
};
expect(
actions.loadDataInitiation()
).toEqual(expectedAction);
});
it('should dispatch an action to successfully finish loading', () => {
const data = {
items: [],
};
const expectedAction = {
type: LOAD_DATA_SUCCESS,
data,
};
expect(
actions.loadDataSuccess(data)
).toEqual(expectedAction);
});
it('should dispatch an action with an error describing a failure to load data', () => {
const error = {
message: 'An error occured',
};
const expectedAction = {
type: LOAD_DATA_FAILURE,
error,
};
expect(
actions.loadDataFailure(error)
).toEqual(expectedAction);
});
it('should dispatch an action to clear the error', () => {
const expectedAction = {
type: CLEAR_DATA_ERROR,
};
expect(
actions.clearDataError()
).toEqual(expectedAction);
});
});
|
/**
* Created by USER: tarso.
* On DATE: 20/12/16.
* By NAME: app05-multiparm
*
* Source: https://hapijs.com/tutorials/routing?lang=en_US
*/
'use strict';
const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({ port: 3000 });
server.route({
method: 'GET',
path: '/hello/{user*2}',
handler: function (request, reply) {
const userParts = request.params.user.split('/');
reply('Hello ' + encodeURIComponent(userParts[0]) + ' ' + encodeURIComponent(userParts[1]) + '!');
}
});
server.start((err) => {
if (err) {
throw err;
}
console.log(`Server running at: ${server.info.uri}`);
});
|
/*
* SignalConnection
*
* 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.
*/
"use strict";
var SignalConnection = (function () {
/**
*
* @param {SignalAbstract} signal
* @param {Function} listener
*/
function SignalConnection(signal, listener) {
this._next = null;
this.stayInList = true;
this._signal = signal;
this._listener = listener;
}
/**
* Only dispatches once
* @returns {SignalConnection}
*/
SignalConnection.prototype.once = function () {
this.stayInList = false;
return this;
};
/**
* Throws away the signal
*/
SignalConnection.prototype.dispose = function () {
if (this._signal != null) {
this._signal.disconnect(this);
this._signal = null;
}
};
return SignalConnection;
}());
exports.SignalConnection = SignalConnection;
|
var slideBlocker = 0;
function sliderSlideLeft(outerClassName, leftArrowID, itemCounterClass, itemClass, sliderLoaderBackgroundClass, sliderLoaderProgressClass, sliderLoaderFinishClass, ItemsCount, ajaxMode, switchClass, switchItemClass, switchItemActClass, switchItemCountClass, switchResAct, switchResInAct, HideItemClass)
{
//последовательность действий):
// если Ajax
// 1)ставим заставку слайдера (SliderGen::splash_class)
// 2)отображаем прогресс бар/ы (SliderGen::lp_class) (миннимум 1 секунда)
// 3)получаем элементы для подстановки
// 4)отображаем финальную картинку удачной загрузки бар/ы (SliderGen::lp_class_ok)
// 5)подменяем отображаемые элементы новыми элементами
//
// если не Ajax
// 1)ставим заставку слайдера (SliderGen::splash_class)
// 2)отображаем прогресс бар/ы (SliderGen::lp_class) (миннимум 1 секунда)
// 3)отображаем финальную картинку удачной загрузки бар/ы (SliderGen::lp_class_ok)
// 4)подменяем отображаемые элементы новыми элементами
if(ajaxMode == 1)
{
}
else
{
//получаем номера, которые необходимо обновить
var f_item = 0;
var l_item = 0;
$("." + outerClassName + " ." + itemClass).each(function(){
if($(this).css("display") == "block")
{
f_item = parseInt($(this).attr("class").replace(/[a-zA-Z _]/g, ""));
return false;
}
});
l_item = parseInt(f_item) + parseInt(ItemsCount);
var work = sliderCheckSlide(f_item, outerClassName, itemClass, itemCounterClass, ItemsCount, "left", HideItemClass);
if(work == 1)
{
sliderShowBack(f_item, l_item, outerClassName, itemCounterClass, ItemsCount, sliderLoaderBackgroundClass, sliderLoaderProgressClass, "left");
//setTimeout('sliderShowFinish(' + f_item + ', ' + l_item + ', "' + outerClassName + '", "' + itemCounterClass + '", "' + ItemsCount + '", "' + sliderLoaderProgressClass + '", "' + sliderLoaderFinishClass + '", "left");', 2000);
setTimeout('sliderChangeItems(' + f_item + ', ' + l_item + ', "' + outerClassName + '", "' + itemClass + '", "' + itemCounterClass + '", "' + ItemsCount + '", "left", "' + HideItemClass + '");', 250);
setTimeout('sliderHideBack(' + f_item + ', ' + l_item + ', "' + outerClassName + '", "' + itemClass + '", "' + itemCounterClass + '", "' + ItemsCount + '", "' + sliderLoaderBackgroundClass + '", "' + sliderLoaderFinishClass + '", "left", "' + HideItemClass + '");', 300);
setTimeout('sliderSwitchSide("' + outerClassName + '", "' + switchClass + '", "' + switchItemClass + '", "' + switchItemActClass + '", "' + switchItemCountClass + '", "' + switchResAct + '", "' + switchResInAct + '", "left", "' + HideItemClass + '");', 220);
}
}
}
function sliderSlideRight(outerClassName, rightArrowID, itemCounterClass, itemClass, sliderLoaderBackgroundClass, sliderLoaderProgressClass, sliderLoaderFinishClass, ItemsCount, ajaxMode, switchClass, switchItemClass, switchItemActClass, switchItemCountClass, switchResAct, switchResInAct, HideItemClass)
{
//последовательность действий):
// если Ajax
// 1)ставим заставку слайдера (SliderGen::splash_class)
// 2)отображаем прогресс бар/ы (SliderGen::lp_class) (миннимум 1 секунда)
// 3)получаем элементы для подстановки
// 4)отображаем финальную картинку удачной загрузки бар/ы (SliderGen::lp_class_ok)
// 5)подменяем отображаемые элементы новыми элементами
//
// если не Ajax
// 1)ставим заставку слайдера (SliderGen::splash_class)
// 2)отображаем прогресс бар/ы (SliderGen::lp_class) (миннимум 1 секунда)
// 3)отображаем финальную картинку удачной загрузки бар/ы (SliderGen::lp_class_ok)
// 4)подменяем отображаемые элементы новыми элементами
if(ajaxMode == 1)
{
}
else
{
//получаем номера, которые необходимо обновить
var f_item = 0;
var l_item = 0;
$("." + outerClassName + " ." + itemClass).each(function(){
if($(this).css("display") == "block")
{
f_item = parseInt($(this).attr("class").replace(/[a-zA-Z _-]/g, ""));
return false;
}
});
l_item = parseInt(f_item) + parseInt(ItemsCount);
//проверяем - есть ли элементы для обновления
var work = sliderCheckSlide(f_item, outerClassName, itemClass, itemCounterClass, ItemsCount, "right", HideItemClass);
if(work == 1)
{
sliderShowBack(f_item, l_item, outerClassName, itemCounterClass, ItemsCount, sliderLoaderBackgroundClass, sliderLoaderProgressClass, "right");
//setTimeout('sliderShowFinish(' + f_item + ', ' + l_item + ', "' + outerClassName + '", "' + itemCounterClass + '", "' + ItemsCount + '", "' + sliderLoaderProgressClass + '", "' + sliderLoaderFinishClass + '", "right");', 2000);
setTimeout('sliderChangeItems(' + f_item + ', ' + l_item + ', "' + outerClassName + '", "' + itemClass + '", "' + itemCounterClass + '", "' + ItemsCount + '", "right", "' + HideItemClass + '");', 250);
setTimeout('sliderHideBack(' + f_item + ', ' + l_item + ', "' + outerClassName + '", "' + itemClass + '", "' + itemCounterClass + '", "' + ItemsCount + '", "' + sliderLoaderBackgroundClass + '", "' + sliderLoaderFinishClass + '", "right", "' + HideItemClass + '");', 250);
setTimeout('sliderSwitchSide("' + outerClassName + '", "' + switchClass + '", "' + switchItemClass + '", "' + switchItemActClass + '", "' + switchItemCountClass + '", "' + switchResAct + '", "' + switchResInAct + '", "right", "' + HideItemClass + '");', 220);
}
}
}
function sliderSlideNum(NewNum, outerClassName, itemCounterClass, itemClass, sliderLoaderBackgroundClass, sliderLoaderProgressClass, sliderLoaderFinishClass, ItemsCount, ajaxMode, switchClass, switchItemClass, switchItemActClass, switchItemCountClass, switchResAct, switchResInAct, HideItemClass)
{
//последовательность действий):
// если Ajax
// 1)ставим заставку слайдера (SliderGen::splash_class)
// 2)отображаем прогресс бар/ы (SliderGen::lp_class) (миннимум 1 секунда)
// 3)получаем элементы для подстановки
// 4)отображаем финальную картинку удачной загрузки бар/ы (SliderGen::lp_class_ok)
// 5)подменяем отображаемые элементы новыми элементами
//
// если не Ajax
// 1)ставим заставку слайдера (SliderGen::splash_class)
// 2)отображаем прогресс бар/ы (SliderGen::lp_class) (миннимум 1 секунда)
// 3)отображаем финальную картинку удачной загрузки бар/ы (SliderGen::lp_class_ok)
// 4)подменяем отображаемые элементы новыми элементами
if(ajaxMode == 1)
{
}
else
{
//получаем номера, которые необходимо обновить
var f_item = 0;
var l_item = 0;
var new_item = parseInt(NewNum) * parseInt(ItemsCount) - parseInt(ItemsCount) + parseInt(1);
$("." + outerClassName + " ." + itemClass).each(function(){
if($(this).css("display") == "block")
{
f_item = parseInt($(this).attr("class").replace(/[a-zA-Z _-]/g, ""));
return false;
}
});
l_item = parseInt(f_item) + parseInt(ItemsCount);
//проверяем - есть ли элементы для обновления
var work = sliderCheckSlide(f_item, outerClassName, itemClass, itemCounterClass, ItemsCount, new_item, HideItemClass);
if(work == 1)
{
//alert(outerClassName);
sliderShowBack(f_item, l_item, outerClassName, itemCounterClass, ItemsCount, sliderLoaderBackgroundClass, sliderLoaderProgressClass, new_item);
//setTimeout('sliderShowFinish(' + f_item + ', ' + l_item + ', "' + outerClassName + '", "' + itemCounterClass + '", "' + ItemsCount + '", "' + sliderLoaderProgressClass + '", "' + sliderLoaderFinishClass + '", "right");', 2000);
setTimeout('sliderChangeItems(' + f_item + ', ' + l_item + ', "' + outerClassName + '", "' + itemClass + '", "' + itemCounterClass + '", "' + ItemsCount + '", ' + new_item + ', "' + HideItemClass + '");', 250);
setTimeout('sliderHideBack(' + f_item + ', ' + l_item + ', "' + outerClassName + '", "' + itemClass + '", "' + itemCounterClass + '", "' + ItemsCount + '", "' + sliderLoaderBackgroundClass + '", "' + sliderLoaderFinishClass + '", ' + new_item + ', "' + HideItemClass + '");', 250);
setTimeout('sliderSwitchSide("' + outerClassName + '", "' + switchClass + '", "' + switchItemClass + '", "' + switchItemActClass + '", "' + switchItemCountClass + '", "' + switchResAct + '", "' + switchResInAct + '", ' + NewNum + ', "' + HideItemClass + '");', 220);
}
}
}
function sliderShowBack(firstNum, lastNum, outerClassName, itemCounterClass, ItemsCount, sliderLoaderBackgroundClass, sliderLoaderProgressClass, mode)
{
switch(mode)
{
case 'right':
for(var i = firstNum; i < lastNum; i++)
{
//alert("." + outerClassName + " ." + itemCounterClass + i + " ." + sliderLoaderBackgroundClass);
$("." + outerClassName + " ." + itemCounterClass + i + " ." + sliderLoaderBackgroundClass).fadeIn(150);
//$("." + outerClassName + " ." + itemCounterClass + i + " ." + sliderLoaderBackgroundClass).fadeIn(700).find(" ." + sliderLoaderProgressClass).css("display", "block");
$("." + outerClassName + " ." + itemCounterClass + parseInt(parseInt(i) + parseInt(ItemsCount)) + " ." + sliderLoaderBackgroundClass).fadeIn(150);
//$("." + outerClassName + " ." + itemCounterClass + parseInt(parseInt(i) + parseInt(ItemsCount)) + " ." + sliderLoaderBackgroundClass).fadeIn(700).find(" ." + sliderLoaderProgressClass).css("display", "block");
}
break;
case 'left':
for(var i = firstNum; i < lastNum; i++)
{
$("." + outerClassName + " ." + itemCounterClass + i + " ." + sliderLoaderBackgroundClass).fadeIn(150);
//$("." + outerClassName + " ." + itemCounterClass + i + " ." + sliderLoaderBackgroundClass).fadeIn(700).find(" ." + sliderLoaderProgressClass).css("display", "block");
$("." + outerClassName + " ." + itemCounterClass + parseInt(parseInt(i) - parseInt(ItemsCount)) + " ." + sliderLoaderBackgroundClass).fadeIn(150);
//$("." + outerClassName + " ." + itemCounterClass + parseInt(parseInt(i) - parseInt(ItemsCount)) + " ." + sliderLoaderBackgroundClass).fadeIn(700).find(" ." + sliderLoaderProgressClass).css("display", "block");
}
break;
default:
var my_c = 0;
for(var i = firstNum; i < lastNum; i++)
{
$("." + outerClassName + " ." + itemCounterClass + i + " ." + sliderLoaderBackgroundClass).fadeIn(150);
//$("." + outerClassName + " ." + itemCounterClass + i + " ." + sliderLoaderBackgroundClass).fadeIn(700).find(" ." + sliderLoaderProgressClass).css("display", "block");
$("." + outerClassName + " ." + itemCounterClass + parseInt(parseInt(mode) + parseInt(my_c)) + " ." + sliderLoaderBackgroundClass).fadeIn(150);
//$("." + outerClassName + " ." + itemCounterClass + parseInt(parseInt(i) - parseInt(ItemsCount)) + " ." + sliderLoaderBackgroundClass).fadeIn(700).find(" ." + sliderLoaderProgressClass).css("display", "block");
my_c++;
}
break;
}
if(mode == 'right')
{
}
else
{
}
}
function sliderChangeItems(firstNum, lastNum, outerClassName, innerClassName, itemCounterClass, ItemsCount, mode, HideItemClass)
{
switch(mode)
{
case 'right':
for(var i = firstNum; i < lastNum; i++)
{
$("." + outerClassName + " ." + innerClassName + "." + itemCounterClass + i).addClass(HideItemClass);
$("." + outerClassName + " ." + innerClassName + "." + itemCounterClass + parseInt(parseInt(i) + parseInt(ItemsCount))).removeClass(HideItemClass);
}
break;
case 'left':
for(var i = firstNum; i < lastNum; i++)
{
$("." + outerClassName + " ." + innerClassName + "." + itemCounterClass + i).addClass(HideItemClass);
$("." + outerClassName + " ." + innerClassName + "." + itemCounterClass + parseInt(parseInt(i) - parseInt(ItemsCount))).removeClass(HideItemClass);
}
break;
default:
//слайдим на конкретный элемент
var my_c = 0;
for(var i = firstNum; i < lastNum; i++)
{
$("." + outerClassName + " ." + innerClassName + "." + itemCounterClass + i).addClass(HideItemClass);
$("." + outerClassName + " ." + innerClassName + "." + itemCounterClass + parseInt(parseInt(my_c) + parseInt(mode))).removeClass(HideItemClass);
my_c++;
}
break;
}
}
function sliderShowFinish(firstNum, lastNum, outerClassName, itemCounterClass, ItemsCount, sliderLoaderProgressClass, sliderLoaderFinishClass, mode)
{
var _firstNum = 0;
var _lastNum = 0;
if(mode == "right")
{
_firstNum = parseInt(firstNum) + parseInt(ItemsCount);
_lastNum = parseInt(lastNum) + parseInt(ItemsCount);
}
else
{
_firstNum = parseInt(firstNum) + parseInt(ItemsCount);
_lastNum = parseInt(lastNum) + parseInt(ItemsCount);
}
for(var i = _firstNum; i < _lastNum; i++)
{
$("." + outerClassName + " ." + itemCounterClass + i + " ." + sliderLoaderProgressClass).css("display", "none");
$("." + outerClassName + " ." + itemCounterClass + i + " ." + sliderLoaderFinishClass).css("display", "block");
}
}
function sliderHideBack(firstNum, lastNum, outerClassName, itemClassName, itemCounterClass, ItemsCount, sliderLoaderBackgroundClass, sliderLoaderFinishClass, mode, HideItemClass)
{
switch(mode)
{
case 'right':
for(var i = firstNum; i < lastNum; i++)
{
//$("." + outerClassName + " ." + itemCounterClass + i + " ." + sliderLoaderBackgroundClass).fadeOut(700).find(" ." + sliderLoaderFinishClass).css("display", "none");
$("." + outerClassName + " ." + itemClassName + "." + itemCounterClass + parseInt(parseInt(i) + parseInt(ItemsCount)) + " ." + sliderLoaderBackgroundClass).fadeOut(200);
//$("." + outerClassName + " ." + itemCounterClass + parseInt(parseInt(i) + parseInt(ItemsCount)) + " ." + sliderLoaderBackgroundClass).fadeOut(700).find(" ." + sliderLoaderFinishClass).css("display", "none");
}
break;
case 'left':
for(var i = firstNum; i < lastNum; i++)
{
//$("." + outerClassName + " ." + itemCounterClass + i + " ." + sliderLoaderBackgroundClass).fadeOut(700).find(" ." + sliderLoaderFinishClass).css("display", "none");
$("." + outerClassName + " ." + itemClassName + "." + itemCounterClass + parseInt(parseInt(i) - parseInt(ItemsCount)) + " ." + sliderLoaderBackgroundClass).fadeOut(200);
//$("." + outerClassName + " ." + itemCounterClass + parseInt(parseInt(i) - parseInt(ItemsCount)) + " ." + sliderLoaderBackgroundClass).fadeOut(700).find(" ." + sliderLoaderFinishClass).css("display", "none");
}
break;
default:
var my_c = 0;
for(var i = 0; i < ItemsCount; i++)
{
//if(switchClass == 'laws_switch_area')
//{
//alert("." + outerClassName + " ." + itemClassName + "." + itemCounterClass + parseInt(parseInt(i) + parseInt(mode)) + " ." + sliderLoaderBackgroundClass);
//}
//$("." + outerClassName + " ." + itemCounterClass + i + " ." + sliderLoaderBackgroundClass).fadeOut(700).find(" ." + sliderLoaderFinishClass).css("display", "none");
if($("." + outerClassName + " ." + itemClassName + "." + itemCounterClass + parseInt(parseInt(i) + parseInt(mode)) + " ." + sliderLoaderBackgroundClass).length > 0)
{
$("." + outerClassName + " ." + itemClassName + "." + itemCounterClass + parseInt(parseInt(i) + parseInt(mode)) + " ." + sliderLoaderBackgroundClass).fadeOut(200);
}
//$("." + outerClassName + " ." + itemCounterClass + parseInt(parseInt(i) - parseInt(ItemsCount)) + " ." + sliderLoaderBackgroundClass).fadeOut(700).find(" ." + sliderLoaderFinishClass).css("display", "none");
my_c++;
}
break;
}
slideBlocker = 0;
}
function sliderCheckSlide(curFirstNum, outerClassName, itemClassName, itemCounterClass, ItemsCount, mode, HideItemClass)
{
switch(mode)
{
case "right":
var cur_find = parseInt(curFirstNum) + parseInt(ItemsCount);
if($("." + outerClassName + " ." + itemClassName + "." + itemCounterClass + cur_find).length)
{//ок - есть хотя бы один элемент
if(slideBlocker == 0)
{
slideBlocker = 1;
return 1;
}
}
else
{
return 0;
}
break;
case "left":
var cur_find = parseInt(curFirstNum) - 1;
if($("." + outerClassName + " ." + itemClassName + "." + itemCounterClass + cur_find).length)
{//ок - есть хотя бы один элемент
if(slideBlocker == 0)
{
slideBlocker = 1;
return 1;
}
}
else
{
return 0;
}
break;
default:
// if(switchClass = 'laws_switch_area')
// {
// alert("." + outerClassName + " ." + itemClassName + "." + itemCounterClass + mode);
// }
if($("." + outerClassName + " ." + itemClassName + "." + itemCounterClass + mode).length)
{//ок - есть хотя бы один элемент и если он уже неактивен
if(slideBlocker == 0 && $("." + outerClassName + " ." + itemClassName + "." + itemCounterClass + mode).hasClass(HideItemClass))
{
slideBlocker = 1;
return 1;
}
}
else
{
return 0;
}
break;
}
if(mode == "right")
{
}
else
{
}
return 0;
}
function sliderSwitchSide(outerClassName, switchClass, switchItemClass, switchItemActClass, switchItemCountClass, switchResAct, switchResInAct, mode, HideItemClass)
{
var curNum = $("." + switchClass + " ." + switchItemClass + "." + switchItemActClass).attr("class").replace(/[a-zA-Z _]/g, "");
if(curNum == "")
curNum = 1;
switch(mode)
{
case 'right':
var nextNum = parseInt(curNum) + 1;
$("." + switchClass + " ." + switchItemClass + "." + switchItemCountClass + curNum).attr("src", switchResInAct).removeClass(switchItemActClass);
$("." + switchClass + " ." + switchItemClass + "." + switchItemCountClass + nextNum).attr("src", switchResAct).addClass(switchItemActClass);
break;
case 'left':
var nextNum = parseInt(curNum) - 1;
$("." + switchClass + " ." + switchItemClass + "." + switchItemCountClass + curNum).attr("src", switchResInAct).removeClass(switchItemActClass);
$("." + switchClass + " ." + switchItemClass + "." + switchItemCountClass + nextNum).attr("src", switchResAct).addClass(switchItemActClass);
break;
default:
$("." + switchClass + " ." + switchItemClass + "." + switchItemCountClass + curNum).attr("src", switchResInAct).removeClass(switchItemActClass);
$("." + switchClass + " ." + switchItemClass + "." + switchItemCountClass + mode).attr("src", switchResAct).addClass(switchItemActClass);
break;
}
}
|
module.exports = function(grunt) {
"use strict";
grunt.initConfig({
pkg: grunt.file.readJSON("package.json"),
meta: {
banner: "/*\n" +
" * <%= pkg.title || pkg.name %> - v<%= pkg.version %>\n" +
" * <%= pkg.description %>\n" +
" * <%= pkg.homepage %>\n" +
" *\n" +
" * Made by <%= pkg.author.name %>\n" +
" * Under <%= pkg.license %> License\n" +
" */\n"
},
jshint: {
all: ["Gruntfile.js", "src/**/*.js", "test/**/*.js", "!test/util.js"],
options: {
jshintrc: true
}
},
concat: {
dist: {
src: ["src/jquery.maskMoney.js"],
dest: "dist/jquery.maskMoney.js"
},
options: {
banner: "<%= meta.banner %>"
}
},
uglify: {
options: {
banner: "<%= meta.banner %>",
mangle: {
reserved: ["jQuery", "$"]
}
},
build: {
files: [
{ src: "src/jquery.maskMoney.js", dest: "dist/jquery.maskMoney.min.js" },
]
}
},
qunit: {
all: ["test/*.html"]
},
jquerymanifest: {
options: {
source: grunt.file.readJSON("package.json"),
overrides: {
"name": "maskMoney",
"title": "jQuery maskMoney",
"download": "https://raw.github.com/plentz/jquery-maskmoney/master/dist/jquery.maskMoney.min.js",
"docs": "http://github.com/plentz/jquery-maskmoney",
"demo": "http://plentz.github.com/jquery-maskmoney",
"keywords": ["form", "input", "mask", "money"]
}
}
},
watch: {
files: ["test/*.html", "test/*.js", "src/*.js"],
tasks: ["jshint", "qunit"]
}
});
grunt.loadNpmTasks("grunt-contrib-concat");
grunt.loadNpmTasks("grunt-contrib-jshint");
grunt.loadNpmTasks("grunt-contrib-uglify");
grunt.loadNpmTasks("grunt-jquerymanifest");
grunt.loadNpmTasks("grunt-contrib-qunit");
grunt.loadNpmTasks("grunt-contrib-watch");
grunt.registerTask("test", ["jshint", "qunit"]);
grunt.registerTask("default", ["jshint", "qunit", "concat", "uglify", "jquerymanifest"]);
};
|
/*
* Wegas
* http://wegas.albasim.ch
*
* Copyright (c) 2013-2020 School of Management and Engineering Vaud, Comem, MEI
* Licensed under the MIT License
*/
/**
* @fileoverview
* @author Jarle Hulaas
*/
/*global Variable, gameModel, self */
YUI.add("wegas-i18n-survey-en", function(Y) {
Y.Wegas.I18n.register("wegas-i18n-survey", "en", {
survey: {
global: {
next: "Next",
back: "Back",
validate: "Submit",
close: "Close this survey",
confirmation: "Once submitted,<br>your replies will be final!<br> Do you really want to submit them ?",
save: "Save",
unavailableValue: "(Anonymous reply)",
statusSaving: "Saving...",
statusSaved: "Saved",
replyCompulsory: "(compulsory reply)",
replyOptional: "(optional reply)"
},
errors: {
incomplete: "Some questions have not been replied yet.<br>Please resume from question<br>{{question}}",
returnToQuestion: "Return to this question",
empty: "This survey contains no questions.",
outOfBounds: "This question expects a number between {{min}} and {{max}}.",
notGreaterThanMin: "This question expects a number greater than or equal to {{min}}.",
notLessThanMax: "This question expects a number less than or equal to {{max}}."
},
orchestrator: {
globalTitle: "Survey orchestration",
searchExternalSurveys: "Find all surveys",
standardSurveysTitle: "Standard Surveys",
externalSurveysTitle: "Your own surveys",
activeSurveysTitle: "Active surveys",
noSurveyFound: "No surveys found",
lastModifiedOn: "last modified on",
sessionOfScenario: "session of scenario",
scenario: "scenario",
doImport: "Import selected surveys",
importing: "Importing surveys",
importTerminated: "Overview of imported surveys",
hasPlayerScope: "This survey is to be answered individually by each player",
hasTeamScope: "This survey is to be answered teamwise",
currentStatus: "Status",
inactive: "Empty or inactive",
inviting: "Invitations sent",
notStarted: "Not yet started",
requested: "Start requested",
ongoing: "Ongoing",
completed: "Completed",
closed: "Closed",
editButton: "Edit",
previewButton: "Preview",
copyButton: "Copy",
requestButton: "Launch",
inviteButton: "Invite",
deleteButton: "Delete",
renameButton: "Rename (via edit)",
shareButton: "Share",
scopeTitle: "Players shall answer:",
playerScopeButton: "Individually",
teamScopeButton: "Teamwise",
progressDetailsButton: "Details",
teamOrPlayer: "Team/Player",
team: "Team",
player: "Player",
teamStatus: "Status",
teamRepliesCompulsory: "Compulsory Replies",
teamRepliesOptional: "Optional Replies",
alreadyLaunched: "This survey is already launched",
deleteRunning: "This survey is already running.<br>Really delete it?",
modifyRunning: "This survey is running and cannot be modified now.",
surveyCancelled: "The survey is cancelled.",
surveyLaunched: "The survey has been started successfully.",
scenarioCreated: "This survey is now available for sharing in game scenario<br>\"{{name}}\".<br>Please refresh the browser tab containing your current scenarios.",
sessionCreated: "This survey is now available for sharing in game session<br>\"{{name}}\".<br>Please refresh the browser tab containing your current sessions.",
invitePanel: {
invitePanelTitle: "Invite to",
currentPlayers: "Current number of players who joined the game",
inviteTitle: "Send invitations:",
inviteLiveChoice: "<b>Option A</b><br>To players who already joined the game",
inviteListChoice: "<b>Option B</b><br>To an email list<br>(anonymous replies)",
inviteLiveAndListChoice: "<b>Option C</b><br>Combine (A) with (B) to reach everyone optimally",
inviteLiveTitle: "Player replies shall be:",
inviteLiveAnonChoice: "Anonymous",
inviteLiveLinkedChoice: "Linked to their accounts",
sendButton: "Send invitations",
liveRecipients: "Emails of current players",
liveRecipientsAutomatic: "(updated automatically)",
listRecipients: "Emails of all course participants",
countEmails: "Count: ",
cleanupButton: "Remove duplicates",
cleanupMessage: "Removed {{number}} duplicates from your list",
validationMessage: "Found {{number}} valid emails in your list",
senderName: "Your sender name",
subject: "Subject",
body: "Message",
surveyInvitedFromLive: "Invitations have been sent to {{number}} current players.",
surveyInvitedFromList: "Invitations have been sent to {{number}} guests from your mailing list.",
defaultMailBody: "Hi {\\{player}\\},<br>As a participant in the software simulation \"{{game}}\", you are cordially invited to complete an online survey.<br>Please click here to start: {\\{link}\\}<br>Thank you!",
defaultMailSubject: "[Albasim Wegas] Survey"
},
errors: {
inviteNoEmails: "Currently no players have joined the game<br>(or they have no registered email address)",
nameTaken: "a variable in this game already has the same internal name \"{{name}}\"",
noLogId: "No \"Log ID\" has been set for this session.<br>Replies to the survey will not be saved!<br>Please contact the platform administrator (AlbaSim).",
invalidEmail: "Invalid email address: {{email}}<br>Please correct and try again.",
noValidPlayers: "No players have joined the game yet",
noValidEmails: "Please enter at least one recipient email address.",
noValidSender: "Please enter your name (not your email address)",
noValidSubject: "Please enter the subject of the message",
noValidBody: "The body of the message cannot be empty",
noLinkInBody: "The body of the message must contain the code <b>{\\{link}\\}</b> which will automatically be replaced by the real URL address of the survey",
noPlayerInBody: "The body of the message must contain the code <b>{\\{player}\\}</b> which will automatically be replaced by the real name or email of the participant"
}
}
}
});
});
|
"use strict";
////////////////////////////////////////////////////////////////////////////////
// 検索
////////////////////////////////////////////////////////////////////////////////
Contents.searchbox = function( cp )
{
var p = $( '#' + cp.id );
var cont = p.find( 'div.contents' );
cp.SetIcon( 'icon-search' );
////////////////////////////////////////////////////////////
// 開始処理
////////////////////////////////////////////////////////////
this.start = function() {
cont.addClass( 'searchbox' )
.html( OutputTPL( 'searchbox', {} ) );
cp.SetTitle( i18nGetMessage( 'i18n_0206' ), false );
$( '#searchbox_box' ).find( '.btn' ).addClass( 'disabled' );
////////////////////////////////////////
// リサイズ処理
////////////////////////////////////////
cont.on( 'contents_resize', function() {
$( '#searchbox_result' ).height( cont.outerHeight() - $( '#searchbox_box' ).outerHeight() - cont.find( '.account_select' ).outerHeight() );
} );
cont.trigger( 'contents_resize' );
////////////////////////////////////////
// アカウント選択変更
////////////////////////////////////////
cont.on( 'account_changed', function() {
$( '#searchbox_result > .users_list' ).html( '' );
$( '#searchbox_result > .hashtags_list' ).html( '' );
} );
////////////////////////////////////////
// アカウント情報更新
////////////////////////////////////////
cont.on( 'account_update', function() {
// アカウントが0件の場合はパネルを閉じる
if ( AccountCount() == 0 )
{
// 検索パネルを閉じる
p.find( '.close' ).trigger( 'click', [false] );
return;
}
else
{
AccountSelectMake( cp );
cont.trigger( 'account_changed' );
}
} );
cont.trigger( 'account_update' );
////////////////////////////////////////
// 検索ボタンクリック処理
////////////////////////////////////////
$( '#search' ).click( function( e ) {
// disabledなら処理しない
if ( $( this ).hasClass( 'disabled' ) )
{
return;
}
Loading( true, 'search' );
SendRequest(
{
method: 'GET',
action: 'api_call',
instance: g_cmn.account[cp.param.account_id].instance,
access_token: g_cmn.account[cp.param.account_id].access_token,
api: 'search',
param: {
q: $( '#searchbox_text' ).val(),
}
},
function( res )
{
if ( res.status === undefined )
{
var items = [];
for ( var i = 0 ; i < res.accounts.length ; i++ )
{
var instance = GetInstanceFromAcct( res.accounts[i].acct, g_cmn.account[cp.param.account_id].instance );
items.push( {
avatar: ImageURLConvert( res.accounts[i].avatar, res.accounts[i].acct, g_cmn.account[cp.param.account_id].instance ),
display_name_disp: ConvertDisplayName( res.accounts[i].display_name, res.accounts[i].username ),
display_name: res.accounts[i].display_name,
username: res.accounts[i].username,
instance: instance,
id: res.accounts[i].id,
statuses_count: NumFormat( res.accounts[i].statuses_count ),
following_count: NumFormat( res.accounts[i].following_count ),
followers_count: NumFormat( res.accounts[i].followers_count ),
created_at: res.accounts[i].created_at,
users_type: 'search',
} );
}
$( '#searchbox_result .users_list' ).html( OutputTPL( 'users_list', { items: items } ) );
for ( var i = 0, items = [] ; i < res.hashtags.length ; i++ )
{
items.push( {
hashtag: res.hashtags[i]
} );
}
$( '#searchbox_result .hashtags_list' ).html( OutputTPL( 'hashtags_list', { items: items } ) );
var _p = p.outerHeight();
var _h = p.find( '.titlebar' ).outerHeight() + p.find( '.account_select' ).outerHeight() +
cont.find( '#searchbox_box' ).outerHeight() + $( '#searchbox_result .users_list' ).outerHeight() +
$( '#searchbox_result .hashtags_list' ).outerHeight() + parseInt( p.css( 'border-top-width' ) ) * 2;
p.css( { height: Math.min( _h, $( window ).height() * 0.75 ) } );
cont.css( { height: cont.outerHeight() + p.outerHeight() - _p } );
cont.trigger( 'contents_resize' );
}
else
{
ApiError( res );
}
Loading( false, 'search' );
}
);
e.stopPropagation();
} );
////////////////////////////////////////
// 入力文字数によるボタン制御
////////////////////////////////////////
$( '#searchbox_text' ).on( 'keyup change', function() {
var slen = $( this ).val().length;
if ( slen > 0 )
{
$( '#searchbox_box' ).find( '.btn' ).removeClass( 'disabled' );
}
else
{
$( '#searchbox_box' ).find( '.btn' ).addClass( 'disabled' );
}
} );
$( '#searchbox_text' ).focus();
////////////////////////////////////////
// Enterで検索実行
////////////////////////////////////////
$( '#searchbox_text' ).keypress( function( e ) {
if ( e.keyCode == 13 )
{
$( '#search' ).trigger( 'click' );
}
} );
////////////////////////////////////////
// ユーザ名クリック
////////////////////////////////////////
cont.find( '.users_list' ).on( 'click', '> div.item .display_name, > div.item .username', function( e ) {
var item = $( this ).closest( '.item' );
OpenUserTimeline( cp.param.account_id, item.attr( 'id' ), item.attr( 'username' ),
item.attr( 'display_name' ), item.attr( 'instance' ) );
e.stopPropagation();
} );
////////////////////////////////////////
// アイコンクリック
////////////////////////////////////////
cont.find( '.users_list' ).on( 'click', '> div.item .avatar', function( e ) {
var item = $( this ).closest( '.item' );
OpenUserProfile( item.attr( 'id' ), item.attr( 'instance' ), cp.param.account_id );
e.stopPropagation();
} );
////////////////////////////////////////
// ハッシュタグクリック
////////////////////////////////////////
cont.find( '.hashtags_list' ).on( 'click', '> div.item .hashtag', function( e ) {
OpenHashtagTimeline( cp.param.account_id, $( this ).find( '> span' ).text() );
e.stopPropagation();
} );
////////////////////////////////////////
// アイコンにカーソルを乗せたとき
////////////////////////////////////////
cont.find( '.users_list' ).on( 'mouseenter mouseleave', '> div.item div.avatar > img', function( e ) {
if ( e.type == 'mouseenter' )
{
// Draggableの設定をする
if ( !$( this ).hasClass( 'ui-draggable' ) )
{
SetDraggable( $( this ), p, cp );
}
}
else
{
$( '#tooltip' ).hide();
}
} );
};
////////////////////////////////////////////////////////////
// 終了処理
////////////////////////////////////////////////////////////
this.stop = function() {
};
}
|
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _immutable = require('immutable');
var _immutable2 = _interopRequireDefault(_immutable);
var _action = require('./action');
var _action2 = _interopRequireDefault(_action);
var _rx = require('rx');
var _rx2 = _interopRequireDefault(_rx);
var Core = (function () {
function Core() {
var config = arguments[0] === undefined ? {} : arguments[0];
_classCallCheck(this, Core);
this._state = _immutable2['default'].Map({});
this._stores = _immutable2['default'].Map({});
this._actions = _immutable2['default'].Map({});
if (config.actions) this.createActions.apply(this, _toConsumableArray(config.actions));
if (config.stores) this.createStores(config.stores);
}
_createClass(Core, [{
key: 'createActions',
value: function createActions() {
for (var _len = arguments.length, actionNames = Array(_len), _key = 0; _key < _len; _key++) {
actionNames[_key] = arguments[_key];
}
var newActions = _immutable2['default'].Map({});
actionNames.forEach(function (name) {
return newActions = newActions.set(name, new _action2['default']());
});
this._actions = newActions.merge(this._actions);
return this._actions.toObject();
}
}, {
key: 'createStores',
value: function createStores(storeMap) {
var _this = this;
var keys = Object.keys(storeMap);
var newStores = _immutable2['default'].Map({});
keys.forEach(function (key) {
var StoreDef = storeMap[key];
var initStore = new StoreDef(key, _this);
newStores = newStores.set(key, initStore);
_this._updateState(key, initStore.getInitialState());
initStore.observable.subscribe(function (updatedState) {
return _this._updateState(key, updatedState);
});
});
this._stores = this._stores.merge(newStores);
}
}, {
key: 'actions',
get: function () {
return this._actions.toObject();
}
}, {
key: 'stores',
get: function () {
return this._stores.toObject();
}
}, {
key: 'get',
value: function get(keyPath) {
var val = Array.isArray(keyPath) ? this._state.getIn(keyPath) : this._state.get(keyPath);
return _immutable2['default'].Iterable.isIterable(val) ? val.toJS() : val;
}
}, {
key: 'combineStores',
value: function combineStores() {
var _this2 = this;
var _Rx$Observable;
for (var _len2 = arguments.length, stores = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
stores[_key2] = arguments[_key2];
}
return (_Rx$Observable = _rx2['default'].Observable).merge.apply(_Rx$Observable, _toConsumableArray(this._getObservables('_stores', stores))).map(function () {
return stores.map(function (name) {
return _this2.get(name);
});
});
}
}, {
key: 'waitForStores',
value: function waitForStores() {
for (var _len3 = arguments.length, stores = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
stores[_key3] = arguments[_key3];
}
return this._waitFor('_stores', stores);
}
}, {
key: 'waitForActions',
value: function waitForActions() {
for (var _len4 = arguments.length, actions = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
actions[_key4] = arguments[_key4];
}
return this._waitFor('_actions', actions);
}
}, {
key: 'takeSnapshot',
value: function takeSnapshot() {
return this._state.toJS();
}
}, {
key: 'restore',
value: function restore(state) {
var _this3 = this;
var storeKeys = Object.keys(state);
storeKeys.forEach(function (key) {
_this3._stores.get(key).replaceState(state[key]);
});
}
}, {
key: '_waitFor',
value: function _waitFor(type, keys) {
var _this4 = this;
return _rx2['default'].Observable.just().flatMap(function () {
var _Rx$Observable2;
return (_Rx$Observable2 = _rx2['default'].Observable).zipArray.apply(_Rx$Observable2, _toConsumableArray(_this4._getObservables(type, keys)));
});
}
}, {
key: '_getObservables',
value: function _getObservables(type, keys) {
var _this5 = this;
var storeKeys = Array.isArray(keys) ? keys : [keys];
return storeKeys.map(function (name) {
return _this5[type].get(name).observable;
});
}
}, {
key: '_updateState',
value: function _updateState(name, data) {
this._state = this._state.set(name, _immutable2['default'].fromJS(data));
}
}]);
return Core;
})();
exports['default'] = Core;
module.exports = exports['default'];
|
import jwt from 'jsonwebtoken'
import {COOKIE_NAMES} from '../../config/const'
export function loadUser (secret) {
return function (req, res, next) {
const userCookie = req.cookies[COOKIE_NAMES.auth]
req.user = null
if (userCookie) {
// verifies secret and checks exp
jwt.verify(userCookie, secret, function (err, decoded) {
if (err) {
req.user = null
} else {
req.user = decoded
}
})
}
next()
}
}
export function requiresRole(role, forWriteOnly = true) {
return function (req, res, next) {
if (req.method !== 'GET' || !forWriteOnly) {
if (req.user.roles.indexOf(role) === -1) return next({httpStatus: 403, message: 'Access denied'})
}
next()
}
}
export function mustBeAuthenticated (req, res, next) {
if (req.baseUrl === '/authenticate') return next()
if (!req.user) return next({httpStatus: 401, message: 'Not authenticated'})
next()
}
|
define(function () {
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
var CryptoJS = CryptoJS || function (e, m) {
var p = {}, j = p.lib = {}, l = function () { }, f = j.Base = { extend: function (a) { l.prototype = this; var c = new l; a && c.mixIn(a); c.hasOwnProperty("init") || (c.init = function () { c.$super.init.apply(this, arguments) }); c.init.prototype = c; c.$super = this; return c }, create: function () { var a = this.extend(); a.init.apply(a, arguments); return a }, init: function () { }, mixIn: function (a) { for (var c in a) a.hasOwnProperty(c) && (this[c] = a[c]); a.hasOwnProperty("toString") && (this.toString = a.toString) }, clone: function () { return this.init.prototype.extend(this) } },
n = j.WordArray = f.extend({
init: function (a, c) { a = this.words = a || []; this.sigBytes = c != m ? c : 4 * a.length }, toString: function (a) { return (a || h).stringify(this) }, concat: function (a) { var c = this.words, q = a.words, d = this.sigBytes; a = a.sigBytes; this.clamp(); if (d % 4) for (var b = 0; b < a; b++) c[d + b >>> 2] |= (q[b >>> 2] >>> 24 - 8 * (b % 4) & 255) << 24 - 8 * ((d + b) % 4); else if (65535 < q.length) for (b = 0; b < a; b += 4) c[d + b >>> 2] = q[b >>> 2]; else c.push.apply(c, q); this.sigBytes += a; return this }, clamp: function () {
var a = this.words, c = this.sigBytes; a[c >>> 2] &= 4294967295 <<
32 - 8 * (c % 4); a.length = e.ceil(c / 4)
}, clone: function () { var a = f.clone.call(this); a.words = this.words.slice(0); return a }, random: function (a) { for (var c = [], b = 0; b < a; b += 4) c.push(4294967296 * e.random() | 0); return new n.init(c, a) }
}), b = p.enc = {}, h = b.Hex = {
stringify: function (a) { var c = a.words; a = a.sigBytes; for (var b = [], d = 0; d < a; d++) { var f = c[d >>> 2] >>> 24 - 8 * (d % 4) & 255; b.push((f >>> 4).toString(16)); b.push((f & 15).toString(16)) } return b.join("") }, parse: function (a) {
for (var c = a.length, b = [], d = 0; d < c; d += 2) b[d >>> 3] |= parseInt(a.substr(d,
2), 16) << 24 - 4 * (d % 8); return new n.init(b, c / 2)
}
}, g = b.Latin1 = { stringify: function (a) { var c = a.words; a = a.sigBytes; for (var b = [], d = 0; d < a; d++) b.push(String.fromCharCode(c[d >>> 2] >>> 24 - 8 * (d % 4) & 255)); return b.join("") }, parse: function (a) { for (var c = a.length, b = [], d = 0; d < c; d++) b[d >>> 2] |= (a.charCodeAt(d) & 255) << 24 - 8 * (d % 4); return new n.init(b, c) } }, r = b.Utf8 = { stringify: function (a) { try { return decodeURIComponent(escape(g.stringify(a))) } catch (c) { throw Error("Malformed UTF-8 data"); } }, parse: function (a) { return g.parse(unescape(encodeURIComponent(a))) } },
k = j.BufferedBlockAlgorithm = f.extend({
reset: function () { this._data = new n.init; this._nDataBytes = 0 }, _append: function (a) { "string" == typeof a && (a = r.parse(a)); this._data.concat(a); this._nDataBytes += a.sigBytes }, _process: function (a) { var c = this._data, b = c.words, d = c.sigBytes, f = this.blockSize, h = d / (4 * f), h = a ? e.ceil(h) : e.max((h | 0) - this._minBufferSize, 0); a = h * f; d = e.min(4 * a, d); if (a) { for (var g = 0; g < a; g += f) this._doProcessBlock(b, g); g = b.splice(0, a); c.sigBytes -= d } return new n.init(g, d) }, clone: function () {
var a = f.clone.call(this);
a._data = this._data.clone(); return a
}, _minBufferSize: 0
}); j.Hasher = k.extend({
cfg: f.extend(), init: function (a) { this.cfg = this.cfg.extend(a); this.reset() }, reset: function () { k.reset.call(this); this._doReset() }, update: function (a) { this._append(a); this._process(); return this }, finalize: function (a) { a && this._append(a); return this._doFinalize() }, blockSize: 16, _createHelper: function (a) { return function (c, b) { return (new a.init(b)).finalize(c) } }, _createHmacHelper: function (a) {
return function (b, f) {
return (new s.HMAC.init(a,
f)).finalize(b)
}
}
}); var s = p.algo = {}; return p
}(Math);
(function () {
var e = CryptoJS, m = e.lib, p = m.WordArray, j = m.Hasher, l = [], m = e.algo.SHA1 = j.extend({
_doReset: function () { this._hash = new p.init([1732584193, 4023233417, 2562383102, 271733878, 3285377520]) }, _doProcessBlock: function (f, n) {
for (var b = this._hash.words, h = b[0], g = b[1], e = b[2], k = b[3], j = b[4], a = 0; 80 > a; a++) {
if (16 > a) l[a] = f[n + a] | 0; else { var c = l[a - 3] ^ l[a - 8] ^ l[a - 14] ^ l[a - 16]; l[a] = c << 1 | c >>> 31 } c = (h << 5 | h >>> 27) + j + l[a]; c = 20 > a ? c + ((g & e | ~g & k) + 1518500249) : 40 > a ? c + ((g ^ e ^ k) + 1859775393) : 60 > a ? c + ((g & e | g & k | e & k) - 1894007588) : c + ((g ^ e ^
k) - 899497514); j = k; k = e; e = g << 30 | g >>> 2; g = h; h = c
} b[0] = b[0] + h | 0; b[1] = b[1] + g | 0; b[2] = b[2] + e | 0; b[3] = b[3] + k | 0; b[4] = b[4] + j | 0
}, _doFinalize: function () { var f = this._data, e = f.words, b = 8 * this._nDataBytes, h = 8 * f.sigBytes; e[h >>> 5] |= 128 << 24 - h % 32; e[(h + 64 >>> 9 << 4) + 14] = Math.floor(b / 4294967296); e[(h + 64 >>> 9 << 4) + 15] = b; f.sigBytes = 4 * e.length; this._process(); return this._hash }, clone: function () { var e = j.clone.call(this); e._hash = this._hash.clone(); return e }
}); e.SHA1 = j._createHelper(m); e.HmacSHA1 = j._createHmacHelper(m)
})();
return CryptoJS;
});
|
const maxApi = require('max-api');
const io = require('socket.io-client');
let socket;
maxApi.addHandler('connect', (url) => {
socket = io(url);
socket.on('message', (msg) => {
maxApi.outlet("message", msg);
});
});
maxApi.addHandler('disconnect', () => {
socket.close();
});
maxApi.addHandler('message', (msg) => {
console.log(msg)
socket.emit('message', msg);
});
|
export const boldDown = {"viewBox":"0 0 20 20","children":[{"name":"path","attribs":{"d":"M2.5,10H6V3h8v7h3.5L10,17.5L2.5,10z"}}]};
|
function empty (value) {
return typeof value === 'undefined' || !(value);
}
exports.empty = empty;
function nonEmpty (value) {
return !empty(value);
}
exports.nonEmpty = nonEmpty;
// min and max included in the integer distribution
function randomInteger (min, max) {
return Math.floor(Math.random() * ((max + 1) - min)) + min;
}
exports.randomInteger = randomInteger;
|
const {
parentPort,
workerData
} = require('worker_threads');
parentPort.on('message', message => {
let args = Object.keys(message).filter(function (key) {
return key.match(/^argument/);
}).sort(function (a, b) {
return parseInt(a.slice(8), 10) - parseInt(b.slice(8), 10);
}).map(function (key) {
return message[key];
});
try {
let result = eval('(' + message.func + ')').apply(null, args);
if (typeof Promise != 'undefined' && result instanceof Promise) {
result.then(function (result) {
parentPort.postMessage({
id: message.id,
result: result
});
}).catch(function (error) {
parentPort.postMessage({
id: message.id,
error: error.stack
});
});
} else {
parentPort.postMessage({
id: message.id,
result: result
});
}
} catch (error) {
parentPort.postMessage({
id: message.id,
error: error.stack
});
}
});
|
const router = require('express').Router() // eslint-disable-line new-cap
const log = require('winston')
const debug = require('debug')('streamInfo:routes:webhooks')
const request = require('snekfetch')
const config = require('../config')
const twitchAPI = require('../bin/twitchAPI')
const moment = require('moment')
const lastHooks = {
following: [],
}
router.get('/twitch/following', (req, res, next) => {
// eslint-disable-line no-unused-vars
debug('Confirmation of follow webhook subscription.')
res.send(req.query['hub.challenge'])
})
router.post('/twitch/following', async (req, res, next) => {
// eslint-disable-line no-unused-vars
debug('New Follow event via webhook from Twitch')
// return 200 OK to twitch immediately
res.sendStatus(200)
// stop if not a validated request using the secret
if (!req.verified) return
// extract the data object from the request body
const data = req.body.data[0]
// stop if no data (shouldn't be a thing)
if (!data) return
// ensure no duplicates
if (lastHooks.following.indexOf(data.from_id) !== -1) return
lastHooks.following.push(data.from_id)
if (lastHooks.length > 20) lastHooks.shift()
debug(JSON.stringify(data, null, 2))
// emit that we got a new follower to the client page
req.io.emit('following', data)
// check for suspicious terms in the user name
const terms = await req.db.SuspiciousTerms.find()
const match = terms.filter((term) =>
data.from_name.toLowerCase().includes(term.term)
)
// const query = `{"$where": "function() { return '${data.from_name.toLowerCase()}'.includes(this.term) }"}`
// const match = await req.db.SuspiciousTerms.findOne(JSON.parse(query))
// stop if no matching terms
if (!match || match.length === 0) return
// check the account creation date of the user
const userData = await twitchAPI.getUserByIdKraken(data.from_id)
if (!userData) return
// extract the created_at timestamp
const creationDate = userData.body.created_at
if (!creationDate) return
const thresholdDate = moment.utc(creationDate).add(1, 'month')
// stop if now is after the set threshold
// ie the account is older than 1 month
if (moment().isAfter(thresholdDate)) return
// send webhook to #mod-chat in discord @ing the moderators role
request
.post(config.discord.susFollowerWebhookUrl)
.send({
content: `@here \`\`${data.from_name}\`\` <https://www.twitch.tv/popout/annemunition/viewercard/${data.from_name}>`,
})
.catch((err) => {
debug('Error sending a SUSPICIOUS FOLLOWER DETECTED Webhook to Discord')
log.error(err)
})
})
module.exports = router
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import invariant from '../jsutils/invariant';
import type { GraphQLError } from './GraphQLError';
import type { SourceLocation } from '../language/location';
/**
* Given a GraphQLError, format it according to the rules described by the
* Response Format, Errors section of the GraphQL Specification.
*/
export function formatError(error: GraphQLError): GraphQLFormattedError {
invariant(error, 'Received null or undefined error.');
return {
...error.extensions,
message: error.message || 'An unknown error occurred.',
locations: error.locations,
path: error.path,
};
}
export type GraphQLFormattedError = {
+message: string,
+locations: $ReadOnlyArray<SourceLocation> | void,
+path: $ReadOnlyArray<string | number> | void,
// Extensions
+[key: string]: mixed,
};
|
export const basic_paperplane = {"viewBox":"0 0 64 64","children":[{"name":"polygon","attribs":{"fill":"none","stroke":"#000000","stroke-width":"2","stroke-linejoin":"bevel","stroke-miterlimit":"10","points":"1,30 63,1 23,41 \r\n\t"},"children":[]},{"name":"polygon","attribs":{"fill":"none","stroke":"#000000","stroke-width":"2","stroke-linejoin":"bevel","stroke-miterlimit":"10","points":"34,63 63,1 23,41 \r\n\t"},"children":[]}]};
|
'use strict';
/*
* Do not edit the parser directly. This is a generated file created using a
* build script and the PEG grammar.
*/
module.exports = (function() {
/*
* Generated by PEG.js 0.8.0.
*
* http://pegjs.majda.cz/
*/
function peg$subclass(child, parent) {
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor();
}
function SyntaxError(message, expected, found, offset, line, column) {
this.message = message;
this.expected = expected;
this.found = found;
this.offset = offset;
this.line = line;
this.column = column;
this.name = "SyntaxError";
}
peg$subclass(SyntaxError, Error);
function parse(input) {
var options = arguments.length > 1 ? arguments[1] : {},
peg$FAILED = {},
peg$startRuleFunctions = { start: peg$parsestart },
peg$startRuleFunction = peg$parsestart,
peg$c0 = [],
peg$c1 = function(p) {
return ["body"]
.concat(p)
.concat([['line', line()], ['col', column()]]);
},
peg$c2 = { type: "other", description: "section" },
peg$c3 = peg$FAILED,
peg$c4 = null,
peg$c5 = function(t, b, e, n) {
if( (!n) || (t[1].text !== n.text) ) {
error("Expected end tag for "+t[1].text+" but it was not found.");
}
return true;
},
peg$c6 = void 0,
peg$c7 = function(t, b, e, n) {
e.push(["param", ["literal", "block"], b]);
t.push(e);
return t.concat([['line', line()], ['col', column()]]);
},
peg$c8 = "/",
peg$c9 = { type: "literal", value: "/", description: "\"/\"" },
peg$c10 = function(t) {
t.push(["bodies"]);
return t.concat([['line', line()], ['col', column()]]);
},
peg$c11 = /^[#?\^<+@]/,
peg$c12 = { type: "class", value: "[#?\\^<+@]", description: "[#?\\^<+@]" },
peg$c13 = function(t, n, c, p) { return [t, n, c, p] },
peg$c14 = { type: "other", description: "end tag" },
peg$c15 = function(n) { return n },
peg$c16 = ":",
peg$c17 = { type: "literal", value: ":", description: "\":\"" },
peg$c18 = function(n) {return n},
peg$c19 = function(n) { return n ? ["context", n] : ["context"] },
peg$c20 = { type: "other", description: "params" },
peg$c21 = "=",
peg$c22 = { type: "literal", value: "=", description: "\"=\"" },
peg$c23 = function(k, v) {return ["param", ["literal", k], v]},
peg$c24 = function(p) { return ["params"].concat(p) },
peg$c25 = { type: "other", description: "bodies" },
peg$c26 = function(p) { return ["bodies"].concat(p) },
peg$c27 = { type: "other", description: "reference" },
peg$c28 = function(n, f) { return ["reference", n, f].concat([['line', line()], ['col', column()]]) },
peg$c29 = { type: "other", description: "partial" },
peg$c30 = ">",
peg$c31 = { type: "literal", value: ">", description: "\">\"" },
peg$c32 = "+",
peg$c33 = { type: "literal", value: "+", description: "\"+\"" },
peg$c34 = function(k) {return ["literal", k]},
peg$c35 = function(s, n, c, p) {
var key = (s === ">") ? "partial" : s;
return [key, n, c, p].concat([['line', line()], ['col', column()]]);
},
peg$c36 = { type: "other", description: "filters" },
peg$c37 = "|",
peg$c38 = { type: "literal", value: "|", description: "\"|\"" },
peg$c39 = function(f) { return ["filters"].concat(f) },
peg$c40 = { type: "other", description: "special" },
peg$c41 = "~",
peg$c42 = { type: "literal", value: "~", description: "\"~\"" },
peg$c43 = function(k) { return ["special", k].concat([['line', line()], ['col', column()]]) },
peg$c44 = { type: "other", description: "identifier" },
peg$c45 = function(p) { var arr = ["path"].concat(p); arr.text = p[1].join('.'); return arr; },
peg$c46 = function(k) { var arr = ["key", k]; arr.text = k; return arr; },
peg$c47 = { type: "other", description: "number" },
peg$c48 = function(n) { return ['literal', n]; },
peg$c49 = { type: "other", description: "float" },
peg$c50 = ".",
peg$c51 = { type: "literal", value: ".", description: "\".\"" },
peg$c52 = function(l, r) { return parseFloat(l + "." + r.join('')); },
peg$c53 = { type: "other", description: "integer" },
peg$c54 = /^[0-9]/,
peg$c55 = { type: "class", value: "[0-9]", description: "[0-9]" },
peg$c56 = function(digits) { return parseInt(digits.join(""), 10); },
peg$c57 = { type: "other", description: "path" },
peg$c58 = function(k, d) {
d = d[0];
if (k && d) {
d.unshift(k);
return [false, d].concat([['line', line()], ['col', column()]]);
}
return [true, d].concat([['line', line()], ['col', column()]]);
},
peg$c59 = function(d) {
if (d.length > 0) {
return [true, d[0]].concat([['line', line()], ['col', column()]]);
}
return [true, []].concat([['line', line()], ['col', column()]]);
},
peg$c60 = { type: "other", description: "key" },
peg$c61 = /^[a-zA-Z_$]/,
peg$c62 = { type: "class", value: "[a-zA-Z_$]", description: "[a-zA-Z_$]" },
peg$c63 = /^[0-9a-zA-Z_$\-]/,
peg$c64 = { type: "class", value: "[0-9a-zA-Z_$\\-]", description: "[0-9a-zA-Z_$\\-]" },
peg$c65 = function(h, t) { return h + t.join('') },
peg$c66 = { type: "other", description: "array" },
peg$c67 = function(n) {return n.join('')},
peg$c68 = function(a) {return a; },
peg$c69 = function(i, nk) { if(nk) { nk.unshift(i); } else {nk = [i] } return nk; },
peg$c70 = { type: "other", description: "array_part" },
peg$c71 = function(k) {return k},
peg$c72 = function(d, a) { if (a) { return d.concat(a); } else { return d; } },
peg$c73 = { type: "other", description: "inline" },
peg$c74 = "\"",
peg$c75 = { type: "literal", value: "\"", description: "\"\\\"\"" },
peg$c76 = function() { return ["literal", ""].concat([['line', line()], ['col', column()]]) },
peg$c77 = function(l) { return ["literal", l].concat([['line', line()], ['col', column()]]) },
peg$c78 = function(p) { return ["body"].concat(p).concat([['line', line()], ['col', column()]]) },
peg$c79 = function(l) { return ["buffer", l] },
peg$c80 = { type: "other", description: "buffer" },
peg$c81 = function(e, w) { return ["format", e, w.join('')].concat([['line', line()], ['col', column()]]) },
peg$c82 = { type: "any", description: "any character" },
peg$c83 = function(c) {return c},
peg$c84 = function(b) { return ["buffer", b.join('')].concat([['line', line()], ['col', column()]]) },
peg$c85 = { type: "other", description: "literal" },
peg$c86 = /^[^"]/,
peg$c87 = { type: "class", value: "[^\"]", description: "[^\"]" },
peg$c88 = function(b) { return b.join('') },
peg$c89 = "\\\"",
peg$c90 = { type: "literal", value: "\\\"", description: "\"\\\\\\\"\"" },
peg$c91 = function() { return '"' },
peg$c92 = { type: "other", description: "raw" },
peg$c93 = "{`",
peg$c94 = { type: "literal", value: "{`", description: "\"{`\"" },
peg$c95 = "`}",
peg$c96 = { type: "literal", value: "`}", description: "\"`}\"" },
peg$c97 = function(char) {return char},
peg$c98 = function(rawText) { return ["raw", rawText.join('')].concat([['line', line()], ['col', column()]]) },
peg$c99 = { type: "other", description: "comment" },
peg$c100 = "{!",
peg$c101 = { type: "literal", value: "{!", description: "\"{!\"" },
peg$c102 = "!}",
peg$c103 = { type: "literal", value: "!}", description: "\"!}\"" },
peg$c104 = function(c) { return ["comment", c.join('')].concat([['line', line()], ['col', column()]]) },
peg$c105 = /^[#?\^><+:@\/~]/,
peg$c106 = { type: "class", value: "[#?\\^><+:@\\/~]", description: "[#?\\^><+:@\\/~]" },
peg$c107 = "{",
peg$c108 = { type: "literal", value: "{", description: "\"{\"" },
peg$c109 = "}",
peg$c110 = { type: "literal", value: "}", description: "\"}\"" },
peg$c111 = "[",
peg$c112 = { type: "literal", value: "[", description: "\"[\"" },
peg$c113 = "]",
peg$c114 = { type: "literal", value: "]", description: "\"]\"" },
peg$c115 = "\n",
peg$c116 = { type: "literal", value: "\n", description: "\"\\n\"" },
peg$c117 = "\r\n",
peg$c118 = { type: "literal", value: "\r\n", description: "\"\\r\\n\"" },
peg$c119 = "\r",
peg$c120 = { type: "literal", value: "\r", description: "\"\\r\"" },
peg$c121 = "\u2028",
peg$c122 = { type: "literal", value: "\u2028", description: "\"\\u2028\"" },
peg$c123 = "\u2029",
peg$c124 = { type: "literal", value: "\u2029", description: "\"\\u2029\"" },
peg$c125 = /^[\t\x0B\f \xA0\uFEFF]/,
peg$c126 = { type: "class", value: "[\\t\\x0B\\f \\xA0\\uFEFF]", description: "[\\t\\x0B\\f \\xA0\\uFEFF]" },
peg$currPos = 0,
peg$reportedPos = 0,
peg$cachedPos = 0,
peg$cachedPosDetails = { line: 1, column: 1, seenCR: false },
peg$maxFailPos = 0,
peg$maxFailExpected = [],
peg$silentFails = 0,
peg$result;
if ("startRule" in options) {
if (!(options.startRule in peg$startRuleFunctions)) {
throw new Error("Can't start parsing from rule \"" + options.startRule + "\".");
}
peg$startRuleFunction = peg$startRuleFunctions[options.startRule];
}
function text() {
return input.substring(peg$reportedPos, peg$currPos);
}
function offset() {
return peg$reportedPos;
}
function line() {
return peg$computePosDetails(peg$reportedPos).line;
}
function column() {
return peg$computePosDetails(peg$reportedPos).column;
}
function expected(description) {
throw peg$buildException(
null,
[{ type: "other", description: description }],
peg$reportedPos
);
}
function error(message) {
throw peg$buildException(message, null, peg$reportedPos);
}
function peg$computePosDetails(pos) {
function advance(details, startPos, endPos) {
var p, ch;
for (p = startPos; p < endPos; p++) {
ch = input.charAt(p);
if (ch === "\n") {
if (!details.seenCR) { details.line++; }
details.column = 1;
details.seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
details.line++;
details.column = 1;
details.seenCR = true;
} else {
details.column++;
details.seenCR = false;
}
}
}
if (peg$cachedPos !== pos) {
if (peg$cachedPos > pos) {
peg$cachedPos = 0;
peg$cachedPosDetails = { line: 1, column: 1, seenCR: false };
}
advance(peg$cachedPosDetails, peg$cachedPos, pos);
peg$cachedPos = pos;
}
return peg$cachedPosDetails;
}
function peg$fail(expected) {
if (peg$currPos < peg$maxFailPos) { return; }
if (peg$currPos > peg$maxFailPos) {
peg$maxFailPos = peg$currPos;
peg$maxFailExpected = [];
}
peg$maxFailExpected.push(expected);
}
function peg$buildException(message, expected, pos) {
function cleanupExpected(expected) {
var i = 1;
expected.sort(function(a, b) {
if (a.description < b.description) {
return -1;
} else if (a.description > b.description) {
return 1;
} else {
return 0;
}
});
while (i < expected.length) {
if (expected[i - 1] === expected[i]) {
expected.splice(i, 1);
} else {
i++;
}
}
}
function buildMessage(expected, found) {
function stringEscape(s) {
function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); }
return s
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\x08/g, '\\b')
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n')
.replace(/\f/g, '\\f')
.replace(/\r/g, '\\r')
.replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); })
.replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); })
.replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); })
.replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); });
}
var expectedDescs = new Array(expected.length),
expectedDesc, foundDesc, i;
for (i = 0; i < expected.length; i++) {
expectedDescs[i] = expected[i].description;
}
expectedDesc = expected.length > 1
? expectedDescs.slice(0, -1).join(", ")
+ " or "
+ expectedDescs[expected.length - 1]
: expectedDescs[0];
foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input";
return "Expected " + expectedDesc + " but " + foundDesc + " found.";
}
var posDetails = peg$computePosDetails(pos),
found = pos < input.length ? input.charAt(pos) : null;
if (expected !== null) {
cleanupExpected(expected);
}
return new SyntaxError(
message !== null ? message : buildMessage(expected, found),
expected,
found,
pos,
posDetails.line,
posDetails.column
);
}
function peg$parsestart() {
var s0;
s0 = peg$parsebody();
return s0;
}
function peg$parsebody() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = [];
s2 = peg$parsepart();
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parsepart();
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c1(s1);
}
s0 = s1;
return s0;
}
function peg$parsepart() {
var s0;
s0 = peg$parseraw();
if (s0 === peg$FAILED) {
s0 = peg$parsecomment();
if (s0 === peg$FAILED) {
s0 = peg$parsesection();
if (s0 === peg$FAILED) {
s0 = peg$parsepartial();
if (s0 === peg$FAILED) {
s0 = peg$parsespecial();
if (s0 === peg$FAILED) {
s0 = peg$parsereference();
if (s0 === peg$FAILED) {
s0 = peg$parsebuffer();
}
}
}
}
}
}
return s0;
}
function peg$parsesection() {
var s0, s1, s2, s3, s4, s5, s6, s7;
peg$silentFails++;
s0 = peg$currPos;
s1 = peg$parsesec_tag_start();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parsews();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsews();
}
if (s2 !== peg$FAILED) {
s3 = peg$parserd();
if (s3 !== peg$FAILED) {
s4 = peg$parsebody();
if (s4 !== peg$FAILED) {
s5 = peg$parsebodies();
if (s5 !== peg$FAILED) {
s6 = peg$parseend_tag();
if (s6 === peg$FAILED) {
s6 = peg$c4;
}
if (s6 !== peg$FAILED) {
peg$reportedPos = peg$currPos;
s7 = peg$c5(s1, s4, s5, s6);
if (s7) {
s7 = peg$c6;
} else {
s7 = peg$c3;
}
if (s7 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c7(s1, s4, s5, s6);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parsesec_tag_start();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parsews();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsews();
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 47) {
s3 = peg$c8;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c9); }
}
if (s3 !== peg$FAILED) {
s4 = peg$parserd();
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c10(s1);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c2); }
}
return s0;
}
function peg$parsesec_tag_start() {
var s0, s1, s2, s3, s4, s5, s6;
s0 = peg$currPos;
s1 = peg$parseld();
if (s1 !== peg$FAILED) {
if (peg$c11.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c12); }
}
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parsews();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parsews();
}
if (s3 !== peg$FAILED) {
s4 = peg$parseidentifier();
if (s4 !== peg$FAILED) {
s5 = peg$parsecontext();
if (s5 !== peg$FAILED) {
s6 = peg$parseparams();
if (s6 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c13(s2, s4, s5, s6);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
return s0;
}
function peg$parseend_tag() {
var s0, s1, s2, s3, s4, s5, s6;
peg$silentFails++;
s0 = peg$currPos;
s1 = peg$parseld();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 47) {
s2 = peg$c8;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c9); }
}
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parsews();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parsews();
}
if (s3 !== peg$FAILED) {
s4 = peg$parseidentifier();
if (s4 !== peg$FAILED) {
s5 = [];
s6 = peg$parsews();
while (s6 !== peg$FAILED) {
s5.push(s6);
s6 = peg$parsews();
}
if (s5 !== peg$FAILED) {
s6 = peg$parserd();
if (s6 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c15(s4);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c14); }
}
return s0;
}
function peg$parsecontext() {
var s0, s1, s2, s3;
s0 = peg$currPos;
s1 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 58) {
s2 = peg$c16;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c17); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parseidentifier();
if (s3 !== peg$FAILED) {
peg$reportedPos = s1;
s2 = peg$c18(s3);
s1 = s2;
} else {
peg$currPos = s1;
s1 = peg$c3;
}
} else {
peg$currPos = s1;
s1 = peg$c3;
}
if (s1 === peg$FAILED) {
s1 = peg$c4;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c19(s1);
}
s0 = s1;
return s0;
}
function peg$parseparams() {
var s0, s1, s2, s3, s4, s5, s6;
peg$silentFails++;
s0 = peg$currPos;
s1 = [];
s2 = peg$currPos;
s3 = [];
s4 = peg$parsews();
if (s4 !== peg$FAILED) {
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parsews();
}
} else {
s3 = peg$c3;
}
if (s3 !== peg$FAILED) {
s4 = peg$parsekey();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s5 = peg$c21;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c22); }
}
if (s5 !== peg$FAILED) {
s6 = peg$parsenumber();
if (s6 === peg$FAILED) {
s6 = peg$parseidentifier();
if (s6 === peg$FAILED) {
s6 = peg$parseinline();
}
}
if (s6 !== peg$FAILED) {
peg$reportedPos = s2;
s3 = peg$c23(s4, s6);
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$currPos;
s3 = [];
s4 = peg$parsews();
if (s4 !== peg$FAILED) {
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parsews();
}
} else {
s3 = peg$c3;
}
if (s3 !== peg$FAILED) {
s4 = peg$parsekey();
if (s4 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 61) {
s5 = peg$c21;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c22); }
}
if (s5 !== peg$FAILED) {
s6 = peg$parsenumber();
if (s6 === peg$FAILED) {
s6 = peg$parseidentifier();
if (s6 === peg$FAILED) {
s6 = peg$parseinline();
}
}
if (s6 !== peg$FAILED) {
peg$reportedPos = s2;
s3 = peg$c23(s4, s6);
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c24(s1);
}
s0 = s1;
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c20); }
}
return s0;
}
function peg$parsebodies() {
var s0, s1, s2, s3, s4, s5, s6, s7;
peg$silentFails++;
s0 = peg$currPos;
s1 = [];
s2 = peg$currPos;
s3 = peg$parseld();
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 58) {
s4 = peg$c16;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c17); }
}
if (s4 !== peg$FAILED) {
s5 = peg$parsekey();
if (s5 !== peg$FAILED) {
s6 = peg$parserd();
if (s6 !== peg$FAILED) {
s7 = peg$parsebody();
if (s7 !== peg$FAILED) {
peg$reportedPos = s2;
s3 = peg$c23(s5, s7);
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$currPos;
s3 = peg$parseld();
if (s3 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 58) {
s4 = peg$c16;
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c17); }
}
if (s4 !== peg$FAILED) {
s5 = peg$parsekey();
if (s5 !== peg$FAILED) {
s6 = peg$parserd();
if (s6 !== peg$FAILED) {
s7 = peg$parsebody();
if (s7 !== peg$FAILED) {
peg$reportedPos = s2;
s3 = peg$c23(s5, s7);
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c26(s1);
}
s0 = s1;
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c25); }
}
return s0;
}
function peg$parsereference() {
var s0, s1, s2, s3, s4;
peg$silentFails++;
s0 = peg$currPos;
s1 = peg$parseld();
if (s1 !== peg$FAILED) {
s2 = peg$parseidentifier();
if (s2 !== peg$FAILED) {
s3 = peg$parsefilters();
if (s3 !== peg$FAILED) {
s4 = peg$parserd();
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c28(s2, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c27); }
}
return s0;
}
function peg$parsepartial() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9;
peg$silentFails++;
s0 = peg$currPos;
s1 = peg$parseld();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 62) {
s2 = peg$c30;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c31); }
}
if (s2 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 43) {
s2 = peg$c32;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c33); }
}
}
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parsews();
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parsews();
}
if (s3 !== peg$FAILED) {
s4 = peg$currPos;
s5 = peg$parsekey();
if (s5 !== peg$FAILED) {
peg$reportedPos = s4;
s5 = peg$c34(s5);
}
s4 = s5;
if (s4 === peg$FAILED) {
s4 = peg$parseinline();
}
if (s4 !== peg$FAILED) {
s5 = peg$parsecontext();
if (s5 !== peg$FAILED) {
s6 = peg$parseparams();
if (s6 !== peg$FAILED) {
s7 = [];
s8 = peg$parsews();
while (s8 !== peg$FAILED) {
s7.push(s8);
s8 = peg$parsews();
}
if (s7 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 47) {
s8 = peg$c8;
peg$currPos++;
} else {
s8 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c9); }
}
if (s8 !== peg$FAILED) {
s9 = peg$parserd();
if (s9 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c35(s2, s4, s5, s6);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c29); }
}
return s0;
}
function peg$parsefilters() {
var s0, s1, s2, s3, s4;
peg$silentFails++;
s0 = peg$currPos;
s1 = [];
s2 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 124) {
s3 = peg$c37;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c38); }
}
if (s3 !== peg$FAILED) {
s4 = peg$parsekey();
if (s4 !== peg$FAILED) {
peg$reportedPos = s2;
s3 = peg$c18(s4);
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 124) {
s3 = peg$c37;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c38); }
}
if (s3 !== peg$FAILED) {
s4 = peg$parsekey();
if (s4 !== peg$FAILED) {
peg$reportedPos = s2;
s3 = peg$c18(s4);
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c39(s1);
}
s0 = s1;
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c36); }
}
return s0;
}
function peg$parsespecial() {
var s0, s1, s2, s3, s4;
peg$silentFails++;
s0 = peg$currPos;
s1 = peg$parseld();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 126) {
s2 = peg$c41;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c42); }
}
if (s2 !== peg$FAILED) {
s3 = peg$parsekey();
if (s3 !== peg$FAILED) {
s4 = peg$parserd();
if (s4 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c43(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c40); }
}
return s0;
}
function peg$parseidentifier() {
var s0, s1;
peg$silentFails++;
s0 = peg$currPos;
s1 = peg$parsepath();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c45(s1);
}
s0 = s1;
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parsekey();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c46(s1);
}
s0 = s1;
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c44); }
}
return s0;
}
function peg$parsenumber() {
var s0, s1;
peg$silentFails++;
s0 = peg$currPos;
s1 = peg$parsefloat();
if (s1 === peg$FAILED) {
s1 = peg$parseinteger();
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c48(s1);
}
s0 = s1;
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c47); }
}
return s0;
}
function peg$parsefloat() {
var s0, s1, s2, s3, s4;
peg$silentFails++;
s0 = peg$currPos;
s1 = peg$parseinteger();
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 46) {
s2 = peg$c50;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c51); }
}
if (s2 !== peg$FAILED) {
s3 = [];
s4 = peg$parseinteger();
if (s4 !== peg$FAILED) {
while (s4 !== peg$FAILED) {
s3.push(s4);
s4 = peg$parseinteger();
}
} else {
s3 = peg$c3;
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c52(s1, s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c49); }
}
return s0;
}
function peg$parseinteger() {
var s0, s1, s2;
peg$silentFails++;
s0 = peg$currPos;
s1 = [];
if (peg$c54.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c55); }
}
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
if (peg$c54.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c55); }
}
}
} else {
s1 = peg$c3;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c56(s1);
}
s0 = s1;
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c53); }
}
return s0;
}
function peg$parsepath() {
var s0, s1, s2, s3;
peg$silentFails++;
s0 = peg$currPos;
s1 = peg$parsekey();
if (s1 === peg$FAILED) {
s1 = peg$c4;
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parsearray_part();
if (s3 === peg$FAILED) {
s3 = peg$parsearray();
}
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsearray_part();
if (s3 === peg$FAILED) {
s3 = peg$parsearray();
}
}
} else {
s2 = peg$c3;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c58(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s1 = peg$c50;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c51); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parsearray_part();
if (s3 === peg$FAILED) {
s3 = peg$parsearray();
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsearray_part();
if (s3 === peg$FAILED) {
s3 = peg$parsearray();
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c59(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c57); }
}
return s0;
}
function peg$parsekey() {
var s0, s1, s2, s3;
peg$silentFails++;
s0 = peg$currPos;
if (peg$c61.test(input.charAt(peg$currPos))) {
s1 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c62); }
}
if (s1 !== peg$FAILED) {
s2 = [];
if (peg$c63.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c64); }
}
while (s3 !== peg$FAILED) {
s2.push(s3);
if (peg$c63.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c64); }
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c65(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c60); }
}
return s0;
}
function peg$parsearray() {
var s0, s1, s2, s3, s4, s5;
peg$silentFails++;
s0 = peg$currPos;
s1 = peg$currPos;
s2 = peg$parselb();
if (s2 !== peg$FAILED) {
s3 = peg$currPos;
s4 = [];
if (peg$c54.test(input.charAt(peg$currPos))) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c55); }
}
if (s5 !== peg$FAILED) {
while (s5 !== peg$FAILED) {
s4.push(s5);
if (peg$c54.test(input.charAt(peg$currPos))) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c55); }
}
}
} else {
s4 = peg$c3;
}
if (s4 !== peg$FAILED) {
peg$reportedPos = s3;
s4 = peg$c67(s4);
}
s3 = s4;
if (s3 === peg$FAILED) {
s3 = peg$parseidentifier();
}
if (s3 !== peg$FAILED) {
s4 = peg$parserb();
if (s4 !== peg$FAILED) {
peg$reportedPos = s1;
s2 = peg$c68(s3);
s1 = s2;
} else {
peg$currPos = s1;
s1 = peg$c3;
}
} else {
peg$currPos = s1;
s1 = peg$c3;
}
} else {
peg$currPos = s1;
s1 = peg$c3;
}
if (s1 !== peg$FAILED) {
s2 = peg$parsearray_part();
if (s2 === peg$FAILED) {
s2 = peg$c4;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c69(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c66); }
}
return s0;
}
function peg$parsearray_part() {
var s0, s1, s2, s3, s4;
peg$silentFails++;
s0 = peg$currPos;
s1 = [];
s2 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s3 = peg$c50;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c51); }
}
if (s3 !== peg$FAILED) {
s4 = peg$parsekey();
if (s4 !== peg$FAILED) {
peg$reportedPos = s2;
s3 = peg$c71(s4);
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 46) {
s3 = peg$c50;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c51); }
}
if (s3 !== peg$FAILED) {
s4 = peg$parsekey();
if (s4 !== peg$FAILED) {
peg$reportedPos = s2;
s3 = peg$c71(s4);
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
}
} else {
s1 = peg$c3;
}
if (s1 !== peg$FAILED) {
s2 = peg$parsearray();
if (s2 === peg$FAILED) {
s2 = peg$c4;
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c72(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c70); }
}
return s0;
}
function peg$parseinline() {
var s0, s1, s2, s3;
peg$silentFails++;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 34) {
s1 = peg$c74;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c75); }
}
if (s1 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 34) {
s2 = peg$c74;
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c75); }
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c76();
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 34) {
s1 = peg$c74;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c75); }
}
if (s1 !== peg$FAILED) {
s2 = peg$parseliteral();
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 34) {
s3 = peg$c74;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c75); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c77(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 34) {
s1 = peg$c74;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c75); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parseinline_part();
if (s3 !== peg$FAILED) {
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parseinline_part();
}
} else {
s2 = peg$c3;
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 34) {
s3 = peg$c74;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c75); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c78(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
}
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c73); }
}
return s0;
}
function peg$parseinline_part() {
var s0, s1;
s0 = peg$parsespecial();
if (s0 === peg$FAILED) {
s0 = peg$parsereference();
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = peg$parseliteral();
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c79(s1);
}
s0 = s1;
}
}
return s0;
}
function peg$parsebuffer() {
var s0, s1, s2, s3, s4, s5, s6, s7;
peg$silentFails++;
s0 = peg$currPos;
s1 = peg$parseeol();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parsews();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsews();
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c81(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
if (s0 === peg$FAILED) {
s0 = peg$currPos;
s1 = [];
s2 = peg$currPos;
s3 = peg$currPos;
peg$silentFails++;
s4 = peg$parsetag();
peg$silentFails--;
if (s4 === peg$FAILED) {
s3 = peg$c6;
} else {
peg$currPos = s3;
s3 = peg$c3;
}
if (s3 !== peg$FAILED) {
s4 = peg$currPos;
peg$silentFails++;
s5 = peg$parseraw();
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c6;
} else {
peg$currPos = s4;
s4 = peg$c3;
}
if (s4 !== peg$FAILED) {
s5 = peg$currPos;
peg$silentFails++;
s6 = peg$parsecomment();
peg$silentFails--;
if (s6 === peg$FAILED) {
s5 = peg$c6;
} else {
peg$currPos = s5;
s5 = peg$c3;
}
if (s5 !== peg$FAILED) {
s6 = peg$currPos;
peg$silentFails++;
s7 = peg$parseeol();
peg$silentFails--;
if (s7 === peg$FAILED) {
s6 = peg$c6;
} else {
peg$currPos = s6;
s6 = peg$c3;
}
if (s6 !== peg$FAILED) {
if (input.length > peg$currPos) {
s7 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s7 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c82); }
}
if (s7 !== peg$FAILED) {
peg$reportedPos = s2;
s3 = peg$c83(s7);
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$currPos;
s3 = peg$currPos;
peg$silentFails++;
s4 = peg$parsetag();
peg$silentFails--;
if (s4 === peg$FAILED) {
s3 = peg$c6;
} else {
peg$currPos = s3;
s3 = peg$c3;
}
if (s3 !== peg$FAILED) {
s4 = peg$currPos;
peg$silentFails++;
s5 = peg$parseraw();
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c6;
} else {
peg$currPos = s4;
s4 = peg$c3;
}
if (s4 !== peg$FAILED) {
s5 = peg$currPos;
peg$silentFails++;
s6 = peg$parsecomment();
peg$silentFails--;
if (s6 === peg$FAILED) {
s5 = peg$c6;
} else {
peg$currPos = s5;
s5 = peg$c3;
}
if (s5 !== peg$FAILED) {
s6 = peg$currPos;
peg$silentFails++;
s7 = peg$parseeol();
peg$silentFails--;
if (s7 === peg$FAILED) {
s6 = peg$c6;
} else {
peg$currPos = s6;
s6 = peg$c3;
}
if (s6 !== peg$FAILED) {
if (input.length > peg$currPos) {
s7 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s7 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c82); }
}
if (s7 !== peg$FAILED) {
peg$reportedPos = s2;
s3 = peg$c83(s7);
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
}
} else {
s1 = peg$c3;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c84(s1);
}
s0 = s1;
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c80); }
}
return s0;
}
function peg$parseliteral() {
var s0, s1, s2, s3, s4;
peg$silentFails++;
s0 = peg$currPos;
s1 = [];
s2 = peg$currPos;
s3 = peg$currPos;
peg$silentFails++;
s4 = peg$parsetag();
peg$silentFails--;
if (s4 === peg$FAILED) {
s3 = peg$c6;
} else {
peg$currPos = s3;
s3 = peg$c3;
}
if (s3 !== peg$FAILED) {
s4 = peg$parseesc();
if (s4 === peg$FAILED) {
if (peg$c86.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c87); }
}
}
if (s4 !== peg$FAILED) {
peg$reportedPos = s2;
s3 = peg$c83(s4);
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$currPos;
s3 = peg$currPos;
peg$silentFails++;
s4 = peg$parsetag();
peg$silentFails--;
if (s4 === peg$FAILED) {
s3 = peg$c6;
} else {
peg$currPos = s3;
s3 = peg$c3;
}
if (s3 !== peg$FAILED) {
s4 = peg$parseesc();
if (s4 === peg$FAILED) {
if (peg$c86.test(input.charAt(peg$currPos))) {
s4 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s4 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c87); }
}
}
if (s4 !== peg$FAILED) {
peg$reportedPos = s2;
s3 = peg$c83(s4);
s2 = s3;
} else {
peg$currPos = s2;
s2 = peg$c3;
}
} else {
peg$currPos = s2;
s2 = peg$c3;
}
}
} else {
s1 = peg$c3;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c88(s1);
}
s0 = s1;
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c85); }
}
return s0;
}
function peg$parseesc() {
var s0, s1;
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c89) {
s1 = peg$c89;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c90); }
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c91();
}
s0 = s1;
return s0;
}
function peg$parseraw() {
var s0, s1, s2, s3, s4, s5;
peg$silentFails++;
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c93) {
s1 = peg$c93;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c94); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$currPos;
peg$silentFails++;
if (input.substr(peg$currPos, 2) === peg$c95) {
s5 = peg$c95;
peg$currPos += 2;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c96); }
}
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c6;
} else {
peg$currPos = s4;
s4 = peg$c3;
}
if (s4 !== peg$FAILED) {
if (input.length > peg$currPos) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c82); }
}
if (s5 !== peg$FAILED) {
peg$reportedPos = s3;
s4 = peg$c97(s5);
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c3;
}
} else {
peg$currPos = s3;
s3 = peg$c3;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$currPos;
peg$silentFails++;
if (input.substr(peg$currPos, 2) === peg$c95) {
s5 = peg$c95;
peg$currPos += 2;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c96); }
}
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c6;
} else {
peg$currPos = s4;
s4 = peg$c3;
}
if (s4 !== peg$FAILED) {
if (input.length > peg$currPos) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c82); }
}
if (s5 !== peg$FAILED) {
peg$reportedPos = s3;
s4 = peg$c97(s5);
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c3;
}
} else {
peg$currPos = s3;
s3 = peg$c3;
}
}
if (s2 !== peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c95) {
s3 = peg$c95;
peg$currPos += 2;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c96); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c98(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c92); }
}
return s0;
}
function peg$parsecomment() {
var s0, s1, s2, s3, s4, s5;
peg$silentFails++;
s0 = peg$currPos;
if (input.substr(peg$currPos, 2) === peg$c100) {
s1 = peg$c100;
peg$currPos += 2;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c101); }
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$currPos;
peg$silentFails++;
if (input.substr(peg$currPos, 2) === peg$c102) {
s5 = peg$c102;
peg$currPos += 2;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c103); }
}
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c6;
} else {
peg$currPos = s4;
s4 = peg$c3;
}
if (s4 !== peg$FAILED) {
if (input.length > peg$currPos) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c82); }
}
if (s5 !== peg$FAILED) {
peg$reportedPos = s3;
s4 = peg$c83(s5);
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c3;
}
} else {
peg$currPos = s3;
s3 = peg$c3;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$currPos;
peg$silentFails++;
if (input.substr(peg$currPos, 2) === peg$c102) {
s5 = peg$c102;
peg$currPos += 2;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c103); }
}
peg$silentFails--;
if (s5 === peg$FAILED) {
s4 = peg$c6;
} else {
peg$currPos = s4;
s4 = peg$c3;
}
if (s4 !== peg$FAILED) {
if (input.length > peg$currPos) {
s5 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c82); }
}
if (s5 !== peg$FAILED) {
peg$reportedPos = s3;
s4 = peg$c83(s5);
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c3;
}
} else {
peg$currPos = s3;
s3 = peg$c3;
}
}
if (s2 !== peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c102) {
s3 = peg$c102;
peg$currPos += 2;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c103); }
}
if (s3 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c104(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c99); }
}
return s0;
}
function peg$parsetag() {
var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9;
s0 = peg$currPos;
s1 = peg$parseld();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parsews();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsews();
}
if (s2 !== peg$FAILED) {
if (peg$c105.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c106); }
}
if (s3 !== peg$FAILED) {
s4 = [];
s5 = peg$parsews();
while (s5 !== peg$FAILED) {
s4.push(s5);
s5 = peg$parsews();
}
if (s4 !== peg$FAILED) {
s5 = [];
s6 = peg$currPos;
s7 = peg$currPos;
peg$silentFails++;
s8 = peg$parserd();
peg$silentFails--;
if (s8 === peg$FAILED) {
s7 = peg$c6;
} else {
peg$currPos = s7;
s7 = peg$c3;
}
if (s7 !== peg$FAILED) {
s8 = peg$currPos;
peg$silentFails++;
s9 = peg$parseeol();
peg$silentFails--;
if (s9 === peg$FAILED) {
s8 = peg$c6;
} else {
peg$currPos = s8;
s8 = peg$c3;
}
if (s8 !== peg$FAILED) {
if (input.length > peg$currPos) {
s9 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s9 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c82); }
}
if (s9 !== peg$FAILED) {
s7 = [s7, s8, s9];
s6 = s7;
} else {
peg$currPos = s6;
s6 = peg$c3;
}
} else {
peg$currPos = s6;
s6 = peg$c3;
}
} else {
peg$currPos = s6;
s6 = peg$c3;
}
if (s6 !== peg$FAILED) {
while (s6 !== peg$FAILED) {
s5.push(s6);
s6 = peg$currPos;
s7 = peg$currPos;
peg$silentFails++;
s8 = peg$parserd();
peg$silentFails--;
if (s8 === peg$FAILED) {
s7 = peg$c6;
} else {
peg$currPos = s7;
s7 = peg$c3;
}
if (s7 !== peg$FAILED) {
s8 = peg$currPos;
peg$silentFails++;
s9 = peg$parseeol();
peg$silentFails--;
if (s9 === peg$FAILED) {
s8 = peg$c6;
} else {
peg$currPos = s8;
s8 = peg$c3;
}
if (s8 !== peg$FAILED) {
if (input.length > peg$currPos) {
s9 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s9 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c82); }
}
if (s9 !== peg$FAILED) {
s7 = [s7, s8, s9];
s6 = s7;
} else {
peg$currPos = s6;
s6 = peg$c3;
}
} else {
peg$currPos = s6;
s6 = peg$c3;
}
} else {
peg$currPos = s6;
s6 = peg$c3;
}
}
} else {
s5 = peg$c3;
}
if (s5 !== peg$FAILED) {
s6 = [];
s7 = peg$parsews();
while (s7 !== peg$FAILED) {
s6.push(s7);
s7 = peg$parsews();
}
if (s6 !== peg$FAILED) {
s7 = peg$parserd();
if (s7 !== peg$FAILED) {
s1 = [s1, s2, s3, s4, s5, s6, s7];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
} else {
peg$currPos = s0;
s0 = peg$c3;
}
if (s0 === peg$FAILED) {
s0 = peg$parsereference();
}
return s0;
}
function peg$parseld() {
var s0;
if (input.charCodeAt(peg$currPos) === 123) {
s0 = peg$c107;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c108); }
}
return s0;
}
function peg$parserd() {
var s0;
if (input.charCodeAt(peg$currPos) === 125) {
s0 = peg$c109;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c110); }
}
return s0;
}
function peg$parselb() {
var s0;
if (input.charCodeAt(peg$currPos) === 91) {
s0 = peg$c111;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c112); }
}
return s0;
}
function peg$parserb() {
var s0;
if (input.charCodeAt(peg$currPos) === 93) {
s0 = peg$c113;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c114); }
}
return s0;
}
function peg$parseeol() {
var s0;
if (input.charCodeAt(peg$currPos) === 10) {
s0 = peg$c115;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c116); }
}
if (s0 === peg$FAILED) {
if (input.substr(peg$currPos, 2) === peg$c117) {
s0 = peg$c117;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c118); }
}
if (s0 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 13) {
s0 = peg$c119;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c120); }
}
if (s0 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 8232) {
s0 = peg$c121;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c122); }
}
if (s0 === peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 8233) {
s0 = peg$c123;
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c124); }
}
}
}
}
}
return s0;
}
function peg$parsews() {
var s0;
if (peg$c125.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c126); }
}
if (s0 === peg$FAILED) {
s0 = peg$parseeol();
}
return s0;
}
peg$result = peg$startRuleFunction();
if (peg$result !== peg$FAILED && peg$currPos === input.length) {
return peg$result;
} else {
if (peg$result !== peg$FAILED && peg$currPos < input.length) {
peg$fail({ type: "end", description: "end of input" });
}
throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos);
}
}
return {
SyntaxError: SyntaxError,
parse: parse
};
})();
|
import {Deck, OrthographicView} from '@deck.gl/core';
import {ScatterplotLayer, PathLayer, SolidPolygonLayer} from '@deck.gl/layers';
import GL from '@luma.gl/constants';
import {Buffer} from '@luma.gl/core';
import data from './data';
/** DeckGL **/
const deck = new Deck({
container: 'container',
views: new OrthographicView(),
controller: true,
initialViewState: {
target: [6, 6, 0],
zoom: 5
},
onWebGLInitialized
});
function onWebGLInitialized(gl) {
const buffer = new Buffer(gl, data);
const positions = {buffer, type: GL.FLOAT, size: 3, offset: 4, stride: 16};
const colors = {buffer, type: GL.UNSIGNED_BYTE, size: 4, offset: 0, stride: 16};
const indices = new Uint16Array([0, 1, 2, 3, 4, 5, 4, 5, 6]);
const layers = [
new SolidPolygonLayer({
id: 'polygons',
data: {
length: 2,
startIndices: [0, 3],
attributes: {
indices,
getPolygon: positions,
getFillColor: colors
}
},
pickable: true,
autoHighlight: true,
_normalize: false, // this instructs SolidPolygonLayer to skip normalization and use the binary as is
getWidth: 0.5
}),
new PathLayer({
id: 'paths',
data: {
length: 2,
startIndices: [0, 3],
attributes: {
// PathLayer expects padded positions (1 vertex to the left & 2 vertices to the right)
// So it cannot share the same buffer with other layers without padding
// TODO - handle in PathTesselator?
getPath: {value: data, size: 3, offset: 4, stride: 16},
getColor: colors
}
},
pickable: true,
autoHighlight: true,
_pathType: 'open', // this instructs PathLayer to skip normalization and use the binary as is
getWidth: 0.5
}),
new ScatterplotLayer({
id: 'points',
data: {
length: 7,
attributes: {
getPosition: positions,
getLineColor: colors
}
},
pickable: true,
autoHighlight: true,
stroked: true,
filled: false,
getRadius: 1,
getLineWidth: 0.5
})
];
deck.setProps({layers});
}
/* global document */
document.body.style.margin = '0px';
|
// JavaScript Document
jQuery(function(){
// 幫 #qaContent 的 ul 子元素加上 .accordionPart
// 接著再找出 li 中的第一個 div 子元素加上 .qa_title
// 並幫其加上 hover 及 click 事件
// 同時把兄弟元素加上 .qa_content 並隱藏起來
jQuery('#qaContent ul').addClass('accordionPart').find('li div:nth-child(1)').addClass('qa_title').hover(function(){
jQuery(this).addClass('qa_title_on');
}, function(){
jQuery(this).removeClass('qa_title_on');
}).click(function(){
// 當點到標題時,若答案是隱藏時則顯示它,同時隱藏其它已經展開的項目
// 反之則隱藏
var jQueryqa_content = jQuery(this).next('div.qa_content');
if(!jQueryqa_content.is(':visible')){
jQuery('#qaContent ul li div.qa_content:visible').slideUp();
}
jQueryqa_content.slideToggle();
}).siblings().addClass('qa_content').hide();
// 全部展開
jQuery('#qaContent .qa_showall').click(function(){
jQuery('#qaContent ul.accordionPart li div.qa_content').slideDown();
return false;
});
// 全部隱藏
jQuery('#qaContent .qa_hideall').click(function(){
jQuery('#qaContent ul.accordionPart li div.qa_content').slideUp();
return false;
});
});
|
const expect = require('chai').expect;
const User = require('../index');
const mongoose = require('mongoose');
const userData = {
minimal : require('../data/sample.minimal.json'),
full : require('../data/sample.full.json')
};
describe('User instance data', function() {
describe('should fail if ', () => {
it('username was not set', testErrorIfFieldIsMissing('username'));
it('email was not set', testErrorIfFieldIsMissing('email'));
it('email is not a proper email', testErrorIfFieldIsMissing('username', {email: 'this is not an email'}));
it('friends is not an array', testErrorIfFieldIsMissing('friends', {friends: {}}));
it('friends are not ids', testErrorIfFieldIsMissing('friends', {friends: ['123']}));
function testErrorIfFieldIsMissing(field, value){
return (done) => {
const user = new User(value);
user.validate((err) => {
expect(err.errors[field]).to.exist;
done();
});
};
}
});
describe('should be valid if', () => {
it('the minimun data is provided', (done) => {
const user = new User(userData.minimal);
user.validate((err) => {
expect(err).to.be.not.ok;
done();
});
});
it('every data type is right', (done) => {
userData.full.updatedAt = new Date();
userData.full.questions = mongoose.Types.ObjectId('4edd40c86762e0fb12000003');
const user = new User(userData.full);
user.validate((err) => {
expect(err).to.be.not.ok;
done();
});
});
});
});
|
var Tome = require('../..');
exports.testSelfDestroy = function (test) {
test.expect(5);
var a = { b: { c: 1 }, d: { e: 1} };
var b = Tome.conjure(a);
function fail() {
test.ok();
}
function ok() {
test.ok(true);
}
b.on('readable', fail);
b.on('destroy', ok);
b.b.on('destroy', ok);
b.b.c.on('destroy', ok);
b.d.on('destroy', ok);
b.d.e.on('destroy', ok);
b.destroy();
// Calling a 2nd time shouldn't have any effect.
b.destroy();
test.done();
};
exports.testTomeDestroy = function (test) {
test.expect(5);
var a = { b: { c: 1 }, d: { e: 1} };
var b = Tome.conjure(a);
function fail() {
test.ok();
}
function ok() {
test.ok(true);
}
b.on('readable', fail);
b.on('destroy', ok);
b.b.on('destroy', ok);
b.b.c.on('destroy', ok);
b.d.on('destroy', ok);
b.d.e.on('destroy', ok);
Tome.destroy(b);
// Calling a 2nd time shouldn't have any effect.
Tome.destroy(b);
test.done();
};
|
define( "Confirm" , [ "Base" , "Panel" , "DataView" , "EventBind" ] , function( Base , Panel , DV , EB ){
var tool ,
Confirm = Base.extend( function( opt ){
this._confirmConfig = {
_opt : $.extend( {} , opt )
}
this.panel = new Panel( "zjddConfirmTmpContainerTemplate" , {} , null , {
width : "75%"
} );
this.show( opt );
} , {
__confirmConfig : {
optDefault : {
cancelTitle : "取消" ,
sureTitle : "确定"
}
} ,
show : function( opt ){
opt = $.extend( {} , this.__confirmConfig.optDefault , opt );
tool.makeupOpt( opt );
if( !this.dataView ){
this.dataView = tool.getConfirmDataView.call( this , opt );
} else {
this.dataView.set( opt );
this.panel.show();
}
return this;
} ,
hide : function(){
this.panel.hide();
return this;
}
} );
tool = {
getConfirmDataView : function( opt ){
var _self = this ,
_dv = new DV( "zjddConfirmContainerTemplate" , opt );
this.panel.$content.html( _dv.getDataModal() );
new EB( {
"a.cancel::tap" : function(){
if( typeof opt.cancel === "function" ){
opt.cancel();
}
_self.hide();
} ,
"a.sure::tap" : function(){
if( typeof opt.sure === "function" ){
if( opt.sure() !== false ){
_self.hide();
};
}
}
} , this.panel.$content );
return _dv;
} ,
makeupOpt : function( opt ){
if( opt.sure ){
opt[ "footerClass" ] = "btn-is-2";
} else {
opt[ "footerClass" ] = "";
}
}
}
return Confirm;
} );
|
var app = require('app');
var ipc = require('ipc');
var server = require('./server');
var BrowserWindow = require('browser-window');
var mainWindow = null;
// Quit when all windows are closed.
app.on('window-all-closed', function() {
app.quit();
});
app.on('ready', function() {
mainWindow = new BrowserWindow({
title: 'Hathor',
width: 800,
height: 600,
'auto-hide-menu-bar': false,
'use-content-size': true,
});
mainWindow.loadUrl('file://' + __dirname + '/index.html');
mainWindow.focus();
});
ipc.on('close', function() {
app.quit()
});
ipc.on('minimize', function() {
mainWindow.minimize();
});
server(function(port) {
window.serverPort = port;
});
|
/*!
* QUnit 1.14.1pre
* http://qunitjs.com/
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-03-22T14:42Z
*/
(function( window ) {
var QUnit,
assert,
config,
onErrorFnPrev,
testId = 0,
fileName = (sourceFromStacktrace( 0 ) || "" ).replace(/(:\d+)+\)?/, "").replace(/.+\//, ""),
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
// Keep a local reference to Date (GH-283)
Date = window.Date,
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
defined = {
document: typeof window.document !== "undefined",
setTimeout: typeof window.setTimeout !== "undefined",
sessionStorage: (function() {
var x = "qunit-test-string";
try {
sessionStorage.setItem( x, x );
sessionStorage.removeItem( x );
return true;
} catch( e ) {
return false;
}
}())
},
/**
* Provides a normalized error string, correcting an issue
* with IE 7 (and prior) where Error.prototype.toString is
* not properly implemented
*
* Based on http://es5.github.com/#x15.11.4.4
*
* @param {String|Error} error
* @return {String} error message
*/
errorString = function( error ) {
var name, message,
errorString = error.toString();
if ( errorString.substring( 0, 7 ) === "[object" ) {
name = error.name ? error.name.toString() : "Error";
message = error.message ? error.message.toString() : "";
if ( name && message ) {
return name + ": " + message;
} else if ( name ) {
return name;
} else if ( message ) {
return message;
} else {
return "Error";
}
} else {
return errorString;
}
},
/**
* Makes a clone of an object using only Array or Object as base,
* and copies over the own enumerable properties.
*
* @param {Object} obj
* @return {Object} New object with only the own properties (recursively).
*/
objectValues = function( obj ) {
// Grunt 0.3.x uses an older version of jshint that still has jshint/jshint#392.
/*jshint newcap: false */
var key, val,
vals = QUnit.is( "array", obj ) ? [] : {};
for ( key in obj ) {
if ( hasOwn.call( obj, key ) ) {
val = obj[key];
vals[key] = val === Object(val) ? objectValues(val) : val;
}
}
return vals;
};
// Root QUnit object.
// `QUnit` initialized at top of scope
QUnit = {
// call on start of module test to prepend name to all tests
module: function( name, testEnvironment ) {
config.currentModule = name;
config.currentModuleTestEnvironment = testEnvironment;
config.modules[name] = true;
},
asyncTest: function( testName, expected, callback ) {
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
QUnit.test( testName, expected, callback, true );
},
test: function( testName, expected, callback, async ) {
var test,
nameHtml = "<span class='test-name'>" + escapeText( testName ) + "</span>";
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
if ( config.currentModule ) {
nameHtml = "<span class='module-name'>" + escapeText( config.currentModule ) + "</span>: " + nameHtml;
}
test = new Test({
nameHtml: nameHtml,
testName: testName,
expected: expected,
async: async,
callback: callback,
module: config.currentModule,
moduleTestEnvironment: config.currentModuleTestEnvironment,
stack: sourceFromStacktrace( 2 )
});
if ( !validTest( test ) ) {
return;
}
test.queue();
},
// Specify the number of expected assertions to guarantee that failed test (no assertions are run at all) don't slip through.
expect: function( asserts ) {
if (arguments.length === 1) {
config.current.expected = asserts;
} else {
return config.current.expected;
}
},
start: function( count ) {
// QUnit hasn't been initialized yet.
// Note: RequireJS (et al) may delay onLoad
if ( config.semaphore === undefined ) {
QUnit.begin(function() {
// This is triggered at the top of QUnit.load, push start() to the event loop, to allow QUnit.load to finish first
setTimeout(function() {
QUnit.start( count );
});
});
return;
}
config.semaphore -= count || 1;
// don't start until equal number of stop-calls
if ( config.semaphore > 0 ) {
return;
}
// ignore if start is called more often then stop
if ( config.semaphore < 0 ) {
config.semaphore = 0;
QUnit.pushFailure( "Called start() while already started (QUnit.config.semaphore was 0 already)", null, sourceFromStacktrace(2) );
return;
}
// A slight delay, to avoid any current callbacks
if ( defined.setTimeout ) {
setTimeout(function() {
if ( config.semaphore > 0 ) {
return;
}
if ( config.timeout ) {
clearTimeout( config.timeout );
}
config.blocking = false;
process( true );
}, 13);
} else {
config.blocking = false;
process( true );
}
},
stop: function( count ) {
config.semaphore += count || 1;
config.blocking = true;
if ( config.testTimeout && defined.setTimeout ) {
clearTimeout( config.timeout );
config.timeout = setTimeout(function() {
QUnit.ok( false, "Test timed out" );
config.semaphore = 1;
QUnit.start();
}, config.testTimeout );
}
}
};
// We use the prototype to distinguish between properties that should
// be exposed as globals (and in exports) and those that shouldn't
(function() {
function F() {}
F.prototype = QUnit;
QUnit = new F();
// Make F QUnit's constructor so that we can add to the prototype later
QUnit.constructor = F;
}());
/**
* Config object: Maintain internal state
* Later exposed as QUnit.config
* `config` initialized at top of scope
*/
config = {
// The queue of tests to run
queue: [],
// block until document ready
blocking: true,
// when enabled, show only failing tests
// gets persisted through sessionStorage and can be changed in UI via checkbox
hidepassed: false,
// by default, run previously failed tests first
// very useful in combination with "Hide passed tests" checked
reorder: true,
// by default, modify document.title when suite is done
altertitle: true,
// by default, scroll to top of the page when suite is done
scrolltop: true,
// when enabled, all tests must call expect()
requireExpects: false,
// add checkboxes that are persisted in the query-string
// when enabled, the id is set to `true` as a `QUnit.config` property
urlConfig: [
{
id: "noglobals",
label: "Check for Globals",
tooltip: "Enabling this will test if any test introduces new properties on the `window` object. Stored as query-strings."
},
{
id: "notrycatch",
label: "No try-catch",
tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging exceptions in IE reasonable. Stored as query-strings."
}
],
// Set of all modules.
modules: {},
// logging callback queues
begin: [],
done: [],
log: [],
testStart: [],
testDone: [],
moduleStart: [],
moduleDone: []
};
// Initialize more QUnit.config and QUnit.urlParams
(function() {
var i, current,
location = window.location || { search: "", protocol: "file:" },
params = location.search.slice( 1 ).split( "&" ),
length = params.length,
urlParams = {};
if ( params[ 0 ] ) {
for ( i = 0; i < length; i++ ) {
current = params[ i ].split( "=" );
current[ 0 ] = decodeURIComponent( current[ 0 ] );
// allow just a key to turn on a flag, e.g., test.html?noglobals
current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true;
if ( urlParams[ current[ 0 ] ] ) {
urlParams[ current[ 0 ] ] = [].concat( urlParams[ current[ 0 ] ], current[ 1 ] );
} else {
urlParams[ current[ 0 ] ] = current[ 1 ];
}
}
}
QUnit.urlParams = urlParams;
// String search anywhere in moduleName+testName
config.filter = urlParams.filter;
// Exact match of the module name
config.module = urlParams.module;
config.testNumber = [];
if ( urlParams.testNumber ) {
// Ensure that urlParams.testNumber is an array
urlParams.testNumber = [].concat( urlParams.testNumber );
for ( i = 0; i < urlParams.testNumber.length; i++ ) {
current = urlParams.testNumber[ i ];
config.testNumber.push( parseInt( current, 10 ) );
}
}
// Figure out if we're running the tests from a server or not
QUnit.isLocal = location.protocol === "file:";
}());
extend( QUnit, {
config: config,
// Initialize the configuration options
init: function() {
extend( config, {
stats: { all: 0, bad: 0 },
moduleStats: { all: 0, bad: 0 },
started: +new Date(),
updateRate: 1000,
blocking: false,
autostart: true,
autorun: false,
filter: "",
queue: [],
semaphore: 1
});
var tests, banner, result,
qunit = id( "qunit" );
if ( qunit ) {
qunit.innerHTML =
"<h1 id='qunit-header'>" + escapeText( document.title ) + "</h1>" +
"<h2 id='qunit-banner'></h2>" +
"<div id='qunit-testrunner-toolbar'></div>" +
"<h2 id='qunit-userAgent'></h2>" +
"<ol id='qunit-tests'></ol>";
}
tests = id( "qunit-tests" );
banner = id( "qunit-banner" );
result = id( "qunit-testresult" );
if ( tests ) {
tests.innerHTML = "";
}
if ( banner ) {
banner.className = "";
}
if ( result ) {
result.parentNode.removeChild( result );
}
if ( tests ) {
result = document.createElement( "p" );
result.id = "qunit-testresult";
result.className = "result";
tests.parentNode.insertBefore( result, tests );
result.innerHTML = "Running...<br/> ";
}
},
// Resets the test setup. Useful for tests that modify the DOM.
/*
DEPRECATED: Use multiple tests instead of resetting inside a test.
Use testStart or testDone for custom cleanup.
This method will throw an error in 2.0, and will be removed in 2.1
*/
reset: function() {
var fixture = id( "qunit-fixture" );
if ( fixture ) {
fixture.innerHTML = config.fixture;
}
},
// Safe object type checking
is: function( type, obj ) {
return QUnit.objectType( obj ) === type;
},
objectType: function( obj ) {
if ( typeof obj === "undefined" ) {
return "undefined";
}
// Consider: typeof null === object
if ( obj === null ) {
return "null";
}
var match = toString.call( obj ).match(/^\[object\s(.*)\]$/),
type = match && match[1] || "";
switch ( type ) {
case "Number":
if ( isNaN(obj) ) {
return "nan";
}
return "number";
case "String":
case "Boolean":
case "Array":
case "Date":
case "RegExp":
case "Function":
return type.toLowerCase();
}
if ( typeof obj === "object" ) {
return "object";
}
return undefined;
},
push: function( result, actual, expected, message ) {
if ( !config.current ) {
throw new Error( "assertion outside test context, was " + sourceFromStacktrace() );
}
var output, stack,
details = {
module: config.current.module,
name: config.current.testName,
result: result,
message: message,
actual: actual,
expected: expected
};
message = escapeText( message ) || ( result ? "okay" : "failed" );
message = "<span class='test-message'>" + message + "</span>";
output = message;
if ( !result ) {
expected = escapeText( QUnit.jsDump.parse(expected) );
actual = escapeText( QUnit.jsDump.parse(actual) );
output += "<table><tr class='test-expected'><th>Expected: </th><td><pre>" + expected + "</pre></td></tr>";
if ( actual !== expected ) {
output += "<tr class='test-actual'><th>Result: </th><td><pre>" + actual + "</pre></td></tr>";
output += "<tr class='test-diff'><th>Diff: </th><td><pre>" + QUnit.diff( expected, actual ) + "</pre></td></tr>";
}
stack = sourceFromStacktrace();
if ( stack ) {
details.source = stack[0];
details.stack = stack;
output += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText( details.source ) + "</pre></td></tr>";
}
output += "</table>";
}
runLoggingCallbacks( "log", QUnit, details );
config.current.assertions.push({
result: !!result,
message: output
});
},
pushFailure: function( message, stack, actual ) {
if ( !config.current ) {
throw new Error( "pushFailure() assertion outside test context, was " + sourceFromStacktrace(2) );
}
var output,
details = {
module: config.current.module,
name: config.current.testName,
result: false,
message: message
};
message = escapeText( message ) || "error";
message = "<span class='test-message'>" + message + "</span>";
output = message;
output += "<table>";
if ( actual ) {
output += "<tr class='test-actual'><th>Result: </th><td><pre>" + escapeText( actual ) + "</pre></td></tr>";
}
if ( stack ) {
details.source = stack[0];
details.stack = stack;
output += "<tr class='test-source'><th>Source: </th><td><pre>" + escapeText( details.source ) + "</pre></td></tr>";
}
output += "</table>";
runLoggingCallbacks( "log", QUnit, details );
config.current.assertions.push({
result: false,
message: output
});
},
url: function( params ) {
params = extend( extend( {}, QUnit.urlParams ), params );
var key,
querystring = "?";
for ( key in params ) {
if ( hasOwn.call( params, key ) ) {
querystring += encodeURIComponent( key ) + "=" +
encodeURIComponent( params[ key ] ) + "&";
}
}
return window.location.protocol + "//" + window.location.host +
window.location.pathname + querystring.slice( 0, -1 );
},
extend: extend,
id: id,
addEvent: addEvent,
addClass: addClass,
hasClass: hasClass,
removeClass: removeClass
// load, equiv, jsDump, diff: Attached later
});
/**
* @deprecated: Created for backwards compatibility with test runner that set the hook function
* into QUnit.{hook}, instead of invoking it and passing the hook function.
* QUnit.constructor is set to the empty F() above so that we can add to it's prototype here.
* Doing this allows us to tell if the following methods have been overwritten on the actual
* QUnit object.
*/
extend( QUnit.constructor.prototype, {
// Logging callbacks; all receive a single argument with the listed properties
// run test/logs.html for any related changes
begin: registerLoggingCallback( "begin" ),
// done: { failed, passed, total, runtime }
done: registerLoggingCallback( "done" ),
// log: { result, actual, expected, message }
log: registerLoggingCallback( "log" ),
// testStart: { name }
testStart: registerLoggingCallback( "testStart" ),
// testDone: { name, failed, passed, total, runtime }
testDone: registerLoggingCallback( "testDone" ),
// moduleStart: { name }
moduleStart: registerLoggingCallback( "moduleStart" ),
// moduleDone: { name, failed, passed, total }
moduleDone: registerLoggingCallback( "moduleDone" )
});
if ( !defined.document || document.readyState === "complete" ) {
config.autorun = true;
}
QUnit.load = function() {
runLoggingCallbacks( "begin", QUnit, {} );
// Initialize the config, saving the execution queue
var banner, filter, i, j, label, len, main, ol, toolbar, val, selection,
urlConfigContainer, moduleFilter, userAgent,
numModules = 0,
moduleNames = [],
moduleFilterHtml = "",
urlConfigHtml = "",
oldconfig = extend( {}, config );
QUnit.init();
extend(config, oldconfig);
config.blocking = false;
len = config.urlConfig.length;
for ( i = 0; i < len; i++ ) {
val = config.urlConfig[i];
if ( typeof val === "string" ) {
val = {
id: val,
label: val
};
}
config[ val.id ] = QUnit.urlParams[ val.id ];
if ( !val.value || typeof val.value === "string" ) {
urlConfigHtml += "<input id='qunit-urlconfig-" + escapeText( val.id ) +
"' name='" + escapeText( val.id ) +
"' type='checkbox'" +
( val.value ? " value='" + escapeText( val.value ) + "'" : "" ) +
( config[ val.id ] ? " checked='checked'" : "" ) +
" title='" + escapeText( val.tooltip ) +
"'><label for='qunit-urlconfig-" + escapeText( val.id ) +
"' title='" + escapeText( val.tooltip ) + "'>" + val.label + "</label>";
} else {
urlConfigHtml += "<label for='qunit-urlconfig-" + escapeText( val.id ) +
"' title='" + escapeText( val.tooltip ) +
"'>" + val.label +
": </label><select id='qunit-urlconfig-" + escapeText( val.id ) +
"' name='" + escapeText( val.id ) +
"' title='" + escapeText( val.tooltip ) +
"'><option></option>";
selection = false;
if ( QUnit.is( "array", val.value ) ) {
for ( j = 0; j < val.value.length; j++ ) {
urlConfigHtml += "<option value='" + escapeText( val.value[j] ) + "'" +
( config[ val.id ] === val.value[j] ?
(selection = true) && " selected='selected'" :
"" ) +
">" + escapeText( val.value[j] ) + "</option>";
}
} else {
for ( j in val.value ) {
if ( hasOwn.call( val.value, j ) ) {
urlConfigHtml += "<option value='" + escapeText( j ) + "'" +
( config[ val.id ] === j ?
(selection = true) && " selected='selected'" :
"" ) +
">" + escapeText( val.value[j] ) + "</option>";
}
}
}
if ( config[ val.id ] && !selection ) {
urlConfigHtml += "<option value='" + escapeText( config[ val.id ] ) +
"' selected='selected' disabled='disabled'>" +
escapeText( config[ val.id ] ) +
"</option>";
}
urlConfigHtml += "</select>";
}
}
for ( i in config.modules ) {
if ( config.modules.hasOwnProperty( i ) ) {
moduleNames.push(i);
}
}
numModules = moduleNames.length;
moduleNames.sort( function( a, b ) {
return a.localeCompare( b );
});
moduleFilterHtml += "<label for='qunit-modulefilter'>Module: </label><select id='qunit-modulefilter' name='modulefilter'><option value='' " +
( config.module === undefined ? "selected='selected'" : "" ) +
">< All Modules ></option>";
for ( i = 0; i < numModules; i++) {
moduleFilterHtml += "<option value='" + escapeText( encodeURIComponent(moduleNames[i]) ) + "' " +
( config.module === moduleNames[i] ? "selected='selected'" : "" ) +
">" + escapeText(moduleNames[i]) + "</option>";
}
moduleFilterHtml += "</select>";
// `userAgent` initialized at top of scope
userAgent = id( "qunit-userAgent" );
if ( userAgent ) {
userAgent.innerHTML = navigator.userAgent;
}
// `banner` initialized at top of scope
banner = id( "qunit-header" );
if ( banner ) {
banner.innerHTML = "<a href='" + QUnit.url({ filter: undefined, module: undefined, testNumber: undefined }) + "'>" + banner.innerHTML + "</a> ";
}
// `toolbar` initialized at top of scope
toolbar = id( "qunit-testrunner-toolbar" );
if ( toolbar ) {
// `filter` initialized at top of scope
filter = document.createElement( "input" );
filter.type = "checkbox";
filter.id = "qunit-filter-pass";
addEvent( filter, "click", function() {
var tmp,
ol = id( "qunit-tests" );
if ( filter.checked ) {
ol.className = ol.className + " hidepass";
} else {
tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " ";
ol.className = tmp.replace( / hidepass /, " " );
}
if ( defined.sessionStorage ) {
if (filter.checked) {
sessionStorage.setItem( "qunit-filter-passed-tests", "true" );
} else {
sessionStorage.removeItem( "qunit-filter-passed-tests" );
}
}
});
if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem( "qunit-filter-passed-tests" ) ) {
filter.checked = true;
// `ol` initialized at top of scope
ol = id( "qunit-tests" );
ol.className = ol.className + " hidepass";
}
toolbar.appendChild( filter );
// `label` initialized at top of scope
label = document.createElement( "label" );
label.setAttribute( "for", "qunit-filter-pass" );
label.setAttribute( "title", "Only show tests and assertions that fail. Stored in sessionStorage." );
label.innerHTML = "Hide passed tests";
toolbar.appendChild( label );
urlConfigContainer = document.createElement("span");
urlConfigContainer.innerHTML = urlConfigHtml;
// For oldIE support:
// * Add handlers to the individual elements instead of the container
// * Use "click" instead of "change" for checkboxes
// * Fallback from event.target to event.srcElement
addEvents( urlConfigContainer.getElementsByTagName("input"), "click", function( event ) {
var params = {},
target = event.target || event.srcElement;
params[ target.name ] = target.checked ?
target.defaultValue || true :
undefined;
window.location = QUnit.url( params );
});
addEvents( urlConfigContainer.getElementsByTagName("select"), "change", function( event ) {
var params = {},
target = event.target || event.srcElement;
params[ target.name ] = target.options[ target.selectedIndex ].value || undefined;
window.location = QUnit.url( params );
});
toolbar.appendChild( urlConfigContainer );
if (numModules > 1) {
moduleFilter = document.createElement( "span" );
moduleFilter.setAttribute( "id", "qunit-modulefilter-container" );
moduleFilter.innerHTML = moduleFilterHtml;
addEvent( moduleFilter.lastChild, "change", function() {
var selectBox = moduleFilter.getElementsByTagName("select")[0],
selectedModule = decodeURIComponent(selectBox.options[selectBox.selectedIndex].value);
window.location = QUnit.url({
module: ( selectedModule === "" ) ? undefined : selectedModule,
// Remove any existing filters
filter: undefined,
testNumber: undefined
});
});
toolbar.appendChild(moduleFilter);
}
}
// `main` initialized at top of scope
main = id( "qunit-fixture" );
if ( main ) {
config.fixture = main.innerHTML;
}
if ( config.autostart ) {
QUnit.start();
}
};
if ( defined.document ) {
addEvent( window, "load", QUnit.load );
}
// `onErrorFnPrev` initialized at top of scope
// Preserve other handlers
onErrorFnPrev = window.onerror;
// Cover uncaught exceptions
// Returning true will suppress the default browser handler,
// returning false will let it run.
window.onerror = function ( error, filePath, linerNr ) {
var ret = false;
if ( onErrorFnPrev ) {
ret = onErrorFnPrev( error, filePath, linerNr );
}
// Treat return value as window.onerror itself does,
// Only do our handling if not suppressed.
if ( ret !== true ) {
if ( QUnit.config.current ) {
if ( QUnit.config.current.ignoreGlobalErrors ) {
return true;
}
QUnit.pushFailure( error, [filePath + ":" + linerNr] );
} else {
QUnit.test( "global failure", extend( function() {
QUnit.pushFailure( error, [filePath + ":" + linerNr] );
}, { validTest: validTest } ) );
}
return false;
}
return ret;
};
function done() {
config.autorun = true;
// Log the last module results
if ( config.previousModule ) {
runLoggingCallbacks( "moduleDone", QUnit, {
name: config.previousModule,
failed: config.moduleStats.bad,
passed: config.moduleStats.all - config.moduleStats.bad,
total: config.moduleStats.all
});
}
delete config.previousModule;
var i, key,
banner = id( "qunit-banner" ),
tests = id( "qunit-tests" ),
runtime = +new Date() - config.started,
passed = config.stats.all - config.stats.bad,
html = [
"Tests completed in ",
runtime,
" milliseconds.<br/>",
"<span class='passed'>",
passed,
"</span> assertions of <span class='total'>",
config.stats.all,
"</span> passed, <span class='failed'>",
config.stats.bad,
"</span> failed."
].join( "" );
if ( banner ) {
banner.className = ( config.stats.bad ? "qunit-fail" : "qunit-pass" );
}
if ( tests ) {
id( "qunit-testresult" ).innerHTML = html;
}
if ( config.altertitle && defined.document && document.title ) {
// show ✖ for good, ✔ for bad suite result in title
// use escape sequences in case file gets loaded with non-utf-8-charset
document.title = [
( config.stats.bad ? "\u2716" : "\u2714" ),
document.title.replace( /^[\u2714\u2716] /i, "" )
].join( " " );
}
// clear own sessionStorage items if all tests passed
if ( config.reorder && defined.sessionStorage && config.stats.bad === 0 ) {
// `key` & `i` initialized at top of scope
for ( i = 0; i < sessionStorage.length; i++ ) {
key = sessionStorage.key( i++ );
if ( key.indexOf( "qunit-test-" ) === 0 ) {
sessionStorage.removeItem( key );
}
}
}
// scroll back to top to show results
if ( config.scrolltop && window.scrollTo ) {
window.scrollTo(0, 0);
}
runLoggingCallbacks( "done", QUnit, {
failed: config.stats.bad,
passed: passed,
total: config.stats.all,
runtime: runtime
});
}
/** @return Boolean: true if this test should be ran */
function validTest( test ) {
var include,
filter = config.filter && config.filter.toLowerCase(),
module = config.module && config.module.toLowerCase(),
fullName = ( test.module + ": " + test.testName ).toLowerCase();
// Internally-generated tests are always valid
if ( test.callback && test.callback.validTest === validTest ) {
delete test.callback.validTest;
return true;
}
if ( config.testNumber.length > 0 ) {
if ( inArray( test.testNumber, config.testNumber ) < 0 ) {
return false;
}
}
if ( module && ( !test.module || test.module.toLowerCase() !== module ) ) {
return false;
}
if ( !filter ) {
return true;
}
include = filter.charAt( 0 ) !== "!";
if ( !include ) {
filter = filter.slice( 1 );
}
// If the filter matches, we need to honour include
if ( fullName.indexOf( filter ) !== -1 ) {
return include;
}
// Otherwise, do the opposite
return !include;
}
// so far supports only Firefox, Chrome and Opera (buggy), Safari (for real exceptions)
// Later Safari and IE10 are supposed to support error.stack as well
// See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack
function extractStacktrace( e, offset, produceStack ) {
offset = offset === undefined ? 3 : offset;
var stack, include, i;
if ( e.stacktrace ) {
// Opera
if (!produceStack) {
return e.stacktrace.split( "\n" )[ offset + 3 ];
} else {
return e.stacktrace.split( "\n" ).slice( offset + 3 );
}
} else if ( e.stack ) {
// Firefox, Chrome
stack = e.stack.split( "\n" );
if (/^error$/i.test( stack[0] ) ) {
stack.shift();
}
if ( fileName ) {
include = [];
for ( i = offset; i < stack.length; i++ ) {
if ( stack[ i ].indexOf( fileName ) !== -1 ) {
break;
}
include.push( stack[ i ] );
}
if ( include.length ) {
if (!produceStack) {
return include.join( "\n" );
} else {
return include;
}
}
}
if (!produceStack) {
return stack[ offset ];
} else {
return stack.slice( offset );
}
} else if ( e.sourceURL ) {
// Safari, PhantomJS
// hopefully one day Safari provides actual stacktraces
// exclude useless self-reference for generated Error objects
if ( /qunit.js$/.test( e.sourceURL ) ) {
return;
}
// for actual exceptions, this is useful
if (!produceStack) {
return e.sourceURL + ":" + e.line;
} else {
return [e.sourceURL + ":" + e.line];
}
}
}
function sourceFromStacktrace( offset ) {
try {
throw new Error();
} catch ( e ) {
return extractStacktrace( e, offset );
}
}
/**
* Escape text for attribute or text content.
*/
function escapeText( s ) {
if ( !s ) {
return "";
}
s = s + "";
// Both single quotes and double quotes (for attributes)
return s.replace( /['"<>&]/g, function( s ) {
switch( s ) {
case "'":
return "'";
case "\"":
return """;
case "<":
return "<";
case ">":
return ">";
case "&":
return "&";
}
});
}
function synchronize( callback, last ) {
config.queue.push( callback );
if ( config.autorun && !config.blocking ) {
process( last );
}
}
function process( last ) {
function next() {
process( last );
}
var start = new Date().getTime();
config.depth = config.depth ? config.depth + 1 : 1;
while ( config.queue.length && !config.blocking ) {
if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) {
config.queue.shift()();
} else {
setTimeout( next, 13 );
break;
}
}
config.depth--;
if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) {
done();
}
}
function saveGlobal() {
config.pollution = [];
if ( config.noglobals ) {
for ( var key in window ) {
if ( hasOwn.call( window, key ) ) {
// in Opera sometimes DOM element ids show up here, ignore them
if ( /^qunit-test-output/.test( key ) ) {
continue;
}
config.pollution.push( key );
}
}
}
}
function checkPollution() {
var newGlobals,
deletedGlobals,
old = config.pollution;
saveGlobal();
newGlobals = diff( config.pollution, old );
if ( newGlobals.length > 0 ) {
QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join(", ") );
}
deletedGlobals = diff( old, config.pollution );
if ( deletedGlobals.length > 0 ) {
QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join(", ") );
}
}
// returns a new Array with the elements that are in a but not in b
function diff( a, b ) {
var i, j,
result = a.slice();
for ( i = 0; i < result.length; i++ ) {
for ( j = 0; j < b.length; j++ ) {
if ( result[i] === b[j] ) {
result.splice( i, 1 );
i--;
break;
}
}
}
return result;
}
function extend( a, b ) {
for ( var prop in b ) {
if ( hasOwn.call( b, prop ) ) {
// Avoid "Member not found" error in IE8 caused by messing with window.constructor
if ( !( prop === "constructor" && a === window ) ) {
if ( b[ prop ] === undefined ) {
delete a[ prop ];
} else {
a[ prop ] = b[ prop ];
}
}
}
}
return a;
}
/**
* @param {HTMLElement} elem
* @param {string} type
* @param {Function} fn
*/
function addEvent( elem, type, fn ) {
if ( elem.addEventListener ) {
// Standards-based browsers
elem.addEventListener( type, fn, false );
} else if ( elem.attachEvent ) {
// support: IE <9
elem.attachEvent( "on" + type, fn );
} else {
// Caller must ensure support for event listeners is present
throw new Error( "addEvent() was called in a context without event listener support" );
}
}
/**
* @param {Array|NodeList} elems
* @param {string} type
* @param {Function} fn
*/
function addEvents( elems, type, fn ) {
var i = elems.length;
while ( i-- ) {
addEvent( elems[i], type, fn );
}
}
function hasClass( elem, name ) {
return (" " + elem.className + " ").indexOf(" " + name + " ") > -1;
}
function addClass( elem, name ) {
if ( !hasClass( elem, name ) ) {
elem.className += (elem.className ? " " : "") + name;
}
}
function removeClass( elem, name ) {
var set = " " + elem.className + " ";
// Class name may appear multiple times
while ( set.indexOf(" " + name + " ") > -1 ) {
set = set.replace(" " + name + " " , " ");
}
// If possible, trim it for prettiness, but not necessarily
elem.className = typeof set.trim === "function" ? set.trim() : set.replace(/^\s+|\s+$/g, "");
}
function id( name ) {
return defined.document && document.getElementById && document.getElementById( name );
}
function registerLoggingCallback( key ) {
return function( callback ) {
config[key].push( callback );
};
}
// Supports deprecated method of completely overwriting logging callbacks
function runLoggingCallbacks( key, scope, args ) {
var i, callbacks;
if ( QUnit.hasOwnProperty( key ) ) {
QUnit[ key ].call(scope, args );
} else {
callbacks = config[ key ];
for ( i = 0; i < callbacks.length; i++ ) {
callbacks[ i ].call( scope, args );
}
}
}
// from jquery.js
function inArray( elem, array ) {
if ( array.indexOf ) {
return array.indexOf( elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
}
function Test( settings ) {
extend( this, settings );
this.assertions = [];
this.testNumber = ++Test.count;
}
Test.count = 0;
Test.prototype = {
init: function() {
var a, b, li,
tests = id( "qunit-tests" );
if ( tests ) {
b = document.createElement( "strong" );
b.innerHTML = this.nameHtml;
// `a` initialized at top of scope
a = document.createElement( "a" );
a.innerHTML = "Rerun";
a.href = QUnit.url({ testNumber: this.testNumber });
li = document.createElement( "li" );
li.appendChild( b );
li.appendChild( a );
li.className = "running";
li.id = this.id = "qunit-test-output" + testId++;
tests.appendChild( li );
}
},
setup: function() {
if (
// Emit moduleStart when we're switching from one module to another
this.module !== config.previousModule ||
// They could be equal (both undefined) but if the previousModule property doesn't
// yet exist it means this is the first test in a suite that isn't wrapped in a
// module, in which case we'll just emit a moduleStart event for 'undefined'.
// Without this, reporters can get testStart before moduleStart which is a problem.
!hasOwn.call( config, "previousModule" )
) {
if ( hasOwn.call( config, "previousModule" ) ) {
runLoggingCallbacks( "moduleDone", QUnit, {
name: config.previousModule,
failed: config.moduleStats.bad,
passed: config.moduleStats.all - config.moduleStats.bad,
total: config.moduleStats.all
});
}
config.previousModule = this.module;
config.moduleStats = { all: 0, bad: 0 };
runLoggingCallbacks( "moduleStart", QUnit, {
name: this.module
});
}
config.current = this;
this.testEnvironment = extend({
setup: function() {},
teardown: function() {}
}, this.moduleTestEnvironment );
this.started = +new Date();
runLoggingCallbacks( "testStart", QUnit, {
name: this.testName,
module: this.module
});
/*jshint camelcase:false */
/**
* Expose the current test environment.
*
* @deprecated since 1.12.0: Use QUnit.config.current.testEnvironment instead.
*/
QUnit.current_testEnvironment = this.testEnvironment;
/*jshint camelcase:true */
if ( !config.pollution ) {
saveGlobal();
}
if ( config.notrycatch ) {
this.testEnvironment.setup.call( this.testEnvironment, QUnit.assert );
return;
}
try {
this.testEnvironment.setup.call( this.testEnvironment, QUnit.assert );
} catch( e ) {
QUnit.pushFailure( "Setup failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1, true ) );
}
},
run: function() {
config.current = this;
var running = id( "qunit-testresult" );
if ( running ) {
running.innerHTML = "Running: <br/>" + this.nameHtml;
}
if ( this.async ) {
QUnit.stop();
}
this.callbackStarted = +new Date();
if ( config.notrycatch ) {
this.callback.call( this.testEnvironment, QUnit.assert );
this.callbackRuntime = +new Date() - this.callbackStarted;
return;
}
try {
this.callback.call( this.testEnvironment, QUnit.assert );
this.callbackRuntime = +new Date() - this.callbackStarted;
} catch( e ) {
this.callbackRuntime = +new Date() - this.callbackStarted;
QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + ( e.message || e ), extractStacktrace( e, 0, true ) );
// else next test will carry the responsibility
saveGlobal();
// Restart the tests if they're blocking
if ( config.blocking ) {
QUnit.start();
}
}
},
teardown: function() {
config.current = this;
if ( config.notrycatch ) {
if ( typeof this.callbackRuntime === "undefined" ) {
this.callbackRuntime = +new Date() - this.callbackStarted;
}
this.testEnvironment.teardown.call( this.testEnvironment, QUnit.assert );
return;
} else {
try {
this.testEnvironment.teardown.call( this.testEnvironment, QUnit.assert );
} catch( e ) {
QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1, true ) );
}
}
checkPollution();
},
finish: function() {
config.current = this;
if ( config.requireExpects && this.expected === null ) {
QUnit.pushFailure( "Expected number of assertions to be defined, but expect() was not called.", this.stack );
} else if ( this.expected !== null && this.expected !== this.assertions.length ) {
QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack );
} else if ( this.expected === null && !this.assertions.length ) {
QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.", this.stack );
}
var i, assertion, a, b, time, li, ol,
test = this,
good = 0,
bad = 0,
tests = id( "qunit-tests" );
this.runtime = +new Date() - this.started;
config.stats.all += this.assertions.length;
config.moduleStats.all += this.assertions.length;
if ( tests ) {
ol = document.createElement( "ol" );
ol.className = "qunit-assert-list";
for ( i = 0; i < this.assertions.length; i++ ) {
assertion = this.assertions[i];
li = document.createElement( "li" );
li.className = assertion.result ? "pass" : "fail";
li.innerHTML = assertion.message || ( assertion.result ? "okay" : "failed" );
ol.appendChild( li );
if ( assertion.result ) {
good++;
} else {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
// store result when possible
if ( QUnit.config.reorder && defined.sessionStorage ) {
if ( bad ) {
sessionStorage.setItem( "qunit-test-" + this.module + "-" + this.testName, bad );
} else {
sessionStorage.removeItem( "qunit-test-" + this.module + "-" + this.testName );
}
}
if ( bad === 0 ) {
addClass( ol, "qunit-collapsed" );
}
// `b` initialized at top of scope
b = document.createElement( "strong" );
b.innerHTML = this.nameHtml + " <b class='counts'>(<b class='failed'>" + bad + "</b>, <b class='passed'>" + good + "</b>, " + this.assertions.length + ")</b>";
addEvent(b, "click", function() {
var next = b.parentNode.lastChild,
collapsed = hasClass( next, "qunit-collapsed" );
( collapsed ? removeClass : addClass )( next, "qunit-collapsed" );
});
addEvent(b, "dblclick", function( e ) {
var target = e && e.target ? e.target : window.event.srcElement;
if ( target.nodeName.toLowerCase() === "span" || target.nodeName.toLowerCase() === "b" ) {
target = target.parentNode;
}
if ( window.location && target.nodeName.toLowerCase() === "strong" ) {
window.location = QUnit.url({ testNumber: test.testNumber });
}
});
// `time` initialized at top of scope
time = document.createElement( "span" );
time.className = "runtime";
time.innerHTML = this.runtime + " ms";
// `li` initialized at top of scope
li = id( this.id );
li.className = bad ? "fail" : "pass";
li.removeChild( li.firstChild );
a = li.firstChild;
li.appendChild( b );
li.appendChild( a );
li.appendChild( time );
li.appendChild( ol );
} else {
for ( i = 0; i < this.assertions.length; i++ ) {
if ( !this.assertions[i].result ) {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
}
runLoggingCallbacks( "testDone", QUnit, {
name: this.testName,
module: this.module,
failed: bad,
passed: this.assertions.length - bad,
total: this.assertions.length,
runtime: this.runtime,
// DEPRECATED: this property will be removed in 2.0.0, use runtime instead
duration: this.runtime
});
QUnit.reset();
config.current = undefined;
},
queue: function() {
var bad,
test = this;
synchronize(function() {
test.init();
});
function run() {
// each of these can by async
synchronize(function() {
test.setup();
});
synchronize(function() {
test.run();
});
synchronize(function() {
test.teardown();
});
synchronize(function() {
test.finish();
});
}
// `bad` initialized at top of scope
// defer when previous test run passed, if storage is available
bad = QUnit.config.reorder && defined.sessionStorage &&
+sessionStorage.getItem( "qunit-test-" + this.module + "-" + this.testName );
if ( bad ) {
run();
} else {
synchronize( run, true );
}
}
};
// `assert` initialized at top of scope
// Assert helpers
// All of these must either call QUnit.push() or manually do:
// - runLoggingCallbacks( "log", .. );
// - config.current.assertions.push({ .. });
assert = QUnit.assert = {
/**
* Asserts rough true-ish result.
* @name ok
* @function
* @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
*/
ok: function( result, msg ) {
if ( !config.current ) {
throw new Error( "ok() assertion outside test context, was " + sourceFromStacktrace(2) );
}
result = !!result;
msg = msg || ( result ? "okay" : "failed" );
var stack,
details = {
module: config.current.module,
name: config.current.testName,
result: result,
message: msg
};
msg = "<span class='test-message'>" + escapeText( msg ) + "</span>";
if ( !result ) {
stack = sourceFromStacktrace( 2, true );
if ( stack ) {
details.source = stack[0];
details.stack = stack;
msg += "<table><tr class='test-source'><th>Source: </th><td><pre>" +
escapeText( details.source ) +
"</pre></td></tr></table>";
}
}
runLoggingCallbacks( "log", QUnit, details );
config.current.assertions.push({
result: result,
message: msg
});
},
/**
* Assert that the first two arguments are equal, with an optional message.
* Prints out both actual and expected values.
* @name equal
* @function
* @example equal( format( "Received {0} bytes.", 2), "Received 2 bytes.", "format() replaces {0} with next argument" );
*/
equal: function( actual, expected, message ) {
/*jshint eqeqeq:false */
QUnit.push( expected == actual, actual, expected, message );
},
/**
* @name notEqual
* @function
*/
notEqual: function( actual, expected, message ) {
/*jshint eqeqeq:false */
QUnit.push( expected != actual, actual, expected, message );
},
/**
* @name propEqual
* @function
*/
propEqual: function( actual, expected, message ) {
actual = objectValues(actual);
expected = objectValues(expected);
QUnit.push( QUnit.equiv(actual, expected), actual, expected, message );
},
/**
* @name notPropEqual
* @function
*/
notPropEqual: function( actual, expected, message ) {
actual = objectValues(actual);
expected = objectValues(expected);
QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message );
},
/**
* @name deepEqual
* @function
*/
deepEqual: function( actual, expected, message ) {
QUnit.push( QUnit.equiv(actual, expected), actual, expected, message );
},
/**
* @name notDeepEqual
* @function
*/
notDeepEqual: function( actual, expected, message ) {
QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message );
},
/**
* @name strictEqual
* @function
*/
strictEqual: function( actual, expected, message ) {
QUnit.push( expected === actual, actual, expected, message );
},
/**
* @name notStrictEqual
* @function
*/
notStrictEqual: function( actual, expected, message ) {
QUnit.push( expected !== actual, actual, expected, message );
},
"throws": function( block, expected, message ) {
var actual,
expectedOutput = expected,
ok = false;
// 'expected' is optional
if ( !message && typeof expected === "string" ) {
message = expected;
expected = null;
}
config.current.ignoreGlobalErrors = true;
try {
block.call( config.current.testEnvironment );
} catch (e) {
actual = e;
}
config.current.ignoreGlobalErrors = false;
if ( actual ) {
// we don't want to validate thrown error
if ( !expected ) {
ok = true;
expectedOutput = null;
// expected is an Error object
} else if ( expected instanceof Error ) {
ok = actual instanceof Error &&
actual.name === expected.name &&
actual.message === expected.message;
// expected is a regexp
} else if ( QUnit.objectType( expected ) === "regexp" ) {
ok = expected.test( errorString( actual ) );
// expected is a string
} else if ( QUnit.objectType( expected ) === "string" ) {
ok = expected === errorString( actual );
// expected is a constructor
} else if ( actual instanceof expected ) {
ok = true;
// expected is a validation function which returns true is validation passed
} else if ( expected.call( {}, actual ) === true ) {
expectedOutput = null;
ok = true;
}
QUnit.push( ok, actual, expectedOutput, message );
} else {
QUnit.pushFailure( message, null, "No exception was thrown." );
}
}
};
/**
* @deprecated since 1.8.0
* Kept assertion helpers in root for backwards compatibility.
*/
extend( QUnit.constructor.prototype, assert );
/**
* @deprecated since 1.9.0
* Kept to avoid TypeErrors for undefined methods.
*/
QUnit.constructor.prototype.raises = function() {
QUnit.push( false, false, false, "QUnit.raises has been deprecated since 2012 (fad3c1ea), use QUnit.throws instead" );
};
/**
* @deprecated since 1.0.0, replaced with error pushes since 1.3.0
* Kept to avoid TypeErrors for undefined methods.
*/
QUnit.constructor.prototype.equals = function() {
QUnit.push( false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead" );
};
QUnit.constructor.prototype.same = function() {
QUnit.push( false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead" );
};
// Test for equality any JavaScript type.
// Author: Philippe Rathé <prathe@gmail.com>
QUnit.equiv = (function() {
// Call the o related callback with the given arguments.
function bindCallbacks( o, callbacks, args ) {
var prop = QUnit.objectType( o );
if ( prop ) {
if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) {
return callbacks[ prop ].apply( callbacks, args );
} else {
return callbacks[ prop ]; // or undefined
}
}
}
// the real equiv function
var innerEquiv,
// stack to decide between skip/abort functions
callers = [],
// stack to avoiding loops from circular referencing
parents = [],
parentsB = [],
getProto = Object.getPrototypeOf || function ( obj ) {
/* jshint camelcase: false, proto: true */
return obj.__proto__;
},
callbacks = (function () {
// for string, boolean, number and null
function useStrictEquality( b, a ) {
/*jshint eqeqeq:false */
if ( b instanceof a.constructor || a instanceof b.constructor ) {
// to catch short annotation VS 'new' annotation of a
// declaration
// e.g. var i = 1;
// var j = new Number(1);
return a == b;
} else {
return a === b;
}
}
return {
"string": useStrictEquality,
"boolean": useStrictEquality,
"number": useStrictEquality,
"null": useStrictEquality,
"undefined": useStrictEquality,
"nan": function( b ) {
return isNaN( b );
},
"date": function( b, a ) {
return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf();
},
"regexp": function( b, a ) {
return QUnit.objectType( b ) === "regexp" &&
// the regex itself
a.source === b.source &&
// and its modifiers
a.global === b.global &&
// (gmi) ...
a.ignoreCase === b.ignoreCase &&
a.multiline === b.multiline &&
a.sticky === b.sticky;
},
// - skip when the property is a method of an instance (OOP)
// - abort otherwise,
// initial === would have catch identical references anyway
"function": function() {
var caller = callers[callers.length - 1];
return caller !== Object && typeof caller !== "undefined";
},
"array": function( b, a ) {
var i, j, len, loop, aCircular, bCircular;
// b could be an object literal here
if ( QUnit.objectType( b ) !== "array" ) {
return false;
}
len = a.length;
if ( len !== b.length ) {
// safe and faster
return false;
}
// track reference to avoid circular references
parents.push( a );
parentsB.push( b );
for ( i = 0; i < len; i++ ) {
loop = false;
for ( j = 0; j < parents.length; j++ ) {
aCircular = parents[j] === a[i];
bCircular = parentsB[j] === b[i];
if ( aCircular || bCircular ) {
if ( a[i] === b[i] || aCircular && bCircular ) {
loop = true;
} else {
parents.pop();
parentsB.pop();
return false;
}
}
}
if ( !loop && !innerEquiv(a[i], b[i]) ) {
parents.pop();
parentsB.pop();
return false;
}
}
parents.pop();
parentsB.pop();
return true;
},
"object": function( b, a ) {
/*jshint forin:false */
var i, j, loop, aCircular, bCircular,
// Default to true
eq = true,
aProperties = [],
bProperties = [];
// comparing constructors is more strict than using
// instanceof
if ( a.constructor !== b.constructor ) {
// Allow objects with no prototype to be equivalent to
// objects with Object as their constructor.
if ( !(( getProto(a) === null && getProto(b) === Object.prototype ) ||
( getProto(b) === null && getProto(a) === Object.prototype ) ) ) {
return false;
}
}
// stack constructor before traversing properties
callers.push( a.constructor );
// track reference to avoid circular references
parents.push( a );
parentsB.push( b );
// be strict: don't ensure hasOwnProperty and go deep
for ( i in a ) {
loop = false;
for ( j = 0; j < parents.length; j++ ) {
aCircular = parents[j] === a[i];
bCircular = parentsB[j] === b[i];
if ( aCircular || bCircular ) {
if ( a[i] === b[i] || aCircular && bCircular ) {
loop = true;
} else {
eq = false;
break;
}
}
}
aProperties.push(i);
if ( !loop && !innerEquiv(a[i], b[i]) ) {
eq = false;
break;
}
}
parents.pop();
parentsB.pop();
callers.pop(); // unstack, we are done
for ( i in b ) {
bProperties.push( i ); // collect b's properties
}
// Ensures identical properties name
return eq && innerEquiv( aProperties.sort(), bProperties.sort() );
}
};
}());
innerEquiv = function() { // can take multiple arguments
var args = [].slice.apply( arguments );
if ( args.length < 2 ) {
return true; // end transition
}
return (function( a, b ) {
if ( a === b ) {
return true; // catch the most you can
} else if ( a === null || b === null || typeof a === "undefined" ||
typeof b === "undefined" ||
QUnit.objectType(a) !== QUnit.objectType(b) ) {
return false; // don't lose time with error prone cases
} else {
return bindCallbacks(a, callbacks, [ b, a ]);
}
// apply transition with (1..n) arguments
}( args[0], args[1] ) && innerEquiv.apply( this, args.splice(1, args.length - 1 )) );
};
return innerEquiv;
}());
/**
* jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com |
* http://flesler.blogspot.com Licensed under BSD
* (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008
*
* @projectDescription Advanced and extensible data dumping for Javascript.
* @version 1.0.0
* @author Ariel Flesler
* @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
*/
QUnit.jsDump = (function() {
function quote( str ) {
return "\"" + str.toString().replace( /"/g, "\\\"" ) + "\"";
}
function literal( o ) {
return o + "";
}
function join( pre, arr, post ) {
var s = jsDump.separator(),
base = jsDump.indent(),
inner = jsDump.indent(1);
if ( arr.join ) {
arr = arr.join( "," + s + inner );
}
if ( !arr ) {
return pre + post;
}
return [ pre, inner + arr, base + post ].join(s);
}
function array( arr, stack ) {
var i = arr.length, ret = new Array(i);
this.up();
while ( i-- ) {
ret[i] = this.parse( arr[i] , undefined , stack);
}
this.down();
return join( "[", ret, "]" );
}
var reName = /^function (\w+)/,
jsDump = {
// type is used mostly internally, you can fix a (custom)type in advance
parse: function( obj, type, stack ) {
stack = stack || [ ];
var inStack, res,
parser = this.parsers[ type || this.typeOf(obj) ];
type = typeof parser;
inStack = inArray( obj, stack );
if ( inStack !== -1 ) {
return "recursion(" + (inStack - stack.length) + ")";
}
if ( type === "function" ) {
stack.push( obj );
res = parser.call( this, obj, stack );
stack.pop();
return res;
}
return ( type === "string" ) ? parser : this.parsers.error;
},
typeOf: function( obj ) {
var type;
if ( obj === null ) {
type = "null";
} else if ( typeof obj === "undefined" ) {
type = "undefined";
} else if ( QUnit.is( "regexp", obj) ) {
type = "regexp";
} else if ( QUnit.is( "date", obj) ) {
type = "date";
} else if ( QUnit.is( "function", obj) ) {
type = "function";
} else if ( typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined" ) {
type = "window";
} else if ( obj.nodeType === 9 ) {
type = "document";
} else if ( obj.nodeType ) {
type = "node";
} else if (
// native arrays
toString.call( obj ) === "[object Array]" ||
// NodeList objects
( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) )
) {
type = "array";
} else if ( obj.constructor === Error.prototype.constructor ) {
type = "error";
} else {
type = typeof obj;
}
return type;
},
separator: function() {
return this.multiline ? this.HTML ? "<br />" : "\n" : this.HTML ? " " : " ";
},
// extra can be a number, shortcut for increasing-calling-decreasing
indent: function( extra ) {
if ( !this.multiline ) {
return "";
}
var chr = this.indentChar;
if ( this.HTML ) {
chr = chr.replace( /\t/g, " " ).replace( / /g, " " );
}
return new Array( this.depth + ( extra || 0 ) ).join(chr);
},
up: function( a ) {
this.depth += a || 1;
},
down: function( a ) {
this.depth -= a || 1;
},
setParser: function( name, parser ) {
this.parsers[name] = parser;
},
// The next 3 are exposed so you can use them
quote: quote,
literal: literal,
join: join,
//
depth: 1,
// This is the list of parsers, to modify them, use jsDump.setParser
parsers: {
window: "[Window]",
document: "[Document]",
error: function(error) {
return "Error(\"" + error.message + "\")";
},
unknown: "[Unknown]",
"null": "null",
"undefined": "undefined",
"function": function( fn ) {
var ret = "function",
// functions never have name in IE
name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1];
if ( name ) {
ret += " " + name;
}
ret += "( ";
ret = [ ret, QUnit.jsDump.parse( fn, "functionArgs" ), "){" ].join( "" );
return join( ret, QUnit.jsDump.parse(fn,"functionCode" ), "}" );
},
array: array,
nodelist: array,
"arguments": array,
object: function( map, stack ) {
/*jshint forin:false */
var ret = [ ], keys, key, val, i;
QUnit.jsDump.up();
keys = [];
for ( key in map ) {
keys.push( key );
}
keys.sort();
for ( i = 0; i < keys.length; i++ ) {
key = keys[ i ];
val = map[ key ];
ret.push( QUnit.jsDump.parse( key, "key" ) + ": " + QUnit.jsDump.parse( val, undefined, stack ) );
}
QUnit.jsDump.down();
return join( "{", ret, "}" );
},
node: function( node ) {
var len, i, val,
open = QUnit.jsDump.HTML ? "<" : "<",
close = QUnit.jsDump.HTML ? ">" : ">",
tag = node.nodeName.toLowerCase(),
ret = open + tag,
attrs = node.attributes;
if ( attrs ) {
for ( i = 0, len = attrs.length; i < len; i++ ) {
val = attrs[i].nodeValue;
// IE6 includes all attributes in .attributes, even ones not explicitly set.
// Those have values like undefined, null, 0, false, "" or "inherit".
if ( val && val !== "inherit" ) {
ret += " " + attrs[i].nodeName + "=" + QUnit.jsDump.parse( val, "attribute" );
}
}
}
ret += close;
// Show content of TextNode or CDATASection
if ( node.nodeType === 3 || node.nodeType === 4 ) {
ret += node.nodeValue;
}
return ret + open + "/" + tag + close;
},
// function calls it internally, it's the arguments part of the function
functionArgs: function( fn ) {
var args,
l = fn.length;
if ( !l ) {
return "";
}
args = new Array(l);
while ( l-- ) {
// 97 is 'a'
args[l] = String.fromCharCode(97+l);
}
return " " + args.join( ", " ) + " ";
},
// object calls it internally, the key part of an item in a map
key: quote,
// function calls it internally, it's the content of the function
functionCode: "[code]",
// node calls it internally, it's an html attribute value
attribute: quote,
string: quote,
date: quote,
regexp: literal,
number: literal,
"boolean": literal
},
// if true, entities are escaped ( <, >, \t, space and \n )
HTML: false,
// indentation unit
indentChar: " ",
// if true, items in a collection, are separated by a \n, else just a space.
multiline: true
};
return jsDump;
}());
/*
* Javascript Diff Algorithm
* By John Resig (http://ejohn.org/)
* Modified by Chu Alan "sprite"
*
* Released under the MIT license.
*
* More Info:
* http://ejohn.org/projects/javascript-diff-algorithm/
*
* Usage: QUnit.diff(expected, actual)
*
* QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over"
*/
QUnit.diff = (function() {
/*jshint eqeqeq:false, eqnull:true */
function diff( o, n ) {
var i,
ns = {},
os = {};
for ( i = 0; i < n.length; i++ ) {
if ( !hasOwn.call( ns, n[i] ) ) {
ns[ n[i] ] = {
rows: [],
o: null
};
}
ns[ n[i] ].rows.push( i );
}
for ( i = 0; i < o.length; i++ ) {
if ( !hasOwn.call( os, o[i] ) ) {
os[ o[i] ] = {
rows: [],
n: null
};
}
os[ o[i] ].rows.push( i );
}
for ( i in ns ) {
if ( hasOwn.call( ns, i ) ) {
if ( ns[i].rows.length === 1 && hasOwn.call( os, i ) && os[i].rows.length === 1 ) {
n[ ns[i].rows[0] ] = {
text: n[ ns[i].rows[0] ],
row: os[i].rows[0]
};
o[ os[i].rows[0] ] = {
text: o[ os[i].rows[0] ],
row: ns[i].rows[0]
};
}
}
}
for ( i = 0; i < n.length - 1; i++ ) {
if ( n[i].text != null && n[ i + 1 ].text == null && n[i].row + 1 < o.length && o[ n[i].row + 1 ].text == null &&
n[ i + 1 ] == o[ n[i].row + 1 ] ) {
n[ i + 1 ] = {
text: n[ i + 1 ],
row: n[i].row + 1
};
o[ n[i].row + 1 ] = {
text: o[ n[i].row + 1 ],
row: i + 1
};
}
}
for ( i = n.length - 1; i > 0; i-- ) {
if ( n[i].text != null && n[ i - 1 ].text == null && n[i].row > 0 && o[ n[i].row - 1 ].text == null &&
n[ i - 1 ] == o[ n[i].row - 1 ]) {
n[ i - 1 ] = {
text: n[ i - 1 ],
row: n[i].row - 1
};
o[ n[i].row - 1 ] = {
text: o[ n[i].row - 1 ],
row: i - 1
};
}
}
return {
o: o,
n: n
};
}
return function( o, n ) {
o = o.replace( /\s+$/, "" );
n = n.replace( /\s+$/, "" );
var i, pre,
str = "",
out = diff( o === "" ? [] : o.split(/\s+/), n === "" ? [] : n.split(/\s+/) ),
oSpace = o.match(/\s+/g),
nSpace = n.match(/\s+/g);
if ( oSpace == null ) {
oSpace = [ " " ];
}
else {
oSpace.push( " " );
}
if ( nSpace == null ) {
nSpace = [ " " ];
}
else {
nSpace.push( " " );
}
if ( out.n.length === 0 ) {
for ( i = 0; i < out.o.length; i++ ) {
str += "<del>" + out.o[i] + oSpace[i] + "</del>";
}
}
else {
if ( out.n[0].text == null ) {
for ( n = 0; n < out.o.length && out.o[n].text == null; n++ ) {
str += "<del>" + out.o[n] + oSpace[n] + "</del>";
}
}
for ( i = 0; i < out.n.length; i++ ) {
if (out.n[i].text == null) {
str += "<ins>" + out.n[i] + nSpace[i] + "</ins>";
}
else {
// `pre` initialized at top of scope
pre = "";
for ( n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++ ) {
pre += "<del>" + out.o[n] + oSpace[n] + "</del>";
}
str += " " + out.n[i].text + nSpace[i] + pre;
}
}
}
return str;
};
}());
// For browser, export only select globals
if ( typeof window !== "undefined" ) {
extend( window, QUnit.constructor.prototype );
window.QUnit = QUnit;
}
// For CommonJS environments, export everything
if ( typeof module !== "undefined" && module.exports ) {
module.exports = QUnit;
}
// Get a reference to the global object, like window in browsers
}( (function() {
return this;
})() ));
|
export const mailReply = {"viewBox":"0 0 1792 1792","children":[{"name":"path","attribs":{"d":"M1792 1120q0 166-127 451-3 7-10.5 24t-13.5 30-13 22q-12 17-28 17-15 0-23.5-10t-8.5-25q0-9 2.5-26.5t2.5-23.5q5-68 5-123 0-101-17.5-181t-48.5-138.5-80-101-105.5-69.5-133-42.5-154-21.5-175.5-6h-224v256q0 26-19 45t-45 19-45-19l-512-512q-19-19-19-45t19-45l512-512q19-19 45-19t45 19 19 45v256h224q713 0 875 403 53 134 53 333z"}}]};
|
var fs = require('fs');
console.log('Started reading a file');
//read the json file
fs.exists('./'+'source.json', function (exists)
{
if (exists)
{
fs.readFile('source.json', function(error, data)
{
console.log('Content of file: ' + data);
//parse the received data into json object
try
{
var studentObject = JSON.parse(data);
console.log('First Record: ', studentObject.students[0]);
//heading line for the text file
var wholeDataString = 'ID | FName | LName | Score' + '\n';
for (var i = 0; i < studentObject.students.length; i++)
{
//concat each record to a varible
wholeDataString = wholeDataString + studentObject.students[i].id + ' | ' + studentObject.students[i].fName + ' | ' + studentObject.students[i].lName + ' | ' + studentObject.students[i].score + '\n';
console.log('Students' + ': ' + studentObject.students[i].id + ' | ' + studentObject.students[i].fName + ' | ' + studentObject.students[i].lName + ' | ' + studentObject.students[i].score + '\n');
}
console.log('wholeDataString: ' + '\n' + wholeDataString);
//writting all the data at once
fs.writeFile('destination.txt', wholeDataString, function(error, data) {
console.log('Wrote to the file');
});
console.log('finished executing');
}
catch (e)
{
console.log('not a JSON');
}
});
}
else
{
console.log('source.json file does not exist');
}
});
|
var express = require('express');
var colors=require('colors');
var path=require('path');
var fs=require('fs');
var app = express();
var config=require('../configs');
app.set('host', process.env.IP || config.HOST);
app.set('port', process.env.PORT || config.PRO_PORT);
var cors=require('cors');
var logger=require('morgan');
var bodyParser=require('body-parser');
var compression=require('compression');
app.use(logger('dev'));
app.use(bodyParser.json({limit:'20mb'}));
app.use(bodyParser.urlencoded({limit:'20mb',extended:true}));
app.use(compression());
if(app.get('env')==='production'){
app.use(function(req,res,next) {
var protocol=req.get('x-forwarded-proto');
protocol=='https'?next():res.redirect('https://'+req.hostname+req.url);
});
}
app.use(express.static(path.join(__dirname, '../build')));
app.get('*',function(request,response){
response.sendFile(path.resolve(__dirname,'../build','index.html'));
});
const server=app.listen(app.get('port'),(err)=>{
if (err) {
console.log(err);
return false;
}
console.log('\n服务已启动! '.black+'✓'.green);
console.log(`\n监听端口: ${app.get('port')} ,正在构建,请稍后...`.cyan);
console.log('-----------------------------------'.grey);
console.log(` 本地地址: http://${app.get('host')}:${app.get('port')}`.magenta);
console.log('-----------------------------------'.grey);
console.log('\n按下 CTRL-C 停止服务\n'.blue);
});
|
import Ember from 'ember';
const globalParent = {};
export default Ember.Component.extend({
tagName: '',
isPopOver: true,
isOpen: false,
manual: false,
'anchor-attachment': 'bottom left',
'body-attachment': 'top left',
'body-constraints': [{
to: 'window',
attachment: 'together'
}],
bodyClassNames: null,
anchorClassNames: null,
'body-class': null,
'anchor-class': null,
_scopeParent: null,
parentPopOver: Ember.computed("_scopeParent", function() {
const parent = this.get("_scopeParent");
if (parent === globalParent) {
return null;
} else {
return parent;
}
}),
body: null,
anchor: null,
setupScopeParent: Ember.on("init", function() {
const parent = this.nearestWithProperty("isPopOver");
this.set("_scopeParent", parent || globalParent);
}),
reposition() {
this.get("body").reposition();
},
registerCurrentWhenOpened: Ember.on("didInsertElement", Ember.observer("isOpen", function() {
let current = this.get("_scopeParent").currentPopOver;
if (this.get("isOpen")) {
if (current && current !== this) {
current.send("close");
}
current = this;
} else {
if (current === this) {
current = null;
}
}
this.get("_scopeParent").currentPopOver = current;
})),
unregisterCurrentWhenClosed: Ember.on("willDestroyElement", function() {
if (this.get("_scopeParent").currentPopOver === this) {
this.get("_scopeParent").currentPopOver = null;
}
}),
actions: {
close() {
if (!this.get("manual")) {
this.set("isOpen", false);
}
this.sendAction("closed");
},
toggle() {
if (this.get("isOpen")) {
this.send("close");
} else {
this.send("open");
}
},
open() {
if (!this.get("manual")) {
this.set("isOpen", true);
}
this.sendAction("opened");
}
}
});
|
import React, {PropTypes} from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Dropdown, Text, Icon, Menu, Item } from "react-semantify";
import { Link } from "react-router";
import {japanMap } from './map/jquery.japan-map';
import ReactDOM from 'react-dom';
//var uid = localStorage.getItem(UidRef);
class Map extends React.Component {
renderMap(mapWidth, mapHeigth){
var areas = [
{code : 1, name: "Hokkaido", color: "#7f7eda", hoverColor: "#b3b2ee", prefectures: [1], description:'alguna'},
{code : 2, name: "Tohoku", color: "#759ef4", hoverColor: "#98b9ff", prefectures: [2,3,4,5,6,7], description:'otra'},
{code : 3, name: "Kanto", color: "#7ecfea", hoverColor: "#b7e5f4", prefectures: [8,9,10,11,12,13,14], description:'3'},
{code : 4, name: "Chubu", color: "#7cdc92", hoverColor: "#aceebb", prefectures: [15,16,17,18,19,20,21,22,23], description:'4'},
{code : 5, name: "Kinki", color: "#ffe966", hoverColor: "#fff19c", prefectures: [24,25,26,27,28,29,30], description:'5'},
{code : 6, name: "Chugoku", color: "#ffcc66", hoverColor: "#ffe0a3", prefectures: [31,32,33,34,35], description:'6'},
{code : 7, name: "Shikoku", color: "#fb9466", hoverColor: "#ffbb9c", prefectures: [36,37,38,39], description:'7'},
{code : 8, name: "Kyushu", color: "#ff9999", hoverColor: "#ffbdbd", prefectures: [40,41,42,43,44,45,46], description:'8'},
{code : 9, name: "Okinawa", color: "#eb98ff", hoverColor: "#f5c9ff", prefectures: [47], description:'9'}
];
$(ReactDOM.findDOMNode(this)).japanMap({
//element: ReactDOM.findDOMNode(this),
width: mapWidth,
//height: mapHeigth,
selection: "area",
areas: areas,
backgroundColor : "#f2fcff",
//borderLineColor: "#f2fcff",
borderLineWidth : 0,
lineColor : "#a0a0a0",
showsAreaName : true,
lineWidth: 0,
drawsBoxLine: true,
prefectureNameType: "short",
font : "MS Mincho",
fontSize : 15,
fontColor : "areaColor",
fontShadowColor : "black",
movesIslands : true,
onSelect : function(data){
$('.ui.small.modal').modal('show');
$('#headerModal').html(data.name);
$('#contentModal').html(data.area.description);
}
});
}
currentScreenWidth(){
return window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
}
deleteCanvasDom(){
let element = document.getElementsByTagName("canvas");
for (let index = element.length - 1; index >= 0; index--) {
element[index].parentNode.removeChild(element[index]);
}
}
componentDidMount(){
const initialScreenWidth = this.currentScreenWidth();
console.log('ini'+initialScreenWidth);
const containerWidth = (initialScreenWidth < 800) ? (initialScreenWidth-50) : (initialScreenWidth < 1000) ? 800:1000;
this.renderMap(containerWidth,0);
window.addEventListener('resize', () => {
const currentScreenWidth = this.currentScreenWidth();
if (currentScreenWidth > 1000) {
this.deleteCanvasDom();
this.renderMap(1000,0);
}
else if (currentScreenWidth >= 800 && currentScreenWidth<=1000) {
this.deleteCanvasDom();
this.renderMap(800,0);
}else if(currentScreenWidth<800){
this.deleteCanvasDom();
this.renderMap(currentScreenWidth - 50,0);
}
});
}
componentWillUnmount(){
this.deleteCanvasDom();
}
render() {
const { router } = this.context;
return (
<div className='ui grid centered container'>
<div className='column'>
<div id="map_container" ></div>
</div>
<div className="ui small modal">
<div className="header" id="headerModal">Header</div>
<div className="content" id="contentModal">
<p>contenido</p>
</div>
<div className="actions">
<div className="ui cancel button">Cancel</div>
</div>
</div>
</div>
);
}
}
Map.contextTypes = {
router: PropTypes.any
};
var mapStateProps = function(state) {
const { auth, user } = state;
return {
auth,user
};
};
export default connect(mapStateProps)(Map);
|
/***
* This file allows to control the super vessel with the LeapMotion
* @type {{}}
*/
var cats = {};
function setLeap(frame) {
frame.hands.forEach(function (hand, index) {
if (hand.screenPosition()[0] >= 700) {
target.x = 200;
} else {
target.x = -200;
}
});
}
var Cat = function () {
var cat = this;
};
cats[0] = new Cat();
|
var config = require('config');
var crypto = require('crypto');
var moment = require('moment');
var drivers = [];
config.get('drivers').forEach(function (driver) {
drivers.push(require('./driver/' + driver));
});
exports.authenticate = authenticate;
function authenticate(username, password, token) {
return findUser(username)
.then(function (result) {
if (password && result.user.password === crypto.createHash(config.get('hashAlgorithm')).update(password).digest('hex')) {
result.user.lastLogin = new Date();
result.user.accessToken = makeAccessToken(result.user.username);
result.user.clientToken = token ? token : makeClientToken(result.user.username);
return result.driver.saveUser(result.user);
}
throw new Error('Authentication is unsuccessful.');
})
.then(function (user) {
return {
accessToken: user.accessToken,
clientToken: user.clientToken,
userId: createIdFromUUID(user.id),
playerName: user.playerName
}
});
}
exports.getUserId = getUserId;
function getUserId(username) {
return findUser(username)
.then(function (result) {
return createIdFromUUID(result.user.id);
});
}
exports.refreshAccessToken = refreshAccessToken;
function refreshAccessToken(accessToken, clientToken) {
return findUser(clientToken, 'clientToken')
.then(function (result) {
if (result.user.accessToken === accessToken) {
result.user.accessToken = makeAccessToken(result.user.username);
result.user.lastLogin = new Date();
return result.driver.saveUser(result.user)
.then(function () {
return result.user.accessToken;
});
}
throw new Error('Access token refresh was unsuccessful.');
});
}
exports.isAccessTokenAnActiveSession = isAccessTokenAnActiveSession;
function isAccessTokenAnActiveSession(accessToken) {
return findUser(accessToken, 'accessToken')
.then(function (result) {
if (moment().subtract(2, 'hours').isBefore(result.user.lastLogin)) {
return;
}
throw new Error('Session inactive.');
});
}
exports.signOut = signOut;
function signOut(username, password) {
return findUser(username)
.then(function (result) {
if (password && result.user.password === crypto.createHash(config.get('hashAlgorithm')).update(password).digest("hex")) {
result.user.accessToken = undefined;
return result.driver.saveUser(result.user);
}
throw new Error('Logging out was unsuccessful.');
});
}
exports.invalidate = invalidate;
function invalidate(accessToken, clientToken) {
return findUser(accessToken, 'accessToken')
.then(function (result) {
if (!clientToken || result.user.clientToken === clientToken) {
result.user.accessToken = undefined;
return result.driver.saveUser(result.user);
}
});
}
exports.sessionJoin = sessionJoin;
function sessionJoin(accessToken, selectedProfile, serverId) {
return findUser(accessToken, 'accessToken')
.then(function (result) {
if (selectedProfile !== createIdFromUUID(result.user.id)) {
throw new Error('Invalid selected profile.');
}
result.user.serverId = serverId;
return result.driver.saveUser(result.user);
});
}
exports.sessionHasJoined = sessionHasJoined;
function sessionHasJoined(playername, serverId) {
return findUser(playername, 'playerName')
.then(function (result) {
if (serverId === result.user.serverId) {
return result.user;
}
throw new Error('ServerId mismatch.');
});
}
exports.nameToUUID = nameToUUID;
function nameToUUID(playername) {
return findUser(playername, 'playerName')
.then(function (result) {
return createIdFromUUID(result.user.id);
});
}
exports.getUserByUuid = getUserByUuid;
function getUserByUuid(uuid) {
return findUser(createUUIDFromId(uuid), 'id')
.then(function (result) {
return result.user;
});
}
function findUser(value, field) {
if (!value) {
return new Promise(function (resolve, reject) {
resolve(null);
});
}
if (!field) {
field = 'username';
}
return findUserInDriver(field, value, 0);
}
function findUserInDriver(field, value, driverId) {
return drivers[driverId].findUserBy(field, value)
.then(function (user) {
if (user) {
return {
user: user,
driver: drivers[driverId]
};
}
if (drivers.length === driverId + 1) {
throw new Error('Value not found in any of the drivers!');
}
return findUserInDriver(field, value, driverId + 1);
});
}
function makeAccessToken(username) {
return crypto.createHash('md5').update(username + 'ACCESS' + new Date().getTime() + config.get('secret')).digest('hex');
}
function makeClientToken(username) {
return crypto.createHash('md5').update(username + 'CLIENT' + new Date().getTime() + config.get('secret')).digest('hex');
}
function createIdFromUUID(uuid) {
return uuid.replace(/-/g, '');
}
function createUUIDFromId(id) {
return id.slice(0, 8) + '-' + id.slice(8, 12) + '-' + id.slice(12, 16) + '-' + id.slice(16, 20) + '-' + id.slice(20);
}
|
/*!
* jQuery JavaScript Library v3.1.1
* https://jquery.com/
*
* Includes Sizzle.js
* https://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* https://jquery.org/license
*
* Date: 2016-09-22T22:30Z
*/
"use strict";
( function( global, factory ) {
"use strict";
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 ) {
// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1
// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode
// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common
// enough that all such attempts are guarded in a try block.
"use strict";
var arr = [];
var document = window.document;
var getProto = Object.getPrototypeOf;
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 fnToString = hasOwn.toString;
var ObjectFunctionString = fnToString.call( Object );
var support = {};
function DOMEval( code, doc ) {
doc = doc || document;
var script = doc.createElement( "script" );
script.text = code;
doc.head.appendChild( script ).parentNode.removeChild( script );
}
/* global Symbol */
// Defining this global in .eslintrc.json would create a danger of using the global
// unguarded in another place, it seems safer to define global only for this module
var
version = "3.1.1",
// 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.0 only
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([a-z])/g,
// 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,
// 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 all the elements in a clean array
if ( num == null ) {
return slice.call( this );
}
// Return just the one element from the set
return num < 0 ? this[ num + this.length ] : this[ num ];
},
// 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;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
each: function( callback ) {
return jQuery.each( this, callback );
},
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();
},
// 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 ) {
// As of jQuery 3.0, isNumeric is limited to
// strings and numbers (primitives or objects)
// that can be coerced to finite numbers (gh-2662)
var type = jQuery.type( obj );
return ( type === "number" || type === "string" ) &&
// parseFloat NaNs numeric-cast false positives ("")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
!isNaN( obj - parseFloat( obj ) );
},
isPlainObject: function( obj ) {
var proto, Ctor;
// Detect obvious negatives
// Use toString instead of jQuery.type to catch host objects
if ( !obj || toString.call( obj ) !== "[object Object]" ) {
return false;
}
proto = getProto( obj );
// Objects with no prototype (e.g., `Object.create( null )`) are plain
if ( !proto ) {
return true;
}
// Objects with prototype are plain iff they were constructed by a global Object function
Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor;
return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString;
},
isEmptyObject: function( obj ) {
/* eslint-disable no-unused-vars */
// See https://github.com/eslint/eslint/issues/6125
var name;
for ( name in obj ) {
return false;
}
return true;
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
// Support: Android <=2.3 only (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 ) {
DOMEval( code );
},
// Convert dashed to camelCase; used by the css and data modules
// Support: IE <=9 - 11, Edge 12 - 13
// 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();
},
each: function( obj, callback ) {
var length, i = 0;
if ( isArrayLike( obj ) ) {
length = obj.length;
for ( ; i < length; i++ ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
} else {
for ( i in obj ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
}
return obj;
},
// Support: Android <=4.0 only
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 );
},
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
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 length, value,
i = 0,
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArrayLike( elems ) ) {
length = elems.length;
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
} );
if ( typeof Symbol === "function" ) {
jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
}
// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
function( i, name ) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
} );
function isArrayLike( obj ) {
// Support: real iOS 8.2 only (not reproducible in simulator)
// `in` check used to prevent JIT error (gh-2145)
// hasOwn isn't used here due to false negatives
// regarding Nodelist length in IE
var length = !!obj && "length" in obj && obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v2.3.3
* https://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-08-08
*/
(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;
},
// 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
// https://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
// http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+",
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + identifier + ")(?:\\((" +
// 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( "^#(" + identifier + ")" ),
"CLASS": new RegExp( "^\\.(" + identifier + ")" ),
"TAG": new RegExp( "^(" + identifier + "|[*])" ),
"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 = /[+~]/,
// 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 );
},
// CSS string/identifier serialization
// https://drafts.csswg.org/cssom/#common-serializing-idioms
rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,
fcssescape = function( ch, asCodePoint ) {
if ( asCodePoint ) {
// U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
if ( ch === "\0" ) {
return "\uFFFD";
}
// Control characters and (dependent upon position) numbers get escaped as code points
return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
}
// Other potentially-special ASCII characters get backslash-escaped
return "\\" + ch;
},
// Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function() {
setDocument();
},
disabledAncestor = addCombinator(
function( elem ) {
return elem.disabled === true && ("form" in elem || "label" in elem);
},
{ dir: "parentNode", next: "legend" }
);
// 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 m, i, elem, nid, match, groups, newSelector,
newContext = context && context.ownerDocument,
// nodeType defaults to 9, since context defaults to document
nodeType = context ? context.nodeType : 9;
results = results || [];
// Return early from calls with invalid selector or context
if ( typeof selector !== "string" || !selector ||
nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
return results;
}
// Try to shortcut find operations (as opposed to filters) in HTML documents
if ( !seed ) {
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
if ( documentIsHTML ) {
// If the selector is sufficiently simple, try using a "get*By*" DOM method
// (excepting DocumentFragment context, where the methods don't exist)
if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
// ID selector
if ( (m = match[1]) ) {
// Document context
if ( nodeType === 9 ) {
if ( (elem = context.getElementById( m )) ) {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
// Element context
} else {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( newContext && (elem = newContext.getElementById( m )) &&
contains( context, elem ) &&
elem.id === m ) {
results.push( elem );
return results;
}
}
// Type selector
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Class selector
} else if ( (m = match[3]) && support.getElementsByClassName &&
context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// Take advantage of querySelectorAll
if ( support.qsa &&
!compilerCache[ selector + " " ] &&
(!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
if ( nodeType !== 1 ) {
newContext = context;
newSelector = selector;
// qSA looks outside Element context, which is not what we want
// Thanks to Andrew Dupont for this workaround technique
// Support: IE <=8
// Exclude object elements
} else if ( context.nodeName.toLowerCase() !== "object" ) {
// Capture the context ID, setting it first if necessary
if ( (nid = context.getAttribute( "id" )) ) {
nid = nid.replace( rcssescape, fcssescape );
} else {
context.setAttribute( "id", (nid = expando) );
}
// Prefix every selector in the list
groups = tokenize( selector );
i = groups.length;
while ( i-- ) {
groups[i] = "#" + nid + " " + toSelector( groups[i] );
}
newSelector = groups.join( "," );
// Expand context for sibling selectors
newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
context;
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch ( qsaError ) {
} finally {
if ( nid === expando ) {
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 element and returns a boolean result
*/
function assert( fn ) {
var el = document.createElement("fieldset");
try {
return !!fn( el );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( el.parentNode ) {
el.parentNode.removeChild( el );
}
// release memory in IE
el = 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 = arr.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 &&
a.sourceIndex - b.sourceIndex;
// 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 :enabled/:disabled
* @param {Boolean} disabled true for :disabled; false for :enabled
*/
function createDisabledPseudo( disabled ) {
// Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
return function( elem ) {
// Only certain elements can match :enabled or :disabled
// https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
// https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
if ( "form" in elem ) {
// Check for inherited disabledness on relevant non-disabled elements:
// * listed form-associated elements in a disabled fieldset
// https://html.spec.whatwg.org/multipage/forms.html#category-listed
// https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
// * option elements in a disabled optgroup
// https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
// All such elements have a "form" property.
if ( elem.parentNode && elem.disabled === false ) {
// Option elements defer to a parent optgroup if present
if ( "label" in elem ) {
if ( "label" in elem.parentNode ) {
return elem.parentNode.disabled === disabled;
} else {
return elem.disabled === disabled;
}
}
// Support: IE 6 - 11
// Use the isDisabled shortcut property to check for disabled fieldset ancestors
return elem.isDisabled === disabled ||
// Where there is no isDisabled, check manually
/* jshint -W018 */
elem.isDisabled !== !disabled &&
disabledAncestor( elem ) === disabled;
}
return elem.disabled === disabled;
// Try to winnow out elements that can't be disabled before trusting the disabled property.
// Some victims get caught in our net (label, legend, menu, track), but it shouldn't
// even exist on them, let alone have a boolean value.
} else if ( "label" in elem ) {
return elem.disabled === disabled;
}
// Remaining elements are neither :enabled nor :disabled
return false;
};
}
/**
* 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, subWindow,
doc = node ? node.ownerDocument || node : preferredDoc;
// Return early if doc is invalid or already selected
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Update global variables
document = doc;
docElem = document.documentElement;
documentIsHTML = !isXML( document );
// Support: IE 9-11, Edge
// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
if ( preferredDoc !== document &&
(subWindow = document.defaultView) && subWindow.top !== subWindow ) {
// Support: IE 11, Edge
if ( subWindow.addEventListener ) {
subWindow.addEventListener( "unload", unloadHandler, false );
// Support: IE 9 - 10 only
} else if ( subWindow.attachEvent ) {
subWindow.attachEvent( "onunload", unloadHandler );
}
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties
// (excepting IE8 booleans)
support.attributes = assert(function( el ) {
el.className = "i";
return !el.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( el ) {
el.appendChild( document.createComment("") );
return !el.getElementsByTagName("*").length;
});
// Support: IE<9
support.getElementsByClassName = rnative.test( document.getElementsByClassName );
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programmatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( el ) {
docElem.appendChild( el ).id = expando;
return !document.getElementsByName || !document.getElementsByName( expando ).length;
});
// ID filter and find
if ( support.getById ) {
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var elem = context.getElementById( id );
return elem ? [ elem ] : [];
}
};
} else {
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;
};
};
// Support: IE 6 - 7 only
// getElementById is not reliable as a find shortcut
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var node, i, elems,
elem = context.getElementById( id );
if ( elem ) {
// Verify the id attribute
node = elem.getAttributeNode("id");
if ( node && node.value === id ) {
return [ elem ];
}
// Fall back on getElementsByName
elems = context.getElementsByName( id );
i = 0;
while ( (elem = elems[i++]) ) {
node = elem.getAttributeNode("id");
if ( node && node.value === id ) {
return [ elem ];
}
}
}
return [];
}
};
}
// 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 ( typeof context.getElementsByClassName !== "undefined" && 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 https://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( el ) {
// 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
// https://bugs.jquery.com/ticket/12359
docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" +
"<select id='" + expando + "-\r\\' 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
// https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( el.querySelectorAll("[msallowcapture^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !el.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
if ( !el.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 ( !el.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
// Support: Safari 8+, iOS 8+
// https://bugs.webkit.org/show_bug.cgi?id=136851
// In-page `selector#id sibling-combinator selector` fails
if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) {
rbuggyQSA.push(".#.+[+~]");
}
});
assert(function( el ) {
el.innerHTML = "<a href='' disabled='disabled'></a>" +
"<select disabled='disabled'><option/></select>";
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = document.createElement("input");
input.setAttribute( "type", "hidden" );
el.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( el.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 ( el.querySelectorAll(":enabled").length !== 2 ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Support: IE9-11+
// IE's :disabled selector does not pick up the children of disabled fieldsets
docElem.appendChild( el ).disabled = true;
if ( el.querySelectorAll(":disabled").length !== 2 ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
el.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( el ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( el, "*" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( el, "[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 self-exclusive
// 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 === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === document || 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 === document ? -1 :
b === document ? 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 document;
};
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 &&
!compilerCache[ expr + " " ] &&
( !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.escape = function( sel ) {
return (sel + "").replace( rcssescape, fcssescape );
};
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, uniqueCache, outerCache, node, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType,
diff = false;
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
// ...in a gzip-friendly way
node = parent;
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex && 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 ) {
uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
} else {
// Use previously-cached element index if available
if ( useCache ) {
// ...in a gzip-friendly way
node = elem;
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex;
}
// xml :nth-child(...)
// or :nth-last-child(...) or :nth(-last)?-of-type(...)
if ( diff === false ) {
// 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 ) {
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
uniqueCache[ 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": createDisabledPseudo( false ),
"disabled": createDisabledPseudo( 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,
skip = combinator.next,
key = skip || dir,
checkNonElements = base && key === "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 );
}
}
return false;
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, uniqueCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from combinator 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 ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});
if ( skip && skip === elem.nodeName.toLowerCase() ) {
elem = elem[ dir ] || elem;
} else if ( (oldCache = uniqueCache[ key ]) &&
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
uniqueCache[ key ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
return false;
};
}
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 || outermost;
}
// Add elements passing elementMatchers directly to results
// 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;
if ( !context && elem.ownerDocument !== document ) {
setDocument( elem );
xml = !documentIsHTML;
}
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context || document, 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 );
}
}
}
// `i` is now the count of elements visited above, and adding it to `matchedCount`
// makes the latter nonnegative.
matchedCount += i;
// Apply set filters to unmatched elements
// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
// no element matchers and no seed.
// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
// case, which will result in a "00" `matchedCount` that differs from `i` but is also
// numerically zero.
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 only one selector in the list and no seed
// (the latter of which guarantees us context)
if ( match.length === 1 ) {
// Reduce context if the leading compound selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
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,
!context || 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( el ) {
// Should return 1, but returns 4 (following)
return el.compareDocumentPosition( document.createElement("fieldset") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( el ) {
el.innerHTML = "<a href='#'></a>";
return el.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( el ) {
el.innerHTML = "<input/>";
el.firstChild.setAttribute( "value", "" );
return el.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( el ) {
return el.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;
// Deprecated
jQuery.expr[ ":" ] = jQuery.expr.pseudos;
jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
jQuery.escapeSelector = Sizzle.escape;
var 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;
};
var siblings = function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
};
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i );
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 ) {
return !!qualifier.call( elem, i, elem ) !== not;
} );
}
// Single element
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
} );
}
// Arraylike of elements (jQuery, arguments, Array)
if ( typeof qualifier !== "string" ) {
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) > -1 ) !== not;
} );
}
// Simple selector that can be filtered directly, removing non-Elements
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
// Complex selector, compare the two sets, removing non-Elements
qualifier = jQuery.filter( qualifier, elements );
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1;
} );
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
if ( elems.length === 1 && elem.nodeType === 1 ) {
return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [];
}
return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
} ) );
};
jQuery.fn.extend( {
find: function( selector ) {
var i, ret,
len = this.length,
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;
}
}
} ) );
}
ret = this.pushStack( [] );
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
return len > 1 ? jQuery.uniqueSort( ret ) : 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 <)
// Shortcut simple #id case for speed
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,
init = jQuery.fn.init = function( selector, context, root ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Method init() accepts an alternate rootjQuery
// so migrate can support jQuery.sub (gh-2101)
root = root || rootjQuery;
// 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 ] );
if ( elem ) {
// Inject the element directly into the jQuery object
this[ 0 ] = elem;
this.length = 1;
}
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || root ).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[ 0 ] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return root.ready !== undefined ?
root.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
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.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 = [],
targets = typeof selectors !== "string" && jQuery( selectors );
// Positional selectors never match, since there's no _selection_ context
if ( !rneedsContext.test( selectors ) ) {
for ( ; i < l; i++ ) {
for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && ( targets ?
targets.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.uniqueSort( 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.uniqueSort(
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 dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return siblings( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return siblings( 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.uniqueSort( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
} );
var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g );
// Convert String-formatted options into Object-formatted ones
function createOptions( options ) {
var object = {};
jQuery.each( options.match( rnothtmlwhite ) || [], 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 event 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" ?
createOptions( options ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value for non-forgettable lists
memory,
// Flag to know if list was already fired
fired,
// Flag to prevent firing
locked,
// Actual callback list
list = [],
// Queue of execution data for repeatable lists
queue = [],
// Index of currently firing callback (modified by add/remove as needed)
firingIndex = -1,
// Fire callbacks
fire = function() {
// Enforce single-firing
locked = options.once;
// Execute callbacks for all pending executions,
// respecting firingIndex overrides and runtime changes
fired = firing = true;
for ( ; queue.length; firingIndex = -1 ) {
memory = queue.shift();
while ( ++firingIndex < list.length ) {
// Run callback and check for early termination
if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
options.stopOnFalse ) {
// Jump to end and forget the data so .add doesn't re-fire
firingIndex = list.length;
memory = false;
}
}
}
// Forget the data if we're done with it
if ( !options.memory ) {
memory = false;
}
firing = false;
// Clean up if we're done firing for good
if ( locked ) {
// Keep an empty list if we have data for future add calls
if ( memory ) {
list = [];
// Otherwise, this object is spent
} else {
list = "";
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// If we have memory from a past run, we should fire after adding
if ( memory && !firing ) {
firingIndex = list.length - 1;
queue.push( memory );
}
( function add( args ) {
jQuery.each( args, function( _, arg ) {
if ( jQuery.isFunction( arg ) ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) {
// Inspect recursively
add( arg );
}
} );
} )( arguments );
if ( memory && !firing ) {
fire();
}
}
return this;
},
// Remove a callback from the list
remove: function() {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
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.length > 0;
},
// Remove all callbacks from the list
empty: function() {
if ( list ) {
list = [];
}
return this;
},
// Disable .fire and .add
// Abort any current/pending executions
// Clear all callbacks and values
disable: function() {
locked = queue = [];
list = memory = "";
return this;
},
disabled: function() {
return !list;
},
// Disable .fire
// Also disable .add unless we have memory (since it would have no effect)
// Abort any pending executions
lock: function() {
locked = queue = [];
if ( !memory && !firing ) {
list = memory = "";
}
return this;
},
locked: function() {
return !!locked;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( !locked ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
queue.push( args );
if ( !firing ) {
fire();
}
}
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;
};
function Identity( v ) {
return v;
}
function Thrower( ex ) {
throw ex;
}
function adoptValue( value, resolve, reject ) {
var method;
try {
// Check for promise aspect first to privilege synchronous behavior
if ( value && jQuery.isFunction( ( method = value.promise ) ) ) {
method.call( value ).done( resolve ).fail( reject );
// Other thenables
} else if ( value && jQuery.isFunction( ( method = value.then ) ) ) {
method.call( value, resolve, reject );
// Other non-thenables
} else {
// Support: Android 4.0 only
// Strict mode functions invoked without .call/.apply get global-object context
resolve.call( undefined, value );
}
// For Promises/A+, convert exceptions into rejections
// Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in
// Deferred#then to conditionally suppress rejection.
} catch ( value ) {
// Support: Android 4.0 only
// Strict mode functions invoked without .call/.apply get global-object context
reject.call( undefined, value );
}
}
jQuery.extend( {
Deferred: function( func ) {
var tuples = [
// action, add listener, callbacks,
// ... .then handlers, argument index, [final state]
[ "notify", "progress", jQuery.Callbacks( "memory" ),
jQuery.Callbacks( "memory" ), 2 ],
[ "resolve", "done", jQuery.Callbacks( "once memory" ),
jQuery.Callbacks( "once memory" ), 0, "resolved" ],
[ "reject", "fail", jQuery.Callbacks( "once memory" ),
jQuery.Callbacks( "once memory" ), 1, "rejected" ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
"catch": function( fn ) {
return promise.then( null, fn );
},
// Keep pipe for back-compat
pipe: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred( function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
// Map tuples (progress, done, fail) to arguments (done, fail, progress)
var fn = jQuery.isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ];
// deferred.progress(function() { bind to newDefer or newDefer.notify })
// deferred.done(function() { bind to newDefer or newDefer.resolve })
// deferred.fail(function() { bind to newDefer or newDefer.reject })
deferred[ tuple[ 1 ] ]( function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.progress( newDefer.notify )
.done( newDefer.resolve )
.fail( newDefer.reject );
} else {
newDefer[ tuple[ 0 ] + "With" ](
this,
fn ? [ returned ] : arguments
);
}
} );
} );
fns = null;
} ).promise();
},
then: function( onFulfilled, onRejected, onProgress ) {
var maxDepth = 0;
function resolve( depth, deferred, handler, special ) {
return function() {
var that = this,
args = arguments,
mightThrow = function() {
var returned, then;
// Support: Promises/A+ section 2.3.3.3.3
// https://promisesaplus.com/#point-59
// Ignore double-resolution attempts
if ( depth < maxDepth ) {
return;
}
returned = handler.apply( that, args );
// Support: Promises/A+ section 2.3.1
// https://promisesaplus.com/#point-48
if ( returned === deferred.promise() ) {
throw new TypeError( "Thenable self-resolution" );
}
// Support: Promises/A+ sections 2.3.3.1, 3.5
// https://promisesaplus.com/#point-54
// https://promisesaplus.com/#point-75
// Retrieve `then` only once
then = returned &&
// Support: Promises/A+ section 2.3.4
// https://promisesaplus.com/#point-64
// Only check objects and functions for thenability
( typeof returned === "object" ||
typeof returned === "function" ) &&
returned.then;
// Handle a returned thenable
if ( jQuery.isFunction( then ) ) {
// Special processors (notify) just wait for resolution
if ( special ) {
then.call(
returned,
resolve( maxDepth, deferred, Identity, special ),
resolve( maxDepth, deferred, Thrower, special )
);
// Normal processors (resolve) also hook into progress
} else {
// ...and disregard older resolution values
maxDepth++;
then.call(
returned,
resolve( maxDepth, deferred, Identity, special ),
resolve( maxDepth, deferred, Thrower, special ),
resolve( maxDepth, deferred, Identity,
deferred.notifyWith )
);
}
// Handle all other returned values
} else {
// Only substitute handlers pass on context
// and multiple values (non-spec behavior)
if ( handler !== Identity ) {
that = undefined;
args = [ returned ];
}
// Process the value(s)
// Default process is resolve
( special || deferred.resolveWith )( that, args );
}
},
// Only normal processors (resolve) catch and reject exceptions
process = special ?
mightThrow :
function() {
try {
mightThrow();
} catch ( e ) {
if ( jQuery.Deferred.exceptionHook ) {
jQuery.Deferred.exceptionHook( e,
process.stackTrace );
}
// Support: Promises/A+ section 2.3.3.3.4.1
// https://promisesaplus.com/#point-61
// Ignore post-resolution exceptions
if ( depth + 1 >= maxDepth ) {
// Only substitute handlers pass on context
// and multiple values (non-spec behavior)
if ( handler !== Thrower ) {
that = undefined;
args = [ e ];
}
deferred.rejectWith( that, args );
}
}
};
// Support: Promises/A+ section 2.3.3.3.1
// https://promisesaplus.com/#point-57
// Re-resolve promises immediately to dodge false rejection from
// subsequent errors
if ( depth ) {
process();
} else {
// Call an optional hook to record the stack, in case of exception
// since it's otherwise lost when execution goes async
if ( jQuery.Deferred.getStackHook ) {
process.stackTrace = jQuery.Deferred.getStackHook();
}
window.setTimeout( process );
}
};
}
return jQuery.Deferred( function( newDefer ) {
// progress_handlers.add( ... )
tuples[ 0 ][ 3 ].add(
resolve(
0,
newDefer,
jQuery.isFunction( onProgress ) ?
onProgress :
Identity,
newDefer.notifyWith
)
);
// fulfilled_handlers.add( ... )
tuples[ 1 ][ 3 ].add(
resolve(
0,
newDefer,
jQuery.isFunction( onFulfilled ) ?
onFulfilled :
Identity
)
);
// rejected_handlers.add( ... )
tuples[ 2 ][ 3 ].add(
resolve(
0,
newDefer,
jQuery.isFunction( onRejected ) ?
onRejected :
Thrower
)
);
} ).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 = {};
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 5 ];
// promise.progress = list.add
// promise.done = list.add
// promise.fail = list.add
promise[ tuple[ 1 ] ] = list.add;
// Handle state
if ( stateString ) {
list.add(
function() {
// state = "resolved" (i.e., fulfilled)
// state = "rejected"
state = stateString;
},
// rejected_callbacks.disable
// fulfilled_callbacks.disable
tuples[ 3 - i ][ 2 ].disable,
// progress_callbacks.lock
tuples[ 0 ][ 2 ].lock
);
}
// progress_handlers.fire
// fulfilled_handlers.fire
// rejected_handlers.fire
list.add( tuple[ 3 ].fire );
// deferred.notify = function() { deferred.notifyWith(...) }
// deferred.resolve = function() { deferred.resolveWith(...) }
// deferred.reject = function() { deferred.rejectWith(...) }
deferred[ tuple[ 0 ] ] = function() {
deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments );
return this;
};
// deferred.notifyWith = list.fireWith
// deferred.resolveWith = list.fireWith
// deferred.rejectWith = list.fireWith
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( singleValue ) {
var
// count of uncompleted subordinates
remaining = arguments.length,
// count of unprocessed arguments
i = remaining,
// subordinate fulfillment data
resolveContexts = Array( i ),
resolveValues = slice.call( arguments ),
// the master Deferred
master = jQuery.Deferred(),
// subordinate callback factory
updateFunc = function( i ) {
return function( value ) {
resolveContexts[ i ] = this;
resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( !( --remaining ) ) {
master.resolveWith( resolveContexts, resolveValues );
}
};
};
// Single- and empty arguments are adopted like Promise.resolve
if ( remaining <= 1 ) {
adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject );
// Use .then() to unwrap secondary thenables (cf. gh-3000)
if ( master.state() === "pending" ||
jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) {
return master.then();
}
}
// Multiple arguments are aggregated like Promise.all array elements
while ( i-- ) {
adoptValue( resolveValues[ i ], updateFunc( i ), master.reject );
}
return master.promise();
}
} );
// These usually indicate a programmer mistake during development,
// warn about them ASAP rather than swallowing them by default.
var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;
jQuery.Deferred.exceptionHook = function( error, stack ) {
// Support: IE 8 - 9 only
// Console exists when dev tools are open, which can happen at any time
if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) {
window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack );
}
};
jQuery.readyException = function( error ) {
window.setTimeout( function() {
throw error;
} );
};
// The deferred used on DOM ready
var readyList = jQuery.Deferred();
jQuery.fn.ready = function( fn ) {
readyList
.then( fn )
// Wrap jQuery.readyException in a function so that the lookup
// happens at the time of error handling instead of callback
// registration.
.catch( function( error ) {
jQuery.readyException( error );
} );
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 event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
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 event 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 ] );
}
} );
jQuery.ready.then = readyList.then;
// The ready event handler and self cleanup method
function completed() {
document.removeEventListener( "DOMContentLoaded", completed );
window.removeEventListener( "load", completed );
jQuery.ready();
}
// Catch cases where $(document).ready() is called
// after the browser event has already occurred.
// Support: IE <=9 - 10 only
// Older IE sometimes signals "interactive" too soon
if ( document.readyState === "complete" ||
( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
window.setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed );
}
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var 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 ) {
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 ) )
);
}
}
}
if ( chainable ) {
return elems;
}
// Gets
if ( bulk ) {
return fn.call( elems );
}
return len ? fn( elems[ 0 ], key ) : emptyGet;
};
var acceptData = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};
function Data() {
this.expando = jQuery.expando + Data.uid++;
}
Data.uid = 1;
Data.prototype = {
cache: function( owner ) {
// Check if the owner object already has a cache
var value = owner[ this.expando ];
// If not, create one
if ( !value ) {
value = {};
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return an empty object.
if ( acceptData( owner ) ) {
// If it is a node unlikely to be stringify-ed or looped over
// use plain assignment
if ( owner.nodeType ) {
owner[ this.expando ] = value;
// Otherwise secure it in a non-enumerable property
// configurable must be true to allow the property to be
// deleted when data is removed
} else {
Object.defineProperty( owner, this.expando, {
value: value,
configurable: true
} );
}
}
}
return value;
},
set: function( owner, data, value ) {
var prop,
cache = this.cache( owner );
// Handle: [ owner, key, value ] args
// Always use camelCase key (gh-2257)
if ( typeof data === "string" ) {
cache[ jQuery.camelCase( data ) ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Copy the properties one-by-one to the cache object
for ( prop in data ) {
cache[ jQuery.camelCase( prop ) ] = data[ prop ];
}
}
return cache;
},
get: function( owner, key ) {
return key === undefined ?
this.cache( owner ) :
// Always use camelCase key (gh-2257)
owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ];
},
access: function( owner, key, value ) {
// 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 ) ) {
return this.get( owner, 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,
cache = owner[ this.expando ];
if ( cache === undefined ) {
return;
}
if ( key !== undefined ) {
// Support array or space separated string of keys
if ( jQuery.isArray( key ) ) {
// If key is an array of keys...
// We always set camelCase keys, so remove that.
key = key.map( jQuery.camelCase );
} else {
key = jQuery.camelCase( key );
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
key = key in cache ?
[ key ] :
( key.match( rnothtmlwhite ) || [] );
}
i = key.length;
while ( i-- ) {
delete cache[ key[ i ] ];
}
}
// Remove the expando if there's no more data
if ( key === undefined || jQuery.isEmptyObject( cache ) ) {
// Support: Chrome <=35 - 45
// Webkit & Blink performance suffers when deleting properties
// from DOM nodes, so set to undefined instead
// https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
if ( owner.nodeType ) {
owner[ this.expando ] = undefined;
} else {
delete owner[ this.expando ];
}
}
},
hasData: function( owner ) {
var cache = owner[ this.expando ];
return cache !== undefined && !jQuery.isEmptyObject( cache );
}
};
var dataPriv = new Data();
var dataUser = 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 getData( data ) {
if ( data === "true" ) {
return true;
}
if ( data === "false" ) {
return false;
}
if ( data === "null" ) {
return null;
}
// Only convert to a number if it doesn't change the string
if ( data === +data + "" ) {
return +data;
}
if ( rbrace.test( data ) ) {
return JSON.parse( data );
}
return data;
}
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, "-$&" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = getData( data );
} catch ( e ) {}
// Make sure we set the data so it isn't changed later
dataUser.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend( {
hasData: function( elem ) {
return dataUser.hasData( elem ) || dataPriv.hasData( elem );
},
data: function( elem, name, data ) {
return dataUser.access( elem, name, data );
},
removeData: function( elem, name ) {
dataUser.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to dataPriv methods, these can be deprecated.
_data: function( elem, name, data ) {
return dataPriv.access( elem, name, data );
},
_removeData: function( elem, name ) {
dataPriv.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 = dataUser.get( elem );
if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE 11 only
// 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 ] );
}
}
}
dataPriv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each( function() {
dataUser.set( this, key );
} );
}
return access( this, function( value ) {
var data;
// 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
// The key will always be camelCased in Data
data = dataUser.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, key );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each( function() {
// We always store the camelCased key
dataUser.set( this, key, value );
} );
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each( function() {
dataUser.remove( this, key );
} );
}
} );
jQuery.extend( {
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = dataPriv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = dataPriv.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 dataPriv.get( elem, key ) || dataPriv.access( elem, key, {
empty: jQuery.Callbacks( "once memory" ).add( function() {
dataPriv.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 = dataPriv.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 rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHiddenWithinTree = function( elem, el ) {
// isHiddenWithinTree might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
// Inline style trumps all
return elem.style.display === "none" ||
elem.style.display === "" &&
// Otherwise, check computed style
// Support: Firefox <=43 - 45
// Disconnected elements can have computed display: none, so first confirm that elem is
// in the document.
jQuery.contains( elem.ownerDocument, elem ) &&
jQuery.css( elem, "display" ) === "none";
};
var 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;
};
function adjustCSS( elem, prop, valueParts, tween ) {
var adjusted,
scale = 1,
maxIterations = 20,
currentValue = tween ?
function() {
return tween.cur();
} :
function() {
return jQuery.css( elem, prop, "" );
},
initial = currentValue(),
unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&
rcssNum.exec( jQuery.css( elem, prop ) );
if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || initialInUnit[ 3 ];
// Make sure we update the tween properties later on
valueParts = valueParts || [];
// Iteratively approximate from a nonzero starting point
initialInUnit = +initial || 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
initialInUnit = initialInUnit / scale;
jQuery.style( elem, prop, initialInUnit + 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 = currentValue() / initial ) && scale !== 1 && --maxIterations
);
}
if ( valueParts ) {
initialInUnit = +initialInUnit || +initial || 0;
// Apply relative offset (+=/-=) if specified
adjusted = valueParts[ 1 ] ?
initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
+valueParts[ 2 ];
if ( tween ) {
tween.unit = unit;
tween.start = initialInUnit;
tween.end = adjusted;
}
}
return adjusted;
}
var defaultDisplayMap = {};
function getDefaultDisplay( elem ) {
var temp,
doc = elem.ownerDocument,
nodeName = elem.nodeName,
display = defaultDisplayMap[ nodeName ];
if ( display ) {
return display;
}
temp = doc.body.appendChild( doc.createElement( nodeName ) );
display = jQuery.css( temp, "display" );
temp.parentNode.removeChild( temp );
if ( display === "none" ) {
display = "block";
}
defaultDisplayMap[ nodeName ] = display;
return display;
}
function showHide( elements, show ) {
var display, elem,
values = [],
index = 0,
length = elements.length;
// Determine new display value for elements that need to change
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
display = elem.style.display;
if ( show ) {
// Since we force visibility upon cascade-hidden elements, an immediate (and slow)
// check is required in this first loop unless we have a nonempty display value (either
// inline or about-to-be-restored)
if ( display === "none" ) {
values[ index ] = dataPriv.get( elem, "display" ) || null;
if ( !values[ index ] ) {
elem.style.display = "";
}
}
if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) {
values[ index ] = getDefaultDisplay( elem );
}
} else {
if ( display !== "none" ) {
values[ index ] = "none";
// Remember what we're overwriting
dataPriv.set( elem, "display", display );
}
}
}
// Set the display of the elements in a second loop to avoid constant reflow
for ( index = 0; index < length; index++ ) {
if ( values[ index ] != null ) {
elements[ index ].style.display = values[ index ];
}
}
return elements;
}
jQuery.fn.extend( {
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 ( isHiddenWithinTree( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
} );
}
} );
var rcheckableType = ( /^(?:checkbox|radio)$/i );
var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i );
var rscriptType = ( /^$|\/(?:java|ecma)script/i );
// We have to close these tags to support XHTML (#13200)
var wrapMap = {
// Support: IE <=9 only
option: [ 1, "<select multiple='multiple'>", "</select>" ],
// XHTML parsers do not magically insert elements in the
// same way that tag soup parsers do. So we cannot shorten
// this by omitting <tbody> or other required elements.
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: IE <=9 only
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function getAll( context, tag ) {
// Support: IE <=9 - 11 only
// Use typeof to avoid zero-argument method invocation on host objects (#15151)
var ret;
if ( typeof context.getElementsByTagName !== "undefined" ) {
ret = context.getElementsByTagName( tag || "*" );
} else if ( typeof context.querySelectorAll !== "undefined" ) {
ret = context.querySelectorAll( tag || "*" );
} else {
ret = [];
}
if ( tag === undefined || tag && jQuery.nodeName( context, tag ) ) {
return jQuery.merge( [ context ], ret );
}
return ret;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
dataPriv.set(
elems[ i ],
"globalEval",
!refElements || dataPriv.get( refElements[ i ], "globalEval" )
);
}
}
var rhtml = /<|&#?\w+;/;
function buildFragment( elems, context, scripts, selection, ignored ) {
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: Android <=4.0 only, PhantomJS 1 only
// 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 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ];
// Descend through wrappers to the right content
j = wrap[ 0 ];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Support: Android <=4.0 only, PhantomJS 1 only
// 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++ ] ) ) {
// Skip elements already in the context collection (trac-4087)
if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
if ( ignored ) {
ignored.push( elem );
}
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;
}
( function() {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild( document.createElement( "div" ) ),
input = document.createElement( "input" );
// Support: Android 4.0 - 4.3 only
// 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: Android <=4.1 only
// Older WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE <=11 only
// Make sure textarea (and checkbox) defaultValue is properly cloned
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
} )();
var documentElement = document.documentElement;
var
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
// Support: IE <=9 only
// See #13393 for more info
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
function on( elem, types, selector, data, fn, 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 ) {
on( elem, type, selector, data, types[ type ], one );
}
return elem;
}
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 elem;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event 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 elem.each( function() {
jQuery.event.add( this, types, fn, data, selector );
} );
}
/*
* 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 = dataPriv.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;
}
// Ensure that invalid selectors throw exceptions at attach time
// Evaluate against documentElement in case elem is a non-element node (e.g., document)
if ( selector ) {
jQuery.find.matchesSelector( documentElement, 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 event 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 event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
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 event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event 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 event 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 event 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 );
}
}
}
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 event optimization
jQuery.event.global[ type ] = true;
}
},
// Detach an event 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 = dataPriv.hasData( elem ) && dataPriv.get( elem );
if ( !elemData || !( events = elemData.events ) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
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 event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event 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 data and the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
dataPriv.remove( elem, "handle events" );
}
},
dispatch: function( nativeEvent ) {
// Make a writable jQuery.Event from the native event object
var event = jQuery.event.fix( nativeEvent );
var i, j, ret, matched, handleObj, handlerQueue,
args = new Array( arguments.length ),
handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[ 0 ] = event;
for ( i = 1; i < arguments.length; i++ ) {
args[ i ] = arguments[ i ];
}
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 event must either 1) have no namespace, or 2) have namespace(s)
// a subset or equal to those in the bound event (both can have no namespace).
if ( !event.rnamespace || event.rnamespace.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, handleObj, sel, matchedHandlers, matchedSelectors,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
if ( delegateCount &&
// Support: IE <=9
// Black-hole SVG <use> instance trees (trac-13180)
cur.nodeType &&
// Support: Firefox <=42
// Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861)
// https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click
// Support: IE 11 only
// ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343)
!( event.type === "click" && event.button >= 1 ) ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) {
matchedHandlers = [];
matchedSelectors = {};
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matchedSelectors[ sel ] === undefined ) {
matchedSelectors[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) > -1 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matchedSelectors[ sel ] ) {
matchedHandlers.push( handleObj );
}
}
if ( matchedHandlers.length ) {
handlerQueue.push( { elem: cur, handlers: matchedHandlers } );
}
}
}
}
// Add the remaining (directly-bound) handlers
cur = this;
if ( delegateCount < handlers.length ) {
handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } );
}
return handlerQueue;
},
addProp: function( name, hook ) {
Object.defineProperty( jQuery.Event.prototype, name, {
enumerable: true,
configurable: true,
get: jQuery.isFunction( hook ) ?
function() {
if ( this.originalEvent ) {
return hook( this.originalEvent );
}
} :
function() {
if ( this.originalEvent ) {
return this.originalEvent[ name ];
}
},
set: function( value ) {
Object.defineProperty( this, name, {
enumerable: true,
configurable: true,
writable: true,
value: value
} );
}
} );
},
fix: function( originalEvent ) {
return originalEvent[ jQuery.expando ] ?
originalEvent :
new jQuery.Event( originalEvent );
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event 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 event 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;
}
}
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
// This "if" is needed for plain objects
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle );
}
};
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 <=2.3 only
src.returnValue === false ?
returnTrue :
returnFalse;
// Create target properties
// Support: Safari <=6 - 7 only
// Target should not be a text node (#504, #13143)
this.target = ( src.target && src.target.nodeType === 3 ) ?
src.target.parentNode :
src.target;
this.currentTarget = src.currentTarget;
this.relatedTarget = src.relatedTarget;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event 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
// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
constructor: jQuery.Event,
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
isSimulated: false,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && !this.isSimulated ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && !this.isSimulated ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && !this.isSimulated ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Includes all common event props including KeyEvent and MouseEvent specific props
jQuery.each( {
altKey: true,
bubbles: true,
cancelable: true,
changedTouches: true,
ctrlKey: true,
detail: true,
eventPhase: true,
metaKey: true,
pageX: true,
pageY: true,
shiftKey: true,
view: true,
"char": true,
charCode: true,
key: true,
keyCode: true,
button: true,
buttons: true,
clientX: true,
clientY: true,
offsetX: true,
offsetY: true,
pointerId: true,
pointerType: true,
screenX: true,
screenY: true,
targetTouches: true,
toElement: true,
touches: true,
which: function( event ) {
var button = event.button;
// Add which for key events
if ( event.which == null && rkeyEvent.test( event.type ) ) {
return event.charCode != null ? event.charCode : event.keyCode;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) {
if ( button & 1 ) {
return 1;
}
if ( button & 2 ) {
return 3;
}
if ( button & 4 ) {
return 2;
}
return 0;
}
return event.which;
}
}, jQuery.event.addProp );
// Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
// https://bugs.chromium.org/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
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 mouseenter/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;
}
};
} );
jQuery.fn.extend( {
on: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn );
},
one: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) 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 );
} );
}
} );
var
/* eslint-disable max-len */
// See https://github.com/eslint/eslint/issues/3229
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,
/* eslint-enable */
// Support: IE <=10 - 11, Edge 12 - 13
// In IE/Edge using regex groups here causes severe slowdowns.
// See https://connect.microsoft.com/IE/feedback/details/1736512/
rnoInnerhtml = /<script|<style|<link/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;
function manipulationTarget( elem, content ) {
if ( jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {
return elem.getElementsByTagName( "tbody" )[ 0 ] || elem;
}
return 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;
}
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 ( dataPriv.hasData( src ) ) {
pdataOld = dataPriv.access( src );
pdataCur = dataPriv.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 ( dataUser.hasData( src ) ) {
udataOld = dataUser.access( src );
udataCur = jQuery.extend( {}, udataOld );
dataUser.set( dest, udataCur );
}
}
// 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;
}
}
function domManip( collection, args, callback, ignored ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = collection.length,
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 collection.each( function( index ) {
var self = collection.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
domManip( self, args, callback, ignored );
} );
}
if ( l ) {
fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
// Require either new content or an interest in ignored elements to invoke the callback
if ( first || ignored ) {
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: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( collection[ 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 || "" ) &&
!dataPriv.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 {
DOMEval( node.textContent.replace( rcleanScript, "" ), doc );
}
}
}
}
}
}
return collection;
}
function remove( elem, selector, keepData ) {
var node,
nodes = selector ? jQuery.filter( selector, elem ) : elem,
i = 0;
for ( ; ( node = nodes[ i ] ) != null; i++ ) {
if ( !keepData && node.nodeType === 1 ) {
jQuery.cleanData( getAll( node ) );
}
if ( node.parentNode ) {
if ( keepData && jQuery.contains( node.ownerDocument, node ) ) {
setGlobalEval( getAll( node, "script" ) );
}
node.parentNode.removeChild( node );
}
}
return elem;
}
jQuery.extend( {
htmlPrefilter: function( html ) {
return html.replace( rxhtmlTag, "<$1></$2>" );
},
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: https://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;
},
cleanData: function( elems ) {
var data, elem, type,
special = jQuery.event.special,
i = 0;
for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) {
if ( acceptData( elem ) ) {
if ( ( data = elem[ dataPriv.expando ] ) ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Support: Chrome <=35 - 45+
// Assign undefined instead of using delete, see Data#remove
elem[ dataPriv.expando ] = undefined;
}
if ( elem[ dataUser.expando ] ) {
// Support: Chrome <=35 - 45+
// Assign undefined instead of using delete, see Data#remove
elem[ dataUser.expando ] = undefined;
}
}
}
}
} );
jQuery.fn.extend( {
detach: function( selector ) {
return remove( this, selector, true );
},
remove: function( selector ) {
return remove( this, selector );
},
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 domManip( this, arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
} );
},
prepend: function() {
return domManip( this, 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 domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
} );
},
after: function() {
return domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
} );
},
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 = jQuery.htmlPrefilter( value );
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 ignored = [];
// Make the changes, replacing each non-ignored context element with the new content
return domManip( this, arguments, function( elem ) {
var parent = this.parentNode;
if ( jQuery.inArray( this, ignored ) < 0 ) {
jQuery.cleanData( getAll( this ) );
if ( parent ) {
parent.replaceChild( elem, this );
}
}
// Force callback invocation
}, ignored );
}
} );
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: Android <=4.0 only, PhantomJS 1 only
// .get() because push.apply(_, arraylike) throws on ancient WebKit
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
} );
var rmargin = ( /^margin/ );
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles = function( elem ) {
// Support: IE <=11 only, Firefox <=30 (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
var view = elem.ownerDocument.defaultView;
if ( !view || !view.opener ) {
view = window;
}
return view.getComputedStyle( elem );
};
( function() {
// Executing both pixelPosition & boxSizingReliable tests require only one layout
// so they're executed at the same time to save the second computation.
function computeStyleTests() {
// This is a singleton, we need to execute it only once
if ( !div ) {
return;
}
div.style.cssText =
"box-sizing:border-box;" +
"position:relative;display:block;" +
"margin:auto;border:1px;padding:1px;" +
"top:1%;width:50%";
div.innerHTML = "";
documentElement.appendChild( container );
var divStyle = window.getComputedStyle( div );
pixelPositionVal = divStyle.top !== "1%";
// Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
reliableMarginLeftVal = divStyle.marginLeft === "2px";
boxSizingReliableVal = divStyle.width === "4px";
// Support: Android 4.0 - 4.3 only
// Some styles come back with percentage values, even though they shouldn't
div.style.marginRight = "50%";
pixelMarginRightVal = divStyle.marginRight === "4px";
documentElement.removeChild( container );
// Nullify the div so it wouldn't be stored in the memory and
// it will also be a sign that checks already performed
div = null;
}
var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal,
container = document.createElement( "div" ),
div = document.createElement( "div" );
// Finish early in limited (non-browser) environments
if ( !div.style ) {
return;
}
// Support: IE <=9 - 11 only
// 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:8px;height:0;top:0;left:-9999px;" +
"padding:0;margin-top:1px;position:absolute";
container.appendChild( div );
jQuery.extend( support, {
pixelPosition: function() {
computeStyleTests();
return pixelPositionVal;
},
boxSizingReliable: function() {
computeStyleTests();
return boxSizingReliableVal;
},
pixelMarginRight: function() {
computeStyleTests();
return pixelMarginRightVal;
},
reliableMarginLeft: function() {
computeStyleTests();
return reliableMarginLeftVal;
}
} );
} )();
function curCSS( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// Support: IE <=9 only
// getPropertyValue is only needed for .css('filter') (#12537)
if ( computed ) {
ret = computed.getPropertyValue( name ) || computed[ name ];
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Android Browser returns percentage for some values,
// but width seems to be reliably pixels.
// This is against the CSSOM draft spec:
// https://drafts.csswg.org/cssom/#resolved-values
if ( !support.pixelMarginRight() && 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 <=9 - 11 only
// 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 );
}
};
}
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]).+)/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "Moz", "ms" ],
emptyStyle = document.createElement( "div" ).style;
// Return a css property mapped to a potentially vendor prefixed property
function vendorPropName( name ) {
// Shortcut for names that are not vendor prefixed
if ( name in emptyStyle ) {
return name;
}
// Check for vendor prefixed names
var capName = name[ 0 ].toUpperCase() + name.slice( 1 ),
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in emptyStyle ) {
return name;
}
}
}
function setPositiveNumber( elem, value, subtract ) {
// Any relative (+/-) values have already been
// normalized at this point
var matches = rcssNum.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i,
val = 0;
// If we already have the right measurement, avoid augmentation
if ( extra === ( isBorderBox ? "border" : "content" ) ) {
i = 4;
// Otherwise initialize for horizontal or vertical properties
} else {
i = name === "width" ? 1 : 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 val,
valueIsBorderBox = true,
styles = getStyles( elem ),
isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// Support: IE <=11 only
// Running getBoundingClientRect on a disconnected node
// in IE throws an error.
if ( elem.getClientRects().length ) {
val = elem.getBoundingClientRect()[ name ];
}
// 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";
}
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: {
"animationIterationCount": true,
"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( origName ) || 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 = rcssNum.exec( value ) ) && ret[ 1 ] ) {
value = adjustCSS( elem, name, ret );
// 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 was passed in, add the unit (except for certain CSS properties)
if ( type === "number" ) {
value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
}
// 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( origName ) || 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 || isFinite( 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" ) ) &&
// Support: Safari 8+
// Table columns in Safari have non-zero offsetWidth & zero
// getBoundingClientRect().width unless display is changed.
// Support: IE <=11 only
// Running getBoundingClientRect on a disconnected node
// in IE throws an error.
( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ?
swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
} ) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var matches,
styles = extra && getStyles( elem ),
subtract = extra && augmentWidthOrHeight(
elem,
name,
extra,
jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
);
// Convert to pixels if value adjustment is needed
if ( subtract && ( matches = rcssNum.exec( value ) ) &&
( matches[ 3 ] || "px" ) !== "px" ) {
elem.style[ name ] = value;
value = jQuery.css( elem, name );
}
return setPositiveNumber( elem, value, subtract );
}
};
} );
jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
function( elem, computed ) {
if ( computed ) {
return ( parseFloat( curCSS( elem, "marginLeft" ) ) ||
elem.getBoundingClientRect().left -
swap( elem, { marginLeft: 0 }, function() {
return elem.getBoundingClientRect().left;
} )
) + "px";
}
}
);
// 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 );
}
} );
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 || jQuery.easing._default;
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;
// Use a property on the element directly when it is not a DOM element,
// or when there is no matching style property that exists.
if ( tween.elem.nodeType !== 1 ||
tween.elem[ tween.prop ] != null && 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.nodeType === 1 &&
( 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: IE <=9 only
// 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;
},
_default: "swing"
};
jQuery.fx = Tween.prototype.init;
// Back compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rrun = /queueHooks$/;
function raf() {
if ( timerId ) {
window.requestAnimationFrame( raf );
jQuery.fx.tick();
}
}
// Animations created synchronously will run synchronously
function createFxNow() {
window.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 = ( Animation.tweeners[ prop ] || [] ).concat( Animation.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 ) {
var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display,
isBox = "width" in props || "height" in props,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHiddenWithinTree( elem ),
dataShow = dataPriv.get( elem, "fxshow" );
// Queue-skipping animations hijack the fx hooks
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();
}
} );
} );
}
// Detect show/hide animations
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.test( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// Pretend to be hidden if this is a "show" and
// there is still data from a stopped show/hide
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
// Ignore all other no-op show/hide data
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
}
}
// Bail out if this is a no-op like .hide().hide()
propTween = !jQuery.isEmptyObject( props );
if ( !propTween && jQuery.isEmptyObject( orig ) ) {
return;
}
// Restrict "overflow" and "display" styles during box animations
if ( isBox && elem.nodeType === 1 ) {
// Support: IE <=9 - 11, Edge 12 - 13
// Record all 3 overflow attributes because IE does not infer the shorthand
// from identically-valued overflowX and overflowY
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Identify a display type, preferring old show/hide data over the CSS cascade
restoreDisplay = dataShow && dataShow.display;
if ( restoreDisplay == null ) {
restoreDisplay = dataPriv.get( elem, "display" );
}
display = jQuery.css( elem, "display" );
if ( display === "none" ) {
if ( restoreDisplay ) {
display = restoreDisplay;
} else {
// Get nonempty value(s) by temporarily forcing visibility
showHide( [ elem ], true );
restoreDisplay = elem.style.display || restoreDisplay;
display = jQuery.css( elem, "display" );
showHide( [ elem ] );
}
}
// Animate inline elements as inline-block
if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) {
if ( jQuery.css( elem, "float" ) === "none" ) {
// Restore the original display value at the end of pure show/hide animations
if ( !propTween ) {
anim.done( function() {
style.display = restoreDisplay;
} );
if ( restoreDisplay == null ) {
display = style.display;
restoreDisplay = display === "none" ? "" : display;
}
}
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 ];
} );
}
// Implement show/hide animations
propTween = false;
for ( prop in orig ) {
// General show/hide setup for this element animation
if ( !propTween ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } );
}
// Store hidden/visible for toggle so `.stop().toggle()` "reverses"
if ( toggle ) {
dataShow.hidden = !hidden;
}
// Show elements before animating them
if ( hidden ) {
showHide( [ elem ], true );
}
/* eslint-disable no-loop-func */
anim.done( function() {
/* eslint-enable no-loop-func */
// The final step of a "hide" animation is actually hiding the element
if ( !hidden ) {
showHide( [ elem ] );
}
dataPriv.remove( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
} );
}
// Per-property setup
propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = propTween.start;
if ( hidden ) {
propTween.end = propTween.start;
propTween.start = 0;
}
}
}
}
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 = Animation.prefilters.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 only
// 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: {},
easing: jQuery.easing._default
}, 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.notifyWith( elem, [ animation, 1, 0 ] );
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 = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
if ( jQuery.isFunction( result.stop ) ) {
jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
jQuery.proxy( result.stop, 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, {
tweeners: {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value );
adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
return tween;
} ]
},
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.match( rnothtmlwhite );
}
var prop,
index = 0,
length = props.length;
for ( ; index < length; index++ ) {
prop = props[ index ];
Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
Animation.tweeners[ prop ].unshift( callback );
}
},
prefilters: [ defaultPrefilter ],
prefilter: function( callback, prepend ) {
if ( prepend ) {
Animation.prefilters.unshift( callback );
} else {
Animation.prefilters.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
};
// Go to the end state if fx are off or if document is hidden
if ( jQuery.fx.off || document.hidden ) {
opt.duration = 0;
} else {
if ( typeof opt.duration !== "number" ) {
if ( opt.duration in jQuery.fx.speeds ) {
opt.duration = jQuery.fx.speeds[ opt.duration ];
} else {
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( isHiddenWithinTree ).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 || dataPriv.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 = dataPriv.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 = dataPriv.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 = window.requestAnimationFrame ?
window.requestAnimationFrame( raf ) :
window.setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
if ( window.cancelAnimationFrame ) {
window.cancelAnimationFrame( timerId );
} else {
window.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.
// https://web.archive.org/web/20100324014747/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 = window.setTimeout( next, time );
hooks.stop = function() {
window.clearTimeout( timeout );
};
} );
};
( function() {
var input = document.createElement( "input" ),
select = document.createElement( "select" ),
opt = select.appendChild( document.createElement( "option" ) );
input.type = "checkbox";
// Support: Android <=4.3 only
// Default value for a checkbox should be "on"
support.checkOn = input.value !== "";
// Support: IE <=11 only
// Must access selectedIndex to make default options select
support.optSelected = opt.selected;
// Support: IE <=11 only
// 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 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 ret, hooks,
nType = elem.nodeType;
// Don't get/set attributes on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
// Attribute hooks are determined by the lowercase version
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
hooks = jQuery.attrHooks[ name.toLowerCase() ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : undefined );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
}
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
elem.setAttribute( name, value + "" );
return value;
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ? undefined : ret;
},
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;
}
}
}
},
removeAttr: function( elem, value ) {
var name,
i = 0,
// Attribute names can contain non-HTML whitespace characters
// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
attrNames = value && value.match( rnothtmlwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( ( name = attrNames[ i++ ] ) ) {
elem.removeAttribute( name );
}
}
}
} );
// 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,
lowercaseName = name.toLowerCase();
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ lowercaseName ];
attrHandle[ lowercaseName ] = ret;
ret = getter( elem, name, isXML ) != null ?
lowercaseName :
null;
attrHandle[ lowercaseName ] = handle;
}
return ret;
};
} );
var rfocusable = /^(?:input|select|textarea|button)$/i,
rclickable = /^(?:a|area)$/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( {
prop: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set properties on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
return ( elem[ name ] = value );
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
return elem[ name ];
},
propHooks: {
tabIndex: {
get: function( elem ) {
// Support: IE <=9 - 11 only
// elem.tabIndex doesn't always return the
// correct value when it hasn't been explicitly set
// https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
if ( tabindex ) {
return parseInt( tabindex, 10 );
}
if (
rfocusable.test( elem.nodeName ) ||
rclickable.test( elem.nodeName ) &&
elem.href
) {
return 0;
}
return -1;
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
}
} );
// Support: IE <=11 only
// Accessing the selectedIndex property
// forces the browser to respect setting selected
// on the option
// The getter ensures a default option is selected
// when in an optgroup
// eslint rule "no-unused-expressions" is disabled for this code
// since it considers such accessions noop
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
/* eslint no-unused-expressions: "off" */
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
},
set: function( elem ) {
/* eslint no-unused-expressions: "off" */
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
}
};
}
jQuery.each( [
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
} );
// Strip and collapse whitespace according to HTML spec
// https://html.spec.whatwg.org/multipage/infrastructure.html#strip-and-collapse-whitespace
function stripAndCollapse( value ) {
var tokens = value.match( rnothtmlwhite ) || [];
return tokens.join( " " );
}
function getClass( elem ) {
return elem.getAttribute && elem.getAttribute( "class" ) || "";
}
jQuery.fn.extend( {
addClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( jQuery.isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
} );
}
if ( typeof value === "string" && value ) {
classes = value.match( rnothtmlwhite ) || [];
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = stripAndCollapse( cur );
if ( curValue !== finalValue ) {
elem.setAttribute( "class", finalValue );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( jQuery.isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
} );
}
if ( !arguments.length ) {
return this.attr( "class", "" );
}
if ( typeof value === "string" && value ) {
classes = value.match( rnothtmlwhite ) || [];
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = stripAndCollapse( cur );
if ( curValue !== finalValue ) {
elem.setAttribute( "class", 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, getClass( this ), stateVal ),
stateVal
);
} );
}
return this.each( function() {
var className, i, self, classNames;
if ( type === "string" ) {
// Toggle individual class names
i = 0;
self = jQuery( this );
classNames = value.match( rnothtmlwhite ) || [];
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 ( value === undefined || type === "boolean" ) {
className = getClass( this );
if ( className ) {
// Store className if set
dataPriv.set( this, "__className__", 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.
if ( this.setAttribute ) {
this.setAttribute( "class",
className || value === false ?
"" :
dataPriv.get( this, "__className__" ) || ""
);
}
}
} );
},
hasClass: function( selector ) {
var className, elem,
i = 0;
className = " " + selector + " ";
while ( ( elem = this[ i++ ] ) ) {
if ( elem.nodeType === 1 &&
( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) {
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;
// Handle most common string cases
if ( typeof ret === "string" ) {
return ret.replace( rreturn, "" );
}
// Handle cases where value is null/undef or number
return 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: IE <=10 - 11 only
// option.text throws exceptions (#14686, #14858)
// Strip and collapse whitespace
// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
stripAndCollapse( jQuery.text( elem ) );
}
},
select: {
get: function( elem ) {
var value, option, i,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one",
values = one ? null : [],
max = one ? index + 1 : options.length;
if ( index < 0 ) {
i = max;
} else {
i = one ? index : 0;
}
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// Support: IE <=9 only
// IE8-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
!option.disabled &&
( !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 ];
/* eslint-disable no-cond-assign */
if ( option.selected =
jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1
) {
optionSet = true;
}
/* eslint-enable no-cond-assign */
}
// 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 ) > -1 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
return elem.getAttribute( "value" ) === null ? "on" : elem.value;
};
}
} );
// Return jQuery for attributes-only inclusion
var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/;
jQuery.extend( jQuery.event, {
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( "." ) > -1 ) {
// Namespaced trigger; create a regexp to match event 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 event 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.rnamespace = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, 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 event 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 event path
i = 0;
while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] &&
dataPriv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && 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 ) &&
acceptData( elem ) ) {
// Call a native DOM method on the target with the same name as the event.
// 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 event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
// Piggyback on a donor event to simulate a different one
// Used only for `focus(in | out)` events
simulate: function( type, elem, event ) {
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true
}
);
jQuery.event.trigger( e, null, elem );
}
} );
jQuery.fn.extend( {
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 );
}
}
} );
jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup contextmenu" ).split( " " ),
function( i, name ) {
// Handle event 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 );
}
} );
support.focusin = "onfocusin" in window;
// Support: Firefox <=44
// Firefox doesn't have focus(in | out) events
// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
//
// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1
// focus(in | out) events fire after focus & blur events,
// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857
if ( !support.focusin ) {
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 ) );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = dataPriv.access( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
dataPriv.access( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = dataPriv.access( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
dataPriv.remove( doc, fix );
} else {
dataPriv.access( doc, fix, attaches );
}
}
};
} );
}
var location = window.location;
var nonce = jQuery.now();
var rquery = ( /\?/ );
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE 9 - 11 only
// IE throws on parseFromString with invalid input.
try {
xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
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" && v != null ? 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, valueOrFunction ) {
// If value is a function, invoke it and use its return value
var value = jQuery.isFunction( valueOrFunction ) ?
valueOrFunction() :
valueOrFunction;
s[ s.length ] = encodeURIComponent( key ) + "=" +
encodeURIComponent( value == null ? "" : value );
};
// 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( "&" );
};
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();
if ( val == null ) {
return null;
}
if ( jQuery.isArray( val ) ) {
return jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
} );
}
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
} ).get();
}
} );
var
r20 = /%20/g,
rhash = /#.*$/,
rantiCache = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
/* 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( "*" ),
// Anchor tag for parsing the document origin
originAnchor = document.createElement( "a" );
originAnchor.href = location.href;
// 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( rnothtmlwhite ) || [];
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: location.href,
type: "GET",
isLocal: rlocalProtocol.test( location.protocol ),
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: /\bxml\b/,
html: /\bhtml/,
json: /\bjson\b/
},
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": JSON.parse,
// 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,
// Url cleanup var
urlAnchor,
// Request state (becomes false upon send and true upon completion)
completed,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// uncached part of the url
uncached,
// 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 = {},
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( completed ) {
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 completed ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
if ( completed == null ) {
name = requestHeadersNames[ name.toLowerCase() ] =
requestHeadersNames[ name.toLowerCase() ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( completed == null ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( completed ) {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
} else {
// Lazy-add the new callbacks in a way that preserves old ones
for ( code in map ) {
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
}
}
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 );
// 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 || location.href ) + "" )
.replace( rprotocol, location.protocol + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ];
// A cross-domain request is in order when the origin doesn't match the current origin.
if ( s.crossDomain == null ) {
urlAnchor = document.createElement( "a" );
// Support: IE <=8 - 11, Edge 12 - 13
// IE throws exception on accessing the href property if url is malformed,
// e.g. http://example.com:80x/
try {
urlAnchor.href = s.url;
// Support: IE <=8 - 11 only
// Anchor's host property isn't correctly set when s.url is relative
urlAnchor.href = urlAnchor.href;
s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !==
urlAnchor.protocol + "//" + urlAnchor.host;
} catch ( e ) {
// If there is an error parsing the URL, assume it is crossDomain,
// it can be rejected by the transport if it is invalid
s.crossDomain = true;
}
}
// 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 ( completed ) {
return jqXHR;
}
// We can fire global events as of now if asked to
// Don't fire events if jQuery.event 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
// Remove hash to simplify url manipulation
cacheURL = s.url.replace( rhash, "" );
// More options handling for requests with no content
if ( !s.hasContent ) {
// Remember the hash so we can put it back
uncached = s.url.slice( cacheURL.length );
// If data is available, append data to url
if ( s.data ) {
cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add or update anti-cache param if needed
if ( s.cache === false ) {
cacheURL = cacheURL.replace( rantiCache, "$1" );
uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached;
}
// Put hash and anti-cache on the URL that will be requested (gh-1732)
s.url = cacheURL + uncached;
// Change '%20' to '+' if this is encoded form body content (gh-2658)
} else if ( s.data && s.processData &&
( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) {
s.data = s.data.replace( r20, "+" );
}
// 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 || completed ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// Aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
completeDeferred.add( s.complete );
jqXHR.done( s.success );
jqXHR.fail( s.error );
// 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 ] );
}
// If request was aborted inside ajaxSend, stop there
if ( completed ) {
return jqXHR;
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = window.setTimeout( function() {
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
completed = false;
transport.send( requestHeaders, done );
} catch ( e ) {
// Rethrow post-completion exceptions
if ( completed ) {
throw e;
}
// Propagate others as results
done( -1, e );
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Ignore repeat invocations
if ( completed ) {
return;
}
completed = true;
// Clear timeout if it exists
if ( timeoutTimer ) {
window.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;
}
// The url can be an options object (which then must have .url)
return jQuery.ajax( jQuery.extend( {
url: url,
type: method,
dataType: type,
data: data,
success: callback
}, jQuery.isPlainObject( url ) && url ) );
};
} );
jQuery._evalUrl = function( url ) {
return jQuery.ajax( {
url: url,
// Make this explicit, since user can override this through ajaxSetup (#11264)
type: "GET",
dataType: "script",
cache: true,
async: false,
global: false,
"throws": true
} );
};
jQuery.fn.extend( {
wrapAll: function( html ) {
var wrap;
if ( this[ 0 ] ) {
if ( jQuery.isFunction( html ) ) {
html = html.call( 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( selector ) {
this.parent( selector ).not( "body" ).each( function() {
jQuery( this ).replaceWith( this.childNodes );
} );
return this;
}
} );
jQuery.expr.pseudos.hidden = function( elem ) {
return !jQuery.expr.pseudos.visible( elem );
};
jQuery.expr.pseudos.visible = function( elem ) {
return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};
jQuery.ajaxSettings.xhr = function() {
try {
return new window.XMLHttpRequest();
} catch ( e ) {}
};
var xhrSuccessStatus = {
// File protocol always yields status code 0, assume 200
0: 200,
// Support: IE <=9 only
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
xhrSupported = jQuery.ajaxSettings.xhr();
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport( function( options ) {
var callback, errorCallback;
// Cross domain only allowed if supported through XMLHttpRequest
if ( support.cors || xhrSupported && !options.crossDomain ) {
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr();
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 ) {
callback = errorCallback = xhr.onload =
xhr.onerror = xhr.onabort = xhr.onreadystatechange = null;
if ( type === "abort" ) {
xhr.abort();
} else if ( type === "error" ) {
// Support: IE <=9 only
// On a manual native abort, IE9 throws
// errors on any property access that is not readyState
if ( typeof xhr.status !== "number" ) {
complete( 0, "error" );
} else {
complete(
// File: protocol always yields status 0; see #8605, #14207
xhr.status,
xhr.statusText
);
}
} else {
complete(
xhrSuccessStatus[ xhr.status ] || xhr.status,
xhr.statusText,
// Support: IE <=9 only
// IE9 has no XHR2 but throws on binary (trac-11426)
// For XHR2 non-text, let the caller handle it (gh-2498)
( xhr.responseType || "text" ) !== "text" ||
typeof xhr.responseText !== "string" ?
{ binary: xhr.response } :
{ text: xhr.responseText },
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
errorCallback = xhr.onerror = callback( "error" );
// Support: IE 9 only
// Use onreadystatechange to replace onabort
// to handle uncaught aborts
if ( xhr.onabort !== undefined ) {
xhr.onabort = errorCallback;
} else {
xhr.onreadystatechange = function() {
// Check readyState before timeout as it changes
if ( xhr.readyState === 4 ) {
// Allow onerror to be called first,
// but that will not handle a native abort
// Also, save errorCallback to a variable
// as xhr.onerror cannot be accessed
window.setTimeout( function() {
if ( callback ) {
errorCallback();
}
} );
}
};
}
// Create the abort callback
callback = 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();
}
}
};
}
} );
// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432)
jQuery.ajaxPrefilter( function( s ) {
if ( s.crossDomain ) {
s.contents.script = false;
}
} );
// Install script dataType
jQuery.ajaxSetup( {
accepts: {
script: "text/javascript, application/javascript, " +
"application/ecmascript, application/x-ecmascript"
},
contents: {
script: /\b(?:java|ecma)script\b/
},
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( {
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 );
}
}
);
// Use native DOM manipulation to avoid our domManip AJAX trickery
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" ) === 0 &&
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() {
// If previous value didn't exist - remove it
if ( overwritten === undefined ) {
jQuery( window ).removeProp( callbackName );
// Otherwise restore preexisting value
} else {
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";
}
} );
// Support: Safari 8 only
// In Safari 8 documents created via document.implementation.createHTMLDocument
// collapse sibling forms: the second one becomes a child of the first one.
// Because of that, this security measure has to be disabled in Safari 8.
// https://bugs.webkit.org/show_bug.cgi?id=137337
support.createHTMLDocument = ( function() {
var body = document.implementation.createHTMLDocument( "" ).body;
body.innerHTML = "<form></form><form></form>";
return body.childNodes.length === 2;
} )();
// Argument "data" should be 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 ( typeof data !== "string" ) {
return [];
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
var base, parsed, scripts;
if ( !context ) {
// Stop scripts or inline event handlers from being executed immediately
// by using document.implementation
if ( support.createHTMLDocument ) {
context = document.implementation.createHTMLDocument( "" );
// Set the base href for the created document
// so any parsed elements with URLs
// are based on the document's URL (gh-2965)
base = context.createElement( "base" );
base.href = document.location.href;
context.head.appendChild( base );
} else {
context = document;
}
}
parsed = rsingleTag.exec( data );
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[ 1 ] ) ];
}
parsed = buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
var selector, type, response,
self = this,
off = url.indexOf( " " );
if ( off > -1 ) {
selector = stripAndCollapse( 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.
// Make value of this field explicit since
// user can override it through ajaxSetup method
type: type || "GET",
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 );
// If the request succeeds, this function gets "data", "status", "jqXHR"
// but they are ignored because response was set above.
// If it fails, this function gets "jqXHR", "status", "error"
} ).always( callback && function( jqXHR, status ) {
self.each( function() {
callback.apply( this, 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.pseudos.animated = function( elem ) {
return jQuery.grep( jQuery.timers, function( fn ) {
return elem === fn.elem;
} ).length;
};
/**
* 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 ) ) {
// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
options = options.call( elem, i, jQuery.extend( {}, 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 ) {
// Preserve chaining for setter
if ( arguments.length ) {
return options === undefined ?
this :
this.each( function( i ) {
jQuery.offset.setOffset( this, options, i );
} );
}
var docElem, win, rect, doc,
elem = this[ 0 ];
if ( !elem ) {
return;
}
// Support: IE <=11 only
// Running getBoundingClientRect on a
// disconnected node in IE throws an error
if ( !elem.getClientRects().length ) {
return { top: 0, left: 0 };
}
rect = elem.getBoundingClientRect();
// Make sure element is not hidden (display: none)
if ( rect.width || rect.height ) {
doc = elem.ownerDocument;
win = getWindow( doc );
docElem = doc.documentElement;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
}
// Return zeros for disconnected and hidden elements (gh-2310)
return rect;
},
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: parentOffset.top + jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ),
left: 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 )
};
},
// This method will return documentElement in the following cases:
// 1) For the element inside the iframe without offsetParent, this method will return
// documentElement of the parent window
// 2) For the hidden or detached element
// 3) For body or html element, i.e. in case of the html node - it will return itself
//
// but those exceptions were never presented as a real life use-cases
// and might be considered as more preferable results.
//
// This logic, however, is not guaranteed and can change at any point in the future
offsetParent: function() {
return this.map( function() {
var offsetParent = this.offsetParent;
while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || documentElement;
} );
}
} );
// 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 : win.pageXOffset,
top ? val : win.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length );
};
} );
// Support: Safari <=7 - 9.1, Chrome <=37 - 49
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347
// 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 ) ) {
// $( window ).outerWidth/Height return w/h including scrollbars (gh-1729)
return funcName.indexOf( "outer" ) === 0 ?
elem[ "inner" + name ] :
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 );
};
} );
} );
jQuery.fn.extend( {
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 );
}
} );
jQuery.parseJSON = JSON.parse;
// 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 ( !noGlobal ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
} );
|
const Article = require('../../structs/Article.js')
describe('Unit::structs/Article', function () {
const baseArticle = {
meta: {}
}
const feedData = {
feed: {}
}
describe('testFilters', function () {
it('passes with no filters', function () {
const article = new Article(baseArticle, feedData)
article.fullTitle = 'my sentence is this'
const filters = {}
const returned = article.testFilters(filters)
expect(returned.passed).toEqual(true)
})
it('works with regular filters', function () {
const article = new Article(baseArticle, feedData)
article.fullTitle = 'my sentence is this'
const filters = {
title: ['foo', 'sentence']
}
const returned = article.testFilters(filters)
expect(returned.passed).toEqual(true)
})
it('blocks when regular filters are not found', function () {
const article = new Article(baseArticle, feedData)
article.fullTitle = 'my cahones'
const filters = {
title: ['foo', 'sentence']
}
const returned = article.testFilters(filters)
expect(returned.passed).toEqual(false)
})
it('works with negated filters', function () {
const article = new Article(baseArticle, feedData)
article.fullTitle = 'my sentence is this'
const filters = {
title: ['!sentence']
}
const returned = article.testFilters(filters)
expect(returned.passed).toEqual(false)
})
it('passes when negated filters are not found', function () {
const article = new Article(baseArticle, feedData)
article.fullTitle = 'my cajones is this'
const filters = {
title: ['!sentence']
}
const returned = article.testFilters(filters)
expect(returned.passed).toEqual(true)
})
it('works with broad filters', function () {
const article = new Article(baseArticle, feedData)
article.fullTitle = 'my sentence is this'
const filters = {
title: ['~ence']
}
const returned = article.testFilters(filters)
expect(returned.passed).toEqual(true)
})
it('blocks when broad filters are not found', function () {
const article = new Article(baseArticle, feedData)
article.fullTitle = 'is this'
const filters = {
title: ['~ence']
}
const returned = article.testFilters(filters)
expect(returned.passed).toEqual(false)
})
it('works with regular and negated filters', function () {
const article = new Article(baseArticle, feedData)
article.fullTitle = 'my sentence is this'
const filters = {
title: ['!sentence', 'my']
}
const returned = article.testFilters(filters)
expect(returned.passed).toEqual(false)
})
it('works with broad and negated filters', function () {
const article = new Article(baseArticle, feedData)
article.fullTitle = 'my sentence is this'
const filters = {
title: ['!sentence', '~ence']
}
const returned = article.testFilters(filters)
expect(returned.passed).toEqual(false)
})
it('all types works together', function () {
const filters = {
title: [
'(free/100% off)',
'(free / 100% off)',
'100% off',
'$0.99',
'~100%',
'!~itch.io',
'!boogeyman'
]
}
const article = new Article(baseArticle, feedData)
article.fullTitle = '[Steam] Key x Sekai Project Publisher Weekend (Planetarian $4.49/55%, Re;Lord $6.99/30%, Clannad Complete $34.40/60%, Maitetsu $8.99/40% and more)'
const returned = article.testFilters(filters)
expect(returned.passed).toEqual(false)
})
it('blocks for non-existent article properties', function () {
const filters = {
Title: [
'Blah'
]
}
const article = new Article(baseArticle, feedData)
article.title = 'Blah george'
const returned = article.testFilters(filters)
expect(returned.passed).toEqual(false)
})
it('works with filters across multiple categories', function () {
const filters = {
title: [
'Blah'
],
description: [
'Boh'
]
}
const article = new Article(baseArticle, feedData)
article.title = 'Blah george'
article.description = 'hoder'
const returned = article.testFilters(filters)
expect(returned.passed).toEqual(true)
})
it('blocks when one filter blocks with filters in multiple categories', function () {
const filters = {
title: [
'Blah'
],
description: [
'!Boh'
],
author: [
'Bang'
]
}
const article = new Article(baseArticle, feedData)
article.title = 'Blah Blahs'
article.description = 'Ban Boh'
article.author = 'Bang Bang'
const returned = article.testFilters(filters)
expect(returned.passed).toEqual(false)
})
it('blocks when using broad filters and negated filters in different categories', function () {
const filters = {
title: [
'~campaig'
],
guid: [
'!60097a6bf64cf135e3323184'
]
}
const article = new Article(baseArticle, feedData)
article.title = 'Sirius and Utopia Compete to Host Galactic Summit'
article.guid = '600accd53eb598007a0385f8'
const returned = article.testFilters(filters)
expect(returned.passed).toEqual(false)
})
it('passes with negated and regular in one category with regular in another, and the other matches', function () {
const filters = {
title: [
'!software',
'srfdhetgfj'
],
author: [
'huntermc'
]
}
const article = new Article(baseArticle, feedData)
article.title = "[UPDATE] Hunter's Harem [v0.4.3.2a]"
article.author = 'huntermc'
const returned = article.testFilters(filters)
expect(returned.passed).toEqual(true)
})
})
})
|
/* global define */
;(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// eslint-disable-line
// AMD. Register as an anonymous module.
define(['exports', 'echarts'], factory) // eslint-disable-line
} else if (
typeof exports === 'object' &&
typeof exports.nodeName !== 'string'
) {
// CommonJS
factory(exports, require('echarts'))
} else {
// Browser globals
factory({}, root.echarts)
}
})(this, (exports, echarts) => {
let log = function(msg) {
if (typeof console !== 'undefined') {
/* eslint-disable */
console && console.error && console.error(msg)
}
}
if (!echarts) {
log('ECharts is not Loaded')
return
}
let colorPalette = [
'#c12e34',
'#e6b600',
'#0098d9',
'#2b821d',
'#005eaa',
'#339ca8',
'#cda819',
'#32a487',
]
let theme = {
color: colorPalette,
title: {
textStyle: {
fontWeight: 'normal',
},
},
visualMap: {
color: ['#1790cf', '#a2d4e6'],
},
toolbox: {
iconStyle: {
normal: {
borderColor: '#06467c',
},
},
},
tooltip: {
backgroundColor: 'rgba(0,0,0,0.6)',
},
dataZoom: {
dataBackgroundColor: '#dedede',
fillerColor: 'rgba(154,217,247,0.2)',
handleColor: '#005eaa',
},
timeline: {
lineStyle: {
color: '#005eaa',
},
controlStyle: {
normal: {
color: '#005eaa',
borderColor: '#005eaa',
},
},
},
candlestick: {
itemStyle: {
normal: {
color: '#c12e34',
color0: '#2b821d',
lineStyle: {
width: 1,
color: '#c12e34',
color0: '#2b821d',
},
},
},
},
graph: {
color: colorPalette,
},
map: {
label: {
normal: {
textStyle: {
color: '#c12e34',
},
},
emphasis: {
textStyle: {
color: '#c12e34',
},
},
},
itemStyle: {
normal: {
borderColor: '#eee',
areaColor: '#ddd',
},
emphasis: {
areaColor: '#e6b600',
},
},
},
gauge: {
axisLine: {
show: true,
lineStyle: {
color: [[0.2, '#2b821d'], [0.8, '#005eaa'], [1, '#c12e34']],
width: 5,
},
},
axisTick: {
splitNumber: 10,
length: 8,
lineStyle: {
color: 'auto',
},
},
axisLabel: {
textStyle: {
color: 'auto',
},
},
splitLine: {
length: 12,
lineStyle: {
color: 'auto',
},
},
pointer: {
length: '90%',
width: 3,
color: 'auto',
},
title: {
textStyle: {
color: '#333',
},
},
detail: {
textStyle: {
color: 'auto',
},
},
},
}
echarts.registerTheme('shine', theme)
})
|
'use strict';
window.ExamplesView = Backbone.View.extend({
block: "i-examples",
el: 'body',
'events': {
'click .i-example-test__run': 'runTest'
},
'initialize': function(){
this.listenTo(this.collection, "sync", this.render);
this.listenTo(this.collection, "testsComplete", this.afterAllTests);
this.nodes = {};
this.$content = this.$el.find('.i-examples-container');
this.$sidebar = this.$el.find('.i-examples-sidebar');
},
'runAllTests': function(){
document.location.href = exampleState.url({'runtest': true});
},
'afterAllTests': function(){
$('#mocha').show();
$('.i-examples-container').get(0).scrollTop = 0;
},
'mochaClear': function(){
this.$mocha = $('#mocha');
this.$mocha.empty();
mocha.suite.tests = [];
mocha.suite.title = "";
},
'runTest': function(e){
var elem = e.target,
testSign = elem.getAttribute('data-test'),
blockName = elem.getAttribute('data-name'),
testFunc = tests[testSign],
$container = $(".sign-"+testSign),
view = this;
this.mochaClear();
it(blockName, testFunc);
mocha.run(
function(){
$container.addClass('mocha');
$('.mocha-report-'+testSign).remove();
$_mocha = view.$mocha.find('#mocha-report').clone();
$_mocha.removeAttr('id');
$_mocha.attr('class', 'mocha-report ' + 'mocha-report-'+testSign);
$container.find('.i-example-test__run').replaceWith($_mocha);
view.$mocha.empty();
}
);
},
'render': function(){
this.sidebar() && this.content();
this.collection.trigger('render');
},
'sidebar': function(){
this.$sidebar.empty();
this.nodes['sidebar'] = $C.tpl[this.block + "__sidebar"].call(this.$sidebar[0], this.collection);
this.listenToOnce(
this.nodes['sidebar'].test,
'action',
this.runAllTests
);
this.listenToOnce(
this.nodes['sidebar'].be,
'change:selected',
this.reload
);
this.listenToOnce(
this.nodes['sidebar'].jz,
'change:selected',
this.reload
);
return true;
},
'reload': function(){
location.href = exampleState.url({
'framework': this.nodes['sidebar'].be.get('selected').get('name'),
'$': this.nodes['sidebar'].jz.get('selected').get('name')
});
},
'content': function(){
this.$content.empty();
this.nodes['content'] = $C.tpl[this.block].call(this.$content[0], this.collection);
if(this.nodes.test){
this.listenToOnce(
this.nodes.test,
'action',
this.showTests
);
this.collection.listenToOnce(
this.nodes.test,
'action',
this.collection.runTest
)
}
this.renderExamples();
this.$content.on(
'scroll',
function(){
$(document.body).trigger('scroll');
}
);
Prism.highlightAll();
return true;
},
'renderSUITE': function(suite){
this.$(".sign-"+suite.sign).prepend( "<h4 id="+ exampleState.name(suite.name +'__'+ suite.opts) +">"+ suite.opts +"</h4>" );
},
'renderCODE': function(code){
var $code = $("<div class='i-example-prism'/>"),
$container = this.$(".sign-"+code.sign);
$(this.$(".sign-"+code.sign).children().get(0)).wrap("<div class='i-example-container'/>");
$container.append( $code );
$container.prepend( "<h4 class=i-example-code__header>"+ code.opts +"</h4>" );
$C.tpl['i-prism'].call($code.get(0), code.code.join('\n'), 'ctpl');
},
'renderTEST': function(test){
var $code = $("<div class='i-example-prism'/>");
this.$(".sign-"+test.sign).append( $code );
this.$(".sign-"+test.sign).prepend( "<div class='i-pseudo i-example-test__run' data-test='"+test.sign+"' data-name='"+test.name+"'>test</div>" );
$C.tpl['i-prism'].call($code.get(0), test.code.join('\n'), 'javascript');
},
'renderExample': function(example){
var view = this;
example
.get('code')
.forEach(
function(code){
var renderer = "render" + code.type;
view[ renderer ].call(view, code)
}
);
},
'renderExamples': function(){
return this.collection.forEach(this.renderExample.bind(this));
}
});
|
module.exports = [{
input : [[-2, 0, -1]],
output : 0
}, {
input : [[2, 0, 3, -2, 4]],
output : 4
}];
|
(function() {
'use strict';
angular
.module('csc510ProjectApp')
.config(stateConfig);
stateConfig.$inject = ['$stateProvider'];
function stateConfig($stateProvider) {
$stateProvider.state('audits', {
parent: 'admin',
url: '/audits',
data: {
authorities: ['ROLE_ADMIN'],
pageTitle: 'Audits'
},
views: {
'content@': {
templateUrl: 'app/admin/audits/audits.html',
controller: 'AuditsController',
controllerAs: 'vm'
}
}
});
}
})();
|
var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost:27017/Measurements';
router.get('/weather', function(req, res) {
MongoClient.connect(url, function (err, db) {
var collection = db.collection('WeatherStation');
collection.count({}, function(error, numOfDocs){
if(error) return callback(err);
db.close();
res.json(numOfDocs);
});
});
});
router.get('/wstime', function(req, res) {
MongoClient.connect(url, function(err, db) {
var collection = db.collection('WeatherStation');
var cursor = collection.find().sort({ "time" : -1 }).limit(1);
cursor.toArray(function(err, results) {
if (err) throw err;
console.log('%j', results);
var a = new Date(results[0].createdAt);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
if(hour.toString().length < 2) {hour = '0' + hour}
var min = a.getMinutes();
if(min.toString().length < 2) {min = '0' + min}
var sec = a.getSeconds();
if(sec.toString().length < 2) {sec = '0' + sec}
var time = date + ' ' + month + ' ' + hour + ':' + min + ':' + sec ;
res.json(time);
db.close();
});
});
});
router.get('/count', function(req, res) {
MongoClient.connect(url, function (err, db) {
var collection = db.collection('Hflux');
collection.count({}, function(error, numOfDocs){
if(error) return callback(err);
db.close();
res.json(numOfDocs);
});
});
});
router.get('/time', function(req, res) {
MongoClient.connect(url, function(err, db) {
var collection = db.collection('Hflux');
var cursor = collection.find().sort({ "createdAt" : -1 }).limit(1);
cursor.toArray(function(err, results) {
if (err) throw err;
console.log('%j', results);
var a = new Date(results[0].createdAt);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
if(hour.toString().length < 2) {hour = '0' + hour}
var min = a.getMinutes();
if(min.toString().length < 2) {min = '0' + min}
var sec = a.getSeconds();
if(sec.toString().length < 2) {sec = '0' + sec}
var time = date + ' ' + month + ' ' + hour + ':' + min + ':' + sec ;
res.json(time);
db.close();
});
});
});
/* GET form. */
router.get('/', function(req, res) {
res.render('reading');
});
/* POST form. */
router.post('/', function(req, res) {
console.log(req.body.comment);
res.redirect('index');
});
module.exports = router;
|
/*jslint indent: 4 */
/*global module */
module.exports = {
options: {
match: '.',
forceExit: false,
extensions: 'js',
keepRunner: true,
specNameMatcher: 'spec',
includeStackTrace: false,
jUnit: {
report: true,
savePath: './build/reports/jasmine/',
useDotNotation: true,
consolidate: true
}
},
all: ['tests/src/']
};
|
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'forms', 'nb', {
button: {
title: 'Egenskaper for knapp',
text: 'Tekst (verdi)',
type: 'Type',
typeBtn: 'Knapp',
typeSbm: 'Send',
typeRst: 'Nullstill'
},
checkboxAndRadio: {
checkboxTitle: 'Egenskaper for avmerkingsboks',
radioTitle: 'Egenskaper for alternativknapp',
value: 'Verdi',
selected: 'Valgt'
},
form: {
title: 'Egenskaper for skjema',
menu: 'Egenskaper for skjema',
action: 'Handling',
method: 'Metode',
encoding: 'Encoding'
},
hidden: {
title: 'Egenskaper for skjult felt',
name: 'Navn',
value: 'Verdi'
},
select: {
title: 'Egenskaper for rullegardinliste',
selectInfo: 'Info',
opAvail: 'Tilgjenglige alternativer',
value: 'Verdi',
size: 'Størrelse',
lines: 'Linjer',
chkMulti: 'Tillat flervalg',
opText: 'Tekst',
opValue: 'Verdi',
btnAdd: 'Legg til',
btnModify: 'Endre',
btnUp: 'Opp',
btnDown: 'Ned',
btnSetValue: 'Sett som valgt',
btnDelete: 'Slett'
},
textarea: {
title: 'Egenskaper for tekstområde',
cols: 'Kolonner',
rows: 'Rader'
},
textfield: {
title: 'Egenskaper for tekstfelt',
name: 'Navn',
value: 'Verdi',
charWidth: 'Tegnbredde',
maxChars: 'Maks antall tegn',
type: 'Type',
typeText: 'Tekst',
typePass: 'Passord',
typeEmail: 'Epost',
typeSearch: 'Søk',
typeTel: 'Telefonnummer',
typeUrl: 'URL'
}
} );
|
import { moduleFor, test } from 'ember-qunit';
moduleFor('route:project.vocabulary', 'Unit | Route | project.vocabulary', {
// Specify the other units that are required for this test.
// needs: ['controller:foo']
});
test('it exists', function(assert) {
let route = this.subject();
assert.ok(route);
});
|
define(['exports', 'aurelia-templating', '../dialog-controller'], function (exports, _aureliaTemplating, _dialogController) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.AiDialogFooter = undefined;
function _initDefineProp(target, property, descriptor, context) {
if (!descriptor) return;
Object.defineProperty(target, property, {
enumerable: descriptor.enumerable,
configurable: descriptor.configurable,
writable: descriptor.writable,
value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
});
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
var desc = {};
Object['ke' + 'ys'](descriptor).forEach(function (key) {
desc[key] = descriptor[key];
});
desc.enumerable = !!desc.enumerable;
desc.configurable = !!desc.configurable;
if ('value' in desc || desc.initializer) {
desc.writable = true;
}
desc = decorators.slice().reverse().reduce(function (desc, decorator) {
return decorator(target, property, desc) || desc;
}, desc);
if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined;
}
if (desc.initializer === void 0) {
Object['define' + 'Property'](target, property, desc);
desc = null;
}
return desc;
}
function _initializerWarningHelper(descriptor, context) {
throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.');
}
var _dec, _class, _desc, _value, _class2, _descriptor, _descriptor2, _class3, _temp;
var AiDialogFooter = exports.AiDialogFooter = (_dec = (0, _aureliaTemplating.customElement)('ai-dialog-footer'), _dec(_class = (_class2 = (_temp = _class3 = function () {
function AiDialogFooter(controller) {
_classCallCheck(this, AiDialogFooter);
_initDefineProp(this, 'buttons', _descriptor, this);
_initDefineProp(this, 'useDefaultButtons', _descriptor2, this);
this.controller = controller;
}
AiDialogFooter.prototype.close = function close(buttonValue) {
if (AiDialogFooter.isCancelButton(buttonValue)) {
this.controller.cancel(buttonValue);
} else {
this.controller.ok(buttonValue);
}
};
AiDialogFooter.prototype.useDefaultButtonsChanged = function useDefaultButtonsChanged(newValue) {
if (newValue) {
this.buttons = ['Cancel', 'Ok'];
}
};
AiDialogFooter.isCancelButton = function isCancelButton(value) {
return value === 'Cancel';
};
return AiDialogFooter;
}(), _class3.inject = [_dialogController.DialogController], _temp), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, 'buttons', [_aureliaTemplating.bindable], {
enumerable: true,
initializer: function initializer() {
return [];
}
}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'useDefaultButtons', [_aureliaTemplating.bindable], {
enumerable: true,
initializer: function initializer() {
return false;
}
})), _class2)) || _class);
});
|
jQuery(document).ready(function($) {
$(".scroll").click(function(event){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 300);
$('html,body').animate({scrollTop:$(this.hash).offset().top-=5}, 300);
$(this.hash).effect("highlight", {color: "#FFCC85"}, 2000);
});
});
|
define('moduleA', ['require', 'exports'], function(require, exports) {
var moduleB = require('moduleB');
exports.stuff = moduleB.doStuff();
});
|
module.exports = require('./_project_generator');
|
// DOM Manipulation Challenge
// I worked on this challenge [by myself, with: ].
// Add your JavaScript calls to this page:
// Release 0:
// Release 1:
var done = document.getElementById("release-0");
done.className = "done";
document.getElementByClassName("done");
// Release 2:
document.getElementById("release-1").style.display = none;
// Release 3:
document.getElementById("release-2").innerHTML = "I completed release 2."
// Release 4:
document.getElementById("release-3").style.backgroundColor = "#955251";
// Release 5:
var x = document.getElementsByClassName("release-4");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.fontSize = "2em";
}
// Release 6:
var tmpl = document.getElementById("hidden");
document.body.appendChild(tmpl.content.cloneNode(true));
|
'use strict';
var options = require('../options/common');
options.orientation = 'portrait';
module.exports = options;
|
const homebridge = new (require('homebridge/lib/api').API)();
const Service = homebridge.hap.Service;
const Characteristic = homebridge.hap.Characteristic;
const Requester = require('./mock-Requester.js');
const exportedTypes = {
Service,
Characteristic,
Requester,
};
const DaikinAirconAccessory = require('../lib/DaikinAirconAccessory')(exportedTypes);
describe('DaikinAirconAccessory', () => {
describe('parseResponse()', () => {
it('should be parsed', () => {
const result = DaikinAirconAccessory.parseResponse('a=1,b=2');
expect(result).toEqual({
a: '1',
b: '2',
});
});
});
describe('getActive()', () => {
it('should be success', () => {
const accessory = new DaikinAirconAccessory();
accessory.getActive((error, value) => {
expect(error).toBeNull();
expect(value).toBe(Characteristic.Active.INACTIVE);
});
Requester.currentPower = '1';
accessory.getActive((error, value) => {
expect(error).toBeNull();
expect(value).toBe(Characteristic.Active.ACTIVE);
});
});
});
describe('setActive()', () => {
it('should be active with valid mode', () => {
const config = {
coolingHeatingThreshold: 26,
};
const accessory = new DaikinAirconAccessory(console.log, config);
Requester.currentPower = '0';
// 閾値より高い状態で運転開始
Requester.currentTemp = '28';
accessory.setActive(Characteristic.Active.ACTIVE, () => {
accessory.getActive((error, value) => {
expect(error).toBeNull();
expect(value).toBe(Characteristic.Active.ACTIVE);
});
// 室温が閾値より高いので冷房
accessory.getHeaterCoolerState((error, value) => {
expect(error).toBeNull();
expect(value).toBe(Characteristic.CurrentHeaterCoolerState.COOLING);
});
});
// 閾値より高い状態で運転開始
Requester.currentTemp = '20';
accessory.setActive(Characteristic.Active.ACTIVE, () => {
accessory.getActive((error, value) => {
expect(error).toBeNull();
expect(value).toBe(Characteristic.Active.ACTIVE);
});
// 室温が閾値より低いので暖房
accessory.getHeaterCoolerState((error, value) => {
expect(error).toBeNull();
expect(value).toBe(Characteristic.CurrentHeaterCoolerState.HEATING);
});
});
});
it('should be inactive', () => {
const config = {
coolingHeatingThreshold: 26,
};
const accessory = new DaikinAirconAccessory(console.log, config);
Requester.currentPower = '1';
// 運転停止
accessory.setActive(Characteristic.Active.INACTIVE, () => {
accessory.getActive((error, value) => {
expect(error).toBeNull();
expect(value).toBe(Characteristic.Active.INACTIVE);
});
});
});
});
});
|
'use strict';
/**
* Module dependencies.
*/
var itemPolicy = require('../policies/item.server.policy'),
items = require('../controllers/item.server.controller');
module.exports = function (app) {
// Items collection routes
app.route('/api/item').all(itemPolicy.isAllowed)
.get(items.list)
.post(items.create);
// Single item routes
app.route('/api/item/:itemId').all(itemPolicy.isAllowed)
.get(items.read)
.put(items.update)
.delete(items.delete);
// Finish by binding the item middleware
app.param('itemId', items.itemByID);
};
|
#!/usr/bin/env node
'use strict';
// stores From lang from the first menu (From menu). Passed byref to translationHandler and menu.initMenus
var langChoice = {
from: {
code: "",
label: ""
}
};
var checkYandexKey = require('./lib/checkYandexKey.js'),
menu = require('./lib/menu.js'),
translationHandler = require('./lib/translationHandler.js')(langChoice);
/*Checks Yandex API Key, handles all key-related errors / responses launches menus with menu.initMenus
translationHandler passed to launch prompt and handle translations after second (To
lang) menu*/
checkYandexKey(function() {
menu.initMenus(translationHandler, langChoice);
});
|
/*
*
* TestContainerB constants
*
*/
export const DEFAULT_ACTION = 'app/TestContainerB/DEFAULT_ACTION';
export const FILE_ID_UPDATE_ACTION = 'app/TestContainerB/FILE_ID_UPDATE_ACTION';
|
'use strict';
// Cars controller
angular.module('cars').controller('CarsController', ['$scope', '$stateParams', '$location', 'Authentication', 'Cars','UrlService',
function ($scope, $stateParams, $location, Authentication, Cars, UrlService) {
$scope.authentication = Authentication;
// Create new Car
$scope.create = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'carForm');
return false;
}
// Create new Car object
var car = new Cars({
title: this.title,
price: this.price,
make: this.make,
model: this.model,
type: this.type,
year: this.year,
description: this.description,
imageurl: this.imageurl,
state: this.state,
contact_email: this.contact_email
});
// Redirect after save
car.$save(function (response) {
$location.path('cars/' + response._id);
// Clear form fields
$scope.title = '';
$scope.price = '';
$scope.make = '';
$scope.model = '';
$scope.type = '';
$scope.year = '';
$scope.description = '';
$scope.imageurl = '';
$scope.state = '';
$scope.contact_email = '';
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Car
$scope.remove = function (car) {
if (car) {
car.$remove();
for (var i in $scope.cars) {
if ($scope.cars[i] === car) {
$scope.cars.splice(i, 1);
}
}
} else {
$scope.car.$remove(function () {
$location.path('cars');
});
}
};
// Update existing Car
$scope.update = function (isValid) {
$scope.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'carForm');
return false;
}
var car = $scope.car;
car.$update(function () {
$location.path('cars/' + car._id);
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Cars
$scope.find = function () {
$scope.cars = Cars.query();
};
$scope.search = function () {
console.log(UrlService.getQueryStringvar('make'));
var make = UrlService.getQueryStringvar('make');
var model = UrlService.getQueryStringvar('model');
var state = UrlService.getQueryStringvar('state');
var type = UrlService.getQueryStringvar('type');
var query = {};
if(make !== 0){
query.make = make;
}
if(model !== 0){
query.model = model;
}
if(state !== 0){
query.state = state;
}
if(type !== 0){
query.type = type;
}
$scope.cars = Cars.query(query);
};
// Find existing Car
$scope.findOne = function () {
$scope.car = Cars.get({
carId: $stateParams.carId
});
};
}
]);
|
/* eslint no-magic-numbers:0 */
"use strict"
const test = require("tape")
const utils = require("../utils")
const testEvents = (t) => (err, events) => {
t.notOk(err)
t.equal(events[0].region, "nba finals")
t.end()
}
test("works with tbd first round", (t) => {
utils.parseFile("20210319-tbd-first-round", (err, events) => {
t.equal(events.length, 16)
t.end()
})
})
test.skip("works with tbd first round", (t) => {
utils.parseUrl(
"https://www.espn.com/mens-college-basketball/scoreboard/_/group/100/date/20210319",
(err, events) => {
t.equal(events.length, 16)
t.end()
}
)
})
|
$('.navbar-header .nav a h4').html('Sites');
getData(url, sites => {
new GrapheneDataGrid({...tableConfig,
schema: [
{label: 'Site Name', name:'name', required: true},
{label: 'Domain', name:'domain', required: true},
{name: 'id', type:'hidden'}
],
data: sites,
name: 'sites'
})
.on('click', e => {
window.location = '/admin/sites/'+e.model.attributes.id
})
});
|
const { expect } = require('chai');
const nock = require('nock');
const API_URL = 'https://tenant.auth0.com';
const LogStreamsManager = require(`../../src/management/LogStreamsManager`);
const { ArgumentError } = require('rest-facade');
describe('LogStreamsManager', () => {
before(function () {
this.token = 'TOKEN';
this.logStreams = new LogStreamsManager({
headers: { authorization: `Bearer ${this.token}` },
baseUrl: API_URL,
});
});
describe('instance', () => {
const methods = ['getAll', 'get', 'create', 'update', 'delete'];
methods.forEach((method) => {
it(`should have a ${method} method`, function () {
expect(this.logStreams[method]).to.exist.to.be.an.instanceOf(Function);
});
});
});
describe('#constructor', () => {
it('should error when no options are provided', () => {
expect(() => {
new LogStreamsManager();
}).to.throw(ArgumentError, 'Must provide client options');
});
it('should throw an error when no base URL is provided', () => {
expect(() => {
new LogStreamsManager({});
}).to.throw(ArgumentError, 'Must provide a base URL for the API');
});
it('should throw an error when the base URL is invalid', () => {
expect(() => {
new LogStreamsManager({ baseUrl: '' });
}).to.throw(ArgumentError, 'The provided base URL is invalid');
});
});
describe('#getAll', () => {
beforeEach(function () {
this.request = nock(API_URL).get('/log-streams').reply(200);
});
it('should accept a callback', function (done) {
this.logStreams.getAll(() => {
done();
});
});
it('should return a promise if no callback is given', function (done) {
this.logStreams.getAll().then(done.bind(null, null)).catch(done.bind(null, null));
});
it('should pass any errors to the promise catch handler', function (done) {
nock.cleanAll();
nock(API_URL).get('/log-streams').reply(500);
this.logStreams.getAll().catch((err) => {
expect(err).to.exist;
done();
});
});
it('should pass the body of the response to the "then" handler', function (done) {
nock.cleanAll();
const data = [{ test: true }];
nock(API_URL).get('/log-streams').reply(200, data);
this.logStreams.getAll().then((logStreams) => {
expect(logStreams).to.be.an.instanceOf(Array);
expect(logStreams.length).to.equal(data.length);
expect(logStreams[0].test).to.equal(data[0].test);
done();
});
});
it('should perform a GET request to /api/v2/log-streams', function (done) {
const { request } = this;
this.logStreams.getAll().then(() => {
expect(request.isDone()).to.be.true;
done();
});
});
it('should include the token in the Authorization header', function (done) {
nock.cleanAll();
const request = nock(API_URL)
.get('/log-streams')
.matchHeader('Authorization', `Bearer ${this.token}`)
.reply(200);
this.logStreams.getAll().then(() => {
expect(request.isDone()).to.be.true;
done();
});
});
});
describe('#get', () => {
const params = { id: 5 };
const data = {
id: params.id,
name: 'Test log',
};
beforeEach(function () {
this.request = nock(API_URL).get(`/log-streams/${data.id}`).reply(200);
});
it('should accept a callback', function (done) {
this.logStreams.get(params, () => {
done();
});
});
it('should return a promise if no callback is given', function (done) {
this.logStreams.get(params).then(done.bind(null, null)).catch(done.bind(null, null));
});
it('should pass any errors to the promise catch handler', function (done) {
nock.cleanAll();
nock(API_URL).get(`/log-streams/${params.id}`).reply(500);
this.logStreams.get().catch((err) => {
expect(err).to.exist;
done();
});
});
it('should pass the body of the response to the "then" handler', function (done) {
nock.cleanAll();
nock(API_URL).get(`/log-streams/${params.id}`).reply(200, data);
this.logStreams.get(params).then((log) => {
expect(log.id).to.equal(data.id);
done();
});
});
it('should perform a GET request to /api/v2/log-streams/:id', function (done) {
const { request } = this;
this.logStreams.get(params).then(() => {
expect(request.isDone()).to.be.true;
done();
});
});
it('should include the token in the Authorization header', function (done) {
nock.cleanAll();
const request = nock(API_URL)
.get('/log-streams')
.matchHeader('Authorization', `Bearer ${this.token}`)
.reply(200);
this.logStreams.getAll().then(() => {
expect(request.isDone()).to.be.true;
done();
});
});
it('should pass the parameters in the query-string', function (done) {
nock.cleanAll();
const request = nock(API_URL)
.get('/log-streams')
.query({
include_fields: true,
fields: 'test',
})
.reply(200);
this.logStreams.getAll({ include_fields: true, fields: 'test' }).then(() => {
expect(request.isDone()).to.be.true;
done();
});
});
});
describe('#create', () => {
const data = {
name: 'Test log stream',
};
beforeEach(function () {
this.request = nock(API_URL).post('/log-streams').reply(200);
});
it('should accept a callback', function (done) {
this.logStreams.create(data, () => {
done();
});
});
it('should return a promise if no callback is given', function (done) {
this.logStreams.create(data).then(done.bind(null, null)).catch(done.bind(null, null));
});
it('should pass any errors to the promise catch handler', function (done) {
nock.cleanAll();
nock(API_URL).post('/log-streams').reply(500);
this.logStreams.create(data).catch((err) => {
expect(err).to.exist;
done();
});
});
it('should perform a POST request to /api/v2/log-streams', function (done) {
const { request } = this;
this.logStreams.create(data).then(() => {
expect(request.isDone()).to.be.true;
done();
});
});
it('should pass the data in the body of the request', function (done) {
nock.cleanAll();
const request = nock(API_URL).post('/log-streams', data).reply(200);
this.logStreams.create(data).then(() => {
expect(request.isDone()).to.be.true;
done();
});
});
it('should include the token in the Authorization header', function (done) {
nock.cleanAll();
const request = nock(API_URL)
.post('/log-streams')
.matchHeader('Authorization', `Bearer ${this.token}`)
.reply(200);
this.logStreams.create(data).then(() => {
expect(request.isDone()).to.be.true;
done();
});
});
});
describe('#update', () => {
beforeEach(function () {
this.data = { id: 5 };
this.request = nock(API_URL).patch(`/log-streams/${this.data.id}`).reply(200, this.data);
});
it('should accept a callback', function (done) {
this.logStreams.update({ id: 5 }, {}, done.bind(null, null));
});
it('should return a promise if no callback is given', function (done) {
this.logStreams
.update({ id: 5 }, {})
.then(done.bind(null, null))
.catch(done.bind(null, null));
});
it('should perform a PATCH request to /api/v2/log-streams/5', function (done) {
const { request } = this;
this.logStreams.update({ id: 5 }, {}).then(() => {
expect(request.isDone()).to.be.true;
done();
});
});
it('should include the new data in the body of the request', function (done) {
nock.cleanAll();
const request = nock(API_URL).patch(`/log-streams/${this.data.id}`, this.data).reply(200);
this.logStreams.update({ id: 5 }, this.data).then(() => {
expect(request.isDone()).to.be.true;
done();
});
});
it('should pass any errors to the promise catch handler', function (done) {
nock.cleanAll();
nock(API_URL).patch(`/log-streams/${this.data.id}`).reply(500);
this.logStreams.update({ id: this.data.id }, this.data).catch((err) => {
expect(err).to.exist;
done();
});
});
});
describe('#delete', () => {
const id = 5;
beforeEach(function () {
this.request = nock(API_URL).delete(`/log-streams/${id}`).reply(200);
});
it('should accept a callback', function (done) {
this.logStreams.delete({ id }, done.bind(null, null));
});
it('should return a promise when no callback is given', function (done) {
this.logStreams.delete({ id }).then(done.bind(null, null));
});
it(`should perform a delete request to /log-streams/${id}`, function (done) {
const { request } = this;
this.logStreams.delete({ id }).then(() => {
expect(request.isDone()).to.be.true;
done();
});
});
it('should pass any errors to the promise catch handler', function (done) {
nock.cleanAll();
nock(API_URL).delete(`/log-streams/${id}`).reply(500);
this.logStreams.delete({ id }).catch((err) => {
expect(err).to.exist;
done();
});
});
it('should include the token in the authorization header', function (done) {
nock.cleanAll();
const request = nock(API_URL)
.delete(`/log-streams/${id}`)
.matchHeader('authorization', `Bearer ${this.token}`)
.reply(200);
this.logStreams.delete({ id }).then(() => {
expect(request.isDone()).to.be.true;
done();
});
});
});
});
|
/**
* Created by JinWYP on 7/27/16.
*/
var express = require('express');
var router = express.Router();
var orderController = require('../../controllers/apiv1/apidemo');
// define the demo page route
// RESTful API http://mherman.org/blog/2016/03/13/designing-a-restful-api-with-node-and-postgres/
router.get('/orders', orderController.orderList);
router.post('/orders', orderController.orderAdd);
router.post('/orders/error', orderController.orderAddWithError);
router.get('/orders/:id', orderController.orderById);
router.put('/orders/:id', orderController.orderUpdateById);
router.delete('/orders/:id', orderController.orderDelete);
module.exports = router;
|
import { expect } from 'chai';
import * as types from '../../../app/constants/ActionTypes';
import * as actions from '../../../app/actions/navigation';
describe('githubExtension Navigation actions', () => {
it('navigateTo should create NAVIGATE_TO action', () => {
expect(actions.navigateTo('data')).to.eql({
type: types.NAVIGATE_TO,
data: 'data',
});
});
});
|
'use strict';
/**
* Module dependencies
*/
var path = require('path'),
config = require(path.resolve('./config/config'));
/**
* Geos module init function.
*/
module.exports = function (app, db) {
};
|
import nodeExternals from 'webpack-node-externals';
export default {
target: 'node',
externals: [nodeExternals()],
resolve: {
extensions: [' ', '.js'],
},
node: {
fs: 'empty'
},
module: {
rules: [
{
test: /\.js?$/,
use: 'babel-loader',
exclude: /node_modules/
},
],
},
};
|
let supportsPassive_
/**
* Determine whether the current browser supports passive event listeners, and if so, use them.
* @param {!Window=} globalObj
* @param {boolean=} forceRefresh
* @return {boolean|{passive: boolean}}
*/
export function applyPassive(globalObj = window, forceRefresh = false) {
if (supportsPassive_ === undefined || forceRefresh) {
let isSupported = false
try {
globalObj.document.addEventListener('test', null, {
get passive() {
isSupported = { passive: true }
}
})
} catch (e) {
//empty
}
supportsPassive_ = isSupported
}
return supportsPassive_
}
|
/************************************
DON'T TOUCH THIS!
This file is used just to combine
everything with CodeKit.
Minified version.
************************************/
/*
CODEKIT PREPRENDs
*/
/* LIBRARIES */
// @codekit-prepend '../bower_components/angular/angular.min.js'
// @codekit-prepend '../bower_components/angular-ui-router/release/angular-ui-router.min.js'
// @codekit-prepend '../bower_components/angular-bootstrap/ui-bootstrap.min.js'
// @codekit-prepend '../bower_components/angular-loading-bar/build/loading-bar.min.js'
/* CORE */
// @codekit-append 'app.js'
|
/* @flow */
import Rx from 'rx';
// import assert from 'assert';
var literal = Rx.Observable.of;
import translateType from '../translate/type';
import translateArguments from '../translate/arguments';
export
default
function emitIndexer(node: {
arguments: ? array <IdlArgument>,
idlType ? : IdlType
}): Rx.Observable {
return translateArguments(node.arguments, '[]').concat(literal(': '), translateType(node.idlType), literal(';'));
}
|
/**
* Accordion component is added on the sidenav component and now
* requires a click event listener to handle its function.
*
* Get the CSS class named project-accordion-label
*/
var projectAccordionLabel = document.getElementsByClassName("project-accordion-label");
////console.log("projectAccordionLabel.length = "+projectAccordionLabel.length);
/**
* add click event on the tab components
*/
//for (var i = 0; i < projectAccordionLabel.length; i++) {
projectAccordionLabel[0].addEventListener("click", updateProjectAccordionContent, false);
//}
function updateProjectAccordionContent(evt) {
////console.log("what class: "+evt.currentTarget.id.toLowerCase());
/**
* get the current target element and then look up the value of its
* height
*/
var el = document.getElementById(evt.currentTarget.id.toLowerCase());
////console.log("el.className = "+el.className);
var styleOfContent = window.getComputedStyle(el);
////console.log("stylesOfContent = "+styleOfContent);
var heightOfContent = styleOfContent.getPropertyValue('height');
////console.log("heigthOfContent = "+heightOfContent);
////console.log("evt.currentTarget.style.height: "+evt.currentTarget);
/**
* by default the height is reduced to 0, however, due to
* added css styling of 2px on padding-top, the actual height of
* the element is 2px
*/
//if (heightOfContent == "2px") {
if (heightOfContent == "0px") {
/**
* reset all the active CSS class
*/
for (i = 0; i < projectAccordionLabel.length; i++) {
projectAccordionLabel[0].className = projectAccordionLabel[0].className.replace(" project-accordion-label--active", "");
document.getElementById(projectAccordionLabel[0].id.toLowerCase()).style.height = "0";
}
evt.currentTarget.className += " project-accordion-label--active";
//this.classList.toggle("project-accordion-label--active");
/**
* perform a hack to retrieve a specific accordion content id and then reveal its content by increasing its height
*/
document.getElementById(evt.currentTarget.id.toLowerCase()).style.height = "auto ";
document.getElementById(evt.currentTarget.id.toLowerCase()).style.marginTop = "5px";
} else {
/**
* perform a hack to retrieve a specific accordion content id and
* then close it if its already opened
*/
projectAccordionLabel[0].className = projectAccordionLabel[0].className.replace(" project-accordion-label--active", "");
document.getElementById(evt.currentTarget.id.toLowerCase()).style.height = "0";
document.getElementById(evt.currentTarget.id.toLowerCase()).style.marginTop = "0";
}
}
/**
* Add click event listener on sidenav-menu
* When any menu is click sidenav shutdown and bring anchored link into focus
*/
var sideNavMenu = document.getElementsByClassName("sidenav-menu");
////console.log("sideNavMenu.length = "+sideNavMenu.length);
for (var i = 0; i < sideNavMenu.length; i++) {
sideNavMenu[i].addEventListener("click", shutdownSideNav, false);
}
/**
* Shut down sidenav on sidenav menu click event
*/
function shutdownSideNav() {
if (document.getElementById("mySidenav").style.width != "") {
//document.getElementsByClassName("sidenav-icon")[0].classList.toggle("change");
document.getElementsByClassName("sidenav-icon")[0].className = document.getElementsByClassName("sidenav-icon")[0].className.replace(" change", "");
document.getElementById("mySidenav").style.width = "";
document.getElementsByClassName("sidenav-icon")[0].style.marginLeft = "";
document.getElementsByClassName("searchform")[0].style.display = "block";
projectAccordionLabel[0].className = projectAccordionLabel[0].className.replace(" project-accordion-label--active", "");
}
}
/**
* Add click event listener on sidenav-project-menu
*/
var sideNavProjMenu = document.getElementsByClassName("sidenav-project-menu");
////console.log("sideNavProjMenu.length = "+sideNavProjMenu.length);
for (var i = 0; i < sideNavProjMenu.length; i++) {
sideNavProjMenu[i].addEventListener("click", shutdownSideNavProjMenu, false);
}
/**
* Shut down sidenav on sidenav project menu click event
*/
function shutdownSideNavProjMenu() {
if (document.getElementById("mySidenav").style.width != "") {
//document.getElementsByClassName("sidenav-icon")[0].classList.toggle("change");
document.getElementsByClassName("sidenav-icon")[0].className = document.getElementsByClassName("sidenav-icon")[0].className.replace(" change", "");
document.getElementById("mySidenav").style.width = "";
document.getElementsByClassName("sidenav-icon")[0].style.marginLeft = "";
document.getElementsByClassName("searchform")[0].style.display = "block";
projectAccordionLabel[0].className = projectAccordionLabel[0].className.replace(" project-accordion-label--active", "");
}
}
/* search form hover efffect transformation */
var searchInput = document.getElementsByClassName("searchform-input")[0];
searchInput.onclick = function() {
document.getElementsByClassName("searchform-label")[0].style.top = "0px";
document.getElementsByClassName("searchform-label")[0].style.fontSize = "80%";
document.getElementsByClassName("searchform-window-modal")[0].style.display = "block";
}
/* search form modal mode */
var openSearchformModal = document.getElementsByClassName("searchform-open-modal")[0];
openSearchformModal.onclick = function() {
document.getElementsByClassName("searchform-modal")[0].style.display = "block";
}
/* close the opened modal */
window.onclick = function(evt) {
if (evt.target == document.getElementsByClassName("searchform-window-modal")[0]) {
document.getElementsByClassName("searchform-window-modal")[0].style.display = "none";
document.getElementsByClassName("searchform-label")[0].style.top = "23px";
document.getElementsByClassName("searchform-label")[0].style.fontSize = "100%";
}
if (evt.target == document.getElementsByClassName("searchform-modal")[0]) {
document.getElementsByClassName("searchform-modal")[0].style.display = "none";
}
}
|
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const LiveReloadPlugin = require('webpack-livereload-plugin');
module.exports = {
context: __dirname,
entry: ['./js/App.jsx', './scss/main.scss'],
devtool: 'eval',
output: {
path: path.join(__dirname, 'public'),
filename: 'bundle.js'
},
devServer: {
publicPath: '/public/',
historyApiFallback: true
},
resolve: {
extensions: ['.js', '.jsx', '.json']
},
stats: {
colors: true,
reasons: true,
chunks: true
},
module: {
rules: [
{
test: /\.jsx?$/,
loaders: ['babel-loader']
},
{
test: /(\.scss|\.css)$/,
loaders: [
require.resolve('style-loader'),
require.resolve('css-loader') +
'?sourceMap&modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
require.resolve('sass-loader') + '?sourceMap'
]
},
{
test: /\.(png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000'
}
]
},
plugins: [
// new ExtractTextPlugin({
// // define where to save the file
// filename: '[name].css',
// allChunks: true
// }),
new LiveReloadPlugin()
]
};
|
// All code points in the `ASCII` category as per Unicode v7.0.0:
[
0x0,
0x1,
0x2,
0x3,
0x4,
0x5,
0x6,
0x7,
0x8,
0x9,
0xA,
0xB,
0xC,
0xD,
0xE,
0xF,
0x10,
0x11,
0x12,
0x13,
0x14,
0x15,
0x16,
0x17,
0x18,
0x19,
0x1A,
0x1B,
0x1C,
0x1D,
0x1E,
0x1F,
0x20,
0x21,
0x22,
0x23,
0x24,
0x25,
0x26,
0x27,
0x28,
0x29,
0x2A,
0x2B,
0x2C,
0x2D,
0x2E,
0x2F,
0x30,
0x31,
0x32,
0x33,
0x34,
0x35,
0x36,
0x37,
0x38,
0x39,
0x3A,
0x3B,
0x3C,
0x3D,
0x3E,
0x3F,
0x40,
0x41,
0x42,
0x43,
0x44,
0x45,
0x46,
0x47,
0x48,
0x49,
0x4A,
0x4B,
0x4C,
0x4D,
0x4E,
0x4F,
0x50,
0x51,
0x52,
0x53,
0x54,
0x55,
0x56,
0x57,
0x58,
0x59,
0x5A,
0x5B,
0x5C,
0x5D,
0x5E,
0x5F,
0x60,
0x61,
0x62,
0x63,
0x64,
0x65,
0x66,
0x67,
0x68,
0x69,
0x6A,
0x6B,
0x6C,
0x6D,
0x6E,
0x6F,
0x70,
0x71,
0x72,
0x73,
0x74,
0x75,
0x76,
0x77,
0x78,
0x79,
0x7A,
0x7B,
0x7C,
0x7D,
0x7E,
0x7F
];
|
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class AndroidCalendar extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<path d="M368.005,272h-96v96h96V272z M336.005,64v32h-160V64h-48v32h-24.01c-22.002,0-40,17.998-40,40v272
c0,22.002,17.998,40,40,40h304.01c22.002,0,40-17.998,40-40V136c0-22.002-17.998-40-40-40h-24V64H336.005z M408.005,408h-304.01
V196h304.01V408z"></path>
</g>
</g>;
} return <IconBase>
<g>
<path d="M368.005,272h-96v96h96V272z M336.005,64v32h-160V64h-48v32h-24.01c-22.002,0-40,17.998-40,40v272
c0,22.002,17.998,40,40,40h304.01c22.002,0,40-17.998,40-40V136c0-22.002-17.998-40-40-40h-24V64H336.005z M408.005,408h-304.01
V196h304.01V408z"></path>
</g>
</IconBase>;
}
};AndroidCalendar.defaultProps = {bare: false}
|
'use strict';
var root = require('path').normalize(__dirname + '/../../..');
// Production specific configuration
// =================================
module.exports = {
// Server IP
ip: process.env.OPENSHIFT_NODEJS_IP ||
process.env.IP ||
undefined,
// Server port
port: process.env.OPENSHIFT_NODEJS_PORT ||
process.env.PORT ||
8080,
flatDb: {
file: root + '/flat.file.db'
}
};
|
(function($) {
// Templates
var notificationTemplate = _.template("\
<% for (var i = 0; i < notifications.length; i++) { %>\
<% var notification = notifications[i]; %>\
<li class='notification' data-next='<%= notification.next %>'>\
<div class='user-thumbnail pull-left'>\
<a href='<%= notification.user_url %>'>\
<img src='<%= notification.user_avatar %>' />\
</a>\
</div>\
<div class='notification-meta'>\
<a href='<%= notification.user_url %>'><%= notification.user_name %></a>\
<%= notification.message %>\
<% if (notification.item_name) { %>\
<a href='<%= notification.item_url %>'><%= notification.item_name %></a>.\
</div>\
<% if (notification.thank_you) { %>\
<div class='notification-text'>\
<%= notification.thank_you %>\
</div>\
<% } %>\
<% } %>\
<div class='timestamp pull-right'>\
<%= notification.time_since %> ago\
</div>\
<div style='clear: both;'></div>\
</li>\
<% } %>\
");
$.fn.loadNotifications = function(url) {
listSelector = $(this);
$.get(url, function(notifications) {
var list = notificationTemplate({ notifications: notifications });
listSelector.append(list);
listSelector.trigger('appended');
});
}
}) (jQuery);
|
// Requred by theme templates
window.jQuery = $ = require('jquery');
require('parsleyjs');
// Import Nav module
import * as nav from './modules/nav.js';
import * as login from './modules/login.js';
import * as searchbar from './modules/searchbar.js';
import Tabs from './modules/tabs.js';
import Modal from './modules/modal.js';
import Filter from './modules/filter.js';
var Drift = require('drift-zoom');
Filter();
// Kick off the nav js
nav.init();
searchbar.init();
login.init();
if (document.querySelectorAll('.js-tabs').length) {
var alltabs = document.querySelectorAll('.js-tabs');
[].forEach.call(alltabs, function(item, i) {
new Tabs(alltabs[i]);
});
}
if (document.querySelectorAll('.js-modal').length) {
var modals = document.querySelectorAll('.js-modal');
[].forEach.call(modals, function(item, i) {
new Modal(modals[i]);
});
}
if (document.querySelectorAll('#FeaturedImage').length && window.matchMedia('(min-width: 600px)').matches) {
new Drift(document.querySelector('#FeaturedImage'), {
paneContainer: document.querySelector('.gallery__fig'),
namespace: 'gallery__drift',
containInline: true
});
}
$('.js-parsley-validate form').parsley({
successClass: 'is-valid',
errorClass: 'is-error',
trigger: 'change',
classHandler: function(el) {
return el.$element.parent();
},
errorsWrapper: '<ul class="form__errors-list"></ul>',
errorTemplate: '<li class="form__error-item"></li>'
});
|
/*jslint browser: true, devel: true, node: true, nomen: true, es5: true*/
/*global angular, $ */
module.exports = [
{
name: "user",
pattern: function (odm) {
"use strict";
return {
title: String,
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
};
}
},
{
name: "blog",
pattern: {
title: String,
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
}
},
{
name: "articles",
pattern: function (odm) {
"use strict";
return {
title: String,
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
meta: {
votes: Number,
favs: Number
}
};
}
}
];
|
// import webpack plugins
import {
DefinePlugin,
BannerPlugin,
optimize,
} from 'webpack';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import CleanWebpackPlugin from 'clean-webpack-plugin';
function makeConfig({ paths, pkg, isLive, screwIE8 }) {
const banner = `${pkg.name} - ${pkg.version}\nMade with love by ${pkg.author}`;
if (isLive) {
console.log('Building for LIVE env...');
console.log(`Build root -> "${paths.liveBasePath}"`);
}
return {
// Define vendor entry point needed for splitting
entry: {
// Exclude all node_modules that hasn't a package.json as main file for example alt-utils
// vendor: Object.keys(pkg.dependencies).filter((v) => v !== 'alt-utils'),
vendor: Object.keys(pkg.dependencies),
},
output: {
// path: paths.build,
// filename: '[name]-[chunkhash].js',
// chunkFilename: '[chunkhash].js',
publicPath: isLive ? paths.liveBasePath : '/',
},
module: {
loaders: [
// Define CSS setup w/ ExtractTextPlugin
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style', [
'css?camelCase&modules&importLoaders=1&' +
'localIdentName=[folder]--[local]---[emoji:1]',
'postcss?sourceMap',
]),
include: paths.app,
},
],
},
plugins: [
new CleanWebpackPlugin([paths.build]),
// Output extracted CSS to a file
new ExtractTextPlugin('css/[name].css', {
// allChunks: true, // CHECK
}),
// extract vendor and manifest files removing duplicate modules (used both by app and vendor
// modules)
new optimize.CommonsChunkPlugin({
names: ['vendor', 'manifest'],
}),
// setting NODE_ENV to production reduces React library size
new DefinePlugin({
'process.env.NODE_ENV': '"production"',
}),
new optimize.OccurrenceOrderPlugin(),
new optimize.DedupePlugin(),
new optimize.UglifyJsPlugin({
compressor: {
screw_ie8: screwIE8,
warnings: false,
// drop `console` statements
drop_console: true,
},
mangle: {
screw_ie8: screwIE8,
},
output: {
comments: false,
screw_ie8: screwIE8,
},
}),
new BannerPlugin(banner, {
raw: false,
entryOnly: true,
}),
],
};
}
export default makeConfig;
|
var BlendFileReaderSample;
(function (BlendFileReaderSample) {
window.onload = function () {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'sample.blend');
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', function (e) {
var blendFile = BlendFileReader.readBlendFile(xhr.response);
ouputSample(blendFile);
});
xhr.send();
};
function getAddressText(address) {
var tempText = '00000000' + address.toString(16);
return tempText.substr(tempText.length - 8);
}
function ouputSample(blendFile) {
var file_element = document.getElementById('file');
var dna_element = document.getElementById('dna');
var blocks_element = document.getElementById('blocks');
var content_element = document.getElementById('content');
var result = [];
result.push(".blend version: " + blendFile.fileHeader.version_number);
file_element.innerHTML = result.join('<br/>');
// DNA
result = [];
result.push('[DNA]');
for (var _i = 0, _a = blendFile.dna.structureTypeInfoList; _i < _a.length; _i++) {
var typeInfo = _a[_i];
result.push(typeInfo.name);
for (var _b = 0, _c = typeInfo.fieldInfoList; _b < _c.length; _b++) {
var fieldInfo = _c[_b];
result.push(' ' + fieldInfo.definitionName + ': ' + fieldInfo.typeName + ' ' + fieldInfo.offset);
}
result.push('');
}
dna_element.innerHTML = result.join('<br/>');
// Data blocks
result = [];
result.push('[All data blocks]');
for (var _d = 0, _e = blendFile.bheadList; _d < _e.length; _d++) {
var bhead = _e[_d];
var typeInfo = blendFile.dna.structureTypeInfoList[bhead.SDNAnr];
result.push(bhead.code + ' ' + typeInfo.name + ' ' + getAddressText(bhead.old) + ' (' + bhead.nr.toString() + ')');
}
blocks_element.innerHTML = result.join('<br/>');
// Detail data samples
result = [];
result.push('[Data samples]');
var material_TypeInfo = blendFile.dna.getStructureTypeInfo('Material');
for (var _f = 0, _g = blendFile.bheadList; _f < _g.length; _f++) {
var bHead = _g[_f];
if (bHead.SDNAnr == material_TypeInfo.sdnaIndex) {
var dataset = blendFile.dna.createDataSet(bHead);
var out = 'Material ' + getAddressText(bHead.old) + ' (' + bHead.nr.toString() + ')' + '<br/>'
+ ' name: ' + dataset.id.name + '<br/>'
+ ' r: ' + dataset.r.toFixed(4) + '<br/>'
+ ' g: ' + dataset.g.toFixed(4) + '<br/>'
+ ' b: ' + dataset.b.toFixed(4) + '<br/>';
result.push(out);
}
}
var object_TypeInfo = blendFile.dna.getStructureTypeInfo('Object');
for (var _h = 0, _j = blendFile.bheadList; _h < _j.length; _h++) {
var bHead = _j[_h];
if (bHead.SDNAnr == object_TypeInfo.sdnaIndex) {
var dataset = blendFile.dna.createDataSet(bHead);
var out = 'Object ' + getAddressText(bHead.old) + ' (' + bHead.nr.toString() + ')' + '<br/>'
+ ' name: ' + dataset.id.name + '<br/>'
+ ' loc: (' + dataset.loc[0].toFixed(4)
+ ', ' + dataset.loc[1].toFixed(4)
+ ', ' + dataset.loc[2].toFixed(4) + ')<br/>';
result.push(out);
}
}
content_element.innerHTML = result.join('<br/>');
}
})(BlendFileReaderSample || (BlendFileReaderSample = {}));
|
const GraphQL = require('graphql');
const {
GraphQLSchema,
GraphQLObjectType,
GraphQLString,
graphql
} = GraphQL;
const graphqlMiddleware = require('graphql-middleware').default;
const ExampleType = new GraphQLObjectType({
name: 'Example',
fields: {
id: {
type: GraphQLString
},
name: {
type: GraphQLString
}
}
})
const querySchema = graphqlMiddleware({
name: 'RootQueryType',
fields: {
hello: {
beforeResolve (root, args, ctx) {
throw new Error('Test');
},
type: GraphQLString,
resolve (root, args, ctx) {
return 'world';
}
},
haha: {
type: ExampleType,
resolve () {
return {
id: 1
};
}
}
}
}, [
(root, args, ctx) => {
// throw new Error('Applies to all');
},
(root, args, ctx) => {
throw new Error('Applies to all after first');
},
]);
const schema = new GraphQLSchema({
query: new GraphQLObjectType(querySchema)
});
const query = '{ hello }';
graphql(schema, query).then((res) => {
console.log(res);
}).catch((err) => {
console.error(err.stack);
});
const queryTwo = '{ haha { id } }';
graphql(schema, queryTwo).then((res) => {
console.log(res);
}).catch((err) => {
console.error(err.stack);
});
|
/**
* Express configuration
*/
'use strict';
var express = require('express');
var morgan = require('morgan');
var compression = require('compression');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var errorHandler = require('errorhandler');
var path = require('path');
var config = require('./environment');
var passport = require('passport');
var favicon = require('serve-favicon');
module.exports = function (app) {
var env = app.get('env');
app.set('views', __dirname + '/server/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(favicon('apps/favicon.ico'));
app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(methodOverride());
app.use(cookieParser());
app.use(passport.initialize());
if ('production' === env) {
app.use(express.static(path.join(config.root, 'apps')));
app.use(express.static(path.join(config.root, 'assets')));
app.set('appPath', 'apps');
}
if ('development' === env || 'test' === env) {
app.use(express.static(path.join(config.root, 'apps')));
app.use(express.static(path.join(config.root, 'assets')));
app.set('appPath', 'apps');
app.use(morgan('dev'));
app.use(errorHandler());
}
};
|
import React from 'react';
import {storiesOf} from '@storybook/react';
import {chartAsReactComponent} from '../index';
import moment from 'moment';
import currentCount from './index';
const CurrentCount = chartAsReactComponent(currentCount);
storiesOf('Current Count', module)
.add('With current count, capacity, lastEvent', () => (
<CurrentCount currentCount={24} capacity={100} lastEvent={moment()} />
))
.add('With current count and capacity', () => (
<CurrentCount currentCount={24} capacity={100} />
))
.add('With a full capacity', () => (
<CurrentCount currentCount={100} capacity={100} />
))
.add('With a label', () => (
<CurrentCount currentCount={100} label="Current Count" capacity={100} />
))
|
const webpack = require('webpack');
var path = require('path');
module.exports = {
entry: {
'es-ES': './client/es-ES-loader',
'en-US': './client/en-US-loader',
'en-GB': './client/en-GB-loader'
},
output: {
path: path.join(__dirname, '/public/lib'),
filename: '[name].js',
publicPath: '/lib/'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin('index.js')
],
module: {
loaders: [
{
loader: 'babel-loader'
},
{
test: './client/actions/i18n.js',
loader: 'if-loader'
}
]
},
'if-loader': 'client-side'
};
|
/*!
* froala_editor v3.2.7 (https://www.froala.com/wysiwyg-editor)
* License https://froala.com/wysiwyg-editor/terms/
* Copyright 2014-2021 Froala Labs
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) :
typeof define === 'function' && define.amd ? define(['froala-editor'], factory) :
(factory(global.FroalaEditor));
}(this, (function (FE) { 'use strict';
FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE;
/**
* French
*/
FE.LANGUAGE['fr'] = {
translation: {
// Place holder
'Type something': 'Tapez quelque chose',
// Basic formatting
'Bold': 'Gras',
'Italic': 'Italique',
'Underline': "Soulign\xE9",
'Strikethrough': "Barr\xE9",
// Main buttons
'Insert': "Ins\xE9rer",
'Delete': 'Supprimer',
'Cancel': 'Annuler',
'OK': 'Ok',
'Back': 'Retour',
'Remove': 'Supprimer',
'More': 'Plus',
'Update': 'Actualiser',
'Style': 'Style',
// Font
'Font Family': "Polices de caract\xE8res",
'Font Size': 'Taille de police',
'Text Color': 'Couleur de police',
'Background Color': 'Couleur d\'arri\xE8re plan',
// Colors
'Colors': 'Couleurs',
'Background': "Arri\xE8re-plan",
'Text': 'Texte',
'HEX Color': "Couleur hexad\xE9cimale",
// Paragraphs
'Paragraph Format': 'Format de paragraphe',
'Normal': 'Normal',
'Code': 'Code',
'Heading 1': 'Titre 1',
'Heading 2': 'Titre 2',
'Heading 3': 'Titre 3',
'Heading 4': 'Titre 4',
'Line Height': 'Interligne',
'Single': 'Célibataire',
// Style
'Paragraph Style': 'Style de paragraphe',
'Inline Style': 'Style en ligne',
'Gray': 'Grise',
'Bordered': 'Bordé',
'Spaced': 'Espacé',
'Uppercase': 'Majuscule',
// Alignment
'Align': 'Aligner',
'Align Left': "Aligner \xE0 gauche",
'Align Center': 'Aligner au centre',
'Align Right': "Aligner \xE0 droite",
'Align Justify': 'Justifier',
'None': 'Aucun',
// Download PDF
'Download PDF': 'Télécharger le PDF',
// Inline Class
'Inline Class': 'Classe en ligne',
// Lists
'Ordered List': "Liste ordonn\xE9e",
'Unordered List': "Liste non ordonn\xE9e",
'Default': 'D\xE9faut',
'Circle': 'Cercle',
'Disc': 'Rond',
'Square': 'Carr\xE9',
'Lower Alpha': 'Alpha inf\xE9rieur',
'Lower Greek': 'Grec inf\xE9rieur',
'Lower Roman': 'Romain inf\xE9rieur',
'Upper Alpha': 'Alpha sup\xE9rieur',
'Upper Roman': 'Romain sup\xE9rieur',
// Indent
'Decrease Indent': 'Diminuer le retrait',
'Increase Indent': 'Augmenter le retrait',
// Links
'Insert Link': "Ins\xE9rer un lien",
'Open in new tab': 'Ouvrir dans un nouvel onglet',
'Open Link': 'Ouvrir le lien',
'Edit Link': 'Modifier le lien',
'Unlink': 'Enlever le lien',
'Choose Link': 'Choisir le lien',
// Images
'Insert Image': "Ins\xE9rer une image",
'Upload Image': "T\xE9l\xE9verser une image",
'By URL': 'Par URL',
'Browse': 'Parcourir',
'Drop image': 'Cliquer pour parcourir',
'or click': 'ou glisser/d\xE9poser en plein \xE9cran',
'Manage Images': "G\xE9rer les images",
'Loading': 'Chargement',
'Deleting': 'Suppression',
'Tags': "\xC9tiquettes",
'Are you sure? Image will be deleted.': "Etes-vous certain? L'image sera supprim\xE9e.",
'Replace': 'Remplacer',
'Uploading': 'Envoi en cours',
'Loading image': 'Chargement d\'image en cours',
'Display': 'Afficher',
'Inline': 'En ligne',
'Break Text': 'Rompre le texte',
'Alternative Text': 'Texte alternatif',
'Change Size': 'Changer la dimension',
'Width': 'Largeur',
'Height': 'Hauteur',
'Something went wrong. Please try again.': "Quelque chose a mal tourn\xE9. Veuillez r\xE9essayer.",
'Image Caption': "L\xE9gende de l'image",
'Advanced Edit': "\xC9dition avanc\xE9e",
// Video
'Insert Video': "Ins\xE9rer une vid\xE9o",
'Embedded Code': "Code int\xE9gr\xE9",
'Paste in a video URL': "Coller l'URL d'une vid\xE9o",
'Drop video': 'Cliquer pour parcourir',
'Your browser does not support HTML5 video.': "Votre navigateur ne supporte pas les vid\xE9os au format HTML5.",
'Upload Video': "T\xE9l\xE9verser une vid\xE9o",
// Tables
'Insert Table': "Ins\xE9rer un tableau",
'Table Header': "Ent\xEAte de tableau",
'Remove Table': 'Supprimer le tableau',
'Table Style': 'Style de tableau',
'Horizontal Align': 'Alignement horizontal',
'Row': 'Ligne',
'Insert row above': "Ins\xE9rer une ligne au-dessus",
'Insert row below': "Ins\xE9rer une ligne en-dessous",
'Delete row': 'Supprimer la ligne',
'Column': 'Colonne',
'Insert column before': "Ins\xE9rer une colonne avant",
'Insert column after': "Ins\xE9rer une colonne apr\xE8s",
'Delete column': 'Supprimer la colonne',
'Cell': 'Cellule',
'Merge cells': 'Fusionner les cellules',
'Horizontal split': 'Diviser horizontalement',
'Vertical split': 'Diviser verticalement',
'Cell Background': "Arri\xE8re-plan de la cellule",
'Vertical Align': 'Alignement vertical',
'Top': 'En haut',
'Middle': 'Au centre',
'Bottom': 'En bas',
'Align Top': 'Aligner en haut',
'Align Middle': 'Aligner au centre',
'Align Bottom': 'Aligner en bas',
'Cell Style': 'Style de cellule',
// Files
'Upload File': "T\xE9l\xE9verser un fichier",
'Drop file': 'Cliquer pour parcourir',
// Emoticons
'Emoticons': "\xC9motic\xF4nes",
'Grinning face': 'Souriant visage',
'Grinning face with smiling eyes': 'Souriant visage aux yeux souriants',
'Face with tears of joy': "Visage \xE0 des larmes de joie",
'Smiling face with open mouth': 'Visage souriant avec la bouche ouverte',
'Smiling face with open mouth and smiling eyes': 'Visage souriant avec la bouche ouverte et les yeux en souriant',
'Smiling face with open mouth and cold sweat': 'Visage souriant avec la bouche ouverte et la sueur froide',
'Smiling face with open mouth and tightly-closed eyes': "Visage souriant avec la bouche ouverte et les yeux herm\xE9tiquement clos",
'Smiling face with halo': 'Sourire visage avec halo',
'Smiling face with horns': 'Visage souriant avec des cornes',
'Winking face': 'Clin d\'oeil visage',
'Smiling face with smiling eyes': 'Sourire visage aux yeux souriants',
'Face savoring delicious food': "Visage savourant de d\xE9licieux plats",
'Relieved face': "Soulag\xE9 visage",
'Smiling face with heart-shaped eyes': 'Visage souriant avec des yeux en forme de coeur',
'Smiling face with sunglasses': 'Sourire visage avec des lunettes de soleil',
'Smirking face': 'Souriant visage',
'Neutral face': 'Visage neutre',
'Expressionless face': 'Visage sans expression',
'Unamused face': "Visage pas amus\xE9",
'Face with cold sweat': "Face \xE0 la sueur froide",
'Pensive face': 'pensif visage',
'Confused face': 'Visage confus',
'Confounded face': 'visage maudit',
'Kissing face': 'Embrasser le visage',
'Face throwing a kiss': 'Visage jetant un baiser',
'Kissing face with smiling eyes': 'Embrasser le visage avec les yeux souriants',
'Kissing face with closed eyes': "Embrasser le visage avec les yeux ferm\xE9s",
'Face with stuck out tongue': 'Visage avec sortait de la langue',
'Face with stuck out tongue and winking eye': 'Visage avec sortait de la langue et des yeux clignotante',
'Face with stuck out tongue and tightly-closed eyes': "Visage avec sortait de la langue et les yeux ferm\xE9s herm\xE9tiquement",
'Disappointed face': "Visage d\xE9\xE7u",
'Worried face': 'Visage inquiet',
'Angry face': "Visage en col\xE9re",
'Pouting face': 'Faire la moue face',
'Crying face': 'Pleurer visage',
'Persevering face': "Pers\xE9v\xE9rer face",
'Face with look of triumph': 'Visage avec le regard de triomphe',
'Disappointed but relieved face': "D\xE9\xE7u, mais le visage soulag\xE9",
'Frowning face with open mouth': "Les sourcils fronc\xE9s visage avec la bouche ouverte",
'Anguished face': "Visage angoiss\xE9",
'Fearful face': 'Craignant visage',
'Weary face': 'Visage las',
'Sleepy face': 'Visage endormi',
'Tired face': "Visage fatigu\xE9",
'Grimacing face': "Visage grima\xE7ante",
'Loudly crying face': 'Pleurer bruyamment visage',
'Face with open mouth': "Visage \xE0 la bouche ouverte",
'Hushed face': "Visage feutr\xE9e",
'Face with open mouth and cold sweat': "Visage \xE0 la bouche ouverte et la sueur froide",
'Face screaming in fear': 'Visage hurlant de peur',
'Astonished face': "Visage \xE9tonn\xE9",
'Flushed face': "Visage congestionn\xE9",
'Sleeping face': 'Visage au bois dormant',
'Dizzy face': 'Visage vertige',
'Face without mouth': 'Visage sans bouche',
'Face with medical mask': "Visage avec un masque m\xE9dical",
// Line breaker
'Break': 'Rompre',
// Math
'Subscript': 'Indice',
'Superscript': 'Exposant',
// Full screen
'Fullscreen': "Plein \xE9cran",
// Horizontal line
'Insert Horizontal Line': "Ins\xE9rer une ligne horizontale",
// Clear formatting
'Clear Formatting': 'Effacer le formatage',
// Save
'Save': 'Sauvegarder',
// Undo, redo
'Undo': 'Annuler',
'Redo': "R\xE9tablir",
// Select all
'Select All': "Tout s\xE9lectionner",
// Code view
'Code View': 'Mode HTML',
// Quote
'Quote': 'Citation',
'Increase': 'Augmenter',
'Decrease': 'Diminuer',
// Quick Insert
'Quick Insert': 'Insertion rapide',
// Spcial Characters
'Special Characters': "Caract\xE8res sp\xE9ciaux",
'Latin': 'Latin',
'Greek': 'Grec',
'Cyrillic': 'Cyrillique',
'Punctuation': 'Ponctuation',
'Currency': 'Devise',
'Arrows': "Fl\xE8ches",
'Math': 'Math',
'Misc': 'Divers',
// Print.
'Print': 'Imprimer',
// Spell Checker.
'Spell Checker': 'Correcteur orthographique',
// Help
'Help': 'Aide',
'Shortcuts': 'Raccourcis',
'Inline Editor': "\xC9diteur en ligne",
'Show the editor': "Montrer l'\xE9diteur",
'Common actions': 'Actions communes',
'Copy': 'Copier',
'Cut': 'Couper',
'Paste': 'Coller',
'Basic Formatting': 'Formatage de base',
'Increase quote level': 'Augmenter le niveau de citation',
'Decrease quote level': 'Diminuer le niveau de citation',
'Image / Video': "Image / vid\xE9o",
'Resize larger': 'Redimensionner plus grand',
'Resize smaller': 'Redimensionner plus petit',
'Table': 'Table',
'Select table cell': "S\xE9lectionner la cellule du tableau",
'Extend selection one cell': "\xC9tendre la s\xE9lection d'une cellule",
'Extend selection one row': "\xC9tendre la s\xE9lection d'une ligne",
'Navigation': 'Navigation',
'Focus popup / toolbar': 'Focus popup / toolbar',
'Return focus to previous position': "Retourner l'accent sur le poste pr\xE9c\xE9dent",
// Embed.ly
'Embed URL': "URL int\xE9gr\xE9e",
'Paste in a URL to embed': "Coller une URL int\xE9gr\xE9e",
// Word Paste.
'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?': "Le contenu coll\xE9 provient d'un document Microsoft Word. Voulez-vous conserver le format ou le nettoyer?",
'Keep': 'Conserver',
'Clean': 'Nettoyer',
'Word Paste Detected': "Copiage de mots d\xE9tect\xE9",
// Character Counter
'Characters': 'Caract\xE8res',
// More Buttons
'More Text': 'Autres options de texte',
'More Paragraph': 'Autres options de paragraphe',
'More Rich': 'Autres options d\'enrichissement',
'More Misc': 'Autres fonctionnalit\xE9s diverses'
},
direction: 'ltr'
};
})));
//# sourceMappingURL=fr.js.map
|
(function (global) {
if (global.cpkb == undefined) {
global.cpkb = global.$c = {};
global.cpkb.app = global.$ca = {};
global.cpkb.locale = global.$cl = {};
//get resource text by key
$cl.get = global.$clg = function (key) {
if (key in cpkb.locale) { return cpkb.locale[key]; }
return key;
};
//define notification type and and event for the server response
$ca.notification = {
type: {
success: "success", error: "error", alert: "alert",
warning: "warning", information: "information", confirmation: "confirmation"
},
clientNotificationReceiveEvent: "client.notification.received",
serverNotificationReceivedEvent: "server.notification.received",
serverUserAuthenticatedEvent: "server.notification.userAuthenticated",
serverUserSignOutEvent: "server.notification.userSignOut",
tokenUserCreated: "notification.tokenUserCreated",
userAuthenticationRequired: "notification.userAuthenticationRequired",
selectableListValueChanged: "notification.selectableListValueChanged",
pageNumberChanged: "notification.pageNumberChanged",
progressOperationBeginEvent: "progressOperationBeginEvent",
progressOperationEndEvent: "progressOperationEndEvent"
};
$ca.page = { firstPageNumber: 1 };
$ca.validateCurrentUser = function (user) {
if (!$ca.user || !$ca.user.userName() || $ca.user.isAuthenticated() !== true) return false;
return true;
};
$ca.isCurrentUserValid = ko.observable(false);
amplify.subscribe($ca.notification.tokenUserCreated, function (tokenUser) {
$ca.user = tokenUser;
$ca.isCurrentUserValid($ca.validateCurrentUser());
});
}
})(window);
|
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});/**
* Created by adi on 9/30/2015.
*/
|
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.0.1
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { EventService } from "../eventService";
import { Autowired, PreDestroy } from "./context";
import { forEach } from '../utils/array';
import { addSafePassiveEventListener } from "../utils/event";
var BeanStub = /** @class */ (function () {
function BeanStub() {
var _this = this;
this.destroyFunctions = [];
this.destroyed = false;
// for vue 3 - prevents Vue from trying to make this (and obviously any sub classes) from being reactive
// prevents vue from creating proxies for created objects and prevents identity related issues
this.__v_skip = true;
this.getContext = function () { return _this.context; };
this.isAlive = function () { return !_this.destroyed; };
}
// this was a test constructor niall built, when active, it prints after 5 seconds all beans/components that are
// not destroyed. to use, create a new grid, then api.destroy() before 5 seconds. then anything that gets printed
// points to a bean or component that was not properly disposed of.
// constructor() {
// setTimeout(()=> {
// if (this.isAlive()) {
// let prototype: any = Object.getPrototypeOf(this);
// const constructor: any = prototype.constructor;
// const constructorString = constructor.toString();
// const beanName = constructorString.substring(9, constructorString.indexOf("("));
// console.log('is alive ' + beanName);
// }
// }, 5000);
// }
// CellComp and GridComp and override this because they get the FrameworkOverrides from the Beans bean
BeanStub.prototype.getFrameworkOverrides = function () {
return this.frameworkOverrides;
};
BeanStub.prototype.destroy = function () {
// let prototype: any = Object.getPrototypeOf(this);
// const constructor: any = prototype.constructor;
// const constructorString = constructor.toString();
// const beanName = constructorString.substring(9, constructorString.indexOf("("));
this.destroyFunctions.forEach(function (func) { return func(); });
this.destroyFunctions.length = 0;
this.destroyed = true;
this.dispatchEvent({ type: BeanStub.EVENT_DESTROYED });
};
BeanStub.prototype.addEventListener = function (eventType, listener) {
if (!this.localEventService) {
this.localEventService = new EventService();
}
this.localEventService.addEventListener(eventType, listener);
};
BeanStub.prototype.removeEventListener = function (eventType, listener) {
if (this.localEventService) {
this.localEventService.removeEventListener(eventType, listener);
}
};
BeanStub.prototype.dispatchEventAsync = function (event) {
var _this = this;
window.setTimeout(function () { return _this.dispatchEvent(event); }, 0);
};
BeanStub.prototype.dispatchEvent = function (event) {
if (this.localEventService) {
this.localEventService.dispatchEvent(event);
}
};
BeanStub.prototype.addManagedListener = function (object, event, listener) {
var _this = this;
if (this.destroyed) {
return;
}
if (object instanceof HTMLElement) {
addSafePassiveEventListener(this.getFrameworkOverrides(), object, event, listener);
}
else {
object.addEventListener(event, listener);
}
var destroyFunc = function () {
object.removeEventListener(event, listener);
_this.destroyFunctions = _this.destroyFunctions.filter(function (fn) { return fn !== destroyFunc; });
return null;
};
this.destroyFunctions.push(destroyFunc);
return destroyFunc;
};
BeanStub.prototype.addDestroyFunc = function (func) {
// if we are already destroyed, we execute the func now
if (this.isAlive()) {
this.destroyFunctions.push(func);
}
else {
func();
}
};
BeanStub.prototype.createManagedBean = function (bean, context) {
var res = this.createBean(bean, context);
this.addDestroyFunc(this.destroyBean.bind(this, bean, context));
return res;
};
BeanStub.prototype.createBean = function (bean, context, afterPreCreateCallback) {
return (context || this.getContext()).createBean(bean, afterPreCreateCallback);
};
BeanStub.prototype.destroyBean = function (bean, context) {
return (context || this.getContext()).destroyBean(bean);
};
BeanStub.prototype.destroyBeans = function (beans, context) {
var _this = this;
if (beans) {
forEach(beans, function (bean) { return _this.destroyBean(bean, context); });
}
return [];
};
BeanStub.EVENT_DESTROYED = 'destroyed';
__decorate([
Autowired('frameworkOverrides')
], BeanStub.prototype, "frameworkOverrides", void 0);
__decorate([
Autowired('context')
], BeanStub.prototype, "context", void 0);
__decorate([
Autowired('eventService')
], BeanStub.prototype, "eventService", void 0);
__decorate([
Autowired('gridOptionsWrapper')
], BeanStub.prototype, "gridOptionsWrapper", void 0);
__decorate([
PreDestroy
], BeanStub.prototype, "destroy", null);
return BeanStub;
}());
export { BeanStub };
|
var http = require('http');
var Promise = require("promised-io/promise").Promise;
var _ = require('underscore');
var Integration = {
testRequest: function(opts, confs, callback) {
"use strict";
var promiseResult;
var promise = new Promise();
opts = opts || {};
opts.port = confs.port;
opts.headers = opts.headers || {
"Content-Type": "application/json"
};
var req = http.request(opts, function(res) {
var statusCode = res.statusCode;
var headers = res.headers;
var body = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
if(headers['content-type'] === 'application/json') {
body = body !== '' ? JSON.parse(body) : {};
}
promise.resolve({statusCode: statusCode, headers: headers, body: body});
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
if(opts.body) {
req.write(JSON.stringify(opts.body));
}
req.end();
promise.then(function() {
promiseResult = arguments;
});
waitsFor(function() {
return promiseResult;
});
runs(function() {
callback.apply(this, promiseResult);
});
}
};
var Common = {
waitsForPromise: function(promise) {
"use strict";
promise.then(function resolved() {
promise.resolved = true;
promise.result = _.toArray(arguments);
}, function rejected() {
promise.rejected = true;
promise.result = _.toArray(arguments);
});
waitsFor(function() {
return promise.resolved || promise.rejected;
});
},
spyOnPromise: function(Klass, method) {
"use strict";
if(!method) {
throw "Please give the method to spy as a String";
}
var spy = spyOn(Klass, method);
var realPromise = new Promise();
return {
andCallSuccess: function(returnValue) {
spy.andReturn({
then: function(callback) {
callback(returnValue);
}
});
},
andCallError: function(errorValue) {
spy.andReturn({
then: function(callback, error) {
error(errorValue);
}
});
},
andCallRealSuccess: function(returnValue) {
realPromise.resolve(returnValue);
spy.andReturn(realPromise);
return realPromise;
},
andCallRealError: function(errorValue) {
realPromise.reject(errorValue);
spy.andReturn(realPromise);
return realPromise;
}
};
}
};
module.exports = {
Integration: Integration,
Common: Common
};
|
import template from './trends-chart.html';
import Chart from 'chart.js';
export default {
template,
bindings: {
array: '<',
count: '<',
},
controller: ['$scope', controllerFunc],
};
function controllerFunc($scope) {
this.chartType = 'line';
$scope.$watch('$ctrl.count', () => {
const params = (this.array[0] && this.array[0].sequence) ? this.array[0].sequence : null;
if (params) this.createChart();
});
$scope.$watch('$ctrl.chartType', () => {
if ($scope.myTrendsChart) this.createChart();
});
this.createChart = () => {
if ($scope.myTrendsChart) $scope.myTrendsChart.destroy();
const newctx = document.getElementById('myTrendsChart');
const datasets = createDataSets(this.array);
$scope.myTrendsChart = new Chart(newctx, {
type: this.chartType,
lineTension: 0.2,
borderWidth: (this.chartType === 'bar') ? 1 : 4,
data: {
labels: ['Feb', 'March', 'April', 'May', 'June', 'July'],
datasets,
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
},
}],
},
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: function(tooltipItems, data) { // eslint-disable-line
return '$' + Math.floor(tooltipItems.yLabel); // eslint-disable-line
},
},
},
responsive: true,
maintainAspectRatio: true,
},
});
};
function createDataSets(myarray) {
const sets = [];
myarray.forEach((e) => {
sets.push(
{
label: `${e.name} `,
data: [
e.sequence[1].avgAdm || 0,
e.sequence[2].avgAdm || 0,
e.sequence[3].avgAdm || 0,
e.sequence[4].avgAdm || 0,
e.sequence[5].avgAdm || 0,
e.sequence[6].avgAdm || 0,
],
// backgroundColor: [
// `rgba(${255 - index * 30}, 159, ${100 + index * 30}, 0.5)`,
// `rgba(${255 - index * 30}, 159, ${100 + index * 30}, 0.5)`,
// `rgba(${255 - index * 30}, 159, ${100 + index * 30}, 0.5)`,
// `rgba(${255 - index * 30}, 159, ${100 + index * 30}, 0.5)`,
// `rgba(${255 - index * 30}, 159, ${100 + index * 30}, 0.5)`,
// `rgba(${255 - index * 30}, 159, ${100 + index * 30}, 0.5)`,
// // 'hsla(50, 70%, 50%, 1)',
// ],
// borderColor: [
// `rgba(${255 - index * 2}, 159, ${100 + index * 2}, 0.8)`,
// `rgba(${255 - index * 2}, 159, ${100 + index * 2}, 0.8)`,
// `rgba(${255 - index * 2}, 159, ${100 + index * 2}, 0.8)`,
// `rgba(${255 - index * 2}, 159, ${100 + index * 2}, 0.8)`,
// `rgba(${255 - index * 2}, 159, ${100 + index * 2}, 0.8)`,
// `rgba(${255 - index * 2}, 159, ${100 + index * 2}, 0.8)`,
// ],
backgroundColor: 'rgba(255, 155, 130, 0.5)',
borderColor: 'rgba(255, 155, 130, 0.5)',
fill: false,
}
);
}, this);
return sets;
}
this.createChart();
}
|
// Taken from https://github.com/netlify/netlify-identity-widget
const routes = /(confirmation|invite|recovery|email_change)_token=([^&]+)/
const errorRoute = /error=access_denied&error_description=403/
const accessTokenRoute = /access_token=/
exports.onInitialClientRender = (
_,
{ enableIdentityWidget = true, publicPath = `admin` }
) => {
const hash = (document.location.hash || ``).replace(/^#\/?/, ``)
if (
enableIdentityWidget &&
(routes.test(hash) || errorRoute.test(hash) || accessTokenRoute.test(hash))
) {
import(`netlify-identity-widget`).then(
({ default: netlifyIdentityWidget }) => {
netlifyIdentityWidget.on(`init`, user => {
if (!user) {
netlifyIdentityWidget.on(`login`, () => {
document.location.href = `${__PATH_PREFIX__}/${publicPath}/`
})
}
})
netlifyIdentityWidget.init()
}
)
}
}
|
"use strict";
exports["default"] = {
CLASSES: {
'alert': 'alert',
'button': 'btn',
'button-group': 'btn-group',
'button-toolbar': 'btn-toolbar',
'column': 'col',
'input-group': 'input-group',
'form': 'form',
'glyphicon': 'glyphicon',
'label': 'label',
'panel': 'panel',
'panel-group': 'panel-group',
'progress-bar': 'progress-bar',
'nav': 'nav',
'navbar': 'navbar',
'modal': 'modal',
'row': 'row',
'well': 'well'
},
STYLES: {
'default': 'default',
'primary': 'primary',
'success': 'success',
'info': 'info',
'warning': 'warning',
'danger': 'danger',
'link': 'link',
'inline': 'inline',
'tabs': 'tabs',
'pills': 'pills'
},
SIZES: {
'large': 'lg',
'medium': 'md',
'small': 'sm',
'xsmall': 'xs'
},
GLYPHS: [
'asterisk',
'plus',
'euro',
'minus',
'cloud',
'envelope',
'pencil',
'glass',
'music',
'search',
'heart',
'star',
'star-empty',
'user',
'film',
'th-large',
'th',
'th-list',
'ok',
'remove',
'zoom-in',
'zoom-out',
'off',
'signal',
'cog',
'trash',
'home',
'file',
'time',
'road',
'download-alt',
'download',
'upload',
'inbox',
'play-circle',
'repeat',
'refresh',
'list-alt',
'lock',
'flag',
'headphones',
'volume-off',
'volume-down',
'volume-up',
'qrcode',
'barcode',
'tag',
'tags',
'book',
'bookmark',
'print',
'camera',
'font',
'bold',
'italic',
'text-height',
'text-width',
'align-left',
'align-center',
'align-right',
'align-justify',
'list',
'indent-left',
'indent-right',
'facetime-video',
'picture',
'map-marker',
'adjust',
'tint',
'edit',
'share',
'check',
'move',
'step-backward',
'fast-backward',
'backward',
'play',
'pause',
'stop',
'forward',
'fast-forward',
'step-forward',
'eject',
'chevron-left',
'chevron-right',
'plus-sign',
'minus-sign',
'remove-sign',
'ok-sign',
'question-sign',
'info-sign',
'screenshot',
'remove-circle',
'ok-circle',
'ban-circle',
'arrow-left',
'arrow-right',
'arrow-up',
'arrow-down',
'share-alt',
'resize-full',
'resize-small',
'exclamation-sign',
'gift',
'leaf',
'fire',
'eye-open',
'eye-close',
'warning-sign',
'plane',
'calendar',
'random',
'comment',
'magnet',
'chevron-up',
'chevron-down',
'retweet',
'shopping-cart',
'folder-close',
'folder-open',
'resize-vertical',
'resize-horizontal',
'hdd',
'bullhorn',
'bell',
'certificate',
'thumbs-up',
'thumbs-down',
'hand-right',
'hand-left',
'hand-up',
'hand-down',
'circle-arrow-right',
'circle-arrow-left',
'circle-arrow-up',
'circle-arrow-down',
'globe',
'wrench',
'tasks',
'filter',
'briefcase',
'fullscreen',
'dashboard',
'paperclip',
'heart-empty',
'link',
'phone',
'pushpin',
'usd',
'gbp',
'sort',
'sort-by-alphabet',
'sort-by-alphabet-alt',
'sort-by-order',
'sort-by-order-alt',
'sort-by-attributes',
'sort-by-attributes-alt',
'unchecked',
'expand',
'collapse-down',
'collapse-up',
'log-in',
'flash',
'log-out',
'new-window',
'record',
'save',
'open',
'saved',
'import',
'export',
'send',
'floppy-disk',
'floppy-saved',
'floppy-remove',
'floppy-save',
'floppy-open',
'credit-card',
'transfer',
'cutlery',
'header',
'compressed',
'earphone',
'phone-alt',
'tower',
'stats',
'sd-video',
'hd-video',
'subtitles',
'sound-stereo',
'sound-dolby',
'sound-5-1',
'sound-6-1',
'sound-7-1',
'copyright-mark',
'registration-mark',
'cloud-download',
'cloud-upload',
'tree-conifer',
'tree-deciduous'
]
};
|
/*!
* jQuery QueryBuilder 2.3.2
* Locale: Romanian (ro)
* Author: ArianServ
* Licensed under MIT (http://opensource.org/licenses/MIT)
*/
(function (root, factory) {
if (typeof define == 'function' && define.amd) {
define(['jquery', 'query-builder'], factory);
}
else {
factory(root.jQuery);
}
}(this, function ($) {
"use strict";
var QueryBuilder = $.fn.queryBuilder;
QueryBuilder.regional['ro'] = {
"__locale": "Romanian (ro)",
"__author": "ArianServ",
"add_rule": "Adaugă regulă",
"add_group": "Adaugă grup",
"delete_rule": "Şterge",
"delete_group": "Şterge",
"conditions": {
"AND": "ŞI",
"OR": "SAU"
},
"operators": {
"equal": "egal",
"not_equal": "diferit",
"in": "în",
"not_in": "nu în",
"less": "mai puţin",
"less_or_equal": "mai puţin sau egal",
"greater": "mai mare",
"greater_or_equal": "mai mare sau egal",
"begins_with": "începe cu",
"not_begins_with": "nu începe cu",
"contains": "conţine",
"not_contains": "nu conţine",
"ends_with": "se termină cu",
"not_ends_with": "nu se termină cu",
"is_empty": "este gol",
"is_not_empty": "nu este gol",
"is_null": "e nul",
"is_not_null": "nu e nul"
}
};
QueryBuilder.defaults({lang_code: 'ro'});
}));
|
// a simple random color picker
// clear previous program...
clearInterval();
// leds to choose from
var leds = [ LED1, LED2, LED3 ];
// state
var i;
var stop;
function dice() {
i++;
leds[i % 3].write(true);
leds[(i - 1) % 3].write(false);
if (i >= stop) return;
setTimeout(dice, i * 10);
}
function roll() {
i = 0;
stop = ~~(Math.random() * 25) + 5;
dice();
}
// register to the button press
setWatch(roll, BTN, { edge: "falling", repeat: true });
|
// notesForAppEngine.js
/**
The MIT License (MIT)
Copyright (c) 2014 James Mortensen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
var addFontAwesome = function() {
var fontAwesomeCSS = '//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css';
var fontAwesomeStyle = document.createElement('link');
fontAwesomeStyle.setAttribute('rel', 'stylesheet');
fontAwesomeStyle.setAttribute('href', fontAwesomeCSS);
document.head.appendChild(fontAwesomeStyle);
};
/**
* Get the key for the row using targetElement as a reference point.
*
* @param {DOMElement} targetElement Any direct child of the table row containing the key.
* @return {String} The unique key representing that row.
*/
var getKeyFromRow = function(targetElement) {
return $(targetElement).parent().parent().find('td.cbc input').val();
};
/**
* On click of a list item and on every keystroke, update the stored note.
*
* @param {jQueryElement} explorerEntitiesElement A jQuery object representing the table.
*/
var bindEventsToNotesBox = function(explorerEntitiesElement) {
var keyFilterer = new KeyFilterer();
explorerEntitiesElement.on('click keyup', '.notes-for-appengine-note input', function(event) {
if (event.type === 'keyup') {
var isValidKey = keyFilterer.isValidKey(event.keyCode);
var key = getKeyFromRow(event.currentTarget);
var value = $(event.currentTarget).val();
if (isValidKey) {
saveNotes(key, value);
}
}
});
};
/**
* Add click handler for note button.
*/
var bindClickEventForNotesButton = function() {
$('tr').on('click', 'span.notes-for-appengine-edit-note', function(event) {
var key = getKeyFromRow(event.currentTarget);
$(this).parent().parent().find('.notes-for-appengine-note input').focus();
});
};
/**
* Save the note in storage, using the datastore key as a key for the note.
*
* @param {String} key The datastore row key.
* @param {String} noteText The note to store.
*/
var saveNotes = function(key, noteText) {
var noteToStore = {};
noteToStore[key] = noteText;
chrome.storage.local.set(noteToStore, function() {});
};
/**
* Get notes from storage that match an array of keys.
*
* @param {Array} keysToFetch An array of strings representing keys.
* @return {Promise} The object containing the done, fail, progress methods.
*/
var getNotesFromStorage = function(keysToFetch) {
var deferred = $.Deferred();
chrome.storage.local.get(keysToFetch, function(notes) {
deferred.resolve(notes);
});
return deferred.promise();
};
/**
* Scrape the DOM for all of the Datastore keys that are visible on the page. This
* helps us limit the amount of data we fetch from storage to only what we actually
* need.
*
* @return {Array} The array of string keys found on the page.
*/
var getKeysFromPage = function() {
var inputKeyElements = $('.cbc input[name="key"]');
var keys = [];
for (var i = 0; i < inputKeyElements.length; i++) {
keys.push(inputKeyElements.eq(i).val());
}
return keys;
};
/**
* Insert the note text in the note fields in the DOM by mapping the notes to the
* corresponding row in the DOM table.
*
* @param {Object} notes The object containing key/value pairs.
*/
var insertNotesInPage = function(notes) {
if (notes === undefined) return;
var keys = Object.keys(notes);
keys.forEach(function(key) {
var value = notes[key];
$('.cbc input[value="' + key + '"]').parent().parent().find('.notes-for-appengine-note input').val(value);
});
};
/**
* Insert the column fields themselves into the DOM.
*
* @param {jQueryElement} explorerEntitiesElement jQuery DOM object representing the table.
*/
var insertNotesColumns = function(explorerEntitiesElement) {
var tableHeaderElement = explorerEntitiesElement.find('thead tr .cbc');
var editNoteElement = '<span class="fa fa-edit notes-for-appengine-edit-note"></span>';
var noteHeaderElement = '<th class="notes-for-appengine-note">Note</th>';
var noteElement = '<td class="notes-for-appengine-note"><input type="text"></input></td>';
tableHeaderElement.before(
'<th class="notes-for-appengine-edit-note-cell">' + editNoteElement + '</th>' + noteHeaderElement
);
var bodyHeaderElement = explorerEntitiesElement.find('tbody tr .cbc');
bodyHeaderElement.before(
'<td class="notes-for-appengine-edit-note-cell">' + editNoteElement + '</td>' + noteElement
);
};
/**
* We use Font Awesome for all icons, and load the CSS prior to the pageload event to speed up rendering.
*/
addFontAwesome();
/**
* Entry point to the content script. This loads all data on the page and binds all click and keydown
* events in the DOM, as well as retrieving the notes from storage and inserting them in the page.
*/
//window.addEventListener('load', function() {
var explorerEntitiesElement = $('#ae-datastore-explorer-entities');
insertNotesColumns(explorerEntitiesElement);
bindEventsToNotesBox(explorerEntitiesElement);
bindClickEventForNotesButton();
var keys = getKeysFromPage();
var notesResults = getNotesFromStorage(keys);
notesResults.done(function(notes) {
insertNotesInPage(notes);
});
//});
|
'use strict'
const checkRepeatable = ( task ) => {
if ( task.repeatableTime === 1 && checkDay( task.dayRef )) {
resetTask( task )
} else if ( task.repeatableTime === 2 && checkWeek( task.dayRef )) {
resetTask( task )
} else if ( task.repeatableTime === 3 && checkMonth( task.monthRef )) {
resetTask( task )
}
return
}
const resetTask = ( task ) => {
task.dayRef = getDay()
task.monthRef = getMonth()
task.completed = false
task.save()
}
const checkDay = ( day ) => {
if ( day === getDay() ) {
return false
} else {
return true
}
}
const checkWeek = ( day ) => {
if ( getWeek(day) === getWeek(getDay()) ) {
return false
} else {
return true
}
}
const checkMonth = ( month ) => {
if ( month === getMonth() ) {
return false
} else {
return true
}
}
const getDay = () => {
const now = new Date()
const start = new Date(now.getFullYear(), 0, 0)
const diff = now - start
const oneDay = 1000 * 60 * 60 * 24
const day = Math.floor(diff / oneDay)
return day
}
const getWeek = ( day ) => {
const thisDate = new Date()
const thisYear = thisDate.getFullYear()
const firstDate = new Date(`January 1 ${thisYear}`)
const firstWeekDay = firstDate.getDay()
const week = Math.floor( ( day + firstWeekDay ) / 7 )
return week
}
const getMonth = () => {
let now = new Date()
return now.getMonth()
}
module.exports = checkRepeatable
|
angular.module('WaffleApp').directive('waffleNewRoomForm', function() {
return {
restrict: 'E',
scope: {},
templateUrl: 'views/chat/new-room-form.html',
replace: true,
controller: 'NewRoomFormCtrl',
controllerAs: 'ctrl'
};
}).controller('NewRoomFormCtrl', ['RoomService', function(roomService) {
var self = this;
this.createRoom = function() {
roomService.create(self.newRoom);
self.newRoom = {};
};
}]);
|
import { Schema, model, joigoose } from 'config/mongoose'
import { setup } from 'helpers/crud'
import Joi from 'joi'
const joiSchema = Joi.object({
lead: Joi.any().meta({
type: Schema.Types.ObjectId,
ref: 'Lead'
}).required(),
subscription: Joi.any().meta({
type: Schema.Types.ObjectId,
ref: 'Subscription'
}).required(),
deliveredAt: Joi.date(),
deliveredTo: Joi.string(),
createdAt: Joi.date().default(Date.now, 'time of creation').required()
})
const schema = setup(new Schema(joigoose.convert(joiSchema)))
schema.index({ lead: 1, subscription: 1 }, { unique: true })
export default model('Communication', schema)
|
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
require('./chunk-92621ff7.js');
require('./helpers.js');
require('./chunk-9103eeda.js');
require('./chunk-bd1feb6c.js');
require('./chunk-c00639be.js');
var __chunk_5 = require('./chunk-13e039f5.js');
require('./chunk-adaa5792.js');
require('./chunk-2dc027c9.js');
require('./chunk-ae7e641a.js');
require('./chunk-3aaecc36.js');
require('./chunk-7b13241d.js');
require('./chunk-47e1b22b.js');
var __chunk_18 = require('./chunk-d9a33552.js');
var Plugin = {
install: function install(Vue) {
__chunk_5.registerComponent(Vue, __chunk_18.Datepicker);
}
};
__chunk_5.use(Plugin);
exports.BDatepicker = __chunk_18.Datepicker;
exports.default = Plugin;
|
import alt from '../alt';
import ImmutableUtil from 'alt/utils/ImmutableUtil';
import Immutable from 'immutable';
import OrdersActions from '../actions/orders_actions';
class OrdersStore {
constructor() {
this.orders = Immutable.List();
this.selectedStatus = 'all';
this.amountFilter = null;
this.bindListeners({
handleUpdateOrders: OrdersActions.UPDATE_ORDERS,
handleUpdateSelectedStatus: OrdersActions.UPDATE_SELECTED_STATUS,
handleUpdateAmountFilter: OrdersActions.UPDATE_AMOUNT_FILTER,
handleFetchOrders: OrdersActions.FETCH_ORDERS
});
}
handleUpdateOrders(orders) {
this.orders = orders;
}
handleUpdateSelectedStatus(status) {
this.selectedStatus = status;
}
handleUpdateAmountFilter(amount) {
this.amountFilter = amount;
}
handleFetchOrders() {
this.orders = [];
}
}
export default alt.createStore(ImmutableUtil(OrdersStore));
|
// jshint node:true
"use strict";
var traverse = require('./traverse');
var find = require('mout/array/find');
var insert = require('mout/array/insert');
// ---
var IMPLIED_GLOBALS = {'window':1, 'document':1};
var GLOBAL_CONTEXT = 'window';
var CUSTOM_CONTEXT = '__CUSTOM_CONTEXT__';
// ---
// simplify and delegate logic
var hooks = {};
var _globals;
var _root;
// ---
module.exports = function(ast) {
_globals = [];
_root = ast;
traverse(ast, function(node, parent){
node.parent = parent;
setupScope(node);
setupContext(node);
if (node.type in hooks) {
hooks[node.type](node);
}
});
_root = null;
return _globals;
};
// ---
function setupScope(node) {
// by default reuse parent scope
node.scope = (node.type === 'Program')? [] : node.parent.scope;
if (node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration') {
// Functions create a new "scope" that "augments" parent scope
node.scope = node.parent.scope.slice();
}
}
// gets reference to the "this" value
function setupContext(node) {
if (node.type === 'Program') {
node.context = GLOBAL_CONTEXT;
return;
}
// default context is the parent context
node.context = node.parent.context;
// IIFE (function(win){ win.x = 'x' }(window))
if ( isIIFE(node) ) {
var args = node.arguments;
var params = node.callee.params;
if (args.length && params.length) {
params.forEach(function(param, i){
var arg = args[i] || {};
var init = arg.type === 'ThisExpression'? node.context : arg.name;
addVarToScope(node, {
name: param.name,
init: init
});
});
}
node.context = node.parent.context;
return;
}
// function.call and function.apply change the context
if (node.type === 'CallExpression' &&
node.callee.type === 'MemberExpression' &&
(node.callee.property.name === 'call' || node.callee.property.name === 'apply')) {
var arg = node.arguments[0];
var ctx = (!arg || arg.type === 'ThisExpression' ||
(arg.type === 'Literal' && arg.value == null))? GLOBAL_CONTEXT : CUSTOM_CONTEXT;
addVarToScope(node, {
name: 'this',
init: ctx,
pointer: ctx
});
node.context = ctx;
return;
}
if ((node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration') && !isIIFE(node.parent)) {
// params are "free variables"
node.params.forEach(function(param){
addVarToScope(node, {
name: param.name,
init: undefined
});
});
// by default we assume that all properties of object use "this" to referece
// itself even tho this might not be true depending on how the method is
// called
if (node.parent.type === 'Property' ||
(node.parent.type === 'AssignmentExpression' &&
node.parent.left.type === 'MemberExpression')) {
node.context = CUSTOM_CONTEXT;
return;
}
}
}
function isIIFE(node){
return node.type === 'CallExpression' && node.callee.type === 'FunctionExpression';
}
// ---
hooks.VariableDeclaration = function(node){
node.declarations.forEach(function(declarator){
var init;
if (declarator.init) {
init = (declarator.init.type === 'ThisExpression')? 'this' : declarator.init.value;
}
addVarToScope(node, {
name: declarator.id.name,
init: init
});
if (node.parent.type === 'Program') {
addGlobal(declarator.id.name);
}
});
};
function addVarToScope(node, declarator) {
// pointer is a reference to the original var value
// in case the "init" points to another identifier
if (!declarator.pointer) {
if (declarator.init === 'this'){
declarator.pointer = node.context;
} else {
var p = getVar(node, declarator.init);
if (p) {
declarator.pointer = p.init;
} else {
declarator.pointer = declarator.init;
}
}
}
// need to remove previous var (since we overwrite the value)
node.scope.forEach(function(d, i, arr){
if (d.name === declarator.name) {
arr.splice(i, 1);
}
});
node.scope.push(declarator);
}
function addGlobal(varName){
insert(_globals, varName);
}
hooks.AssignmentExpression = function(node){
var left = node.left;
if (left.type === 'MemberExpression') {
if (( left.object.type === 'ThisExpression' && pointsToGlobal(node, 'this') ) ||
(left.object.type === 'Identifier' && pointsToGlobal(node, left.object.name))) {
// property can be a Literal obj['foo'] or an Identifier `obj.bar`
var prop = left.property;
addGlobal(prop.name || prop.value);
}
return;
}
// if identifier doesn't exist on scope it's an implied global
if (left.type === 'Identifier' && notInScope(node, left.name) ) {
addGlobal(left.name);
}
};
hooks.FunctionDeclaration = function(node){
if (node.parent.scope === _root.scope) {
addGlobal(node.id.name);
}
};
function pointsToGlobal(node, varName){
var declaration = getVar(node, varName);
return (declaration && declaration.pointer in IMPLIED_GLOBALS) ||
(varName === 'this' && node.context === GLOBAL_CONTEXT) ||
(!declaration && varName in IMPLIED_GLOBALS);
}
function notInScope(node, varName){
return !getVar(node, varName);
}
function getVar(node, varName){
return find(node.scope, {name: varName});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.