text
stringlengths 3
1.05M
|
---|
function createWidgetClock($container, options) {
let value = 0;
const render = () => {
$container.innerHTML = `
<div class="clock">
<p class="clock__title">${options.title}</p>
<p class="clock__value">${value}</p>
</div>
`;
};
return {
render,
init: () => {
value = 0;
render();
},
inc: () => {
value += 1;
render();
}
};
} |
$(function(){
$('#dataTables-example').DataTable({
responsive: false
});
$('#myModal').on('show.bs.modal',function(e){
var btn = $(e.relatedTarget);
var type = btn.data('type');
if(type == 'edit'){
var url = btn.data('url');
var update = btn.data('update');
var id = btn.data('id');
$('#myModal form').attr('action',update);
$('#myModal .modal-title').text("User Details");
$('#myModal #upduser').val("Update Details");
$('.password-field').hide();
getMandi(url,id,function(){});
}else if(type == 'insert'){
var url = btn.data('url');
var id = btn.data('id');
$('#myModal form').attr('action',url);
$('#myModal .modal-title').text("User Details");
$('#myModal #upduser').val("Insert Details");
$('.password-field').show();
getMandi(url,id,function(){});
}
});
$("#modal").click(function(){
//alert("hi");
//For User ID
var url = $(this).attr('data-url');
var url1 = $(this).attr('data-url1');
var url2 = $(this).attr('data-url2');
var url3 = $(this).attr('data-url3');
var url4 = $(this).attr('data-url4');
var url5 = $(this).attr('data-url5');
});
$("#upduser").click(function(){
var url = $('#myform').attr('action');
var data = $('#myform').serializeArray();
$.ajax({
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type:'POST',
url:url,
data:data,
success:function(res){
if(res.error){
var err = "";
var counter = 0;
var fieldname = "";
$.each(res.error,function(k,v){
if(counter==0)
{
fieldname = k;
}
err += v+"\n";
counter++;
});
alert(err);
if(fieldname!=0)
{
$("select[name='"+fieldname+"']").focus();
$("input[name='"+fieldname+"']").focus();
}
return false;
}else if(res.success){
location.reload();
}
}
});
});
});
function getMandi(url,id,cb){
$.ajax({
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type:'GET',
url:url,
success:function(res){
if(res.success){
var data = res.success;
$('#user_id').val(data.user_id);
$('#password').val(data.password);
$('#mobile_1').val(data.mobile_1);
$('#mobile_2').val(data.mobile_2);
$('#address_1').val(data.address_1);
$('#address_2').val(data.address_2);
$('#pincode').val(data.pincode);
$('#gstin').val(data.gstin);
$('#roles_id').val(data.roles_id);
$('#email_1').val(data.email_1);
$('#email_2').val(data.email_2);
$('#active').val(data.active);
}
cb();
}
});
}
|
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 26.1.9
description: >
Throws a TypeError if target is a Symbol
info: |
26.1.9 Reflect.has ( target, propertyKey )
1. If Type(target) is not Object, throw a TypeError exception.
...
features: [Reflect, Symbol]
---*/
assert.throws(TypeError, function() {
Reflect.has(Symbol(1), 'p');
});
|
import actions from './actions';
const initState = {
allProposals: [],
tag: undefined,
selectedProposal: -1,
filterAttr: { },
composeProposal: false,
replyProposal: false,
searchString: ''
};
export default function proposalReducer(state = initState, action) {
switch (action.type) {
case actions.STORE_PROPOSAL:
return {
...state,
allProposals: action.proposals || []
}
case actions.FILTER_ATTRIBUTE:
return {
...state,
composeProposal: false,
replyProposal: false,
selectedproposal: -1,
filterAttr: { ...action.filterAttr }
};
case actions.SELECTED_PROPOSAL:
return {
...state,
replyProposal: false,
selectedProposal: action.selectedproposal,
allProposals: action.allproposals
};
case actions.REPLY_PROPOSAL:
return {
...state,
replyProposal: action.replyProposal
};
case actions.SEARCH_STRING:
return {
...state,
searchString: action.searchString
};
default:
return state;
}
}
|
/*
* Copyright (c) 2008-2015 Institut National de l'Information Geographique et Forestiere (IGN) France.
* Released under the BSD license.
*/
/*
* @requires Geoportal/OLS/UOM/Distance.js
*/
/**
* Class: Geoportal.OLS.UOM.Distance.Altitude
* The Geoportal framework Open Location Service support Altitude class.
*
* Inherits from:
* - <Geoportal.OLS.UOM.Distance>
*/
Geoportal.OLS.UOM.Distance.Altitude=
OpenLayers.Class(Geoportal.OLS.UOM.Distance, {
/**
* Constructor: Geoportal.OLS.UOM.Distance.Altitude
*
* Parameters:
* value - {Number} the distance measurement.
* options - {Object} An optional object whose properties will be set on
* this instance.
*/
initialize: function(value,options) {
Geoportal.OLS.UOM.Distance.prototype.initialize.apply(this,arguments);
},
/**
* APIMethod: destroy
* The destroy method is used to perform any clean up.
*/
destroy: function() {
Geoportal.OLS.UOM.Distance.prototype.destroy.apply(this,arguments);
},
/**
* Constant: CLASS_NAME
* {String} *"Geoportal.OLS.UOM.Distance.Altitude"*
*/
CLASS_NAME:"Geoportal.OLS.UOM.Distance.Altitude"
});
|
"""S3 bucket paths."""
from django.conf import settings
from storages.backends.s3boto import S3BotoStorage
class StaticStorage(S3BotoStorage):
"""Class for storage of static files in s3 bucket."""
location = settings.STATICFILES_LOCATION
class MediaStorage(S3BotoStorage):
"""Class for storage of media in s3 bucket."""
location = settings.MEDIAFILES_LOCATION
|
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const chai_1 = require("chai");
const __1 = require("..");
const plugins_1 = require("../plugins");
const MpSettingsCases_1 = require("./cases/MpSettingsCases");
const TestUtils_1 = __importDefault(require("./TestUtils"));
describe("AutoHostSelectorTest", function () {
before(function () {
TestUtils_1.default.configMochaAsSilent();
});
this.afterEach(() => {
plugins_1.DENY_LIST.players.clear();
});
async function prepareSelector(logIrc = false) {
const { lobby, ircClient } = await TestUtils_1.default.SetupLobbyAsync();
return { selector: new plugins_1.AutoHostSelector(lobby, { deny_list: [] }), lobby, ircClient };
}
function assertStateIs(state, s) {
const l = s.lobby;
switch (state) {
case "s0": // no players
chai_1.assert.equal(s.hostQueue.length, 0);
break;
case "s1": // no host
chai_1.assert.isTrue(s.hostQueue.length > 0);
chai_1.assert.isTrue(!l.isMatching);
chai_1.assert.isTrue(l.host == null);
break;
case "hr": // has host and needs to rotate
chai_1.assert.isTrue(s.hostQueue.length > 0, "s.hostQueue.length > 0");
chai_1.assert.isTrue(!l.isMatching), "!l.isMatching";
chai_1.assert.isTrue(s.needsRotate, "s.needsRotate");
chai_1.assert.isTrue(l.host != null, "l.host != null");
break;
case "hn": // has host and no needs to rotate
chai_1.assert.isTrue(s.hostQueue.length > 0);
chai_1.assert.isTrue(!l.isMatching);
chai_1.assert.isFalse(s.needsRotate);
chai_1.assert.isTrue(l.host != null);
break;
case "m": // matching
chai_1.assert.isTrue(s.hostQueue.length > 0);
chai_1.assert.isTrue(l.isMatching);
break;
default:
chai_1.assert.fail();
}
}
it("constructor test", async () => {
const { selector } = await prepareSelector();
assertStateIs("s0", selector);
});
it("dispose event test", (done) => {
prepareSelector().then(({ selector, ircClient }) => {
ircClient.part(ircClient.channel, "", () => {
chai_1.assert.isEmpty(selector.eventDisposers);
done();
});
});
});
describe("state transition tests", function () {
it("s0 -> h test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
assertStateIs("s0", selector);
await ircClient.emulateAddPlayerAsync("player1");
assertStateIs("hr", selector);
});
it("s0 -> s1 -> hr test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
ircClient.latency = 1;
let s1checked = false;
lobby.PlayerJoined.once(({ player, slot }) => {
chai_1.assert.equal(player.name, "player1");
assertStateIs("s1", selector);
s1checked = true;
});
assertStateIs("s0", selector);
await ircClient.emulateAddPlayerAsync("player1");
TestUtils_1.default.assertEventFire(lobby.HostChanged, (a) => {
assertStateIs("hr", selector);
chai_1.assert.isTrue(s1checked);
return true;
});
});
it("s0 -> hr -> s0 test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
assertStateIs("s0", selector);
await ircClient.emulateAddPlayerAsync("player1");
assertStateIs("hr", selector);
await TestUtils_1.default.delayAsync(10);
await ircClient.emulateRemovePlayerAsync("player1");
assertStateIs("s0", selector);
});
it("hr[1] -> hr[3] -> s0", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
assertStateIs("s0", selector);
const pids = ["player1", "player2", "player3"];
await TestUtils_1.default.AddPlayersAsync(pids, ircClient);
TestUtils_1.default.assertHost("player1", lobby);
assertStateIs("hr", selector);
await ircClient.emulateRemovePlayerAsync("player2");
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateRemovePlayerAsync("player1");
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player3", lobby);
await ircClient.emulateRemovePlayerAsync("player3");
assertStateIs("s0", selector);
});
it("hr -> m -> hr", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateMatchAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player2", lobby);
});
it("hr -> m -> hr repeat", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateMatchAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player2", lobby);
await ircClient.emulateMatchAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player3", lobby);
await ircClient.emulateMatchAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
});
it("hr -> hn -> m -> hr", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateChangeMapAsync(0);
assertStateIs("hr", selector);
await ircClient.emulateRemovePlayerAsync("player1");
assertStateIs("hn", selector);
TestUtils_1.default.assertHost("player2", lobby);
await ircClient.emulateMatchAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player2", lobby);
});
it("hr -[leave]-> hn -[change map]-> hr -> m -> hr", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateChangeMapAsync(0);
await ircClient.emulateRemovePlayerAsync("player1");
assertStateIs("hn", selector);
TestUtils_1.default.assertHost("player2", lobby);
await ircClient.emulateChangeMapAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player2", lobby);
await ircClient.emulateMatchAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player3", lobby);
});
it("hr -[transfer]-> hn -[change map]-> hr -> m -> hr", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateChangeMapAsync(0);
await ircClient.emulateChangeHost("player2");
assertStateIs("hn", selector);
TestUtils_1.default.assertHost("player2", lobby);
await ircClient.emulateChangeMapAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player2", lobby);
await ircClient.emulateMatchAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player3", lobby);
});
it("hr -> m -[abort]-> hn", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateChangeMapAsync(0);
assertStateIs("hr", selector);
await ircClient.emulateMatchAndAbortAsync(0, 0);
assertStateIs("hn", selector);
TestUtils_1.default.assertHost("player1", lobby);
});
// アボート後にホストがマップを変更するとhostが切り替わる
it("hr -> m -[abort]-> hn -[mapchange]-> hn -> hr", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateChangeMapAsync(0);
assertStateIs("hr", selector);
await ircClient.emulateMatchAndAbortAsync(0, 0);
assertStateIs("hn", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateChangeMapAsync(0);
assertStateIs("hn", selector);
TestUtils_1.default.assertHost("player2", lobby);
await ircClient.emulateChangeMapAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player2", lobby);
});
it("hr -> m -[abort]-> hn -[leave]-> hn -> hr", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateChangeMapAsync(0);
assertStateIs("hr", selector);
await ircClient.emulateMatchAndAbortAsync(0, 0);
assertStateIs("hn", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateRemovePlayerAsync("player1");
assertStateIs("hn", selector);
TestUtils_1.default.assertHost("player2", lobby);
await ircClient.emulateChangeMapAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player2", lobby);
});
it("hr -> s0 -> hr", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateChangeMapAsync(0);
assertStateIs("hr", selector);
await ircClient.emulateRemovePlayerAsync("player1");
assertStateIs("s0", selector);
await TestUtils_1.default.AddPlayersAsync(["player1"], ircClient);
TestUtils_1.default.assertHost("player1", lobby);
assertStateIs("hr", selector);
});
it("hr -> s0 -> hn -[map change]-> hr", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateChangeMapAsync(0);
assertStateIs("hr", selector);
await ircClient.emulateRemovePlayerAsync("player1");
assertStateIs("s0", selector);
await TestUtils_1.default.AddPlayersAsync(["player2", "player3"], ircClient);
TestUtils_1.default.assertHost("player2", lobby);
assertStateIs("hn", selector);
await ircClient.emulateMatchAsync(0);
TestUtils_1.default.assertHost("player2", lobby);
assertStateIs("hr", selector);
});
});
describe("join and left tests", function () {
// 試合中にプレイヤーが入ってきた場合、現在のホストの後ろに配置される
it("newcomer who join during the match should be enqueued after the currnt host.", async () => {
const { selector, lobby, ircClient } = await prepareSelector(false);
await TestUtils_1.default.AddPlayersAsync(["player1", "player2"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
const task = ircClient.emulateMatchAsync(4);
await TestUtils_1.default.delayAsync(1);
ircClient.emulateAddPlayerAsync("player3"); // join during the match
await task;
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player2", lobby);
await ircClient.emulateMatchAsync();
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby); // not player3
});
it("player left in the match", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
let task = ircClient.emulateMatchAsync(4);
await TestUtils_1.default.delayAsync(1);
await ircClient.emulateRemovePlayerAsync("player3");
await task;
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player2", lobby);
task = ircClient.emulateMatchAsync(4);
await TestUtils_1.default.delayAsync(1);
await ircClient.emulateRemovePlayerAsync("player2");
await task;
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateAddPlayerAsync("player4");
await ircClient.emulateAddPlayerAsync("player5");
await ircClient.emulateAddPlayerAsync("player6");
task = ircClient.emulateMatchAsync(4);
await TestUtils_1.default.delayAsync(1);
await ircClient.emulateRemovePlayerAsync("player1");
await task;
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player4", lobby);
});
it("transfer host manually test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateChangeHost("player2");
await TestUtils_1.default.delayAsync(1);
TestUtils_1.default.assertHost("player2", lobby);
await ircClient.emulateChangeHost("player1");
await TestUtils_1.default.delayAsync(1);
TestUtils_1.default.assertHost("player3", lobby);
await ircClient.emulateChangeHost("player3");
await TestUtils_1.default.delayAsync(1);
TestUtils_1.default.assertHost("player3", lobby);
await ircClient.emulateChangeHost("player2");
await TestUtils_1.default.delayAsync(1);
TestUtils_1.default.assertHost("player1", lobby);
});
it("appoint next host when current host leave", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateRemovePlayerAsync("player1");
await TestUtils_1.default.delayAsync(1);
TestUtils_1.default.assertHost("player2", lobby);
});
it("conflict transfer host manually and plugin rotation test1", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
const t1 = ircClient.emulateMatchAsync(1);
ircClient.latency = 1;
await t1;
ircClient.latency = 0;
await ircClient.emulateChangeHost("player3");
await TestUtils_1.default.delayAsync(10);
TestUtils_1.default.assertHost("player2", lobby);
});
it("conflict transfer host manually and plugin rotation test2", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
const t1 = ircClient.emulateMatchAsync(1);
ircClient.latency = 1;
await t1;
ircClient.latency = 0;
await ircClient.emulateChangeHost("player2");
await TestUtils_1.default.delayAsync(10);
TestUtils_1.default.assertHost("player2", lobby);
});
it("issue #37 host left and match started at the same time", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateChangeMapAsync(0);
ircClient.latency = 10; // it makes bot respond to !mp start command before !mp host command
await ircClient.emulateRemovePlayerAsync("player1");
ircClient.latency = 0;
const t1 = ircClient.emulateMatchAsync(20);
await TestUtils_1.default.delayAsync(10);
TestUtils_1.default.assertHost("player2", lobby);
assertStateIs("m", selector);
await t1;
TestUtils_1.default.assertHost("player2", lobby);
assertStateIs("hr", selector);
});
it("issue #37 test rotation after the issue", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateChangeMapAsync(0);
ircClient.latency = 10;
await ircClient.emulateRemovePlayerAsync("player1");
ircClient.latency = 0;
const t1 = ircClient.emulateMatchAsync(20);
await TestUtils_1.default.delayAsync(10);
TestUtils_1.default.assertHost("player2", lobby);
await t1;
TestUtils_1.default.assertHost("player2", lobby);
await ircClient.emulateChangeMapAsync(0);
await ircClient.emulateMatchAsync(0);
TestUtils_1.default.assertHost("player3", lobby);
});
it("issue #37 player2 dosen't change map test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateChangeMapAsync(0);
ircClient.latency = 10; // it makes bot respond to !mp start command before !mp host command
await ircClient.emulateRemovePlayerAsync("player1");
ircClient.latency = 0;
const t1 = ircClient.emulateMatchAsync(20);
await TestUtils_1.default.delayAsync(10);
TestUtils_1.default.assertHost("player2", lobby);
await t1;
TestUtils_1.default.assertHost("player2", lobby);
await ircClient.emulateMatchAsync(0);
TestUtils_1.default.assertHost("player3", lobby);
});
});
describe("external operation tests", function () {
it("plugin message skip test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
selector.SendPluginMessage("skip");
await TestUtils_1.default.delayAsync(5);
TestUtils_1.default.assertHost("player2", lobby);
});
it("plugin message skipto test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
selector.SendPluginMessage("skipto", ["player3"]);
await TestUtils_1.default.delayAsync(5);
TestUtils_1.default.assertHost("player3", lobby);
chai_1.assert.equal(selector.hostQueue[0].name, "player3");
chai_1.assert.equal(selector.hostQueue[1].name, "player1");
chai_1.assert.equal(selector.hostQueue[2].name, "player2");
selector.SendPluginMessage("skipto", ["player3"]);
await TestUtils_1.default.delayAsync(5);
TestUtils_1.default.assertHost("player3", lobby);
chai_1.assert.equal(selector.hostQueue[0].name, "player3");
chai_1.assert.equal(selector.hostQueue[1].name, "player1");
chai_1.assert.equal(selector.hostQueue[2].name, "player2");
});
});
describe("skip tests", function () {
it("should change host when changed map -> changed host -> map change -> match start", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateMatchAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player2", lobby);
await ircClient.emulateChangeMapAsync(0);
await ircClient.emulateRemovePlayerAsync("player2");
assertStateIs("hn", selector);
TestUtils_1.default.assertHost("player3", lobby);
await ircClient.emulateChangeMapAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player3", lobby);
await ircClient.emulateMatchAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
});
it("should not change host when changed map -> changed host -> started match", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
await ircClient.emulateMatchAsync(0);
await ircClient.emulateChangeMapAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player2", lobby);
await ircClient.emulateChangeMapAsync(0);
await ircClient.emulateRemovePlayerAsync("player2");
assertStateIs("hn", selector);
TestUtils_1.default.assertHost("player3", lobby);
await ircClient.emulateMatchAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player3", lobby);
await ircClient.emulateMatchAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
});
});
describe("match abort tests", function () {
it("should not change host if match is aborted before any player finished", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateMatchAndAbortAsync();
assertStateIs("hn", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateMatchAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player2", lobby);
});
it("should change host when match is aborted after some players finished", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateMatchAndAbortAsync(0, 1);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player2", lobby);
await ircClient.emulateMatchAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player3", lobby);
});
it("should change host when match start -> abort -> map change", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateMatchAndAbortAsync();
assertStateIs("hn", selector);
TestUtils_1.default.assertHost("player1", lobby);
await ircClient.emulateChangeMapAsync();
assertStateIs("hn", selector);
TestUtils_1.default.assertHost("player2", lobby);
await ircClient.emulateMatchAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player2", lobby);
});
it("should change host and be remainable when map change -> match start -> host left -> match abort", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
const players = await TestUtils_1.default.AddPlayersAsync(5, ircClient);
await ircClient.emulateMatchAsync(0);
await ircClient.emulateChangeMapAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost(players[1], lobby);
let t = ircClient.emulateMatchAsync(60);
await TestUtils_1.default.delayAsync(1);
await ircClient.emulateRemovePlayerAsync(players[1]);
assertStateIs("m", selector);
chai_1.assert.isNull(lobby.host);
lobby.AbortMatch();
await TestUtils_1.default.delayAsync(1);
assertStateIs("hn", selector);
TestUtils_1.default.assertHost(players[2], lobby);
await ircClient.emulateMatchAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost(players[2], lobby);
});
it("should not change host when -> match start -> host left -> match abort -> map change", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
const players = await TestUtils_1.default.AddPlayersAsync(5, ircClient);
await ircClient.emulateMatchAsync(0);
await ircClient.emulateChangeMapAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost(players[1], lobby);
let t = ircClient.emulateMatchAsync(30);
await TestUtils_1.default.delayAsync(1);
await ircClient.emulateRemovePlayerAsync(players[1]);
assertStateIs("m", selector);
chai_1.assert.isNull(lobby.host);
lobby.AbortMatch();
await TestUtils_1.default.delayAsync(1);
assertStateIs("hn", selector);
TestUtils_1.default.assertHost(players[2], lobby);
await ircClient.emulateChangeMapAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost(players[2], lobby);
});
it("should change host when -> match start -> host left -> player finish -> match abort -> map change", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
const players = await TestUtils_1.default.AddPlayersAsync(["a", "b", "c", "d"], ircClient);
await ircClient.emulateMatchAsync(0);
await ircClient.emulateChangeMapAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("b", lobby);
let t = ircClient.emulateMatchAndAbortAsync(10, ["a", "c", "d"]);
await TestUtils_1.default.delayAsync(1);
await ircClient.emulateRemovePlayerAsync("b");
assertStateIs("m", selector);
chai_1.assert.isNull(lobby.host);
await t;
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("c", lobby);
await ircClient.emulateChangeMapAsync(0);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("c", lobby);
});
});
describe("mp settings tests", function () {
it("empty lobby case1_1", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
const c = MpSettingsCases_1.MpSettingsCases.case1_1;
const q = ["p1", "p2", "p3", "p4", "p5"];
ircClient.emulateMpSettings(c);
for (let i = 0; i < selector.hostQueue.length; i++) {
chai_1.assert.equal(selector.hostQueue[i].name, q[i]);
}
});
it("empty lobby case1_2", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
const c = MpSettingsCases_1.MpSettingsCases.case1_2;
const q = ["p3", "p4", "p5", "p1", "p2"];
ircClient.emulateMpSettings(c);
for (let i = 0; i < selector.hostQueue.length; i++) {
chai_1.assert.equal(selector.hostQueue[i].name, q[i]);
}
});
it("change host test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
const c = MpSettingsCases_1.MpSettingsCases.case1_1;
const q1 = ["p1", "p2", "p3", "p4", "p5"];
const q2 = ["p3", "p4", "p5", "p1", "p2"];
ircClient.emulateMpSettings(c);
for (let i = 0; i < selector.hostQueue.length; i++) {
chai_1.assert.equal(selector.hostQueue[i].name, q1[i]);
}
selector.SkipTo("p3");
for (let i = 0; i < selector.hostQueue.length; i++) {
chai_1.assert.equal(selector.hostQueue[i].name, q2[i]);
}
if (lobby.host == null)
return;
chai_1.assert.isTrue(lobby.host.isHost);
chai_1.assert.equal(lobby.host.name, "p3");
ircClient.emulateMpSettings(c);
for (let i = 0; i < selector.hostQueue.length; i++) {
chai_1.assert.equal(selector.hostQueue[i].name, q1[i]);
}
chai_1.assert.equal(lobby.host.name, "p1");
});
it("mod queue test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
const c1 = MpSettingsCases_1.MpSettingsCases.case1_1;
const c3 = MpSettingsCases_1.MpSettingsCases.case1_3;
const q1 = ["p1", "p2", "p3", "p4", "p5"];
const q2 = ["p4", "p5", "p6", "p7", "p2"];
ircClient.emulateMpSettings(c1);
for (let i = 0; i < selector.hostQueue.length; i++) {
chai_1.assert.equal(selector.hostQueue[i].name, q1[i]);
}
ircClient.emulateMpSettings(c3);
for (let i = 0; i < selector.hostQueue.length; i++) {
chai_1.assert.equal(selector.hostQueue[i].name, q2[i], `${i} a-${selector.hostQueue[i].name} e-${q2[i]}`);
}
if (lobby.host == null)
chai_1.assert.fail();
else
chai_1.assert.equal(lobby.host.name, "p4");
});
it("reset queue test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
const c1 = MpSettingsCases_1.MpSettingsCases.case1_1;
const q1 = ["p1", "p2", "p3", "p4", "p5"];
const q2 = ["p4", "p5", "p6", "p7", "p2"];
ircClient.emulateMpSettings(c1);
for (let i = 0; i < selector.hostQueue.length; i++) {
chai_1.assert.equal(selector.hostQueue[i].name, q1[i]);
}
ircClient.emulateRemovePlayerAsync("p1");
selector.SkipTo("p3");
ircClient.emulateMpSettings(c1);
for (let i = 0; i < selector.hostQueue.length; i++) {
chai_1.assert.equal(selector.hostQueue[i].name, q1[i], `${i} a-${selector.hostQueue[i].name} e-${q2[i]}`);
}
if (lobby.host == null)
chai_1.assert.fail();
else
chai_1.assert.equal(lobby.host.name, "p1");
});
});
describe("reoder tests", function () {
it("reaoder", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
const players = await TestUtils_1.default.AddPlayersAsync(5, ircClient);
const od = ["p3", "p1", "p2", "p4", "p0"];
selector.Reorder(od.join(","));
await TestUtils_1.default.delayAsync(1);
TestUtils_1.default.assertHost("p3", lobby);
for (let i = 0; i < od.length; i++) {
chai_1.assert.equal(selector.hostQueue[i].name, od[i]);
}
});
it("disguised string", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
const players = await TestUtils_1.default.AddPlayersAsync(5, ircClient);
const disguised = "p0, p1, p2, p3, p4";
const od = ["p0", "p1", "p2", "p3", "p4"];
selector.SkipTo("p3");
await TestUtils_1.default.delayAsync(1);
selector.Reorder(disguised);
await TestUtils_1.default.delayAsync(1);
TestUtils_1.default.assertHost("p0", lobby);
for (let i = 0; i < od.length; i++) {
chai_1.assert.equal(selector.hostQueue[i].name, od[i]);
}
});
it("no change", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
const players = await TestUtils_1.default.AddPlayersAsync(5, ircClient);
const odtxt = "p0, p1, p2, p3, p4";
const od = ["p0", "p1", "p2", "p3", "p4"];
selector.Reorder(odtxt);
await TestUtils_1.default.delayAsync(1);
TestUtils_1.default.assertHost("p0", lobby);
for (let i = 0; i < od.length; i++) {
chai_1.assert.equal(selector.hostQueue[i].name, od[i]);
}
});
it("partially specify", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
const players = await TestUtils_1.default.AddPlayersAsync(5, ircClient);
const odtxt = "p3, p4, p2";
const od = ["p3", "p4", "p2", "p0", "p1"];
selector.Reorder(odtxt);
await TestUtils_1.default.delayAsync(1);
TestUtils_1.default.assertHost("p3", lobby);
for (let i = 0; i < od.length; i++) {
chai_1.assert.equal(selector.hostQueue[i].name, od[i]);
}
});
it("extra specify", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
const players = await TestUtils_1.default.AddPlayersAsync(5, ircClient);
const odtxt = "p3, p6, p4, p2, p5, p0, p1";
const od = ["p3", "p4", "p2", "p0", "p1"];
selector.Reorder(odtxt);
await TestUtils_1.default.delayAsync(1);
TestUtils_1.default.assertHost("p3", lobby);
for (let i = 0; i < od.length; i++) {
chai_1.assert.equal(selector.hostQueue[i].name, od[i]);
}
});
it("from custom command", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
lobby.option.authorized_users = ["p0"];
const players = await TestUtils_1.default.AddPlayersAsync(5, ircClient);
const odtxt = "*reorder p0, p1, p2, p3, p4";
const od = ["p0", "p1", "p2", "p3", "p4"];
selector.SkipTo("p3");
TestUtils_1.default.assertHost("p3", lobby);
await TestUtils_1.default.delayAsync(1);
await ircClient.emulateMessageAsync("p0", ircClient.channel, odtxt);
for (let i = 0; i < od.length; i++) {
chai_1.assert.equal(selector.hostQueue[i].name, od[i]);
}
});
it("invalid custom command", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
lobby.option.authorized_users = ["p0"];
const players = await TestUtils_1.default.AddPlayersAsync(5, ircClient);
let odtxt = "*reorder";
const od = ["p3", "p4", "p0", "p1", "p2"];
selector.SkipTo("p3");
TestUtils_1.default.assertHost("p3", lobby);
await TestUtils_1.default.delayAsync(1);
await ircClient.emulateMessageAsync("p0", ircClient.channel, odtxt);
for (let i = 0; i < od.length; i++) {
chai_1.assert.equal(selector.hostQueue[i].name, od[i]);
}
odtxt = "*reorder asdfsafasdf";
await TestUtils_1.default.delayAsync(1);
await ircClient.emulateMessageAsync("p0", ircClient.channel, odtxt);
for (let i = 0; i < od.length; i++) {
chai_1.assert.equal(selector.hostQueue[i].name, od[i]);
}
});
});
describe("cleared host tests", function () {
it("clearhost and match", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
lobby.SendMessage("!mp clearhost");
chai_1.assert.isTrue(lobby.isClearedHost);
chai_1.assert.isNull(lobby.host);
await ircClient.emulateMatchAsync();
TestUtils_1.default.assertHost("player2", lobby);
});
it("plugin skip test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await TestUtils_1.default.AddPlayersAsync(["player1", "player2", "player3"], ircClient);
assertStateIs("hr", selector);
TestUtils_1.default.assertHost("player1", lobby);
lobby.SendMessage("!mp clearhost");
chai_1.assert.isTrue(lobby.isClearedHost);
chai_1.assert.isNull(lobby.host);
selector.SendPluginMessage("skip");
await TestUtils_1.default.delayAsync(5);
TestUtils_1.default.assertHost("player2", lobby);
});
});
describe("denylist tests", function () {
it("denied player should ignore test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p3"));
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1);
chai_1.assert.equal(selector.hostQueue.length, 4);
chai_1.assert.equal(selector.hostQueue[0], lobby.GetOrMakePlayer("p1"));
chai_1.assert.equal(selector.hostQueue[1], lobby.GetOrMakePlayer("p2"));
chai_1.assert.equal(selector.hostQueue[2], lobby.GetOrMakePlayer("p4"));
chai_1.assert.equal(selector.hostQueue[3], lobby.GetOrMakePlayer("p5"));
lobby.destroy();
});
it("transfer host to denied player test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p4"));
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1);
chai_1.assert.equal(selector.hostQueue.length, 4);
TestUtils_1.default.assertHost("p1", lobby);
await ircClient.emulateChangeHost("p4");
TestUtils_1.default.assertHost("p2", lobby);
await ircClient.emulateChangeHost("p4");
TestUtils_1.default.assertHost("p3", lobby);
await ircClient.emulateChangeHost("p4");
TestUtils_1.default.assertHost("p5", lobby);
await ircClient.emulateChangeHost("p1");
TestUtils_1.default.assertHost("p1", lobby);
lobby.destroy();
});
it("only denied player test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p4"));
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p5"));
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1);
chai_1.assert.equal(selector.hostQueue.length, 3);
TestUtils_1.default.assertHost("p1", lobby);
await ircClient.emulateRemovePlayerAsync("p1");
TestUtils_1.default.assertHost("p2", lobby);
await ircClient.emulateRemovePlayerAsync("p3");
TestUtils_1.default.assertHost("p2", lobby);
await ircClient.emulateRemovePlayerAsync("p2");
chai_1.assert.equal(selector.hostQueue.length, 0);
chai_1.assert.isNull(lobby.host);
await ircClient.emulateRemovePlayerAsync("p4");
chai_1.assert.equal(selector.hostQueue.length, 0);
chai_1.assert.isNull(lobby.host);
lobby.destroy();
});
it("only denied player -> join someone test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p4"));
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p5"));
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1);
chai_1.assert.equal(selector.hostQueue.length, 3);
await ircClient.emulateRemovePlayerAsync("p1");
await ircClient.emulateRemovePlayerAsync("p2");
await ircClient.emulateRemovePlayerAsync("p3");
chai_1.assert.equal(selector.hostQueue.length, 0);
chai_1.assert.isNull(lobby.host);
await ircClient.emulateAddPlayerAsync("p6");
TestUtils_1.default.assertHost("p6", lobby);
lobby.destroy();
});
it("skipto command test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p4"));
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1);
selector.SendPluginMessage("skipto", ["p3"]);
TestUtils_1.default.assertHost("p3", lobby);
selector.SendPluginMessage("skipto", ["p4"]);
TestUtils_1.default.assertHost("p3", lobby);
lobby.destroy();
});
it("add player to denylist test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1);
TestUtils_1.default.assertHost("p1", lobby);
chai_1.assert.equal(selector.hostQueue.length, 5);
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p3"));
chai_1.assert.equal(selector.hostQueue.length, 4);
chai_1.assert.equal(selector.hostQueue[0], lobby.GetOrMakePlayer("p1"));
chai_1.assert.equal(selector.hostQueue[1], lobby.GetOrMakePlayer("p2"));
chai_1.assert.equal(selector.hostQueue[2], lobby.GetOrMakePlayer("p4"));
chai_1.assert.equal(selector.hostQueue[3], lobby.GetOrMakePlayer("p5"));
lobby.destroy();
});
it("add host to denylist test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1);
TestUtils_1.default.assertHost("p1", lobby);
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p1"));
TestUtils_1.default.assertHost("p2", lobby);
chai_1.assert.equal(selector.hostQueue[0], lobby.GetOrMakePlayer("p2"));
chai_1.assert.equal(selector.hostQueue[1], lobby.GetOrMakePlayer("p3"));
chai_1.assert.equal(selector.hostQueue[2], lobby.GetOrMakePlayer("p4"));
chai_1.assert.equal(selector.hostQueue[3], lobby.GetOrMakePlayer("p5"));
lobby.destroy();
});
it("add last player to denylist test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1);
TestUtils_1.default.assertHost("p1", lobby);
chai_1.assert.equal(selector.hostQueue.length, 5);
await ircClient.emulateRemovePlayerAsync("p1");
await ircClient.emulateRemovePlayerAsync("p2");
await ircClient.emulateRemovePlayerAsync("p3");
TestUtils_1.default.assertHost("p4", lobby);
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p5"));
TestUtils_1.default.assertHost("p4", lobby);
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p4"));
chai_1.assert.equal(selector.hostQueue.length, 0);
chai_1.assert.isNull(lobby.host);
lobby.destroy();
});
it("remove player from denlylist test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1);
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p3"));
TestUtils_1.default.assertHost("p1", lobby);
chai_1.assert.equal(selector.hostQueue.length, 4);
plugins_1.DENY_LIST.removePlayer(lobby.GetOrMakePlayer("p3"));
chai_1.assert.equal(selector.hostQueue.length, 5);
chai_1.assert.equal(selector.hostQueue[0], lobby.GetOrMakePlayer("p1"));
chai_1.assert.equal(selector.hostQueue[1], lobby.GetOrMakePlayer("p2"));
chai_1.assert.equal(selector.hostQueue[2], lobby.GetOrMakePlayer("p4"));
chai_1.assert.equal(selector.hostQueue[3], lobby.GetOrMakePlayer("p5"));
chai_1.assert.equal(selector.hostQueue[4], lobby.GetOrMakePlayer("p3"));
lobby.destroy();
});
it("remove player from denlylist test - no one in queue", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1);
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p1"));
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p2"));
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p3"));
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p4"));
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p5"));
chai_1.assert.equal(selector.hostQueue.length, 0);
plugins_1.DENY_LIST.removePlayer(lobby.GetOrMakePlayer("p3"));
chai_1.assert.equal(selector.hostQueue.length, 1);
chai_1.assert.equal(selector.hostQueue[0], lobby.GetOrMakePlayer("p3"));
TestUtils_1.default.assertHost("p3", lobby);
lobby.destroy();
});
it("slotbase reoder test1", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p3"));
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1);
chai_1.assert.equal(selector.hostQueue.length, 4);
chai_1.assert.equal(selector.hostQueue[0], lobby.GetOrMakePlayer("p1"));
chai_1.assert.equal(selector.hostQueue[1], lobby.GetOrMakePlayer("p2"));
chai_1.assert.equal(selector.hostQueue[2], lobby.GetOrMakePlayer("p4"));
chai_1.assert.equal(selector.hostQueue[3], lobby.GetOrMakePlayer("p5"));
lobby.destroy();
});
it("slotbase reoder test2", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p4"));
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_2);
chai_1.assert.equal(selector.hostQueue.length, 4);
chai_1.assert.equal(selector.hostQueue[0], lobby.GetOrMakePlayer("p3"));
chai_1.assert.equal(selector.hostQueue[1], lobby.GetOrMakePlayer("p5"));
chai_1.assert.equal(selector.hostQueue[2], lobby.GetOrMakePlayer("p1"));
chai_1.assert.equal(selector.hostQueue[3], lobby.GetOrMakePlayer("p2"));
lobby.destroy();
});
it("slotbase reoder test - host is denied", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p3"));
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_2);
chai_1.assert.equal(selector.hostQueue.length, 4);
chai_1.assert.equal(selector.hostQueue[0], lobby.GetOrMakePlayer("p1"));
chai_1.assert.equal(selector.hostQueue[1], lobby.GetOrMakePlayer("p2"));
chai_1.assert.equal(selector.hostQueue[2], lobby.GetOrMakePlayer("p4"));
chai_1.assert.equal(selector.hostQueue[3], lobby.GetOrMakePlayer("p5"));
lobby.destroy();
});
it("modify order test - stay", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p5"));
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1);
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_3);
chai_1.assert.equal(selector.hostQueue.length, 4);
chai_1.assert.equal(selector.hostQueue[0], lobby.GetOrMakePlayer("p4"));
chai_1.assert.equal(selector.hostQueue[1], lobby.GetOrMakePlayer("p6"));
chai_1.assert.equal(selector.hostQueue[2], lobby.GetOrMakePlayer("p7"));
chai_1.assert.equal(selector.hostQueue[3], lobby.GetOrMakePlayer("p2"));
lobby.destroy();
});
it("modify order test - leave", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p1"));
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1);
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_3);
chai_1.assert.equal(selector.hostQueue.length, 5);
chai_1.assert.equal(selector.hostQueue[0], lobby.GetOrMakePlayer("p4"));
chai_1.assert.equal(selector.hostQueue[1], lobby.GetOrMakePlayer("p5"));
chai_1.assert.equal(selector.hostQueue[2], lobby.GetOrMakePlayer("p6"));
chai_1.assert.equal(selector.hostQueue[3], lobby.GetOrMakePlayer("p7"));
chai_1.assert.equal(selector.hostQueue[4], lobby.GetOrMakePlayer("p2"));
lobby.destroy();
});
it("modify order test - join", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
plugins_1.DENY_LIST.addPlayer(lobby.GetOrMakePlayer("p7"));
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1);
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_3);
chai_1.assert.equal(selector.hostQueue.length, 4);
chai_1.assert.equal(selector.hostQueue[0], lobby.GetOrMakePlayer("p4"));
chai_1.assert.equal(selector.hostQueue[1], lobby.GetOrMakePlayer("p5"));
chai_1.assert.equal(selector.hostQueue[2], lobby.GetOrMakePlayer("p6"));
chai_1.assert.equal(selector.hostQueue[3], lobby.GetOrMakePlayer("p2"));
lobby.destroy();
});
describe("denylist command tests", () => {
it("add test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1);
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 0);
TestUtils_1.default.sendMessageAsOwner(lobby, "*denylist add p1");
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 1);
chai_1.assert.include(plugins_1.DENY_LIST.players, "p1");
TestUtils_1.default.sendMessageAsOwner(lobby, "*denylist add p2 sfd");
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 2);
chai_1.assert.include(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p2 sfd"));
TestUtils_1.default.sendMessageAsOwner(lobby, "*denylist add");
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 2);
let un = "asdf hello";
TestUtils_1.default.sendMessageAsOwner(lobby, "*denylist add " + un);
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 3);
chai_1.assert.include(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)(un));
lobby.destroy();
});
it("add twice test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1);
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 0);
TestUtils_1.default.sendMessageAsOwner(lobby, "*denylist add p1");
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 1);
chai_1.assert.include(plugins_1.DENY_LIST.players, "p1");
TestUtils_1.default.sendMessageAsOwner(lobby, "*denylist add p1");
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 1);
chai_1.assert.include(plugins_1.DENY_LIST.players, "p1");
lobby.destroy();
});
it("remove test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1);
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 0);
TestUtils_1.default.sendMessageAsOwner(lobby, "*denylist add p1");
TestUtils_1.default.sendMessageAsOwner(lobby, "*denylist add p2 piyo");
TestUtils_1.default.sendMessageAsOwner(lobby, "*denylist add p3 HOGE");
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 3);
chai_1.assert.include(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p1"));
chai_1.assert.include(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p2 piyo"));
chai_1.assert.include(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p3 HOGE"));
TestUtils_1.default.sendMessageAsOwner(lobby, "*denylist remove p1");
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 2);
chai_1.assert.notInclude(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p1"));
chai_1.assert.include(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p2 piyo"));
chai_1.assert.include(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p3 HOGE"));
TestUtils_1.default.sendMessageAsOwner(lobby, "*denylist remove p2 piyo");
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 1);
chai_1.assert.notInclude(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p1"));
chai_1.assert.notInclude(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p2 piyo"));
chai_1.assert.include(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p3 HOGE"));
TestUtils_1.default.sendMessageAsOwner(lobby, "*denylist remove p3 hoge");
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 0);
chai_1.assert.notInclude(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p1"));
chai_1.assert.notInclude(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p2 piyo"));
chai_1.assert.notInclude(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p3 HOGE"));
lobby.destroy();
});
it("remove twice test", async () => {
const { selector, lobby, ircClient } = await prepareSelector();
await ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1);
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 0);
TestUtils_1.default.sendMessageAsOwner(lobby, "*denylist add p1");
TestUtils_1.default.sendMessageAsOwner(lobby, "*denylist add p2");
TestUtils_1.default.sendMessageAsOwner(lobby, "*denylist add p3");
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 3);
chai_1.assert.include(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p1"));
chai_1.assert.include(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p2"));
chai_1.assert.include(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p3"));
TestUtils_1.default.sendMessageAsOwner(lobby, "*denylist remove p1");
TestUtils_1.default.sendMessageAsOwner(lobby, "*denylist remove p1");
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 2);
chai_1.assert.notInclude(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p1"));
chai_1.assert.include(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p2"));
chai_1.assert.include(plugins_1.DENY_LIST.players, (0, __1.escapeUserName)("p3"));
lobby.destroy();
});
});
it("multi lobby tests", async () => {
const a = await prepareSelector();
const b = await prepareSelector();
await a.ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_1); // p1 p2 p3 p4 p5
await b.ircClient.emulateMpSettings(MpSettingsCases_1.MpSettingsCases.case1_3); // p6 p2 p4 p5 p7
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 0);
chai_1.assert.equal(a.selector.hostQueue.length, 5);
chai_1.assert.equal(b.selector.hostQueue.length, 5);
plugins_1.DENY_LIST.addPlayer(a.lobby.GetOrMakePlayer("p1"));
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 1);
chai_1.assert.equal(a.selector.hostQueue.length, 4);
chai_1.assert.equal(b.selector.hostQueue.length, 5);
plugins_1.DENY_LIST.addPlayer(a.lobby.GetOrMakePlayer("p2"));
chai_1.assert.equal(plugins_1.DENY_LIST.players.size, 2);
chai_1.assert.equal(a.selector.hostQueue.length, 3);
chai_1.assert.equal(b.selector.hostQueue.length, 4);
chai_1.assert.equal(a.selector.hostQueue[0], a.lobby.GetOrMakePlayer("p3"));
chai_1.assert.equal(a.selector.hostQueue[1], a.lobby.GetOrMakePlayer("p4"));
chai_1.assert.equal(a.selector.hostQueue[2], a.lobby.GetOrMakePlayer("p5"));
chai_1.assert.equal(b.selector.hostQueue[0], b.lobby.GetOrMakePlayer("p4"));
chai_1.assert.equal(b.selector.hostQueue[1], b.lobby.GetOrMakePlayer("p5"));
chai_1.assert.equal(b.selector.hostQueue[2], b.lobby.GetOrMakePlayer("p7"));
chai_1.assert.equal(b.selector.hostQueue[3], b.lobby.GetOrMakePlayer("p6"));
a.lobby.destroy();
b.lobby.destroy();
});
});
describe("tests for issues", () => {
});
});
//# sourceMappingURL=AutoHostSelectorTest.js.map |
/** @flow */
import R from 'ramda';
import { inspect } from 'util';
import { HOOKS_NAMES } from '../constants';
import logger from '../logger/logger';
import * as errors from './exceptions';
export type HookAction = {
name: ?string,
run: Function[]
};
export type Hooks = {
[string]: HookAction[]
};
type HookFailures = {
[string]: Error
};
/*
* Setting up block level variable to store class state
* set's to null by default.
*/
let instance = null;
/**
* A class which manage all the hooks
* This is a singelton class which expose getInstance method
* This class used for register new hooks, actions for existing hooks and trigger hooks
*/
export default class HooksManager {
hooks = new Map();
constructor() {
if (!instance) {
instance = this;
}
return instance;
}
/**
* Initialize the default hooks
*/
static init() {
const self = new HooksManager();
HOOKS_NAMES.forEach(hookName => self.hooks.set(hookName, []));
}
/**
* Get the instance of the HooksManager
* @return {HooksManager} instance of the HooksManager
*
*/
static getInstance(): HooksManager {
return instance;
}
/**
* register new hook name
* @param {string} hookName
* @param {boolean} throwIfExist - whether to throw an error if the hook name already exists
* @return {boolean} whether the hook has been registerd
*/
registerNewHook(hookName: string, context: Object = {}, throwIfExist: boolean = false): boolean {
if (this.hooks.has(hookName)) {
const contextMsg = context.extension ? `from ${context.extension}` : '';
logger.warn(`trying to register an already existing hook ${hookName} ${contextMsg}`);
if (throwIfExist) {
throw new errors.HookAlreadyExists(hookName);
}
return false;
}
this.hooks.set(hookName, []);
return true;
}
/**
* Register action to an existing hook
* @param {string} hookName - hook to register action to
* @param {HookAction} hookAction - The action to register to the hook
* @param {boolean} throwIfNotExist - whether to throw an exception in case the hook doesn't exists
* @return {boolean} whether the action has been registerd successfully
*/
registerActionToHook(
hookName: string,
hookAction: HookAction,
context: Object = {},
throwIfNotExist: boolean = false
) {
if (!this.hooks.has(hookName)) {
const contextMsg = context.extension ? `from ${context.extension}` : '';
logger.warn(`trying to register to a non existing hook ${hookName} ${contextMsg}`);
if (throwIfNotExist) {
throw new errors.HookNotExists(hookName);
}
return false;
}
this.hooks.get(hookName).push(hookAction);
return true;
}
/**
* Trigger a hook - run all the actions registerd to this hook
* The actions will be run in parallel and the errors will be aggregated
* @param {string} hookName - The hook name to trigger
* @return {HookFailures} Aggregated errors of the actions failures
*/
async triggerHook(hookName: string, args: Object = {}, headers: Object = {}): ?(HookFailures[]) {
const resultErrors = [];
if (!this.hooks.has(hookName)) {
logger.warn(`trying to trigger a non existing hook ${hookName}`);
throw new errors.HookNotExists(hookName);
}
logger.info(
`triggering hook ${hookName} with args:\n ${_stringifyIfNeeded(
_stripArgs(args)
)} \n and headers \n ${_stringifyIfNeeded(_stripHeaders(headers))}`
);
const actions = this.hooks.get(hookName);
const actionsP = actions.map((action) => {
// Catch errors in order to aggregate them
// Wrap in a promise in case the action doesn't return a promise
return Promise.resolve()
.then(() => {
logger.info(`running action ${action.name} on hook ${hookName}`);
return action.run(args, headers);
})
.catch((e) => {
logger.error(`running action ${action.name} on hook ${hookName} failed, err:`);
logger.error(e);
resultErrors.push({ [action.name]: e });
});
});
await Promise.all(actionsP);
return resultErrors;
}
}
function _stringifyIfNeeded(val) {
return typeof val === 'string' ? val : inspect(val, { depth: null });
}
/**
* Remove some data from the logs (because it's too verbose or because it's sensitive)
* @param {Object} args
*/
function _stripArgs(args) {
// Create deep clone
const res = R.clone(args);
if (res.componentObjects) {
res.componentObjects = res.componentObjects.length;
}
return res;
}
/**
* Remove some data from the logs (because it's too verbose or because it's sensitive)
* @param {Object} headers
*/
function _stripHeaders(headers) {
// Create deep clone
const res = R.clone(headers);
if (res.context && res.context.pubSshKey) {
const key = res.context.pubSshKey;
res.context.pubSshKey = `last 70 characters: ${key.substr(key.length - 70)}`;
}
return res;
}
|
# encoding: utf-8
# Edition
from . import (
Base,
get_one,
get_one_or_create,
PresentationCalculationPolicy,
)
from .coverage import CoverageRecord
from .constants import (
DataSourceConstants,
EditionConstants,
LinkRelations,
MediaTypes,
)
from .contributor import (
Contributor,
Contribution,
)
from .datasource import DataSource
from .identifier import Identifier
from .licensing import (
DeliveryMechanism,
LicensePool,
)
from collections import defaultdict
import logging
from sqlalchemy import (
Column,
Date,
Enum,
ForeignKey,
Index,
Integer,
String,
Unicode,
)
from sqlalchemy.dialects.postgresql import JSON
from sqlalchemy.ext.mutable import MutableDict
from sqlalchemy.orm import relationship
from sqlalchemy.orm.session import Session
from ..util import (
LanguageCodes,
TitleProcessor
)
from ..util.permanent_work_id import WorkIDCalculator
class Edition(Base, EditionConstants):
"""A lightly schematized collection of metadata for a work, or an
edition of a work, or a book, or whatever. If someone thinks of it
as a "book" with a "title" it can go in here.
"""
__tablename__ = 'editions'
id = Column(Integer, primary_key=True)
data_source_id = Column(Integer, ForeignKey('datasources.id'), index=True)
MAX_THUMBNAIL_HEIGHT = 300
MAX_THUMBNAIL_WIDTH = 200
# A full-sized image no larger than this height can be used as a thumbnail
# in a pinch.
MAX_FALLBACK_THUMBNAIL_HEIGHT = 500
# This Edition is associated with one particular
# identifier--the one used by its data source to identify
# it. Through the Equivalency class, it is associated with a
# (probably huge) number of other identifiers.
primary_identifier_id = Column(
Integer, ForeignKey('identifiers.id'), index=True)
# An Edition may be the presentation edition for a single Work. If it's not
# a presentation edition for a work, work will be None.
work = relationship("Work", uselist=False, backref="presentation_edition")
# An Edition may show up in many CustomListEntries.
custom_list_entries = relationship("CustomListEntry", backref="edition")
# An Edition may be the presentation edition for many LicensePools.
is_presentation_for = relationship(
"LicensePool", backref="presentation_edition"
)
title = Column(Unicode, index=True)
sort_title = Column(Unicode, index=True)
subtitle = Column(Unicode, index=True)
series = Column(Unicode, index=True)
series_position = Column(Integer)
# This is not a foreign key per se; it's a calculated UUID-like
# identifier for this work based on its title and author, used to
# group together different editions of the same work.
permanent_work_id = Column(String(36), index=True)
# A string depiction of the authors' names.
author = Column(Unicode, index=True)
sort_author = Column(Unicode, index=True)
contributions = relationship("Contribution", backref="edition")
language = Column(Unicode, index=True)
publisher = Column(Unicode, index=True)
imprint = Column(Unicode, index=True)
# `issued` is the date the ebook edition was sent to the distributor by the publisher,
# i.e. the date it became available for librarians to buy for their libraries
issued = Column(Date)
# `published is the original publication date of the text.
# A Project Gutenberg text was likely `published` long before being `issued`.
published = Column(Date)
MEDIUM_ENUM = Enum(*EditionConstants.KNOWN_MEDIA, name="medium")
medium = Column(MEDIUM_ENUM, index=True)
cover_id = Column(
Integer, ForeignKey(
'resources.id', use_alter=True, name='fk_editions_summary_id'),
index=True)
# These two let us avoid actually loading up the cover Resource
# every time.
cover_full_url = Column(Unicode)
cover_thumbnail_url = Column(Unicode)
# An OPDS entry containing all metadata about this entry that
# would be relevant to display to a library patron.
simple_opds_entry = Column(Unicode, default=None)
# Information kept in here probably won't be used.
extra = Column(MutableDict.as_mutable(JSON), default={})
def __repr__(self):
id_repr = repr(self.primary_identifier)
return "Edition %s [%r] (%s/%s/%s)" % (
self.id, id_repr, self.title,
", ".join([x.sort_name for x in self.contributors]),
self.language
)
@property
def language_code(self):
return LanguageCodes.three_to_two.get(self.language, self.language)
@property
def contributors(self):
return set([x.contributor for x in self.contributions])
@property
def author_contributors(self):
"""All distinct 'author'-type contributors, with the primary author
first, other authors sorted by sort name.
Basically, we're trying to figure out what would go on the
book cover. The primary author should go first, and be
followed by non-primary authors in alphabetical order. People
whose role does not rise to the level of "authorship"
(e.g. author of afterword) do not show up.
The list as a whole should contain no duplicates. This might
happen because someone is erroneously listed twice in the same
role, someone is listed as both primary author and regular
author, someone is listed as both author and translator,
etc. However it happens, your name only shows up once on the
front of the book.
"""
seen_authors = set()
primary_author = None
other_authors = []
acceptable_substitutes = defaultdict(list)
if not self.contributions:
return []
# If there is one and only one contributor, return them, no
# matter what their role is.
if len(self.contributions) == 1:
return [self.contributions[0].contributor]
# There is more than one contributor. Try to pick out the ones
# that rise to the level of being 'authors'.
for x in self.contributions:
if not primary_author and x.role == Contributor.PRIMARY_AUTHOR_ROLE:
primary_author = x.contributor
elif x.role in Contributor.AUTHOR_ROLES:
other_authors.append(x.contributor)
elif x.role.lower().startswith('author and'):
other_authors.append(x.contributor)
elif (x.role in Contributor.AUTHOR_SUBSTITUTE_ROLES
or x.role in Contributor.PERFORMER_ROLES):
l = acceptable_substitutes[x.role]
if x.contributor not in l:
l.append(x.contributor)
def dedupe(l):
"""If an item shows up multiple times in a list,
keep only the first occurence.
"""
seen = set()
deduped = []
for i in l:
if i in seen:
continue
deduped.append(i)
seen.add(i)
return deduped
if primary_author:
return dedupe([primary_author] + sorted(other_authors, key=lambda x: x.sort_name))
if other_authors:
return dedupe(other_authors)
for role in (
Contributor.AUTHOR_SUBSTITUTE_ROLES
+ Contributor.PERFORMER_ROLES
):
if role in acceptable_substitutes:
contributors = acceptable_substitutes[role]
return dedupe(sorted(contributors, key=lambda x: x.sort_name))
else:
# There are roles, but they're so random that we can't be
# sure who's the 'author' or so low on the creativity
# scale (like 'Executive producer') that we just don't
# want to put them down as 'author'.
return []
@classmethod
def medium_from_media_type(cls, media_type):
"""Derive a value for Edition.medium from a media type.
TODO: It's not necessary right now, but we could theoretically
derive this information from some other types such as
our internal types for Overdrive manifests.
:param media_type: A media type with optional parameters
:return: A value for Edition.medium.
"""
if not media_type:
return None
for types, conclusion in (
(MediaTypes.AUDIOBOOK_MEDIA_TYPES, Edition.AUDIO_MEDIUM),
(MediaTypes.BOOK_MEDIA_TYPES, Edition.BOOK_MEDIUM),
):
if any(media_type.startswith(x) for x in types):
return conclusion
if media_type.startswith(DeliveryMechanism.ADOBE_DRM):
# Adobe DRM is only applied to ebooks.
return Edition.BOOK_MEDIUM
return None
@classmethod
def for_foreign_id(cls, _db, data_source,
foreign_id_type, foreign_id,
create_if_not_exists=True):
"""Find the Edition representing the given data source's view of
the work that it primarily identifies by foreign ID.
e.g. for_foreign_id(_db, DataSource.OVERDRIVE, Identifier.OVERDRIVE_ID, uuid)
finds the Edition for Overdrive's view of a book identified
by Overdrive UUID.
This:
for_foreign_id(_db, DataSource.OVERDRIVE, Identifier.ISBN, isbn)
will probably return nothing, because although Overdrive knows
that books have ISBNs, it doesn't use ISBN as a primary
identifier.
"""
# Look up the data source if necessary.
if isinstance(data_source, (bytes, str)):
data_source = DataSource.lookup(_db, data_source)
identifier, ignore = Identifier.for_foreign_id(
_db, foreign_id_type, foreign_id)
# Combine the two to get/create a Edition.
if create_if_not_exists:
f = get_one_or_create
kwargs = dict()
else:
f = get_one
kwargs = dict()
r = f(_db, Edition, data_source=data_source,
primary_identifier=identifier,
**kwargs)
return r
@property
def license_pools(self):
"""The LicensePools that provide access to the book described
by this Edition.
"""
_db = Session.object_session(self)
return _db.query(LicensePool).filter(
LicensePool.data_source==self.data_source,
LicensePool.identifier==self.primary_identifier).all()
def equivalent_identifiers(self, type=None, policy=None):
"""All Identifiers equivalent to this
Edition's primary identifier, according to the given
PresentationCalculationPolicy
"""
_db = Session.object_session(self)
identifier_id_subquery = Identifier.recursively_equivalent_identifier_ids_query(
self.primary_identifier.id, policy=policy
)
q = _db.query(Identifier).filter(
Identifier.id.in_(identifier_id_subquery))
if type:
if isinstance(type, list):
q = q.filter(Identifier.type.in_(type))
else:
q = q.filter(Identifier.type==type)
return q.all()
def equivalent_editions(self, policy=None):
"""All Editions whose primary ID is equivalent to this Edition's
primary ID, according to the given PresentationCalculationPolicy.
"""
_db = Session.object_session(self)
identifier_id_subquery = Identifier.recursively_equivalent_identifier_ids_query(
self.primary_identifier.id, policy=policy
)
return _db.query(Edition).filter(
Edition.primary_identifier_id.in_(identifier_id_subquery))
@classmethod
def missing_coverage_from(
cls, _db, edition_data_sources, coverage_data_source,
operation=None
):
"""Find Editions from `edition_data_source` whose primary
identifiers have no CoverageRecord from
`coverage_data_source`.
e.g.::
gutenberg = DataSource.lookup(_db, DataSource.GUTENBERG)
oclc_classify = DataSource.lookup(_db, DataSource.OCLC)
missing_coverage_from(_db, gutenberg, oclc_classify)
will find Editions that came from Project Gutenberg and
have never been used as input to the OCLC Classify web
service.
"""
if isinstance(edition_data_sources, DataSource):
edition_data_sources = [edition_data_sources]
edition_data_source_ids = [x.id for x in edition_data_sources]
join_clause = (
(Edition.primary_identifier_id==CoverageRecord.identifier_id) &
(CoverageRecord.data_source_id==coverage_data_source.id) &
(CoverageRecord.operation==operation)
)
q = _db.query(Edition).outerjoin(
CoverageRecord, join_clause)
if edition_data_source_ids:
q = q.filter(Edition.data_source_id.in_(edition_data_source_ids))
q2 = q.filter(CoverageRecord.id==None)
return q2
@classmethod
def sort_by_priority(cls, editions, license_source=None):
"""Return all Editions that describe the Identifier associated with
this LicensePool, in the order they should be used to create a
presentation Edition for the LicensePool.
"""
def sort_key(edition):
"""Return a numeric ordering of this edition."""
source = edition.data_source
if not source:
# This shouldn't happen. Give this edition the
# lowest priority.
return -100
if source == license_source:
# This Edition contains information from the same data
# source as the LicensePool itself. Put it below any
# Edition from one of the data sources in
# PRESENTATION_EDITION_PRIORITY, but above all other
# Editions.
return -1
elif source.name == DataSourceConstants.METADATA_WRANGLER:
# The metadata wrangler is slightly less trustworthy
# than the license source, for everything except cover
# image (which is handled by
# Representation.quality_as_thumbnail_image)
return -1.5
if source.name in DataSourceConstants.PRESENTATION_EDITION_PRIORITY:
return DataSourceConstants.PRESENTATION_EDITION_PRIORITY.index(source.name)
else:
return -2
return sorted(editions, key=sort_key)
@classmethod
def _content(cls, content, is_html=False):
"""Represent content that might be plain-text or HTML.
e.g. a book's summary.
"""
if not content:
return None
if is_html:
type = "html"
else:
type = "text"
return dict(type=type, value=content)
def set_cover(self, resource):
old_cover = self.cover
old_cover_full_url = self.cover_full_url
self.cover = resource
self.cover_full_url = resource.representation.public_url
# TODO: In theory there could be multiple scaled-down
# versions of this representation and we need some way of
# choosing between them. Right now we just pick the first one
# that works.
if (resource.representation.image_height
and resource.representation.image_height <= self.MAX_THUMBNAIL_HEIGHT):
# This image doesn't need a thumbnail.
self.cover_thumbnail_url = resource.representation.public_url
else:
# Use the best available thumbnail for this image.
best_thumbnail = resource.representation.best_thumbnail
if best_thumbnail:
self.cover_thumbnail_url = best_thumbnail.public_url
if (not self.cover_thumbnail_url and
resource.representation.image_height
and resource.representation.image_height <= self.MAX_FALLBACK_THUMBNAIL_HEIGHT):
# The full-sized image is too large to be a thumbnail, but it's
# not huge, and there is no other thumbnail, so use it.
self.cover_thumbnail_url = resource.representation.public_url
if old_cover != self.cover or old_cover_full_url != self.cover_full_url:
logging.debug(
"Setting cover for %s/%s: full=%s thumb=%s",
self.primary_identifier.type, self.primary_identifier.identifier,
self.cover_full_url, self.cover_thumbnail_url
)
def add_contributor(self, name, roles, aliases=None, lc=None, viaf=None,
**kwargs):
"""Assign a contributor to this Edition."""
_db = Session.object_session(self)
if isinstance(roles, (bytes, str)):
roles = [roles]
# First find or create the Contributor.
if isinstance(name, Contributor):
contributor = name
else:
contributor, was_new = Contributor.lookup(
_db, name, lc, viaf, aliases)
if isinstance(contributor, list):
# Contributor was looked up/created by name,
# which returns a list.
contributor = contributor[0]
# Then add their Contributions.
for role in roles:
contribution, was_new = get_one_or_create(
_db, Contribution, edition=self, contributor=contributor,
role=role)
return contributor
def similarity_to(self, other_record):
"""How likely is it that this record describes the same book as the
given record?
1 indicates very strong similarity, 0 indicates no similarity
at all.
For now we just compare the sets of words used in the titles
and the authors' names. This should be good enough for most
cases given that there is usually some preexisting reason to
suppose that the two records are related (e.g. OCLC said
they were).
Most of the Editions are from OCLC Classify, and we expect
to get some of them wrong (e.g. when a single OCLC work is a
compilation of several novels by the same author). That's okay
because those Editions aren't backed by
LicensePools. They're purely informative. We will have some
bad information in our database, but the clear-cut cases
should outnumber the fuzzy cases, so we we should still group
the Editions that really matter--the ones backed by
LicensePools--together correctly.
TODO: apply much more lenient terms if the two Editions are
identified by the same ISBN or other unique identifier.
"""
if other_record == self:
# A record is always identical to itself.
return 1
if other_record.language == self.language:
# The books are in the same language. Hooray!
language_factor = 1
else:
if other_record.language and self.language:
# Each record specifies a different set of languages. This
# is an immediate disqualification.
return 0
else:
# One record specifies a language and one does not. This
# is a little tricky. We're going to apply a penalty, but
# since the majority of records we're getting from OCLC are in
# English, the penalty will be less if one of the
# languages is English. It's more likely that an unlabeled
# record is in English than that it's in some other language.
if self.language == 'eng' or other_record.language == 'eng':
language_factor = 0.80
else:
language_factor = 0.50
title_quotient = MetadataSimilarity.title_similarity(
self.title, other_record.title)
author_quotient = MetadataSimilarity.author_similarity(
self.author_contributors, other_record.author_contributors)
if author_quotient == 0:
# The two works have no authors in common. Immediate
# disqualification.
return 0
# We weight title more heavily because it's much more likely
# that one author wrote two different books than that two
# books with the same title have different authors.
return language_factor * (
(title_quotient * 0.80) + (author_quotient * 0.20))
def apply_similarity_threshold(self, candidates, threshold=0.5):
"""Yield the Editions from the given list that are similar
enough to this one.
"""
for candidate in candidates:
if self == candidate:
yield candidate
else:
similarity = self.similarity_to(candidate)
if similarity >= threshold:
yield candidate
def best_cover_within_distance(self, distance, rel=None, policy=None):
_db = Session.object_session(self)
identifier_ids = [self.primary_identifier.id]
if distance > 0:
if policy is None:
new_policy = PresentationCalculationPolicy()
else:
new_policy = PresentationCalculationPolicy(
equivalent_identifier_levels=distance,
equivalent_identifier_cutoff=policy.equivalent_identifier_cutoff,
equivalent_identifier_threshold=policy.equivalent_identifier_threshold,
)
identifier_ids_dict = Identifier.recursively_equivalent_identifier_ids(
_db, identifier_ids, policy=new_policy
)
identifier_ids += identifier_ids_dict[self.primary_identifier.id]
return Identifier.best_cover_for(_db, identifier_ids, rel=rel)
@property
def title_for_permanent_work_id(self):
title = self.title
if self.subtitle:
title += (": " + self.subtitle)
return title
@property
def author_for_permanent_work_id(self):
authors = self.author_contributors
if authors:
# Use the sort name of the primary author.
author = authors[0].sort_name
else:
# This may be an Edition that represents an item on a best-seller list
# or something like that. In this case it wouldn't have any Contributor
# objects, just an author string. Use that.
author = self.sort_author or self.author
return author
def calculate_permanent_work_id(self, debug=False):
title = self.title_for_permanent_work_id
medium = self.medium_for_permanent_work_id.get(self.medium, None)
if not title or not medium:
# If a book has no title or medium, it has no permanent work ID.
self.permanent_work_id = None
return
author = self.author_for_permanent_work_id
w = WorkIDCalculator
norm_title = w.normalize_title(title)
norm_author = w.normalize_author(author)
old_id = self.permanent_work_id
self.permanent_work_id = self.calculate_permanent_work_id_for_title_and_author(
title, author, medium)
args = (
"Permanent work ID for %d: %s/%s -> %s/%s/%s -> %s (was %s)",
self.id, title, author, norm_title, norm_author, medium,
self.permanent_work_id, old_id
)
if debug:
logging.debug(*args)
elif old_id != self.permanent_work_id:
logging.info(*args)
@classmethod
def calculate_permanent_work_id_for_title_and_author(
cls, title, author, medium):
w = WorkIDCalculator
norm_title = w.normalize_title(title)
norm_author = w.normalize_author(author)
return WorkIDCalculator.permanent_id(
norm_title, norm_author, medium)
UNKNOWN_AUTHOR = "[Unknown]"
def calculate_presentation(self, policy=None):
"""Make sure the presentation of this Edition is up-to-date."""
_db = Session.object_session(self)
changed = False
if policy is None:
policy = PresentationCalculationPolicy()
# Gather information up front that will be used to determine
# whether this method actually did anything.
old_author = self.author
old_sort_author = self.sort_author
old_sort_title = self.sort_title
old_work_id = self.permanent_work_id
old_cover = self.cover
old_cover_full_url = self.cover_full_url
old_cover_thumbnail_url = self.cover_thumbnail_url
if policy.set_edition_metadata:
self.author, self.sort_author = self.calculate_author()
self.sort_title = TitleProcessor.sort_title_for(self.title)
self.calculate_permanent_work_id()
CoverageRecord.add_for(
self, data_source=self.data_source,
operation=CoverageRecord.SET_EDITION_METADATA_OPERATION
)
if policy.choose_cover:
self.choose_cover(policy=policy)
if (self.author != old_author
or self.sort_author != old_sort_author
or self.sort_title != old_sort_title
or self.permanent_work_id != old_work_id
or self.cover != old_cover
or self.cover_full_url != old_cover_full_url
or self.cover_thumbnail_url != old_cover_thumbnail_url
):
changed = True
# Now that everything's calculated, log it.
if policy.verbose:
if changed:
changed_status = "changed"
level = logging.info
else:
changed_status = "unchanged"
level = logging.debug
msg = "Presentation %s for Edition %s (by %s, pub=%s, ident=%s/%s, pwid=%s, language=%s, cover=%r)"
args = [changed_status, self.title, self.author, self.publisher,
self.primary_identifier.type, self.primary_identifier.identifier,
self.permanent_work_id, self.language
]
if self.cover and self.cover.representation:
args.append(self.cover.representation.public_url)
else:
args.append(None)
level(msg, *args)
return changed
def calculate_author(self):
"""Turn the list of Contributors into string values for .author
and .sort_author.
"""
sort_names = []
display_names = []
for author in self.author_contributors:
if author.sort_name and not author.display_name or not author.family_name:
default_family, default_display = author.default_names()
display_name = author.display_name or default_display or author.sort_name
family_name = author.family_name or default_family or author.sort_name
display_names.append([family_name, display_name])
sort_names.append(author.sort_name)
if display_names:
author = ", ".join([x[1] for x in sorted(display_names)])
else:
author = self.UNKNOWN_AUTHOR
if sort_names:
sort_author = " ; ".join(sorted(sort_names))
else:
sort_author = self.UNKNOWN_AUTHOR
return author, sort_author
def choose_cover(self, policy=None):
"""Try to find a cover that can be used for this Edition."""
self.cover_full_url = None
self.cover_thumbnail_url = None
for distance in (0, 5):
# If there's a cover directly associated with the
# Edition's primary ID, use it. Otherwise, find the
# best cover associated with any related identifier.
best_cover, covers = self.best_cover_within_distance(
distance=distance, policy=policy
)
if best_cover:
if not best_cover.representation:
logging.warn(
"Best cover for %r has no representation!",
self.primary_identifier,
)
else:
rep = best_cover.representation
if not rep.thumbnails:
logging.warn(
"Best cover for %r (%s) was never thumbnailed!",
self.primary_identifier,
rep.public_url
)
self.set_cover(best_cover)
break
else:
# No cover has been found. If the Edition currently references
# a cover, it has since been rejected or otherwise removed.
# Cover details need to be removed.
cover_info = [self.cover, self.cover_full_url]
if any(cover_info):
self.cover = None
self.cover_full_url = None
if not self.cover_thumbnail_url:
# The process we went through above did not result in the
# setting of a thumbnail cover.
#
# It's possible there's a thumbnail even when there's no
# full-sized cover, or when the full-sized cover and
# thumbnail are different Resources on the same
# Identifier. Try to find a thumbnail the same way we'd
# look for a cover.
for distance in (0, 5):
best_thumbnail, thumbnails = self.best_cover_within_distance(
distance=distance, policy=policy,
rel=LinkRelations.THUMBNAIL_IMAGE,
)
if best_thumbnail:
if not best_thumbnail.representation:
logging.warn(
"Best thumbnail for %r has no representation!",
self.primary_identifier,
)
else:
rep = best_thumbnail.representation
if rep:
self.cover_thumbnail_url = rep.public_url
break
else:
# No thumbnail was found. If the Edition references a thumbnail,
# it needs to be removed.
if self.cover_thumbnail_url:
self.cover_thumbnail_url = None
# Whether or not we succeeded in setting the cover,
# record the fact that we tried.
CoverageRecord.add_for(
self, data_source=self.data_source,
operation=CoverageRecord.CHOOSE_COVER_OPERATION
)
Index("ix_editions_data_source_id_identifier_id", Edition.data_source_id, Edition.primary_identifier_id, unique=True)
|
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import TimeAgo from 'react-timeago';
import { handleSaveQuestionAnswer } from '../actions/questions.js';
import { handleSaveUserAnswer } from '../actions/users.js';
const VoteQuestion = ({ creator, question, authedUser, dispatch }) => {
const creatorId = creator.map(user => user.id)[0];
const creatorName = creator.map(user => user.name)[0];
const handleVote = (event, answer) => {
dispatch(handleSaveQuestionAnswer(authedUser, question.id, answer));
dispatch(handleSaveUserAnswer(authedUser, question.id, answer));
}
return (
<div className='home-list'>
<h1 className='page-title'>VOTE</h1>
<div className='question vote'>
<div className='question-inner'>
<div className='question-header'>
<div className='avatar'>
<img src={`${window.location.origin}/images/${creatorId}.jpg`} alt={creatorName} />
</div>
<span>{creatorName} asks</span>
<span className='flex-right'><TimeAgo date={question.timestamp} /></span>
</div>
<div className='question-title'>
Would you rather:
</div>
<div
className='option-one'
onClick={(event) => handleVote(event, 'optionOne')}
>
<span className='chosen'><p></p></span>
{question.optionOne.text}?
</div>
<div
className='option-two'
onClick={(event) => handleVote(event, 'optionTwo')}>
<span className='chosen'><p></p></span>
{question.optionTwo.text}?
</div>
</div>
<div className='see-details vote'>
<p>Select One</p>
</div>
</div>
</div>
);
}
VoteQuestion.propTypes = {
creator: PropTypes.array.isRequired,
question: PropTypes.object.isRequired,
authedUser: PropTypes.string.isRequired,
dispatch: PropTypes.func.isRequired
};
export default connect()(VoteQuestion); |
// THIS FILE IS AUTO GENERATED
import { GenIcon } from '../lib';
export function IoDiceSharp (props) {
return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 512 512"},"child":[{"tag":"path","attr":{"d":"M48 366.92L240 480V284L48 170zM192 288c8.84 0 16 10.75 16 24s-7.16 24-16 24-16-10.75-16-24 7.16-24 16-24zm-96 32c8.84 0 16 10.75 16 24s-7.16 24-16 24-16-10.75-16-24 7.16-24 16-24zm176-36v196l192-113.08V170zm48 140c-8.84 0-16-10.75-16-24s7.16-24 16-24 16 10.75 16 24-7.16 24-16 24zm0-88c-8.84 0-16-10.75-16-24s7.16-24 16-24 16 10.75 16 24-7.16 24-16 24zm96 32c-8.84 0-16-10.75-16-24s7.16-24 16-24 16 10.75 16 24-7.16 24-16 24zm0-88c-8.84 0-16-10.75-16-24s7.16-24 16-24 16 10.75 16 24-7.16 24-16 24zm32 77.64zM256 32L64 144l192 112 192-112zm0 120c-13.25 0-24-7.16-24-16s10.75-16 24-16 24 7.16 24 16-10.75 16-24 16z"}}]})(props);
};
|
import React from 'react';
import PropTypes from 'prop-types';
import Label from '../Label';
/** Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker. */
function TextInput({htmlId, name, label, type = "text", required = false, onChange, placeholder, value, error, children, ...props}) {
return (
<div className="textinput">
<Label htmlFor={htmlId} label={label} required={required}/>
<input
id={htmlId}
type={type}
name={name}
placeholder={placeholder}
value={value}
onChange={onChange}
className={error && 'textinput__input--state-error'}
{...props}
/>
{children}
{error && <div className="textinput__error">{error}</div>}
</div>
);
}
TextInput.propTypes = {
/** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing */
htmlId: PropTypes.string.isRequired,
/** Input name. Recommend setting this to match object's property so a single change handler can be used */
name: PropTypes.string.isRequired,
/** Input label */
label: PropTypes.string.isRequired,
/** Input type */
type: PropTypes.oneOf(['text', 'number', 'password']),
/** Mark label with asterisk if set to true */
required: PropTypes.bool,
/** Function to call onChange */
onChange: PropTypes.func,
/** Placeholder to display when empty */
placeholder: PropTypes.string,
/** Value */
value: PropTypes.any,
/** String to display when error occurs */
error: PropTypes.string,
/** Child component to display next to the input */
children: PropTypes.node
};
export default TextInput;
|
return {
loud: function (aString) { return aString.toString().toUpperCase() },
small: function (aString) { return aString.toString().toLowerCase() }
};
|
import React, { PureComponent, Fragment } from 'react';
import { Route, Redirect, Switch } from 'dva/router';
import { Card, Steps } from 'antd';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout';
import NotFound from '../../Exception/404';
import { getRoutes } from '../../../utils/utils';
import styles from '../style.less';
const { Step } = Steps;
export default class StepForm extends PureComponent {
getCurrentStep() {
const { location } = this.props;
const { pathname } = location;
const pathList = pathname.split('/');
switch (pathList[pathList.length - 1]) {
case 'info':
return 0;
case 'confirm':
return 1;
case 'result':
return 2;
default:
return 0;
}
}
render() {
const { match, routerData, location } = this.props;
return (
<PageHeaderLayout
title="Step-by-step form"
tabActiveKey={location.pathname}
content="Divide a lengthy or unfamiliar form task into multiple steps to guide the user through it."
>
<Card bordered={false}>
<Fragment>
<Steps current={this.getCurrentStep()} className={styles.steps}>
<Step title="Fill in transfer information" />
<Step title="Confirm transfer information" />
<Step title="Carry out" />
</Steps>
<Switch>
{getRoutes(match.path, routerData).map(item => (
<Route
key={item.key}
path={item.path}
component={item.component}
exact={item.exact}
/>
))}
<Redirect exact from="/form/step-form" to="/form/step-form/info" />
<Route render={NotFound} />
</Switch>
</Fragment>
</Card>
</PageHeaderLayout>
);
}
}
|
import React from 'react';
import './SearchPage.css';
import ChannelRow from './ChannelRow';
import TuneIcon from '@material-ui/icons/Tune';
import channelimg from './Devtubes.png';
import VideoRow from './VideoRow.js';
import VideoCard from './VideoCard';
import dev from './Tanay tube.jpg'
import dsc from './DSC.png'
import devs from './Devtubes.png';
import tanay from './TanayTapanshu.jpg';
import spells from './spells.png';
import MLSA from './MLSA.png';
import SDE from './SDE.png';
import Reactor from './reactor.png';
import AI from './Aigame.png';
import community from './community.jpg';
import Problem from './problem.png';
function SearchPage() {
return (
<div className="SearchPage">
<div className = "SearchPage__filter">
<TuneIcon></TuneIcon>
<h3>FILTER</h3>
</div>
<hr />
<ChannelRow
image={channelimg}
channel=" Warrior Programmer"
verified
subs="100k"
noOfVideos={5}
description="You can find awesome coding videos and projects."
/>
<hr />
<VideoRow title="Productivity Spells"
channel="Warrior Programmer"
views="12k"
subs='100k'
description="Know the secret spells to maintain your productivity."
timestamp="2hr ago"
image={spells}
/>
<hr />
<VideoRow title="SDE Road Map"
channel="Warrior Programmer"
views="22k"
subs='100k'
description="Roadmap you need to become a succesful Software engineer."
timestamp="8hr ago"
image={SDE}
/>
<hr />
<VideoRow title="Starting Up with AI gaming"
channel="Warrior Programmer"
views="2k"
subs='100k'
description="AI gaming is currently the most trending topic among coders. Watch to know about it"
timestamp="18hr ago"
image={AI}
/>
<hr />
<VideoRow title="How to develop problem solving skills?"
channel="Warrior Programmer"
views="209k"
subs='100k'
description="A lot of people ask this question to me. Hope this video clear"
timestamp="21hr ago"
image={Problem}
/>
</div>
)
}
export default SearchPage;
|
const CustomError = require("../extensions/custom-error");
module.exports = function createDreamTeam(members) {
let names= [];
if(Array.isArray(members)){
for(let i = 0; i < members.length; i++){
if(typeof members[i] == 'string'){
members[i] = members[i].trim();
names.push(members[i][0].toUpperCase());
}
}
}
return names.sort().join('')
};
|
import { Redirect } from 'react-router-dom'
var deleteIcon = function(value, data, cell, row, options){ //plain text value
return "<i class='fa fa-trash'></i>"
};
var editIcon = function(value, data, cell, row, options){ //plain text value
return "<a href='/#/branddetails'><i class='fa fa-edit'></i></a>"
};
function customFilter(data, filterParams){
return data.id !== filterParams.id; //must return a boolean, true if it passes the filter.
}
const columns = [
{
title:"" ,
field: "id",
sortable:false,
align: 'center',
formatter:editIcon,
cellClick: function (e, cell) {
let table = cell.getTable();
console.log(table);
console.log(table.options);
let rowId = cell.getRow().getData().id;
// return (<Redirect to='/branddetails' />);
}
},
{
title:"" ,
field: "id",
sortable:false,
align: 'center',
formatter: deleteIcon,
cellClick: function (e, cell) {
let table = cell.getTable();
let rowId = cell.getRow().getData().id;
table.addFilter(customFilter, {id: rowId})
}
},
{title:"Name", headerFilter:true, field:"name", editor: true},
{title:"Status", headerFilter:true, field:"status", editor:true},
{title:"Active", headerFilter:true, field:"is_active", sorter: "boolean", align:"center", formatter:"tickCross", editor: "tick", width: "input"},
{title:"Primary Source", headerFilter:true, field:"primary_source", editor:true},
{title:"Sold on Amazon", headerFilter:true, field:"is_sold_on_amazon", sorter:"boolean", align:"center", formatter:"tickCross", editor: "tick", width: 'input', widthShrink: 2},
{title:"Amazon Listing", headerFilter:true, field:"amazon_listing", align:"right", editor:true, widthShrink: 2},
{title:"Scan Amazon", headerFilter:true, field:"is_scan_amazon", sorter:"boolean", align:"center", formatter:"tickCross", editor: "tick", width: "input", widthShrink: 2},
{title:"Restricted", headerFilter:true, field:"restricted", align:"center", editor:"select", editorParams:{"Y":"Yes", "N":"No"}},
{title:"Good buys", headerFilter:true, field:"is_good_buys", sorter:"boolean", align:"center", formatter:"tickCross", editor: "tick", width: "input", widthShrink: 2},
{title:"Scraping", headerFilter:true, field:"is_scraping", sorter:"boolean", align:"center", formatter:"tickCross", editor: "tick", width: "input", widthShrink: 2, variableHeight: true},
];
export default columns;
|
#32 Faça um programa que leia um ano qualquer e mostre se ele é bissexto.
import datetime
print("Digite 0 para analisar o ano atual")
ano = int(input("Que ano quer analisar? "))
if ano == 0:
ano = datetime.date.today().year
if ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0:
print(f"O ano {ano} é bissexto")
else:
ano = 2021
print(f"O ano {ano} não é bissexto") |
#!/usr/bin/env python
# Copyright 2014, Rackspace US, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
import argparse
import memcache
from ipaddr import IPv4Address
from maas_common import (status_ok, status_err, metric, metric_bool,
print_output)
VERSION_RE = re.compile('STAT version (\d+\.\d+\.\d+)(?![-+0-9\\.])')
VERSION = '1.4.14 (Ubuntu)'
MEMCACHE_METRICS = {'total_items': 'items',
'get_hits': 'cache_hits',
'get_misses': 'cache_misses',
'total_connections': 'connections'}
def item_stats(host, port):
"""Check the stats for items and connection status."""
stats = None
try:
mc = memcache.Client(['%s:%s' % (host, port)])
stats = mc.get_stats()[0][1]
except IndexError:
raise
finally:
return stats
def main(args):
bind_ip = str(args.ip)
port = args.port
is_up = True
try:
stats = item_stats(bind_ip, port)
current_version = stats['version']
except TypeError, IndexError:
is_up = False
else:
is_up = True
#if current_version != VERSION:
# status_err('This plugin has only been tested with version %s '
# 'of memcached, and you are using version %s'
# % (VERSION, current_version))
status_ok()
metric_bool('memcache_api_local_status', is_up)
if is_up:
for m, u in MEMCACHE_METRICS.iteritems():
metric('memcache_%s' % m, 'uint64', stats[m], u)
if __name__ == '__main__':
with print_output():
parser = argparse.ArgumentParser(description='Check memcached status')
parser.add_argument('ip', type=IPv4Address, help='memcached IP address.')
parser.add_argument('--port', type=int,
default=11211, help='memcached port.')
args = parser.parse_args()
main(args)
|
!function(e){e.fn.datepicker.dates.de={days:["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag","Sonntag"],daysShort:["Son","Mon","Die","Mit","Don","Fre","Sam","Son"],daysMin:["So","Mo","Di","Mi","Do","Fr","Sa","So"],months:["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],monthsShort:["Jan","Feb","Mär","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez"],today:"Heute"}}(jQuery); |
import React from 'react';
import {Container, Row, Col} from "react-bootstrap";
import AboutThumbOne from "../../components/about-us/thumbnail/AboutThumbOne";
import aboutThumb from "../../assets/img/about/home-creative-agency-image-01.png"
import AboutContentOne from "../../components/about-us/content/AboutContentOne";
const AboutCreativeAgency = () => {
return (
<div className="bk-about-area section-ptb-100">
<Container>
<Row className="about--creative align-items-center">
<Col xs={12} lg={6}>
<AboutThumbOne thumb={aboutThumb}/>
</Col>
<Col xs={12} lg={6} className="mt_md--40 mt_sm--40">
<AboutContentOne
title={'About Us'}
heading={"We're motivated by the <span class='theme-creative'>desire to achieve.</span>"}
content={"In order for you to achieve the things you are capable of, you need to constantly be creating goals for yourself."}
btnText={"More Details"}
btnLink={'/'}
/>
</Col>
</Row>
</Container>
</div>
);
};
export default AboutCreativeAgency;
|
/**
* @license
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('shaka.offline.OfflineScheme');
goog.require('goog.asserts');
goog.require('shaka.net.NetworkingEngine');
goog.require('shaka.offline.OfflineUri');
goog.require('shaka.offline.StorageMuxer');
goog.require('shaka.util.AbortableOperation');
goog.require('shaka.util.Error');
goog.require('shaka.util.IDestroyable');
/**
* @namespace
* @summary A plugin that handles requests for offline content.
* @param {string} uri
* @param {shaka.extern.Request} request
* @param {shaka.net.NetworkingEngine.RequestType=} requestType
* @return {!shaka.extern.IAbortableOperation.<shaka.extern.Response>}
* @export
*/
shaka.offline.OfflineScheme = function(uri, request, requestType) {
let offlineUri = shaka.offline.OfflineUri.parse(uri);
if (offlineUri && offlineUri.isManifest()) {
return shaka.offline.OfflineScheme.getManifest_(uri);
}
if (offlineUri && offlineUri.isSegment()) {
return shaka.offline.OfflineScheme.getSegment_(
offlineUri.key(), offlineUri);
}
return shaka.util.AbortableOperation.failed(
new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.NETWORK,
shaka.util.Error.Code.MALFORMED_OFFLINE_URI,
uri));
};
/**
* @param {string} uri
* @return {!shaka.extern.IAbortableOperation.<shaka.extern.Response>}
* @private
*/
shaka.offline.OfflineScheme.getManifest_ = function(uri) {
/** @type {shaka.extern.Response} */
let response = {
uri: uri,
data: new ArrayBuffer(0),
headers: {'content-type': 'application/x-offline-manifest'}
};
return shaka.util.AbortableOperation.completed(response);
};
/**
* @param {number} id
* @param {!shaka.offline.OfflineUri} uri
* @return {!shaka.extern.IAbortableOperation.<shaka.extern.Response>}
* @private
*/
shaka.offline.OfflineScheme.getSegment_ = function(id, uri) {
goog.asserts.assert(
uri.isSegment(),
'Only segment uri\'s should be given to getSegment');
let muxer = new shaka.offline.StorageMuxer();
let promise = shaka.util.IDestroyable.with([muxer], async () => {
await muxer.init();
let cell = await muxer.getCell(uri.mechanism(), uri.cell());
let segments = await cell.getSegments([uri.key()]);
let segment = segments[0];
return {
uri: uri,
data: segment.data,
headers: {}
};
});
// TODO: Support abort() in OfflineScheme.
return shaka.util.AbortableOperation.notAbortable(promise);
};
shaka.net.NetworkingEngine.registerScheme(
'offline', shaka.offline.OfflineScheme);
|
deepmacDetailCallback("e02a82000000/24",[{"d":"2010-08-28","t":"add","a":"135, LANE 351, TAIPING RD.\nSEC.1, TSAO TUEN\nNAN-TOU 542\n","c":"TAIWAN, REPUBLIC OF CHINA","o":"USI"},{"d":"2011-02-12","t":"change","a":"141, LANE 351, SEC.1, TAIPING RD.\nTSAOTUEN\nNANTOU 54261\n","c":"TAIWAN, REPUBLIC OF CHINA","o":"Universal Global Scientific Industrial Co., Ltd."},{"d":"2012-11-29","t":"change","a":"141, LANE 351, SEC.1, TAIPING RD.\nTSAOTUEN\nNANTOU 54261\n","c":"TAIWAN, PROVINCE OF CHINA","o":"Universal Global Scientific Industrial Co., Ltd."},{"d":"2015-08-27","t":"change","a":"141, LANE 351,SEC.1, TAIPING RD. TSAOTUEN, NANTOU TW 54261","c":"TW","o":"Universal Global Scientific Industrial Co., Ltd."}]);
|
import * as THREE from 'three';
import MaterialDescriptorBase from './MaterialDescriptorBase';
class MeshLambertMaterialDescriptor extends MaterialDescriptorBase {
constructor(react3RendererInstance) {
super(react3RendererInstance);
this.hasColor();
this.hasColor('emissive', 0);
this.hasWireframe();
this.hasMap();
this.hasMap('lightMap');
this.hasMap('aoMap');
this.hasMap('emissiveMap');
this.hasMap('specularMap');
this.hasMap('alphaMap');
this.hasMap('envMap');
}
construct(props) {
const materialDescription = this.getMaterialDescription(props);
return new THREE.MeshLambertMaterial(materialDescription);
}
getMaterialDescription(props) {
const materialDescription = super.getMaterialDescription(props);
if (props.hasOwnProperty('shininess')) {
materialDescription.shininess = props.shininess;
}
if (props.hasOwnProperty('map')) {
materialDescription.map = props.map;
}
return materialDescription;
}
applyInitialProps(threeObject, props) {
super.applyInitialProps(threeObject, props);
if (!props.hasOwnProperty('map')) {
threeObject.map = null;
}
}
}
module.exports = MeshLambertMaterialDescriptor;
|
# Copyright (c) ZenML GmbH 2021. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing
# permissions and limitations under the License.
from typing import TYPE_CHECKING, Any, Dict, Type
from zenml.exceptions import IntegrationError
from zenml.logger import get_logger
if TYPE_CHECKING:
from zenml.integrations.integration import Integration
logger = get_logger(__name__)
class IntegrationRegistry(object):
"""Registry to keep track of ZenML Integrations"""
def __init__(self) -> None:
"""Initializing the integration registry"""
self._integrations: Dict[str, Type["Integration"]] = {}
@property
def integrations(self) -> Dict[str, Type["Integration"]]:
"""Method to get integrations dictionary.
Returns:
A dict of integration key to type of `Integration`.
"""
return self._integrations
@integrations.setter
def integrations(self, i: Any) -> None:
"""Setter method for the integrations property"""
raise IntegrationError(
"Please do not manually change the integrations within the "
"registry. If you would like to register a new integration "
"manually, please use "
"`integration_registry.register_integration()`."
)
def register_integration(
self, key: str, type_: Type["Integration"]
) -> None:
"""Method to register an integration with a given name"""
self._integrations[key] = type_
def activate_integrations(self) -> None:
"""Method to activate the integrations with are registered in the
registry"""
for name, integration in self._integrations.items():
if integration.check_installation():
integration.activate()
logger.debug(f"Integration `{name}` is activated.")
else:
logger.debug(f"Integration `{name}` could not be activated.")
integration_registry = IntegrationRegistry()
|
/**
* @fileoverview added by tsickle
* @suppress {checkTypes,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc
*/
// This icon file is generated by build/generate.ts
// tslint:disable
/** @type {?} */
export const manifest = {
fill: [
'account-book',
'alert',
'alipay-circle',
'alipay-square',
'aliwangwang',
'amazon-circle',
'amazon-square',
'android',
'api',
'apple',
'appstore',
'audio',
'backward',
'bank',
'behance-circle',
'behance-square',
'bell',
'book',
'box-plot',
'build',
'bulb',
'calculator',
'calendar',
'camera',
'car',
'caret-down',
'caret-left',
'caret-right',
'carry-out',
'check-circle',
'caret-up',
'check-square',
'chrome',
'ci-circle',
'clock-circle',
'close-circle',
'close-square',
'cloud',
'code-sandbox-circle',
'code-sandbox-square',
'code',
'codepen-circle',
'codepen-square',
'compass',
'contacts',
'container',
'control',
'copy',
'copyright-circle',
'credit-card',
'crown',
'customer-service',
'dashboard',
'database',
'delete',
'diff',
'dingtalk-circle',
'dingtalk-square',
'dislike',
'dollar-circle',
'down-circle',
'down-square',
'dribbble-circle',
'dribbble-square',
'dropbox-circle',
'dropbox-square',
'edit',
'environment',
'euro-circle',
'exclamation-circle',
'experiment',
'eye-invisible',
'eye',
'facebook',
'fast-backward',
'fast-forward',
'file-add',
'file-excel',
'file-exclamation',
'file-image',
'file-markdown',
'file-pdf',
'file-ppt',
'file-text',
'file-unknown',
'file-word',
'file-zip',
'file',
'filter',
'fire',
'flag',
'folder-add',
'folder-open',
'folder',
'forward',
'frown',
'fund',
'funnel-plot',
'gift',
'github',
'gitlab',
'golden',
'google-circle',
'google-plus-circle',
'google-plus-square',
'google-square',
'hdd',
'heart',
'highlight',
'home',
'hourglass',
'html5',
'idcard',
'ie-circle',
'ie-square',
'info-circle',
'instagram',
'insurance',
'interation',
'layout',
'left-circle',
'left-square',
'like',
'linkedin',
'lock',
'mail',
'medicine-box',
'medium-circle',
'medium-square',
'message',
'minus-circle',
'meh',
'minus-square',
'mobile',
'notification',
'money-collect',
'pause-circle',
'pay-circle',
'phone',
'picture',
'pie-chart',
'play-circle',
'play-square',
'plus-circle',
'plus-square',
'pound-circle',
'printer',
'profile',
'project',
'property-safety',
'pushpin',
'qq-circle',
'qq-square',
'question-circle',
'read',
'reconciliation',
'red-envelope',
'reddit-circle',
'reddit-square',
'rest',
'right-circle',
'right-square',
'rocket',
'safety-certificate',
'save',
'schedule',
'security-scan',
'setting',
'shop',
'shopping',
'sketch-circle',
'sketch-square',
'skin',
'skype',
'slack-circle',
'slack-square',
'sliders',
'smile',
'snippets',
'sound',
'star',
'step-backward',
'step-forward',
'stop',
'switcher',
'tablet',
'tag',
'tags',
'taobao-circle',
'taobao-square',
'thunderbolt',
'tool',
'trademark-circle',
'trophy',
'twitter-circle',
'twitter-square',
'unlock',
'up-circle',
'up-square',
'usb',
'video-camera',
'wallet',
'warning',
'wechat',
'weibo-circle',
'weibo-square',
'windows',
'yahoo',
'youtube',
'yuque',
'zhihu-circle',
'zhihu-square'
],
outline: [
'account-book',
'alert',
'alipay-circle',
'aliwangwang',
'android',
'api',
'apple',
'appstore',
'audio',
'backward',
'bank',
'behance-square',
'bell',
'book',
'box-plot',
'build',
'bulb',
'calculator',
'calendar',
'camera',
'car',
'caret-down',
'caret-left',
'caret-right',
'carry-out',
'check-circle',
'caret-up',
'check-square',
'chrome',
'clock-circle',
'close-circle',
'close-square',
'cloud',
'code',
'codepen-circle',
'compass',
'contacts',
'container',
'control',
'copy',
'credit-card',
'crown',
'customer-service',
'dashboard',
'database',
'delete',
'diff',
'dislike',
'down-circle',
'down-square',
'dribbble-square',
'edit',
'environment',
'exclamation-circle',
'experiment',
'eye-invisible',
'eye',
'facebook',
'fast-backward',
'fast-forward',
'file-add',
'file-excel',
'file-exclamation',
'file-image',
'file-markdown',
'file-pdf',
'file-ppt',
'file-text',
'file-unknown',
'file-word',
'file-zip',
'file',
'filter',
'fire',
'flag',
'folder-add',
'folder-open',
'folder',
'forward',
'frown',
'fund',
'funnel-plot',
'gift',
'github',
'gitlab',
'hdd',
'heart',
'highlight',
'home',
'hourglass',
'html5',
'idcard',
'info-circle',
'instagram',
'insurance',
'interation',
'layout',
'left-circle',
'left-square',
'like',
'linkedin',
'lock',
'mail',
'medicine-box',
'message',
'minus-circle',
'meh',
'minus-square',
'mobile',
'notification',
'money-collect',
'pause-circle',
'pay-circle',
'phone',
'picture',
'pie-chart',
'play-circle',
'play-square',
'plus-circle',
'plus-square',
'printer',
'profile',
'project',
'property-safety',
'pushpin',
'question-circle',
'read',
'reconciliation',
'red-envelope',
'rest',
'right-circle',
'right-square',
'rocket',
'safety-certificate',
'save',
'schedule',
'security-scan',
'setting',
'shop',
'shopping',
'skin',
'skype',
'slack-square',
'sliders',
'smile',
'snippets',
'sound',
'star',
'step-backward',
'step-forward',
'stop',
'switcher',
'tablet',
'tag',
'tags',
'taobao-circle',
'thunderbolt',
'tool',
'trophy',
'unlock',
'up-circle',
'up-square',
'usb',
'video-camera',
'wallet',
'warning',
'wechat',
'weibo-circle',
'weibo-square',
'windows',
'yahoo',
'youtube',
'yuque',
'alibaba',
'align-left',
'align-right',
'alipay',
'aliyun',
'amazon',
'ant-cloud',
'ant-design',
'apartment',
'area-chart',
'arrow-down',
'arrow-left',
'arrow-right',
'arrow-up',
'arrows-alt',
'audit',
'align-center',
'barcode',
'bar-chart',
'bars',
'behance',
'bg-colors',
'block',
'bold',
'border-bottom',
'border-horizontal',
'border-inner',
'border-left',
'border-outer',
'border-right',
'border-top',
'border-verticle',
'border',
'branches',
'check',
'ci',
'close',
'cloud-download',
'cloud-server',
'cloud-sync',
'cloud-upload',
'cluster',
'code-sandbox',
'codepen',
'coffee',
'colum-height',
'column-width',
'copyright',
'dash',
'deployment-unit',
'desktop',
'dingding',
'disconnect',
'dollar',
'dot-chart',
'double-right',
'double-left',
'down',
'download',
'drag',
'dribbble',
'dropbox',
'ellipsis',
'enter',
'euro',
'exception',
'exclamation',
'export',
'fall',
'file-done',
'file-jpg',
'file-protect',
'file-search',
'file-sync',
'font-colors',
'font-size',
'fork',
'form',
'fullscreen-exit',
'fullscreen',
'gateway',
'global',
'gold',
'google-plus',
'google',
'heat-map',
'ie',
'import',
'inbox',
'info',
'issues-close',
'italic',
'key',
'laptop',
'left',
'line-chart',
'line-height',
'line',
'link',
'loading-3-quarters',
'loading',
'login',
'logout',
'man',
'medium-workmark',
'medium',
'menu-fold',
'menu-unfold',
'menu',
'minus',
'monitor',
'mr',
'number',
'ordered-list',
'paper-clip',
'pause',
'percentage',
'pic-center',
'pic-left',
'pic-right',
'plus',
'pound',
'poweroff',
'qq',
'qrcode',
'question',
'radar-chart',
'radius-bottomleft',
'radius-bottomright',
'radius-setting',
'radius-upleft',
'radius-upright',
'reddit',
'redo',
'reload',
'reload-time',
'retweet',
'right',
'rise',
'robot',
'rollback',
'safety',
'scan',
'scissor',
'search',
'select',
'shake',
'share-alt',
'shopping-cart',
'shrink',
'sketch',
'slack',
'small-dash',
'solution',
'sort-ascending',
'sort-descending',
'stock',
'strikethrough',
'swap-left',
'swap-right',
'swap',
'sync',
'table',
'taobao',
'team',
'to-top',
'trademark',
'transaction',
'twitter',
'underline',
'undo',
'unordered-list',
'up',
'upload',
'user-add',
'user-delete',
'user',
'usergroup-add',
'usergroup-delete',
'vertical-align-bottom',
'vertical-align-middle',
'vertical-align-top',
'vertical-left',
'vertical-right',
'weibo',
'wifi',
'woman',
'zhihu',
'zoom-in',
'zoom-out'
],
twotone: [
'account-book',
'alert',
'api',
'appstore',
'audio',
'bank',
'bell',
'book',
'box-plot',
'build',
'bulb',
'calculator',
'camera',
'car',
'carry-out',
'check-circle',
'check-square',
'clock-circle',
'close-circle',
'close-square',
'cloud',
'code',
'compass',
'contacts',
'container',
'control',
'copy',
'credit-card',
'crown',
'customer-service',
'dashboard',
'database',
'delete',
'diff',
'dislike',
'down-circle',
'down-square',
'edit',
'environment',
'exclamation-circle',
'experiment',
'eye-invisible',
'eye',
'file-add',
'file-excel',
'file-exclamation',
'file-image',
'file-markdown',
'file-pdf',
'file-ppt',
'file-text',
'file-unknown',
'file-word',
'file-zip',
'file',
'filter',
'fire',
'flag',
'folder-add',
'folder-open',
'folder',
'frown',
'fund',
'funnel-plot',
'gift',
'hdd',
'heart',
'highlight',
'home',
'hourglass',
'html5',
'idcard',
'info-circle',
'insurance',
'interation',
'layout',
'left-circle',
'left-square',
'like',
'lock',
'mail',
'medicine-box',
'message',
'minus-circle',
'meh',
'minus-square',
'mobile',
'notification',
'money-collect',
'pause-circle',
'phone',
'picture',
'pie-chart',
'play-circle',
'play-square',
'plus-circle',
'plus-square',
'pound-circle',
'printer',
'profile',
'project',
'property-safety',
'pushpin',
'question-circle',
'reconciliation',
'red-envelope',
'rest',
'right-circle',
'right-square',
'rocket',
'safety-certificate',
'save',
'schedule',
'security-scan',
'setting',
'shop',
'shopping',
'skin',
'sliders',
'smile',
'snippets',
'sound',
'star',
'stop',
'switcher',
'tablet',
'tag',
'tags',
'thunderbolt',
'tool',
'trademark-circle',
'trophy',
'unlock',
'up-circle',
'up-square',
'usb',
'video-camera',
'wallet',
'warning',
'ci',
'copyright',
'dollar',
'euro',
'gold',
'canlendar'
]
};
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWFuaWZlc3QuanMiLCJzb3VyY2VSb290Ijoibmc6Ly9AYW50LWRlc2lnbi9pY29ucy1hbmd1bGFyLyIsInNvdXJjZXMiOlsibWFuaWZlc3QudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7OztBQUtBLE1BQU0sT0FBTyxRQUFRLEdBQWE7SUFDaEMsSUFBSSxFQUFFO1FBQ0osY0FBYztRQUNkLE9BQU87UUFDUCxlQUFlO1FBQ2YsZUFBZTtRQUNmLGFBQWE7UUFDYixlQUFlO1FBQ2YsZUFBZTtRQUNmLFNBQVM7UUFDVCxLQUFLO1FBQ0wsT0FBTztRQUNQLFVBQVU7UUFDVixPQUFPO1FBQ1AsVUFBVTtRQUNWLE1BQU07UUFDTixnQkFBZ0I7UUFDaEIsZ0JBQWdCO1FBQ2hCLE1BQU07UUFDTixNQUFNO1FBQ04sVUFBVTtRQUNWLE9BQU87UUFDUCxNQUFNO1FBQ04sWUFBWTtRQUNaLFVBQVU7UUFDVixRQUFRO1FBQ1IsS0FBSztRQUNMLFlBQVk7UUFDWixZQUFZO1FBQ1osYUFBYTtRQUNiLFdBQVc7UUFDWCxjQUFjO1FBQ2QsVUFBVTtRQUNWLGNBQWM7UUFDZCxRQUFRO1FBQ1IsV0FBVztRQUNYLGNBQWM7UUFDZCxjQUFjO1FBQ2QsY0FBYztRQUNkLE9BQU87UUFDUCxxQkFBcUI7UUFDckIscUJBQXFCO1FBQ3JCLE1BQU07UUFDTixnQkFBZ0I7UUFDaEIsZ0JBQWdCO1FBQ2hCLFNBQVM7UUFDVCxVQUFVO1FBQ1YsV0FBVztRQUNYLFNBQVM7UUFDVCxNQUFNO1FBQ04sa0JBQWtCO1FBQ2xCLGFBQWE7UUFDYixPQUFPO1FBQ1Asa0JBQWtCO1FBQ2xCLFdBQVc7UUFDWCxVQUFVO1FBQ1YsUUFBUTtRQUNSLE1BQU07UUFDTixpQkFBaUI7UUFDakIsaUJBQWlCO1FBQ2pCLFNBQVM7UUFDVCxlQUFlO1FBQ2YsYUFBYTtRQUNiLGFBQWE7UUFDYixpQkFBaUI7UUFDakIsaUJBQWlCO1FBQ2pCLGdCQUFnQjtRQUNoQixnQkFBZ0I7UUFDaEIsTUFBTTtRQUNOLGFBQWE7UUFDYixhQUFhO1FBQ2Isb0JBQW9CO1FBQ3BCLFlBQVk7UUFDWixlQUFlO1FBQ2YsS0FBSztRQUNMLFVBQVU7UUFDVixlQUFlO1FBQ2YsY0FBYztRQUNkLFVBQVU7UUFDVixZQUFZO1FBQ1osa0JBQWtCO1FBQ2xCLFlBQVk7UUFDWixlQUFlO1FBQ2YsVUFBVTtRQUNWLFVBQVU7UUFDVixXQUFXO1FBQ1gsY0FBYztRQUNkLFdBQVc7UUFDWCxVQUFVO1FBQ1YsTUFBTTtRQUNOLFFBQVE7UUFDUixNQUFNO1FBQ04sTUFBTTtRQUNOLFlBQVk7UUFDWixhQUFhO1FBQ2IsUUFBUTtRQUNSLFNBQVM7UUFDVCxPQUFPO1FBQ1AsTUFBTTtRQUNOLGFBQWE7UUFDYixNQUFNO1FBQ04sUUFBUTtRQUNSLFFBQVE7UUFDUixRQUFRO1FBQ1IsZUFBZTtRQUNmLG9CQUFvQjtRQUNwQixvQkFBb0I7UUFDcEIsZUFBZTtRQUNmLEtBQUs7UUFDTCxPQUFPO1FBQ1AsV0FBVztRQUNYLE1BQU07UUFDTixXQUFXO1FBQ1gsT0FBTztRQUNQLFFBQVE7UUFDUixXQUFXO1FBQ1gsV0FBVztRQUNYLGFBQWE7UUFDYixXQUFXO1FBQ1gsV0FBVztRQUNYLFlBQVk7UUFDWixRQUFRO1FBQ1IsYUFBYTtRQUNiLGFBQWE7UUFDYixNQUFNO1FBQ04sVUFBVTtRQUNWLE1BQU07UUFDTixNQUFNO1FBQ04sY0FBYztRQUNkLGVBQWU7UUFDZixlQUFlO1FBQ2YsU0FBUztRQUNULGNBQWM7UUFDZCxLQUFLO1FBQ0wsY0FBYztRQUNkLFFBQVE7UUFDUixjQUFjO1FBQ2QsZUFBZTtRQUNmLGNBQWM7UUFDZCxZQUFZO1FBQ1osT0FBTztRQUNQLFNBQVM7UUFDVCxXQUFXO1FBQ1gsYUFBYTtRQUNiLGFBQWE7UUFDYixhQUFhO1FBQ2IsYUFBYTtRQUNiLGNBQWM7UUFDZCxTQUFTO1FBQ1QsU0FBUztRQUNULFNBQVM7UUFDVCxpQkFBaUI7UUFDakIsU0FBUztRQUNULFdBQVc7UUFDWCxXQUFXO1FBQ1gsaUJBQWlCO1FBQ2pCLE1BQU07UUFDTixnQkFBZ0I7UUFDaEIsY0FBYztRQUNkLGVBQWU7UUFDZixlQUFlO1FBQ2YsTUFBTTtRQUNOLGNBQWM7UUFDZCxjQUFjO1FBQ2QsUUFBUTtRQUNSLG9CQUFvQjtRQUNwQixNQUFNO1FBQ04sVUFBVTtRQUNWLGVBQWU7UUFDZixTQUFTO1FBQ1QsTUFBTTtRQUNOLFVBQVU7UUFDVixlQUFlO1FBQ2YsZUFBZTtRQUNmLE1BQU07UUFDTixPQUFPO1FBQ1AsY0FBYztRQUNkLGNBQWM7UUFDZCxTQUFTO1FBQ1QsT0FBTztRQUNQLFVBQVU7UUFDVixPQUFPO1FBQ1AsTUFBTTtRQUNOLGVBQWU7UUFDZixjQUFjO1FBQ2QsTUFBTTtRQUNOLFVBQVU7UUFDVixRQUFRO1FBQ1IsS0FBSztRQUNMLE1BQU07UUFDTixlQUFlO1FBQ2YsZUFBZTtRQUNmLGFBQWE7UUFDYixNQUFNO1FBQ04sa0JBQWtCO1FBQ2xCLFFBQVE7UUFDUixnQkFBZ0I7UUFDaEIsZ0JBQWdCO1FBQ2hCLFFBQVE7UUFDUixXQUFXO1FBQ1gsV0FBVztRQUNYLEtBQUs7UUFDTCxjQUFjO1FBQ2QsUUFBUTtRQUNSLFNBQVM7UUFDVCxRQUFRO1FBQ1IsY0FBYztRQUNkLGNBQWM7UUFDZCxTQUFTO1FBQ1QsT0FBTztRQUNQLFNBQVM7UUFDVCxPQUFPO1FBQ1AsY0FBYztRQUNkLGNBQWM7S0FDZjtJQUNELE9BQU8sRUFBRTtRQUNQLGNBQWM7UUFDZCxPQUFPO1FBQ1AsZUFBZTtRQUNmLGFBQWE7UUFDYixTQUFTO1FBQ1QsS0FBSztRQUNMLE9BQU87UUFDUCxVQUFVO1FBQ1YsT0FBTztRQUNQLFVBQVU7UUFDVixNQUFNO1FBQ04sZ0JBQWdCO1FBQ2hCLE1BQU07UUFDTixNQUFNO1FBQ04sVUFBVTtRQUNWLE9BQU87UUFDUCxNQUFNO1FBQ04sWUFBWTtRQUNaLFVBQVU7UUFDVixRQUFRO1FBQ1IsS0FBSztRQUNMLFlBQVk7UUFDWixZQUFZO1FBQ1osYUFBYTtRQUNiLFdBQVc7UUFDWCxjQUFjO1FBQ2QsVUFBVTtRQUNWLGNBQWM7UUFDZCxRQUFRO1FBQ1IsY0FBYztRQUNkLGNBQWM7UUFDZCxjQUFjO1FBQ2QsT0FBTztRQUNQLE1BQU07UUFDTixnQkFBZ0I7UUFDaEIsU0FBUztRQUNULFVBQVU7UUFDVixXQUFXO1FBQ1gsU0FBUztRQUNULE1BQU07UUFDTixhQUFhO1FBQ2IsT0FBTztRQUNQLGtCQUFrQjtRQUNsQixXQUFXO1FBQ1gsVUFBVTtRQUNWLFFBQVE7UUFDUixNQUFNO1FBQ04sU0FBUztRQUNULGFBQWE7UUFDYixhQUFhO1FBQ2IsaUJBQWlCO1FBQ2pCLE1BQU07UUFDTixhQUFhO1FBQ2Isb0JBQW9CO1FBQ3BCLFlBQVk7UUFDWixlQUFlO1FBQ2YsS0FBSztRQUNMLFVBQVU7UUFDVixlQUFlO1FBQ2YsY0FBYztRQUNkLFVBQVU7UUFDVixZQUFZO1FBQ1osa0JBQWtCO1FBQ2xCLFlBQVk7UUFDWixlQUFlO1FBQ2YsVUFBVTtRQUNWLFVBQVU7UUFDVixXQUFXO1FBQ1gsY0FBYztRQUNkLFdBQVc7UUFDWCxVQUFVO1FBQ1YsTUFBTTtRQUNOLFFBQVE7UUFDUixNQUFNO1FBQ04sTUFBTTtRQUNOLFlBQVk7UUFDWixhQUFhO1FBQ2IsUUFBUTtRQUNSLFNBQVM7UUFDVCxPQUFPO1FBQ1AsTUFBTTtRQUNOLGFBQWE7UUFDYixNQUFNO1FBQ04sUUFBUTtRQUNSLFFBQVE7UUFDUixLQUFLO1FBQ0wsT0FBTztRQUNQLFdBQVc7UUFDWCxNQUFNO1FBQ04sV0FBVztRQUNYLE9BQU87UUFDUCxRQUFRO1FBQ1IsYUFBYTtRQUNiLFdBQVc7UUFDWCxXQUFXO1FBQ1gsWUFBWTtRQUNaLFFBQVE7UUFDUixhQUFhO1FBQ2IsYUFBYTtRQUNiLE1BQU07UUFDTixVQUFVO1FBQ1YsTUFBTTtRQUNOLE1BQU07UUFDTixjQUFjO1FBQ2QsU0FBUztRQUNULGNBQWM7UUFDZCxLQUFLO1FBQ0wsY0FBYztRQUNkLFFBQVE7UUFDUixjQUFjO1FBQ2QsZUFBZTtRQUNmLGNBQWM7UUFDZCxZQUFZO1FBQ1osT0FBTztRQUNQLFNBQVM7UUFDVCxXQUFXO1FBQ1gsYUFBYTtRQUNiLGFBQWE7UUFDYixhQUFhO1FBQ2IsYUFBYTtRQUNiLFNBQVM7UUFDVCxTQUFTO1FBQ1QsU0FBUztRQUNULGlCQUFpQjtRQUNqQixTQUFTO1FBQ1QsaUJBQWlCO1FBQ2pCLE1BQU07UUFDTixnQkFBZ0I7UUFDaEIsY0FBYztRQUNkLE1BQU07UUFDTixjQUFjO1FBQ2QsY0FBYztRQUNkLFFBQVE7UUFDUixvQkFBb0I7UUFDcEIsTUFBTTtRQUNOLFVBQVU7UUFDVixlQUFlO1FBQ2YsU0FBUztRQUNULE1BQU07UUFDTixVQUFVO1FBQ1YsTUFBTTtRQUNOLE9BQU87UUFDUCxjQUFjO1FBQ2QsU0FBUztRQUNULE9BQU87UUFDUCxVQUFVO1FBQ1YsT0FBTztRQUNQLE1BQU07UUFDTixlQUFlO1FBQ2YsY0FBYztRQUNkLE1BQU07UUFDTixVQUFVO1FBQ1YsUUFBUTtRQUNSLEtBQUs7UUFDTCxNQUFNO1FBQ04sZUFBZTtRQUNmLGFBQWE7UUFDYixNQUFNO1FBQ04sUUFBUTtRQUNSLFFBQVE7UUFDUixXQUFXO1FBQ1gsV0FBVztRQUNYLEtBQUs7UUFDTCxjQUFjO1FBQ2QsUUFBUTtRQUNSLFNBQVM7UUFDVCxRQUFRO1FBQ1IsY0FBYztRQUNkLGNBQWM7UUFDZCxTQUFTO1FBQ1QsT0FBTztRQUNQLFNBQVM7UUFDVCxPQUFPO1FBQ1AsU0FBUztRQUNULFlBQVk7UUFDWixhQUFhO1FBQ2IsUUFBUTtRQUNSLFFBQVE7UUFDUixRQUFRO1FBQ1IsV0FBVztRQUNYLFlBQVk7UUFDWixXQUFXO1FBQ1gsWUFBWTtRQUNaLFlBQVk7UUFDWixZQUFZO1FBQ1osYUFBYTtRQUNiLFVBQVU7UUFDVixZQUFZO1FBQ1osT0FBTztRQUNQLGNBQWM7UUFDZCxTQUFTO1FBQ1QsV0FBVztRQUNYLE1BQU07UUFDTixTQUFTO1FBQ1QsV0FBVztRQUNYLE9BQU87UUFDUCxNQUFNO1FBQ04sZUFBZTtRQUNmLG1CQUFtQjtRQUNuQixjQUFjO1FBQ2QsYUFBYTtRQUNiLGNBQWM7UUFDZCxjQUFjO1FBQ2QsWUFBWTtRQUNaLGlCQUFpQjtRQUNqQixRQUFRO1FBQ1IsVUFBVTtRQUNWLE9BQU87UUFDUCxJQUFJO1FBQ0osT0FBTztRQUNQLGdCQUFnQjtRQUNoQixjQUFjO1FBQ2QsWUFBWTtRQUNaLGNBQWM7UUFDZCxTQUFTO1FBQ1QsY0FBYztRQUNkLFNBQVM7UUFDVCxRQUFRO1FBQ1IsY0FBYztRQUNkLGNBQWM7UUFDZCxXQUFXO1FBQ1gsTUFBTTtRQUNOLGlCQUFpQjtRQUNqQixTQUFTO1FBQ1QsVUFBVTtRQUNWLFlBQVk7UUFDWixRQUFRO1FBQ1IsV0FBVztRQUNYLGNBQWM7UUFDZCxhQUFhO1FBQ2IsTUFBTTtRQUNOLFVBQVU7UUFDVixNQUFNO1FBQ04sVUFBVTtRQUNWLFNBQVM7UUFDVCxVQUFVO1FBQ1YsT0FBTztRQUNQLE1BQU07UUFDTixXQUFXO1FBQ1gsYUFBYTtRQUNiLFFBQVE7UUFDUixNQUFNO1FBQ04sV0FBVztRQUNYLFVBQVU7UUFDVixjQUFjO1FBQ2QsYUFBYTtRQUNiLFdBQVc7UUFDWCxhQUFhO1FBQ2IsV0FBVztRQUNYLE1BQU07UUFDTixNQUFNO1FBQ04saUJBQWlCO1FBQ2pCLFlBQVk7UUFDWixTQUFTO1FBQ1QsUUFBUTtRQUNSLE1BQU07UUFDTixhQUFhO1FBQ2IsUUFBUTtRQUNSLFVBQVU7UUFDVixJQUFJO1FBQ0osUUFBUTtRQUNSLE9BQU87UUFDUCxNQUFNO1FBQ04sY0FBYztRQUNkLFFBQVE7UUFDUixLQUFLO1FBQ0wsUUFBUTtRQUNSLE1BQU07UUFDTixZQUFZO1FBQ1osYUFBYTtRQUNiLE1BQU07UUFDTixNQUFNO1FBQ04sb0JBQW9CO1FBQ3BCLFNBQVM7UUFDVCxPQUFPO1FBQ1AsUUFBUTtRQUNSLEtBQUs7UUFDTCxpQkFBaUI7UUFDakIsUUFBUTtRQUNSLFdBQVc7UUFDWCxhQUFhO1FBQ2IsTUFBTTtRQUNOLE9BQU87UUFDUCxTQUFTO1FBQ1QsSUFBSTtRQUNKLFFBQVE7UUFDUixjQUFjO1FBQ2QsWUFBWTtRQUNaLE9BQU87UUFDUCxZQUFZO1FBQ1osWUFBWTtRQUNaLFVBQVU7UUFDVixXQUFXO1FBQ1gsTUFBTTtRQUNOLE9BQU87UUFDUCxVQUFVO1FBQ1YsSUFBSTtRQUNKLFFBQVE7UUFDUixVQUFVO1FBQ1YsYUFBYTtRQUNiLG1CQUFtQjtRQUNuQixvQkFBb0I7UUFDcEIsZ0JBQWdCO1FBQ2hCLGVBQWU7UUFDZixnQkFBZ0I7UUFDaEIsUUFBUTtRQUNSLE1BQU07UUFDTixRQUFRO1FBQ1IsYUFBYTtRQUNiLFNBQVM7UUFDVCxPQUFPO1FBQ1AsTUFBTTtRQUNOLE9BQU87UUFDUCxVQUFVO1FBQ1YsUUFBUTtRQUNSLE1BQU07UUFDTixTQUFTO1FBQ1QsUUFBUTtRQUNSLFFBQVE7UUFDUixPQUFPO1FBQ1AsV0FBVztRQUNYLGVBQWU7UUFDZixRQUFRO1FBQ1IsUUFBUTtRQUNSLE9BQU87UUFDUCxZQUFZO1FBQ1osVUFBVTtRQUNWLGdCQUFnQjtRQUNoQixpQkFBaUI7UUFDakIsT0FBTztRQUNQLGVBQWU7UUFDZixXQUFXO1FBQ1gsWUFBWTtRQUNaLE1BQU07UUFDTixNQUFNO1FBQ04sT0FBTztRQUNQLFFBQVE7UUFDUixNQUFNO1FBQ04sUUFBUTtRQUNSLFdBQVc7UUFDWCxhQUFhO1FBQ2IsU0FBUztRQUNULFdBQVc7UUFDWCxNQUFNO1FBQ04sZ0JBQWdCO1FBQ2hCLElBQUk7UUFDSixRQUFRO1FBQ1IsVUFBVTtRQUNWLGFBQWE7UUFDYixNQUFNO1FBQ04sZUFBZTtRQUNmLGtCQUFrQjtRQUNsQix1QkFBdUI7UUFDdkIsdUJBQXVCO1FBQ3ZCLG9CQUFvQjtRQUNwQixlQUFlO1FBQ2YsZ0JBQWdCO1FBQ2hCLE9BQU87UUFDUCxNQUFNO1FBQ04sT0FBTztRQUNQLE9BQU87UUFDUCxTQUFTO1FBQ1QsVUFBVTtLQUNYO0lBQ0QsT0FBTyxFQUFFO1FBQ1AsY0FBYztRQUNkLE9BQU87UUFDUCxLQUFLO1FBQ0wsVUFBVTtRQUNWLE9BQU87UUFDUCxNQUFNO1FBQ04sTUFBTTtRQUNOLE1BQU07UUFDTixVQUFVO1FBQ1YsT0FBTztRQUNQLE1BQU07UUFDTixZQUFZO1FBQ1osUUFBUTtRQUNSLEtBQUs7UUFDTCxXQUFXO1FBQ1gsY0FBYztRQUNkLGNBQWM7UUFDZCxjQUFjO1FBQ2QsY0FBYztRQUNkLGNBQWM7UUFDZCxPQUFPO1FBQ1AsTUFBTTtRQUNOLFNBQVM7UUFDVCxVQUFVO1FBQ1YsV0FBVztRQUNYLFNBQVM7UUFDVCxNQUFNO1FBQ04sYUFBYTtRQUNiLE9BQU87UUFDUCxrQkFBa0I7UUFDbEIsV0FBVztRQUNYLFVBQVU7UUFDVixRQUFRO1FBQ1IsTUFBTTtRQUNOLFNBQVM7UUFDVCxhQUFhO1FBQ2IsYUFBYTtRQUNiLE1BQU07UUFDTixhQUFhO1FBQ2Isb0JBQW9CO1FBQ3BCLFlBQVk7UUFDWixlQUFlO1FBQ2YsS0FBSztRQUNMLFVBQVU7UUFDVixZQUFZO1FBQ1osa0JBQWtCO1FBQ2xCLFlBQVk7UUFDWixlQUFlO1FBQ2YsVUFBVTtRQUNWLFVBQVU7UUFDVixXQUFXO1FBQ1gsY0FBYztRQUNkLFdBQVc7UUFDWCxVQUFVO1FBQ1YsTUFBTTtRQUNOLFFBQVE7UUFDUixNQUFNO1FBQ04sTUFBTTtRQUNOLFlBQVk7UUFDWixhQUFhO1FBQ2IsUUFBUTtRQUNSLE9BQU87UUFDUCxNQUFNO1FBQ04sYUFBYTtRQUNiLE1BQU07UUFDTixLQUFLO1FBQ0wsT0FBTztRQUNQLFdBQVc7UUFDWCxNQUFNO1FBQ04sV0FBVztRQUNYLE9BQU87UUFDUCxRQUFRO1FBQ1IsYUFBYTtRQUNiLFdBQVc7UUFDWCxZQUFZO1FBQ1osUUFBUTtRQUNSLGFBQWE7UUFDYixhQUFhO1FBQ2IsTUFBTTtRQUNOLE1BQU07UUFDTixNQUFNO1FBQ04sY0FBYztRQUNkLFNBQVM7UUFDVCxjQUFjO1FBQ2QsS0FBSztRQUNMLGNBQWM7UUFDZCxRQUFRO1FBQ1IsY0FBYztRQUNkLGVBQWU7UUFDZixjQUFjO1FBQ2QsT0FBTztRQUNQLFNBQVM7UUFDVCxXQUFXO1FBQ1gsYUFBYTtRQUNiLGFBQWE7UUFDYixhQUFhO1FBQ2IsYUFBYTtRQUNiLGNBQWM7UUFDZCxTQUFTO1FBQ1QsU0FBUztRQUNULFNBQVM7UUFDVCxpQkFBaUI7UUFDakIsU0FBUztRQUNULGlCQUFpQjtRQUNqQixnQkFBZ0I7UUFDaEIsY0FBYztRQUNkLE1BQU07UUFDTixjQUFjO1FBQ2QsY0FBYztRQUNkLFFBQVE7UUFDUixvQkFBb0I7UUFDcEIsTUFBTTtRQUNOLFVBQVU7UUFDVixlQUFlO1FBQ2YsU0FBUztRQUNULE1BQU07UUFDTixVQUFVO1FBQ1YsTUFBTTtRQUNOLFNBQVM7UUFDVCxPQUFPO1FBQ1AsVUFBVTtRQUNWLE9BQU87UUFDUCxNQUFNO1FBQ04sTUFBTTtRQUNOLFVBQVU7UUFDVixRQUFRO1FBQ1IsS0FBSztRQUNMLE1BQU07UUFDTixhQUFhO1FBQ2IsTUFBTTtRQUNOLGtCQUFrQjtRQUNsQixRQUFRO1FBQ1IsUUFBUTtRQUNSLFdBQVc7UUFDWCxXQUFXO1FBQ1gsS0FBSztRQUNMLGNBQWM7UUFDZCxRQUFRO1FBQ1IsU0FBUztRQUNULElBQUk7UUFDSixXQUFXO1FBQ1gsUUFBUTtRQUNSLE1BQU07UUFDTixNQUFNO1FBQ04sV0FBVztLQUNaO0NBQ0YiLCJzb3VyY2VzQ29udGVudCI6WyIvLyBUaGlzIGljb24gZmlsZSBpcyBnZW5lcmF0ZWQgYnkgYnVpbGQvZ2VuZXJhdGUudHNcbi8vIHRzbGludDpkaXNhYmxlXG5cbmltcG9ydCB7IE1hbmlmZXN0IH0gZnJvbSAnLi90eXBlcyc7XG5cbmV4cG9ydCBjb25zdCBtYW5pZmVzdDogTWFuaWZlc3QgPSB7XG4gIGZpbGw6IFtcbiAgICAnYWNjb3VudC1ib29rJyxcbiAgICAnYWxlcnQnLFxuICAgICdhbGlwYXktY2lyY2xlJyxcbiAgICAnYWxpcGF5LXNxdWFyZScsXG4gICAgJ2FsaXdhbmd3YW5nJyxcbiAgICAnYW1hem9uLWNpcmNsZScsXG4gICAgJ2FtYXpvbi1zcXVhcmUnLFxuICAgICdhbmRyb2lkJyxcbiAgICAnYXBpJyxcbiAgICAnYXBwbGUnLFxuICAgICdhcHBzdG9yZScsXG4gICAgJ2F1ZGlvJyxcbiAgICAnYmFja3dhcmQnLFxuICAgICdiYW5rJyxcbiAgICAnYmVoYW5jZS1jaXJjbGUnLFxuICAgICdiZWhhbmNlLXNxdWFyZScsXG4gICAgJ2JlbGwnLFxuICAgICdib29rJyxcbiAgICAnYm94LXBsb3QnLFxuICAgICdidWlsZCcsXG4gICAgJ2J1bGInLFxuICAgICdjYWxjdWxhdG9yJyxcbiAgICAnY2FsZW5kYXInLFxuICAgICdjYW1lcmEnLFxuICAgICdjYXInLFxuICAgICdjYXJldC1kb3duJyxcbiAgICAnY2FyZXQtbGVmdCcsXG4gICAgJ2NhcmV0LXJpZ2h0JyxcbiAgICAnY2Fycnktb3V0JyxcbiAgICAnY2hlY2stY2lyY2xlJyxcbiAgICAnY2FyZXQtdXAnLFxuICAgICdjaGVjay1zcXVhcmUnLFxuICAgICdjaHJvbWUnLFxuICAgICdjaS1jaXJjbGUnLFxuICAgICdjbG9jay1jaXJjbGUnLFxuICAgICdjbG9zZS1jaXJjbGUnLFxuICAgICdjbG9zZS1zcXVhcmUnLFxuICAgICdjbG91ZCcsXG4gICAgJ2NvZGUtc2FuZGJveC1jaXJjbGUnLFxuICAgICdjb2RlLXNhbmRib3gtc3F1YXJlJyxcbiAgICAnY29kZScsXG4gICAgJ2NvZGVwZW4tY2lyY2xlJyxcbiAgICAnY29kZXBlbi1zcXVhcmUnLFxuICAgICdjb21wYXNzJyxcbiAgICAnY29udGFjdHMnLFxuICAgICdjb250YWluZXInLFxuICAgICdjb250cm9sJyxcbiAgICAnY29weScsXG4gICAgJ2NvcHlyaWdodC1jaXJjbGUnLFxuICAgICdjcmVkaXQtY2FyZCcsXG4gICAgJ2Nyb3duJyxcbiAgICAnY3VzdG9tZXItc2VydmljZScsXG4gICAgJ2Rhc2hib2FyZCcsXG4gICAgJ2RhdGFiYXNlJyxcbiAgICAnZGVsZXRlJyxcbiAgICAnZGlmZicsXG4gICAgJ2Rpbmd0YWxrLWNpcmNsZScsXG4gICAgJ2Rpbmd0YWxrLXNxdWFyZScsXG4gICAgJ2Rpc2xpa2UnLFxuICAgICdkb2xsYXItY2lyY2xlJyxcbiAgICAnZG93bi1jaXJjbGUnLFxuICAgICdkb3duLXNxdWFyZScsXG4gICAgJ2RyaWJiYmxlLWNpcmNsZScsXG4gICAgJ2RyaWJiYmxlLXNxdWFyZScsXG4gICAgJ2Ryb3Bib3gtY2lyY2xlJyxcbiAgICAnZHJvcGJveC1zcXVhcmUnLFxuICAgICdlZGl0JyxcbiAgICAnZW52aXJvbm1lbnQnLFxuICAgICdldXJvLWNpcmNsZScsXG4gICAgJ2V4Y2xhbWF0aW9uLWNpcmNsZScsXG4gICAgJ2V4cGVyaW1lbnQnLFxuICAgICdleWUtaW52aXNpYmxlJyxcbiAgICAnZXllJyxcbiAgICAnZmFjZWJvb2snLFxuICAgICdmYXN0LWJhY2t3YXJkJyxcbiAgICAnZmFzdC1mb3J3YXJkJyxcbiAgICAnZmlsZS1hZGQnLFxuICAgICdmaWxlLWV4Y2VsJyxcbiAgICAnZmlsZS1leGNsYW1hdGlvbicsXG4gICAgJ2ZpbGUtaW1hZ2UnLFxuICAgICdmaWxlLW1hcmtkb3duJyxcbiAgICAnZmlsZS1wZGYnLFxuICAgICdmaWxlLXBwdCcsXG4gICAgJ2ZpbGUtdGV4dCcsXG4gICAgJ2ZpbGUtdW5rbm93bicsXG4gICAgJ2ZpbGUtd29yZCcsXG4gICAgJ2ZpbGUtemlwJyxcbiAgICAnZmlsZScsXG4gICAgJ2ZpbHRlcicsXG4gICAgJ2ZpcmUnLFxuICAgICdmbGFnJyxcbiAgICAnZm9sZGVyLWFkZCcsXG4gICAgJ2ZvbGRlci1vcGVuJyxcbiAgICAnZm9sZGVyJyxcbiAgICAnZm9yd2FyZCcsXG4gICAgJ2Zyb3duJyxcbiAgICAnZnVuZCcsXG4gICAgJ2Z1bm5lbC1wbG90JyxcbiAgICAnZ2lmdCcsXG4gICAgJ2dpdGh1YicsXG4gICAgJ2dpdGxhYicsXG4gICAgJ2dvbGRlbicsXG4gICAgJ2dvb2dsZS1jaXJjbGUnLFxuICAgICdnb29nbGUtcGx1cy1jaXJjbGUnLFxuICAgICdnb29nbGUtcGx1cy1zcXVhcmUnLFxuICAgICdnb29nbGUtc3F1YXJlJyxcbiAgICAnaGRkJyxcbiAgICAnaGVhcnQnLFxuICAgICdoaWdobGlnaHQnLFxuICAgICdob21lJyxcbiAgICAnaG91cmdsYXNzJyxcbiAgICAnaHRtbDUnLFxuICAgICdpZGNhcmQnLFxuICAgICdpZS1jaXJjbGUnLFxuICAgICdpZS1zcXVhcmUnLFxuICAgICdpbmZvLWNpcmNsZScsXG4gICAgJ2luc3RhZ3JhbScsXG4gICAgJ2luc3VyYW5jZScsXG4gICAgJ2ludGVyYXRpb24nLFxuICAgICdsYXlvdXQnLFxuICAgICdsZWZ0LWNpcmNsZScsXG4gICAgJ2xlZnQtc3F1YXJlJyxcbiAgICAnbGlrZScsXG4gICAgJ2xpbmtlZGluJyxcbiAgICAnbG9jaycsXG4gICAgJ21haWwnLFxuICAgICdtZWRpY2luZS1ib3gnLFxuICAgICdtZWRpdW0tY2lyY2xlJyxcbiAgICAnbWVkaXVtLXNxdWFyZScsXG4gICAgJ21lc3NhZ2UnLFxuICAgICdtaW51cy1jaXJjbGUnLFxuICAgICdtZWgnLFxuICAgICdtaW51cy1zcXVhcmUnLFxuICAgICdtb2JpbGUnLFxuICAgICdub3RpZmljYXRpb24nLFxuICAgICdtb25leS1jb2xsZWN0JyxcbiAgICAncGF1c2UtY2lyY2xlJyxcbiAgICAncGF5LWNpcmNsZScsXG4gICAgJ3Bob25lJyxcbiAgICAncGljdHVyZScsXG4gICAgJ3BpZS1jaGFydCcsXG4gICAgJ3BsYXktY2lyY2xlJyxcbiAgICAncGxheS1zcXVhcmUnLFxuICAgICdwbHVzLWNpcmNsZScsXG4gICAgJ3BsdXMtc3F1YXJlJyxcbiAgICAncG91bmQtY2lyY2xlJyxcbiAgICAncHJpbnRlcicsXG4gICAgJ3Byb2ZpbGUnLFxuICAgICdwcm9qZWN0JyxcbiAgICAncHJvcGVydHktc2FmZXR5JyxcbiAgICAncHVzaHBpbicsXG4gICAgJ3FxLWNpcmNsZScsXG4gICAgJ3FxLXNxdWFyZScsXG4gICAgJ3F1ZXN0aW9uLWNpcmNsZScsXG4gICAgJ3JlYWQnLFxuICAgICdyZWNvbmNpbGlhdGlvbicsXG4gICAgJ3JlZC1lbnZlbG9wZScsXG4gICAgJ3JlZGRpdC1jaXJjbGUnLFxuICAgICdyZWRkaXQtc3F1YXJlJyxcbiAgICAncmVzdCcsXG4gICAgJ3JpZ2h0LWNpcmNsZScsXG4gICAgJ3JpZ2h0LXNxdWFyZScsXG4gICAgJ3JvY2tldCcsXG4gICAgJ3NhZmV0eS1jZXJ0aWZpY2F0ZScsXG4gICAgJ3NhdmUnLFxuICAgICdzY2hlZHVsZScsXG4gICAgJ3NlY3VyaXR5LXNjYW4nLFxuICAgICdzZXR0aW5nJyxcbiAgICAnc2hvcCcsXG4gICAgJ3Nob3BwaW5nJyxcbiAgICAnc2tldGNoLWNpcmNsZScsXG4gICAgJ3NrZXRjaC1zcXVhcmUnLFxuICAgICdza2luJyxcbiAgICAnc2t5cGUnLFxuICAgICdzbGFjay1jaXJjbGUnLFxuICAgICdzbGFjay1zcXVhcmUnLFxuICAgICdzbGlkZXJzJyxcbiAgICAnc21pbGUnLFxuICAgICdzbmlwcGV0cycsXG4gICAgJ3NvdW5kJyxcbiAgICAnc3RhcicsXG4gICAgJ3N0ZXAtYmFja3dhcmQnLFxuICAgICdzdGVwLWZvcndhcmQnLFxuICAgICdzdG9wJyxcbiAgICAnc3dpdGNoZXInLFxuICAgICd0YWJsZXQnLFxuICAgICd0YWcnLFxuICAgICd0YWdzJyxcbiAgICAndGFvYmFvLWNpcmNsZScsXG4gICAgJ3Rhb2Jhby1zcXVhcmUnLFxuICAgICd0aHVuZGVyYm9sdCcsXG4gICAgJ3Rvb2wnLFxuICAgICd0cmFkZW1hcmstY2lyY2xlJyxcbiAgICAndHJvcGh5JyxcbiAgICAndHdpdHRlci1jaXJjbGUnLFxuICAgICd0d2l0dGVyLXNxdWFyZScsXG4gICAgJ3VubG9jaycsXG4gICAgJ3VwLWNpcmNsZScsXG4gICAgJ3VwLXNxdWFyZScsXG4gICAgJ3VzYicsXG4gICAgJ3ZpZGVvLWNhbWVyYScsXG4gICAgJ3dhbGxldCcsXG4gICAgJ3dhcm5pbmcnLFxuICAgICd3ZWNoYXQnLFxuICAgICd3ZWliby1jaXJjbGUnLFxuICAgICd3ZWliby1zcXVhcmUnLFxuICAgICd3aW5kb3dzJyxcbiAgICAneWFob28nLFxuICAgICd5b3V0dWJlJyxcbiAgICAneXVxdWUnLFxuICAgICd6aGlodS1jaXJjbGUnLFxuICAgICd6aGlodS1zcXVhcmUnXG4gIF0sXG4gIG91dGxpbmU6IFtcbiAgICAnYWNjb3VudC1ib29rJyxcbiAgICAnYWxlcnQnLFxuICAgICdhbGlwYXktY2lyY2xlJyxcbiAgICAnYWxpd2FuZ3dhbmcnLFxuICAgICdhbmRyb2lkJyxcbiAgICAnYXBpJyxcbiAgICAnYXBwbGUnLFxuICAgICdhcHBzdG9yZScsXG4gICAgJ2F1ZGlvJyxcbiAgICAnYmFja3dhcmQnLFxuICAgICdiYW5rJyxcbiAgICAnYmVoYW5jZS1zcXVhcmUnLFxuICAgICdiZWxsJyxcbiAgICAnYm9vaycsXG4gICAgJ2JveC1wbG90JyxcbiAgICAnYnVpbGQnLFxuICAgICdidWxiJyxcbiAgICAnY2FsY3VsYXRvcicsXG4gICAgJ2NhbGVuZGFyJyxcbiAgICAnY2FtZXJhJyxcbiAgICAnY2FyJyxcbiAgICAnY2FyZXQtZG93bicsXG4gICAgJ2NhcmV0LWxlZnQnLFxuICAgICdjYXJldC1yaWdodCcsXG4gICAgJ2NhcnJ5LW91dCcsXG4gICAgJ2NoZWNrLWNpcmNsZScsXG4gICAgJ2NhcmV0LXVwJyxcbiAgICAnY2hlY2stc3F1YXJlJyxcbiAgICAnY2hyb21lJyxcbiAgICAnY2xvY2stY2lyY2xlJyxcbiAgICAnY2xvc2UtY2lyY2xlJyxcbiAgICAnY2xvc2Utc3F1YXJlJyxcbiAgICAnY2xvdWQnLFxuICAgICdjb2RlJyxcbiAgICAnY29kZXBlbi1jaXJjbGUnLFxuICAgICdjb21wYXNzJyxcbiAgICAnY29udGFjdHMnLFxuICAgICdjb250YWluZXInLFxuICAgICdjb250cm9sJyxcbiAgICAnY29weScsXG4gICAgJ2NyZWRpdC1jYXJkJyxcbiAgICAnY3Jvd24nLFxuICAgICdjdXN0b21lci1zZXJ2aWNlJyxcbiAgICAnZGFzaGJvYXJkJyxcbiAgICAnZGF0YWJhc2UnLFxuICAgICdkZWxldGUnLFxuICAgICdkaWZmJyxcbiAgICAnZGlzbGlrZScsXG4gICAgJ2Rvd24tY2lyY2xlJyxcbiAgICAnZG93bi1zcXVhcmUnLFxuICAgICdkcmliYmJsZS1zcXVhcmUnLFxuICAgICdlZGl0JyxcbiAgICAnZW52aXJvbm1lbnQnLFxuICAgICdleGNsYW1hdGlvbi1jaXJjbGUnLFxuICAgICdleHBlcmltZW50JyxcbiAgICAnZXllLWludmlzaWJsZScsXG4gICAgJ2V5ZScsXG4gICAgJ2ZhY2Vib29rJyxcbiAgICAnZmFzdC1iYWNrd2FyZCcsXG4gICAgJ2Zhc3QtZm9yd2FyZCcsXG4gICAgJ2ZpbGUtYWRkJyxcbiAgICAnZmlsZS1leGNlbCcsXG4gICAgJ2ZpbGUtZXhjbGFtYXRpb24nLFxuICAgICdmaWxlLWltYWdlJyxcbiAgICAnZmlsZS1tYXJrZG93bicsXG4gICAgJ2ZpbGUtcGRmJyxcbiAgICAnZmlsZS1wcHQnLFxuICAgICdmaWxlLXRleHQnLFxuICAgICdmaWxlLXVua25vd24nLFxuICAgICdmaWxlLXdvcmQnLFxuICAgICdmaWxlLXppcCcsXG4gICAgJ2ZpbGUnLFxuICAgICdmaWx0ZXInLFxuICAgICdmaXJlJyxcbiAgICAnZmxhZycsXG4gICAgJ2ZvbGRlci1hZGQnLFxuICAgICdmb2xkZXItb3BlbicsXG4gICAgJ2ZvbGRlcicsXG4gICAgJ2ZvcndhcmQnLFxuICAgICdmcm93bicsXG4gICAgJ2Z1bmQnLFxuICAgICdmdW5uZWwtcGxvdCcsXG4gICAgJ2dpZnQnLFxuICAgICdnaXRodWInLFxuICAgICdnaXRsYWInLFxuICAgICdoZGQnLFxuICAgICdoZWFydCcsXG4gICAgJ2hpZ2hsaWdodCcsXG4gICAgJ2hvbWUnLFxuICAgICdob3VyZ2xhc3MnLFxuICAgICdodG1sNScsXG4gICAgJ2lkY2FyZCcsXG4gICAgJ2luZm8tY2lyY2xlJyxcbiAgICAnaW5zdGFncmFtJyxcbiAgICAnaW5zdXJhbmNlJyxcbiAgICAnaW50ZXJhdGlvbicsXG4gICAgJ2xheW91dCcsXG4gICAgJ2xlZnQtY2lyY2xlJyxcbiAgICAnbGVmdC1zcXVhcmUnLFxuICAgICdsaWtlJyxcbiAgICAnbGlua2VkaW4nLFxuICAgICdsb2NrJyxcbiAgICAnbWFpbCcsXG4gICAgJ21lZGljaW5lLWJveCcsXG4gICAgJ21lc3NhZ2UnLFxuICAgICdtaW51cy1jaXJjbGUnLFxuICAgICdtZWgnLFxuICAgICdtaW51cy1zcXVhcmUnLFxuICAgICdtb2JpbGUnLFxuICAgICdub3RpZmljYXRpb24nLFxuICAgICdtb25leS1jb2xsZWN0JyxcbiAgICAncGF1c2UtY2lyY2xlJyxcbiAgICAncGF5LWNpcmNsZScsXG4gICAgJ3Bob25lJyxcbiAgICAncGljdHVyZScsXG4gICAgJ3BpZS1jaGFydCcsXG4gICAgJ3BsYXktY2lyY2xlJyxcbiAgICAncGxheS1zcXVhcmUnLFxuICAgICdwbHVzLWNpcmNsZScsXG4gICAgJ3BsdXMtc3F1YXJlJyxcbiAgICAncHJpbnRlcicsXG4gICAgJ3Byb2ZpbGUnLFxuICAgICdwcm9qZWN0JyxcbiAgICAncHJvcGVydHktc2FmZXR5JyxcbiAgICAncHVzaHBpbicsXG4gICAgJ3F1ZXN0aW9uLWNpcmNsZScsXG4gICAgJ3JlYWQnLFxuICAgICdyZWNvbmNpbGlhdGlvbicsXG4gICAgJ3JlZC1lbnZlbG9wZScsXG4gICAgJ3Jlc3QnLFxuICAgICdyaWdodC1jaXJjbGUnLFxuICAgICdyaWdodC1zcXVhcmUnLFxuICAgICdyb2NrZXQnLFxuICAgICdzYWZldHktY2VydGlmaWNhdGUnLFxuICAgICdzYXZlJyxcbiAgICAnc2NoZWR1bGUnLFxuICAgICdzZWN1cml0eS1zY2FuJyxcbiAgICAnc2V0dGluZycsXG4gICAgJ3Nob3AnLFxuICAgICdzaG9wcGluZycsXG4gICAgJ3NraW4nLFxuICAgICdza3lwZScsXG4gICAgJ3NsYWNrLXNxdWFyZScsXG4gICAgJ3NsaWRlcnMnLFxuICAgICdzbWlsZScsXG4gICAgJ3NuaXBwZXRzJyxcbiAgICAnc291bmQnLFxuICAgICdzdGFyJyxcbiAgICAnc3RlcC1iYWNrd2FyZCcsXG4gICAgJ3N0ZXAtZm9yd2FyZCcsXG4gICAgJ3N0b3AnLFxuICAgICdzd2l0Y2hlcicsXG4gICAgJ3RhYmxldCcsXG4gICAgJ3RhZycsXG4gICAgJ3RhZ3MnLFxuICAgICd0YW9iYW8tY2lyY2xlJyxcbiAgICAndGh1bmRlcmJvbHQnLFxuICAgICd0b29sJyxcbiAgICAndHJvcGh5JyxcbiAgICAndW5sb2NrJyxcbiAgICAndXAtY2lyY2xlJyxcbiAgICAndXAtc3F1YXJlJyxcbiAgICAndXNiJyxcbiAgICAndmlkZW8tY2FtZXJhJyxcbiAgICAnd2FsbGV0JyxcbiAgICAnd2FybmluZycsXG4gICAgJ3dlY2hhdCcsXG4gICAgJ3dlaWJvLWNpcmNsZScsXG4gICAgJ3dlaWJvLXNxdWFyZScsXG4gICAgJ3dpbmRvd3MnLFxuICAgICd5YWhvbycsXG4gICAgJ3lvdXR1YmUnLFxuICAgICd5dXF1ZScsXG4gICAgJ2FsaWJhYmEnLFxuICAgICdhbGlnbi1sZWZ0JyxcbiAgICAnYWxpZ24tcmlnaHQnLFxuICAgICdhbGlwYXknLFxuICAgICdhbGl5dW4nLFxuICAgICdhbWF6b24nLFxuICAgICdhbnQtY2xvdWQnLFxuICAgICdhbnQtZGVzaWduJyxcbiAgICAnYXBhcnRtZW50JyxcbiAgICAnYXJlYS1jaGFydCcsXG4gICAgJ2Fycm93LWRvd24nLFxuICAgICdhcnJvdy1sZWZ0JyxcbiAgICAnYXJyb3ctcmlnaHQnLFxuICAgICdhcnJvdy11cCcsXG4gICAgJ2Fycm93cy1hbHQnLFxuICAgICdhdWRpdCcsXG4gICAgJ2FsaWduLWNlbnRlcicsXG4gICAgJ2JhcmNvZGUnLFxuICAgICdiYXItY2hhcnQnLFxuICAgICdiYXJzJyxcbiAgICAnYmVoYW5jZScsXG4gICAgJ2JnLWNvbG9ycycsXG4gICAgJ2Jsb2NrJyxcbiAgICAnYm9sZCcsXG4gICAgJ2JvcmRlci1ib3R0b20nLFxuICAgICdib3JkZXItaG9yaXpvbnRhbCcsXG4gICAgJ2JvcmRlci1pbm5lcicsXG4gICAgJ2JvcmRlci1sZWZ0JyxcbiAgICAnYm9yZGVyLW91dGVyJyxcbiAgICAnYm9yZGVyLXJpZ2h0JyxcbiAgICAnYm9yZGVyLXRvcCcsXG4gICAgJ2JvcmRlci12ZXJ0aWNsZScsXG4gICAgJ2JvcmRlcicsXG4gICAgJ2JyYW5jaGVzJyxcbiAgICAnY2hlY2snLFxuICAgICdjaScsXG4gICAgJ2Nsb3NlJyxcbiAgICAnY2xvdWQtZG93bmxvYWQnLFxuICAgICdjbG91ZC1zZXJ2ZXInLFxuICAgICdjbG91ZC1zeW5jJyxcbiAgICAnY2xvdWQtdXBsb2FkJyxcbiAgICAnY2x1c3RlcicsXG4gICAgJ2NvZGUtc2FuZGJveCcsXG4gICAgJ2NvZGVwZW4nLFxuICAgICdjb2ZmZWUnLFxuICAgICdjb2x1bS1oZWlnaHQnLFxuICAgICdjb2x1bW4td2lkdGgnLFxuICAgICdjb3B5cmlnaHQnLFxuICAgICdkYXNoJyxcbiAgICAnZGVwbG95bWVudC11bml0JyxcbiAgICAnZGVza3RvcCcsXG4gICAgJ2RpbmdkaW5nJyxcbiAgICAnZGlzY29ubmVjdCcsXG4gICAgJ2RvbGxhcicsXG4gICAgJ2RvdC1jaGFydCcsXG4gICAgJ2RvdWJsZS1yaWdodCcsXG4gICAgJ2RvdWJsZS1sZWZ0JyxcbiAgICAnZG93bicsXG4gICAgJ2Rvd25sb2FkJyxcbiAgICAnZHJhZycsXG4gICAgJ2RyaWJiYmxlJyxcbiAgICAnZHJvcGJveCcsXG4gICAgJ2VsbGlwc2lzJyxcbiAgICAnZW50ZXInLFxuICAgICdldXJvJyxcbiAgICAnZXhjZXB0aW9uJyxcbiAgICAnZXhjbGFtYXRpb24nLFxuICAgICdleHBvcnQnLFxuICAgICdmYWxsJyxcbiAgICAnZmlsZS1kb25lJyxcbiAgICAnZmlsZS1qcGcnLFxuICAgICdmaWxlLXByb3RlY3QnLFxuICAgICdmaWxlLXNlYXJjaCcsXG4gICAgJ2ZpbGUtc3luYycsXG4gICAgJ2ZvbnQtY29sb3JzJyxcbiAgICAnZm9udC1zaXplJyxcbiAgICAnZm9yaycsXG4gICAgJ2Zvcm0nLFxuICAgICdmdWxsc2NyZWVuLWV4aXQnLFxuICAgICdmdWxsc2NyZWVuJyxcbiAgICAnZ2F0ZXdheScsXG4gICAgJ2dsb2JhbCcsXG4gICAgJ2dvbGQnLFxuICAgICdnb29nbGUtcGx1cycsXG4gICAgJ2dvb2dsZScsXG4gICAgJ2hlYXQtbWFwJyxcbiAgICAnaWUnLFxuICAgICdpbXBvcnQnLFxuICAgICdpbmJveCcsXG4gICAgJ2luZm8nLFxuICAgICdpc3N1ZXMtY2xvc2UnLFxuICAgICdpdGFsaWMnLFxuICAgICdrZXknLFxuICAgICdsYXB0b3AnLFxuICAgICdsZWZ0JyxcbiAgICAnbGluZS1jaGFydCcsXG4gICAgJ2xpbmUtaGVpZ2h0JyxcbiAgICAnbGluZScsXG4gICAgJ2xpbmsnLFxuICAgICdsb2FkaW5nLTMtcXVhcnRlcnMnLFxuICAgICdsb2FkaW5nJyxcbiAgICAnbG9naW4nLFxuICAgICdsb2dvdXQnLFxuICAgICdtYW4nLFxuICAgICdtZWRpdW0td29ya21hcmsnLFxuICAgICdtZWRpdW0nLFxuICAgICdtZW51LWZvbGQnLFxuICAgICdtZW51LXVuZm9sZCcsXG4gICAgJ21lbnUnLFxuICAgICdtaW51cycsXG4gICAgJ21vbml0b3InLFxuICAgICdtcicsXG4gICAgJ251bWJlcicsXG4gICAgJ29yZGVyZWQtbGlzdCcsXG4gICAgJ3BhcGVyLWNsaXAnLFxuICAgICdwYXVzZScsXG4gICAgJ3BlcmNlbnRhZ2UnLFxuICAgICdwaWMtY2VudGVyJyxcbiAgICAncGljLWxlZnQnLFxuICAgICdwaWMtcmlnaHQnLFxuICAgICdwbHVzJyxcbiAgICAncG91bmQnLFxuICAgICdwb3dlcm9mZicsXG4gICAgJ3FxJyxcbiAgICAncXJjb2RlJyxcbiAgICAncXVlc3Rpb24nLFxuICAgICdyYWRhci1jaGFydCcsXG4gICAgJ3JhZGl1cy1ib3R0b21sZWZ0JyxcbiAgICAncmFkaXVzLWJvdHRvbXJpZ2h0JyxcbiAgICAncmFkaXVzLXNldHRpbmcnLFxuICAgICdyYWRpdXMtdXBsZWZ0JyxcbiAgICAncmFkaXVzLXVwcmlnaHQnLFxuICAgICdyZWRkaXQnLFxuICAgICdyZWRvJyxcbiAgICAncmVsb2FkJyxcbiAgICAncmVsb2FkLXRpbWUnLFxuICAgICdyZXR3ZWV0JyxcbiAgICAncmlnaHQnLFxuICAgICdyaXNlJyxcbiAgICAncm9ib3QnLFxuICAgICdyb2xsYmFjaycsXG4gICAgJ3NhZmV0eScsXG4gICAgJ3NjYW4nLFxuICAgICdzY2lzc29yJyxcbiAgICAnc2VhcmNoJyxcbiAgICAnc2VsZWN0JyxcbiAgICAnc2hha2UnLFxuICAgICdzaGFyZS1hbHQnLFxuICAgICdzaG9wcGluZy1jYXJ0JyxcbiAgICAnc2hyaW5rJyxcbiAgICAnc2tldGNoJyxcbiAgICAnc2xhY2snLFxuICAgICdzbWFsbC1kYXNoJyxcbiAgICAnc29sdXRpb24nLFxuICAgICdzb3J0LWFzY2VuZGluZycsXG4gICAgJ3NvcnQtZGVzY2VuZGluZycsXG4gICAgJ3N0b2NrJyxcbiAgICAnc3RyaWtldGhyb3VnaCcsXG4gICAgJ3N3YXAtbGVmdCcsXG4gICAgJ3N3YXAtcmlnaHQnLFxuICAgICdzd2FwJyxcbiAgICAnc3luYycsXG4gICAgJ3RhYmxlJyxcbiAgICAndGFvYmFvJyxcbiAgICAndGVhbScsXG4gICAgJ3RvLXRvcCcsXG4gICAgJ3RyYWRlbWFyaycsXG4gICAgJ3RyYW5zYWN0aW9uJyxcbiAgICAndHdpdHRlcicsXG4gICAgJ3VuZGVybGluZScsXG4gICAgJ3VuZG8nLFxuICAgICd1bm9yZGVyZWQtbGlzdCcsXG4gICAgJ3VwJyxcbiAgICAndXBsb2FkJyxcbiAgICAndXNlci1hZGQnLFxuICAgICd1c2VyLWRlbGV0ZScsXG4gICAgJ3VzZXInLFxuICAgICd1c2VyZ3JvdXAtYWRkJyxcbiAgICAndXNlcmdyb3VwLWRlbGV0ZScsXG4gICAgJ3ZlcnRpY2FsLWFsaWduLWJvdHRvbScsXG4gICAgJ3ZlcnRpY2FsLWFsaWduLW1pZGRsZScsXG4gICAgJ3ZlcnRpY2FsLWFsaWduLXRvcCcsXG4gICAgJ3ZlcnRpY2FsLWxlZnQnLFxuICAgICd2ZXJ0aWNhbC1yaWdodCcsXG4gICAgJ3dlaWJvJyxcbiAgICAnd2lmaScsXG4gICAgJ3dvbWFuJyxcbiAgICAnemhpaHUnLFxuICAgICd6b29tLWluJyxcbiAgICAnem9vbS1vdXQnXG4gIF0sXG4gIHR3b3RvbmU6IFtcbiAgICAnYWNjb3VudC1ib29rJyxcbiAgICAnYWxlcnQnLFxuICAgICdhcGknLFxuICAgICdhcHBzdG9yZScsXG4gICAgJ2F1ZGlvJyxcbiAgICAnYmFuaycsXG4gICAgJ2JlbGwnLFxuICAgICdib29rJyxcbiAgICAnYm94LXBsb3QnLFxuICAgICdidWlsZCcsXG4gICAgJ2J1bGInLFxuICAgICdjYWxjdWxhdG9yJyxcbiAgICAnY2FtZXJhJyxcbiAgICAnY2FyJyxcbiAgICAnY2Fycnktb3V0JyxcbiAgICAnY2hlY2stY2lyY2xlJyxcbiAgICAnY2hlY2stc3F1YXJlJyxcbiAgICAnY2xvY2stY2lyY2xlJyxcbiAgICAnY2xvc2UtY2lyY2xlJyxcbiAgICAnY2xvc2Utc3F1YXJlJyxcbiAgICAnY2xvdWQnLFxuICAgICdjb2RlJyxcbiAgICAnY29tcGFzcycsXG4gICAgJ2NvbnRhY3RzJyxcbiAgICAnY29udGFpbmVyJyxcbiAgICAnY29udHJvbCcsXG4gICAgJ2NvcHknLFxuICAgICdjcmVkaXQtY2FyZCcsXG4gICAgJ2Nyb3duJyxcbiAgICAnY3VzdG9tZXItc2VydmljZScsXG4gICAgJ2Rhc2hib2FyZCcsXG4gICAgJ2RhdGFiYXNlJyxcbiAgICAnZGVsZXRlJyxcbiAgICAnZGlmZicsXG4gICAgJ2Rpc2xpa2UnLFxuICAgICdkb3duLWNpcmNsZScsXG4gICAgJ2Rvd24tc3F1YXJlJyxcbiAgICAnZWRpdCcsXG4gICAgJ2Vudmlyb25tZW50JyxcbiAgICAnZXhjbGFtYXRpb24tY2lyY2xlJyxcbiAgICAnZXhwZXJpbWVudCcsXG4gICAgJ2V5ZS1pbnZpc2libGUnLFxuICAgICdleWUnLFxuICAgICdmaWxlLWFkZCcsXG4gICAgJ2ZpbGUtZXhjZWwnLFxuICAgICdmaWxlLWV4Y2xhbWF0aW9uJyxcbiAgICAnZmlsZS1pbWFnZScsXG4gICAgJ2ZpbGUtbWFya2Rvd24nLFxuICAgICdmaWxlLXBkZicsXG4gICAgJ2ZpbGUtcHB0JyxcbiAgICAnZmlsZS10ZXh0JyxcbiAgICAnZmlsZS11bmtub3duJyxcbiAgICAnZmlsZS13b3JkJyxcbiAgICAnZmlsZS16aXAnLFxuICAgICdmaWxlJyxcbiAgICAnZmlsdGVyJyxcbiAgICAnZmlyZScsXG4gICAgJ2ZsYWcnLFxuICAgICdmb2xkZXItYWRkJyxcbiAgICAnZm9sZGVyLW9wZW4nLFxuICAgICdmb2xkZXInLFxuICAgICdmcm93bicsXG4gICAgJ2Z1bmQnLFxuICAgICdmdW5uZWwtcGxvdCcsXG4gICAgJ2dpZnQnLFxuICAgICdoZGQnLFxuICAgICdoZWFydCcsXG4gICAgJ2hpZ2hsaWdodCcsXG4gICAgJ2hvbWUnLFxuICAgICdob3VyZ2xhc3MnLFxuICAgICdodG1sNScsXG4gICAgJ2lkY2FyZCcsXG4gICAgJ2luZm8tY2lyY2xlJyxcbiAgICAnaW5zdXJhbmNlJyxcbiAgICAnaW50ZXJhdGlvbicsXG4gICAgJ2xheW91dCcsXG4gICAgJ2xlZnQtY2lyY2xlJyxcbiAgICAnbGVmdC1zcXVhcmUnLFxuICAgICdsaWtlJyxcbiAgICAnbG9jaycsXG4gICAgJ21haWwnLFxuICAgICdtZWRpY2luZS1ib3gnLFxuICAgICdtZXNzYWdlJyxcbiAgICAnbWludXMtY2lyY2xlJyxcbiAgICAnbWVoJyxcbiAgICAnbWludXMtc3F1YXJlJyxcbiAgICAnbW9iaWxlJyxcbiAgICAnbm90aWZpY2F0aW9uJyxcbiAgICAnbW9uZXktY29sbGVjdCcsXG4gICAgJ3BhdXNlLWNpcmNsZScsXG4gICAgJ3Bob25lJyxcbiAgICAncGljdHVyZScsXG4gICAgJ3BpZS1jaGFydCcsXG4gICAgJ3BsYXktY2lyY2xlJyxcbiAgICAncGxheS1zcXVhcmUnLFxuICAgICdwbHVzLWNpcmNsZScsXG4gICAgJ3BsdXMtc3F1YXJlJyxcbiAgICAncG91bmQtY2lyY2xlJyxcbiAgICAncHJpbnRlcicsXG4gICAgJ3Byb2ZpbGUnLFxuICAgICdwcm9qZWN0JyxcbiAgICAncHJvcGVydHktc2FmZXR5JyxcbiAgICAncHVzaHBpbicsXG4gICAgJ3F1ZXN0aW9uLWNpcmNsZScsXG4gICAgJ3JlY29uY2lsaWF0aW9uJyxcbiAgICAncmVkLWVudmVsb3BlJyxcbiAgICAncmVzdCcsXG4gICAgJ3JpZ2h0LWNpcmNsZScsXG4gICAgJ3JpZ2h0LXNxdWFyZScsXG4gICAgJ3JvY2tldCcsXG4gICAgJ3NhZmV0eS1jZXJ0aWZpY2F0ZScsXG4gICAgJ3NhdmUnLFxuICAgICdzY2hlZHVsZScsXG4gICAgJ3NlY3VyaXR5LXNjYW4nLFxuICAgICdzZXR0aW5nJyxcbiAgICAnc2hvcCcsXG4gICAgJ3Nob3BwaW5nJyxcbiAgICAnc2tpbicsXG4gICAgJ3NsaWRlcnMnLFxuICAgICdzbWlsZScsXG4gICAgJ3NuaXBwZXRzJyxcbiAgICAnc291bmQnLFxuICAgICdzdGFyJyxcbiAgICAnc3RvcCcsXG4gICAgJ3N3aXRjaGVyJyxcbiAgICAndGFibGV0JyxcbiAgICAndGFnJyxcbiAgICAndGFncycsXG4gICAgJ3RodW5kZXJib2x0JyxcbiAgICAndG9vbCcsXG4gICAgJ3RyYWRlbWFyay1jaXJjbGUnLFxuICAgICd0cm9waHknLFxuICAgICd1bmxvY2snLFxuICAgICd1cC1jaXJjbGUnLFxuICAgICd1cC1zcXVhcmUnLFxuICAgICd1c2InLFxuICAgICd2aWRlby1jYW1lcmEnLFxuICAgICd3YWxsZXQnLFxuICAgICd3YXJuaW5nJyxcbiAgICAnY2knLFxuICAgICdjb3B5cmlnaHQnLFxuICAgICdkb2xsYXInLFxuICAgICdldXJvJyxcbiAgICAnZ29sZCcsXG4gICAgJ2NhbmxlbmRhcidcbiAgXVxufTtcbiJdfQ== |
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
import sys
import argparse
def main(args):
name = args.name
n = args.n
inp = args.inp
file = f"../GB_projects/{name}/thermo_output/{inp}.txt"
print(file)
df = pd.read_csv(file, sep=';', comment='#', names=['t','T', 'pe'])
t = df['t']
pe = df['pe']
T = df['T']
def rolling_mean(numbers_series, window_size):
windows = numbers_series.rolling(window_size)
moving_averages = windows.mean()
moving_averages_list = moving_averages.tolist()
final_list = moving_averages_list[window_size - 1:]
return final_list
pe1 = rolling_mean(pe, n)
t1 = t[len(pe)-len(pe1):]
t = np.array(t)
f, (ax1, ax3) = plt.subplots(2, 2)
ax1.plot(t, pe)
ax1.set_xlabel('$t, ps$')
ax1.set_ylabel('$E_{pot}, eV$')
ax3.plot(t1, pe1)
ax3.set_xlabel('$t, ps$')
ax3.set_ylabel('$<E_{pot}>_{roll}, eV$')
ax3.set_title(f'rolling mean over {n}')
f.suptitle(f"{inp.replace('_', ' ')} {name} {round(t[-1])}ps")
f.tight_layout()
plt.savefig(f'../GB_projects/{name}/images/plot.{inp}_time{round(t[-1])}.png')
plt.show()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--name", required=True, help='for example STGB_210')
parser.add_argument("-n", required=True, type=int)
parser.add_argument("--inp", required=True)
args = parser.parse_args()
main(args) |
const Discord = require('discord.js');
const weather = require('weather-js');
exports.run = (client, message, args) => {
weather.find({search: args.join(" "), degreeType: 'C'}, function(err, result) {
if (err) message.channel.send(err);
if (result === undefined || result.length === 0) {
message.channel.send(new Discord.MessageEmbed().setDescription('Lütfen bir yer gir.').setColor('RANDOM'));
return;
}
var current = result[0].current;
var location = result[0].location;
const embed = new Discord.MessageEmbed()
.setDescription(`**${current.skytext}**`)
.setAuthor(`${current.observationpoint} için hava durumu`)
.setThumbnail(current.imageUrl)
.setColor(0x00AE86)
.addField('Zaman Dilimi',`UTC${location.timezone}`, true)
.addField('Derece Türü',location.degreetype, true)
.addField('Sıcaklık',`${current.temperature} Derece`, true)
.addField('Hava', `${current.feelslike}`, true)
.addField('Rüzgar',current.winddisplay, true)
.addField('Nem', `${current.humidity}%`, true)
message.channel.send({embed});
})
}
exports.conf = {
enabled: true,
guildOnly: false,
aliases: ['havadurum', 'hava'],
permLevel: "0"
}; |
import inspect
import logging
import hashlib
from data.database import DerivedStorageForImage, TagManifest, Manifest, Image
from data.registry_model.registry_oci_model import back_compat_oci_model, oci_model
from data.registry_model.registry_pre_oci_model import pre_oci_model
from data.registry_model.datatypes import LegacyImage, Manifest as ManifestDataType
logger = logging.getLogger(__name__)
class SplitModel(object):
def __init__(
self, oci_model_proportion, oci_namespace_whitelist, v22_namespace_whitelist, oci_only_mode
):
self.v22_namespace_whitelist = set(v22_namespace_whitelist)
self.oci_namespace_whitelist = set(oci_namespace_whitelist)
self.oci_namespace_whitelist.update(v22_namespace_whitelist)
self.oci_model_proportion = oci_model_proportion
self.oci_only_mode = oci_only_mode
def supports_schema2(self, namespace_name):
""" Returns whether the implementation of the data interface supports schema 2 format
manifests. """
return namespace_name in self.v22_namespace_whitelist
def _namespace_from_kwargs(self, args_dict):
if "namespace_name" in args_dict:
return args_dict["namespace_name"]
if "repository_ref" in args_dict:
return args_dict["repository_ref"].namespace_name
if "tag" in args_dict:
return args_dict["tag"].repository.namespace_name
if "manifest" in args_dict:
manifest = args_dict["manifest"]
if manifest._is_tag_manifest:
return TagManifest.get(id=manifest._db_id).tag.repository.namespace_user.username
else:
return Manifest.get(id=manifest._db_id).repository.namespace_user.username
if "manifest_or_legacy_image" in args_dict:
manifest_or_legacy_image = args_dict["manifest_or_legacy_image"]
if isinstance(manifest_or_legacy_image, LegacyImage):
return Image.get(
id=manifest_or_legacy_image._db_id
).repository.namespace_user.username
else:
manifest = manifest_or_legacy_image
if manifest._is_tag_manifest:
return TagManifest.get(
id=manifest._db_id
).tag.repository.namespace_user.username
else:
return Manifest.get(id=manifest._db_id).repository.namespace_user.username
if "derived_image" in args_dict:
return DerivedStorageForImage.get(
id=args_dict["derived_image"]._db_id
).source_image.repository.namespace_user.username
if "blob" in args_dict:
return "" # Blob functions are shared, so no need to do anything.
if "blob_upload" in args_dict:
return "" # Blob functions are shared, so no need to do anything.
raise Exception("Unknown namespace for dict `%s`" % args_dict)
def __getattr__(self, attr):
def method(*args, **kwargs):
if self.oci_model_proportion >= 1.0:
if self.oci_only_mode:
logger.debug(
"Calling method `%s` under full OCI data model for all namespaces", attr
)
return getattr(oci_model, attr)(*args, **kwargs)
else:
logger.debug(
"Calling method `%s` under compat OCI data model for all namespaces", attr
)
return getattr(back_compat_oci_model, attr)(*args, **kwargs)
argnames = inspect.getargspec(getattr(back_compat_oci_model, attr))[0]
if not argnames and isinstance(args[0], ManifestDataType):
args_dict = dict(manifest=args[0])
else:
args_dict = {argnames[index + 1]: value for index, value in enumerate(args)}
if attr in [
"yield_tags_for_vulnerability_notification",
"get_most_recent_tag_lifetime_start",
]:
use_oci = self.oci_model_proportion >= 1.0
namespace_name = "(implicit for " + attr + ")"
else:
namespace_name = self._namespace_from_kwargs(args_dict)
use_oci = namespace_name in self.oci_namespace_whitelist
if not use_oci and self.oci_model_proportion:
# Hash the namespace name and see if it falls into the proportion bucket.
bucket = int(hashlib.md5(namespace_name).hexdigest(), 16) % 100
if bucket <= int(self.oci_model_proportion * 100):
logger.debug(
"Enabling OCI for namespace `%s` in proportional bucket", namespace_name
)
use_oci = True
if use_oci:
logger.debug(
"Calling method `%s` under OCI data model for namespace `%s`",
attr,
namespace_name,
)
return getattr(back_compat_oci_model, attr)(*args, **kwargs)
else:
return getattr(pre_oci_model, attr)(*args, **kwargs)
return method
|
import os
if '{{ cookiecutter.license|lower }}' != 'bsd':
os.remove('./LICENSE')
|
import test from 'ava';
import request from 'supertest';
import app from '../../server';
import Post from '../post';
import { connectDB, dropDB } from '../../util/test-helpers';
// Initial posts added into test db
const posts = [
new Post({ name: 'Prashant', title: 'Hello Mern', slug: 'hello-mern', cuid: 'f34gb2bh24b24b2', content: "All cats meow 'mern!'" }),
new Post({ name: 'Mayank', title: 'Hi Mern', slug: 'hi-mern', cuid: 'f34gb2bh24b24b3', content: "All dogs bark 'mern!'" }),
];
test.beforeEach('connect and add two post entries', t => {
connectDB(t, () => {
Post.create(posts, err => {
if (err) t.fail('Unable to create posts');
});
});
});
test.afterEach.always(t => {
dropDB(t);
});
test.serial('Should correctly give number of Posts', async t => {
t.plan(2);
const res = await request(app)
.get('/api/posts')
.set('Accept', 'application/json');
t.is(res.status, 200);
t.deepEqual(posts.length, res.body.posts.length);
});
test.serial('Should send correct data when queried against a cuid', async t => {
t.plan(2);
const post = new Post({ name: 'Foo', title: 'bar', slug: 'bar', cuid: 'f34gb2bh24b24b2', content: 'Hello Mern says Foo' });
post.save();
const res = await request(app)
.get('/api/posts/f34gb2bh24b24b2')
.set('Accept', 'application/json');
t.is(res.status, 200);
t.is(res.body.post.name, post.name);
});
test.serial('Should correctly add a post', async t => {
t.plan(2);
const res = await request(app)
.post('/api/posts')
.send({ post: { name: 'Foo', title: 'bar', content: 'Hello Mern says Foo' } })
.set('Accept', 'application/json');
t.is(res.status, 200);
const savedPost = await Post.findOne({ title: 'bar' }).exec();
t.is(savedPost.name, 'Foo');
});
test.serial('Should correctly delete a post', async t => {
t.plan(2);
const post = new Post({ name: 'Foo', title: 'bar', slug: 'bar', cuid: 'f34gb2bh24b24b2', content: 'Hello Mern says Foo' });
post.save();
const res = await request(app)
.delete(`/api/posts/${post.cuid}`)
.set('Accept', 'application/json');
t.is(res.status, 200);
const queriedPost = await Post.findOne({ cuid: post.cuid }).exec();
t.is(queriedPost, null);
}); |
var helper = require("../../helper");
var Manager = require("../../../src/etl/fact-total-hutang-etl-ag-manager");
var instanceManager = null;
var should = require("should");
var sqlHelper = require("../../sql-helper")
before("#00. connect db", function (done) {
Promise.all([helper, sqlHelper])
.then((result) => {
var db = result[0];
var sql = result[1];
db.getDb().then((db) => {
instanceManager = new Manager(db, {
username: "unit-test"
}, sql);
done();
})
.catch((e) => {
done(e);
});
});
});
it("#01. should success when create etl fact-total-hutang", function (done) {
instanceManager.run()
.then((a) => {
done();
})
.catch((e) => {
done(e);
});
});
it("#02. should success when transforming data for fact-total-hutang", function (done) {
var data = [{}, {}];
instanceManager.transform(data)
.then(() => {
done();
})
.catch((e) => {
done(e);
});
});
it("#03. should error when load empty data", function (done) {
instanceManager.load({})
.then(id => {
done("should error when create with empty data");
})
.catch(e => {
try {
done();
}
catch (ex) {
done(ex);
}
});
});
it("#04. should error when insert empty data", function (done) {
instanceManager.insertQuery(this.sql, "")
.then((id) => {
done("should error when create with empty data");
})
.catch((e) => {
try {
done();
}
catch (ex) {
done(ex);
}
});
});
it("#05. should success when joining URN to UPO", function (done) {
var data = [{}, {}];
instanceManager.joinUnitPaymentOrder(data)
.then(() => {
done();
})
.catch((e) => {
done(e);
});
});
|
const Discord = require("discord.js")
const db = require('croxydb');
module.exports.run = async (client, message, args) => {
let karaliste = db.fetch(`ckaraliste.${message.author.id}`)
const westraben = new Discord.MessageEmbed()
.setColor("#f6ff00")
.setDescription(`<a:siren:778777832976416778> **${karaliste}** sebebiyle karalisteye alınmışsın!\nBeyaz listeye alınmak istiyorsan [BURAYA](https://discord.gg/tuG87ZadFu) gelebilirsin!`)
if(karaliste)
return message.channel.send(westraben)
if(db.fetch(`bakim`)) {
const bakim = new Discord.MessageEmbed()
.setColor("#f6ff00")
.setThumbnail(message.author.displayAvatarURL({dynamic : true}))
.setTitle('Üzgünüm Bot Bakımda')
.addField('Bot Şuan Bakımdadır Lütfen Bekleyin.','Bot Ne Durumda Yada Botla İlgili Güncelleme Ve Duyurular İçin Destek Sunucumuza Gelmeyi Unutmayınız.')
.addField('İşte Destek Sunucum',"[Destek Sunucusu](https://discord.gg/tuG87ZadFu)")
.setFooter('Üzgünüm...')
.setImage('https://lh3.googleusercontent.com/proxy/gAN4I19oqqabXd_VIiwg5or-ITh4XxJTRNJA1ot0EIHPiBpxC74Atj4wNIcFes1N3VcE8WnOk6fIN29BChqNbj4lj9dIF2jiI7MBV6U8v842LA')
if(message.author.id != "477189482206986240") return message.channel.send(bakim)
}
if (!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send(`<a:siren:778777832976416778> Bu komutu kullanabilmek için "\`Yönetici\`" yetkisine sahip olmalısın.`);
let kontrol = await db.fetch(`dil_${message.guild.id}`);
if (kontrol == "spallers") {
let kanal = message.mentions.channels.first();
if (!kanal) {
const embed = new Discord.MessageEmbed()
.setColor('#f6ff00')
.setFooter(client.user.username, client.user.avatarURL())
.setDescription(`<a:siren:778777832976416778> Lütfen bir log kanalı etiketleyiniz!`);
message.channel.send(embed);
return;
}
db.set(`bank_${message.guild.id}`, kanal.id);
const embed = new Discord.MessageEmbed()
.setColor('#f6ff00')
.setFooter(client.user.username, client.user.avatarURL())
.setDescription(`<a:tmdir:778774341357797378> Ban koruma log kanalı; ${kanal} olarak ayarlandı!`);
message.channel.send(embed);
return;
} else {
let kanal = message.mentions.channels.first();
if (!kanal) {
const embed = new Discord.MessageEmbed()
.setColor('#f6ff00')
.setFooter(client.user.username, client.user.avatarURL())
.setDescription(`<a:siren:778777832976416778> Lütfen bir log kanalı etiketleyiniz!`);
message.channel.send(embed);
return;
}
db.set(`bank_${message.guild.id}`, kanal.id);
const embed = new Discord.MessageEmbed()
.setColor('#f6ff00')
.setFooter(client.user.username, client.user.avatarURL())
.setDescription(`<a:tmdir:778774341357797378> Ban koruma log kanalı; ${kanal} olarak ayarlandı!`);
message.channel.send(embed);
return;
}
};
exports.conf = {
enabled: true,
guildOnly: true,
aliases: ["ban-protection"],
permLevel: 3
};
exports.help = {
name: "ban-koruma",
description: "ban-koruma",
usage: "ban-koruma"
};
|
import React, {useEffect} from 'react';
import firebase from 'firebase';
import './RegisterLogin.css';
import CircularProgress from '@material-ui/core/CircularProgress';
import Logout from '../utils/Logout';
import ResendVerification from '../utils/ResendVerification';
import Button from '@material-ui/core/Button';
const VerifyEmail = ( {setEmailVerified} ) =>
{
useEffect(() => {
const refresher = setInterval(() => {
firebase.auth().currentUser.reload();
if (firebase.auth().currentUser.emailVerified)
setEmailVerified(true);
}, 1000);
return () => clearInterval(refresher);
}, []);
const resendVerification = () => {
ResendVerification()
.catch(console.error);
};
return (
<div className='Verify-Box'>
<h2 className='Verify-Header'>verify your email please :)</h2>
<CircularProgress />
<label>Or you could logout</label>
<Button onClick={Logout}>
Logout
</Button>
<label>If the verification link expired, click below!</label>
<Button onClick={resendVerification}>
Resend Verification
</Button>
</div>);
};
export default VerifyEmail; |
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[61],{
/***/ "./node_modules/babel-loader/lib/index.js?!./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/index.js?!./resources/js/views/users/UserProfile.vue?vue&type=script&lang=js&":
/*!*******************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/babel-loader/lib??ref--4-0!./node_modules/babel-loader/lib!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/views/users/UserProfile.vue?vue&type=script&lang=js& ***!
\*******************************************************************************************************************************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @babel/runtime/helpers/asyncToGenerator */ \"./node_modules/@babel/runtime/helpers/asyncToGenerator.js\");\n/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @babel/runtime/regenerator */ \"./node_modules/@babel/runtime/regenerator/index.js\");\n/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var _api_resource__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! @/api/resource */ \"./resources/js/api/resource.js\");\n/* harmony import */ var _components_UserBio__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./components/UserBio */ \"./resources/js/views/users/components/UserBio.vue\");\n/* harmony import */ var _components_UserCard__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./components/UserCard */ \"./resources/js/views/users/components/UserCard.vue\");\n/* harmony import */ var _components_UserActivity__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./components/UserActivity */ \"./resources/js/views/users/components/UserActivity.vue\");\n\n //\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n\n\n\n\n\nvar userResource = new _api_resource__WEBPACK_IMPORTED_MODULE_2__[\"default\"]('users');\n/* harmony default export */ __webpack_exports__[\"default\"] = ({\n name: 'EditUser',\n components: {\n UserBio: _components_UserBio__WEBPACK_IMPORTED_MODULE_3__[\"default\"],\n UserCard: _components_UserCard__WEBPACK_IMPORTED_MODULE_4__[\"default\"],\n UserActivity: _components_UserActivity__WEBPACK_IMPORTED_MODULE_5__[\"default\"]\n },\n data: function data() {\n return {\n user: {}\n };\n },\n watch: {\n '$route': 'getUser'\n },\n created: function created() {\n var id = this.$route.params && this.$route.params.id;\n var currentUserId = this.$store.getters.userId;\n\n if (id === currentUserId) {\n this.$router.push('/profile/edit');\n return;\n }\n\n this.getUser(id);\n },\n methods: {\n getUser: function getUser(id) {\n var _this = this;\n\n return _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_0___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee() {\n var _yield$userResource$g, data;\n\n return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee$(_context) {\n while (1) {\n switch (_context.prev = _context.next) {\n case 0:\n _context.next = 2;\n return userResource.get(id);\n\n case 2:\n _yield$userResource$g = _context.sent;\n data = _yield$userResource$g.data;\n _this.user = data;\n\n case 5:\n case \"end\":\n return _context.stop();\n }\n }\n }, _callee);\n }))();\n }\n }\n});//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9ub2RlX21vZHVsZXMvYmFiZWwtbG9hZGVyL2xpYi9pbmRleC5qcz8hLi9ub2RlX21vZHVsZXMvYmFiZWwtbG9hZGVyL2xpYi9pbmRleC5qcyEuL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9pbmRleC5qcz8hLi9yZXNvdXJjZXMvanMvdmlld3MvdXNlcnMvVXNlclByb2ZpbGUudnVlP3Z1ZSZ0eXBlPXNjcmlwdCZsYW5nPWpzJi5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL3Jlc291cmNlcy9qcy92aWV3cy91c2Vycy9Vc2VyUHJvZmlsZS52dWU/NWVmOCJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgX2FzeW5jVG9HZW5lcmF0b3IgZnJvbSBcIkBiYWJlbC9ydW50aW1lL2hlbHBlcnMvYXN5bmNUb0dlbmVyYXRvclwiO1xuaW1wb3J0IF9yZWdlbmVyYXRvclJ1bnRpbWUgZnJvbSBcIkBiYWJlbC9ydW50aW1lL3JlZ2VuZXJhdG9yXCI7IC8vXG4vL1xuLy9cbi8vXG4vL1xuLy9cbi8vXG4vL1xuLy9cbi8vXG4vL1xuLy9cblxuaW1wb3J0IFJlc291cmNlIGZyb20gJ0AvYXBpL3Jlc291cmNlJztcbmltcG9ydCBVc2VyQmlvIGZyb20gJy4vY29tcG9uZW50cy9Vc2VyQmlvJztcbmltcG9ydCBVc2VyQ2FyZCBmcm9tICcuL2NvbXBvbmVudHMvVXNlckNhcmQnO1xuaW1wb3J0IFVzZXJBY3Rpdml0eSBmcm9tICcuL2NvbXBvbmVudHMvVXNlckFjdGl2aXR5JztcbnZhciB1c2VyUmVzb3VyY2UgPSBuZXcgUmVzb3VyY2UoJ3VzZXJzJyk7XG5leHBvcnQgZGVmYXVsdCB7XG4gIG5hbWU6ICdFZGl0VXNlcicsXG4gIGNvbXBvbmVudHM6IHtcbiAgICBVc2VyQmlvOiBVc2VyQmlvLFxuICAgIFVzZXJDYXJkOiBVc2VyQ2FyZCxcbiAgICBVc2VyQWN0aXZpdHk6IFVzZXJBY3Rpdml0eVxuICB9LFxuICBkYXRhOiBmdW5jdGlvbiBkYXRhKCkge1xuICAgIHJldHVybiB7XG4gICAgICB1c2VyOiB7fVxuICAgIH07XG4gIH0sXG4gIHdhdGNoOiB7XG4gICAgJyRyb3V0ZSc6ICdnZXRVc2VyJ1xuICB9LFxuICBjcmVhdGVkOiBmdW5jdGlvbiBjcmVhdGVkKCkge1xuICAgIHZhciBpZCA9IHRoaXMuJHJvdXRlLnBhcmFtcyAmJiB0aGlzLiRyb3V0ZS5wYXJhbXMuaWQ7XG4gICAgdmFyIGN1cnJlbnRVc2VySWQgPSB0aGlzLiRzdG9yZS5nZXR0ZXJzLnVzZXJJZDtcblxuICAgIGlmIChpZCA9PT0gY3VycmVudFVzZXJJZCkge1xuICAgICAgdGhpcy4kcm91dGVyLnB1c2goJy9wcm9maWxlL2VkaXQnKTtcbiAgICAgIHJldHVybjtcbiAgICB9XG5cbiAgICB0aGlzLmdldFVzZXIoaWQpO1xuICB9LFxuICBtZXRob2RzOiB7XG4gICAgZ2V0VXNlcjogZnVuY3Rpb24gZ2V0VXNlcihpZCkge1xuICAgICAgdmFyIF90aGlzID0gdGhpcztcblxuICAgICAgcmV0dXJuIF9hc3luY1RvR2VuZXJhdG9yKCAvKiNfX1BVUkVfXyovX3JlZ2VuZXJhdG9yUnVudGltZS5tYXJrKGZ1bmN0aW9uIF9jYWxsZWUoKSB7XG4gICAgICAgIHZhciBfeWllbGQkdXNlclJlc291cmNlJGcsIGRhdGE7XG5cbiAgICAgICAgcmV0dXJuIF9yZWdlbmVyYXRvclJ1bnRpbWUud3JhcChmdW5jdGlvbiBfY2FsbGVlJChfY29udGV4dCkge1xuICAgICAgICAgIHdoaWxlICgxKSB7XG4gICAgICAgICAgICBzd2l0Y2ggKF9jb250ZXh0LnByZXYgPSBfY29udGV4dC5uZXh0KSB7XG4gICAgICAgICAgICAgIGNhc2UgMDpcbiAgICAgICAgICAgICAgICBfY29udGV4dC5uZXh0ID0gMjtcbiAgICAgICAgICAgICAgICByZXR1cm4gdXNlclJlc291cmNlLmdldChpZCk7XG5cbiAgICAgICAgICAgICAgY2FzZSAyOlxuICAgICAgICAgICAgICAgIF95aWVsZCR1c2VyUmVzb3VyY2UkZyA9IF9jb250ZXh0LnNlbnQ7XG4gICAgICAgICAgICAgICAgZGF0YSA9IF95aWVsZCR1c2VyUmVzb3VyY2UkZy5kYXRhO1xuICAgICAgICAgICAgICAgIF90aGlzLnVzZXIgPSBkYXRhO1xuXG4gICAgICAgICAgICAgIGNhc2UgNTpcbiAgICAgICAgICAgICAgY2FzZSBcImVuZFwiOlxuICAgICAgICAgICAgICAgIHJldHVybiBfY29udGV4dC5zdG9wKCk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgfVxuICAgICAgICB9LCBfY2FsbGVlKTtcbiAgICAgIH0pKSgpO1xuICAgIH1cbiAgfVxufTsiXSwibWFwcGluZ3MiOiJBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./node_modules/babel-loader/lib/index.js?!./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/index.js?!./resources/js/views/users/UserProfile.vue?vue&type=script&lang=js&\n");
/***/ }),
/***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/users/UserProfile.vue?vue&type=template&id=39b55748&":
/*!***************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/views/users/UserProfile.vue?vue&type=template&id=39b55748& ***!
\***************************************************************************************************************************************************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"render\", function() { return render; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"staticRenderFns\", function() { return staticRenderFns; });\nvar render = function() {\n var _vm = this\n var _h = _vm.$createElement\n var _c = _vm._self._c || _h\n return _c(\n \"div\",\n { staticClass: \"app-container\" },\n [\n _vm.user\n ? _c(\n \"el-form\",\n { attrs: { model: _vm.user } },\n [\n _c(\n \"el-row\",\n [\n _c(\n \"el-col\",\n [_c(\"user-activity\", { attrs: { user: _vm.user } })],\n 1\n )\n ],\n 1\n )\n ],\n 1\n )\n : _vm._e()\n ],\n 1\n )\n}\nvar staticRenderFns = []\nrender._withStripped = true\n\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvbG9hZGVycy90ZW1wbGF0ZUxvYWRlci5qcz8hLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvaW5kZXguanM/IS4vcmVzb3VyY2VzL2pzL3ZpZXdzL3VzZXJzL1VzZXJQcm9maWxlLnZ1ZT92dWUmdHlwZT10ZW1wbGF0ZSZpZD0zOWI1NTc0OCYuanMiLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvdmlld3MvdXNlcnMvVXNlclByb2ZpbGUudnVlPzRlOGIiXSwic291cmNlc0NvbnRlbnQiOlsidmFyIHJlbmRlciA9IGZ1bmN0aW9uKCkge1xuICB2YXIgX3ZtID0gdGhpc1xuICB2YXIgX2ggPSBfdm0uJGNyZWF0ZUVsZW1lbnRcbiAgdmFyIF9jID0gX3ZtLl9zZWxmLl9jIHx8IF9oXG4gIHJldHVybiBfYyhcbiAgICBcImRpdlwiLFxuICAgIHsgc3RhdGljQ2xhc3M6IFwiYXBwLWNvbnRhaW5lclwiIH0sXG4gICAgW1xuICAgICAgX3ZtLnVzZXJcbiAgICAgICAgPyBfYyhcbiAgICAgICAgICAgIFwiZWwtZm9ybVwiLFxuICAgICAgICAgICAgeyBhdHRyczogeyBtb2RlbDogX3ZtLnVzZXIgfSB9LFxuICAgICAgICAgICAgW1xuICAgICAgICAgICAgICBfYyhcbiAgICAgICAgICAgICAgICBcImVsLXJvd1wiLFxuICAgICAgICAgICAgICAgIFtcbiAgICAgICAgICAgICAgICAgIF9jKFxuICAgICAgICAgICAgICAgICAgICBcImVsLWNvbFwiLFxuICAgICAgICAgICAgICAgICAgICBbX2MoXCJ1c2VyLWFjdGl2aXR5XCIsIHsgYXR0cnM6IHsgdXNlcjogX3ZtLnVzZXIgfSB9KV0sXG4gICAgICAgICAgICAgICAgICAgIDFcbiAgICAgICAgICAgICAgICAgIClcbiAgICAgICAgICAgICAgICBdLFxuICAgICAgICAgICAgICAgIDFcbiAgICAgICAgICAgICAgKVxuICAgICAgICAgICAgXSxcbiAgICAgICAgICAgIDFcbiAgICAgICAgICApXG4gICAgICAgIDogX3ZtLl9lKClcbiAgICBdLFxuICAgIDFcbiAgKVxufVxudmFyIHN0YXRpY1JlbmRlckZucyA9IFtdXG5yZW5kZXIuX3dpdGhTdHJpcHBlZCA9IHRydWVcblxuZXhwb3J0IHsgcmVuZGVyLCBzdGF0aWNSZW5kZXJGbnMgfSJdLCJtYXBwaW5ncyI6IkFBQUE7QUFBQTtBQUFBO0FBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTsiLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/users/UserProfile.vue?vue&type=template&id=39b55748&\n");
/***/ }),
/***/ "./resources/js/views/users/UserProfile.vue":
/*!**************************************************!*\
!*** ./resources/js/views/users/UserProfile.vue ***!
\**************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _UserProfile_vue_vue_type_template_id_39b55748___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./UserProfile.vue?vue&type=template&id=39b55748& */ \"./resources/js/views/users/UserProfile.vue?vue&type=template&id=39b55748&\");\n/* harmony import */ var _UserProfile_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./UserProfile.vue?vue&type=script&lang=js& */ \"./resources/js/views/users/UserProfile.vue?vue&type=script&lang=js&\");\n/* empty/unused harmony star reexport *//* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ \"./node_modules/vue-loader/lib/runtime/componentNormalizer.js\");\n\n\n\n\n\n/* normalize component */\n\nvar component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__[\"default\"])(\n _UserProfile_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__[\"default\"],\n _UserProfile_vue_vue_type_template_id_39b55748___WEBPACK_IMPORTED_MODULE_0__[\"render\"],\n _UserProfile_vue_vue_type_template_id_39b55748___WEBPACK_IMPORTED_MODULE_0__[\"staticRenderFns\"],\n false,\n null,\n null,\n null\n \n)\n\n/* hot reload */\nif (false) { var api; }\ncomponent.options.__file = \"resources/js/views/users/UserProfile.vue\"\n/* harmony default export */ __webpack_exports__[\"default\"] = (component.exports);//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9yZXNvdXJjZXMvanMvdmlld3MvdXNlcnMvVXNlclByb2ZpbGUudnVlLmpzIiwic291cmNlcyI6WyJ3ZWJwYWNrOi8vLy4vcmVzb3VyY2VzL2pzL3ZpZXdzL3VzZXJzL1VzZXJQcm9maWxlLnZ1ZT84YzJiIl0sInNvdXJjZXNDb250ZW50IjpbImltcG9ydCB7IHJlbmRlciwgc3RhdGljUmVuZGVyRm5zIH0gZnJvbSBcIi4vVXNlclByb2ZpbGUudnVlP3Z1ZSZ0eXBlPXRlbXBsYXRlJmlkPTM5YjU1NzQ4JlwiXG5pbXBvcnQgc2NyaXB0IGZyb20gXCIuL1VzZXJQcm9maWxlLnZ1ZT92dWUmdHlwZT1zY3JpcHQmbGFuZz1qcyZcIlxuZXhwb3J0ICogZnJvbSBcIi4vVXNlclByb2ZpbGUudnVlP3Z1ZSZ0eXBlPXNjcmlwdCZsYW5nPWpzJlwiXG5cblxuLyogbm9ybWFsaXplIGNvbXBvbmVudCAqL1xuaW1wb3J0IG5vcm1hbGl6ZXIgZnJvbSBcIiEuLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvcnVudGltZS9jb21wb25lbnROb3JtYWxpemVyLmpzXCJcbnZhciBjb21wb25lbnQgPSBub3JtYWxpemVyKFxuICBzY3JpcHQsXG4gIHJlbmRlcixcbiAgc3RhdGljUmVuZGVyRm5zLFxuICBmYWxzZSxcbiAgbnVsbCxcbiAgbnVsbCxcbiAgbnVsbFxuICBcbilcblxuLyogaG90IHJlbG9hZCAqL1xuaWYgKG1vZHVsZS5ob3QpIHtcbiAgdmFyIGFwaSA9IHJlcXVpcmUoXCIvVXNlcnMvd2VzdGhhbS9TaXRlcy9tYXN0ZXItbmEtZG9tL25vZGVfbW9kdWxlcy92dWUtaG90LXJlbG9hZC1hcGkvZGlzdC9pbmRleC5qc1wiKVxuICBhcGkuaW5zdGFsbChyZXF1aXJlKCd2dWUnKSlcbiAgaWYgKGFwaS5jb21wYXRpYmxlKSB7XG4gICAgbW9kdWxlLmhvdC5hY2NlcHQoKVxuICAgIGlmICghYXBpLmlzUmVjb3JkZWQoJzM5YjU1NzQ4JykpIHtcbiAgICAgIGFwaS5jcmVhdGVSZWNvcmQoJzM5YjU1NzQ4JywgY29tcG9uZW50Lm9wdGlvbnMpXG4gICAgfSBlbHNlIHtcbiAgICAgIGFwaS5yZWxvYWQoJzM5YjU1NzQ4JywgY29tcG9uZW50Lm9wdGlvbnMpXG4gICAgfVxuICAgIG1vZHVsZS5ob3QuYWNjZXB0KFwiLi9Vc2VyUHJvZmlsZS52dWU/dnVlJnR5cGU9dGVtcGxhdGUmaWQ9MzliNTU3NDgmXCIsIGZ1bmN0aW9uICgpIHtcbiAgICAgIGFwaS5yZXJlbmRlcignMzliNTU3NDgnLCB7XG4gICAgICAgIHJlbmRlcjogcmVuZGVyLFxuICAgICAgICBzdGF0aWNSZW5kZXJGbnM6IHN0YXRpY1JlbmRlckZuc1xuICAgICAgfSlcbiAgICB9KVxuICB9XG59XG5jb21wb25lbnQub3B0aW9ucy5fX2ZpbGUgPSBcInJlc291cmNlcy9qcy92aWV3cy91c2Vycy9Vc2VyUHJvZmlsZS52dWVcIlxuZXhwb3J0IGRlZmF1bHQgY29tcG9uZW50LmV4cG9ydHMiXSwibWFwcGluZ3MiOiJBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSx1QkFpQkE7QUFDQTtBQUNBIiwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///./resources/js/views/users/UserProfile.vue\n");
/***/ }),
/***/ "./resources/js/views/users/UserProfile.vue?vue&type=script&lang=js&":
/*!***************************************************************************!*\
!*** ./resources/js/views/users/UserProfile.vue?vue&type=script&lang=js& ***!
\***************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_babel_loader_lib_index_js_node_modules_vue_loader_lib_index_js_vue_loader_options_UserProfile_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/babel-loader/lib??ref--4-0!../../../../node_modules/babel-loader/lib!../../../../node_modules/vue-loader/lib??vue-loader-options!./UserProfile.vue?vue&type=script&lang=js& */ \"./node_modules/babel-loader/lib/index.js?!./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/index.js?!./resources/js/views/users/UserProfile.vue?vue&type=script&lang=js&\");\n/* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__[\"default\"] = (_node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_babel_loader_lib_index_js_node_modules_vue_loader_lib_index_js_vue_loader_options_UserProfile_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__[\"default\"]); //# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9yZXNvdXJjZXMvanMvdmlld3MvdXNlcnMvVXNlclByb2ZpbGUudnVlP3Z1ZSZ0eXBlPXNjcmlwdCZsYW5nPWpzJi5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL3Jlc291cmNlcy9qcy92aWV3cy91c2Vycy9Vc2VyUHJvZmlsZS52dWU/NjdiMSJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgbW9kIGZyb20gXCItIS4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy9iYWJlbC1sb2FkZXIvbGliL2luZGV4LmpzPz9yZWYtLTQtMCEuLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvYmFiZWwtbG9hZGVyL2xpYi9pbmRleC5qcyEuLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvaW5kZXguanM/P3Z1ZS1sb2FkZXItb3B0aW9ucyEuL1VzZXJQcm9maWxlLnZ1ZT92dWUmdHlwZT1zY3JpcHQmbGFuZz1qcyZcIjsgZXhwb3J0IGRlZmF1bHQgbW9kOyBleHBvcnQgKiBmcm9tIFwiLSEuLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvYmFiZWwtbG9hZGVyL2xpYi9pbmRleC5qcz8/cmVmLS00LTAhLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL2JhYmVsLWxvYWRlci9saWIvaW5kZXguanMhLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2luZGV4LmpzPz92dWUtbG9hZGVyLW9wdGlvbnMhLi9Vc2VyUHJvZmlsZS52dWU/dnVlJnR5cGU9c2NyaXB0Jmxhbmc9anMmXCIiXSwibWFwcGluZ3MiOiJBQUFBO0FBQUE7QUFBQSIsInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./resources/js/views/users/UserProfile.vue?vue&type=script&lang=js&\n");
/***/ }),
/***/ "./resources/js/views/users/UserProfile.vue?vue&type=template&id=39b55748&":
/*!*********************************************************************************!*\
!*** ./resources/js/views/users/UserProfile.vue?vue&type=template&id=39b55748& ***!
\*********************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_UserProfile_vue_vue_type_template_id_39b55748___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../node_modules/vue-loader/lib??vue-loader-options!./UserProfile.vue?vue&type=template&id=39b55748& */ \"./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/views/users/UserProfile.vue?vue&type=template&id=39b55748&\");\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"render\", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_UserProfile_vue_vue_type_template_id_39b55748___WEBPACK_IMPORTED_MODULE_0__[\"render\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"staticRenderFns\", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_UserProfile_vue_vue_type_template_id_39b55748___WEBPACK_IMPORTED_MODULE_0__[\"staticRenderFns\"]; });\n\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9yZXNvdXJjZXMvanMvdmlld3MvdXNlcnMvVXNlclByb2ZpbGUudnVlP3Z1ZSZ0eXBlPXRlbXBsYXRlJmlkPTM5YjU1NzQ4Ji5qcyIsInNvdXJjZXMiOlsid2VicGFjazovLy8uL3Jlc291cmNlcy9qcy92aWV3cy91c2Vycy9Vc2VyUHJvZmlsZS52dWU/ZWU2NSJdLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgKiBmcm9tIFwiLSEuLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvbG9hZGVycy90ZW1wbGF0ZUxvYWRlci5qcz8/dnVlLWxvYWRlci1vcHRpb25zIS4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9pbmRleC5qcz8/dnVlLWxvYWRlci1vcHRpb25zIS4vVXNlclByb2ZpbGUudnVlP3Z1ZSZ0eXBlPXRlbXBsYXRlJmlkPTM5YjU1NzQ4JlwiIl0sIm1hcHBpbmdzIjoiQUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUE7Iiwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///./resources/js/views/users/UserProfile.vue?vue&type=template&id=39b55748&\n");
/***/ })
}]); |
import { createActions, createReducer } from "reduxsauce";
/**
* Action types & creators
*/
export const { Types, Creators } = createActions({
addTodo: ["text"],
toggleTodo: ["id"],
removeTodo: ["id"]
});
/**
* Handlers
*/
const INITIAL_STATE = [];
const add = (state = INITIAL_STATE, action) => [
...state,
{ id: Math.random(), text: action.text, complete: false }
];
const toggle = (state = INITIAL_STATE, action) =>
state.map(
todo =>
todo.id === action.id ? { ...todo, complete: !todo.complete } : todo
);
const remove = (state = INITIAL_STATE, action) =>
state.filter(todo => todo.id !== action.id);
/**
* Reducer
*/
export default createReducer(INITIAL_STATE, {
[Types.ADD_TODO]: add,
[Types.TOGGLE_TODO]: toggle,
[Types.REMOVE_TODO]: remove
});
|
import asyncio, random, math, os, requests, zipfile, datetime, re, html, bs4, requests, asyncio, textwrap
from telethon import events
from telethon.errors.rpcerrorlist import YouBlockedUserError
from telethon.tl.functions.account import UpdateNotifySettingsRequest
from userbot.events import javes05, rekcah05, progress, humanbytes, time_formatter
from userbot import CMD_HELP, ALIVE_NAME, PM_MESSAGE, JAVES_NAME, JAVES_MSG, ORI_MSG, bot as javes
from io import BytesIO
from PIL import Image
from datetime import datetime
THUMB_IMAGE_PATH = "./thumb_image.jpg"
from hachoir.metadata import extractMetadata
from hachoir.parser import createParser
from pySmartDL import SmartDL
from telethon.tl.types import DocumentAttributeVideo
from userbot import (TEMP_DOWNLOAD_DIRECTORY, CMD_HELP, bot)
from collections import defaultdict
from telethon.errors.rpcerrorlist import StickersetInvalidError
from telethon.errors import MessageNotModifiedError
from telethon.tl.functions.account import UpdateNotifySettingsRequest
from telethon.tl.functions.messages import GetStickerSetRequest
from telethon.tl.types import (DocumentAttributeFilename, DocumentAttributeSticker, InputMediaUploadedDocument, InputPeerNotifySettings, InputStickerSetID, InputStickerSetShortName, MessageMediaPhoto)
def is_message_image(message):
if message.media:
if isinstance(message.media, MessageMediaPhoto):
return True
if message.media.document:
if message.media.document.mime_type.split("/")[0] == "image":
return True
return False
return False
async def silently_send_message(conv, text):
await conv.send_message(text)
response = await conv.get_response()
await conv.mark_read(message=response)
return response
EMOJI_PATTERN = re.compile(
"["
"\U0001F1E0-\U0001F1FF" # flags (iOS)
"\U0001F300-\U0001F5FF" # symbols & pictographs
"\U0001F600-\U0001F64F" # emoticons
"\U0001F680-\U0001F6FF" # transport & map symbols
"\U0001F700-\U0001F77F" # alchemical symbols
"\U0001F780-\U0001F7FF" # Geometric Shapes Extended
"\U0001F800-\U0001F8FF" # Supplemental Arrows-C
"\U0001F900-\U0001F9FF" # Supplemental Symbols and Pictographs
"\U0001FA00-\U0001FA6F" # Chess Symbols
"\U0001FA70-\U0001FAFF" # Symbols and Pictographs Extended-A
"\U00002702-\U000027B0" # Dingbats
"]+")
def deEmojify(inputString: str) -> str:
return re.sub(EMOJI_PATTERN, '', inputString)
@javes.on(rekcah05(pattern=f"song2(?: |$)(.*)", allow_sudo=True))
@javes05(outgoing=True, pattern="^!song2(?: |$)(.*)")
async def _(event):
sender = await event.get_sender() ; me = await event.client.get_me()
if not sender.id == me.id:
rkp = await event.reply("`processing...`")
else:
rkp = await event.edit("`processing...`")
try:
reply_message = event.pattern_match.group(1)
if not reply_message:
reply_message = await event.get_reply_message()
if reply_message:
if reply_message.media:
return await rkp.edit("`Reply to a text message`")
if not reply_message:
return await rkp.edit("`Error\n**Usage** song2 <song> or reply to a message`")
chat = "@vkmusic_bot"
async with event.client.conversation(chat, timeout=7) as conv:
try:
await conv.send_message(reply_message)
response = await conv.get_response()
except YouBlockedUserError:
await rkp.edit("`Please unblock @iLyricsBot and try again`")
return
try:
await response.click(1, 1)
except:
return await rkp.edit(f"`Failed to find {reply_message}`")
test = await conv.get_response()
await rkp.delete()
await event.client.send_file(event.chat_id, test, caption=f"`{reply_message} song`", reply_to=event.message.reply_to_msg_id)
except Exception as e:
error = str(e)
if not error:
error = f"No response from {chat}"
return await rkp.edit(f"**Error**\n\n{error}")
@javes.on(rekcah05(pattern=f"history(?: |$)(.*)", allow_sudo=True))
@javes05(outgoing=True, pattern="^!history(?: |$)(.*)")
async def _(event):
sender = await event.get_sender() ; me = await event.client.get_me()
if not sender.id == me.id:
rkp = await event.reply("`processing...`")
else:
rkp = await event.edit("`processing...`")
try:
name = username = [] ; reply_message = await event.get_reply_message()
if not event.reply_to_msg_id or reply_message.media:
return await rkp.edit("`reply to a user text message`")
chat = "@SangMataInfo_bot"
async with event.client.conversation(chat, timeout=7) as conv:
try:
test = conv.wait_event(events.NewMessage(incoming=True,from_users=461843263))
await event.client.forward_messages(chat, reply_message)
response = await test
except YouBlockedUserError:
await rkp.edit("`Please unblock @sangmatainfo_bot and try again`")
return
if response.text.startswith("Forward"):
return await rkp.edit("`Privacy error!`")
if response.text.startswith("🔗"):
return await rkp.edit("`No name/username history for this user`")
if response.text.startswith("Name"):
name = response.text
await rkp.edit(f"` Got name history Trying to get username history....` ")
test = conv.wait_event(events.NewMessage(incoming=True,from_users=461843263))
response = await test
if response.text.startswith("Username"):
username = response.text
await rkp.edit("` Got username history Trying to give full results....` ")
return await rkp.edit(f"**User History**\n\n{name}\n\n{username}")
except Exception as e:
error = str(e)
if not error:
error = f"No response from {chat}"
return await rkp.edit(f"**Error**\n\n{error}")
@javes.on(rekcah05(pattern=f"ag(?: |$)(.*)", allow_sudo=True))
@javes05(outgoing=True, pattern="^!ag(?: |$)(.*)")
async def ag(animu):
try:
await animu.delete()
except:
pass
text = animu.pattern_match.group(1)
if not text:
if animu.is_reply:
text = (await animu.get_reply_message()).message
else:
await rkp.edit("`No text given`")
return
animus = [20, 32, 33, 40, 41, 42, 58]
sticcers = await bot.inline_query(
"stickerizerbot", f"#{random.choice(animus)}{(deEmojify(text))}")
await sticcers[0].click(animu.chat_id,
reply_to=animu.reply_to_msg_id,
silent=True if animu.is_reply else False,
hide_via=True)
@javes.on(rekcah05(pattern=f"info(?: |$)(.*)", allow_sudo=True))
@javes05(outgoing=True, pattern="^!info(?: |$)(.*)")
async def _(event):
sender = await event.get_sender() ; me = await event.client.get_me()
if not sender.id == me.id:
rkp = await event.reply("`processing...`")
else:
rkp = await event.edit("`processing...`")
try:
reply_message = await event.get_reply_message()
if not event.reply_to_msg_id:
return await rkp.edit("`reply to a user message`")
chat = "@getidsbot"
async with event.client.conversation(chat, timeout=7) as conv:
try:
test = conv.wait_event(events.NewMessage(incoming=True,from_users=186675376))
await event.client.forward_messages(chat, reply_message)
response = await test
except YouBlockedUserError:
return await rkp.edit("`Please unblock @getidsbot_bot and try again`")
return await rkp.edit(f"**Info**\n\n{response.text}")
except Exception as e:
error = str(e)
if not error:
error = f"No response from {chat}"
return await rkp.edit(f"**Error**\n\n{error}")
@javes.on(rekcah05(pattern=f"lyrics2(?: |$)(.*)", allow_sudo=True))
@javes05(outgoing=True, pattern="^!lyrics2(?: |$)(.*)")
async def _(event):
sender = await event.get_sender() ; me = await event.client.get_me()
if not sender.id == me.id:
rkp = await event.reply("`processing...`")
else:
rkp = await event.edit("`processing...`")
try:
reply_message = event.pattern_match.group(1)
if not reply_message:
reply_message = await event.get_reply_message()
if reply_message:
if reply_message.media:
return await rkp.edit("`Reply to a text message`")
if not reply_message:
return await rkp.edit("`Error\n**Usage** lyrics2 <song> or reply to a message`")
chat = "@iLyricsBot"
async with event.client.conversation(chat, timeout=7) as conv:
try:
test = conv.wait_event(events.MessageEdited(incoming=True,from_users=232268607))
await event.client.send_message(chat, reply_message)
response = await test
except YouBlockedUserError:
await rkp.edit("`Please unblock @iLyricsBot and try again`")
return
return await rkp.edit(response.text)
except Exception as e:
error = str(e)
if not error:
error = f"No response from {chat}"
return await rkp.edit(f"**Error**\n\n{error}")
@javes.on(rekcah05(pattern=f"fry(?: |$)(.*)", allow_sudo=True))
@javes05(outgoing=True, pattern="^!fry(?: |$)(.*)")
async def _(event):
sender = await event.get_sender() ; me = await event.client.get_me()
if not sender.id == me.id:
rkp = await event.reply("`processing...`")
else:
rkp = await event.edit("`processing...`")
try:
reply_message = await event.get_reply_message()
if reply_message:
if not reply_message.media:
return await rkp.edit("`Reply to a photo/sticker`")
if not reply_message:
return await rkp.edit("**Error**\n**Usage** fry reply to a non animated sticker / photo")
chat = "@image_deepfrybot"
async with event.client.conversation(chat, timeout=7) as conv:
try:
test = conv.wait_event(events.NewMessage(incoming=True,from_users=432858024))
await event.client.forward_messages(chat, reply_message)
response = await test
except YouBlockedUserError:
await rkp.edit("`Please unblock @image_deepfrybot and try again`")
return
await rkp.delete()
return await event.client.send_file(event.chat_id, response.message.media, reply_to=event.message.reply_to_msg_id)
except Exception as e:
error = str(e)
if not error:
error = f"No response from {chat}"
return await rkp.edit(f"**Error**\n\n{error}")
@javes.on(rekcah05(pattern=f"ss2(?: |$)(.*)", allow_sudo=True))
@javes05(outgoing=True, pattern="^!ss2(?: |$)(.*)")
async def _(event):
sender = await event.get_sender() ; me = await event.client.get_me()
if not sender.id == me.id:
rkp = await event.reply("`processing...`")
else:
rkp = await event.edit("`processing...`")
try:
reply_message = await event.get_reply_message()
if reply_message:
if not reply_message.media:
return await rkp.edit("`Reply to a photo`")
if not reply_message:
return await rkp.edit("**Error**\n**Usage** ss2 reply to a photo")
chat = "@BuildStickerBot"
async with event.client.conversation(chat, timeout=7) as conv:
try:
test = conv.wait_event(events.NewMessage(incoming=True,from_users=164977173))
await event.client.forward_messages(chat, reply_message)
response = await test
except YouBlockedUserError:
return await rkp.edit("`Please unblock @BuildStickerBot and try again`")
if response.text.startswith("🔸"):
return await rkp.edit("`Failed to convert`")
await rkp.delete()
return await event.client.send_file(event.chat_id, response.message.media, reply_to=event.message.reply_to_msg_id)
except Exception as e:
error = str(e)
if not error:
error = f"No response from {chat}"
return await rkp.edit(f"**Error**\n\n{error}")
@javes.on(rekcah05(pattern=f"info2(?: |$)(.*)", allow_sudo=True))
@javes05(outgoing=True, pattern="^!info2(?: |$)(.*)")
async def _(event):
sender = await event.get_sender() ; me = await event.client.get_me()
if not sender.id == me.id:
rkp = await event.reply("`processing...`")
else:
rkp = await event.edit("`processing...`")
try:
reply_message = await event.get_reply_message()
if reply_message:
if not reply_message.media:
return await rkp.edit("`Reply to a photo`")
if not reply_message:
return await rkp.edit("**Error**\n**Usage** read2 reply to a photo")
chat = "@Rekognition_Bot"
async with event.client.conversation(chat, timeout=15) as conv:
try:
test = conv.wait_event(events.NewMessage(incoming=True,from_users=461083923))
await event.client.forward_messages(chat, reply_message)
response = await test
test = conv.wait_event(events.NewMessage(incoming=True,from_users=461083923))
response = await test
except YouBlockedUserError:
return await rkp.edit("`Please unblock @Rekognition_Bot and try again`")
if response.text.startswith("Send"):
return await rkp.edit("`Failed to read`")
return await rkp.edit(response.text)
except Exception as e:
error = str(e)
if not error:
error = f"No response from {chat}"
return await rkp.edit(f"**Error**\n\n{error}")
@javes.on(rekcah05(pattern=f"ss3(?: |$)(.*)", allow_sudo=True))
@javes05(outgoing=True, pattern="^!ss3(?: |$)(.*)")
async def _(event):
sender = await event.get_sender() ; me = await event.client.get_me()
if not sender.id == me.id:
rkp = await event.reply("`processing...`")
else:
rkp = await event.edit("`processing...`")
try:
reply_message = await event.get_reply_message()
if reply_message:
if not reply_message.media:
return await rkp.edit("`Reply to a photo`")
if not reply_message:
return await rkp.edit("**Error**\n**Usage** ss2 reply to a photo")
chat = "@Stickerdownloadbot"
async with event.client.conversation(chat, timeout=7) as conv:
try:
test = conv.wait_event(events.NewMessage(incoming=True,from_users=220255550))
await event.client.forward_messages(chat, reply_message)
response = await test
except YouBlockedUserError:
return await rkp.edit("`Please unblock @Stickerdownloadbot and try again`")
if response.text.startswith("I"):
return await rkp.edit("`Failed to convert`")
await rkp.delete()
return await event.client.send_file(event.chat_id, response.message.media, reply_to=event.message.reply_to_msg_id)
except Exception as e:
error = str(e)
if not error:
error = f"No response from {chat}"
return await rkp.edit(f"**Error**\n\n{error}")
@javes.on(rekcah05(pattern=f"ss4(?: |$)(.*)", allow_sudo=True))
@javes05(outgoing=True, pattern="^!ss4(?: |$)(.*)")
async def _(event):
sender = await event.get_sender() ; me = await event.client.get_me()
if not sender.id == me.id:
rkp = await event.reply("`processing...`")
else:
rkp = await event.edit("`processing...`")
try:
reply_message = await event.get_reply_message()
if reply_message:
if not reply_message.media:
return await rkp.edit("`Reply to a photo`")
if not reply_message:
return await rkp.edit("**Error**\n**Usage** ss2 reply to a photo")
chat = "@stickerator_bot"
async with event.client.conversation(chat, timeout=7) as conv:
try:
test = conv.wait_event(events.NewMessage(incoming=True,from_users=384614990))
await event.client.forward_messages(chat, reply_message)
response = await test
except YouBlockedUserError:
return await rkp.edit("`Please unblock @stickerator_bot and try again`")
if response.text.startswith("274"):
return await rkp.edit("`Failed to convert`")
await rkp.delete()
return await event.client.send_file(event.chat_id, response.message.media, reply_to=event.message.reply_to_msg_id)
except Exception as e:
error = str(e)
if not error:
error = f"No response from {chat}"
return await rkp.edit(f"**Error**\n\n{error}")
@javes.on(rekcah05(pattern=f"mask(?: |$)(.*)", allow_sudo=True))
@javes05(outgoing=True, pattern="^!mask(?: |$)(.*)")
async def _(event):
sender = await event.get_sender() ; me = await event.client.get_me()
if not sender.id == me.id:
rkp = await event.reply("`processing...`")
else:
rkp = await event.edit("`processing...`")
try:
reply_message = await event.get_reply_message()
if reply_message:
if not reply_message.media:
return await rkp.edit("`Reply to a photo/sticker`")
if not reply_message:
return await rkp.edit("**Error**\n**Usage** fry reply to a non animated sticker / photo")
chat = "@hazmat_suit_bot"
async with event.client.conversation(chat, timeout=7) as conv:
try:
test = conv.wait_event(events.NewMessage(incoming=True,from_users=905164246))
await event.client.forward_messages(chat, reply_message)
response = await test
except YouBlockedUserError:
await rkp.edit("`Please unblock @hazmat_suit_bot and try again`")
return
await rkp.delete()
return await event.client.send_file(event.chat_id, response.message.media, reply_to=event.message.reply_to_msg_id)
except Exception as e:
error = str(e)
if not error:
error = f"No response from {chat}"
return await rkp.edit(f"**Error**\n\n{error}")
@javes.on(rekcah05(pattern=f"ushort(?: |$)(.*)", allow_sudo=True))
@javes05(outgoing=True, pattern="^!ushort(?: |$)(.*)")
async def _(event):
sender = await event.get_sender() ; me = await event.client.get_me()
if not sender.id == me.id:
rkp = await event.reply("`processing...`")
else:
rkp = await event.edit("`processing...`")
try:
reply_message = event.pattern_match.group(1)
if not reply_message:
reply_message = await event.get_reply_message()
if reply_message:
if reply_message.media:
return await rkp.edit("`Reply to a link`")
if not reply_message:
return await rkp.edit("`Error\n**Usage** ushort <link> or reply to a link`")
chat = "@LinkGeneratorBot"
async with event.client.conversation(chat, timeout=7) as conv:
try:
test = conv.wait_event(events.NewMessage(incoming=True,from_users=355705793))
await event.client.send_message(chat, reply_message)
response = await test
except YouBlockedUserError:
await rkp.edit("`Please unblock @LinkGeneratorBot and try again`")
return
return await rkp.edit(response.text)
except Exception as e:
error = str(e)
if not error:
error = f"No response from {chat}"
return await rkp.edit(f"**Error**\n\n{error}")
@javes.on(rekcah05(pattern=f"mmf(?: |$)(.*)", allow_sudo=True))
@javes05(outgoing=True, pattern="^!mmf(?: |$)(.*)")
async def mim(event):
sender = await event.get_sender() ; me = await event.client.get_me()
if not sender.id == me.id:
rkp = await event.reply("`processing...`")
else:
rkp = await event.edit("`processing...`")
try:
memeVar = event.pattern_match.group(1)
if not event.reply_to_msg_id or not memeVar:
return await rkp.edit("`Error: usage mmf 'text on top' ; 'text on bottom' reply to an image/sticker/gif ")
reply_message = await event.get_reply_message()
if not reply_message or not reply_message.media:
return await rkp.edit("`reply to a image/sticker/gif`")
chat = "@MemeAutobot"
sender = reply_message.sender
file_ext_ns_ion = "@memetime.png"
file = await event.client.download_file(reply_message.media)
uploaded_gif = None
async with event.client.conversation(chat, timeout=7) as bot_conv:
try:
await silently_send_message(bot_conv, "/start")
await silently_send_message(bot_conv, memeVar)
await event.client.send_file(chat, reply_message.media)
response = await bot_conv.get_response()
except YouBlockedUserError:
return await event.reply("`Please unblock @MemeAutobot and try again`")
if "Okay..." in response.text:
thumb = None
if os.path.exists(THUMB_IMAGE_PATH):
thumb = THUMB_IMAGE_PATH
input_str = event.pattern_match.group(1)
if not os.path.isdir(TEMP_DOWNLOAD_DIRECTORY):
os.makedirs(TEMP_DOWNLOAD_DIRECTORY)
if event.reply_to_msg_id:
file_name = "meme.png"
reply_message = await event.get_reply_message()
to_download_directory = TEMP_DOWNLOAD_DIRECTORY
downloaded_file_name = os.path.join(to_download_directory, file_name)
downloaded_file_name = await event.client.download_media( reply_message, downloaded_file_name )
if os.path.exists(downloaded_file_name):
await event.client.send_file( chat, downloaded_file_name, force_document=False, supports_streaming=False, allow_cache=False, thumb=thumb )
os.remove(downloaded_file_name)
response = await bot_conv.get_response()
the_download_directory = TEMP_DOWNLOAD_DIRECTORY
files_name = "memes.webp"
download_file_name = os.path.join(the_download_directory, files_name)
await event.client.download_media( response.media, download_file_name )
requires_file_name = TEMP_DOWNLOAD_DIRECTORY + "memes.webp"
await event.client.send_file( event.chat_id, requires_file_name, reply_to=event.message.reply_to_msg_id, supports_streaming=False, caption="Memifyed" )
return await rkp.delete()
elif not is_message_image(reply_message):
return
else:
await rkp.delete()
return await event.client.send_file(event.chat_id, response.media, reply_to=event.message.reply_to_msg_id)
except Exception as e:
error = str(e)
if not error:
error = f"No response from {chat}"
return await rkp.edit(f"**Error**\n\n{error}")
@javes.on(rekcah05(pattern=f"ss(?: |$)(.*)", allow_sudo=True))
@javes05(outgoing=True, pattern="^!ss(?: |$)(.*)")
async def _(event):
sender = await event.get_sender() ; me = await event.client.get_me()
if not sender.id == me.id:
rkp = await event.reply("`processing...`")
else:
rkp = await event.edit("`processing...`")
try:
reply_message = await event.get_reply_message()
if reply_message:
if reply_message.media:
return await rkp.edit("`Reply to a text`")
if not reply_message:
return await rkp.edit("**Error**\n**Usage** ss reply to a text")
chat = "@QuotLyBot"
async with event.client.conversation(chat, timeout=7) as conv:
try:
test = conv.wait_event(events.NewMessage(incoming=True,from_users=1031952739))
await event.client.forward_messages(chat, reply_message)
response = await test
except YouBlockedUserError:
await rkp.edit("`Please unblock @QuotLyBot and try again`")
return
await rkp.delete()
return await event.client.send_file(event.chat_id, response.message.media, reply_to=event.message.reply_to_msg_id)
except Exception as e:
error = str(e)
if not error:
error = f"No response from {chat}"
return await rkp.edit(f"**Error**\n\n{error}")
CMD_HELP.update({
"bot":
"!history <reply to a user>\
\n**Usage**: get user name, username history\
\n\n!ag <text>\
\n**Usage**: display given text with anime girl..\
\n\n!info <reply to a message>\
\n**Usage**: get message, user information \
\n\n!lyrics2 <song name>\
\n**Usage**: for get lyrics \
\n\n!fry <reply to a non animated sticker/photo>\
\n**Usage**: fry given img/sticker \
\n\n!ss <reply to a message>\
\n**Usage**: change given text to cool img \
\n\n!ss2 <reply to a photo>\
\n**Usage**: chang img to sticker \
\n\n!ss3 <reply to a photo/sticker>\
\n**Usage**: convert the img/sticker \
\n\n!ss4 <reply to a photo/sticker>\
\n**Usage**: convert the img/sticker \
\n\n!info2 <reply to a photo>\
\n**Usage**: get information about given photo \
\n\n!mask <reply to a photo/sticker>\
\n**Usage**: save your sticker/photo from covid-19 \
\n\n!ushort <link>\
\n**Usage**: shorted the url \
\n\n!mmf <texttop ; textbottom> <reply to a photo/sticker>\
\n**Usage**: mmfying the img \
\n\n **All Commands support sudo** \
"
})
|
const { override, addDecoratorsLegacy } = require('customize-cra');
module.exports = override(
addDecoratorsLegacy()
); |
/**
* Copyright (c) 2006-2018, JGraph Ltd
* Copyright (c) 2006-2018, Gaudenz Alder
*/
/**
* Class: mxGraphModel
*
* Extends <mxEventSource> to implement a graph model. The graph model acts as
* a wrapper around the cells which are in charge of storing the actual graph
* datastructure. The model acts as a transactional wrapper with event
* notification for all changes, whereas the cells contain the atomic
* operations for updating the actual datastructure.
*
* Layers:
*
* The cell hierarchy in the model must have a top-level root cell which
* contains the layers (typically one default layer), which in turn contain the
* top-level cells of the layers. This means each cell is contained in a layer.
* If no layers are required, then all new cells should be added to the default
* layer.
*
* Layers are useful for hiding and showing groups of cells, or for placing
* groups of cells on top of other cells in the display. To identify a layer,
* the <isLayer> function is used. It returns true if the parent of the given
* cell is the root of the model.
*
* Events:
*
* See events section for more details. There is a new set of events for
* tracking transactional changes as they happen. The events are called
* startEdit for the initial beginUpdate, executed for each executed change
* and endEdit for the terminal endUpdate. The executed event contains a
* property called change which represents the change after execution.
*
* Encoding the model:
*
* To encode a graph model, use the following code:
*
* (code)
* var enc = new mxCodec();
* var node = enc.encode(graph.getModel());
* (end)
*
* This will create an XML node that contains all the model information.
*
* Encoding and decoding changes:
*
* For the encoding of changes, a graph model listener is required that encodes
* each change from the given array of changes.
*
* (code)
* model.addListener(mxEvent.CHANGE, function(sender, evt)
* {
* var changes = evt.getProperty('edit').changes;
* var nodes = [];
* var codec = new mxCodec();
*
* for (var i = 0; i < changes.length; i++)
* {
* nodes.push(codec.encode(changes[i]));
* }
* // do something with the nodes
* });
* (end)
*
* For the decoding and execution of changes, the codec needs a lookup function
* that allows it to resolve cell IDs as follows:
*
* (code)
* var codec = new mxCodec();
* codec.lookup = function(id)
* {
* return model.getCell(id);
* }
* (end)
*
* For each encoded change (represented by a node), the following code can be
* used to carry out the decoding and create a change object.
*
* (code)
* var changes = [];
* var change = codec.decode(node);
* change.model = model;
* change.execute();
* changes.push(change);
* (end)
*
* The changes can then be dispatched using the model as follows.
*
* (code)
* var edit = new mxUndoableEdit(model, false);
* edit.changes = changes;
*
* edit.notify = function()
* {
* edit.source.fireEvent(new mxEventObject(mxEvent.CHANGE,
* 'edit', edit, 'changes', edit.changes));
* edit.source.fireEvent(new mxEventObject(mxEvent.NOTIFY,
* 'edit', edit, 'changes', edit.changes));
* }
*
* model.fireEvent(new mxEventObject(mxEvent.UNDO, 'edit', edit));
* model.fireEvent(new mxEventObject(mxEvent.CHANGE,
* 'edit', edit, 'changes', changes));
* (end)
*
* Event: mxEvent.CHANGE
*
* Fires when an undoable edit is dispatched. The <code>edit</code> property
* contains the <mxUndoableEdit>. The <code>changes</code> property contains
* the array of atomic changes inside the undoable edit. The changes property
* is <strong>deprecated</strong>, please use edit.changes instead.
*
* Example:
*
* For finding newly inserted cells, the following code can be used:
*
* (code)
* graph.model.addListener(mxEvent.CHANGE, function(sender, evt)
* {
* var changes = evt.getProperty('edit').changes;
*
* for (var i = 0; i < changes.length; i++)
* {
* var change = changes[i];
*
* if (change instanceof mxChildChange &&
* change.change.previous == null)
* {
* graph.startEditingAtCell(change.child);
* break;
* }
* }
* });
* (end)
*
*
* Event: mxEvent.NOTIFY
*
* Same as <mxEvent.CHANGE>, this event can be used for classes that need to
* implement a sync mechanism between this model and, say, a remote model. In
* such a setup, only local changes should trigger a notify event and all
* changes should trigger a change event.
*
* Event: mxEvent.EXECUTE
*
* Fires between begin- and endUpdate and after an atomic change was executed
* in the model. The <code>change</code> property contains the atomic change
* that was executed.
*
* Event: mxEvent.EXECUTED
*
* Fires between START_EDIT and END_EDIT after an atomic change was executed.
* The <code>change</code> property contains the change that was executed.
*
* Event: mxEvent.BEGIN_UPDATE
*
* Fires after the <updateLevel> was incremented in <beginUpdate>. This event
* contains no properties.
*
* Event: mxEvent.START_EDIT
*
* Fires after the <updateLevel> was changed from 0 to 1. This event
* contains no properties.
*
* Event: mxEvent.END_UPDATE
*
* Fires after the <updateLevel> was decreased in <endUpdate> but before any
* notification or change dispatching. The <code>edit</code> property contains
* the <currentEdit>.
*
* Event: mxEvent.END_EDIT
*
* Fires after the <updateLevel> was changed from 1 to 0. This event
* contains no properties.
*
* Event: mxEvent.BEFORE_UNDO
*
* Fires before the change is dispatched after the update level has reached 0
* in <endUpdate>. The <code>edit</code> property contains the <curreneEdit>.
*
* Event: mxEvent.UNDO
*
* Fires after the change was dispatched in <endUpdate>. The <code>edit</code>
* property contains the <currentEdit>.
*
* Constructor: mxGraphModel
*
* Constructs a new graph model. If no root is specified then a new root
* <mxCell> with a default layer is created.
*
* Parameters:
*
* root - <mxCell> that represents the root cell.
*/
function mxGraphModel(root)
{
this.currentEdit = this.createUndoableEdit();
if (root != null)
{
this.setRoot(root);
}
else
{
this.clear();
}
};
/**
* Extends mxEventSource.
*/
mxGraphModel.prototype = new mxEventSource();
mxGraphModel.prototype.constructor = mxGraphModel;
/**
* Variable: root
*
* Holds the root cell, which in turn contains the cells that represent the
* layers of the diagram as child cells. That is, the actual elements of the
* diagram are supposed to live in the third generation of cells and below.
*/
mxGraphModel.prototype.root = null;
/**
* Variable: cells
*
* Maps from Ids to cells.
*/
mxGraphModel.prototype.cells = null;
/**
* Variable: maintainEdgeParent
*
* Specifies if edges should automatically be moved into the nearest common
* ancestor of their terminals. Default is true.
*/
mxGraphModel.prototype.maintainEdgeParent = true;
/**
* Variable: ignoreRelativeEdgeParent
*
* Specifies if relative edge parents should be ignored for finding the nearest
* common ancestors of an edge's terminals. Default is true.
*/
mxGraphModel.prototype.ignoreRelativeEdgeParent = true;
/**
* Variable: createIds
*
* Specifies if the model should automatically create Ids for new cells.
* Default is true.
*/
mxGraphModel.prototype.createIds = true;
/**
* Variable: prefix
*
* Defines the prefix of new Ids. Default is an empty string.
*/
mxGraphModel.prototype.prefix = '';
/**
* Variable: postfix
*
* Defines the postfix of new Ids. Default is an empty string.
*/
mxGraphModel.prototype.postfix = '';
/**
* Variable: nextId
*
* Specifies the next Id to be created. Initial value is 0.
*/
mxGraphModel.prototype.nextId = 0;
/**
* Variable: currentEdit
*
* Holds the changes for the current transaction. If the transaction is
* closed then a new object is created for this variable using
* <createUndoableEdit>.
*/
mxGraphModel.prototype.currentEdit = null;
/**
* Variable: updateLevel
*
* Counter for the depth of nested transactions. Each call to <beginUpdate>
* will increment this number and each call to <endUpdate> will decrement
* it. When the counter reaches 0, the transaction is closed and the
* respective events are fired. Initial value is 0.
*/
mxGraphModel.prototype.updateLevel = 0;
/**
* Variable: endingUpdate
*
* True if the program flow is currently inside endUpdate.
*/
mxGraphModel.prototype.endingUpdate = false;
/**
* Function: clear
*
* Sets a new root using <createRoot>.
*/
mxGraphModel.prototype.clear = function()
{
this.setRoot(this.createRoot());
};
/**
* Function: isCreateIds
*
* Returns <createIds>.
*/
mxGraphModel.prototype.isCreateIds = function()
{
return this.createIds;
};
/**
* Function: setCreateIds
*
* Sets <createIds>.
*/
mxGraphModel.prototype.setCreateIds = function(value)
{
this.createIds = value;
};
/**
* Function: createRoot
*
* Creates a new root cell with a default layer (child 0).
*/
mxGraphModel.prototype.createRoot = function()
{
var cell = new mxCell();
cell.insert(new mxCell());
return cell;
};
/**
* Function: getCell
*
* Returns the <mxCell> for the specified Id or null if no cell can be
* found for the given Id.
*
* Parameters:
*
* id - A string representing the Id of the cell.
*/
mxGraphModel.prototype.getCell = function(id)
{
return (this.cells != null) ? this.cells[id] : null;
};
/**
* Function: filterCells
*
* Returns the cells from the given array where the given filter function
* returns true.
*/
mxGraphModel.prototype.filterCells = function(cells, filter)
{
var result = null;
if (cells != null)
{
result = [];
for (var i = 0; i < cells.length; i++)
{
if (filter(cells[i]))
{
result.push(cells[i]);
}
}
}
return result;
};
/**
* Function: getDescendants
*
* Returns all descendants of the given cell and the cell itself in an array.
*
* Parameters:
*
* parent - <mxCell> whose descendants should be returned.
*/
mxGraphModel.prototype.getDescendants = function(parent)
{
return this.filterDescendants(null, parent);
};
/**
* Function: filterDescendants
*
* Visits all cells recursively and applies the specified filter function
* to each cell. If the function returns true then the cell is added
* to the resulting array. The parent and result paramters are optional.
* If parent is not specified then the recursion starts at <root>.
*
* Example:
* The following example extracts all vertices from a given model:
* (code)
* var filter = function(cell)
* {
* return model.isVertex(cell);
* }
* var vertices = model.filterDescendants(filter);
* (end)
*
* Parameters:
*
* filter - JavaScript function that takes an <mxCell> as an argument
* and returns a boolean.
* parent - Optional <mxCell> that is used as the root of the recursion.
*/
mxGraphModel.prototype.filterDescendants = function(filter, parent)
{
// Creates a new array for storing the result
var result = [];
// Recursion starts at the root of the model
parent = parent || this.getRoot();
// Checks if the filter returns true for the cell
// and adds it to the result array
if (filter == null || filter(parent))
{
result.push(parent);
}
// Visits the children of the cell
var childCount = this.getChildCount(parent);
for (var i = 0; i < childCount; i++)
{
var child = this.getChildAt(parent, i);
result = result.concat(this.filterDescendants(filter, child));
}
return result;
};
/**
* Function: getRoot
*
* Returns the root of the model or the topmost parent of the given cell.
*
* Parameters:
*
* cell - Optional <mxCell> that specifies the child.
*/
mxGraphModel.prototype.getRoot = function(cell)
{
var root = cell || this.root;
if (cell != null)
{
while (cell != null)
{
root = cell;
cell = this.getParent(cell);
}
}
return root;
};
/**
* Function: setRoot
*
* Sets the <root> of the model using <mxRootChange> and adds the change to
* the current transaction. This resets all datastructures in the model and
* is the preferred way of clearing an existing model. Returns the new
* root.
*
* Example:
*
* (code)
* var root = new mxCell();
* root.insert(new mxCell());
* model.setRoot(root);
* (end)
*
* Parameters:
*
* root - <mxCell> that specifies the new root.
*/
mxGraphModel.prototype.setRoot = function(root)
{
this.execute(new mxRootChange(this, root));
return root;
};
/**
* Function: rootChanged
*
* Inner callback to change the root of the model and update the internal
* datastructures, such as <cells> and <nextId>. Returns the previous root.
*
* Parameters:
*
* root - <mxCell> that specifies the new root.
*/
mxGraphModel.prototype.rootChanged = function(root)
{
var oldRoot = this.root;
this.root = root;
// Resets counters and datastructures
this.nextId = 0;
this.cells = null;
this.cellAdded(root);
return oldRoot;
};
/**
* Function: isRoot
*
* Returns true if the given cell is the root of the model and a non-null
* value.
*
* Parameters:
*
* cell - <mxCell> that represents the possible root.
*/
mxGraphModel.prototype.isRoot = function(cell)
{
return cell != null && this.root == cell;
};
/**
* Function: isLayer
*
* Returns true if <isRoot> returns true for the parent of the given cell.
*
* Parameters:
*
* cell - <mxCell> that represents the possible layer.
*/
mxGraphModel.prototype.isLayer = function(cell)
{
return this.isRoot(this.getParent(cell));
};
/**
* Function: isAncestor
*
* Returns true if the given parent is an ancestor of the given child. Note
* returns true if child == parent.
*
* Parameters:
*
* parent - <mxCell> that specifies the parent.
* child - <mxCell> that specifies the child.
*/
mxGraphModel.prototype.isAncestor = function(parent, child)
{
while (child != null && child != parent)
{
child = this.getParent(child);
}
return child == parent;
};
/**
* Function: contains
*
* Returns true if the model contains the given <mxCell>.
*
* Parameters:
*
* cell - <mxCell> that specifies the cell.
*/
mxGraphModel.prototype.contains = function(cell)
{
return this.isAncestor(this.root, cell);
};
/**
* Function: getParent
*
* Returns the parent of the given cell.
*
* Parameters:
*
* cell - <mxCell> whose parent should be returned.
*/
mxGraphModel.prototype.getParent = function(cell)
{
return (cell != null) ? cell.getParent() : null;
};
/**
* Function: add
*
* Adds the specified child to the parent at the given index using
* <mxChildChange> and adds the change to the current transaction. If no
* index is specified then the child is appended to the parent's array of
* children. Returns the inserted child.
*
* Parameters:
*
* parent - <mxCell> that specifies the parent to contain the child.
* child - <mxCell> that specifies the child to be inserted.
* index - Optional integer that specifies the index of the child.
*/
mxGraphModel.prototype.add = function(parent, child, index)
{
if (child != parent && parent != null && child != null)
{
// Appends the child if no index was specified
if (index == null)
{
index = this.getChildCount(parent);
}
var parentChanged = parent != this.getParent(child);
this.execute(new mxChildChange(this, parent, child, index));
// Maintains the edges parents by moving the edges
// into the nearest common ancestor of its terminals
if (this.maintainEdgeParent && parentChanged)
{
this.updateEdgeParents(child);
}
}
return child;
};
/**
* Function: cellAdded
*
* Inner callback to update <cells> when a cell has been added. This
* implementation resolves collisions by creating new Ids. To change the
* ID of a cell after it was inserted into the model, use the following
* code:
*
* (code
* delete model.cells[cell.getId()];
* cell.setId(newId);
* model.cells[cell.getId()] = cell;
* (end)
*
* If the change of the ID should be part of the command history, then the
* cell should be removed from the model and a clone with the new ID should
* be reinserted into the model instead.
*
* Parameters:
*
* cell - <mxCell> that specifies the cell that has been added.
*/
mxGraphModel.prototype.cellAdded = function(cell)
{
if (cell != null)
{
// Creates an Id for the cell if not Id exists
if (cell.getId() == null && this.createIds)
{
cell.setId(this.createId(cell));
}
if (cell.getId() != null)
{
var collision = this.getCell(cell.getId());
if (collision != cell)
{
// Creates new Id for the cell
// as long as there is a collision
while (collision != null)
{
cell.setId(this.createId(cell));
collision = this.getCell(cell.getId());
}
// Lazily creates the cells dictionary
if (this.cells == null)
{
this.cells = new Object();
}
this.cells[cell.getId()] = cell;
}
}
// Makes sure IDs of deleted cells are not reused
if (mxUtils.isNumeric(cell.getId()))
{
this.nextId = Math.max(this.nextId, cell.getId());
}
// Recursively processes child cells
var childCount = this.getChildCount(cell);
for (var i=0; i<childCount; i++)
{
this.cellAdded(this.getChildAt(cell, i));
}
}
};
/**
* Function: createId
*
* Hook method to create an Id for the specified cell. This implementation
* concatenates <prefix>, id and <postfix> to create the Id and increments
* <nextId>. The cell is ignored by this implementation, but can be used in
* overridden methods to prefix the Ids with eg. the cell type.
*
* Parameters:
*
* cell - <mxCell> to create the Id for.
*/
mxGraphModel.prototype.createId = function(cell)
{
var id = this.nextId;
this.nextId++;
return this.prefix + id + this.postfix;
};
/**
* Function: updateEdgeParents
*
* Updates the parent for all edges that are connected to cell or one of
* its descendants using <updateEdgeParent>.
*/
mxGraphModel.prototype.updateEdgeParents = function(cell, root)
{
// Gets the topmost node of the hierarchy
root = root || this.getRoot(cell);
// Updates edges on children first
var childCount = this.getChildCount(cell);
for (var i = 0; i < childCount; i++)
{
var child = this.getChildAt(cell, i);
this.updateEdgeParents(child, root);
}
// Updates the parents of all connected edges
var edgeCount = this.getEdgeCount(cell);
var edges = [];
for (var i = 0; i < edgeCount; i++)
{
edges.push(this.getEdgeAt(cell, i));
}
for (var i = 0; i < edges.length; i++)
{
var edge = edges[i];
// Updates edge parent if edge and child have
// a common root node (does not need to be the
// model root node)
if (this.isAncestor(root, edge))
{
this.updateEdgeParent(edge, root);
}
}
};
/**
* Function: updateEdgeParent
*
* Inner callback to update the parent of the specified <mxCell> to the
* nearest-common-ancestor of its two terminals.
*
* Parameters:
*
* edge - <mxCell> that specifies the edge.
* root - <mxCell> that represents the current root of the model.
*/
mxGraphModel.prototype.updateEdgeParent = function(edge, root)
{
var source = this.getTerminal(edge, true);
var target = this.getTerminal(edge, false);
var cell = null;
// Uses the first non-relative descendants of the source terminal
while (source != null && !this.isEdge(source) &&
source.geometry != null && source.geometry.relative)
{
source = this.getParent(source);
}
// Uses the first non-relative descendants of the target terminal
while (target != null && this.ignoreRelativeEdgeParent &&
!this.isEdge(target) && target.geometry != null &&
target.geometry.relative)
{
target = this.getParent(target);
}
if (this.isAncestor(root, source) && this.isAncestor(root, target))
{
if (source == target)
{
cell = this.getParent(source);
}
else
{
cell = this.getNearestCommonAncestor(source, target);
}
if (cell != null && (this.getParent(cell) != this.root ||
this.isAncestor(cell, edge)) && this.getParent(edge) != cell)
{
var geo = this.getGeometry(edge);
if (geo != null)
{
var origin1 = this.getOrigin(this.getParent(edge));
var origin2 = this.getOrigin(cell);
var dx = origin2.x - origin1.x;
var dy = origin2.y - origin1.y;
geo = geo.clone();
geo.translate(-dx, -dy);
this.setGeometry(edge, geo);
}
this.add(cell, edge, this.getChildCount(cell));
}
}
};
/**
* Function: getOrigin
*
* Returns the absolute, accumulated origin for the children inside the
* given parent as an <mxPoint>.
*/
mxGraphModel.prototype.getOrigin = function(cell)
{
var result = null;
if (cell != null)
{
result = this.getOrigin(this.getParent(cell));
if (!this.isEdge(cell))
{
var geo = this.getGeometry(cell);
if (geo != null)
{
result.x += geo.x;
result.y += geo.y;
}
}
}
else
{
result = new mxPoint();
}
return result;
};
/**
* Function: getNearestCommonAncestor
*
* Returns the nearest common ancestor for the specified cells.
*
* Parameters:
*
* cell1 - <mxCell> that specifies the first cell in the tree.
* cell2 - <mxCell> that specifies the second cell in the tree.
*/
mxGraphModel.prototype.getNearestCommonAncestor = function(cell1, cell2)
{
if (cell1 != null && cell2 != null)
{
// Creates the cell path for the second cell
var path = mxCellPath.create(cell2);
if (path != null && path.length > 0)
{
// Bubbles through the ancestors of the first
// cell to find the nearest common ancestor.
var cell = cell1;
var current = mxCellPath.create(cell);
// Inverts arguments
if (path.length < current.length)
{
cell = cell2;
var tmp = current;
current = path;
path = tmp;
}
while (cell != null)
{
var parent = this.getParent(cell);
// Checks if the cell path is equal to the beginning of the given cell path
if (path.indexOf(current + mxCellPath.PATH_SEPARATOR) == 0 && parent != null)
{
return cell;
}
current = mxCellPath.getParentPath(current);
cell = parent;
}
}
}
return null;
};
/**
* Function: remove
*
* Removes the specified cell from the model using <mxChildChange> and adds
* the change to the current transaction. This operation will remove the
* cell and all of its children from the model. Returns the removed cell.
*
* Parameters:
*
* cell - <mxCell> that should be removed.
*/
mxGraphModel.prototype.remove = function(cell)
{
if (cell == this.root)
{
this.setRoot(null);
}
else if (this.getParent(cell) != null)
{
this.execute(new mxChildChange(this, null, cell));
}
return cell;
};
/**
* Function: cellRemoved
*
* Inner callback to update <cells> when a cell has been removed.
*
* Parameters:
*
* cell - <mxCell> that specifies the cell that has been removed.
*/
mxGraphModel.prototype.cellRemoved = function(cell)
{
if (cell != null && this.cells != null)
{
// Recursively processes child cells
var childCount = this.getChildCount(cell);
for (var i = childCount - 1; i >= 0; i--)
{
this.cellRemoved(this.getChildAt(cell, i));
}
// Removes the dictionary entry for the cell
if (this.cells != null && cell.getId() != null)
{
delete this.cells[cell.getId()];
}
}
};
/**
* Function: parentForCellChanged
*
* Inner callback to update the parent of a cell using <mxCell.insert>
* on the parent and return the previous parent.
*
* Parameters:
*
* cell - <mxCell> to update the parent for.
* parent - <mxCell> that specifies the new parent of the cell.
* index - Optional integer that defines the index of the child
* in the parent's child array.
*/
mxGraphModel.prototype.parentForCellChanged = function(cell, parent, index)
{
var previous = this.getParent(cell);
if (parent != null)
{
if (parent != previous || previous.getIndex(cell) != index)
{
parent.insert(cell, index);
}
}
else if (previous != null)
{
var oldIndex = previous.getIndex(cell);
previous.remove(oldIndex);
}
// Adds or removes the cell from the model
var par = this.contains(parent);
var pre = this.contains(previous);
if (par && !pre)
{
this.cellAdded(cell);
}
else if (pre && !par)
{
this.cellRemoved(cell);
}
return previous;
};
/**
* Function: getChildCount
*
* Returns the number of children in the given cell.
*
* Parameters:
*
* cell - <mxCell> whose number of children should be returned.
*/
mxGraphModel.prototype.getChildCount = function(cell)
{
return (cell != null) ? cell.getChildCount() : 0;
};
/**
* Function: getChildAt
*
* Returns the child of the given <mxCell> at the given index.
*
* Parameters:
*
* cell - <mxCell> that represents the parent.
* index - Integer that specifies the index of the child to be returned.
*/
mxGraphModel.prototype.getChildAt = function(cell, index)
{
return (cell != null) ? cell.getChildAt(index) : null;
};
/**
* Function: getChildren
*
* Returns all children of the given <mxCell> as an array of <mxCells>. The
* return value should be only be read.
*
* Parameters:
*
* cell - <mxCell> the represents the parent.
*/
mxGraphModel.prototype.getChildren = function(cell)
{
return (cell != null) ? cell.children : null;
};
/**
* Function: getChildVertices
*
* Returns the child vertices of the given parent.
*
* Parameters:
*
* cell - <mxCell> whose child vertices should be returned.
*/
mxGraphModel.prototype.getChildVertices = function(parent)
{
return this.getChildCells(parent, true, false);
};
/**
* Function: getChildEdges
*
* Returns the child edges of the given parent.
*
* Parameters:
*
* cell - <mxCell> whose child edges should be returned.
*/
mxGraphModel.prototype.getChildEdges = function(parent)
{
return this.getChildCells(parent, false, true);
};
/**
* Function: getChildCells
*
* Returns the children of the given cell that are vertices and/or edges
* depending on the arguments.
*
* Parameters:
*
* cell - <mxCell> the represents the parent.
* vertices - Boolean indicating if child vertices should be returned.
* Default is false.
* edges - Boolean indicating if child edges should be returned.
* Default is false.
*/
mxGraphModel.prototype.getChildCells = function(parent, vertices, edges)
{
vertices = (vertices != null) ? vertices : false;
edges = (edges != null) ? edges : false;
var childCount = this.getChildCount(parent);
var result = [];
for (var i = 0; i < childCount; i++)
{
var child = this.getChildAt(parent, i);
if ((!edges && !vertices) || (edges && this.isEdge(child)) ||
(vertices && this.isVertex(child)))
{
result.push(child);
}
}
return result;
};
/**
* Function: getTerminal
*
* Returns the source or target <mxCell> of the given edge depending on the
* value of the boolean parameter.
*
* Parameters:
*
* edge - <mxCell> that specifies the edge.
* isSource - Boolean indicating which end of the edge should be returned.
*/
mxGraphModel.prototype.getTerminal = function(edge, isSource)
{
return (edge != null) ? edge.getTerminal(isSource) : null;
};
/**
* Function: setTerminal
*
* Sets the source or target terminal of the given <mxCell> using
* <mxTerminalChange> and adds the change to the current transaction.
* This implementation updates the parent of the edge using <updateEdgeParent>
* if required.
*
* Parameters:
*
* edge - <mxCell> that specifies the edge.
* terminal - <mxCell> that specifies the new terminal.
* isSource - Boolean indicating if the terminal is the new source or
* target terminal of the edge.
*/
mxGraphModel.prototype.setTerminal = function(edge, terminal, isSource)
{
var terminalChanged = terminal != this.getTerminal(edge, isSource);
this.execute(new mxTerminalChange(this, edge, terminal, isSource));
if (this.maintainEdgeParent && terminalChanged)
{
this.updateEdgeParent(edge, this.getRoot());
}
return terminal;
};
/**
* Function: setTerminals
*
* Sets the source and target <mxCell> of the given <mxCell> in a single
* transaction using <setTerminal> for each end of the edge.
*
* Parameters:
*
* edge - <mxCell> that specifies the edge.
* source - <mxCell> that specifies the new source terminal.
* target - <mxCell> that specifies the new target terminal.
*/
mxGraphModel.prototype.setTerminals = function(edge, source, target)
{
this.beginUpdate();
try
{
this.setTerminal(edge, source, true);
this.setTerminal(edge, target, false);
}
finally
{
this.endUpdate();
}
};
/**
* Function: terminalForCellChanged
*
* Inner helper function to update the terminal of the edge using
* <mxCell.insertEdge> and return the previous terminal.
*
* Parameters:
*
* edge - <mxCell> that specifies the edge to be updated.
* terminal - <mxCell> that specifies the new terminal.
* isSource - Boolean indicating if the terminal is the new source or
* target terminal of the edge.
*/
mxGraphModel.prototype.terminalForCellChanged = function(edge, terminal, isSource)
{
var previous = this.getTerminal(edge, isSource);
if (terminal != null)
{
terminal.insertEdge(edge, isSource);
}
else if (previous != null)
{
previous.removeEdge(edge, isSource);
}
return previous;
};
/**
* Function: getEdgeCount
*
* Returns the number of distinct edges connected to the given cell.
*
* Parameters:
*
* cell - <mxCell> that represents the vertex.
*/
mxGraphModel.prototype.getEdgeCount = function(cell)
{
return (cell != null) ? cell.getEdgeCount() : 0;
};
/**
* Function: getEdgeAt
*
* Returns the edge of cell at the given index.
*
* Parameters:
*
* cell - <mxCell> that specifies the vertex.
* index - Integer that specifies the index of the edge
* to return.
*/
mxGraphModel.prototype.getEdgeAt = function(cell, index)
{
return (cell != null) ? cell.getEdgeAt(index) : null;
};
/**
* Function: getDirectedEdgeCount
*
* Returns the number of incoming or outgoing edges, ignoring the given
* edge.
*
* Parameters:
*
* cell - <mxCell> whose edge count should be returned.
* outgoing - Boolean that specifies if the number of outgoing or
* incoming edges should be returned.
* ignoredEdge - <mxCell> that represents an edge to be ignored.
*/
mxGraphModel.prototype.getDirectedEdgeCount = function(cell, outgoing, ignoredEdge)
{
var count = 0;
var edgeCount = this.getEdgeCount(cell);
for (var i = 0; i < edgeCount; i++)
{
var edge = this.getEdgeAt(cell, i);
if (edge != ignoredEdge && this.getTerminal(edge, outgoing) == cell)
{
count++;
}
}
return count;
};
/**
* Function: getConnections
*
* Returns all edges of the given cell without loops.
*
* Parameters:
*
* cell - <mxCell> whose edges should be returned.
*
*/
mxGraphModel.prototype.getConnections = function(cell)
{
return this.getEdges(cell, true, true, false);
};
/**
* Function: getIncomingEdges
*
* Returns the incoming edges of the given cell without loops.
*
* Parameters:
*
* cell - <mxCell> whose incoming edges should be returned.
*
*/
mxGraphModel.prototype.getIncomingEdges = function(cell)
{
return this.getEdges(cell, true, false, false);
};
/**
* Function: getOutgoingEdges
*
* Returns the outgoing edges of the given cell without loops.
*
* Parameters:
*
* cell - <mxCell> whose outgoing edges should be returned.
*
*/
mxGraphModel.prototype.getOutgoingEdges = function(cell)
{
return this.getEdges(cell, false, true, false);
};
/**
* Function: getEdges
*
* Returns all distinct edges connected to this cell as a new array of
* <mxCells>. If at least one of incoming or outgoing is true, then loops
* are ignored, otherwise if both are false, then all edges connected to
* the given cell are returned including loops.
*
* Parameters:
*
* cell - <mxCell> that specifies the cell.
* incoming - Optional boolean that specifies if incoming edges should be
* returned. Default is true.
* outgoing - Optional boolean that specifies if outgoing edges should be
* returned. Default is true.
* includeLoops - Optional boolean that specifies if loops should be returned.
* Default is true.
*/
mxGraphModel.prototype.getEdges = function(cell, incoming, outgoing, includeLoops)
{
incoming = (incoming != null) ? incoming : true;
outgoing = (outgoing != null) ? outgoing : true;
includeLoops = (includeLoops != null) ? includeLoops : true;
var edgeCount = this.getEdgeCount(cell);
var result = [];
for (var i = 0; i < edgeCount; i++)
{
var edge = this.getEdgeAt(cell, i);
var source = this.getTerminal(edge, true);
var target = this.getTerminal(edge, false);
if ((includeLoops && source == target) || ((source != target) && ((incoming && target == cell) ||
(outgoing && source == cell))))
{
result.push(edge);
}
}
return result;
};
/**
* Function: getEdgesBetween
*
* Returns all edges between the given source and target pair. If directed
* is true, then only edges from the source to the target are returned,
* otherwise, all edges between the two cells are returned.
*
* Parameters:
*
* source - <mxCell> that defines the source terminal of the edge to be
* returned.
* target - <mxCell> that defines the target terminal of the edge to be
* returned.
* directed - Optional boolean that specifies if the direction of the
* edge should be taken into account. Default is false.
*/
mxGraphModel.prototype.getEdgesBetween = function(source, target, directed)
{
directed = (directed != null) ? directed : false;
var tmp1 = this.getEdgeCount(source);
var tmp2 = this.getEdgeCount(target);
// Assumes the source has less connected edges
var terminal = source;
var edgeCount = tmp1;
// Uses the smaller array of connected edges
// for searching the edge
if (tmp2 < tmp1)
{
edgeCount = tmp2;
terminal = target;
}
var result = [];
// Checks if the edge is connected to the correct
// cell and returns the first match
for (var i = 0; i < edgeCount; i++)
{
var edge = this.getEdgeAt(terminal, i);
var src = this.getTerminal(edge, true);
var trg = this.getTerminal(edge, false);
var directedMatch = (src == source) && (trg == target);
var oppositeMatch = (trg == source) && (src == target);
if (directedMatch || (!directed && oppositeMatch))
{
result.push(edge);
}
}
return result;
};
/**
* Function: getOpposites
*
* Returns all opposite vertices wrt terminal for the given edges, only
* returning sources and/or targets as specified. The result is returned
* as an array of <mxCells>.
*
* Parameters:
*
* edges - Array of <mxCells> that contain the edges to be examined.
* terminal - <mxCell> that specifies the known end of the edges.
* sources - Boolean that specifies if source terminals should be contained
* in the result. Default is true.
* targets - Boolean that specifies if target terminals should be contained
* in the result. Default is true.
*/
mxGraphModel.prototype.getOpposites = function(edges, terminal, sources, targets)
{
sources = (sources != null) ? sources : true;
targets = (targets != null) ? targets : true;
var terminals = [];
if (edges != null)
{
for (var i = 0; i < edges.length; i++)
{
var source = this.getTerminal(edges[i], true);
var target = this.getTerminal(edges[i], false);
// Checks if the terminal is the source of
// the edge and if the target should be
// stored in the result
if (source == terminal && target != null && target != terminal && targets)
{
terminals.push(target);
}
// Checks if the terminal is the taget of
// the edge and if the source should be
// stored in the result
else if (target == terminal && source != null && source != terminal && sources)
{
terminals.push(source);
}
}
}
return terminals;
};
/**
* Function: getTopmostCells
*
* Returns the topmost cells of the hierarchy in an array that contains no
* descendants for each <mxCell> that it contains. Duplicates should be
* removed in the cells array to improve performance.
*
* Parameters:
*
* cells - Array of <mxCells> whose topmost ancestors should be returned.
*/
mxGraphModel.prototype.getTopmostCells = function(cells)
{
var dict = new mxDictionary();
var tmp = [];
for (var i = 0; i < cells.length; i++)
{
dict.put(cells[i], true);
}
for (var i = 0; i < cells.length; i++)
{
var cell = cells[i];
var topmost = true;
var parent = this.getParent(cell);
while (parent != null)
{
if (dict.get(parent))
{
topmost = false;
break;
}
parent = this.getParent(parent);
}
if (topmost)
{
tmp.push(cell);
}
}
return tmp;
};
/**
* Function: isVertex
*
* Returns true if the given cell is a vertex.
*
* Parameters:
*
* cell - <mxCell> that represents the possible vertex.
*/
mxGraphModel.prototype.isVertex = function(cell)
{
return (cell != null) ? cell.isVertex() : false;
};
/**
* Function: isEdge
*
* Returns true if the given cell is an edge.
*
* Parameters:
*
* cell - <mxCell> that represents the possible edge.
*/
mxGraphModel.prototype.isEdge = function(cell)
{
return (cell != null) ? cell.isEdge() : false;
};
/**
* Function: isConnectable
*
* Returns true if the given <mxCell> is connectable. If <edgesConnectable>
* is false, then this function returns false for all edges else it returns
* the return value of <mxCell.isConnectable>.
*
* Parameters:
*
* cell - <mxCell> whose connectable state should be returned.
*/
mxGraphModel.prototype.isConnectable = function(cell)
{
return (cell != null) ? cell.isConnectable() : false;
};
/**
* Function: getValue
*
* Returns the user object of the given <mxCell> using <mxCell.getValue>.
*
* Parameters:
*
* cell - <mxCell> whose user object should be returned.
*/
mxGraphModel.prototype.getValue = function(cell)
{
return (cell != null) ? cell.getValue() : null;
};
/**
* Function: setValue
*
* Sets the user object of then given <mxCell> using <mxValueChange>
* and adds the change to the current transaction.
*
* Parameters:
*
* cell - <mxCell> whose user object should be changed.
* value - Object that defines the new user object.
*/
mxGraphModel.prototype.setValue = function(cell, value)
{
this.execute(new mxValueChange(this, cell, value));
return value;
};
/**
* Function: valueForCellChanged
*
* Inner callback to update the user object of the given <mxCell>
* using <mxCell.valueChanged> and return the previous value,
* that is, the return value of <mxCell.valueChanged>.
*
* To change a specific attribute in an XML node, the following code can be
* used.
*
* (code)
* graph.getModel().valueForCellChanged = function(cell, value)
* {
* var previous = cell.value.getAttribute('label');
* cell.value.setAttribute('label', value);
*
* return previous;
* };
* (end)
*/
mxGraphModel.prototype.valueForCellChanged = function(cell, value)
{
return cell.valueChanged(value);
};
/**
* Function: getGeometry
*
* Returns the <mxGeometry> of the given <mxCell>.
*
* Parameters:
*
* cell - <mxCell> whose geometry should be returned.
*/
mxGraphModel.prototype.getGeometry = function(cell)
{
return (cell != null) ? cell.getGeometry() : null;
};
/**
* Function: setGeometry
*
* Sets the <mxGeometry> of the given <mxCell>. The actual update
* of the cell is carried out in <geometryForCellChanged>. The
* <mxGeometryChange> action is used to encapsulate the change.
*
* Parameters:
*
* cell - <mxCell> whose geometry should be changed.
* geometry - <mxGeometry> that defines the new geometry.
*/
mxGraphModel.prototype.setGeometry = function(cell, geometry)
{
if (geometry != this.getGeometry(cell))
{
this.execute(new mxGeometryChange(this, cell, geometry));
}
return geometry;
};
/**
* Function: geometryForCellChanged
*
* Inner callback to update the <mxGeometry> of the given <mxCell> using
* <mxCell.setGeometry> and return the previous <mxGeometry>.
*/
mxGraphModel.prototype.geometryForCellChanged = function(cell, geometry)
{
var previous = this.getGeometry(cell);
cell.setGeometry(geometry);
return previous;
};
/**
* Function: getStyle
*
* Returns the style of the given <mxCell>.
*
* Parameters:
*
* cell - <mxCell> whose style should be returned.
*/
mxGraphModel.prototype.getStyle = function(cell)
{
return (cell != null) ? cell.getStyle() : null;
};
/**
* Function: setStyle
*
* Sets the style of the given <mxCell> using <mxStyleChange> and
* adds the change to the current transaction.
*
* Parameters:
*
* cell - <mxCell> whose style should be changed.
* style - String of the form [stylename;|key=value;] to specify
* the new cell style.
*/
mxGraphModel.prototype.setStyle = function(cell, style)
{
if (style != this.getStyle(cell))
{
this.execute(new mxStyleChange(this, cell, style));
}
return style;
};
/**
* Function: styleForCellChanged
*
* Inner callback to update the style of the given <mxCell>
* using <mxCell.setStyle> and return the previous style.
*
* Parameters:
*
* cell - <mxCell> that specifies the cell to be updated.
* style - String of the form [stylename;|key=value;] to specify
* the new cell style.
*/
mxGraphModel.prototype.styleForCellChanged = function(cell, style)
{
var previous = this.getStyle(cell);
cell.setStyle(style);
return previous;
};
/**
* Function: isCollapsed
*
* Returns true if the given <mxCell> is collapsed.
*
* Parameters:
*
* cell - <mxCell> whose collapsed state should be returned.
*/
mxGraphModel.prototype.isCollapsed = function(cell)
{
return (cell != null) ? cell.isCollapsed() : false;
};
/**
* Function: setCollapsed
*
* Sets the collapsed state of the given <mxCell> using <mxCollapseChange>
* and adds the change to the current transaction.
*
* Parameters:
*
* cell - <mxCell> whose collapsed state should be changed.
* collapsed - Boolean that specifies the new collpased state.
*/
mxGraphModel.prototype.setCollapsed = function(cell, collapsed)
{
if (collapsed != this.isCollapsed(cell))
{
this.execute(new mxCollapseChange(this, cell, collapsed));
}
return collapsed;
};
/**
* Function: collapsedStateForCellChanged
*
* Inner callback to update the collapsed state of the
* given <mxCell> using <mxCell.setCollapsed> and return
* the previous collapsed state.
*
* Parameters:
*
* cell - <mxCell> that specifies the cell to be updated.
* collapsed - Boolean that specifies the new collpased state.
*/
mxGraphModel.prototype.collapsedStateForCellChanged = function(cell, collapsed)
{
var previous = this.isCollapsed(cell);
cell.setCollapsed(collapsed);
return previous;
};
/**
* Function: isVisible
*
* Returns true if the given <mxCell> is visible.
*
* Parameters:
*
* cell - <mxCell> whose visible state should be returned.
*/
mxGraphModel.prototype.isVisible = function(cell)
{
return (cell != null) ? cell.isVisible() : false;
};
/**
* Function: setVisible
*
* Sets the visible state of the given <mxCell> using <mxVisibleChange> and
* adds the change to the current transaction.
*
* Parameters:
*
* cell - <mxCell> whose visible state should be changed.
* visible - Boolean that specifies the new visible state.
*/
mxGraphModel.prototype.setVisible = function(cell, visible)
{
if (visible != this.isVisible(cell))
{
this.execute(new mxVisibleChange(this, cell, visible));
}
return visible;
};
/**
* Function: visibleStateForCellChanged
*
* Inner callback to update the visible state of the
* given <mxCell> using <mxCell.setCollapsed> and return
* the previous visible state.
*
* Parameters:
*
* cell - <mxCell> that specifies the cell to be updated.
* visible - Boolean that specifies the new visible state.
*/
mxGraphModel.prototype.visibleStateForCellChanged = function(cell, visible)
{
var previous = this.isVisible(cell);
cell.setVisible(visible);
return previous;
};
/**
* Function: execute
*
* Executes the given edit and fires events if required. The edit object
* requires an execute function which is invoked. The edit is added to the
* <currentEdit> between <beginUpdate> and <endUpdate> calls, so that
* events will be fired if this execute is an individual transaction, that
* is, if no previous <beginUpdate> calls have been made without calling
* <endUpdate>. This implementation fires an <execute> event before
* executing the given change.
*
* Parameters:
*
* change - Object that described the change.
*/
mxGraphModel.prototype.execute = function(change)
{
change.execute();
this.beginUpdate();
this.currentEdit.add(change);
this.fireEvent(new mxEventObject(mxEvent.EXECUTE, 'change', change));
// New global executed event
this.fireEvent(new mxEventObject(mxEvent.EXECUTED, 'change', change));
this.endUpdate();
};
/**
* Function: beginUpdate
*
* Increments the <updateLevel> by one. The event notification
* is queued until <updateLevel> reaches 0 by use of
* <endUpdate>.
*
* All changes on <mxGraphModel> are transactional,
* that is, they are executed in a single undoable change
* on the model (without transaction isolation).
* Therefore, if you want to combine any
* number of changes into a single undoable change,
* you should group any two or more API calls that
* modify the graph model between <beginUpdate>
* and <endUpdate> calls as shown here:
*
* (code)
* var model = graph.getModel();
* var parent = graph.getDefaultParent();
* var index = model.getChildCount(parent);
* model.beginUpdate();
* try
* {
* model.add(parent, v1, index);
* model.add(parent, v2, index+1);
* }
* finally
* {
* model.endUpdate();
* }
* (end)
*
* Of course there is a shortcut for appending a
* sequence of cells into the default parent:
*
* (code)
* graph.addCells([v1, v2]).
* (end)
*/
mxGraphModel.prototype.beginUpdate = function()
{
this.updateLevel++;
this.fireEvent(new mxEventObject(mxEvent.BEGIN_UPDATE));
if (this.updateLevel == 1)
{
this.fireEvent(new mxEventObject(mxEvent.START_EDIT));
}
};
/**
* Function: endUpdate
*
* Decrements the <updateLevel> by one and fires an <undo>
* event if the <updateLevel> reaches 0. This function
* indirectly fires a <change> event by invoking the notify
* function on the <currentEdit> und then creates a new
* <currentEdit> using <createUndoableEdit>.
*
* The <undo> event is fired only once per edit, whereas
* the <change> event is fired whenever the notify
* function is invoked, that is, on undo and redo of
* the edit.
*/
mxGraphModel.prototype.endUpdate = function()
{
this.updateLevel--;
if (this.updateLevel == 0)
{
this.fireEvent(new mxEventObject(mxEvent.END_EDIT));
}
if (!this.endingUpdate)
{
this.endingUpdate = this.updateLevel == 0;
this.fireEvent(new mxEventObject(mxEvent.END_UPDATE, 'edit', this.currentEdit));
try
{
if (this.endingUpdate && !this.currentEdit.isEmpty())
{
this.fireEvent(new mxEventObject(mxEvent.BEFORE_UNDO, 'edit', this.currentEdit));
var tmp = this.currentEdit;
this.currentEdit = this.createUndoableEdit();
tmp.notify();
this.fireEvent(new mxEventObject(mxEvent.UNDO, 'edit', tmp));
}
}
finally
{
this.endingUpdate = false;
}
}
};
/**
* Function: createUndoableEdit
*
* Creates a new <mxUndoableEdit> that implements the
* notify function to fire a <change> and <notify> event
* through the <mxUndoableEdit>'s source.
*
* Parameters:
*
* significant - Optional boolean that specifies if the edit to be created is
* significant. Default is true.
*/
mxGraphModel.prototype.createUndoableEdit = function(significant)
{
var edit = new mxUndoableEdit(this, (significant != null) ? significant : true);
edit.notify = function()
{
// LATER: Remove changes property (deprecated)
edit.source.fireEvent(new mxEventObject(mxEvent.CHANGE,
'edit', edit, 'changes', edit.changes));
edit.source.fireEvent(new mxEventObject(mxEvent.NOTIFY,
'edit', edit, 'changes', edit.changes));
};
return edit;
};
/**
* Function: mergeChildren
*
* Merges the children of the given cell into the given target cell inside
* this model. All cells are cloned unless there is a corresponding cell in
* the model with the same id, in which case the source cell is ignored and
* all edges are connected to the corresponding cell in this model. Edges
* are considered to have no identity and are always cloned unless the
* cloneAllEdges flag is set to false, in which case edges with the same
* id in the target model are reconnected to reflect the terminals of the
* source edges.
*/
mxGraphModel.prototype.mergeChildren = function(from, to, cloneAllEdges)
{
cloneAllEdges = (cloneAllEdges != null) ? cloneAllEdges : true;
this.beginUpdate();
try
{
var mapping = new Object();
this.mergeChildrenImpl(from, to, cloneAllEdges, mapping);
// Post-processes all edges in the mapping and
// reconnects the terminals to the corresponding
// cells in the target model
for (var key in mapping)
{
var cell = mapping[key];
var terminal = this.getTerminal(cell, true);
if (terminal != null)
{
terminal = mapping[mxCellPath.create(terminal)];
this.setTerminal(cell, terminal, true);
}
terminal = this.getTerminal(cell, false);
if (terminal != null)
{
terminal = mapping[mxCellPath.create(terminal)];
this.setTerminal(cell, terminal, false);
}
}
}
finally
{
this.endUpdate();
}
};
/**
* Function: mergeChildren
*
* Clones the children of the source cell into the given target cell in
* this model and adds an entry to the mapping that maps from the source
* cell to the target cell with the same id or the clone of the source cell
* that was inserted into this model.
*/
mxGraphModel.prototype.mergeChildrenImpl = function(from, to, cloneAllEdges, mapping)
{
this.beginUpdate();
try
{
var childCount = from.getChildCount();
for (var i = 0; i < childCount; i++)
{
var cell = from.getChildAt(i);
if (typeof(cell.getId) == 'function')
{
var id = cell.getId();
var target = (id != null && (!this.isEdge(cell) || !cloneAllEdges)) ?
this.getCell(id) : null;
// Clones and adds the child if no cell exists for the id
if (target == null)
{
var clone = cell.clone();
clone.setId(id);
// Sets the terminals from the original cell to the clone
// because the lookup uses strings not cells in JS
clone.setTerminal(cell.getTerminal(true), true);
clone.setTerminal(cell.getTerminal(false), false);
// Do *NOT* use model.add as this will move the edge away
// from the parent in updateEdgeParent if maintainEdgeParent
// is enabled in the target model
target = to.insert(clone);
this.cellAdded(target);
}
// Stores the mapping for later reconnecting edges
mapping[mxCellPath.create(cell)] = target;
// Recurses
this.mergeChildrenImpl(cell, target, cloneAllEdges, mapping);
}
}
}
finally
{
this.endUpdate();
}
};
/**
* Function: getParents
*
* Returns an array that represents the set (no duplicates) of all parents
* for the given array of cells.
*
* Parameters:
*
* cells - Array of cells whose parents should be returned.
*/
mxGraphModel.prototype.getParents = function(cells)
{
var parents = [];
if (cells != null)
{
var dict = new mxDictionary();
for (var i = 0; i < cells.length; i++)
{
var parent = this.getParent(cells[i]);
if (parent != null && !dict.get(parent))
{
dict.put(parent, true);
parents.push(parent);
}
}
}
return parents;
};
//
// Cell Cloning
//
/**
* Function: cloneCell
*
* Returns a deep clone of the given <mxCell> (including
* the children) which is created using <cloneCells>.
*
* Parameters:
*
* cell - <mxCell> to be cloned.
*/
mxGraphModel.prototype.cloneCell = function(cell)
{
if (cell != null)
{
return this.cloneCells([cell], true)[0];
}
return null;
};
/**
* Function: cloneCells
*
* Returns an array of clones for the given array of <mxCells>.
* Depending on the value of includeChildren, a deep clone is created for
* each cell. Connections are restored based if the corresponding
* cell is contained in the passed in array.
*
* Parameters:
*
* cells - Array of <mxCell> to be cloned.
* includeChildren - Boolean indicating if the cells should be cloned
* with all descendants.
* mapping - Optional mapping for existing clones.
*/
mxGraphModel.prototype.cloneCells = function(cells, includeChildren, mapping)
{
mapping = (mapping != null) ? mapping : new Object();
var clones = [];
for (var i = 0; i < cells.length; i++)
{
if (cells[i] != null)
{
clones.push(this.cloneCellImpl(cells[i], mapping, includeChildren));
}
else
{
clones.push(null);
}
}
for (var i = 0; i < clones.length; i++)
{
if (clones[i] != null)
{
this.restoreClone(clones[i], cells[i], mapping);
}
}
return clones;
};
/**
* Function: cloneCellImpl
*
* Inner helper method for cloning cells recursively.
*/
mxGraphModel.prototype.cloneCellImpl = function(cell, mapping, includeChildren)
{
var ident = mxObjectIdentity.get(cell);
var clone = mapping[ident];
if (clone == null)
{
clone = this.cellCloned(cell);
mapping[ident] = clone;
if (includeChildren)
{
var childCount = this.getChildCount(cell);
for (var i = 0; i < childCount; i++)
{
var cloneChild = this.cloneCellImpl(
this.getChildAt(cell, i), mapping, true);
clone.insert(cloneChild);
}
}
}
return clone;
};
/**
* Function: cellCloned
*
* Hook for cloning the cell. This returns cell.clone() or
* any possible exceptions.
*/
mxGraphModel.prototype.cellCloned = function(cell)
{
return cell.clone();
};
/**
* Function: restoreClone
*
* Inner helper method for restoring the connections in
* a network of cloned cells.
*/
mxGraphModel.prototype.restoreClone = function(clone, cell, mapping)
{
var source = this.getTerminal(cell, true);
if (source != null)
{
var tmp = mapping[mxObjectIdentity.get(source)];
if (tmp != null)
{
tmp.insertEdge(clone, true);
}
}
var target = this.getTerminal(cell, false);
if (target != null)
{
var tmp = mapping[mxObjectIdentity.get(target)];
if (tmp != null)
{
tmp.insertEdge(clone, false);
}
}
var childCount = this.getChildCount(clone);
for (var i = 0; i < childCount; i++)
{
this.restoreClone(this.getChildAt(clone, i),
this.getChildAt(cell, i), mapping);
}
};
//
// Atomic changes
//
/**
* Class: mxRootChange
*
* Action to change the root in a model.
*
* Constructor: mxRootChange
*
* Constructs a change of the root in the
* specified model.
*/
function mxRootChange(model, root)
{
this.model = model;
this.root = root;
this.previous = root;
};
/**
* Function: execute
*
* Carries out a change of the root using
* <mxGraphModel.rootChanged>.
*/
mxRootChange.prototype.execute = function()
{
this.root = this.previous;
this.previous = this.model.rootChanged(this.previous);
};
/**
* Class: mxChildChange
*
* Action to add or remove a child in a model.
*
* Constructor: mxChildChange
*
* Constructs a change of a child in the
* specified model.
*/
function mxChildChange(model, parent, child, index)
{
this.model = model;
this.parent = parent;
this.previous = parent;
this.child = child;
this.index = index;
this.previousIndex = index;
};
/**
* Function: execute
*
* Changes the parent of <child> using
* <mxGraphModel.parentForCellChanged> and
* removes or restores the cell's
* connections.
*/
mxChildChange.prototype.execute = function()
{
if (this.child != null)
{
var tmp = this.model.getParent(this.child);
var tmp2 = (tmp != null) ? tmp.getIndex(this.child) : 0;
if (this.previous == null)
{
this.connect(this.child, false);
}
tmp = this.model.parentForCellChanged(
this.child, this.previous, this.previousIndex);
if (this.previous != null)
{
this.connect(this.child, true);
}
this.parent = this.previous;
this.previous = tmp;
this.index = this.previousIndex;
this.previousIndex = tmp2;
}
};
/**
* Function: disconnect
*
* Disconnects the given cell recursively from its
* terminals and stores the previous terminal in the
* cell's terminals.
*/
mxChildChange.prototype.connect = function(cell, isConnect)
{
isConnect = (isConnect != null) ? isConnect : true;
var source = cell.getTerminal(true);
var target = cell.getTerminal(false);
if (source != null)
{
if (isConnect)
{
this.model.terminalForCellChanged(cell, source, true);
}
else
{
this.model.terminalForCellChanged(cell, null, true);
}
}
if (target != null)
{
if (isConnect)
{
this.model.terminalForCellChanged(cell, target, false);
}
else
{
this.model.terminalForCellChanged(cell, null, false);
}
}
cell.setTerminal(source, true);
cell.setTerminal(target, false);
var childCount = this.model.getChildCount(cell);
for (var i=0; i<childCount; i++)
{
this.connect(this.model.getChildAt(cell, i), isConnect);
}
};
/**
* Class: mxTerminalChange
*
* Action to change a terminal in a model.
*
* Constructor: mxTerminalChange
*
* Constructs a change of a terminal in the
* specified model.
*/
function mxTerminalChange(model, cell, terminal, source)
{
this.model = model;
this.cell = cell;
this.terminal = terminal;
this.previous = terminal;
this.source = source;
};
/**
* Function: execute
*
* Changes the terminal of <cell> to <previous> using
* <mxGraphModel.terminalForCellChanged>.
*/
mxTerminalChange.prototype.execute = function()
{
if (this.cell != null)
{
this.terminal = this.previous;
this.previous = this.model.terminalForCellChanged(
this.cell, this.previous, this.source);
}
};
/**
* Class: mxValueChange
*
* Action to change a user object in a model.
*
* Constructor: mxValueChange
*
* Constructs a change of a user object in the
* specified model.
*/
function mxValueChange(model, cell, value)
{
this.model = model;
this.cell = cell;
this.value = value;
this.previous = value;
};
/**
* Function: execute
*
* Changes the value of <cell> to <previous> using
* <mxGraphModel.valueForCellChanged>.
*/
mxValueChange.prototype.execute = function()
{
if (this.cell != null)
{
this.value = this.previous;
this.previous = this.model.valueForCellChanged(
this.cell, this.previous);
}
};
/**
* Class: mxStyleChange
*
* Action to change a cell's style in a model.
*
* Constructor: mxStyleChange
*
* Constructs a change of a style in the
* specified model.
*/
function mxStyleChange(model, cell, style)
{
this.model = model;
this.cell = cell;
this.style = style;
this.previous = style;
};
/**
* Function: execute
*
* Changes the style of <cell> to <previous> using
* <mxGraphModel.styleForCellChanged>.
*/
mxStyleChange.prototype.execute = function()
{
if (this.cell != null)
{
this.style = this.previous;
this.previous = this.model.styleForCellChanged(
this.cell, this.previous);
}
};
/**
* Class: mxGeometryChange
*
* Action to change a cell's geometry in a model.
*
* Constructor: mxGeometryChange
*
* Constructs a change of a geometry in the
* specified model.
*/
function mxGeometryChange(model, cell, geometry)
{
this.model = model;
this.cell = cell;
this.geometry = geometry;
this.previous = geometry;
};
/**
* Function: execute
*
* Changes the geometry of <cell> ro <previous> using
* <mxGraphModel.geometryForCellChanged>.
*/
mxGeometryChange.prototype.execute = function()
{
if (this.cell != null)
{
this.geometry = this.previous;
this.previous = this.model.geometryForCellChanged(
this.cell, this.previous);
}
};
/**
* Class: mxCollapseChange
*
* Action to change a cell's collapsed state in a model.
*
* Constructor: mxCollapseChange
*
* Constructs a change of a collapsed state in the
* specified model.
*/
function mxCollapseChange(model, cell, collapsed)
{
this.model = model;
this.cell = cell;
this.collapsed = collapsed;
this.previous = collapsed;
};
/**
* Function: execute
*
* Changes the collapsed state of <cell> to <previous> using
* <mxGraphModel.collapsedStateForCellChanged>.
*/
mxCollapseChange.prototype.execute = function()
{
if (this.cell != null)
{
this.collapsed = this.previous;
this.previous = this.model.collapsedStateForCellChanged(
this.cell, this.previous);
}
};
/**
* Class: mxVisibleChange
*
* Action to change a cell's visible state in a model.
*
* Constructor: mxVisibleChange
*
* Constructs a change of a visible state in the
* specified model.
*/
function mxVisibleChange(model, cell, visible)
{
this.model = model;
this.cell = cell;
this.visible = visible;
this.previous = visible;
};
/**
* Function: execute
*
* Changes the visible state of <cell> to <previous> using
* <mxGraphModel.visibleStateForCellChanged>.
*/
mxVisibleChange.prototype.execute = function()
{
if (this.cell != null)
{
this.visible = this.previous;
this.previous = this.model.visibleStateForCellChanged(
this.cell, this.previous);
}
};
/**
* Class: mxCellAttributeChange
*
* Action to change the attribute of a cell's user object.
* There is no method on the graph model that uses this
* action. To use the action, you can use the code shown
* in the example below.
*
* Example:
*
* To change the attributeName in the cell's user object
* to attributeValue, use the following code:
*
* (code)
* model.beginUpdate();
* try
* {
* var edit = new mxCellAttributeChange(
* cell, attributeName, attributeValue);
* model.execute(edit);
* }
* finally
* {
* model.endUpdate();
* }
* (end)
*
* Constructor: mxCellAttributeChange
*
* Constructs a change of a attribute of the DOM node
* stored as the value of the given <mxCell>.
*/
function mxCellAttributeChange(cell, attribute, value)
{
this.cell = cell;
this.attribute = attribute;
this.value = value;
this.previous = value;
};
/**
* Function: execute
*
* Changes the attribute of the cell's user object by
* using <mxCell.setAttribute>.
*/
mxCellAttributeChange.prototype.execute = function()
{
if (this.cell != null)
{
var tmp = this.cell.getAttribute(this.attribute);
if (this.previous == null)
{
this.cell.value.removeAttribute(this.attribute);
}
else
{
this.cell.setAttribute(this.attribute, this.previous);
}
this.previous = tmp;
}
};
__mxOutput.mxGraphModel = typeof mxGraphModel !== 'undefined' ? mxGraphModel : undefined;
|
/** @type {import('@docusaurus/types').DocusaurusConfig} */
const VersionsArchived = require('./versionsArchived.json');
module.exports = {
title: 'SMA Technologies Help',
tagline: 'OpCon',
url: 'https://help.smatechnologies.com',
baseUrl: '/opcon/core/',
onBrokenLinks: 'throw',
onBrokenMarkdownLinks: 'warn',
favicon: 'img/favicon.ico',
organizationName: 'smatechnologies',
projectName: 'opcon-docs',
themeConfig: {
navbar: {
title: 'Help',
logo: {
alt: 'SMA Technologies Help Logo',
src: 'img/logo.svg',
href: 'https://help.smatechnologies.com',
},
items: [
{
type: 'docsVersionDropdown',
position: 'right',
dropdownItemsAfter: [
...Object.entries(VersionsArchived).map(
([versionName, versionUrl]) => ({
label: versionName,
href: versionUrl,
}),
),
],
},
],
},
footer: {
style: 'dark',
copyright: `Copyright © ${new Date().getFullYear()} SMA Technologies.`,
},
},
presets: [
[
'@docusaurus/preset-classic',
{
docs: {
routeBasePath: '/',
sidebarPath: require.resolve('./sidebars.js'),
editUrl:
'https://github.com/smatechnologies/opcon-docs/blob/develop',
lastVersion: 'current',
versions: {
'current': {
label: 'current',
},
'21.0.0': {
label: '21.0.0',
path: 'v21.0',
banner: 'none'
}
}
},
theme: {
customCss: require.resolve('./src/css/custom.css'),
},
},
],
],
plugins: [
[
require.resolve('@cmfcmf/docusaurus-search-local'),
{
docsRouteBasePath: '/',
}
],
],
};
|
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
# 作业平台任务状态参照表
TASK_RESULT = [
(0, '状态未知'),
(1, '未执行'),
(2, '正在执行'),
(3, '执行成功'),
(4, '执行失败'),
(5, '跳过'),
(6, '忽略错误'),
(7, '等待用户'),
(8, '手动结束'),
(9, '状态异常'),
(10, '步骤强制终止中'),
(11, '步骤强制终止成功'),
(12, '步骤强制终止失败'),
(-1, '接口调用失败'),
]
"""
import traceback
import re
from functools import partial
from django.utils.translation import ugettext_lazy as _
from pipeline.core.flow.activity import Service
from pipeline.core.flow.io import (
StringItemSchema,
IntItemSchema,
)
from gcloud.conf import settings
from gcloud.utils.handlers import handle_api_error
# 作业状态码: 1.未执行; 2.正在执行; 3.执行成功; 4.执行失败; 5.跳过; 6.忽略错误; 7.等待用户; 8.手动结束;
# 9.状态异常; 10.步骤强制终止中; 11.步骤强制终止成功; 12.步骤强制终止失败
JOB_SUCCESS = {3}
JOB_VAR_TYPE_IP = 2
# 全局变量标签中key-value分隔符
LOG_VAR_SEPARATOR = ":"
# 全局变量标签匹配正则(<>字符已转义),用于提取key{separator}value
LOG_VAR_LABEL_ESCAPE_RE = r"<SOPS_VAR>([\S]+{separator}[\S]+)</SOPS_VAR>".format(
separator=LOG_VAR_SEPARATOR
)
# 全局变量标签匹配正则,用于提取key{separator}value
LOG_VAR_LABEL_RE = r"<SOPS_VAR>([\S]+{separator}[\S]+)</SOPS_VAR>".format(separator=LOG_VAR_SEPARATOR)
__group_name__ = _("作业平台(JOB)")
get_client_by_user = settings.ESB_GET_CLIENT_BY_USER
job_handle_api_error = partial(handle_api_error, __group_name__)
def get_sops_var_dict_from_log_text(log_text, service_logger):
"""
在日志文本中提取全局变量
:param service_logger:
:param log_text: 日志文本,如下:
"<SOPS_VAR>key1:value1</SOPS_VAR>\ngsectl\n-rwxr-xr-x 1 root<SOPS_VAR>key2:value2</SOPS_VAR>\n"
或者已转义的日志文本
<SOPS_VAR>key2:value2</SOPS_VAR>
:return:
{"key1": "value1", "key2": "value2"}
"""
sops_var_dict = {}
# 逐行匹配以便打印全局变量所在行
for index, log_line in enumerate(log_text.splitlines(), 1):
sops_key_val_list = re.findall(LOG_VAR_LABEL_RE, log_line)
sops_key_val_list.extend(re.findall(LOG_VAR_LABEL_ESCAPE_RE, log_line))
if len(sops_key_val_list) == 0:
continue
sops_var_dict.update(dict([sops_key_val.split(LOG_VAR_SEPARATOR) for sops_key_val in sops_key_val_list]))
service_logger.info(
_("[{group}]提取日志中全局变量,匹配行[{index}]:[{line}]").format(group=__group_name__, index=index, line=log_line)
)
return sops_var_dict
def get_job_sops_var_dict(client, service_logger, job_instance_id, bk_biz_id):
"""
解析作业日志:默认取每个步骤/节点的第一个ip_logs
:param client:
:param service_logger: 组件日志对象
:param job_instance_id: 作业实例id
:param bk_biz_id 业务ID
获取到的job_logs实例
[
{
"status": 3,
"step_results": [
{
"tag": "",
"ip_logs": [
{
"total_time": 0.363,
"ip": "1.1.1.1",
"start_time": "2020-06-15 17:23:11 +0800",
"log_content": "<SOPS_VAR>key1:value1</SOPS_VAR>\ngsectl\n-rwxr-xr-x 1",
"exit_code": 0,
"bk_cloud_id": 0,
"retry_count": 0,
"end_time": "2020-06-15 17:23:11 +0800",
"error_code": 0
},
],
"ip_status": 9
}
],
"is_finished": true,
"step_instance_id": 12321,
"name": "查看文件"
},
]
:return:
- success { "result": True, "data": {"key1": "value1"}}
- fail { "result": False, "message": message}
"""
get_job_instance_log_kwargs = {"job_instance_id": job_instance_id, "bk_biz_id": bk_biz_id}
get_job_instance_log_return = client.job.get_job_instance_log(get_job_instance_log_kwargs)
if not get_job_instance_log_return["result"]:
message = handle_api_error(
__group_name__, "job.get_job_instance_log", get_job_instance_log_kwargs, get_job_instance_log_return
)
service_logger.warning(message)
return {"result": False, "message": message}
job_logs = get_job_instance_log_return["data"]
log_text = "\n".join([job_log["step_results"][0]["ip_logs"][0]["log_content"] for job_log in job_logs])
return {"result": True, "data": get_sops_var_dict_from_log_text(log_text, service_logger)}
class JobService(Service):
__need_schedule__ = True
reload_outputs = True
need_get_sops_var = False
def execute(self, data, parent_data):
pass
def schedule(self, data, parent_data, callback_data=None):
try:
job_instance_id = callback_data.get("job_instance_id", None)
status = callback_data.get("status", None)
except Exception as e:
err_msg = "invalid callback_data: {}, err: {}"
self.logger.error(err_msg.format(callback_data, traceback.format_exc()))
data.outputs.ex_data = err_msg.format(callback_data, e)
return False
if not job_instance_id or not status:
data.outputs.ex_data = "invalid callback_data, job_instance_id: %s, status: %s" % (job_instance_id, status)
self.finish_schedule()
return False
if status in JOB_SUCCESS:
if self.reload_outputs:
client = data.outputs.client
# 全局变量重载
get_var_kwargs = {
"bk_biz_id": data.get_one_of_inputs("biz_cc_id", parent_data.inputs.biz_cc_id),
"job_instance_id": job_instance_id,
}
global_var_result = client.job.get_job_instance_global_var_value(get_var_kwargs)
self.logger.info("get_job_instance_global_var_value return: {}".format(global_var_result))
if not global_var_result["result"]:
message = job_handle_api_error(
"job.get_job_instance_global_var_value", get_var_kwargs, global_var_result,
)
self.logger.error(message)
data.outputs.ex_data = message
self.finish_schedule()
return False
global_var_list = global_var_result["data"].get("job_instance_var_values", [])
if global_var_list:
for global_var in global_var_list[-1]["step_instance_var_values"]:
if global_var["category"] != JOB_VAR_TYPE_IP:
data.set_outputs(global_var["name"], global_var["value"])
# 无需提取全局变量的Service直接返回
if not self.need_get_sops_var:
self.finish_schedule()
return True
get_job_sops_var_dict_return = get_job_sops_var_dict(
data.outputs.client,
self.logger,
job_instance_id,
data.get_one_of_inputs("biz_cc_id", parent_data.inputs.biz_cc_id),
)
if not get_job_sops_var_dict_return["result"]:
self.logger.warning(
_("{group}.{job_service_name}: 提取日志失败,{message}").format(
group=__group_name__,
job_service_name=self.__class__.__name__,
message=get_job_sops_var_dict_return["message"],
)
)
data.set_outputs("log_outputs", {})
self.finish_schedule()
return True
log_outputs = get_job_sops_var_dict_return["data"]
self.logger.info(
_("{group}.{job_service_name}:输出日志提取变量为:{log_outputs}").format(
group=__group_name__, job_service_name=self.__class__.__name__, log_outputs=log_outputs
)
)
data.set_outputs("log_outputs", log_outputs)
self.finish_schedule()
return True
else:
data.set_outputs(
"ex_data",
{
"exception_msg": _("任务执行失败,<a href='%s' target='_blank'>前往作业平台(JOB)查看详情</a>")
% data.outputs.job_inst_url,
"task_inst_id": job_instance_id,
"show_ip_log": True,
},
)
self.finish_schedule()
return False
def outputs_format(self):
return [
self.OutputItem(
name=_("JOB任务ID"),
key="job_inst_id",
type="int",
schema=IntItemSchema(description=_("提交的任务在 JOB 平台的实例 ID")),
),
self.OutputItem(
name=_("JOB任务链接"),
key="job_inst_url",
type="string",
schema=StringItemSchema(description=_("提交的任务在 JOB 平台的 URL")),
),
]
|
import { StyleSheet, Dimensions } from "react-native";
const {width,height} = Dimensions.get('window');
export default StyleSheet.create({
container:{
backgroundColor:'#eceff1',
margin:10,
borderRadius:10,
flex:1
},
body_container:{
padding:10,
},
descreption_container:{
margin:10,
},
image:{
height:height/4,
borderRadius:10,
},
title:{
fontWeight:'bold',
fontSize:25,
color:'#0e0e0e'
},
stock_title:{
color:'red',
fontSize:18,
},
price:{
fontSize:18,
},
}) |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
"""
One way to improve or interprete the former function is that:
the network learns a displacement towards the bottom of the feature map -> sample features there
"""
class LookGround(nn.Module):
""" Some Information about LookGround (GAC) """
def __init__(self, input_features, baseline=0.54, relative_elevation=1.65):
# parent Class __init__ method
super(LookGround, self).__init__()
# disparity create
self.disp_create = nn.Sequential(
nn.Conv2d(input_features, 1, 3, padding=1),
nn.Tanh(),
)
# Conv2d Layer
self.extract = nn.Conv2d(1 + input_features, input_features, 1)
# virtual stereo setup baseline B = 0.54m
self.baseline = baseline
# expected elevation of camera from the ground (1.65 meters)
self.relative_elevation = relative_elevation
# observation angle
self.alpha = nn.Parameter(torch.tensor([0.0], dtype=torch.float32))
def forward(self, inputs):
# input feature map
x = inputs['features']
P2 = inputs['P2']
# downsample to 16.0
P2 = P2.clone()
P2[:, 0:2] /= 16.0
disp = self.disp_create(x)
disp = 0.1 * (0.05 * disp + 0.95 * disp.detach())
batch_size, _, height, width = x.size()
# create Disparity Map
h, w = x.shape[2], x.shape[3]
x_range = np.arange(h, dtype=np.float32)
y_range = np.arange(w, dtype=np.float32)
_, yy_grid = np.meshgrid(y_range, x_range)
yy_grid = x.new(yy_grid).unsqueeze(0) #[1, H, W]
fy = P2[:, 1:2, 1:2] #[B, 1, 1]
cy = P2[:, 1:2, 2:3] #[B, 1, 1]
Ty = P2[:, 1:2, 3:4] #[B, 1, 1]
# compute disparity
disparity = fy * self.baseline * (yy_grid - cy) / (torch.abs(fy * self.relative_elevation + Ty) + 1e-10)
disparity = F.relu(disparity)
# original coordinates of pixels
x_base = torch.linspace(-1, 1, width).repeat(batch_size,
height, 1).type_as(x)
y_base = torch.linspace(-1, 1, height).repeat(batch_size,
width, 1).transpose(1, 2).type_as(x)
# apply shift in Y direction
h_mean = 1.535
y_shifts_base = F.relu(
h_mean * (yy_grid - cy) / (2 * (self.relative_elevation - 0.5 * h_mean))
) / (yy_grid.shape[1] * 0.5) # [1, H, W]
y_shifts = y_shifts_base + disp[:, 0, :, :] # Disparity is passed in NCHW format with 1 channel
flow_field = torch.stack((x_base, y_base + y_shifts), dim=3)
# In grid_sample coordinates are assumed to be between -1 and 1
features = torch.cat([disparity.unsqueeze(1), x], dim=1)
output = F.grid_sample(features, flow_field, mode='bilinear',
padding_mode='border', align_corners=True)
return F.relu(x + self.extract(output) * self.alpha)
|
let handler = async (m, { conn, text }) => {
if (!text) throw 'No Text'
conn.sendFile(m.chat, global.API('https://some-random-api.ml', '/canvas/youtube-comment', {
avatar: await conn.getProfilePicture(m.sender).catch(_ => ''),
comment: text,
username: conn.getName(m.sender)
}), 'file.png', watermark, m, 0, { thumbnail: Buffer.alloc(0) })
}
handler.help = ['ytcomment <komen>']
handler.tags = ['maker']
handler.command = /^(ytcomment)$/i
module.exports = handler |
webpackJsonp([136],{BOPr:function(n,a,e){a=n.exports=e("FZ+f")(!1),a.push([n.i,"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",""])},Ev2d:function(n,a,e){var t=e("BOPr");"string"==typeof t&&(t=[[n.i,t,""]]),t.locals&&(n.exports=t.locals);e("rjj0")("c56bcf7a",t,!0,{})},mNvQ:function(n,a,e){"use strict";function t(n){e("Ev2d")}Object.defineProperty(a,"__esModule",{value:!0});var s=e("lcoF"),r=e("mtWM"),o=e.n(r),i=e("x1ym"),l={mixins:[s.a],data:function(){var n=this,a=i.a.required();i.a.number();return{params:{},rules:{system:[a],username:[a],password:[a,function(){return{validator:function(a,e,t){n.$refs.form.validateField("confirmPassword"),t()},trigger:"blur"}}()],confirmPassword:[a,function(){return{validator:function(a,e,t){void 0===e&&(e=""),e!==n.dataInfo.password?t(new Error("前后密码不一致")):t()},trigger:"blur"}}()]},checkRes:!1}},methods:{getDataInfo:function(n){var a=this,e=this.$api;o.a.all([o.a.post(e.apiWebserviceAuthGet,{id:n})]).then(o.a.spread(function(n){a.dataInfo=n.body,a.dataInfo.password="",a.$refs.form.resetFields(),a.loading=!1})).catch(function(n){a.loading=!1})},add:function(n){this.saveDataInfo(n,this.$api.apiWebserviceAuthSave,this.dataInfo,"list")}},created:function(){this.getDataInfo(this.id)}},d=function(){var n=this,a=n.$createElement,e=n._self._c||a;return e("section",{directives:[{name:"loading",rawName:"v-loading",value:n.loading,expression:"loading"}],staticClass:"cms-body"},[e("cms-back"),n._v(" "),e("el-form",{ref:"form",staticClass:"cms-form",attrs:{model:n.dataInfo,rules:n.rules,"label-width":"162px"}},[e("el-form-item",{staticClass:"flex-100",attrs:{label:"用户名",prop:"username"}},[e("el-input",{staticClass:"cms-width",model:{value:n.dataInfo.username,callback:function(a){n.$set(n.dataInfo,"username",a)},expression:"dataInfo.username"}})],1),n._v(" "),e("el-form-item",{staticClass:"flex-100",attrs:{label:"系统",prop:"system"}},[e("el-input",{staticClass:"cms-width",model:{value:n.dataInfo.system,callback:function(a){n.$set(n.dataInfo,"system",a)},expression:"dataInfo.system"}})],1),n._v(" "),e("el-form-item",{staticClass:"flex-50",attrs:{label:"密码",prop:"password"}},[e("el-input",{staticClass:"cms-width",attrs:{type:"password"},model:{value:n.dataInfo.password,callback:function(a){n.$set(n.dataInfo,"password",a)},expression:"dataInfo.password"}})],1),n._v(" "),e("el-form-item",{staticClass:"flex-50",attrs:{label:"确认密码",prop:"confirmPassword"}},[e("el-input",{staticClass:"cms-width",attrs:{type:"password"},model:{value:n.dataInfo.confirmPassword,callback:function(a){n.$set(n.dataInfo,"confirmPassword",a)},expression:"dataInfo.confirmPassword"}})],1),n._v(" "),e("el-form-item",{staticClass:"flex-100",attrs:{label:"启用"}},[e("el-radio-group",{model:{value:n.dataInfo.enable,callback:function(a){n.$set(n.dataInfo,"enable",a)},expression:"dataInfo.enable"}},[e("el-radio",{attrs:{label:!0}},[n._v("是")]),n._v(" "),e("el-radio",{attrs:{label:!1}},[n._v("否")])],1)],1),n._v(" "),e("div",{staticClass:"form-footer"},[e("el-button",{directives:[{name:"perms",rawName:"v-perms",value:"/apiManage/apiUserMan/add",expression:"'/apiManage/apiUserMan/add'"}],attrs:{type:"warning"},on:{click:function(a){n.add(!0)}}},[n._v("保存并继续添加")]),n._v(" "),e("el-button",{directives:[{name:"perms",rawName:"v-perms",value:"/apiManage/apiUserMan/add",expression:"'/apiManage/apiUserMan/add'"}],attrs:{type:"primary"},on:{click:function(a){n.add(!1)}}},[n._v("提交")]),n._v(" "),e("el-button",{attrs:{type:"info"},on:{click:n.$reset}},[n._v("重置")])],1)],1)],1)},c=[],f={render:d,staticRenderFns:c},m=f,p=e("VU/8"),u=t,v=p(l,m,!1,u,null,null);a.default=v.exports}}); |
import PropTypes from 'prop-types';
// material
import { visuallyHidden } from '@mui/utils';
import { Box, Checkbox, TableRow, TableCell, TableHead, TableSortLabel } from '@mui/material';
// ----------------------------------------------------------------------
staffListHead.propTypes = {
order: PropTypes.oneOf(['asc', 'desc']),
orderBy: PropTypes.string,
rowCount: PropTypes.number,
headLabel: PropTypes.array,
numSelected: PropTypes.number,
onRequestSort: PropTypes.func,
onSelectAllClick: PropTypes.func
};
export default function staffListHead({
order,
orderBy,
rowCount,
headLabel,
numSelected,
onRequestSort,
onSelectAllClick
}) {
const createSortHandler = (property) => (event) => {
onRequestSort(event, property);
};
return (
<TableHead>
<TableRow>
<TableCell padding="checkbox">
<Checkbox
indeterminate={numSelected > 0 && numSelected < rowCount}
checked={rowCount > 0 && numSelected === rowCount}
onChange={onSelectAllClick}
/>
</TableCell>
{headLabel.map((headCell) => (
<TableCell
key={headCell.id}
align={headCell.alignRight ? 'right' : 'left'}
sortDirection={orderBy === headCell.id ? order : false}
>
<TableSortLabel
hideSortIcon
active={orderBy === headCell.id}
direction={orderBy === headCell.id ? order : 'asc'}
onClick={createSortHandler(headCell.id)}
>
{headCell.label}
{orderBy === headCell.id ? (
<Box sx={{ ...visuallyHidden }}>
{order === 'desc' ? 'sorted descending' : 'sorted ascending'}
</Box>
) : null}
</TableSortLabel>
</TableCell>
))}
</TableRow>
</TableHead>
);
}
|
# Solution of;
# Project Euler Problem 203: Squarefree Binomial Coefficients
# https://projecteuler.net/problem=203
#
# The binomial coefficients $\displaystyle \binom n k$ can be arranged in
# triangular form, Pascal's triangle, like
# this:111121133114641151010511615201561172135352171. . . . . . . . . It can
# be seen that the first eight rows of Pascal's triangle contain twelve
# distinct numbers: 1, 2, 3, 4, 5, 6, 7, 10, 15, 20, 21 and 35. A positive
# integer n is called squarefree if no square of a prime divides n. Of the
# twelve distinct numbers in the first eight rows of Pascal's triangle, all
# except 4 and 20 are squarefree. The sum of the distinct squarefree numbers
# in the first eight rows is 105. Find the sum of the distinct squarefree
# numbers in the first 51 rows of Pascal's triangle.
#
# by lcsm29 http://github.com/lcsm29/project-euler
import timed
def dummy(n):
pass
if __name__ == '__main__':
n = 1000
i = 10000
prob_id = 203
timed.caller(dummy, n, i, prob_id)
|
from __future__ import absolute_import
from __future__ import print_function
import veriloggen
import stream_cast
expected_verilog = """
module test;
reg CLK;
reg RST;
reg signed [32-1:0] xdata;
reg signed [32-1:0] ydata;
wire signed [32-1:0] zdata;
main
uut
(
.CLK(CLK),
.RST(RST),
.xdata(xdata),
.ydata(ydata),
.zdata(zdata)
);
reg reset_done;
initial begin
$dumpfile("uut.vcd");
$dumpvars(0, uut);
end
initial begin
CLK = 0;
forever begin
#5 CLK = !CLK;
end
end
initial begin
RST = 0;
reset_done = 0;
xdata = 0;
ydata = 0;
#100;
RST = 1;
#100;
RST = 0;
#1000;
reset_done = 1;
@(posedge CLK);
#1;
#10000;
$finish;
end
reg [32-1:0] send_fsm;
localparam send_fsm_init = 0;
reg [32-1:0] send_count;
reg [32-1:0] recv_fsm;
localparam recv_fsm_init = 0;
reg [32-1:0] recv_count;
localparam send_fsm_1 = 1;
localparam send_fsm_2 = 2;
always @(posedge CLK) begin
if(RST) begin
send_fsm <= send_fsm_init;
send_count <= 0;
end else begin
case(send_fsm)
send_fsm_init: begin
if(reset_done) begin
send_fsm <= send_fsm_1;
end
end
send_fsm_1: begin
xdata <= xdata + 1;
ydata <= ydata + 2;
$display("xdata=%d", xdata);
$display("ydata=%d", ydata);
send_count <= send_count + 1;
if(send_count == 20) begin
send_fsm <= send_fsm_2;
end
end
endcase
end
end
localparam recv_fsm_1 = 1;
localparam recv_fsm_2 = 2;
always @(posedge CLK) begin
if(RST) begin
recv_fsm <= recv_fsm_init;
recv_count <= 0;
end else begin
case(recv_fsm)
recv_fsm_init: begin
if(reset_done) begin
recv_fsm <= recv_fsm_1;
end
end
recv_fsm_1: begin
$display("zdata=%d", zdata);
recv_count <= recv_count + 1;
if(recv_count == 30) begin
recv_fsm <= recv_fsm_2;
end
end
endcase
end
end
endmodule
module main
(
input CLK,
input RST,
input signed [32-1:0] xdata,
input signed [32-1:0] ydata,
output signed [32-1:0] zdata
);
wire signed [32-1:0] _cast_src_2;
assign _cast_src_2 = xdata;
wire signed [64-1:0] _cast_data_2;
assign _cast_data_2 = _cast_src_2 << 8;
wire signed [32-1:0] _cast_src_3;
assign _cast_src_3 = ydata;
wire signed [64-1:0] _cast_data_3;
assign _cast_data_3 = _cast_src_3 << 8;
reg signed [64-1:0] _plus_data_4;
wire signed [64-1:0] _cast_src_5;
assign _cast_src_5 = _plus_data_4;
wire signed [32-1:0] _cast_data_5;
assign _cast_data_5 = _cast_src_5 >>> 8;
assign zdata = _cast_data_5;
always @(posedge CLK) begin
if(RST) begin
_plus_data_4 <= 0;
end else begin
_plus_data_4 <= _cast_data_2 + _cast_data_3;
end
end
endmodule
"""
def test():
veriloggen.reset()
test_module = stream_cast.mkTest()
code = test_module.to_verilog()
from pyverilog.vparser.parser import VerilogParser
from pyverilog.ast_code_generator.codegen import ASTCodeGenerator
parser = VerilogParser()
expected_ast = parser.parse(expected_verilog)
codegen = ASTCodeGenerator()
expected_code = codegen.visit(expected_ast)
assert(expected_code == code)
|
export default [
{
title: "Document props of each component",
description: "I believe this will help with a lot of confusion as far as overriding component goes, and will make it easier to see where we can improve.",
completed: false,
id: "000",
},
{
title: "Add NPM info to README",
description: "Add NPM info to README",
completed: false,
id: "001"
},
] |
/* [email protected] - system */
System.register(["single-spa"],(function(e){"use strict";var t,n;return{setters:[function(e){t=e.pathToActiveWhen,n=e.mountRootParcel}],execute:function(){function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function r(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,o)}return n}function i(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?a(Object(n),!0).forEach((function(t){r(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):a(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function c(e){return function(e){if(Array.isArray(e))return s(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||u(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function u(e,t){if(e){if("string"==typeof e)return s(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?s(e,t):void 0}}function s(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=new Array(t);n<t;n++)o[n]=e[n];return o}e({constructApplications:function(e){var t=e.routes,o=e.loadApp,r={};return function e(t,n,o,r){r.forEach((function(r){"application"===r.type?(t[r.name]||(t[r.name]=[]),t[r.name].push({activeWhen:n,props:N(o,r.props),loader:r.loader})):"route"===r.type?e(t,r.activeWhen,N(o,r.props),r.routes):r.routes&&e(t,n,o,r.routes)}))}(r,O,{},t.routes),Object.keys(r).map((function(e){var t=r[e];return{name:e,customProps:function(e,n){var o=m(t,(function(e){return e.activeWhen(n)}));return o?o.props:{}},activeWhen:t.map((function(e){return e.activeWhen})),app:function(){var r;l&&(r=m(t,(function(e){return e.activeWhen(window.location)})));var a=o({name:e});return r&&r.loader?function(e,t,o){return Promise.resolve().then((function(){var r,a=E(e),i=document.getElementById(a);i||((i=document.createElement("div")).id=a,i.style.display="none",document.body.appendChild(i),r=function(){i.style.removeProperty("display"),""===i.getAttribute("style")&&i.removeAttribute("style"),window.removeEventListener("single-spa:before-mount-routing-event",r)},window.addEventListener("single-spa:before-mount-routing-event",r));var c,s="string"==typeof t.loader?(c=t.loader,{bootstrap:function(){return Promise.resolve()},mount:function(e){return Promise.resolve().then((function(){e.domElement.innerHTML=c}))},unmount:function(e){return Promise.resolve().then((function(){e.domElement.innerHTML=""}))}}):t.loader,l=n(s,{name:"application-loader:".concat(e),domElement:i});return Promise.all([l.mountPromise,o]).then((function(e){var t,n=(2,function(e){if(Array.isArray(e))return e}(t=e)||function(e,t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e)){var n=[],o=!0,r=!1,a=void 0;try{for(var i,c=e[Symbol.iterator]();!(o=(i=c.next()).done)&&(n.push(i.value),2!==n.length);o=!0);}catch(e){r=!0,a=e}finally{try{o||null==c.return||c.return()}finally{if(r)throw a}}return n}}(t)||u(t,2)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()),o=(n[0],n[1]);return l.unmount().then((function(){return r&&r(),o}))}))}))}(e,r,a):a}}}))},constructLayoutEngine:function(e){var t=e.routes,n=(e.applications,e.active),o=void 0===n||n,r=!1,a=[],i=t.base.slice(0,t.base.length-1),c={isActive:function(){return r},activate:function(){r||(r=!0,l&&(window.addEventListener("single-spa:before-mount-routing-event",u),window.addEventListener("single-spa:routing-event",s),u()))},deactivate:function(){r&&(r=!1,l&&(window.removeEventListener("single-spa:before-mount-routing-event",u),window.removeEventListener("single-spa:routing-event",s)))}};return o&&c.activate(),c;function u(){if(0===location["hash"===t.mode?"hash":"pathname"].indexOf(i)){var e="string"==typeof t.containerEl?document.querySelector(t.containerEl):t.containerEl;!function e(t){var n=t.location,o=t.routes,r=t.parentContainer,a=t.previousSibling,i=t.shouldMount,c=t.pendingRemovals;return o.forEach((function(t,o){if("application"===t.type){var u=E(t.name),s=document.getElementById(u);i&&(s||((s=document.createElement("div")).id=u),w(s,r,a),a=s)}else if("route"===t.type)a=e({location:n,routes:t.routes,parentContainer:r,previousSibling:a,shouldMount:i&&t.activeWhen(n),pendingRemovals:c});else if(t instanceof Node)if(i){if(!t.connectedNode){var l=t.cloneNode(!1);t.connectedNode=l}w(t.connectedNode,r,a),t.routes&&e({location:n,routes:t.routes,parentContainer:t.connectedNode,previousSibling:null,shouldMount:i,pendingRemovals:c}),a=t.connectedNode}else c.push((function(){var e;(e=t.connectedNode)&&(e.remove?e.remove():e.parentNode.removeChild(e)),delete t.connectedNode}))})),a}({location:window.location,routes:t.routes,parentContainer:e,shouldMount:!0,pendingRemovals:a})}}function s(e){var t=e.detail.appsByNewStatus;a.forEach((function(e){return e()})),a=[],t.NOT_MOUNTED.concat(t.NOT_LOADED).forEach((function(e){var t=document.getElementById(E(e));t&&t.isConnected&&t.parentNode.removeChild(t)}))}},constructRoutes:function(e,n){if(e&&e.nodeName)e=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("template"===e.nodeName.toLowerCase()&&(e=(e.content||e).querySelector("single-spa-router")),"single-spa-router"!==e.nodeName.toLowerCase())throw Error("single-spa-layout: The HTMLElement passed to constructRoutes must be <single-spa-router> or a <template> containing the router. Received ".concat(e.nodeName));l&&e.isConnected&&e.parentNode.removeChild(e);var n={routes:[]};y(e,"mode")&&(n.mode=y(e,"mode")),y(e,"base")&&(n.base=y(e,"base"));for(var o=0;o<e.childNodes.length;o++){var r;(r=n.routes).push.apply(r,c(b(e.childNodes[o],t)))}return n}(e,n);else if(n)throw Error("constructRoutes should be called either with an HTMLElement and layoutData, or a single json object.");return function(e){p("routesConfig",e);var n=e.disableWarnings;d("routesConfig",e,["mode","base","containerEl","routes","disableWarnings"],n),e.hasOwnProperty("containerEl")?function(e,t){if("string"==typeof t?""===t.trim():!(l&&t instanceof HTMLElement))throw Error("Invalid ".concat("routesConfig.containerEl",": received ").concat(t," but expected either non-blank string or HTMLElement"))}(0,e.containerEl):e.containerEl="body",e.hasOwnProperty("mode")||(e.mode="history"),function(e,t,n){if(n.indexOf(t)<0)throw Error("Invalid ".concat("routesConfig.mode",": received '").concat(t,"' but expected ").concat(n.join(", ")))}(0,e.mode,["history","hash"]),e.hasOwnProperty("base")?(f("routesConfig.base",e.base),e.base=(r=e.base,0!==r.indexOf("/")&&(r="/"+r),"/"!==r[r.length-1]&&(r+="/"),r)):e.base="/";var r;var a=l?window.location.pathname:"/",i="hash"===e.mode?a+"#":"";h("routesConfig.routes",e.routes,(function e(r,a,i){var c,u=i.parentPath,s=i.siblingActiveWhens;if(p(a,r),"application"===r.type)d(a,r,["type","name","props","loader"],n),r.props&&p("".concat(a,".props"),r.props),f("".concat(a,".name"),r.name);else if("route"===r.type){d(a,r,["type","path","routes","props","default"],n);var l,m=r.hasOwnProperty("path"),y=r.hasOwnProperty("default");if(m)f("".concat(a,".path"),r.path),l=v(u,r.path),r.activeWhen=t(l),s.push(r.activeWhen);else{if(!y)throw Error("Invalid ".concat(a,": routes must have either a path or default property."));!function(e,t){if("boolean"!=typeof t)throw Error("Invalid ".concat(e,": received ").concat(o(t),", but expected a boolean"))}("".concat(a,".default"),r.default),l=u,r.activeWhen=(c=s,function(e){return!c.some((function(t){return t(e)}))})}if(m&&y&&r.default)throw Error("Invalid ".concat(a,": cannot have both path and set default to true."));r.routes&&h("".concat(a,".routes"),r.routes,e,{parentPath:l,siblingActiveWhens:[]})}else{if("undefined"!=typeof Node&&r instanceof Node);else for(var b in r)"routes"!==b&&f("".concat(a,"['").concat(b,"']"),r[b]);r.routes&&h("".concat(a,".routes"),r.routes,e,{parentPath:u,siblingActiveWhens:s})}}),{parentPath:i+e.base,siblingActiveWhens:[]}),delete e.disableWarnings}(e),e},matchRoute:function(e,t){f("path",t);var n=i({},e),o=e.base.slice(0,e.base.length-1);if(0===t.indexOf(o)){var r=l?window.location.origin:"http://localhost",a=new URL(v(r,t));n.routes=function e(t,n){var o=[];return n.forEach((function(n){"application"===n.type?o.push(n):"route"===n.type?n.activeWhen(t)&&o.push(i(i({},n),{},{routes:e(t,n.routes)})):Array.isArray(n.routes)&&o.push(i(i({},n),{},{routes:e(t,n.routes)}))})),o}(a,e.routes)}else n.routes=[];return n}});var l="undefined"!=typeof window;function p(e,t){if("object"!==o(t)||Array.isArray(t)||null===t)throw Error("Invalid ".concat(e,": received ").concat(Array.isArray(t)?"array":t," but expected a plain object"))}function d(e,t,n,o){if(!o){var r=Object.keys(t),a=[];r.forEach((function(e){n.indexOf(e)<0&&a.push(e)})),a.length>0&&console.warn(Error("Invalid ".concat(e,": received invalid properties '").concat(a.join(", "),"', but valid properties are ").concat(n.join(", "))))}}function f(e,t){if("string"!=typeof t||""===t.trim())throw Error("Invalid ".concat(e,": received '").concat(t,"', but expected a non-blank string"))}function h(e,t,n){if(!Array.isArray(t)&&("object"!==o(o(t))||"number"!==t.length))throw Error("Invalid ".concat(e,": received '").concat(t,"', but expected an array"));for(var r=arguments.length,a=new Array(r>3?r-3:0),i=3;i<r;i++)a[i-3]=arguments[i];for(var c=0;c<t.length;c++)n.apply(void 0,[t[c],"".concat(e,"[").concat(c,"]")].concat(a))}function v(e,t){return"/"===e.substr(-1)?"/"===t[0]?e+t.slice(1):e+t:"/"===t[0]?e+t:e+"/"+t}function m(e,t){for(var n=0;n<e.length;n++)if(t(e[n]))return e[n];return null}function y(e,t){if(l)return e.getAttribute(t);var n=m(e.attrs,(function(e){return e.name===t}));return n?n.value:null}function b(e,t){if("application"===e.nodeName.toLowerCase()){if(e.childNodes.length>0)throw Error("<application> elements must not have childNodes. You must put in a closing </application> - self closing is not allowed");var n={type:"application",name:y(e,"name")},o=y(e,"loader");if(o){if(!t.loaders||!t.loaders.hasOwnProperty(o))throw Error("Application loader '".concat(o,"' was not defined in the htmlLayoutData"));n.loader=t.loaders[o]}return g(e,n,t),[n]}if("route"===e.nodeName.toLowerCase()){var r={type:"route",routes:[]},a=y(e,"path");a&&(r.path=a),function(e,t){return l?e.hasAttribute("default"):e.attrs.some((function(e){return"default"===e.name}))}(e)&&(r.default=!0),g(e,r,t);for(var i=0;i<e.childNodes.length;i++){var u;(u=r.routes).push.apply(u,c(b(e.childNodes[i],t)))}return[r]}if("undefined"!=typeof Node&&e instanceof Node){if(e.nodeType===Node.TEXT_NODE&&""===e.textContent.trim())return[];if(e.childNodes&&e.childNodes.length>0){e.routes=[];for(var s=0;s<e.childNodes.length;s++){var p;(p=e.routes).push.apply(p,c(b(e.childNodes[s],t)))}}return[e]}if(e.childNodes){for(var d={type:e.nodeName.toLowerCase(),routes:[]},f=0;f<e.childNodes.length;f++){var h;(h=d.routes).push.apply(h,c(b(e.childNodes[f],t)))}return[d]}return[]}function g(e,t,n){for(var o=(y(e,"props")||"").split(","),r=0;r<o.length;r++){var a=o[r].trim();if(0!==a.length){if(t.props||(t.props={}),!n.props||!n.props.hasOwnProperty(a))throw Error("Prop '".concat(a,"' was not defined in the htmlLayoutData. Either remove this attribute from the HTML element or provide the prop's value"));t.props[a]=n.props[a]}}}function w(e,t,n){n&&n.nextSibling?n.parentNode.insertBefore(e,n.nextSibling):t.appendChild(e)}function E(e){return"single-spa-application:".concat(e)}function N(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return i(i({},e),t)}function O(){return!0}}}}));
|
/*
NOTE:
This program looks for an ID of a RSS post and checks if its the same as the last one.
If its not its a new one and posts.
The RSS this program was designed for was using a id named "guid", this might vary depending on the RSS source.
*/
require('dotenv').config()
let sqlite3 = require('sqlite3').verbose()
let fs = require('fs')
let request = require('request')
var Twit = require('twit')
let Parser = require('rss-parser')
let parser = new Parser()
const { BitlyClient } = require('bitly')
const bitly = new BitlyClient(process.env.BITLY_ACCESS_TOKEN, {})
// let startDate = new Date()
// console.log("Started: " + startDate.getUTCHours() + ":" + startDate.getUTCMinutes() + ":" + startDate.getUTCSeconds())
//setup of data to be stored
let lastItem = {
"id": "",
"post_id": "",
"post_title": "",
"fb_id": ""
}
getLast()
let T = new Twit({
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token: process.env.TWITTER_ACCESS_TOKEN,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET,
timeout_ms: 60*1000,
strictSSL: true,
})
//runs on a 1 minute interval and pings the RSS for updates
setInterval(async () => {
// target feed for program
let feed = await parser.parseURL(process.env.RSS)
let post_id = feed.items[0].id || feed.items[0].guid
//posts if there is no prior posts or if the last posts id is not the same as the new one.
if(!lastItem.post_id || lastItem.post_id != post_id) {
//console.log("New post: " + new Date().getTime())
postToSocialMedia(feed.items[0].link, feed.items[0].title, feed.items[0].guid)
}
}, 60000)
async function postToSocialMedia(link, title, post_id) {
//Facebook
let fb_id
encodeTitle = encodeURIComponent(title)
encodeLink = encodeURIComponent(link)
let FACEBOOK_URI = `https://graph.facebook.com/v5.0/me/feed?message=${encodeTitle}&link=${encodeLink}&access_token=${process.env.FACEBOOK_ACCESS_TOKEN}`
request({
url: FACEBOOK_URI,
method: 'POST'
}, function(err, res, req){
if(err){
writeError("URL", err)
}
if(req.error){
writeError("API", req.error.message)
}
fb_id = JSON.parse(req).id
})
let bitlyLink
let linkStr = title + " " + link
//Get a bitly link for twitter
if( !linkStr || linkStr.length >= 279 )
{
try {
bitlyLink = await bitly.shorten(link)
} catch(e) {
writeError("URL", err)
}
linkStr = title + " " + bitlyLink.url
}
//Twitter
let twitter_id
T.post('statuses/update', { status: linkStr }, function(err, data, response) {
twitter_id = data.id_str
})
insertPost(post_id, title, fb_id, twitter_id)
}
//Gets the last field in the DB
async function getLast() {
let db = new sqlite3.Database('./DB/db.sqlite3', sqlite3.OPEN_READWRITE, (err) => {
if (err) {
writeError("CON", err)
}
})
Select(db)
await db.close((err) => {
if (err) {
writeError("CLO", err)
}
})
}
//selects the last field in the sqlite database
function Select(db) {
db.each(`
SELECT *
FROM posts
WHERE ID = (
SELECT MAX(ID)
FROM posts
)`, (err, row) => {
if (err) {
writeError("REA", err)
}
// console.log(typeof row.id)
if(row){
lastItem.id = "" + row.id
lastItem.post_id = "" + row.post_id
lastItem.post_title = "" + row.post_title
lastItem.fb_id = "" + row.fb_id
}
}
)
}
//insert new post into the database
function insertPost(post_id, post_title, fb_id) {
let db = new sqlite3.Database('./DB/db.sqlite3')
//inserts new post
let sql = `INSERT INTO posts(post_id, post_title, fb_id) VALUES ('${post_id}', '${post_title}', '${fb_id}')`
db.serialize(() => {
db.run(sql, function(err) {
if (err) {
writeError("WRI", err)
return
}
console.log(`Rows inserted ${this.changes}`)
})
Select(db)
})
db.close()
}
//writes errors to a .log file, the first 3 letters in the log tells you what kind of error it was.
/*
writes errors to a .log file, the first 3 letters in the log tells you what kind of error it was.
Error codes:
WRI = Write
REA = Read
CON = Connect
CLO = Close
URL = URL
API = API
*/
function writeError(source, error) {
let date = new Date()
//sets the current date as the fileName
let fileName = source +
date.getUTCFullYear().toString() + "_" +
date.getUTCMonth().toString() + "_" +
date.getUTCDate().toString() + "-" +
date.getUTCHours().toString() + "_" +
date.getUTCMinutes().toString() + "_" +
date.getUTCSeconds().toString() + ".log"
//formats the error log
let errorMessage = "" +
date.getUTCFullYear().toString() + "/" +
date.getUTCMonth().toString() + "/" +
date.getUTCDate().toString() + " " +
date.getUTCHours().toString() + ":" +
date.getUTCMinutes().toString() + ":" +
date.getUTCSeconds().toString() + "\n\n" +
error
fs.writeFile(`./Error/${fileName}`, errorMessage, function (err) {
if (err) throw err
console.log(err)
})
} |
describe("echarts-ng $echarts service", function () {
var $echarts
, $dimension
, $waterfall
, $timeout
, $rootScope;
beforeEach(module("echarts-ng"));
beforeEach(inject(function (_$echarts_, _$dimension_, _$waterfall_, _$timeout_, _$rootScope_) {
$echarts = _$echarts_;
$dimension = _$dimension_;
$waterfall = _$waterfall_;
$timeout = _$timeout_;
$rootScope = _$rootScope_;
}));
it("should provide unique identity each time", function () {
var first = $echarts.generateInstanceIdentity()
, second = $echarts.generateInstanceIdentity();
expect(first).not.toEqual(second);
});
it("should register each echarts instance", function () {
var identity = $echarts.generateInstanceIdentity()
, instance = "jasmine-test";
$echarts.registerEchartsInstance(identity, instance);
expect($echarts.storage.has(identity)).toBeTruthy();
expect($echarts.storage.get(identity)).toEqual(instance);
$echarts.removeEchartsInstance(identity);
expect($echarts.storage.has(identity)).toBeFalsy();
});
it("should provide specific instance with promise", function () {
var identity = $echarts.generateInstanceIdentity()
, instance = "jasmine-test"
, target;
$echarts.registerEchartsInstance(identity, instance);
$echarts.queryEchartsInstance(identity).then(function (item) {
target = item;
});
$timeout.flush();
$rootScope.$digest();
expect(target).toEqual(instance);
});
it("should provide specific instance with promise", function () {
var identity = $echarts.generateInstanceIdentity()
, error = spyOn(console, "error").and.stub()
, errorDesc;
$echarts.queryEchartsInstance(identity).catch(function (item) {
errorDesc = item.errorDesc;
});
$timeout.flush();
$rootScope.$digest();
expect(errorDesc).toBeTruthy();
expect(error).toHaveBeenCalled();
});
it("should warn when instance not registered", function () {
var identity = $echarts.generateInstanceIdentity()
, warn = spyOn(console, "warn").and.stub();
$echarts.updateEchartsInstance(identity);
expect(warn).toHaveBeenCalled();
});
it("should update instance into latest", function () {
var identity = $echarts.generateInstanceIdentity()
, instance = jasmine.createSpyObj("instance", ["setOption", "getOption", "showLoading", "hideLoading", "resize", "clear", "getDom"]);
$echarts.registerEchartsInstance(identity, instance);
spyOn($waterfall, "adaptWaterfallTooltip").and.stub();
spyOn($dimension, "adjustEchartsDimension").and.stub();
spyOn($waterfall, "adaptWaterfallSeries").and.returnValue({series: []});
$echarts.updateEchartsInstance(identity, {});
expect(instance.showLoading).toHaveBeenCalled();
});
it("should update instance into latest", function () {
var identity = $echarts.generateInstanceIdentity()
, instance = jasmine.createSpyObj("instance", ["setOption", "getOption", "showLoading", "hideLoading", "resize", "clear", "getDom"])
, series = [{
name: "搜索引擎",
type: "bar",
data: [820, 932, 901, 934, 1290, 1330, 1320]
}];
$echarts.registerEchartsInstance(identity, instance);
spyOn($waterfall, "adaptWaterfallTooltip").and.stub();
spyOn($dimension, "adjustEchartsDimension").and.stub();
spyOn($waterfall, "adaptWaterfallSeries").and.returnValue({series: series});
$echarts.updateEchartsInstance(identity, {});
expect(instance.setOption).toHaveBeenCalledWith({series: series});
});
it("should drift the original palette property", function () {
var palette = ["#2ec7c9", "#b6a2de", "#5ab1ef", "#ffb980"]
, driftPalette = ["#5ab1ef", "#ffb980", "#2ec7c9", "#b6a2de"]
, driftOverflowPalette = ["#b6a2de", "#5ab1ef", "#ffb980", "#2ec7c9"];
expect($echarts.driftPaletteProperty(palette, 2)).toEqual(driftPalette);
expect($echarts.driftPaletteProperty(palette, 5)).toEqual(driftOverflowPalette);
});
it("should drift instance palette", function () {
var identity = $echarts.generateInstanceIdentity()
, instance = jasmine.createSpyObj("instance", ["getOption", "setOption"]);
instance.getOption.and.returnValues({color: ["#2ec7c9", "#b6a2de", "#5ab1ef", "#ffb980"]});
$echarts.registerEchartsInstance(identity, instance);
$echarts.driftEchartsPalette(instance);
expect(instance.setOption).not.toHaveBeenCalled();
$echarts.driftEchartsPalette(instance, true);
expect(instance.setOption).not.toHaveBeenCalled();
$timeout.flush(10);
expect(instance.setOption).toHaveBeenCalledWith({color: ["#b6a2de", "#5ab1ef", "#ffb980", "#2ec7c9"]});
$timeout.verifyNoPendingTasks();
});
});
describe("echarts-ng $echarts provider", function () {
var $echarts;
var setter = {
tooltip: {
axisPointer: {
type: "cross"
}
}
};
var match = {
trigger: "axis",
axisPointer: {
type: "cross"
}
};
beforeEach(module("echarts-ng", function ($echartsProvider) {
$echartsProvider.setGlobalOption(setter);
}));
beforeEach(inject(function (_$echarts_) {
$echarts = _$echarts_;
}));
it("should extend default global option with merge override", function () {
expect($echarts.getEchartsGlobalOption().tooltip).toEqual(match);
});
}); |
/*
* MelonJS Game Engine
* Copyright (C) 2011 - 2013, Olivier Biot, Jason Oster
* http://www.melonjs.org
*
* Clay.io API plugin
*
*/
(function($) {
/**
* @class
* @public
* @extends me.plugin.Base
* @memberOf me
* @constructor
*/
Clayio = me.plugin.Base.extend({
// minimum melonJS version expected
version : "1.0.0",
gameKey: null,
_leaderboard: null,
init : function(gameKey, options) {
// call the parent constructor
this.parent();
this.gameKey = gameKey;
Clay = {};
Clay.gameKey = this.gameKey;
Clay.readyFunctions = [];
Clay.ready = function( fn ) {
Clay.readyFunctions.push( fn );
};
if (options === undefined) {
options = {
debug: false,
hideUI: false
}
}
Clay.options = {
debug: options.debug === undefined ? false: options.debug,
hideUI: options.hideUI === undefined ? false: options.hideUI,
fail: options.fail
}
window.onload = function() {
var clay = document.createElement("script");
clay.async = true;
clay.src = ( "https:" == document.location.protocol ? "https://" : "http://" ) + "cdn.clay.io/api.js";
var tag = document.getElementsByTagName("script")[0];
tag.parentNode.insertBefore(clay, tag);
}
},
leaderboard: function(id, score, callback) {
if (!id) {
throw "You must pass a leaderboard id";
}
// we can get the score directly from game.data.score
if (!score){
score = game.data.score;
}
var leaderboard = new Clay.Leaderboard({id: id});
this._leaderboard = leaderboard;
if (!callback) {
this._leaderboard.post({score: score}, callback);
}else{
this._leaderboard.post({score: score});
}
},
showLeaderBoard: function(id, options, callback) {
if (!options){
options = {};
}
if (options.limit === undefined){
options.limit = 10;
}
if (!this._leaderboard) {
if (id === undefined) {
throw "The leaderboard was not defined before. You must pass a leaderboard id";
}
var leaderboard = new Clay.Leaderboard({id: id});
this._leaderboard = leaderboard;
}
this._leaderboard.show(options, callback);
}
});
})(window);
|
//Setup
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]
}
];
function lookUpProfile(firstName, prop){
// Only change code below this line
if (!contacts[0].hasOwnProperty(prop))
return "No such property";
for (var i=0;i<contacts.length;i++)
if (contacts[i].firstName==firstName)
return contacts[i][prop];
return "No such contact";
// Only change code above this line
}
// Change these values to test your function
lookUpProfile("Akira", "likes");
|
/*
* This combined file was created by the DataTables downloader builder:
* https://datatables.net/download
*
* To rebuild or modify this file with the latest versions of the included
* software please visit:
* https://datatables.net/download/#dt/dt-1.10.24
*
* Included libraries:
* DataTables 1.10.24
*/
/*! DataTables 1.10.24
* ©2008-2021 SpryMedia Ltd - datatables.net/license
*/
/**
* @summary DataTables
* @description Paginate, search and order HTML tables
* @version 1.10.24
* @file jquery.dataTables.js
* @author SpryMedia Ltd
* @contact www.datatables.net
* @copyright Copyright 2008-2021 SpryMedia Ltd.
*
* This source file is free software, available under the following license:
* MIT license - http://datatables.net/license
*
* This source file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
*
* For details please refer to: http://www.datatables.net
*/
/*jslint evil: true, undef: true, browser: true */
/*globals $,require,jQuery,define,_selector_run,_selector_opts,_selector_first,_selector_row_indexes,_ext,_Api,_api_register,_api_registerPlural,_re_new_lines,_re_html,_re_formatted_numeric,_re_escape_regex,_empty,_intVal,_numToDecimal,_isNumber,_isHtml,_htmlNumeric,_pluck,_pluck_order,_range,_stripHtml,_unique,_fnBuildAjax,_fnAjaxUpdate,_fnAjaxParameters,_fnAjaxUpdateDraw,_fnAjaxDataSrc,_fnAddColumn,_fnColumnOptions,_fnAdjustColumnSizing,_fnVisibleToColumnIndex,_fnColumnIndexToVisible,_fnVisbleColumns,_fnGetColumns,_fnColumnTypes,_fnApplyColumnDefs,_fnHungarianMap,_fnCamelToHungarian,_fnLanguageCompat,_fnBrowserDetect,_fnAddData,_fnAddTr,_fnNodeToDataIndex,_fnNodeToColumnIndex,_fnGetCellData,_fnSetCellData,_fnSplitObjNotation,_fnGetObjectDataFn,_fnSetObjectDataFn,_fnGetDataMaster,_fnClearTable,_fnDeleteIndex,_fnInvalidate,_fnGetRowElements,_fnCreateTr,_fnBuildHead,_fnDrawHead,_fnDraw,_fnReDraw,_fnAddOptionsHtml,_fnDetectHeader,_fnGetUniqueThs,_fnFeatureHtmlFilter,_fnFilterComplete,_fnFilterCustom,_fnFilterColumn,_fnFilter,_fnFilterCreateSearch,_fnEscapeRegex,_fnFilterData,_fnFeatureHtmlInfo,_fnUpdateInfo,_fnInfoMacros,_fnInitialise,_fnInitComplete,_fnLengthChange,_fnFeatureHtmlLength,_fnFeatureHtmlPaginate,_fnPageChange,_fnFeatureHtmlProcessing,_fnProcessingDisplay,_fnFeatureHtmlTable,_fnScrollDraw,_fnApplyToChildren,_fnCalculateColumnWidths,_fnThrottle,_fnConvertToWidth,_fnGetWidestNode,_fnGetMaxLenString,_fnStringToCss,_fnSortFlatten,_fnSort,_fnSortAria,_fnSortListener,_fnSortAttachListener,_fnSortingClasses,_fnSortData,_fnSaveState,_fnLoadState,_fnSettingsFromNode,_fnLog,_fnMap,_fnBindAction,_fnCallbackReg,_fnCallbackFire,_fnLengthOverflow,_fnRenderer,_fnDataSource,_fnRowAttributes*/
(function( factory ) {
"use strict";
if ( typeof define === 'function' && define.amd ) {
// AMD
define( ['jquery'], function ( $ ) {
return factory( $, window, document );
} );
}
else if ( typeof exports === 'object' ) {
// CommonJS
module.exports = function (root, $) {
if ( ! root ) {
// CommonJS environments without a window global must pass a
// root. This will give an error otherwise
root = window;
}
if ( ! $ ) {
$ = typeof window !== 'undefined' ? // jQuery's factory checks for a global window
require('jquery') :
require('jquery')( root );
}
return factory( $, root, root.document );
};
}
else {
// Browser
factory( jQuery, window, document );
}
}
(function( $, window, document, undefined ) {
"use strict";
/**
* DataTables is a plug-in for the jQuery Javascript library. It is a highly
* flexible tool, based upon the foundations of progressive enhancement,
* which will add advanced interaction controls to any HTML table. For a
* full list of features please refer to
* [DataTables.net](href="http://datatables.net).
*
* Note that the `DataTable` object is not a global variable but is aliased
* to `jQuery.fn.DataTable` and `jQuery.fn.dataTable` through which it may
* be accessed.
*
* @class
* @param {object} [init={}] Configuration object for DataTables. Options
* are defined by {@link DataTable.defaults}
* @requires jQuery 1.7+
*
* @example
* // Basic initialisation
* $(document).ready( function {
* $('#example').dataTable();
* } );
*
* @example
* // Initialisation with configuration options - in this case, disable
* // pagination and sorting.
* $(document).ready( function {
* $('#example').dataTable( {
* "paginate": false,
* "sort": false
* } );
* } );
*/
var DataTable = function ( options )
{
/**
* Perform a jQuery selector action on the table's TR elements (from the tbody) and
* return the resulting jQuery object.
* @param {string|node|jQuery} sSelector jQuery selector or node collection to act on
* @param {object} [oOpts] Optional parameters for modifying the rows to be included
* @param {string} [oOpts.filter=none] Select TR elements that meet the current filter
* criterion ("applied") or all TR elements (i.e. no filter).
* @param {string} [oOpts.order=current] Order of the TR elements in the processed array.
* Can be either 'current', whereby the current sorting of the table is used, or
* 'original' whereby the original order the data was read into the table is used.
* @param {string} [oOpts.page=all] Limit the selection to the currently displayed page
* ("current") or not ("all"). If 'current' is given, then order is assumed to be
* 'current' and filter is 'applied', regardless of what they might be given as.
* @returns {object} jQuery object, filtered by the given selector.
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Highlight every second row
* oTable.$('tr:odd').css('backgroundColor', 'blue');
* } );
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Filter to rows with 'Webkit' in them, add a background colour and then
* // remove the filter, thus highlighting the 'Webkit' rows only.
* oTable.fnFilter('Webkit');
* oTable.$('tr', {"search": "applied"}).css('backgroundColor', 'blue');
* oTable.fnFilter('');
* } );
*/
this.$ = function ( sSelector, oOpts )
{
return this.api(true).$( sSelector, oOpts );
};
/**
* Almost identical to $ in operation, but in this case returns the data for the matched
* rows - as such, the jQuery selector used should match TR row nodes or TD/TH cell nodes
* rather than any descendants, so the data can be obtained for the row/cell. If matching
* rows are found, the data returned is the original data array/object that was used to
* create the row (or a generated array if from a DOM source).
*
* This method is often useful in-combination with $ where both functions are given the
* same parameters and the array indexes will match identically.
* @param {string|node|jQuery} sSelector jQuery selector or node collection to act on
* @param {object} [oOpts] Optional parameters for modifying the rows to be included
* @param {string} [oOpts.filter=none] Select elements that meet the current filter
* criterion ("applied") or all elements (i.e. no filter).
* @param {string} [oOpts.order=current] Order of the data in the processed array.
* Can be either 'current', whereby the current sorting of the table is used, or
* 'original' whereby the original order the data was read into the table is used.
* @param {string} [oOpts.page=all] Limit the selection to the currently displayed page
* ("current") or not ("all"). If 'current' is given, then order is assumed to be
* 'current' and filter is 'applied', regardless of what they might be given as.
* @returns {array} Data for the matched elements. If any elements, as a result of the
* selector, were not TR, TD or TH elements in the DataTable, they will have a null
* entry in the array.
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Get the data from the first row in the table
* var data = oTable._('tr:first');
*
* // Do something useful with the data
* alert( "First cell is: "+data[0] );
* } );
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Filter to 'Webkit' and get all data for
* oTable.fnFilter('Webkit');
* var data = oTable._('tr', {"search": "applied"});
*
* // Do something with the data
* alert( data.length+" rows matched the search" );
* } );
*/
this._ = function ( sSelector, oOpts )
{
return this.api(true).rows( sSelector, oOpts ).data();
};
/**
* Create a DataTables Api instance, with the currently selected tables for
* the Api's context.
* @param {boolean} [traditional=false] Set the API instance's context to be
* only the table referred to by the `DataTable.ext.iApiIndex` option, as was
* used in the API presented by DataTables 1.9- (i.e. the traditional mode),
* or if all tables captured in the jQuery object should be used.
* @return {DataTables.Api}
*/
this.api = function ( traditional )
{
return traditional ?
new _Api(
_fnSettingsFromNode( this[ _ext.iApiIndex ] )
) :
new _Api( this );
};
/**
* Add a single new row or multiple rows of data to the table. Please note
* that this is suitable for client-side processing only - if you are using
* server-side processing (i.e. "bServerSide": true), then to add data, you
* must add it to the data source, i.e. the server-side, through an Ajax call.
* @param {array|object} data The data to be added to the table. This can be:
* <ul>
* <li>1D array of data - add a single row with the data provided</li>
* <li>2D array of arrays - add multiple rows in a single call</li>
* <li>object - data object when using <i>mData</i></li>
* <li>array of objects - multiple data objects when using <i>mData</i></li>
* </ul>
* @param {bool} [redraw=true] redraw the table or not
* @returns {array} An array of integers, representing the list of indexes in
* <i>aoData</i> ({@link DataTable.models.oSettings}) that have been added to
* the table.
* @dtopt API
* @deprecated Since v1.10
*
* @example
* // Global var for counter
* var giCount = 2;
*
* $(document).ready(function() {
* $('#example').dataTable();
* } );
*
* function fnClickAddRow() {
* $('#example').dataTable().fnAddData( [
* giCount+".1",
* giCount+".2",
* giCount+".3",
* giCount+".4" ]
* );
*
* giCount++;
* }
*/
this.fnAddData = function( data, redraw )
{
var api = this.api( true );
/* Check if we want to add multiple rows or not */
var rows = Array.isArray(data) && ( Array.isArray(data[0]) || $.isPlainObject(data[0]) ) ?
api.rows.add( data ) :
api.row.add( data );
if ( redraw === undefined || redraw ) {
api.draw();
}
return rows.flatten().toArray();
};
/**
* This function will make DataTables recalculate the column sizes, based on the data
* contained in the table and the sizes applied to the columns (in the DOM, CSS or
* through the sWidth parameter). This can be useful when the width of the table's
* parent element changes (for example a window resize).
* @param {boolean} [bRedraw=true] Redraw the table or not, you will typically want to
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable( {
* "sScrollY": "200px",
* "bPaginate": false
* } );
*
* $(window).on('resize', function () {
* oTable.fnAdjustColumnSizing();
* } );
* } );
*/
this.fnAdjustColumnSizing = function ( bRedraw )
{
var api = this.api( true ).columns.adjust();
var settings = api.settings()[0];
var scroll = settings.oScroll;
if ( bRedraw === undefined || bRedraw ) {
api.draw( false );
}
else if ( scroll.sX !== "" || scroll.sY !== "" ) {
/* If not redrawing, but scrolling, we want to apply the new column sizes anyway */
_fnScrollDraw( settings );
}
};
/**
* Quickly and simply clear a table
* @param {bool} [bRedraw=true] redraw the table or not
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Immediately 'nuke' the current rows (perhaps waiting for an Ajax callback...)
* oTable.fnClearTable();
* } );
*/
this.fnClearTable = function( bRedraw )
{
var api = this.api( true ).clear();
if ( bRedraw === undefined || bRedraw ) {
api.draw();
}
};
/**
* The exact opposite of 'opening' a row, this function will close any rows which
* are currently 'open'.
* @param {node} nTr the table row to 'close'
* @returns {int} 0 on success, or 1 if failed (can't find the row)
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable;
*
* // 'open' an information row when a row is clicked on
* $('#example tbody tr').click( function () {
* if ( oTable.fnIsOpen(this) ) {
* oTable.fnClose( this );
* } else {
* oTable.fnOpen( this, "Temporary row opened", "info_row" );
* }
* } );
*
* oTable = $('#example').dataTable();
* } );
*/
this.fnClose = function( nTr )
{
this.api( true ).row( nTr ).child.hide();
};
/**
* Remove a row for the table
* @param {mixed} target The index of the row from aoData to be deleted, or
* the TR element you want to delete
* @param {function|null} [callBack] Callback function
* @param {bool} [redraw=true] Redraw the table or not
* @returns {array} The row that was deleted
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Immediately remove the first row
* oTable.fnDeleteRow( 0 );
* } );
*/
this.fnDeleteRow = function( target, callback, redraw )
{
var api = this.api( true );
var rows = api.rows( target );
var settings = rows.settings()[0];
var data = settings.aoData[ rows[0][0] ];
rows.remove();
if ( callback ) {
callback.call( this, settings, data );
}
if ( redraw === undefined || redraw ) {
api.draw();
}
return data;
};
/**
* Restore the table to it's original state in the DOM by removing all of DataTables
* enhancements, alterations to the DOM structure of the table and event listeners.
* @param {boolean} [remove=false] Completely remove the table from the DOM
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* // This example is fairly pointless in reality, but shows how fnDestroy can be used
* var oTable = $('#example').dataTable();
* oTable.fnDestroy();
* } );
*/
this.fnDestroy = function ( remove )
{
this.api( true ).destroy( remove );
};
/**
* Redraw the table
* @param {bool} [complete=true] Re-filter and resort (if enabled) the table before the draw.
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Re-draw the table - you wouldn't want to do it here, but it's an example :-)
* oTable.fnDraw();
* } );
*/
this.fnDraw = function( complete )
{
// Note that this isn't an exact match to the old call to _fnDraw - it takes
// into account the new data, but can hold position.
this.api( true ).draw( complete );
};
/**
* Filter the input based on data
* @param {string} sInput String to filter the table on
* @param {int|null} [iColumn] Column to limit filtering to
* @param {bool} [bRegex=false] Treat as regular expression or not
* @param {bool} [bSmart=true] Perform smart filtering or not
* @param {bool} [bShowGlobal=true] Show the input global filter in it's input box(es)
* @param {bool} [bCaseInsensitive=true] Do case-insensitive matching (true) or not (false)
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Sometime later - filter...
* oTable.fnFilter( 'test string' );
* } );
*/
this.fnFilter = function( sInput, iColumn, bRegex, bSmart, bShowGlobal, bCaseInsensitive )
{
var api = this.api( true );
if ( iColumn === null || iColumn === undefined ) {
api.search( sInput, bRegex, bSmart, bCaseInsensitive );
}
else {
api.column( iColumn ).search( sInput, bRegex, bSmart, bCaseInsensitive );
}
api.draw();
};
/**
* Get the data for the whole table, an individual row or an individual cell based on the
* provided parameters.
* @param {int|node} [src] A TR row node, TD/TH cell node or an integer. If given as
* a TR node then the data source for the whole row will be returned. If given as a
* TD/TH cell node then iCol will be automatically calculated and the data for the
* cell returned. If given as an integer, then this is treated as the aoData internal
* data index for the row (see fnGetPosition) and the data for that row used.
* @param {int} [col] Optional column index that you want the data of.
* @returns {array|object|string} If mRow is undefined, then the data for all rows is
* returned. If mRow is defined, just data for that row, and is iCol is
* defined, only data for the designated cell is returned.
* @dtopt API
* @deprecated Since v1.10
*
* @example
* // Row data
* $(document).ready(function() {
* oTable = $('#example').dataTable();
*
* oTable.$('tr').click( function () {
* var data = oTable.fnGetData( this );
* // ... do something with the array / object of data for the row
* } );
* } );
*
* @example
* // Individual cell data
* $(document).ready(function() {
* oTable = $('#example').dataTable();
*
* oTable.$('td').click( function () {
* var sData = oTable.fnGetData( this );
* alert( 'The cell clicked on had the value of '+sData );
* } );
* } );
*/
this.fnGetData = function( src, col )
{
var api = this.api( true );
if ( src !== undefined ) {
var type = src.nodeName ? src.nodeName.toLowerCase() : '';
return col !== undefined || type == 'td' || type == 'th' ?
api.cell( src, col ).data() :
api.row( src ).data() || null;
}
return api.data().toArray();
};
/**
* Get an array of the TR nodes that are used in the table's body. Note that you will
* typically want to use the '$' API method in preference to this as it is more
* flexible.
* @param {int} [iRow] Optional row index for the TR element you want
* @returns {array|node} If iRow is undefined, returns an array of all TR elements
* in the table's body, or iRow is defined, just the TR element requested.
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Get the nodes from the table
* var nNodes = oTable.fnGetNodes( );
* } );
*/
this.fnGetNodes = function( iRow )
{
var api = this.api( true );
return iRow !== undefined ?
api.row( iRow ).node() :
api.rows().nodes().flatten().toArray();
};
/**
* Get the array indexes of a particular cell from it's DOM element
* and column index including hidden columns
* @param {node} node this can either be a TR, TD or TH in the table's body
* @returns {int} If nNode is given as a TR, then a single index is returned, or
* if given as a cell, an array of [row index, column index (visible),
* column index (all)] is given.
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* $('#example tbody td').click( function () {
* // Get the position of the current data from the node
* var aPos = oTable.fnGetPosition( this );
*
* // Get the data array for this row
* var aData = oTable.fnGetData( aPos[0] );
*
* // Update the data array and return the value
* aData[ aPos[1] ] = 'clicked';
* this.innerHTML = 'clicked';
* } );
*
* // Init DataTables
* oTable = $('#example').dataTable();
* } );
*/
this.fnGetPosition = function( node )
{
var api = this.api( true );
var nodeName = node.nodeName.toUpperCase();
if ( nodeName == 'TR' ) {
return api.row( node ).index();
}
else if ( nodeName == 'TD' || nodeName == 'TH' ) {
var cell = api.cell( node ).index();
return [
cell.row,
cell.columnVisible,
cell.column
];
}
return null;
};
/**
* Check to see if a row is 'open' or not.
* @param {node} nTr the table row to check
* @returns {boolean} true if the row is currently open, false otherwise
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable;
*
* // 'open' an information row when a row is clicked on
* $('#example tbody tr').click( function () {
* if ( oTable.fnIsOpen(this) ) {
* oTable.fnClose( this );
* } else {
* oTable.fnOpen( this, "Temporary row opened", "info_row" );
* }
* } );
*
* oTable = $('#example').dataTable();
* } );
*/
this.fnIsOpen = function( nTr )
{
return this.api( true ).row( nTr ).child.isShown();
};
/**
* This function will place a new row directly after a row which is currently
* on display on the page, with the HTML contents that is passed into the
* function. This can be used, for example, to ask for confirmation that a
* particular record should be deleted.
* @param {node} nTr The table row to 'open'
* @param {string|node|jQuery} mHtml The HTML to put into the row
* @param {string} sClass Class to give the new TD cell
* @returns {node} The row opened. Note that if the table row passed in as the
* first parameter, is not found in the table, this method will silently
* return.
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable;
*
* // 'open' an information row when a row is clicked on
* $('#example tbody tr').click( function () {
* if ( oTable.fnIsOpen(this) ) {
* oTable.fnClose( this );
* } else {
* oTable.fnOpen( this, "Temporary row opened", "info_row" );
* }
* } );
*
* oTable = $('#example').dataTable();
* } );
*/
this.fnOpen = function( nTr, mHtml, sClass )
{
return this.api( true )
.row( nTr )
.child( mHtml, sClass )
.show()
.child()[0];
};
/**
* Change the pagination - provides the internal logic for pagination in a simple API
* function. With this function you can have a DataTables table go to the next,
* previous, first or last pages.
* @param {string|int} mAction Paging action to take: "first", "previous", "next" or "last"
* or page number to jump to (integer), note that page 0 is the first page.
* @param {bool} [bRedraw=true] Redraw the table or not
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
* oTable.fnPageChange( 'next' );
* } );
*/
this.fnPageChange = function ( mAction, bRedraw )
{
var api = this.api( true ).page( mAction );
if ( bRedraw === undefined || bRedraw ) {
api.draw(false);
}
};
/**
* Show a particular column
* @param {int} iCol The column whose display should be changed
* @param {bool} bShow Show (true) or hide (false) the column
* @param {bool} [bRedraw=true] Redraw the table or not
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Hide the second column after initialisation
* oTable.fnSetColumnVis( 1, false );
* } );
*/
this.fnSetColumnVis = function ( iCol, bShow, bRedraw )
{
var api = this.api( true ).column( iCol ).visible( bShow );
if ( bRedraw === undefined || bRedraw ) {
api.columns.adjust().draw();
}
};
/**
* Get the settings for a particular table for external manipulation
* @returns {object} DataTables settings object. See
* {@link DataTable.models.oSettings}
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
* var oSettings = oTable.fnSettings();
*
* // Show an example parameter from the settings
* alert( oSettings._iDisplayStart );
* } );
*/
this.fnSettings = function()
{
return _fnSettingsFromNode( this[_ext.iApiIndex] );
};
/**
* Sort the table by a particular column
* @param {int} iCol the data index to sort on. Note that this will not match the
* 'display index' if you have hidden data entries
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Sort immediately with columns 0 and 1
* oTable.fnSort( [ [0,'asc'], [1,'asc'] ] );
* } );
*/
this.fnSort = function( aaSort )
{
this.api( true ).order( aaSort ).draw();
};
/**
* Attach a sort listener to an element for a given column
* @param {node} nNode the element to attach the sort listener to
* @param {int} iColumn the column that a click on this node will sort on
* @param {function} [fnCallback] callback function when sort is run
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
*
* // Sort on column 1, when 'sorter' is clicked on
* oTable.fnSortListener( document.getElementById('sorter'), 1 );
* } );
*/
this.fnSortListener = function( nNode, iColumn, fnCallback )
{
this.api( true ).order.listener( nNode, iColumn, fnCallback );
};
/**
* Update a table cell or row - this method will accept either a single value to
* update the cell with, an array of values with one element for each column or
* an object in the same format as the original data source. The function is
* self-referencing in order to make the multi column updates easier.
* @param {object|array|string} mData Data to update the cell/row with
* @param {node|int} mRow TR element you want to update or the aoData index
* @param {int} [iColumn] The column to update, give as null or undefined to
* update a whole row.
* @param {bool} [bRedraw=true] Redraw the table or not
* @param {bool} [bAction=true] Perform pre-draw actions or not
* @returns {int} 0 on success, 1 on error
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
* oTable.fnUpdate( 'Example update', 0, 0 ); // Single cell
* oTable.fnUpdate( ['a', 'b', 'c', 'd', 'e'], $('tbody tr')[0] ); // Row
* } );
*/
this.fnUpdate = function( mData, mRow, iColumn, bRedraw, bAction )
{
var api = this.api( true );
if ( iColumn === undefined || iColumn === null ) {
api.row( mRow ).data( mData );
}
else {
api.cell( mRow, iColumn ).data( mData );
}
if ( bAction === undefined || bAction ) {
api.columns.adjust();
}
if ( bRedraw === undefined || bRedraw ) {
api.draw();
}
return 0;
};
/**
* Provide a common method for plug-ins to check the version of DataTables being used, in order
* to ensure compatibility.
* @param {string} sVersion Version string to check for, in the format "X.Y.Z". Note that the
* formats "X" and "X.Y" are also acceptable.
* @returns {boolean} true if this version of DataTables is greater or equal to the required
* version, or false if this version of DataTales is not suitable
* @method
* @dtopt API
* @deprecated Since v1.10
*
* @example
* $(document).ready(function() {
* var oTable = $('#example').dataTable();
* alert( oTable.fnVersionCheck( '1.9.0' ) );
* } );
*/
this.fnVersionCheck = _ext.fnVersionCheck;
var _that = this;
var emptyInit = options === undefined;
var len = this.length;
if ( emptyInit ) {
options = {};
}
this.oApi = this.internal = _ext.internal;
// Extend with old style plug-in API methods
for ( var fn in DataTable.ext.internal ) {
if ( fn ) {
this[fn] = _fnExternApiFunc(fn);
}
}
this.each(function() {
// For each initialisation we want to give it a clean initialisation
// object that can be bashed around
var o = {};
var oInit = len > 1 ? // optimisation for single table case
_fnExtend( o, options, true ) :
options;
/*global oInit,_that,emptyInit*/
var i=0, iLen, j, jLen, k, kLen;
var sId = this.getAttribute( 'id' );
var bInitHandedOff = false;
var defaults = DataTable.defaults;
var $this = $(this);
/* Sanity check */
if ( this.nodeName.toLowerCase() != 'table' )
{
_fnLog( null, 0, 'Non-table node initialisation ('+this.nodeName+')', 2 );
return;
}
/* Backwards compatibility for the defaults */
_fnCompatOpts( defaults );
_fnCompatCols( defaults.column );
/* Convert the camel-case defaults to Hungarian */
_fnCamelToHungarian( defaults, defaults, true );
_fnCamelToHungarian( defaults.column, defaults.column, true );
/* Setting up the initialisation object */
_fnCamelToHungarian( defaults, $.extend( oInit, $this.data() ), true );
/* Check to see if we are re-initialising a table */
var allSettings = DataTable.settings;
for ( i=0, iLen=allSettings.length ; i<iLen ; i++ )
{
var s = allSettings[i];
/* Base check on table node */
if (
s.nTable == this ||
(s.nTHead && s.nTHead.parentNode == this) ||
(s.nTFoot && s.nTFoot.parentNode == this)
) {
var bRetrieve = oInit.bRetrieve !== undefined ? oInit.bRetrieve : defaults.bRetrieve;
var bDestroy = oInit.bDestroy !== undefined ? oInit.bDestroy : defaults.bDestroy;
if ( emptyInit || bRetrieve )
{
return s.oInstance;
}
else if ( bDestroy )
{
s.oInstance.fnDestroy();
break;
}
else
{
_fnLog( s, 0, 'Cannot reinitialise DataTable', 3 );
return;
}
}
/* If the element we are initialising has the same ID as a table which was previously
* initialised, but the table nodes don't match (from before) then we destroy the old
* instance by simply deleting it. This is under the assumption that the table has been
* destroyed by other methods. Anyone using non-id selectors will need to do this manually
*/
if ( s.sTableId == this.id )
{
allSettings.splice( i, 1 );
break;
}
}
/* Ensure the table has an ID - required for accessibility */
if ( sId === null || sId === "" )
{
sId = "DataTables_Table_"+(DataTable.ext._unique++);
this.id = sId;
}
/* Create the settings object for this table and set some of the default parameters */
var oSettings = $.extend( true, {}, DataTable.models.oSettings, {
"sDestroyWidth": $this[0].style.width,
"sInstance": sId,
"sTableId": sId
} );
oSettings.nTable = this;
oSettings.oApi = _that.internal;
oSettings.oInit = oInit;
allSettings.push( oSettings );
// Need to add the instance after the instance after the settings object has been added
// to the settings array, so we can self reference the table instance if more than one
oSettings.oInstance = (_that.length===1) ? _that : $this.dataTable();
// Backwards compatibility, before we apply all the defaults
_fnCompatOpts( oInit );
_fnLanguageCompat( oInit.oLanguage );
// If the length menu is given, but the init display length is not, use the length menu
if ( oInit.aLengthMenu && ! oInit.iDisplayLength )
{
oInit.iDisplayLength = Array.isArray( oInit.aLengthMenu[0] ) ?
oInit.aLengthMenu[0][0] : oInit.aLengthMenu[0];
}
// Apply the defaults and init options to make a single init object will all
// options defined from defaults and instance options.
oInit = _fnExtend( $.extend( true, {}, defaults ), oInit );
// Map the initialisation options onto the settings object
_fnMap( oSettings.oFeatures, oInit, [
"bPaginate",
"bLengthChange",
"bFilter",
"bSort",
"bSortMulti",
"bInfo",
"bProcessing",
"bAutoWidth",
"bSortClasses",
"bServerSide",
"bDeferRender"
] );
_fnMap( oSettings, oInit, [
"asStripeClasses",
"ajax",
"fnServerData",
"fnFormatNumber",
"sServerMethod",
"aaSorting",
"aaSortingFixed",
"aLengthMenu",
"sPaginationType",
"sAjaxSource",
"sAjaxDataProp",
"iStateDuration",
"sDom",
"bSortCellsTop",
"iTabIndex",
"fnStateLoadCallback",
"fnStateSaveCallback",
"renderer",
"searchDelay",
"rowId",
[ "iCookieDuration", "iStateDuration" ], // backwards compat
[ "oSearch", "oPreviousSearch" ],
[ "aoSearchCols", "aoPreSearchCols" ],
[ "iDisplayLength", "_iDisplayLength" ]
] );
_fnMap( oSettings.oScroll, oInit, [
[ "sScrollX", "sX" ],
[ "sScrollXInner", "sXInner" ],
[ "sScrollY", "sY" ],
[ "bScrollCollapse", "bCollapse" ]
] );
_fnMap( oSettings.oLanguage, oInit, "fnInfoCallback" );
/* Callback functions which are array driven */
_fnCallbackReg( oSettings, 'aoDrawCallback', oInit.fnDrawCallback, 'user' );
_fnCallbackReg( oSettings, 'aoServerParams', oInit.fnServerParams, 'user' );
_fnCallbackReg( oSettings, 'aoStateSaveParams', oInit.fnStateSaveParams, 'user' );
_fnCallbackReg( oSettings, 'aoStateLoadParams', oInit.fnStateLoadParams, 'user' );
_fnCallbackReg( oSettings, 'aoStateLoaded', oInit.fnStateLoaded, 'user' );
_fnCallbackReg( oSettings, 'aoRowCallback', oInit.fnRowCallback, 'user' );
_fnCallbackReg( oSettings, 'aoRowCreatedCallback', oInit.fnCreatedRow, 'user' );
_fnCallbackReg( oSettings, 'aoHeaderCallback', oInit.fnHeaderCallback, 'user' );
_fnCallbackReg( oSettings, 'aoFooterCallback', oInit.fnFooterCallback, 'user' );
_fnCallbackReg( oSettings, 'aoInitComplete', oInit.fnInitComplete, 'user' );
_fnCallbackReg( oSettings, 'aoPreDrawCallback', oInit.fnPreDrawCallback, 'user' );
oSettings.rowIdFn = _fnGetObjectDataFn( oInit.rowId );
/* Browser support detection */
_fnBrowserDetect( oSettings );
var oClasses = oSettings.oClasses;
$.extend( oClasses, DataTable.ext.classes, oInit.oClasses );
$this.addClass( oClasses.sTable );
if ( oSettings.iInitDisplayStart === undefined )
{
/* Display start point, taking into account the save saving */
oSettings.iInitDisplayStart = oInit.iDisplayStart;
oSettings._iDisplayStart = oInit.iDisplayStart;
}
if ( oInit.iDeferLoading !== null )
{
oSettings.bDeferLoading = true;
var tmp = Array.isArray( oInit.iDeferLoading );
oSettings._iRecordsDisplay = tmp ? oInit.iDeferLoading[0] : oInit.iDeferLoading;
oSettings._iRecordsTotal = tmp ? oInit.iDeferLoading[1] : oInit.iDeferLoading;
}
/* Language definitions */
var oLanguage = oSettings.oLanguage;
$.extend( true, oLanguage, oInit.oLanguage );
if ( oLanguage.sUrl )
{
/* Get the language definitions from a file - because this Ajax call makes the language
* get async to the remainder of this function we use bInitHandedOff to indicate that
* _fnInitialise will be fired by the returned Ajax handler, rather than the constructor
*/
$.ajax( {
dataType: 'json',
url: oLanguage.sUrl,
success: function ( json ) {
_fnLanguageCompat( json );
_fnCamelToHungarian( defaults.oLanguage, json );
$.extend( true, oLanguage, json );
_fnCallbackFire( oSettings, null, 'i18n', [oSettings]);
_fnInitialise( oSettings );
},
error: function () {
// Error occurred loading language file, continue on as best we can
_fnInitialise( oSettings );
}
} );
bInitHandedOff = true;
}
else {
_fnCallbackFire( oSettings, null, 'i18n', [oSettings]);
}
/*
* Stripes
*/
if ( oInit.asStripeClasses === null )
{
oSettings.asStripeClasses =[
oClasses.sStripeOdd,
oClasses.sStripeEven
];
}
/* Remove row stripe classes if they are already on the table row */
var stripeClasses = oSettings.asStripeClasses;
var rowOne = $this.children('tbody').find('tr').eq(0);
if ( $.inArray( true, $.map( stripeClasses, function(el, i) {
return rowOne.hasClass(el);
} ) ) !== -1 ) {
$('tbody tr', this).removeClass( stripeClasses.join(' ') );
oSettings.asDestroyStripes = stripeClasses.slice();
}
/*
* Columns
* See if we should load columns automatically or use defined ones
*/
var anThs = [];
var aoColumnsInit;
var nThead = this.getElementsByTagName('thead');
if ( nThead.length !== 0 )
{
_fnDetectHeader( oSettings.aoHeader, nThead[0] );
anThs = _fnGetUniqueThs( oSettings );
}
/* If not given a column array, generate one with nulls */
if ( oInit.aoColumns === null )
{
aoColumnsInit = [];
for ( i=0, iLen=anThs.length ; i<iLen ; i++ )
{
aoColumnsInit.push( null );
}
}
else
{
aoColumnsInit = oInit.aoColumns;
}
/* Add the columns */
for ( i=0, iLen=aoColumnsInit.length ; i<iLen ; i++ )
{
_fnAddColumn( oSettings, anThs ? anThs[i] : null );
}
/* Apply the column definitions */
_fnApplyColumnDefs( oSettings, oInit.aoColumnDefs, aoColumnsInit, function (iCol, oDef) {
_fnColumnOptions( oSettings, iCol, oDef );
} );
/* HTML5 attribute detection - build an mData object automatically if the
* attributes are found
*/
if ( rowOne.length ) {
var a = function ( cell, name ) {
return cell.getAttribute( 'data-'+name ) !== null ? name : null;
};
$( rowOne[0] ).children('th, td').each( function (i, cell) {
var col = oSettings.aoColumns[i];
if ( col.mData === i ) {
var sort = a( cell, 'sort' ) || a( cell, 'order' );
var filter = a( cell, 'filter' ) || a( cell, 'search' );
if ( sort !== null || filter !== null ) {
col.mData = {
_: i+'.display',
sort: sort !== null ? i+'.@data-'+sort : undefined,
type: sort !== null ? i+'.@data-'+sort : undefined,
filter: filter !== null ? i+'.@data-'+filter : undefined
};
_fnColumnOptions( oSettings, i );
}
}
} );
}
var features = oSettings.oFeatures;
var loadedInit = function () {
/*
* Sorting
* @todo For modularisation (1.11) this needs to do into a sort start up handler
*/
// If aaSorting is not defined, then we use the first indicator in asSorting
// in case that has been altered, so the default sort reflects that option
if ( oInit.aaSorting === undefined ) {
var sorting = oSettings.aaSorting;
for ( i=0, iLen=sorting.length ; i<iLen ; i++ ) {
sorting[i][1] = oSettings.aoColumns[ i ].asSorting[0];
}
}
/* Do a first pass on the sorting classes (allows any size changes to be taken into
* account, and also will apply sorting disabled classes if disabled
*/
_fnSortingClasses( oSettings );
if ( features.bSort ) {
_fnCallbackReg( oSettings, 'aoDrawCallback', function () {
if ( oSettings.bSorted ) {
var aSort = _fnSortFlatten( oSettings );
var sortedColumns = {};
$.each( aSort, function (i, val) {
sortedColumns[ val.src ] = val.dir;
} );
_fnCallbackFire( oSettings, null, 'order', [oSettings, aSort, sortedColumns] );
_fnSortAria( oSettings );
}
} );
}
_fnCallbackReg( oSettings, 'aoDrawCallback', function () {
if ( oSettings.bSorted || _fnDataSource( oSettings ) === 'ssp' || features.bDeferRender ) {
_fnSortingClasses( oSettings );
}
}, 'sc' );
/*
* Final init
* Cache the header, body and footer as required, creating them if needed
*/
// Work around for Webkit bug 83867 - store the caption-side before removing from doc
var captions = $this.children('caption').each( function () {
this._captionSide = $(this).css('caption-side');
} );
var thead = $this.children('thead');
if ( thead.length === 0 ) {
thead = $('<thead/>').appendTo($this);
}
oSettings.nTHead = thead[0];
var tbody = $this.children('tbody');
if ( tbody.length === 0 ) {
tbody = $('<tbody/>').appendTo($this);
}
oSettings.nTBody = tbody[0];
var tfoot = $this.children('tfoot');
if ( tfoot.length === 0 && captions.length > 0 && (oSettings.oScroll.sX !== "" || oSettings.oScroll.sY !== "") ) {
// If we are a scrolling table, and no footer has been given, then we need to create
// a tfoot element for the caption element to be appended to
tfoot = $('<tfoot/>').appendTo($this);
}
if ( tfoot.length === 0 || tfoot.children().length === 0 ) {
$this.addClass( oClasses.sNoFooter );
}
else if ( tfoot.length > 0 ) {
oSettings.nTFoot = tfoot[0];
_fnDetectHeader( oSettings.aoFooter, oSettings.nTFoot );
}
/* Check if there is data passing into the constructor */
if ( oInit.aaData ) {
for ( i=0 ; i<oInit.aaData.length ; i++ ) {
_fnAddData( oSettings, oInit.aaData[ i ] );
}
}
else if ( oSettings.bDeferLoading || _fnDataSource( oSettings ) == 'dom' ) {
/* Grab the data from the page - only do this when deferred loading or no Ajax
* source since there is no point in reading the DOM data if we are then going
* to replace it with Ajax data
*/
_fnAddTr( oSettings, $(oSettings.nTBody).children('tr') );
}
/* Copy the data index array */
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
/* Initialisation complete - table can be drawn */
oSettings.bInitialised = true;
/* Check if we need to initialise the table (it might not have been handed off to the
* language processor)
*/
if ( bInitHandedOff === false ) {
_fnInitialise( oSettings );
}
};
/* Must be done after everything which can be overridden by the state saving! */
if ( oInit.bStateSave )
{
features.bStateSave = true;
_fnCallbackReg( oSettings, 'aoDrawCallback', _fnSaveState, 'state_save' );
_fnLoadState( oSettings, oInit, loadedInit );
}
else {
loadedInit();
}
} );
_that = null;
return this;
};
/*
* It is useful to have variables which are scoped locally so only the
* DataTables functions can access them and they don't leak into global space.
* At the same time these functions are often useful over multiple files in the
* core and API, so we list, or at least document, all variables which are used
* by DataTables as private variables here. This also ensures that there is no
* clashing of variable names and that they can easily referenced for reuse.
*/
// Defined else where
// _selector_run
// _selector_opts
// _selector_first
// _selector_row_indexes
var _ext; // DataTable.ext
var _Api; // DataTable.Api
var _api_register; // DataTable.Api.register
var _api_registerPlural; // DataTable.Api.registerPlural
var _re_dic = {};
var _re_new_lines = /[\r\n\u2028]/g;
var _re_html = /<.*?>/g;
// This is not strict ISO8601 - Date.parse() is quite lax, although
// implementations differ between browsers.
var _re_date = /^\d{2,4}[\.\/\-]\d{1,2}[\.\/\-]\d{1,2}([T ]{1}\d{1,2}[:\.]\d{2}([\.:]\d{2})?)?$/;
// Escape regular expression special characters
var _re_escape_regex = new RegExp( '(\\' + [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\', '$', '^', '-' ].join('|\\') + ')', 'g' );
// http://en.wikipedia.org/wiki/Foreign_exchange_market
// - \u20BD - Russian ruble.
// - \u20a9 - South Korean Won
// - \u20BA - Turkish Lira
// - \u20B9 - Indian Rupee
// - R - Brazil (R$) and South Africa
// - fr - Swiss Franc
// - kr - Swedish krona, Norwegian krone and Danish krone
// - \u2009 is thin space and \u202F is narrow no-break space, both used in many
// - Ƀ - Bitcoin
// - Ξ - Ethereum
// standards as thousands separators.
var _re_formatted_numeric = /['\u00A0,$£€¥%\u2009\u202F\u20BD\u20a9\u20BArfkɃΞ]/gi;
var _empty = function ( d ) {
return !d || d === true || d === '-' ? true : false;
};
var _intVal = function ( s ) {
var integer = parseInt( s, 10 );
return !isNaN(integer) && isFinite(s) ? integer : null;
};
// Convert from a formatted number with characters other than `.` as the
// decimal place, to a Javascript number
var _numToDecimal = function ( num, decimalPoint ) {
// Cache created regular expressions for speed as this function is called often
if ( ! _re_dic[ decimalPoint ] ) {
_re_dic[ decimalPoint ] = new RegExp( _fnEscapeRegex( decimalPoint ), 'g' );
}
return typeof num === 'string' && decimalPoint !== '.' ?
num.replace( /\./g, '' ).replace( _re_dic[ decimalPoint ], '.' ) :
num;
};
var _isNumber = function ( d, decimalPoint, formatted ) {
var strType = typeof d === 'string';
// If empty return immediately so there must be a number if it is a
// formatted string (this stops the string "k", or "kr", etc being detected
// as a formatted number for currency
if ( _empty( d ) ) {
return true;
}
if ( decimalPoint && strType ) {
d = _numToDecimal( d, decimalPoint );
}
if ( formatted && strType ) {
d = d.replace( _re_formatted_numeric, '' );
}
return !isNaN( parseFloat(d) ) && isFinite( d );
};
// A string without HTML in it can be considered to be HTML still
var _isHtml = function ( d ) {
return _empty( d ) || typeof d === 'string';
};
var _htmlNumeric = function ( d, decimalPoint, formatted ) {
if ( _empty( d ) ) {
return true;
}
var html = _isHtml( d );
return ! html ?
null :
_isNumber( _stripHtml( d ), decimalPoint, formatted ) ?
true :
null;
};
var _pluck = function ( a, prop, prop2 ) {
var out = [];
var i=0, ien=a.length;
// Could have the test in the loop for slightly smaller code, but speed
// is essential here
if ( prop2 !== undefined ) {
for ( ; i<ien ; i++ ) {
if ( a[i] && a[i][ prop ] ) {
out.push( a[i][ prop ][ prop2 ] );
}
}
}
else {
for ( ; i<ien ; i++ ) {
if ( a[i] ) {
out.push( a[i][ prop ] );
}
}
}
return out;
};
// Basically the same as _pluck, but rather than looping over `a` we use `order`
// as the indexes to pick from `a`
var _pluck_order = function ( a, order, prop, prop2 )
{
var out = [];
var i=0, ien=order.length;
// Could have the test in the loop for slightly smaller code, but speed
// is essential here
if ( prop2 !== undefined ) {
for ( ; i<ien ; i++ ) {
if ( a[ order[i] ][ prop ] ) {
out.push( a[ order[i] ][ prop ][ prop2 ] );
}
}
}
else {
for ( ; i<ien ; i++ ) {
out.push( a[ order[i] ][ prop ] );
}
}
return out;
};
var _range = function ( len, start )
{
var out = [];
var end;
if ( start === undefined ) {
start = 0;
end = len;
}
else {
end = start;
start = len;
}
for ( var i=start ; i<end ; i++ ) {
out.push( i );
}
return out;
};
var _removeEmpty = function ( a )
{
var out = [];
for ( var i=0, ien=a.length ; i<ien ; i++ ) {
if ( a[i] ) { // careful - will remove all falsy values!
out.push( a[i] );
}
}
return out;
};
var _stripHtml = function ( d ) {
return d.replace( _re_html, '' );
};
/**
* Determine if all values in the array are unique. This means we can short
* cut the _unique method at the cost of a single loop. A sorted array is used
* to easily check the values.
*
* @param {array} src Source array
* @return {boolean} true if all unique, false otherwise
* @ignore
*/
var _areAllUnique = function ( src ) {
if ( src.length < 2 ) {
return true;
}
var sorted = src.slice().sort();
var last = sorted[0];
for ( var i=1, ien=sorted.length ; i<ien ; i++ ) {
if ( sorted[i] === last ) {
return false;
}
last = sorted[i];
}
return true;
};
/**
* Find the unique elements in a source array.
*
* @param {array} src Source array
* @return {array} Array of unique items
* @ignore
*/
var _unique = function ( src )
{
if ( _areAllUnique( src ) ) {
return src.slice();
}
// A faster unique method is to use object keys to identify used values,
// but this doesn't work with arrays or objects, which we must also
// consider. See jsperf.com/compare-array-unique-versions/4 for more
// information.
var
out = [],
val,
i, ien=src.length,
j, k=0;
again: for ( i=0 ; i<ien ; i++ ) {
val = src[i];
for ( j=0 ; j<k ; j++ ) {
if ( out[j] === val ) {
continue again;
}
}
out.push( val );
k++;
}
return out;
};
// Surprisingly this is faster than [].concat.apply
// https://jsperf.com/flatten-an-array-loop-vs-reduce/2
var _flatten = function (out, val) {
if (Array.isArray(val)) {
for (var i=0 ; i<val.length ; i++) {
_flatten(out, val[i]);
}
}
else {
out.push(val);
}
return out;
}
// Array.isArray polyfill.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
if (! Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
// .trim() polyfill
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
};
}
/**
* DataTables utility methods
*
* This namespace provides helper methods that DataTables uses internally to
* create a DataTable, but which are not exclusively used only for DataTables.
* These methods can be used by extension authors to save the duplication of
* code.
*
* @namespace
*/
DataTable.util = {
/**
* Throttle the calls to a function. Arguments and context are maintained
* for the throttled function.
*
* @param {function} fn Function to be called
* @param {integer} freq Call frequency in mS
* @return {function} Wrapped function
*/
throttle: function ( fn, freq ) {
var
frequency = freq !== undefined ? freq : 200,
last,
timer;
return function () {
var
that = this,
now = +new Date(),
args = arguments;
if ( last && now < last + frequency ) {
clearTimeout( timer );
timer = setTimeout( function () {
last = undefined;
fn.apply( that, args );
}, frequency );
}
else {
last = now;
fn.apply( that, args );
}
};
},
/**
* Escape a string such that it can be used in a regular expression
*
* @param {string} val string to escape
* @returns {string} escaped string
*/
escapeRegex: function ( val ) {
return val.replace( _re_escape_regex, '\\$1' );
}
};
/**
* Create a mapping object that allows camel case parameters to be looked up
* for their Hungarian counterparts. The mapping is stored in a private
* parameter called `_hungarianMap` which can be accessed on the source object.
* @param {object} o
* @memberof DataTable#oApi
*/
function _fnHungarianMap ( o )
{
var
hungarian = 'a aa ai ao as b fn i m o s ',
match,
newKey,
map = {};
$.each( o, function (key, val) {
match = key.match(/^([^A-Z]+?)([A-Z])/);
if ( match && hungarian.indexOf(match[1]+' ') !== -1 )
{
newKey = key.replace( match[0], match[2].toLowerCase() );
map[ newKey ] = key;
if ( match[1] === 'o' )
{
_fnHungarianMap( o[key] );
}
}
} );
o._hungarianMap = map;
}
/**
* Convert from camel case parameters to Hungarian, based on a Hungarian map
* created by _fnHungarianMap.
* @param {object} src The model object which holds all parameters that can be
* mapped.
* @param {object} user The object to convert from camel case to Hungarian.
* @param {boolean} force When set to `true`, properties which already have a
* Hungarian value in the `user` object will be overwritten. Otherwise they
* won't be.
* @memberof DataTable#oApi
*/
function _fnCamelToHungarian ( src, user, force )
{
if ( ! src._hungarianMap ) {
_fnHungarianMap( src );
}
var hungarianKey;
$.each( user, function (key, val) {
hungarianKey = src._hungarianMap[ key ];
if ( hungarianKey !== undefined && (force || user[hungarianKey] === undefined) )
{
// For objects, we need to buzz down into the object to copy parameters
if ( hungarianKey.charAt(0) === 'o' )
{
// Copy the camelCase options over to the hungarian
if ( ! user[ hungarianKey ] ) {
user[ hungarianKey ] = {};
}
$.extend( true, user[hungarianKey], user[key] );
_fnCamelToHungarian( src[hungarianKey], user[hungarianKey], force );
}
else {
user[hungarianKey] = user[ key ];
}
}
} );
}
/**
* Language compatibility - when certain options are given, and others aren't, we
* need to duplicate the values over, in order to provide backwards compatibility
* with older language files.
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnLanguageCompat( lang )
{
// Note the use of the Hungarian notation for the parameters in this method as
// this is called after the mapping of camelCase to Hungarian
var defaults = DataTable.defaults.oLanguage;
// Default mapping
var defaultDecimal = defaults.sDecimal;
if ( defaultDecimal ) {
_addNumericSort( defaultDecimal );
}
if ( lang ) {
var zeroRecords = lang.sZeroRecords;
// Backwards compatibility - if there is no sEmptyTable given, then use the same as
// sZeroRecords - assuming that is given.
if ( ! lang.sEmptyTable && zeroRecords &&
defaults.sEmptyTable === "No data available in table" )
{
_fnMap( lang, lang, 'sZeroRecords', 'sEmptyTable' );
}
// Likewise with loading records
if ( ! lang.sLoadingRecords && zeroRecords &&
defaults.sLoadingRecords === "Loading..." )
{
_fnMap( lang, lang, 'sZeroRecords', 'sLoadingRecords' );
}
// Old parameter name of the thousands separator mapped onto the new
if ( lang.sInfoThousands ) {
lang.sThousands = lang.sInfoThousands;
}
var decimal = lang.sDecimal;
if ( decimal && defaultDecimal !== decimal ) {
_addNumericSort( decimal );
}
}
}
/**
* Map one parameter onto another
* @param {object} o Object to map
* @param {*} knew The new parameter name
* @param {*} old The old parameter name
*/
var _fnCompatMap = function ( o, knew, old ) {
if ( o[ knew ] !== undefined ) {
o[ old ] = o[ knew ];
}
};
/**
* Provide backwards compatibility for the main DT options. Note that the new
* options are mapped onto the old parameters, so this is an external interface
* change only.
* @param {object} init Object to map
*/
function _fnCompatOpts ( init )
{
_fnCompatMap( init, 'ordering', 'bSort' );
_fnCompatMap( init, 'orderMulti', 'bSortMulti' );
_fnCompatMap( init, 'orderClasses', 'bSortClasses' );
_fnCompatMap( init, 'orderCellsTop', 'bSortCellsTop' );
_fnCompatMap( init, 'order', 'aaSorting' );
_fnCompatMap( init, 'orderFixed', 'aaSortingFixed' );
_fnCompatMap( init, 'paging', 'bPaginate' );
_fnCompatMap( init, 'pagingType', 'sPaginationType' );
_fnCompatMap( init, 'pageLength', 'iDisplayLength' );
_fnCompatMap( init, 'searching', 'bFilter' );
// Boolean initialisation of x-scrolling
if ( typeof init.sScrollX === 'boolean' ) {
init.sScrollX = init.sScrollX ? '100%' : '';
}
if ( typeof init.scrollX === 'boolean' ) {
init.scrollX = init.scrollX ? '100%' : '';
}
// Column search objects are in an array, so it needs to be converted
// element by element
var searchCols = init.aoSearchCols;
if ( searchCols ) {
for ( var i=0, ien=searchCols.length ; i<ien ; i++ ) {
if ( searchCols[i] ) {
_fnCamelToHungarian( DataTable.models.oSearch, searchCols[i] );
}
}
}
}
/**
* Provide backwards compatibility for column options. Note that the new options
* are mapped onto the old parameters, so this is an external interface change
* only.
* @param {object} init Object to map
*/
function _fnCompatCols ( init )
{
_fnCompatMap( init, 'orderable', 'bSortable' );
_fnCompatMap( init, 'orderData', 'aDataSort' );
_fnCompatMap( init, 'orderSequence', 'asSorting' );
_fnCompatMap( init, 'orderDataType', 'sortDataType' );
// orderData can be given as an integer
var dataSort = init.aDataSort;
if ( typeof dataSort === 'number' && ! Array.isArray( dataSort ) ) {
init.aDataSort = [ dataSort ];
}
}
/**
* Browser feature detection for capabilities, quirks
* @param {object} settings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnBrowserDetect( settings )
{
// We don't need to do this every time DataTables is constructed, the values
// calculated are specific to the browser and OS configuration which we
// don't expect to change between initialisations
if ( ! DataTable.__browser ) {
var browser = {};
DataTable.__browser = browser;
// Scrolling feature / quirks detection
var n = $('<div/>')
.css( {
position: 'fixed',
top: 0,
left: $(window).scrollLeft()*-1, // allow for scrolling
height: 1,
width: 1,
overflow: 'hidden'
} )
.append(
$('<div/>')
.css( {
position: 'absolute',
top: 1,
left: 1,
width: 100,
overflow: 'scroll'
} )
.append(
$('<div/>')
.css( {
width: '100%',
height: 10
} )
)
)
.appendTo( 'body' );
var outer = n.children();
var inner = outer.children();
// Numbers below, in order, are:
// inner.offsetWidth, inner.clientWidth, outer.offsetWidth, outer.clientWidth
//
// IE6 XP: 100 100 100 83
// IE7 Vista: 100 100 100 83
// IE 8+ Windows: 83 83 100 83
// Evergreen Windows: 83 83 100 83
// Evergreen Mac with scrollbars: 85 85 100 85
// Evergreen Mac without scrollbars: 100 100 100 100
// Get scrollbar width
browser.barWidth = outer[0].offsetWidth - outer[0].clientWidth;
// IE6/7 will oversize a width 100% element inside a scrolling element, to
// include the width of the scrollbar, while other browsers ensure the inner
// element is contained without forcing scrolling
browser.bScrollOversize = inner[0].offsetWidth === 100 && outer[0].clientWidth !== 100;
// In rtl text layout, some browsers (most, but not all) will place the
// scrollbar on the left, rather than the right.
browser.bScrollbarLeft = Math.round( inner.offset().left ) !== 1;
// IE8- don't provide height and width for getBoundingClientRect
browser.bBounding = n[0].getBoundingClientRect().width ? true : false;
n.remove();
}
$.extend( settings.oBrowser, DataTable.__browser );
settings.oScroll.iBarWidth = DataTable.__browser.barWidth;
}
/**
* Array.prototype reduce[Right] method, used for browsers which don't support
* JS 1.6. Done this way to reduce code size, since we iterate either way
* @param {object} settings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnReduce ( that, fn, init, start, end, inc )
{
var
i = start,
value,
isSet = false;
if ( init !== undefined ) {
value = init;
isSet = true;
}
while ( i !== end ) {
if ( ! that.hasOwnProperty(i) ) {
continue;
}
value = isSet ?
fn( value, that[i], i, that ) :
that[i];
isSet = true;
i += inc;
}
return value;
}
/**
* Add a column to the list used for the table with default values
* @param {object} oSettings dataTables settings object
* @param {node} nTh The th element for this column
* @memberof DataTable#oApi
*/
function _fnAddColumn( oSettings, nTh )
{
// Add column to aoColumns array
var oDefaults = DataTable.defaults.column;
var iCol = oSettings.aoColumns.length;
var oCol = $.extend( {}, DataTable.models.oColumn, oDefaults, {
"nTh": nTh ? nTh : document.createElement('th'),
"sTitle": oDefaults.sTitle ? oDefaults.sTitle : nTh ? nTh.innerHTML : '',
"aDataSort": oDefaults.aDataSort ? oDefaults.aDataSort : [iCol],
"mData": oDefaults.mData ? oDefaults.mData : iCol,
idx: iCol
} );
oSettings.aoColumns.push( oCol );
// Add search object for column specific search. Note that the `searchCols[ iCol ]`
// passed into extend can be undefined. This allows the user to give a default
// with only some of the parameters defined, and also not give a default
var searchCols = oSettings.aoPreSearchCols;
searchCols[ iCol ] = $.extend( {}, DataTable.models.oSearch, searchCols[ iCol ] );
// Use the default column options function to initialise classes etc
_fnColumnOptions( oSettings, iCol, $(nTh).data() );
}
/**
* Apply options for a column
* @param {object} oSettings dataTables settings object
* @param {int} iCol column index to consider
* @param {object} oOptions object with sType, bVisible and bSearchable etc
* @memberof DataTable#oApi
*/
function _fnColumnOptions( oSettings, iCol, oOptions )
{
var oCol = oSettings.aoColumns[ iCol ];
var oClasses = oSettings.oClasses;
var th = $(oCol.nTh);
// Try to get width information from the DOM. We can't get it from CSS
// as we'd need to parse the CSS stylesheet. `width` option can override
if ( ! oCol.sWidthOrig ) {
// Width attribute
oCol.sWidthOrig = th.attr('width') || null;
// Style attribute
var t = (th.attr('style') || '').match(/width:\s*(\d+[pxem%]+)/);
if ( t ) {
oCol.sWidthOrig = t[1];
}
}
/* User specified column options */
if ( oOptions !== undefined && oOptions !== null )
{
// Backwards compatibility
_fnCompatCols( oOptions );
// Map camel case parameters to their Hungarian counterparts
_fnCamelToHungarian( DataTable.defaults.column, oOptions, true );
/* Backwards compatibility for mDataProp */
if ( oOptions.mDataProp !== undefined && !oOptions.mData )
{
oOptions.mData = oOptions.mDataProp;
}
if ( oOptions.sType )
{
oCol._sManualType = oOptions.sType;
}
// `class` is a reserved word in Javascript, so we need to provide
// the ability to use a valid name for the camel case input
if ( oOptions.className && ! oOptions.sClass )
{
oOptions.sClass = oOptions.className;
}
if ( oOptions.sClass ) {
th.addClass( oOptions.sClass );
}
$.extend( oCol, oOptions );
_fnMap( oCol, oOptions, "sWidth", "sWidthOrig" );
/* iDataSort to be applied (backwards compatibility), but aDataSort will take
* priority if defined
*/
if ( oOptions.iDataSort !== undefined )
{
oCol.aDataSort = [ oOptions.iDataSort ];
}
_fnMap( oCol, oOptions, "aDataSort" );
}
/* Cache the data get and set functions for speed */
var mDataSrc = oCol.mData;
var mData = _fnGetObjectDataFn( mDataSrc );
var mRender = oCol.mRender ? _fnGetObjectDataFn( oCol.mRender ) : null;
var attrTest = function( src ) {
return typeof src === 'string' && src.indexOf('@') !== -1;
};
oCol._bAttrSrc = $.isPlainObject( mDataSrc ) && (
attrTest(mDataSrc.sort) || attrTest(mDataSrc.type) || attrTest(mDataSrc.filter)
);
oCol._setter = null;
oCol.fnGetData = function (rowData, type, meta) {
var innerData = mData( rowData, type, undefined, meta );
return mRender && type ?
mRender( innerData, type, rowData, meta ) :
innerData;
};
oCol.fnSetData = function ( rowData, val, meta ) {
return _fnSetObjectDataFn( mDataSrc )( rowData, val, meta );
};
// Indicate if DataTables should read DOM data as an object or array
// Used in _fnGetRowElements
if ( typeof mDataSrc !== 'number' ) {
oSettings._rowReadObject = true;
}
/* Feature sorting overrides column specific when off */
if ( !oSettings.oFeatures.bSort )
{
oCol.bSortable = false;
th.addClass( oClasses.sSortableNone ); // Have to add class here as order event isn't called
}
/* Check that the class assignment is correct for sorting */
var bAsc = $.inArray('asc', oCol.asSorting) !== -1;
var bDesc = $.inArray('desc', oCol.asSorting) !== -1;
if ( !oCol.bSortable || (!bAsc && !bDesc) )
{
oCol.sSortingClass = oClasses.sSortableNone;
oCol.sSortingClassJUI = "";
}
else if ( bAsc && !bDesc )
{
oCol.sSortingClass = oClasses.sSortableAsc;
oCol.sSortingClassJUI = oClasses.sSortJUIAscAllowed;
}
else if ( !bAsc && bDesc )
{
oCol.sSortingClass = oClasses.sSortableDesc;
oCol.sSortingClassJUI = oClasses.sSortJUIDescAllowed;
}
else
{
oCol.sSortingClass = oClasses.sSortable;
oCol.sSortingClassJUI = oClasses.sSortJUI;
}
}
/**
* Adjust the table column widths for new data. Note: you would probably want to
* do a redraw after calling this function!
* @param {object} settings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnAdjustColumnSizing ( settings )
{
/* Not interested in doing column width calculation if auto-width is disabled */
if ( settings.oFeatures.bAutoWidth !== false )
{
var columns = settings.aoColumns;
_fnCalculateColumnWidths( settings );
for ( var i=0 , iLen=columns.length ; i<iLen ; i++ )
{
columns[i].nTh.style.width = columns[i].sWidth;
}
}
var scroll = settings.oScroll;
if ( scroll.sY !== '' || scroll.sX !== '')
{
_fnScrollDraw( settings );
}
_fnCallbackFire( settings, null, 'column-sizing', [settings] );
}
/**
* Covert the index of a visible column to the index in the data array (take account
* of hidden columns)
* @param {object} oSettings dataTables settings object
* @param {int} iMatch Visible column index to lookup
* @returns {int} i the data index
* @memberof DataTable#oApi
*/
function _fnVisibleToColumnIndex( oSettings, iMatch )
{
var aiVis = _fnGetColumns( oSettings, 'bVisible' );
return typeof aiVis[iMatch] === 'number' ?
aiVis[iMatch] :
null;
}
/**
* Covert the index of an index in the data array and convert it to the visible
* column index (take account of hidden columns)
* @param {int} iMatch Column index to lookup
* @param {object} oSettings dataTables settings object
* @returns {int} i the data index
* @memberof DataTable#oApi
*/
function _fnColumnIndexToVisible( oSettings, iMatch )
{
var aiVis = _fnGetColumns( oSettings, 'bVisible' );
var iPos = $.inArray( iMatch, aiVis );
return iPos !== -1 ? iPos : null;
}
/**
* Get the number of visible columns
* @param {object} oSettings dataTables settings object
* @returns {int} i the number of visible columns
* @memberof DataTable#oApi
*/
function _fnVisbleColumns( oSettings )
{
var vis = 0;
// No reduce in IE8, use a loop for now
$.each( oSettings.aoColumns, function ( i, col ) {
if ( col.bVisible && $(col.nTh).css('display') !== 'none' ) {
vis++;
}
} );
return vis;
}
/**
* Get an array of column indexes that match a given property
* @param {object} oSettings dataTables settings object
* @param {string} sParam Parameter in aoColumns to look for - typically
* bVisible or bSearchable
* @returns {array} Array of indexes with matched properties
* @memberof DataTable#oApi
*/
function _fnGetColumns( oSettings, sParam )
{
var a = [];
$.map( oSettings.aoColumns, function(val, i) {
if ( val[sParam] ) {
a.push( i );
}
} );
return a;
}
/**
* Calculate the 'type' of a column
* @param {object} settings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnColumnTypes ( settings )
{
var columns = settings.aoColumns;
var data = settings.aoData;
var types = DataTable.ext.type.detect;
var i, ien, j, jen, k, ken;
var col, cell, detectedType, cache;
// For each column, spin over the
for ( i=0, ien=columns.length ; i<ien ; i++ ) {
col = columns[i];
cache = [];
if ( ! col.sType && col._sManualType ) {
col.sType = col._sManualType;
}
else if ( ! col.sType ) {
for ( j=0, jen=types.length ; j<jen ; j++ ) {
for ( k=0, ken=data.length ; k<ken ; k++ ) {
// Use a cache array so we only need to get the type data
// from the formatter once (when using multiple detectors)
if ( cache[k] === undefined ) {
cache[k] = _fnGetCellData( settings, k, i, 'type' );
}
detectedType = types[j]( cache[k], settings );
// If null, then this type can't apply to this column, so
// rather than testing all cells, break out. There is an
// exception for the last type which is `html`. We need to
// scan all rows since it is possible to mix string and HTML
// types
if ( ! detectedType && j !== types.length-1 ) {
break;
}
// Only a single match is needed for html type since it is
// bottom of the pile and very similar to string
if ( detectedType === 'html' ) {
break;
}
}
// Type is valid for all data points in the column - use this
// type
if ( detectedType ) {
col.sType = detectedType;
break;
}
}
// Fall back - if no type was detected, always use string
if ( ! col.sType ) {
col.sType = 'string';
}
}
}
}
/**
* Take the column definitions and static columns arrays and calculate how
* they relate to column indexes. The callback function will then apply the
* definition found for a column to a suitable configuration object.
* @param {object} oSettings dataTables settings object
* @param {array} aoColDefs The aoColumnDefs array that is to be applied
* @param {array} aoCols The aoColumns array that defines columns individually
* @param {function} fn Callback function - takes two parameters, the calculated
* column index and the definition for that column.
* @memberof DataTable#oApi
*/
function _fnApplyColumnDefs( oSettings, aoColDefs, aoCols, fn )
{
var i, iLen, j, jLen, k, kLen, def;
var columns = oSettings.aoColumns;
// Column definitions with aTargets
if ( aoColDefs )
{
/* Loop over the definitions array - loop in reverse so first instance has priority */
for ( i=aoColDefs.length-1 ; i>=0 ; i-- )
{
def = aoColDefs[i];
/* Each definition can target multiple columns, as it is an array */
var aTargets = def.targets !== undefined ?
def.targets :
def.aTargets;
if ( ! Array.isArray( aTargets ) )
{
aTargets = [ aTargets ];
}
for ( j=0, jLen=aTargets.length ; j<jLen ; j++ )
{
if ( typeof aTargets[j] === 'number' && aTargets[j] >= 0 )
{
/* Add columns that we don't yet know about */
while( columns.length <= aTargets[j] )
{
_fnAddColumn( oSettings );
}
/* Integer, basic index */
fn( aTargets[j], def );
}
else if ( typeof aTargets[j] === 'number' && aTargets[j] < 0 )
{
/* Negative integer, right to left column counting */
fn( columns.length+aTargets[j], def );
}
else if ( typeof aTargets[j] === 'string' )
{
/* Class name matching on TH element */
for ( k=0, kLen=columns.length ; k<kLen ; k++ )
{
if ( aTargets[j] == "_all" ||
$(columns[k].nTh).hasClass( aTargets[j] ) )
{
fn( k, def );
}
}
}
}
}
}
// Statically defined columns array
if ( aoCols )
{
for ( i=0, iLen=aoCols.length ; i<iLen ; i++ )
{
fn( i, aoCols[i] );
}
}
}
/**
* Add a data array to the table, creating DOM node etc. This is the parallel to
* _fnGatherData, but for adding rows from a Javascript source, rather than a
* DOM source.
* @param {object} oSettings dataTables settings object
* @param {array} aData data array to be added
* @param {node} [nTr] TR element to add to the table - optional. If not given,
* DataTables will create a row automatically
* @param {array} [anTds] Array of TD|TH elements for the row - must be given
* if nTr is.
* @returns {int} >=0 if successful (index of new aoData entry), -1 if failed
* @memberof DataTable#oApi
*/
function _fnAddData ( oSettings, aDataIn, nTr, anTds )
{
/* Create the object for storing information about this new row */
var iRow = oSettings.aoData.length;
var oData = $.extend( true, {}, DataTable.models.oRow, {
src: nTr ? 'dom' : 'data',
idx: iRow
} );
oData._aData = aDataIn;
oSettings.aoData.push( oData );
/* Create the cells */
var nTd, sThisType;
var columns = oSettings.aoColumns;
// Invalidate the column types as the new data needs to be revalidated
for ( var i=0, iLen=columns.length ; i<iLen ; i++ )
{
columns[i].sType = null;
}
/* Add to the display array */
oSettings.aiDisplayMaster.push( iRow );
var id = oSettings.rowIdFn( aDataIn );
if ( id !== undefined ) {
oSettings.aIds[ id ] = oData;
}
/* Create the DOM information, or register it if already present */
if ( nTr || ! oSettings.oFeatures.bDeferRender )
{
_fnCreateTr( oSettings, iRow, nTr, anTds );
}
return iRow;
}
/**
* Add one or more TR elements to the table. Generally we'd expect to
* use this for reading data from a DOM sourced table, but it could be
* used for an TR element. Note that if a TR is given, it is used (i.e.
* it is not cloned).
* @param {object} settings dataTables settings object
* @param {array|node|jQuery} trs The TR element(s) to add to the table
* @returns {array} Array of indexes for the added rows
* @memberof DataTable#oApi
*/
function _fnAddTr( settings, trs )
{
var row;
// Allow an individual node to be passed in
if ( ! (trs instanceof $) ) {
trs = $(trs);
}
return trs.map( function (i, el) {
row = _fnGetRowElements( settings, el );
return _fnAddData( settings, row.data, el, row.cells );
} );
}
/**
* Take a TR element and convert it to an index in aoData
* @param {object} oSettings dataTables settings object
* @param {node} n the TR element to find
* @returns {int} index if the node is found, null if not
* @memberof DataTable#oApi
*/
function _fnNodeToDataIndex( oSettings, n )
{
return (n._DT_RowIndex!==undefined) ? n._DT_RowIndex : null;
}
/**
* Take a TD element and convert it into a column data index (not the visible index)
* @param {object} oSettings dataTables settings object
* @param {int} iRow The row number the TD/TH can be found in
* @param {node} n The TD/TH element to find
* @returns {int} index if the node is found, -1 if not
* @memberof DataTable#oApi
*/
function _fnNodeToColumnIndex( oSettings, iRow, n )
{
return $.inArray( n, oSettings.aoData[ iRow ].anCells );
}
/**
* Get the data for a given cell from the internal cache, taking into account data mapping
* @param {object} settings dataTables settings object
* @param {int} rowIdx aoData row id
* @param {int} colIdx Column index
* @param {string} type data get type ('display', 'type' 'filter' 'sort')
* @returns {*} Cell data
* @memberof DataTable#oApi
*/
function _fnGetCellData( settings, rowIdx, colIdx, type )
{
var draw = settings.iDraw;
var col = settings.aoColumns[colIdx];
var rowData = settings.aoData[rowIdx]._aData;
var defaultContent = col.sDefaultContent;
var cellData = col.fnGetData( rowData, type, {
settings: settings,
row: rowIdx,
col: colIdx
} );
if ( cellData === undefined ) {
if ( settings.iDrawError != draw && defaultContent === null ) {
_fnLog( settings, 0, "Requested unknown parameter "+
(typeof col.mData=='function' ? '{function}' : "'"+col.mData+"'")+
" for row "+rowIdx+", column "+colIdx, 4 );
settings.iDrawError = draw;
}
return defaultContent;
}
// When the data source is null and a specific data type is requested (i.e.
// not the original data), we can use default column data
if ( (cellData === rowData || cellData === null) && defaultContent !== null && type !== undefined ) {
cellData = defaultContent;
}
else if ( typeof cellData === 'function' ) {
// If the data source is a function, then we run it and use the return,
// executing in the scope of the data object (for instances)
return cellData.call( rowData );
}
if ( cellData === null && type == 'display' ) {
return '';
}
return cellData;
}
/**
* Set the value for a specific cell, into the internal data cache
* @param {object} settings dataTables settings object
* @param {int} rowIdx aoData row id
* @param {int} colIdx Column index
* @param {*} val Value to set
* @memberof DataTable#oApi
*/
function _fnSetCellData( settings, rowIdx, colIdx, val )
{
var col = settings.aoColumns[colIdx];
var rowData = settings.aoData[rowIdx]._aData;
col.fnSetData( rowData, val, {
settings: settings,
row: rowIdx,
col: colIdx
} );
}
// Private variable that is used to match action syntax in the data property object
var __reArray = /\[.*?\]$/;
var __reFn = /\(\)$/;
/**
* Split string on periods, taking into account escaped periods
* @param {string} str String to split
* @return {array} Split string
*/
function _fnSplitObjNotation( str )
{
return $.map( str.match(/(\\.|[^\.])+/g) || [''], function ( s ) {
return s.replace(/\\\./g, '.');
} );
}
/**
* Return a function that can be used to get data from a source object, taking
* into account the ability to use nested objects as a source
* @param {string|int|function} mSource The data source for the object
* @returns {function} Data get function
* @memberof DataTable#oApi
*/
function _fnGetObjectDataFn( mSource )
{
if ( $.isPlainObject( mSource ) )
{
/* Build an object of get functions, and wrap them in a single call */
var o = {};
$.each( mSource, function (key, val) {
if ( val ) {
o[key] = _fnGetObjectDataFn( val );
}
} );
return function (data, type, row, meta) {
var t = o[type] || o._;
return t !== undefined ?
t(data, type, row, meta) :
data;
};
}
else if ( mSource === null )
{
/* Give an empty string for rendering / sorting etc */
return function (data) { // type, row and meta also passed, but not used
return data;
};
}
else if ( typeof mSource === 'function' )
{
return function (data, type, row, meta) {
return mSource( data, type, row, meta );
};
}
else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||
mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) )
{
/* If there is a . in the source string then the data source is in a
* nested object so we loop over the data for each level to get the next
* level down. On each loop we test for undefined, and if found immediately
* return. This allows entire objects to be missing and sDefaultContent to
* be used if defined, rather than throwing an error
*/
var fetchData = function (data, type, src) {
var arrayNotation, funcNotation, out, innerSrc;
if ( src !== "" )
{
var a = _fnSplitObjNotation( src );
for ( var i=0, iLen=a.length ; i<iLen ; i++ )
{
// Check if we are dealing with special notation
arrayNotation = a[i].match(__reArray);
funcNotation = a[i].match(__reFn);
if ( arrayNotation )
{
// Array notation
a[i] = a[i].replace(__reArray, '');
// Condition allows simply [] to be passed in
if ( a[i] !== "" ) {
data = data[ a[i] ];
}
out = [];
// Get the remainder of the nested object to get
a.splice( 0, i+1 );
innerSrc = a.join('.');
// Traverse each entry in the array getting the properties requested
if ( Array.isArray( data ) ) {
for ( var j=0, jLen=data.length ; j<jLen ; j++ ) {
out.push( fetchData( data[j], type, innerSrc ) );
}
}
// If a string is given in between the array notation indicators, that
// is used to join the strings together, otherwise an array is returned
var join = arrayNotation[0].substring(1, arrayNotation[0].length-1);
data = (join==="") ? out : out.join(join);
// The inner call to fetchData has already traversed through the remainder
// of the source requested, so we exit from the loop
break;
}
else if ( funcNotation )
{
// Function call
a[i] = a[i].replace(__reFn, '');
data = data[ a[i] ]();
continue;
}
if ( data === null || data[ a[i] ] === undefined )
{
return undefined;
}
data = data[ a[i] ];
}
}
return data;
};
return function (data, type) { // row and meta also passed, but not used
return fetchData( data, type, mSource );
};
}
else
{
/* Array or flat object mapping */
return function (data, type) { // row and meta also passed, but not used
return data[mSource];
};
}
}
/**
* Return a function that can be used to set data from a source object, taking
* into account the ability to use nested objects as a source
* @param {string|int|function} mSource The data source for the object
* @returns {function} Data set function
* @memberof DataTable#oApi
*/
function _fnSetObjectDataFn( mSource )
{
if ( $.isPlainObject( mSource ) )
{
/* Unlike get, only the underscore (global) option is used for for
* setting data since we don't know the type here. This is why an object
* option is not documented for `mData` (which is read/write), but it is
* for `mRender` which is read only.
*/
return _fnSetObjectDataFn( mSource._ );
}
else if ( mSource === null )
{
/* Nothing to do when the data source is null */
return function () {};
}
else if ( typeof mSource === 'function' )
{
return function (data, val, meta) {
mSource( data, 'set', val, meta );
};
}
else if ( typeof mSource === 'string' && (mSource.indexOf('.') !== -1 ||
mSource.indexOf('[') !== -1 || mSource.indexOf('(') !== -1) )
{
/* Like the get, we need to get data from a nested object */
var setData = function (data, val, src) {
var a = _fnSplitObjNotation( src ), b;
var aLast = a[a.length-1];
var arrayNotation, funcNotation, o, innerSrc;
for ( var i=0, iLen=a.length-1 ; i<iLen ; i++ )
{
// Protect against prototype pollution
if (a[i] === '__proto__' || a[i] === 'constructor') {
throw new Error('Cannot set prototype values');
}
// Check if we are dealing with an array notation request
arrayNotation = a[i].match(__reArray);
funcNotation = a[i].match(__reFn);
if ( arrayNotation )
{
a[i] = a[i].replace(__reArray, '');
data[ a[i] ] = [];
// Get the remainder of the nested object to set so we can recurse
b = a.slice();
b.splice( 0, i+1 );
innerSrc = b.join('.');
// Traverse each entry in the array setting the properties requested
if ( Array.isArray( val ) )
{
for ( var j=0, jLen=val.length ; j<jLen ; j++ )
{
o = {};
setData( o, val[j], innerSrc );
data[ a[i] ].push( o );
}
}
else
{
// We've been asked to save data to an array, but it
// isn't array data to be saved. Best that can be done
// is to just save the value.
data[ a[i] ] = val;
}
// The inner call to setData has already traversed through the remainder
// of the source and has set the data, thus we can exit here
return;
}
else if ( funcNotation )
{
// Function call
a[i] = a[i].replace(__reFn, '');
data = data[ a[i] ]( val );
}
// If the nested object doesn't currently exist - since we are
// trying to set the value - create it
if ( data[ a[i] ] === null || data[ a[i] ] === undefined )
{
data[ a[i] ] = {};
}
data = data[ a[i] ];
}
// Last item in the input - i.e, the actual set
if ( aLast.match(__reFn ) )
{
// Function call
data = data[ aLast.replace(__reFn, '') ]( val );
}
else
{
// If array notation is used, we just want to strip it and use the property name
// and assign the value. If it isn't used, then we get the result we want anyway
data[ aLast.replace(__reArray, '') ] = val;
}
};
return function (data, val) { // meta is also passed in, but not used
return setData( data, val, mSource );
};
}
else
{
/* Array or flat object mapping */
return function (data, val) { // meta is also passed in, but not used
data[mSource] = val;
};
}
}
/**
* Return an array with the full table data
* @param {object} oSettings dataTables settings object
* @returns array {array} aData Master data array
* @memberof DataTable#oApi
*/
function _fnGetDataMaster ( settings )
{
return _pluck( settings.aoData, '_aData' );
}
/**
* Nuke the table
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnClearTable( settings )
{
settings.aoData.length = 0;
settings.aiDisplayMaster.length = 0;
settings.aiDisplay.length = 0;
settings.aIds = {};
}
/**
* Take an array of integers (index array) and remove a target integer (value - not
* the key!)
* @param {array} a Index array to target
* @param {int} iTarget value to find
* @memberof DataTable#oApi
*/
function _fnDeleteIndex( a, iTarget, splice )
{
var iTargetIndex = -1;
for ( var i=0, iLen=a.length ; i<iLen ; i++ )
{
if ( a[i] == iTarget )
{
iTargetIndex = i;
}
else if ( a[i] > iTarget )
{
a[i]--;
}
}
if ( iTargetIndex != -1 && splice === undefined )
{
a.splice( iTargetIndex, 1 );
}
}
/**
* Mark cached data as invalid such that a re-read of the data will occur when
* the cached data is next requested. Also update from the data source object.
*
* @param {object} settings DataTables settings object
* @param {int} rowIdx Row index to invalidate
* @param {string} [src] Source to invalidate from: undefined, 'auto', 'dom'
* or 'data'
* @param {int} [colIdx] Column index to invalidate. If undefined the whole
* row will be invalidated
* @memberof DataTable#oApi
*
* @todo For the modularisation of v1.11 this will need to become a callback, so
* the sort and filter methods can subscribe to it. That will required
* initialisation options for sorting, which is why it is not already baked in
*/
function _fnInvalidate( settings, rowIdx, src, colIdx )
{
var row = settings.aoData[ rowIdx ];
var i, ien;
var cellWrite = function ( cell, col ) {
// This is very frustrating, but in IE if you just write directly
// to innerHTML, and elements that are overwritten are GC'ed,
// even if there is a reference to them elsewhere
while ( cell.childNodes.length ) {
cell.removeChild( cell.firstChild );
}
cell.innerHTML = _fnGetCellData( settings, rowIdx, col, 'display' );
};
// Are we reading last data from DOM or the data object?
if ( src === 'dom' || ((! src || src === 'auto') && row.src === 'dom') ) {
// Read the data from the DOM
row._aData = _fnGetRowElements(
settings, row, colIdx, colIdx === undefined ? undefined : row._aData
)
.data;
}
else {
// Reading from data object, update the DOM
var cells = row.anCells;
if ( cells ) {
if ( colIdx !== undefined ) {
cellWrite( cells[colIdx], colIdx );
}
else {
for ( i=0, ien=cells.length ; i<ien ; i++ ) {
cellWrite( cells[i], i );
}
}
}
}
// For both row and cell invalidation, the cached data for sorting and
// filtering is nulled out
row._aSortData = null;
row._aFilterData = null;
// Invalidate the type for a specific column (if given) or all columns since
// the data might have changed
var cols = settings.aoColumns;
if ( colIdx !== undefined ) {
cols[ colIdx ].sType = null;
}
else {
for ( i=0, ien=cols.length ; i<ien ; i++ ) {
cols[i].sType = null;
}
// Update DataTables special `DT_*` attributes for the row
_fnRowAttributes( settings, row );
}
}
/**
* Build a data source object from an HTML row, reading the contents of the
* cells that are in the row.
*
* @param {object} settings DataTables settings object
* @param {node|object} TR element from which to read data or existing row
* object from which to re-read the data from the cells
* @param {int} [colIdx] Optional column index
* @param {array|object} [d] Data source object. If `colIdx` is given then this
* parameter should also be given and will be used to write the data into.
* Only the column in question will be written
* @returns {object} Object with two parameters: `data` the data read, in
* document order, and `cells` and array of nodes (they can be useful to the
* caller, so rather than needing a second traversal to get them, just return
* them from here).
* @memberof DataTable#oApi
*/
function _fnGetRowElements( settings, row, colIdx, d )
{
var
tds = [],
td = row.firstChild,
name, col, o, i=0, contents,
columns = settings.aoColumns,
objectRead = settings._rowReadObject;
// Allow the data object to be passed in, or construct
d = d !== undefined ?
d :
objectRead ?
{} :
[];
var attr = function ( str, td ) {
if ( typeof str === 'string' ) {
var idx = str.indexOf('@');
if ( idx !== -1 ) {
var attr = str.substring( idx+1 );
var setter = _fnSetObjectDataFn( str );
setter( d, td.getAttribute( attr ) );
}
}
};
// Read data from a cell and store into the data object
var cellProcess = function ( cell ) {
if ( colIdx === undefined || colIdx === i ) {
col = columns[i];
contents = (cell.innerHTML).trim();
if ( col && col._bAttrSrc ) {
var setter = _fnSetObjectDataFn( col.mData._ );
setter( d, contents );
attr( col.mData.sort, cell );
attr( col.mData.type, cell );
attr( col.mData.filter, cell );
}
else {
// Depending on the `data` option for the columns the data can
// be read to either an object or an array.
if ( objectRead ) {
if ( ! col._setter ) {
// Cache the setter function
col._setter = _fnSetObjectDataFn( col.mData );
}
col._setter( d, contents );
}
else {
d[i] = contents;
}
}
}
i++;
};
if ( td ) {
// `tr` element was passed in
while ( td ) {
name = td.nodeName.toUpperCase();
if ( name == "TD" || name == "TH" ) {
cellProcess( td );
tds.push( td );
}
td = td.nextSibling;
}
}
else {
// Existing row object passed in
tds = row.anCells;
for ( var j=0, jen=tds.length ; j<jen ; j++ ) {
cellProcess( tds[j] );
}
}
// Read the ID from the DOM if present
var rowNode = row.firstChild ? row : row.nTr;
if ( rowNode ) {
var id = rowNode.getAttribute( 'id' );
if ( id ) {
_fnSetObjectDataFn( settings.rowId )( d, id );
}
}
return {
data: d,
cells: tds
};
}
/**
* Create a new TR element (and it's TD children) for a row
* @param {object} oSettings dataTables settings object
* @param {int} iRow Row to consider
* @param {node} [nTrIn] TR element to add to the table - optional. If not given,
* DataTables will create a row automatically
* @param {array} [anTds] Array of TD|TH elements for the row - must be given
* if nTr is.
* @memberof DataTable#oApi
*/
function _fnCreateTr ( oSettings, iRow, nTrIn, anTds )
{
var
row = oSettings.aoData[iRow],
rowData = row._aData,
cells = [],
nTr, nTd, oCol,
i, iLen, create;
if ( row.nTr === null )
{
nTr = nTrIn || document.createElement('tr');
row.nTr = nTr;
row.anCells = cells;
/* Use a private property on the node to allow reserve mapping from the node
* to the aoData array for fast look up
*/
nTr._DT_RowIndex = iRow;
/* Special parameters can be given by the data source to be used on the row */
_fnRowAttributes( oSettings, row );
/* Process each column */
for ( i=0, iLen=oSettings.aoColumns.length ; i<iLen ; i++ )
{
oCol = oSettings.aoColumns[i];
create = nTrIn ? false : true;
nTd = create ? document.createElement( oCol.sCellType ) : anTds[i];
nTd._DT_CellIndex = {
row: iRow,
column: i
};
cells.push( nTd );
// Need to create the HTML if new, or if a rendering function is defined
if ( create || ((oCol.mRender || oCol.mData !== i) &&
(!$.isPlainObject(oCol.mData) || oCol.mData._ !== i+'.display')
)) {
nTd.innerHTML = _fnGetCellData( oSettings, iRow, i, 'display' );
}
/* Add user defined class */
if ( oCol.sClass )
{
nTd.className += ' '+oCol.sClass;
}
// Visibility - add or remove as required
if ( oCol.bVisible && ! nTrIn )
{
nTr.appendChild( nTd );
}
else if ( ! oCol.bVisible && nTrIn )
{
nTd.parentNode.removeChild( nTd );
}
if ( oCol.fnCreatedCell )
{
oCol.fnCreatedCell.call( oSettings.oInstance,
nTd, _fnGetCellData( oSettings, iRow, i ), rowData, iRow, i
);
}
}
_fnCallbackFire( oSettings, 'aoRowCreatedCallback', null, [nTr, rowData, iRow, cells] );
}
}
/**
* Add attributes to a row based on the special `DT_*` parameters in a data
* source object.
* @param {object} settings DataTables settings object
* @param {object} DataTables row object for the row to be modified
* @memberof DataTable#oApi
*/
function _fnRowAttributes( settings, row )
{
var tr = row.nTr;
var data = row._aData;
if ( tr ) {
var id = settings.rowIdFn( data );
if ( id ) {
tr.id = id;
}
if ( data.DT_RowClass ) {
// Remove any classes added by DT_RowClass before
var a = data.DT_RowClass.split(' ');
row.__rowc = row.__rowc ?
_unique( row.__rowc.concat( a ) ) :
a;
$(tr)
.removeClass( row.__rowc.join(' ') )
.addClass( data.DT_RowClass );
}
if ( data.DT_RowAttr ) {
$(tr).attr( data.DT_RowAttr );
}
if ( data.DT_RowData ) {
$(tr).data( data.DT_RowData );
}
}
}
/**
* Create the HTML header for the table
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnBuildHead( oSettings )
{
var i, ien, cell, row, column;
var thead = oSettings.nTHead;
var tfoot = oSettings.nTFoot;
var createHeader = $('th, td', thead).length === 0;
var classes = oSettings.oClasses;
var columns = oSettings.aoColumns;
if ( createHeader ) {
row = $('<tr/>').appendTo( thead );
}
for ( i=0, ien=columns.length ; i<ien ; i++ ) {
column = columns[i];
cell = $( column.nTh ).addClass( column.sClass );
if ( createHeader ) {
cell.appendTo( row );
}
// 1.11 move into sorting
if ( oSettings.oFeatures.bSort ) {
cell.addClass( column.sSortingClass );
if ( column.bSortable !== false ) {
cell
.attr( 'tabindex', oSettings.iTabIndex )
.attr( 'aria-controls', oSettings.sTableId );
_fnSortAttachListener( oSettings, column.nTh, i );
}
}
if ( column.sTitle != cell[0].innerHTML ) {
cell.html( column.sTitle );
}
_fnRenderer( oSettings, 'header' )(
oSettings, cell, column, classes
);
}
if ( createHeader ) {
_fnDetectHeader( oSettings.aoHeader, thead );
}
/* ARIA role for the rows */
$(thead).children('tr').attr('role', 'row');
/* Deal with the footer - add classes if required */
$(thead).children('tr').children('th, td').addClass( classes.sHeaderTH );
$(tfoot).children('tr').children('th, td').addClass( classes.sFooterTH );
// Cache the footer cells. Note that we only take the cells from the first
// row in the footer. If there is more than one row the user wants to
// interact with, they need to use the table().foot() method. Note also this
// allows cells to be used for multiple columns using colspan
if ( tfoot !== null ) {
var cells = oSettings.aoFooter[0];
for ( i=0, ien=cells.length ; i<ien ; i++ ) {
column = columns[i];
column.nTf = cells[i].cell;
if ( column.sClass ) {
$(column.nTf).addClass( column.sClass );
}
}
}
}
/**
* Draw the header (or footer) element based on the column visibility states. The
* methodology here is to use the layout array from _fnDetectHeader, modified for
* the instantaneous column visibility, to construct the new layout. The grid is
* traversed over cell at a time in a rows x columns grid fashion, although each
* cell insert can cover multiple elements in the grid - which is tracks using the
* aApplied array. Cell inserts in the grid will only occur where there isn't
* already a cell in that position.
* @param {object} oSettings dataTables settings object
* @param array {objects} aoSource Layout array from _fnDetectHeader
* @param {boolean} [bIncludeHidden=false] If true then include the hidden columns in the calc,
* @memberof DataTable#oApi
*/
function _fnDrawHead( oSettings, aoSource, bIncludeHidden )
{
var i, iLen, j, jLen, k, kLen, n, nLocalTr;
var aoLocal = [];
var aApplied = [];
var iColumns = oSettings.aoColumns.length;
var iRowspan, iColspan;
if ( ! aoSource )
{
return;
}
if ( bIncludeHidden === undefined )
{
bIncludeHidden = false;
}
/* Make a copy of the master layout array, but without the visible columns in it */
for ( i=0, iLen=aoSource.length ; i<iLen ; i++ )
{
aoLocal[i] = aoSource[i].slice();
aoLocal[i].nTr = aoSource[i].nTr;
/* Remove any columns which are currently hidden */
for ( j=iColumns-1 ; j>=0 ; j-- )
{
if ( !oSettings.aoColumns[j].bVisible && !bIncludeHidden )
{
aoLocal[i].splice( j, 1 );
}
}
/* Prep the applied array - it needs an element for each row */
aApplied.push( [] );
}
for ( i=0, iLen=aoLocal.length ; i<iLen ; i++ )
{
nLocalTr = aoLocal[i].nTr;
/* All cells are going to be replaced, so empty out the row */
if ( nLocalTr )
{
while( (n = nLocalTr.firstChild) )
{
nLocalTr.removeChild( n );
}
}
for ( j=0, jLen=aoLocal[i].length ; j<jLen ; j++ )
{
iRowspan = 1;
iColspan = 1;
/* Check to see if there is already a cell (row/colspan) covering our target
* insert point. If there is, then there is nothing to do.
*/
if ( aApplied[i][j] === undefined )
{
nLocalTr.appendChild( aoLocal[i][j].cell );
aApplied[i][j] = 1;
/* Expand the cell to cover as many rows as needed */
while ( aoLocal[i+iRowspan] !== undefined &&
aoLocal[i][j].cell == aoLocal[i+iRowspan][j].cell )
{
aApplied[i+iRowspan][j] = 1;
iRowspan++;
}
/* Expand the cell to cover as many columns as needed */
while ( aoLocal[i][j+iColspan] !== undefined &&
aoLocal[i][j].cell == aoLocal[i][j+iColspan].cell )
{
/* Must update the applied array over the rows for the columns */
for ( k=0 ; k<iRowspan ; k++ )
{
aApplied[i+k][j+iColspan] = 1;
}
iColspan++;
}
/* Do the actual expansion in the DOM */
$(aoLocal[i][j].cell)
.attr('rowspan', iRowspan)
.attr('colspan', iColspan);
}
}
}
}
/**
* Insert the required TR nodes into the table for display
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnDraw( oSettings )
{
/* Provide a pre-callback function which can be used to cancel the draw is false is returned */
var aPreDraw = _fnCallbackFire( oSettings, 'aoPreDrawCallback', 'preDraw', [oSettings] );
if ( $.inArray( false, aPreDraw ) !== -1 )
{
_fnProcessingDisplay( oSettings, false );
return;
}
var i, iLen, n;
var anRows = [];
var iRowCount = 0;
var asStripeClasses = oSettings.asStripeClasses;
var iStripes = asStripeClasses.length;
var iOpenRows = oSettings.aoOpenRows.length;
var oLang = oSettings.oLanguage;
var iInitDisplayStart = oSettings.iInitDisplayStart;
var bServerSide = _fnDataSource( oSettings ) == 'ssp';
var aiDisplay = oSettings.aiDisplay;
oSettings.bDrawing = true;
/* Check and see if we have an initial draw position from state saving */
if ( iInitDisplayStart !== undefined && iInitDisplayStart !== -1 )
{
oSettings._iDisplayStart = bServerSide ?
iInitDisplayStart :
iInitDisplayStart >= oSettings.fnRecordsDisplay() ?
0 :
iInitDisplayStart;
oSettings.iInitDisplayStart = -1;
}
var iDisplayStart = oSettings._iDisplayStart;
var iDisplayEnd = oSettings.fnDisplayEnd();
/* Server-side processing draw intercept */
if ( oSettings.bDeferLoading )
{
oSettings.bDeferLoading = false;
oSettings.iDraw++;
_fnProcessingDisplay( oSettings, false );
}
else if ( !bServerSide )
{
oSettings.iDraw++;
}
else if ( !oSettings.bDestroying && !_fnAjaxUpdate( oSettings ) )
{
return;
}
if ( aiDisplay.length !== 0 )
{
var iStart = bServerSide ? 0 : iDisplayStart;
var iEnd = bServerSide ? oSettings.aoData.length : iDisplayEnd;
for ( var j=iStart ; j<iEnd ; j++ )
{
var iDataIndex = aiDisplay[j];
var aoData = oSettings.aoData[ iDataIndex ];
if ( aoData.nTr === null )
{
_fnCreateTr( oSettings, iDataIndex );
}
var nRow = aoData.nTr;
/* Remove the old striping classes and then add the new one */
if ( iStripes !== 0 )
{
var sStripe = asStripeClasses[ iRowCount % iStripes ];
if ( aoData._sRowStripe != sStripe )
{
$(nRow).removeClass( aoData._sRowStripe ).addClass( sStripe );
aoData._sRowStripe = sStripe;
}
}
// Row callback functions - might want to manipulate the row
// iRowCount and j are not currently documented. Are they at all
// useful?
_fnCallbackFire( oSettings, 'aoRowCallback', null,
[nRow, aoData._aData, iRowCount, j, iDataIndex] );
anRows.push( nRow );
iRowCount++;
}
}
else
{
/* Table is empty - create a row with an empty message in it */
var sZero = oLang.sZeroRecords;
if ( oSettings.iDraw == 1 && _fnDataSource( oSettings ) == 'ajax' )
{
sZero = oLang.sLoadingRecords;
}
else if ( oLang.sEmptyTable && oSettings.fnRecordsTotal() === 0 )
{
sZero = oLang.sEmptyTable;
}
anRows[ 0 ] = $( '<tr/>', { 'class': iStripes ? asStripeClasses[0] : '' } )
.append( $('<td />', {
'valign': 'top',
'colSpan': _fnVisbleColumns( oSettings ),
'class': oSettings.oClasses.sRowEmpty
} ).html( sZero ) )[0];
}
/* Header and footer callbacks */
_fnCallbackFire( oSettings, 'aoHeaderCallback', 'header', [ $(oSettings.nTHead).children('tr')[0],
_fnGetDataMaster( oSettings ), iDisplayStart, iDisplayEnd, aiDisplay ] );
_fnCallbackFire( oSettings, 'aoFooterCallback', 'footer', [ $(oSettings.nTFoot).children('tr')[0],
_fnGetDataMaster( oSettings ), iDisplayStart, iDisplayEnd, aiDisplay ] );
var body = $(oSettings.nTBody);
body.children().detach();
body.append( $(anRows) );
/* Call all required callback functions for the end of a draw */
_fnCallbackFire( oSettings, 'aoDrawCallback', 'draw', [oSettings] );
/* Draw is complete, sorting and filtering must be as well */
oSettings.bSorted = false;
oSettings.bFiltered = false;
oSettings.bDrawing = false;
}
/**
* Redraw the table - taking account of the various features which are enabled
* @param {object} oSettings dataTables settings object
* @param {boolean} [holdPosition] Keep the current paging position. By default
* the paging is reset to the first page
* @memberof DataTable#oApi
*/
function _fnReDraw( settings, holdPosition )
{
var
features = settings.oFeatures,
sort = features.bSort,
filter = features.bFilter;
if ( sort ) {
_fnSort( settings );
}
if ( filter ) {
_fnFilterComplete( settings, settings.oPreviousSearch );
}
else {
// No filtering, so we want to just use the display master
settings.aiDisplay = settings.aiDisplayMaster.slice();
}
if ( holdPosition !== true ) {
settings._iDisplayStart = 0;
}
// Let any modules know about the draw hold position state (used by
// scrolling internally)
settings._drawHold = holdPosition;
_fnDraw( settings );
settings._drawHold = false;
}
/**
* Add the options to the page HTML for the table
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnAddOptionsHtml ( oSettings )
{
var classes = oSettings.oClasses;
var table = $(oSettings.nTable);
var holding = $('<div/>').insertBefore( table ); // Holding element for speed
var features = oSettings.oFeatures;
// All DataTables are wrapped in a div
var insert = $('<div/>', {
id: oSettings.sTableId+'_wrapper',
'class': classes.sWrapper + (oSettings.nTFoot ? '' : ' '+classes.sNoFooter)
} );
oSettings.nHolding = holding[0];
oSettings.nTableWrapper = insert[0];
oSettings.nTableReinsertBefore = oSettings.nTable.nextSibling;
/* Loop over the user set positioning and place the elements as needed */
var aDom = oSettings.sDom.split('');
var featureNode, cOption, nNewNode, cNext, sAttr, j;
for ( var i=0 ; i<aDom.length ; i++ )
{
featureNode = null;
cOption = aDom[i];
if ( cOption == '<' )
{
/* New container div */
nNewNode = $('<div/>')[0];
/* Check to see if we should append an id and/or a class name to the container */
cNext = aDom[i+1];
if ( cNext == "'" || cNext == '"' )
{
sAttr = "";
j = 2;
while ( aDom[i+j] != cNext )
{
sAttr += aDom[i+j];
j++;
}
/* Replace jQuery UI constants @todo depreciated */
if ( sAttr == "H" )
{
sAttr = classes.sJUIHeader;
}
else if ( sAttr == "F" )
{
sAttr = classes.sJUIFooter;
}
/* The attribute can be in the format of "#id.class", "#id" or "class" This logic
* breaks the string into parts and applies them as needed
*/
if ( sAttr.indexOf('.') != -1 )
{
var aSplit = sAttr.split('.');
nNewNode.id = aSplit[0].substr(1, aSplit[0].length-1);
nNewNode.className = aSplit[1];
}
else if ( sAttr.charAt(0) == "#" )
{
nNewNode.id = sAttr.substr(1, sAttr.length-1);
}
else
{
nNewNode.className = sAttr;
}
i += j; /* Move along the position array */
}
insert.append( nNewNode );
insert = $(nNewNode);
}
else if ( cOption == '>' )
{
/* End container div */
insert = insert.parent();
}
// @todo Move options into their own plugins?
else if ( cOption == 'l' && features.bPaginate && features.bLengthChange )
{
/* Length */
featureNode = _fnFeatureHtmlLength( oSettings );
}
else if ( cOption == 'f' && features.bFilter )
{
/* Filter */
featureNode = _fnFeatureHtmlFilter( oSettings );
}
else if ( cOption == 'r' && features.bProcessing )
{
/* pRocessing */
featureNode = _fnFeatureHtmlProcessing( oSettings );
}
else if ( cOption == 't' )
{
/* Table */
featureNode = _fnFeatureHtmlTable( oSettings );
}
else if ( cOption == 'i' && features.bInfo )
{
/* Info */
featureNode = _fnFeatureHtmlInfo( oSettings );
}
else if ( cOption == 'p' && features.bPaginate )
{
/* Pagination */
featureNode = _fnFeatureHtmlPaginate( oSettings );
}
else if ( DataTable.ext.feature.length !== 0 )
{
/* Plug-in features */
var aoFeatures = DataTable.ext.feature;
for ( var k=0, kLen=aoFeatures.length ; k<kLen ; k++ )
{
if ( cOption == aoFeatures[k].cFeature )
{
featureNode = aoFeatures[k].fnInit( oSettings );
break;
}
}
}
/* Add to the 2D features array */
if ( featureNode )
{
var aanFeatures = oSettings.aanFeatures;
if ( ! aanFeatures[cOption] )
{
aanFeatures[cOption] = [];
}
aanFeatures[cOption].push( featureNode );
insert.append( featureNode );
}
}
/* Built our DOM structure - replace the holding div with what we want */
holding.replaceWith( insert );
oSettings.nHolding = null;
}
/**
* Use the DOM source to create up an array of header cells. The idea here is to
* create a layout grid (array) of rows x columns, which contains a reference
* to the cell that that point in the grid (regardless of col/rowspan), such that
* any column / row could be removed and the new grid constructed
* @param array {object} aLayout Array to store the calculated layout in
* @param {node} nThead The header/footer element for the table
* @memberof DataTable#oApi
*/
function _fnDetectHeader ( aLayout, nThead )
{
var nTrs = $(nThead).children('tr');
var nTr, nCell;
var i, k, l, iLen, jLen, iColShifted, iColumn, iColspan, iRowspan;
var bUnique;
var fnShiftCol = function ( a, i, j ) {
var k = a[i];
while ( k[j] ) {
j++;
}
return j;
};
aLayout.splice( 0, aLayout.length );
/* We know how many rows there are in the layout - so prep it */
for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
{
aLayout.push( [] );
}
/* Calculate a layout array */
for ( i=0, iLen=nTrs.length ; i<iLen ; i++ )
{
nTr = nTrs[i];
iColumn = 0;
/* For every cell in the row... */
nCell = nTr.firstChild;
while ( nCell ) {
if ( nCell.nodeName.toUpperCase() == "TD" ||
nCell.nodeName.toUpperCase() == "TH" )
{
/* Get the col and rowspan attributes from the DOM and sanitise them */
iColspan = nCell.getAttribute('colspan') * 1;
iRowspan = nCell.getAttribute('rowspan') * 1;
iColspan = (!iColspan || iColspan===0 || iColspan===1) ? 1 : iColspan;
iRowspan = (!iRowspan || iRowspan===0 || iRowspan===1) ? 1 : iRowspan;
/* There might be colspan cells already in this row, so shift our target
* accordingly
*/
iColShifted = fnShiftCol( aLayout, i, iColumn );
/* Cache calculation for unique columns */
bUnique = iColspan === 1 ? true : false;
/* If there is col / rowspan, copy the information into the layout grid */
for ( l=0 ; l<iColspan ; l++ )
{
for ( k=0 ; k<iRowspan ; k++ )
{
aLayout[i+k][iColShifted+l] = {
"cell": nCell,
"unique": bUnique
};
aLayout[i+k].nTr = nTr;
}
}
}
nCell = nCell.nextSibling;
}
}
}
/**
* Get an array of unique th elements, one for each column
* @param {object} oSettings dataTables settings object
* @param {node} nHeader automatically detect the layout from this node - optional
* @param {array} aLayout thead/tfoot layout from _fnDetectHeader - optional
* @returns array {node} aReturn list of unique th's
* @memberof DataTable#oApi
*/
function _fnGetUniqueThs ( oSettings, nHeader, aLayout )
{
var aReturn = [];
if ( !aLayout )
{
aLayout = oSettings.aoHeader;
if ( nHeader )
{
aLayout = [];
_fnDetectHeader( aLayout, nHeader );
}
}
for ( var i=0, iLen=aLayout.length ; i<iLen ; i++ )
{
for ( var j=0, jLen=aLayout[i].length ; j<jLen ; j++ )
{
if ( aLayout[i][j].unique &&
(!aReturn[j] || !oSettings.bSortCellsTop) )
{
aReturn[j] = aLayout[i][j].cell;
}
}
}
return aReturn;
}
/**
* Create an Ajax call based on the table's settings, taking into account that
* parameters can have multiple forms, and backwards compatibility.
*
* @param {object} oSettings dataTables settings object
* @param {array} data Data to send to the server, required by
* DataTables - may be augmented by developer callbacks
* @param {function} fn Callback function to run when data is obtained
*/
function _fnBuildAjax( oSettings, data, fn )
{
// Compatibility with 1.9-, allow fnServerData and event to manipulate
_fnCallbackFire( oSettings, 'aoServerParams', 'serverParams', [data] );
// Convert to object based for 1.10+ if using the old array scheme which can
// come from server-side processing or serverParams
if ( data && Array.isArray(data) ) {
var tmp = {};
var rbracket = /(.*?)\[\]$/;
$.each( data, function (key, val) {
var match = val.name.match(rbracket);
if ( match ) {
// Support for arrays
var name = match[0];
if ( ! tmp[ name ] ) {
tmp[ name ] = [];
}
tmp[ name ].push( val.value );
}
else {
tmp[val.name] = val.value;
}
} );
data = tmp;
}
var ajaxData;
var ajax = oSettings.ajax;
var instance = oSettings.oInstance;
var callback = function ( json ) {
_fnCallbackFire( oSettings, null, 'xhr', [oSettings, json, oSettings.jqXHR] );
fn( json );
};
if ( $.isPlainObject( ajax ) && ajax.data )
{
ajaxData = ajax.data;
var newData = typeof ajaxData === 'function' ?
ajaxData( data, oSettings ) : // fn can manipulate data or return
ajaxData; // an object object or array to merge
// If the function returned something, use that alone
data = typeof ajaxData === 'function' && newData ?
newData :
$.extend( true, data, newData );
// Remove the data property as we've resolved it already and don't want
// jQuery to do it again (it is restored at the end of the function)
delete ajax.data;
}
var baseAjax = {
"data": data,
"success": function (json) {
var error = json.error || json.sError;
if ( error ) {
_fnLog( oSettings, 0, error );
}
oSettings.json = json;
callback( json );
},
"dataType": "json",
"cache": false,
"type": oSettings.sServerMethod,
"error": function (xhr, error, thrown) {
var ret = _fnCallbackFire( oSettings, null, 'xhr', [oSettings, null, oSettings.jqXHR] );
if ( $.inArray( true, ret ) === -1 ) {
if ( error == "parsererror" ) {
_fnLog( oSettings, 0, 'Invalid JSON response', 1 );
}
else if ( xhr.readyState === 4 ) {
_fnLog( oSettings, 0, 'Ajax error', 7 );
}
}
_fnProcessingDisplay( oSettings, false );
}
};
// Store the data submitted for the API
oSettings.oAjaxData = data;
// Allow plug-ins and external processes to modify the data
_fnCallbackFire( oSettings, null, 'preXhr', [oSettings, data] );
if ( oSettings.fnServerData )
{
// DataTables 1.9- compatibility
oSettings.fnServerData.call( instance,
oSettings.sAjaxSource,
$.map( data, function (val, key) { // Need to convert back to 1.9 trad format
return { name: key, value: val };
} ),
callback,
oSettings
);
}
else if ( oSettings.sAjaxSource || typeof ajax === 'string' )
{
// DataTables 1.9- compatibility
oSettings.jqXHR = $.ajax( $.extend( baseAjax, {
url: ajax || oSettings.sAjaxSource
} ) );
}
else if ( typeof ajax === 'function' )
{
// Is a function - let the caller define what needs to be done
oSettings.jqXHR = ajax.call( instance, data, callback, oSettings );
}
else
{
// Object to extend the base settings
oSettings.jqXHR = $.ajax( $.extend( baseAjax, ajax ) );
// Restore for next time around
ajax.data = ajaxData;
}
}
/**
* Update the table using an Ajax call
* @param {object} settings dataTables settings object
* @returns {boolean} Block the table drawing or not
* @memberof DataTable#oApi
*/
function _fnAjaxUpdate( settings )
{
if ( settings.bAjaxDataGet ) {
settings.iDraw++;
_fnProcessingDisplay( settings, true );
_fnBuildAjax(
settings,
_fnAjaxParameters( settings ),
function(json) {
_fnAjaxUpdateDraw( settings, json );
}
);
return false;
}
return true;
}
/**
* Build up the parameters in an object needed for a server-side processing
* request. Note that this is basically done twice, is different ways - a modern
* method which is used by default in DataTables 1.10 which uses objects and
* arrays, or the 1.9- method with is name / value pairs. 1.9 method is used if
* the sAjaxSource option is used in the initialisation, or the legacyAjax
* option is set.
* @param {object} oSettings dataTables settings object
* @returns {bool} block the table drawing or not
* @memberof DataTable#oApi
*/
function _fnAjaxParameters( settings )
{
var
columns = settings.aoColumns,
columnCount = columns.length,
features = settings.oFeatures,
preSearch = settings.oPreviousSearch,
preColSearch = settings.aoPreSearchCols,
i, data = [], dataProp, column, columnSearch,
sort = _fnSortFlatten( settings ),
displayStart = settings._iDisplayStart,
displayLength = features.bPaginate !== false ?
settings._iDisplayLength :
-1;
var param = function ( name, value ) {
data.push( { 'name': name, 'value': value } );
};
// DataTables 1.9- compatible method
param( 'sEcho', settings.iDraw );
param( 'iColumns', columnCount );
param( 'sColumns', _pluck( columns, 'sName' ).join(',') );
param( 'iDisplayStart', displayStart );
param( 'iDisplayLength', displayLength );
// DataTables 1.10+ method
var d = {
draw: settings.iDraw,
columns: [],
order: [],
start: displayStart,
length: displayLength,
search: {
value: preSearch.sSearch,
regex: preSearch.bRegex
}
};
for ( i=0 ; i<columnCount ; i++ ) {
column = columns[i];
columnSearch = preColSearch[i];
dataProp = typeof column.mData=="function" ? 'function' : column.mData ;
d.columns.push( {
data: dataProp,
name: column.sName,
searchable: column.bSearchable,
orderable: column.bSortable,
search: {
value: columnSearch.sSearch,
regex: columnSearch.bRegex
}
} );
param( "mDataProp_"+i, dataProp );
if ( features.bFilter ) {
param( 'sSearch_'+i, columnSearch.sSearch );
param( 'bRegex_'+i, columnSearch.bRegex );
param( 'bSearchable_'+i, column.bSearchable );
}
if ( features.bSort ) {
param( 'bSortable_'+i, column.bSortable );
}
}
if ( features.bFilter ) {
param( 'sSearch', preSearch.sSearch );
param( 'bRegex', preSearch.bRegex );
}
if ( features.bSort ) {
$.each( sort, function ( i, val ) {
d.order.push( { column: val.col, dir: val.dir } );
param( 'iSortCol_'+i, val.col );
param( 'sSortDir_'+i, val.dir );
} );
param( 'iSortingCols', sort.length );
}
// If the legacy.ajax parameter is null, then we automatically decide which
// form to use, based on sAjaxSource
var legacy = DataTable.ext.legacy.ajax;
if ( legacy === null ) {
return settings.sAjaxSource ? data : d;
}
// Otherwise, if legacy has been specified then we use that to decide on the
// form
return legacy ? data : d;
}
/**
* Data the data from the server (nuking the old) and redraw the table
* @param {object} oSettings dataTables settings object
* @param {object} json json data return from the server.
* @param {string} json.sEcho Tracking flag for DataTables to match requests
* @param {int} json.iTotalRecords Number of records in the data set, not accounting for filtering
* @param {int} json.iTotalDisplayRecords Number of records in the data set, accounting for filtering
* @param {array} json.aaData The data to display on this page
* @param {string} [json.sColumns] Column ordering (sName, comma separated)
* @memberof DataTable#oApi
*/
function _fnAjaxUpdateDraw ( settings, json )
{
// v1.10 uses camelCase variables, while 1.9 uses Hungarian notation.
// Support both
var compat = function ( old, modern ) {
return json[old] !== undefined ? json[old] : json[modern];
};
var data = _fnAjaxDataSrc( settings, json );
var draw = compat( 'sEcho', 'draw' );
var recordsTotal = compat( 'iTotalRecords', 'recordsTotal' );
var recordsFiltered = compat( 'iTotalDisplayRecords', 'recordsFiltered' );
if ( draw !== undefined ) {
// Protect against out of sequence returns
if ( draw*1 < settings.iDraw ) {
return;
}
settings.iDraw = draw * 1;
}
_fnClearTable( settings );
settings._iRecordsTotal = parseInt(recordsTotal, 10);
settings._iRecordsDisplay = parseInt(recordsFiltered, 10);
for ( var i=0, ien=data.length ; i<ien ; i++ ) {
_fnAddData( settings, data[i] );
}
settings.aiDisplay = settings.aiDisplayMaster.slice();
settings.bAjaxDataGet = false;
_fnDraw( settings );
if ( ! settings._bInitComplete ) {
_fnInitComplete( settings, json );
}
settings.bAjaxDataGet = true;
_fnProcessingDisplay( settings, false );
}
/**
* Get the data from the JSON data source to use for drawing a table. Using
* `_fnGetObjectDataFn` allows the data to be sourced from a property of the
* source object, or from a processing function.
* @param {object} oSettings dataTables settings object
* @param {object} json Data source object / array from the server
* @return {array} Array of data to use
*/
function _fnAjaxDataSrc ( oSettings, json )
{
var dataSrc = $.isPlainObject( oSettings.ajax ) && oSettings.ajax.dataSrc !== undefined ?
oSettings.ajax.dataSrc :
oSettings.sAjaxDataProp; // Compatibility with 1.9-.
// Compatibility with 1.9-. In order to read from aaData, check if the
// default has been changed, if not, check for aaData
if ( dataSrc === 'data' ) {
return json.aaData || json[dataSrc];
}
return dataSrc !== "" ?
_fnGetObjectDataFn( dataSrc )( json ) :
json;
}
/**
* Generate the node required for filtering text
* @returns {node} Filter control element
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnFeatureHtmlFilter ( settings )
{
var classes = settings.oClasses;
var tableId = settings.sTableId;
var language = settings.oLanguage;
var previousSearch = settings.oPreviousSearch;
var features = settings.aanFeatures;
var input = '<input type="search" class="'+classes.sFilterInput+'"/>';
var str = language.sSearch;
str = str.match(/_INPUT_/) ?
str.replace('_INPUT_', input) :
str+input;
var filter = $('<div/>', {
'id': ! features.f ? tableId+'_filter' : null,
'class': classes.sFilter
} )
.append( $('<label/>' ).append( str ) );
var searchFn = function() {
/* Update all other filter input elements for the new display */
var n = features.f;
var val = !this.value ? "" : this.value; // mental IE8 fix :-(
/* Now do the filter */
if ( val != previousSearch.sSearch ) {
_fnFilterComplete( settings, {
"sSearch": val,
"bRegex": previousSearch.bRegex,
"bSmart": previousSearch.bSmart ,
"bCaseInsensitive": previousSearch.bCaseInsensitive
} );
// Need to redraw, without resorting
settings._iDisplayStart = 0;
_fnDraw( settings );
}
};
var searchDelay = settings.searchDelay !== null ?
settings.searchDelay :
_fnDataSource( settings ) === 'ssp' ?
400 :
0;
var jqFilter = $('input', filter)
.val( previousSearch.sSearch )
.attr( 'placeholder', language.sSearchPlaceholder )
.on(
'keyup.DT search.DT input.DT paste.DT cut.DT',
searchDelay ?
_fnThrottle( searchFn, searchDelay ) :
searchFn
)
.on( 'mouseup', function(e) {
// Edge fix! Edge 17 does not trigger anything other than mouse events when clicking
// on the clear icon (Edge bug 17584515). This is safe in other browsers as `searchFn`
// checks the value to see if it has changed. In other browsers it won't have.
setTimeout( function () {
searchFn.call(jqFilter[0]);
}, 10);
} )
.on( 'keypress.DT', function(e) {
/* Prevent form submission */
if ( e.keyCode == 13 ) {
return false;
}
} )
.attr('aria-controls', tableId);
// Update the input elements whenever the table is filtered
$(settings.nTable).on( 'search.dt.DT', function ( ev, s ) {
if ( settings === s ) {
// IE9 throws an 'unknown error' if document.activeElement is used
// inside an iframe or frame...
try {
if ( jqFilter[0] !== document.activeElement ) {
jqFilter.val( previousSearch.sSearch );
}
}
catch ( e ) {}
}
} );
return filter[0];
}
/**
* Filter the table using both the global filter and column based filtering
* @param {object} oSettings dataTables settings object
* @param {object} oSearch search information
* @param {int} [iForce] force a research of the master array (1) or not (undefined or 0)
* @memberof DataTable#oApi
*/
function _fnFilterComplete ( oSettings, oInput, iForce )
{
var oPrevSearch = oSettings.oPreviousSearch;
var aoPrevSearch = oSettings.aoPreSearchCols;
var fnSaveFilter = function ( oFilter ) {
/* Save the filtering values */
oPrevSearch.sSearch = oFilter.sSearch;
oPrevSearch.bRegex = oFilter.bRegex;
oPrevSearch.bSmart = oFilter.bSmart;
oPrevSearch.bCaseInsensitive = oFilter.bCaseInsensitive;
};
var fnRegex = function ( o ) {
// Backwards compatibility with the bEscapeRegex option
return o.bEscapeRegex !== undefined ? !o.bEscapeRegex : o.bRegex;
};
// Resolve any column types that are unknown due to addition or invalidation
// @todo As per sort - can this be moved into an event handler?
_fnColumnTypes( oSettings );
/* In server-side processing all filtering is done by the server, so no point hanging around here */
if ( _fnDataSource( oSettings ) != 'ssp' )
{
/* Global filter */
_fnFilter( oSettings, oInput.sSearch, iForce, fnRegex(oInput), oInput.bSmart, oInput.bCaseInsensitive );
fnSaveFilter( oInput );
/* Now do the individual column filter */
for ( var i=0 ; i<aoPrevSearch.length ; i++ )
{
_fnFilterColumn( oSettings, aoPrevSearch[i].sSearch, i, fnRegex(aoPrevSearch[i]),
aoPrevSearch[i].bSmart, aoPrevSearch[i].bCaseInsensitive );
}
/* Custom filtering */
_fnFilterCustom( oSettings );
}
else
{
fnSaveFilter( oInput );
}
/* Tell the draw function we have been filtering */
oSettings.bFiltered = true;
_fnCallbackFire( oSettings, null, 'search', [oSettings] );
}
/**
* Apply custom filtering functions
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnFilterCustom( settings )
{
var filters = DataTable.ext.search;
var displayRows = settings.aiDisplay;
var row, rowIdx;
for ( var i=0, ien=filters.length ; i<ien ; i++ ) {
var rows = [];
// Loop over each row and see if it should be included
for ( var j=0, jen=displayRows.length ; j<jen ; j++ ) {
rowIdx = displayRows[ j ];
row = settings.aoData[ rowIdx ];
if ( filters[i]( settings, row._aFilterData, rowIdx, row._aData, j ) ) {
rows.push( rowIdx );
}
}
// So the array reference doesn't break set the results into the
// existing array
displayRows.length = 0;
$.merge( displayRows, rows );
}
}
/**
* Filter the table on a per-column basis
* @param {object} oSettings dataTables settings object
* @param {string} sInput string to filter on
* @param {int} iColumn column to filter
* @param {bool} bRegex treat search string as a regular expression or not
* @param {bool} bSmart use smart filtering or not
* @param {bool} bCaseInsensitive Do case insenstive matching or not
* @memberof DataTable#oApi
*/
function _fnFilterColumn ( settings, searchStr, colIdx, regex, smart, caseInsensitive )
{
if ( searchStr === '' ) {
return;
}
var data;
var out = [];
var display = settings.aiDisplay;
var rpSearch = _fnFilterCreateSearch( searchStr, regex, smart, caseInsensitive );
for ( var i=0 ; i<display.length ; i++ ) {
data = settings.aoData[ display[i] ]._aFilterData[ colIdx ];
if ( rpSearch.test( data ) ) {
out.push( display[i] );
}
}
settings.aiDisplay = out;
}
/**
* Filter the data table based on user input and draw the table
* @param {object} settings dataTables settings object
* @param {string} input string to filter on
* @param {int} force optional - force a research of the master array (1) or not (undefined or 0)
* @param {bool} regex treat as a regular expression or not
* @param {bool} smart perform smart filtering or not
* @param {bool} caseInsensitive Do case insenstive matching or not
* @memberof DataTable#oApi
*/
function _fnFilter( settings, input, force, regex, smart, caseInsensitive )
{
var rpSearch = _fnFilterCreateSearch( input, regex, smart, caseInsensitive );
var prevSearch = settings.oPreviousSearch.sSearch;
var displayMaster = settings.aiDisplayMaster;
var display, invalidated, i;
var filtered = [];
// Need to take account of custom filtering functions - always filter
if ( DataTable.ext.search.length !== 0 ) {
force = true;
}
// Check if any of the rows were invalidated
invalidated = _fnFilterData( settings );
// If the input is blank - we just want the full data set
if ( input.length <= 0 ) {
settings.aiDisplay = displayMaster.slice();
}
else {
// New search - start from the master array
if ( invalidated ||
force ||
regex ||
prevSearch.length > input.length ||
input.indexOf(prevSearch) !== 0 ||
settings.bSorted // On resort, the display master needs to be
// re-filtered since indexes will have changed
) {
settings.aiDisplay = displayMaster.slice();
}
// Search the display array
display = settings.aiDisplay;
for ( i=0 ; i<display.length ; i++ ) {
if ( rpSearch.test( settings.aoData[ display[i] ]._sFilterRow ) ) {
filtered.push( display[i] );
}
}
settings.aiDisplay = filtered;
}
}
/**
* Build a regular expression object suitable for searching a table
* @param {string} sSearch string to search for
* @param {bool} bRegex treat as a regular expression or not
* @param {bool} bSmart perform smart filtering or not
* @param {bool} bCaseInsensitive Do case insensitive matching or not
* @returns {RegExp} constructed object
* @memberof DataTable#oApi
*/
function _fnFilterCreateSearch( search, regex, smart, caseInsensitive )
{
search = regex ?
search :
_fnEscapeRegex( search );
if ( smart ) {
/* For smart filtering we want to allow the search to work regardless of
* word order. We also want double quoted text to be preserved, so word
* order is important - a la google. So this is what we want to
* generate:
*
* ^(?=.*?\bone\b)(?=.*?\btwo three\b)(?=.*?\bfour\b).*$
*/
var a = $.map( search.match( /"[^"]+"|[^ ]+/g ) || [''], function ( word ) {
if ( word.charAt(0) === '"' ) {
var m = word.match( /^"(.*)"$/ );
word = m ? m[1] : word;
}
return word.replace('"', '');
} );
search = '^(?=.*?'+a.join( ')(?=.*?' )+').*$';
}
return new RegExp( search, caseInsensitive ? 'i' : '' );
}
/**
* Escape a string such that it can be used in a regular expression
* @param {string} sVal string to escape
* @returns {string} escaped string
* @memberof DataTable#oApi
*/
var _fnEscapeRegex = DataTable.util.escapeRegex;
var __filter_div = $('<div>')[0];
var __filter_div_textContent = __filter_div.textContent !== undefined;
// Update the filtering data for each row if needed (by invalidation or first run)
function _fnFilterData ( settings )
{
var columns = settings.aoColumns;
var column;
var i, j, ien, jen, filterData, cellData, row;
var fomatters = DataTable.ext.type.search;
var wasInvalidated = false;
for ( i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
row = settings.aoData[i];
if ( ! row._aFilterData ) {
filterData = [];
for ( j=0, jen=columns.length ; j<jen ; j++ ) {
column = columns[j];
if ( column.bSearchable ) {
cellData = _fnGetCellData( settings, i, j, 'filter' );
if ( fomatters[ column.sType ] ) {
cellData = fomatters[ column.sType ]( cellData );
}
// Search in DataTables 1.10 is string based. In 1.11 this
// should be altered to also allow strict type checking.
if ( cellData === null ) {
cellData = '';
}
if ( typeof cellData !== 'string' && cellData.toString ) {
cellData = cellData.toString();
}
}
else {
cellData = '';
}
// If it looks like there is an HTML entity in the string,
// attempt to decode it so sorting works as expected. Note that
// we could use a single line of jQuery to do this, but the DOM
// method used here is much faster http://jsperf.com/html-decode
if ( cellData.indexOf && cellData.indexOf('&') !== -1 ) {
__filter_div.innerHTML = cellData;
cellData = __filter_div_textContent ?
__filter_div.textContent :
__filter_div.innerText;
}
if ( cellData.replace ) {
cellData = cellData.replace(/[\r\n\u2028]/g, '');
}
filterData.push( cellData );
}
row._aFilterData = filterData;
row._sFilterRow = filterData.join(' ');
wasInvalidated = true;
}
}
return wasInvalidated;
}
/**
* Convert from the internal Hungarian notation to camelCase for external
* interaction
* @param {object} obj Object to convert
* @returns {object} Inverted object
* @memberof DataTable#oApi
*/
function _fnSearchToCamel ( obj )
{
return {
search: obj.sSearch,
smart: obj.bSmart,
regex: obj.bRegex,
caseInsensitive: obj.bCaseInsensitive
};
}
/**
* Convert from camelCase notation to the internal Hungarian. We could use the
* Hungarian convert function here, but this is cleaner
* @param {object} obj Object to convert
* @returns {object} Inverted object
* @memberof DataTable#oApi
*/
function _fnSearchToHung ( obj )
{
return {
sSearch: obj.search,
bSmart: obj.smart,
bRegex: obj.regex,
bCaseInsensitive: obj.caseInsensitive
};
}
/**
* Generate the node required for the info display
* @param {object} oSettings dataTables settings object
* @returns {node} Information element
* @memberof DataTable#oApi
*/
function _fnFeatureHtmlInfo ( settings )
{
var
tid = settings.sTableId,
nodes = settings.aanFeatures.i,
n = $('<div/>', {
'class': settings.oClasses.sInfo,
'id': ! nodes ? tid+'_info' : null
} );
if ( ! nodes ) {
// Update display on each draw
settings.aoDrawCallback.push( {
"fn": _fnUpdateInfo,
"sName": "information"
} );
n
.attr( 'role', 'status' )
.attr( 'aria-live', 'polite' );
// Table is described by our info div
$(settings.nTable).attr( 'aria-describedby', tid+'_info' );
}
return n[0];
}
/**
* Update the information elements in the display
* @param {object} settings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnUpdateInfo ( settings )
{
/* Show information about the table */
var nodes = settings.aanFeatures.i;
if ( nodes.length === 0 ) {
return;
}
var
lang = settings.oLanguage,
start = settings._iDisplayStart+1,
end = settings.fnDisplayEnd(),
max = settings.fnRecordsTotal(),
total = settings.fnRecordsDisplay(),
out = total ?
lang.sInfo :
lang.sInfoEmpty;
if ( total !== max ) {
/* Record set after filtering */
out += ' ' + lang.sInfoFiltered;
}
// Convert the macros
out += lang.sInfoPostFix;
out = _fnInfoMacros( settings, out );
var callback = lang.fnInfoCallback;
if ( callback !== null ) {
out = callback.call( settings.oInstance,
settings, start, end, max, total, out
);
}
$(nodes).html( out );
}
function _fnInfoMacros ( settings, str )
{
// When infinite scrolling, we are always starting at 1. _iDisplayStart is used only
// internally
var
formatter = settings.fnFormatNumber,
start = settings._iDisplayStart+1,
len = settings._iDisplayLength,
vis = settings.fnRecordsDisplay(),
all = len === -1;
return str.
replace(/_START_/g, formatter.call( settings, start ) ).
replace(/_END_/g, formatter.call( settings, settings.fnDisplayEnd() ) ).
replace(/_MAX_/g, formatter.call( settings, settings.fnRecordsTotal() ) ).
replace(/_TOTAL_/g, formatter.call( settings, vis ) ).
replace(/_PAGE_/g, formatter.call( settings, all ? 1 : Math.ceil( start / len ) ) ).
replace(/_PAGES_/g, formatter.call( settings, all ? 1 : Math.ceil( vis / len ) ) );
}
/**
* Draw the table for the first time, adding all required features
* @param {object} settings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnInitialise ( settings )
{
var i, iLen, iAjaxStart=settings.iInitDisplayStart;
var columns = settings.aoColumns, column;
var features = settings.oFeatures;
var deferLoading = settings.bDeferLoading; // value modified by the draw
/* Ensure that the table data is fully initialised */
if ( ! settings.bInitialised ) {
setTimeout( function(){ _fnInitialise( settings ); }, 200 );
return;
}
/* Show the display HTML options */
_fnAddOptionsHtml( settings );
/* Build and draw the header / footer for the table */
_fnBuildHead( settings );
_fnDrawHead( settings, settings.aoHeader );
_fnDrawHead( settings, settings.aoFooter );
/* Okay to show that something is going on now */
_fnProcessingDisplay( settings, true );
/* Calculate sizes for columns */
if ( features.bAutoWidth ) {
_fnCalculateColumnWidths( settings );
}
for ( i=0, iLen=columns.length ; i<iLen ; i++ ) {
column = columns[i];
if ( column.sWidth ) {
column.nTh.style.width = _fnStringToCss( column.sWidth );
}
}
_fnCallbackFire( settings, null, 'preInit', [settings] );
// If there is default sorting required - let's do it. The sort function
// will do the drawing for us. Otherwise we draw the table regardless of the
// Ajax source - this allows the table to look initialised for Ajax sourcing
// data (show 'loading' message possibly)
_fnReDraw( settings );
// Server-side processing init complete is done by _fnAjaxUpdateDraw
var dataSrc = _fnDataSource( settings );
if ( dataSrc != 'ssp' || deferLoading ) {
// if there is an ajax source load the data
if ( dataSrc == 'ajax' ) {
_fnBuildAjax( settings, [], function(json) {
var aData = _fnAjaxDataSrc( settings, json );
// Got the data - add it to the table
for ( i=0 ; i<aData.length ; i++ ) {
_fnAddData( settings, aData[i] );
}
// Reset the init display for cookie saving. We've already done
// a filter, and therefore cleared it before. So we need to make
// it appear 'fresh'
settings.iInitDisplayStart = iAjaxStart;
_fnReDraw( settings );
_fnProcessingDisplay( settings, false );
_fnInitComplete( settings, json );
}, settings );
}
else {
_fnProcessingDisplay( settings, false );
_fnInitComplete( settings );
}
}
}
/**
* Draw the table for the first time, adding all required features
* @param {object} oSettings dataTables settings object
* @param {object} [json] JSON from the server that completed the table, if using Ajax source
* with client-side processing (optional)
* @memberof DataTable#oApi
*/
function _fnInitComplete ( settings, json )
{
settings._bInitComplete = true;
// When data was added after the initialisation (data or Ajax) we need to
// calculate the column sizing
if ( json || settings.oInit.aaData ) {
_fnAdjustColumnSizing( settings );
}
_fnCallbackFire( settings, null, 'plugin-init', [settings, json] );
_fnCallbackFire( settings, 'aoInitComplete', 'init', [settings, json] );
}
function _fnLengthChange ( settings, val )
{
var len = parseInt( val, 10 );
settings._iDisplayLength = len;
_fnLengthOverflow( settings );
// Fire length change event
_fnCallbackFire( settings, null, 'length', [settings, len] );
}
/**
* Generate the node required for user display length changing
* @param {object} settings dataTables settings object
* @returns {node} Display length feature node
* @memberof DataTable#oApi
*/
function _fnFeatureHtmlLength ( settings )
{
var
classes = settings.oClasses,
tableId = settings.sTableId,
menu = settings.aLengthMenu,
d2 = Array.isArray( menu[0] ),
lengths = d2 ? menu[0] : menu,
language = d2 ? menu[1] : menu;
var select = $('<select/>', {
'name': tableId+'_length',
'aria-controls': tableId,
'class': classes.sLengthSelect
} );
for ( var i=0, ien=lengths.length ; i<ien ; i++ ) {
select[0][ i ] = new Option(
typeof language[i] === 'number' ?
settings.fnFormatNumber( language[i] ) :
language[i],
lengths[i]
);
}
var div = $('<div><label/></div>').addClass( classes.sLength );
if ( ! settings.aanFeatures.l ) {
div[0].id = tableId+'_length';
}
div.children().append(
settings.oLanguage.sLengthMenu.replace( '_MENU_', select[0].outerHTML )
);
// Can't use `select` variable as user might provide their own and the
// reference is broken by the use of outerHTML
$('select', div)
.val( settings._iDisplayLength )
.on( 'change.DT', function(e) {
_fnLengthChange( settings, $(this).val() );
_fnDraw( settings );
} );
// Update node value whenever anything changes the table's length
$(settings.nTable).on( 'length.dt.DT', function (e, s, len) {
if ( settings === s ) {
$('select', div).val( len );
}
} );
return div[0];
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Note that most of the paging logic is done in
* DataTable.ext.pager
*/
/**
* Generate the node required for default pagination
* @param {object} oSettings dataTables settings object
* @returns {node} Pagination feature node
* @memberof DataTable#oApi
*/
function _fnFeatureHtmlPaginate ( settings )
{
var
type = settings.sPaginationType,
plugin = DataTable.ext.pager[ type ],
modern = typeof plugin === 'function',
redraw = function( settings ) {
_fnDraw( settings );
},
node = $('<div/>').addClass( settings.oClasses.sPaging + type )[0],
features = settings.aanFeatures;
if ( ! modern ) {
plugin.fnInit( settings, node, redraw );
}
/* Add a draw callback for the pagination on first instance, to update the paging display */
if ( ! features.p )
{
node.id = settings.sTableId+'_paginate';
settings.aoDrawCallback.push( {
"fn": function( settings ) {
if ( modern ) {
var
start = settings._iDisplayStart,
len = settings._iDisplayLength,
visRecords = settings.fnRecordsDisplay(),
all = len === -1,
page = all ? 0 : Math.ceil( start / len ),
pages = all ? 1 : Math.ceil( visRecords / len ),
buttons = plugin(page, pages),
i, ien;
for ( i=0, ien=features.p.length ; i<ien ; i++ ) {
_fnRenderer( settings, 'pageButton' )(
settings, features.p[i], i, buttons, page, pages
);
}
}
else {
plugin.fnUpdate( settings, redraw );
}
},
"sName": "pagination"
} );
}
return node;
}
/**
* Alter the display settings to change the page
* @param {object} settings DataTables settings object
* @param {string|int} action Paging action to take: "first", "previous",
* "next" or "last" or page number to jump to (integer)
* @param [bool] redraw Automatically draw the update or not
* @returns {bool} true page has changed, false - no change
* @memberof DataTable#oApi
*/
function _fnPageChange ( settings, action, redraw )
{
var
start = settings._iDisplayStart,
len = settings._iDisplayLength,
records = settings.fnRecordsDisplay();
if ( records === 0 || len === -1 )
{
start = 0;
}
else if ( typeof action === "number" )
{
start = action * len;
if ( start > records )
{
start = 0;
}
}
else if ( action == "first" )
{
start = 0;
}
else if ( action == "previous" )
{
start = len >= 0 ?
start - len :
0;
if ( start < 0 )
{
start = 0;
}
}
else if ( action == "next" )
{
if ( start + len < records )
{
start += len;
}
}
else if ( action == "last" )
{
start = Math.floor( (records-1) / len) * len;
}
else
{
_fnLog( settings, 0, "Unknown paging action: "+action, 5 );
}
var changed = settings._iDisplayStart !== start;
settings._iDisplayStart = start;
if ( changed ) {
_fnCallbackFire( settings, null, 'page', [settings] );
if ( redraw ) {
_fnDraw( settings );
}
}
return changed;
}
/**
* Generate the node required for the processing node
* @param {object} settings dataTables settings object
* @returns {node} Processing element
* @memberof DataTable#oApi
*/
function _fnFeatureHtmlProcessing ( settings )
{
return $('<div/>', {
'id': ! settings.aanFeatures.r ? settings.sTableId+'_processing' : null,
'class': settings.oClasses.sProcessing
} )
.html( settings.oLanguage.sProcessing )
.insertBefore( settings.nTable )[0];
}
/**
* Display or hide the processing indicator
* @param {object} settings dataTables settings object
* @param {bool} show Show the processing indicator (true) or not (false)
* @memberof DataTable#oApi
*/
function _fnProcessingDisplay ( settings, show )
{
if ( settings.oFeatures.bProcessing ) {
$(settings.aanFeatures.r).css( 'display', show ? 'block' : 'none' );
}
_fnCallbackFire( settings, null, 'processing', [settings, show] );
}
/**
* Add any control elements for the table - specifically scrolling
* @param {object} settings dataTables settings object
* @returns {node} Node to add to the DOM
* @memberof DataTable#oApi
*/
function _fnFeatureHtmlTable ( settings )
{
var table = $(settings.nTable);
// Add the ARIA grid role to the table
table.attr( 'role', 'grid' );
// Scrolling from here on in
var scroll = settings.oScroll;
if ( scroll.sX === '' && scroll.sY === '' ) {
return settings.nTable;
}
var scrollX = scroll.sX;
var scrollY = scroll.sY;
var classes = settings.oClasses;
var caption = table.children('caption');
var captionSide = caption.length ? caption[0]._captionSide : null;
var headerClone = $( table[0].cloneNode(false) );
var footerClone = $( table[0].cloneNode(false) );
var footer = table.children('tfoot');
var _div = '<div/>';
var size = function ( s ) {
return !s ? null : _fnStringToCss( s );
};
if ( ! footer.length ) {
footer = null;
}
/*
* The HTML structure that we want to generate in this function is:
* div - scroller
* div - scroll head
* div - scroll head inner
* table - scroll head table
* thead - thead
* div - scroll body
* table - table (master table)
* thead - thead clone for sizing
* tbody - tbody
* div - scroll foot
* div - scroll foot inner
* table - scroll foot table
* tfoot - tfoot
*/
var scroller = $( _div, { 'class': classes.sScrollWrapper } )
.append(
$(_div, { 'class': classes.sScrollHead } )
.css( {
overflow: 'hidden',
position: 'relative',
border: 0,
width: scrollX ? size(scrollX) : '100%'
} )
.append(
$(_div, { 'class': classes.sScrollHeadInner } )
.css( {
'box-sizing': 'content-box',
width: scroll.sXInner || '100%'
} )
.append(
headerClone
.removeAttr('id')
.css( 'margin-left', 0 )
.append( captionSide === 'top' ? caption : null )
.append(
table.children('thead')
)
)
)
)
.append(
$(_div, { 'class': classes.sScrollBody } )
.css( {
position: 'relative',
overflow: 'auto',
width: size( scrollX )
} )
.append( table )
);
if ( footer ) {
scroller.append(
$(_div, { 'class': classes.sScrollFoot } )
.css( {
overflow: 'hidden',
border: 0,
width: scrollX ? size(scrollX) : '100%'
} )
.append(
$(_div, { 'class': classes.sScrollFootInner } )
.append(
footerClone
.removeAttr('id')
.css( 'margin-left', 0 )
.append( captionSide === 'bottom' ? caption : null )
.append(
table.children('tfoot')
)
)
)
);
}
var children = scroller.children();
var scrollHead = children[0];
var scrollBody = children[1];
var scrollFoot = footer ? children[2] : null;
// When the body is scrolled, then we also want to scroll the headers
if ( scrollX ) {
$(scrollBody).on( 'scroll.DT', function (e) {
var scrollLeft = this.scrollLeft;
scrollHead.scrollLeft = scrollLeft;
if ( footer ) {
scrollFoot.scrollLeft = scrollLeft;
}
} );
}
$(scrollBody).css('max-height', scrollY);
if (! scroll.bCollapse) {
$(scrollBody).css('height', scrollY);
}
settings.nScrollHead = scrollHead;
settings.nScrollBody = scrollBody;
settings.nScrollFoot = scrollFoot;
// On redraw - align columns
settings.aoDrawCallback.push( {
"fn": _fnScrollDraw,
"sName": "scrolling"
} );
return scroller[0];
}
/**
* Update the header, footer and body tables for resizing - i.e. column
* alignment.
*
* Welcome to the most horrible function DataTables. The process that this
* function follows is basically:
* 1. Re-create the table inside the scrolling div
* 2. Take live measurements from the DOM
* 3. Apply the measurements to align the columns
* 4. Clean up
*
* @param {object} settings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnScrollDraw ( settings )
{
// Given that this is such a monster function, a lot of variables are use
// to try and keep the minimised size as small as possible
var
scroll = settings.oScroll,
scrollX = scroll.sX,
scrollXInner = scroll.sXInner,
scrollY = scroll.sY,
barWidth = scroll.iBarWidth,
divHeader = $(settings.nScrollHead),
divHeaderStyle = divHeader[0].style,
divHeaderInner = divHeader.children('div'),
divHeaderInnerStyle = divHeaderInner[0].style,
divHeaderTable = divHeaderInner.children('table'),
divBodyEl = settings.nScrollBody,
divBody = $(divBodyEl),
divBodyStyle = divBodyEl.style,
divFooter = $(settings.nScrollFoot),
divFooterInner = divFooter.children('div'),
divFooterTable = divFooterInner.children('table'),
header = $(settings.nTHead),
table = $(settings.nTable),
tableEl = table[0],
tableStyle = tableEl.style,
footer = settings.nTFoot ? $(settings.nTFoot) : null,
browser = settings.oBrowser,
ie67 = browser.bScrollOversize,
dtHeaderCells = _pluck( settings.aoColumns, 'nTh' ),
headerTrgEls, footerTrgEls,
headerSrcEls, footerSrcEls,
headerCopy, footerCopy,
headerWidths=[], footerWidths=[],
headerContent=[], footerContent=[],
idx, correction, sanityWidth,
zeroOut = function(nSizer) {
var style = nSizer.style;
style.paddingTop = "0";
style.paddingBottom = "0";
style.borderTopWidth = "0";
style.borderBottomWidth = "0";
style.height = 0;
};
// If the scrollbar visibility has changed from the last draw, we need to
// adjust the column sizes as the table width will have changed to account
// for the scrollbar
var scrollBarVis = divBodyEl.scrollHeight > divBodyEl.clientHeight;
if ( settings.scrollBarVis !== scrollBarVis && settings.scrollBarVis !== undefined ) {
settings.scrollBarVis = scrollBarVis;
_fnAdjustColumnSizing( settings );
return; // adjust column sizing will call this function again
}
else {
settings.scrollBarVis = scrollBarVis;
}
/*
* 1. Re-create the table inside the scrolling div
*/
// Remove the old minimised thead and tfoot elements in the inner table
table.children('thead, tfoot').remove();
if ( footer ) {
footerCopy = footer.clone().prependTo( table );
footerTrgEls = footer.find('tr'); // the original tfoot is in its own table and must be sized
footerSrcEls = footerCopy.find('tr');
}
// Clone the current header and footer elements and then place it into the inner table
headerCopy = header.clone().prependTo( table );
headerTrgEls = header.find('tr'); // original header is in its own table
headerSrcEls = headerCopy.find('tr');
headerCopy.find('th, td').removeAttr('tabindex');
/*
* 2. Take live measurements from the DOM - do not alter the DOM itself!
*/
// Remove old sizing and apply the calculated column widths
// Get the unique column headers in the newly created (cloned) header. We want to apply the
// calculated sizes to this header
if ( ! scrollX )
{
divBodyStyle.width = '100%';
divHeader[0].style.width = '100%';
}
$.each( _fnGetUniqueThs( settings, headerCopy ), function ( i, el ) {
idx = _fnVisibleToColumnIndex( settings, i );
el.style.width = settings.aoColumns[idx].sWidth;
} );
if ( footer ) {
_fnApplyToChildren( function(n) {
n.style.width = "";
}, footerSrcEls );
}
// Size the table as a whole
sanityWidth = table.outerWidth();
if ( scrollX === "" ) {
// No x scrolling
tableStyle.width = "100%";
// IE7 will make the width of the table when 100% include the scrollbar
// - which is shouldn't. When there is a scrollbar we need to take this
// into account.
if ( ie67 && (table.find('tbody').height() > divBodyEl.offsetHeight ||
divBody.css('overflow-y') == "scroll")
) {
tableStyle.width = _fnStringToCss( table.outerWidth() - barWidth);
}
// Recalculate the sanity width
sanityWidth = table.outerWidth();
}
else if ( scrollXInner !== "" ) {
// legacy x scroll inner has been given - use it
tableStyle.width = _fnStringToCss(scrollXInner);
// Recalculate the sanity width
sanityWidth = table.outerWidth();
}
// Hidden header should have zero height, so remove padding and borders. Then
// set the width based on the real headers
// Apply all styles in one pass
_fnApplyToChildren( zeroOut, headerSrcEls );
// Read all widths in next pass
_fnApplyToChildren( function(nSizer) {
headerContent.push( nSizer.innerHTML );
headerWidths.push( _fnStringToCss( $(nSizer).css('width') ) );
}, headerSrcEls );
// Apply all widths in final pass
_fnApplyToChildren( function(nToSize, i) {
// Only apply widths to the DataTables detected header cells - this
// prevents complex headers from having contradictory sizes applied
if ( $.inArray( nToSize, dtHeaderCells ) !== -1 ) {
nToSize.style.width = headerWidths[i];
}
}, headerTrgEls );
$(headerSrcEls).height(0);
/* Same again with the footer if we have one */
if ( footer )
{
_fnApplyToChildren( zeroOut, footerSrcEls );
_fnApplyToChildren( function(nSizer) {
footerContent.push( nSizer.innerHTML );
footerWidths.push( _fnStringToCss( $(nSizer).css('width') ) );
}, footerSrcEls );
_fnApplyToChildren( function(nToSize, i) {
nToSize.style.width = footerWidths[i];
}, footerTrgEls );
$(footerSrcEls).height(0);
}
/*
* 3. Apply the measurements
*/
// "Hide" the header and footer that we used for the sizing. We need to keep
// the content of the cell so that the width applied to the header and body
// both match, but we want to hide it completely. We want to also fix their
// width to what they currently are
_fnApplyToChildren( function(nSizer, i) {
nSizer.innerHTML = '<div class="dataTables_sizing">'+headerContent[i]+'</div>';
nSizer.childNodes[0].style.height = "0";
nSizer.childNodes[0].style.overflow = "hidden";
nSizer.style.width = headerWidths[i];
}, headerSrcEls );
if ( footer )
{
_fnApplyToChildren( function(nSizer, i) {
nSizer.innerHTML = '<div class="dataTables_sizing">'+footerContent[i]+'</div>';
nSizer.childNodes[0].style.height = "0";
nSizer.childNodes[0].style.overflow = "hidden";
nSizer.style.width = footerWidths[i];
}, footerSrcEls );
}
// Sanity check that the table is of a sensible width. If not then we are going to get
// misalignment - try to prevent this by not allowing the table to shrink below its min width
if ( table.outerWidth() < sanityWidth )
{
// The min width depends upon if we have a vertical scrollbar visible or not */
correction = ((divBodyEl.scrollHeight > divBodyEl.offsetHeight ||
divBody.css('overflow-y') == "scroll")) ?
sanityWidth+barWidth :
sanityWidth;
// IE6/7 are a law unto themselves...
if ( ie67 && (divBodyEl.scrollHeight >
divBodyEl.offsetHeight || divBody.css('overflow-y') == "scroll")
) {
tableStyle.width = _fnStringToCss( correction-barWidth );
}
// And give the user a warning that we've stopped the table getting too small
if ( scrollX === "" || scrollXInner !== "" ) {
_fnLog( settings, 1, 'Possible column misalignment', 6 );
}
}
else
{
correction = '100%';
}
// Apply to the container elements
divBodyStyle.width = _fnStringToCss( correction );
divHeaderStyle.width = _fnStringToCss( correction );
if ( footer ) {
settings.nScrollFoot.style.width = _fnStringToCss( correction );
}
/*
* 4. Clean up
*/
if ( ! scrollY ) {
/* IE7< puts a vertical scrollbar in place (when it shouldn't be) due to subtracting
* the scrollbar height from the visible display, rather than adding it on. We need to
* set the height in order to sort this. Don't want to do it in any other browsers.
*/
if ( ie67 ) {
divBodyStyle.height = _fnStringToCss( tableEl.offsetHeight+barWidth );
}
}
/* Finally set the width's of the header and footer tables */
var iOuterWidth = table.outerWidth();
divHeaderTable[0].style.width = _fnStringToCss( iOuterWidth );
divHeaderInnerStyle.width = _fnStringToCss( iOuterWidth );
// Figure out if there are scrollbar present - if so then we need a the header and footer to
// provide a bit more space to allow "overflow" scrolling (i.e. past the scrollbar)
var bScrolling = table.height() > divBodyEl.clientHeight || divBody.css('overflow-y') == "scroll";
var padding = 'padding' + (browser.bScrollbarLeft ? 'Left' : 'Right' );
divHeaderInnerStyle[ padding ] = bScrolling ? barWidth+"px" : "0px";
if ( footer ) {
divFooterTable[0].style.width = _fnStringToCss( iOuterWidth );
divFooterInner[0].style.width = _fnStringToCss( iOuterWidth );
divFooterInner[0].style[padding] = bScrolling ? barWidth+"px" : "0px";
}
// Correct DOM ordering for colgroup - comes before the thead
table.children('colgroup').insertBefore( table.children('thead') );
/* Adjust the position of the header in case we loose the y-scrollbar */
divBody.trigger('scroll');
// If sorting or filtering has occurred, jump the scrolling back to the top
// only if we aren't holding the position
if ( (settings.bSorted || settings.bFiltered) && ! settings._drawHold ) {
divBodyEl.scrollTop = 0;
}
}
/**
* Apply a given function to the display child nodes of an element array (typically
* TD children of TR rows
* @param {function} fn Method to apply to the objects
* @param array {nodes} an1 List of elements to look through for display children
* @param array {nodes} an2 Another list (identical structure to the first) - optional
* @memberof DataTable#oApi
*/
function _fnApplyToChildren( fn, an1, an2 )
{
var index=0, i=0, iLen=an1.length;
var nNode1, nNode2;
while ( i < iLen ) {
nNode1 = an1[i].firstChild;
nNode2 = an2 ? an2[i].firstChild : null;
while ( nNode1 ) {
if ( nNode1.nodeType === 1 ) {
if ( an2 ) {
fn( nNode1, nNode2, index );
}
else {
fn( nNode1, index );
}
index++;
}
nNode1 = nNode1.nextSibling;
nNode2 = an2 ? nNode2.nextSibling : null;
}
i++;
}
}
var __re_html_remove = /<.*?>/g;
/**
* Calculate the width of columns for the table
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnCalculateColumnWidths ( oSettings )
{
var
table = oSettings.nTable,
columns = oSettings.aoColumns,
scroll = oSettings.oScroll,
scrollY = scroll.sY,
scrollX = scroll.sX,
scrollXInner = scroll.sXInner,
columnCount = columns.length,
visibleColumns = _fnGetColumns( oSettings, 'bVisible' ),
headerCells = $('th', oSettings.nTHead),
tableWidthAttr = table.getAttribute('width'), // from DOM element
tableContainer = table.parentNode,
userInputs = false,
i, column, columnIdx, width, outerWidth,
browser = oSettings.oBrowser,
ie67 = browser.bScrollOversize;
var styleWidth = table.style.width;
if ( styleWidth && styleWidth.indexOf('%') !== -1 ) {
tableWidthAttr = styleWidth;
}
/* Convert any user input sizes into pixel sizes */
for ( i=0 ; i<visibleColumns.length ; i++ ) {
column = columns[ visibleColumns[i] ];
if ( column.sWidth !== null ) {
column.sWidth = _fnConvertToWidth( column.sWidthOrig, tableContainer );
userInputs = true;
}
}
/* If the number of columns in the DOM equals the number that we have to
* process in DataTables, then we can use the offsets that are created by
* the web- browser. No custom sizes can be set in order for this to happen,
* nor scrolling used
*/
if ( ie67 || ! userInputs && ! scrollX && ! scrollY &&
columnCount == _fnVisbleColumns( oSettings ) &&
columnCount == headerCells.length
) {
for ( i=0 ; i<columnCount ; i++ ) {
var colIdx = _fnVisibleToColumnIndex( oSettings, i );
if ( colIdx !== null ) {
columns[ colIdx ].sWidth = _fnStringToCss( headerCells.eq(i).width() );
}
}
}
else
{
// Otherwise construct a single row, worst case, table with the widest
// node in the data, assign any user defined widths, then insert it into
// the DOM and allow the browser to do all the hard work of calculating
// table widths
var tmpTable = $(table).clone() // don't use cloneNode - IE8 will remove events on the main table
.css( 'visibility', 'hidden' )
.removeAttr( 'id' );
// Clean up the table body
tmpTable.find('tbody tr').remove();
var tr = $('<tr/>').appendTo( tmpTable.find('tbody') );
// Clone the table header and footer - we can't use the header / footer
// from the cloned table, since if scrolling is active, the table's
// real header and footer are contained in different table tags
tmpTable.find('thead, tfoot').remove();
tmpTable
.append( $(oSettings.nTHead).clone() )
.append( $(oSettings.nTFoot).clone() );
// Remove any assigned widths from the footer (from scrolling)
tmpTable.find('tfoot th, tfoot td').css('width', '');
// Apply custom sizing to the cloned header
headerCells = _fnGetUniqueThs( oSettings, tmpTable.find('thead')[0] );
for ( i=0 ; i<visibleColumns.length ; i++ ) {
column = columns[ visibleColumns[i] ];
headerCells[i].style.width = column.sWidthOrig !== null && column.sWidthOrig !== '' ?
_fnStringToCss( column.sWidthOrig ) :
'';
// For scrollX we need to force the column width otherwise the
// browser will collapse it. If this width is smaller than the
// width the column requires, then it will have no effect
if ( column.sWidthOrig && scrollX ) {
$( headerCells[i] ).append( $('<div/>').css( {
width: column.sWidthOrig,
margin: 0,
padding: 0,
border: 0,
height: 1
} ) );
}
}
// Find the widest cell for each column and put it into the table
if ( oSettings.aoData.length ) {
for ( i=0 ; i<visibleColumns.length ; i++ ) {
columnIdx = visibleColumns[i];
column = columns[ columnIdx ];
$( _fnGetWidestNode( oSettings, columnIdx ) )
.clone( false )
.append( column.sContentPadding )
.appendTo( tr );
}
}
// Tidy the temporary table - remove name attributes so there aren't
// duplicated in the dom (radio elements for example)
$('[name]', tmpTable).removeAttr('name');
// Table has been built, attach to the document so we can work with it.
// A holding element is used, positioned at the top of the container
// with minimal height, so it has no effect on if the container scrolls
// or not. Otherwise it might trigger scrolling when it actually isn't
// needed
var holder = $('<div/>').css( scrollX || scrollY ?
{
position: 'absolute',
top: 0,
left: 0,
height: 1,
right: 0,
overflow: 'hidden'
} :
{}
)
.append( tmpTable )
.appendTo( tableContainer );
// When scrolling (X or Y) we want to set the width of the table as
// appropriate. However, when not scrolling leave the table width as it
// is. This results in slightly different, but I think correct behaviour
if ( scrollX && scrollXInner ) {
tmpTable.width( scrollXInner );
}
else if ( scrollX ) {
tmpTable.css( 'width', 'auto' );
tmpTable.removeAttr('width');
// If there is no width attribute or style, then allow the table to
// collapse
if ( tmpTable.width() < tableContainer.clientWidth && tableWidthAttr ) {
tmpTable.width( tableContainer.clientWidth );
}
}
else if ( scrollY ) {
tmpTable.width( tableContainer.clientWidth );
}
else if ( tableWidthAttr ) {
tmpTable.width( tableWidthAttr );
}
// Get the width of each column in the constructed table - we need to
// know the inner width (so it can be assigned to the other table's
// cells) and the outer width so we can calculate the full width of the
// table. This is safe since DataTables requires a unique cell for each
// column, but if ever a header can span multiple columns, this will
// need to be modified.
var total = 0;
for ( i=0 ; i<visibleColumns.length ; i++ ) {
var cell = $(headerCells[i]);
var border = cell.outerWidth() - cell.width();
// Use getBounding... where possible (not IE8-) because it can give
// sub-pixel accuracy, which we then want to round up!
var bounding = browser.bBounding ?
Math.ceil( headerCells[i].getBoundingClientRect().width ) :
cell.outerWidth();
// Total is tracked to remove any sub-pixel errors as the outerWidth
// of the table might not equal the total given here (IE!).
total += bounding;
// Width for each column to use
columns[ visibleColumns[i] ].sWidth = _fnStringToCss( bounding - border );
}
table.style.width = _fnStringToCss( total );
// Finished with the table - ditch it
holder.remove();
}
// If there is a width attr, we want to attach an event listener which
// allows the table sizing to automatically adjust when the window is
// resized. Use the width attr rather than CSS, since we can't know if the
// CSS is a relative value or absolute - DOM read is always px.
if ( tableWidthAttr ) {
table.style.width = _fnStringToCss( tableWidthAttr );
}
if ( (tableWidthAttr || scrollX) && ! oSettings._reszEvt ) {
var bindResize = function () {
$(window).on('resize.DT-'+oSettings.sInstance, _fnThrottle( function () {
_fnAdjustColumnSizing( oSettings );
} ) );
};
// IE6/7 will crash if we bind a resize event handler on page load.
// To be removed in 1.11 which drops IE6/7 support
if ( ie67 ) {
setTimeout( bindResize, 1000 );
}
else {
bindResize();
}
oSettings._reszEvt = true;
}
}
/**
* Throttle the calls to a function. Arguments and context are maintained for
* the throttled function
* @param {function} fn Function to be called
* @param {int} [freq=200] call frequency in mS
* @returns {function} wrapped function
* @memberof DataTable#oApi
*/
var _fnThrottle = DataTable.util.throttle;
/**
* Convert a CSS unit width to pixels (e.g. 2em)
* @param {string} width width to be converted
* @param {node} parent parent to get the with for (required for relative widths) - optional
* @returns {int} width in pixels
* @memberof DataTable#oApi
*/
function _fnConvertToWidth ( width, parent )
{
if ( ! width ) {
return 0;
}
var n = $('<div/>')
.css( 'width', _fnStringToCss( width ) )
.appendTo( parent || document.body );
var val = n[0].offsetWidth;
n.remove();
return val;
}
/**
* Get the widest node
* @param {object} settings dataTables settings object
* @param {int} colIdx column of interest
* @returns {node} widest table node
* @memberof DataTable#oApi
*/
function _fnGetWidestNode( settings, colIdx )
{
var idx = _fnGetMaxLenString( settings, colIdx );
if ( idx < 0 ) {
return null;
}
var data = settings.aoData[ idx ];
return ! data.nTr ? // Might not have been created when deferred rendering
$('<td/>').html( _fnGetCellData( settings, idx, colIdx, 'display' ) )[0] :
data.anCells[ colIdx ];
}
/**
* Get the maximum strlen for each data column
* @param {object} settings dataTables settings object
* @param {int} colIdx column of interest
* @returns {string} max string length for each column
* @memberof DataTable#oApi
*/
function _fnGetMaxLenString( settings, colIdx )
{
var s, max=-1, maxIdx = -1;
for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
s = _fnGetCellData( settings, i, colIdx, 'display' )+'';
s = s.replace( __re_html_remove, '' );
s = s.replace( / /g, ' ' );
if ( s.length > max ) {
max = s.length;
maxIdx = i;
}
}
return maxIdx;
}
/**
* Append a CSS unit (only if required) to a string
* @param {string} value to css-ify
* @returns {string} value with css unit
* @memberof DataTable#oApi
*/
function _fnStringToCss( s )
{
if ( s === null ) {
return '0px';
}
if ( typeof s == 'number' ) {
return s < 0 ?
'0px' :
s+'px';
}
// Check it has a unit character already
return s.match(/\d$/) ?
s+'px' :
s;
}
function _fnSortFlatten ( settings )
{
var
i, iLen, k, kLen,
aSort = [],
aiOrig = [],
aoColumns = settings.aoColumns,
aDataSort, iCol, sType, srcCol,
fixed = settings.aaSortingFixed,
fixedObj = $.isPlainObject( fixed ),
nestedSort = [],
add = function ( a ) {
if ( a.length && ! Array.isArray( a[0] ) ) {
// 1D array
nestedSort.push( a );
}
else {
// 2D array
$.merge( nestedSort, a );
}
};
// Build the sort array, with pre-fix and post-fix options if they have been
// specified
if ( Array.isArray( fixed ) ) {
add( fixed );
}
if ( fixedObj && fixed.pre ) {
add( fixed.pre );
}
add( settings.aaSorting );
if (fixedObj && fixed.post ) {
add( fixed.post );
}
for ( i=0 ; i<nestedSort.length ; i++ )
{
srcCol = nestedSort[i][0];
aDataSort = aoColumns[ srcCol ].aDataSort;
for ( k=0, kLen=aDataSort.length ; k<kLen ; k++ )
{
iCol = aDataSort[k];
sType = aoColumns[ iCol ].sType || 'string';
if ( nestedSort[i]._idx === undefined ) {
nestedSort[i]._idx = $.inArray( nestedSort[i][1], aoColumns[iCol].asSorting );
}
aSort.push( {
src: srcCol,
col: iCol,
dir: nestedSort[i][1],
index: nestedSort[i]._idx,
type: sType,
formatter: DataTable.ext.type.order[ sType+"-pre" ]
} );
}
}
return aSort;
}
/**
* Change the order of the table
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
* @todo This really needs split up!
*/
function _fnSort ( oSettings )
{
var
i, ien, iLen, j, jLen, k, kLen,
sDataType, nTh,
aiOrig = [],
oExtSort = DataTable.ext.type.order,
aoData = oSettings.aoData,
aoColumns = oSettings.aoColumns,
aDataSort, data, iCol, sType, oSort,
formatters = 0,
sortCol,
displayMaster = oSettings.aiDisplayMaster,
aSort;
// Resolve any column types that are unknown due to addition or invalidation
// @todo Can this be moved into a 'data-ready' handler which is called when
// data is going to be used in the table?
_fnColumnTypes( oSettings );
aSort = _fnSortFlatten( oSettings );
for ( i=0, ien=aSort.length ; i<ien ; i++ ) {
sortCol = aSort[i];
// Track if we can use the fast sort algorithm
if ( sortCol.formatter ) {
formatters++;
}
// Load the data needed for the sort, for each cell
_fnSortData( oSettings, sortCol.col );
}
/* No sorting required if server-side or no sorting array */
if ( _fnDataSource( oSettings ) != 'ssp' && aSort.length !== 0 )
{
// Create a value - key array of the current row positions such that we can use their
// current position during the sort, if values match, in order to perform stable sorting
for ( i=0, iLen=displayMaster.length ; i<iLen ; i++ ) {
aiOrig[ displayMaster[i] ] = i;
}
/* Do the sort - here we want multi-column sorting based on a given data source (column)
* and sorting function (from oSort) in a certain direction. It's reasonably complex to
* follow on it's own, but this is what we want (example two column sorting):
* fnLocalSorting = function(a,b){
* var iTest;
* iTest = oSort['string-asc']('data11', 'data12');
* if (iTest !== 0)
* return iTest;
* iTest = oSort['numeric-desc']('data21', 'data22');
* if (iTest !== 0)
* return iTest;
* return oSort['numeric-asc']( aiOrig[a], aiOrig[b] );
* }
* Basically we have a test for each sorting column, if the data in that column is equal,
* test the next column. If all columns match, then we use a numeric sort on the row
* positions in the original data array to provide a stable sort.
*
* Note - I know it seems excessive to have two sorting methods, but the first is around
* 15% faster, so the second is only maintained for backwards compatibility with sorting
* methods which do not have a pre-sort formatting function.
*/
if ( formatters === aSort.length ) {
// All sort types have formatting functions
displayMaster.sort( function ( a, b ) {
var
x, y, k, test, sort,
len=aSort.length,
dataA = aoData[a]._aSortData,
dataB = aoData[b]._aSortData;
for ( k=0 ; k<len ; k++ ) {
sort = aSort[k];
x = dataA[ sort.col ];
y = dataB[ sort.col ];
test = x<y ? -1 : x>y ? 1 : 0;
if ( test !== 0 ) {
return sort.dir === 'asc' ? test : -test;
}
}
x = aiOrig[a];
y = aiOrig[b];
return x<y ? -1 : x>y ? 1 : 0;
} );
}
else {
// Depreciated - remove in 1.11 (providing a plug-in option)
// Not all sort types have formatting methods, so we have to call their sorting
// methods.
displayMaster.sort( function ( a, b ) {
var
x, y, k, l, test, sort, fn,
len=aSort.length,
dataA = aoData[a]._aSortData,
dataB = aoData[b]._aSortData;
for ( k=0 ; k<len ; k++ ) {
sort = aSort[k];
x = dataA[ sort.col ];
y = dataB[ sort.col ];
fn = oExtSort[ sort.type+"-"+sort.dir ] || oExtSort[ "string-"+sort.dir ];
test = fn( x, y );
if ( test !== 0 ) {
return test;
}
}
x = aiOrig[a];
y = aiOrig[b];
return x<y ? -1 : x>y ? 1 : 0;
} );
}
}
/* Tell the draw function that we have sorted the data */
oSettings.bSorted = true;
}
function _fnSortAria ( settings )
{
var label;
var nextSort;
var columns = settings.aoColumns;
var aSort = _fnSortFlatten( settings );
var oAria = settings.oLanguage.oAria;
// ARIA attributes - need to loop all columns, to update all (removing old
// attributes as needed)
for ( var i=0, iLen=columns.length ; i<iLen ; i++ )
{
var col = columns[i];
var asSorting = col.asSorting;
var sTitle = col.sTitle.replace( /<.*?>/g, "" );
var th = col.nTh;
// IE7 is throwing an error when setting these properties with jQuery's
// attr() and removeAttr() methods...
th.removeAttribute('aria-sort');
/* In ARIA only the first sorting column can be marked as sorting - no multi-sort option */
if ( col.bSortable ) {
if ( aSort.length > 0 && aSort[0].col == i ) {
th.setAttribute('aria-sort', aSort[0].dir=="asc" ? "ascending" : "descending" );
nextSort = asSorting[ aSort[0].index+1 ] || asSorting[0];
}
else {
nextSort = asSorting[0];
}
label = sTitle + ( nextSort === "asc" ?
oAria.sSortAscending :
oAria.sSortDescending
);
}
else {
label = sTitle;
}
th.setAttribute('aria-label', label);
}
}
/**
* Function to run on user sort request
* @param {object} settings dataTables settings object
* @param {node} attachTo node to attach the handler to
* @param {int} colIdx column sorting index
* @param {boolean} [append=false] Append the requested sort to the existing
* sort if true (i.e. multi-column sort)
* @param {function} [callback] callback function
* @memberof DataTable#oApi
*/
function _fnSortListener ( settings, colIdx, append, callback )
{
var col = settings.aoColumns[ colIdx ];
var sorting = settings.aaSorting;
var asSorting = col.asSorting;
var nextSortIdx;
var next = function ( a, overflow ) {
var idx = a._idx;
if ( idx === undefined ) {
idx = $.inArray( a[1], asSorting );
}
return idx+1 < asSorting.length ?
idx+1 :
overflow ?
null :
0;
};
// Convert to 2D array if needed
if ( typeof sorting[0] === 'number' ) {
sorting = settings.aaSorting = [ sorting ];
}
// If appending the sort then we are multi-column sorting
if ( append && settings.oFeatures.bSortMulti ) {
// Are we already doing some kind of sort on this column?
var sortIdx = $.inArray( colIdx, _pluck(sorting, '0') );
if ( sortIdx !== -1 ) {
// Yes, modify the sort
nextSortIdx = next( sorting[sortIdx], true );
if ( nextSortIdx === null && sorting.length === 1 ) {
nextSortIdx = 0; // can't remove sorting completely
}
if ( nextSortIdx === null ) {
sorting.splice( sortIdx, 1 );
}
else {
sorting[sortIdx][1] = asSorting[ nextSortIdx ];
sorting[sortIdx]._idx = nextSortIdx;
}
}
else {
// No sort on this column yet
sorting.push( [ colIdx, asSorting[0], 0 ] );
sorting[sorting.length-1]._idx = 0;
}
}
else if ( sorting.length && sorting[0][0] == colIdx ) {
// Single column - already sorting on this column, modify the sort
nextSortIdx = next( sorting[0] );
sorting.length = 1;
sorting[0][1] = asSorting[ nextSortIdx ];
sorting[0]._idx = nextSortIdx;
}
else {
// Single column - sort only on this column
sorting.length = 0;
sorting.push( [ colIdx, asSorting[0] ] );
sorting[0]._idx = 0;
}
// Run the sort by calling a full redraw
_fnReDraw( settings );
// callback used for async user interaction
if ( typeof callback == 'function' ) {
callback( settings );
}
}
/**
* Attach a sort handler (click) to a node
* @param {object} settings dataTables settings object
* @param {node} attachTo node to attach the handler to
* @param {int} colIdx column sorting index
* @param {function} [callback] callback function
* @memberof DataTable#oApi
*/
function _fnSortAttachListener ( settings, attachTo, colIdx, callback )
{
var col = settings.aoColumns[ colIdx ];
_fnBindAction( attachTo, {}, function (e) {
/* If the column is not sortable - don't to anything */
if ( col.bSortable === false ) {
return;
}
// If processing is enabled use a timeout to allow the processing
// display to be shown - otherwise to it synchronously
if ( settings.oFeatures.bProcessing ) {
_fnProcessingDisplay( settings, true );
setTimeout( function() {
_fnSortListener( settings, colIdx, e.shiftKey, callback );
// In server-side processing, the draw callback will remove the
// processing display
if ( _fnDataSource( settings ) !== 'ssp' ) {
_fnProcessingDisplay( settings, false );
}
}, 0 );
}
else {
_fnSortListener( settings, colIdx, e.shiftKey, callback );
}
} );
}
/**
* Set the sorting classes on table's body, Note: it is safe to call this function
* when bSort and bSortClasses are false
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnSortingClasses( settings )
{
var oldSort = settings.aLastSort;
var sortClass = settings.oClasses.sSortColumn;
var sort = _fnSortFlatten( settings );
var features = settings.oFeatures;
var i, ien, colIdx;
if ( features.bSort && features.bSortClasses ) {
// Remove old sorting classes
for ( i=0, ien=oldSort.length ; i<ien ; i++ ) {
colIdx = oldSort[i].src;
// Remove column sorting
$( _pluck( settings.aoData, 'anCells', colIdx ) )
.removeClass( sortClass + (i<2 ? i+1 : 3) );
}
// Add new column sorting
for ( i=0, ien=sort.length ; i<ien ; i++ ) {
colIdx = sort[i].src;
$( _pluck( settings.aoData, 'anCells', colIdx ) )
.addClass( sortClass + (i<2 ? i+1 : 3) );
}
}
settings.aLastSort = sort;
}
// Get the data to sort a column, be it from cache, fresh (populating the
// cache), or from a sort formatter
function _fnSortData( settings, idx )
{
// Custom sorting function - provided by the sort data type
var column = settings.aoColumns[ idx ];
var customSort = DataTable.ext.order[ column.sSortDataType ];
var customData;
if ( customSort ) {
customData = customSort.call( settings.oInstance, settings, idx,
_fnColumnIndexToVisible( settings, idx )
);
}
// Use / populate cache
var row, cellData;
var formatter = DataTable.ext.type.order[ column.sType+"-pre" ];
for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
row = settings.aoData[i];
if ( ! row._aSortData ) {
row._aSortData = [];
}
if ( ! row._aSortData[idx] || customSort ) {
cellData = customSort ?
customData[i] : // If there was a custom sort function, use data from there
_fnGetCellData( settings, i, idx, 'sort' );
row._aSortData[ idx ] = formatter ?
formatter( cellData ) :
cellData;
}
}
}
/**
* Save the state of a table
* @param {object} oSettings dataTables settings object
* @memberof DataTable#oApi
*/
function _fnSaveState ( settings )
{
if ( !settings.oFeatures.bStateSave || settings.bDestroying )
{
return;
}
/* Store the interesting variables */
var state = {
time: +new Date(),
start: settings._iDisplayStart,
length: settings._iDisplayLength,
order: $.extend( true, [], settings.aaSorting ),
search: _fnSearchToCamel( settings.oPreviousSearch ),
columns: $.map( settings.aoColumns, function ( col, i ) {
return {
visible: col.bVisible,
search: _fnSearchToCamel( settings.aoPreSearchCols[i] )
};
} )
};
_fnCallbackFire( settings, "aoStateSaveParams", 'stateSaveParams', [settings, state] );
settings.oSavedState = state;
settings.fnStateSaveCallback.call( settings.oInstance, settings, state );
}
/**
* Attempt to load a saved table state
* @param {object} oSettings dataTables settings object
* @param {object} oInit DataTables init object so we can override settings
* @param {function} callback Callback to execute when the state has been loaded
* @memberof DataTable#oApi
*/
function _fnLoadState ( settings, oInit, callback )
{
var i, ien;
var columns = settings.aoColumns;
var loaded = function ( s ) {
if ( ! s || ! s.time ) {
callback();
return;
}
// Allow custom and plug-in manipulation functions to alter the saved data set and
// cancelling of loading by returning false
var abStateLoad = _fnCallbackFire( settings, 'aoStateLoadParams', 'stateLoadParams', [settings, s] );
if ( $.inArray( false, abStateLoad ) !== -1 ) {
callback();
return;
}
// Reject old data
var duration = settings.iStateDuration;
if ( duration > 0 && s.time < +new Date() - (duration*1000) ) {
callback();
return;
}
// Number of columns have changed - all bets are off, no restore of settings
if ( s.columns && columns.length !== s.columns.length ) {
callback();
return;
}
// Store the saved state so it might be accessed at any time
settings.oLoadedState = $.extend( true, {}, s );
// Restore key features - todo - for 1.11 this needs to be done by
// subscribed events
if ( s.start !== undefined ) {
settings._iDisplayStart = s.start;
settings.iInitDisplayStart = s.start;
}
if ( s.length !== undefined ) {
settings._iDisplayLength = s.length;
}
// Order
if ( s.order !== undefined ) {
settings.aaSorting = [];
$.each( s.order, function ( i, col ) {
settings.aaSorting.push( col[0] >= columns.length ?
[ 0, col[1] ] :
col
);
} );
}
// Search
if ( s.search !== undefined ) {
$.extend( settings.oPreviousSearch, _fnSearchToHung( s.search ) );
}
// Columns
//
if ( s.columns ) {
for ( i=0, ien=s.columns.length ; i<ien ; i++ ) {
var col = s.columns[i];
// Visibility
if ( col.visible !== undefined ) {
columns[i].bVisible = col.visible;
}
// Search
if ( col.search !== undefined ) {
$.extend( settings.aoPreSearchCols[i], _fnSearchToHung( col.search ) );
}
}
}
_fnCallbackFire( settings, 'aoStateLoaded', 'stateLoaded', [settings, s] );
callback();
};
if ( ! settings.oFeatures.bStateSave ) {
callback();
return;
}
var state = settings.fnStateLoadCallback.call( settings.oInstance, settings, loaded );
if ( state !== undefined ) {
loaded( state );
}
// otherwise, wait for the loaded callback to be executed
}
/**
* Return the settings object for a particular table
* @param {node} table table we are using as a dataTable
* @returns {object} Settings object - or null if not found
* @memberof DataTable#oApi
*/
function _fnSettingsFromNode ( table )
{
var settings = DataTable.settings;
var idx = $.inArray( table, _pluck( settings, 'nTable' ) );
return idx !== -1 ?
settings[ idx ] :
null;
}
/**
* Log an error message
* @param {object} settings dataTables settings object
* @param {int} level log error messages, or display them to the user
* @param {string} msg error message
* @param {int} tn Technical note id to get more information about the error.
* @memberof DataTable#oApi
*/
function _fnLog( settings, level, msg, tn )
{
msg = 'DataTables warning: '+
(settings ? 'table id='+settings.sTableId+' - ' : '')+msg;
if ( tn ) {
msg += '. For more information about this error, please see '+
'http://datatables.net/tn/'+tn;
}
if ( ! level ) {
// Backwards compatibility pre 1.10
var ext = DataTable.ext;
var type = ext.sErrMode || ext.errMode;
if ( settings ) {
_fnCallbackFire( settings, null, 'error', [ settings, tn, msg ] );
}
if ( type == 'alert' ) {
alert( msg );
}
else if ( type == 'throw' ) {
throw new Error(msg);
}
else if ( typeof type == 'function' ) {
type( settings, tn, msg );
}
}
else if ( window.console && console.log ) {
console.log( msg );
}
}
/**
* See if a property is defined on one object, if so assign it to the other object
* @param {object} ret target object
* @param {object} src source object
* @param {string} name property
* @param {string} [mappedName] name to map too - optional, name used if not given
* @memberof DataTable#oApi
*/
function _fnMap( ret, src, name, mappedName )
{
if ( Array.isArray( name ) ) {
$.each( name, function (i, val) {
if ( Array.isArray( val ) ) {
_fnMap( ret, src, val[0], val[1] );
}
else {
_fnMap( ret, src, val );
}
} );
return;
}
if ( mappedName === undefined ) {
mappedName = name;
}
if ( src[name] !== undefined ) {
ret[mappedName] = src[name];
}
}
/**
* Extend objects - very similar to jQuery.extend, but deep copy objects, and
* shallow copy arrays. The reason we need to do this, is that we don't want to
* deep copy array init values (such as aaSorting) since the dev wouldn't be
* able to override them, but we do want to deep copy arrays.
* @param {object} out Object to extend
* @param {object} extender Object from which the properties will be applied to
* out
* @param {boolean} breakRefs If true, then arrays will be sliced to take an
* independent copy with the exception of the `data` or `aaData` parameters
* if they are present. This is so you can pass in a collection to
* DataTables and have that used as your data source without breaking the
* references
* @returns {object} out Reference, just for convenience - out === the return.
* @memberof DataTable#oApi
* @todo This doesn't take account of arrays inside the deep copied objects.
*/
function _fnExtend( out, extender, breakRefs )
{
var val;
for ( var prop in extender ) {
if ( extender.hasOwnProperty(prop) ) {
val = extender[prop];
if ( $.isPlainObject( val ) ) {
if ( ! $.isPlainObject( out[prop] ) ) {
out[prop] = {};
}
$.extend( true, out[prop], val );
}
else if ( breakRefs && prop !== 'data' && prop !== 'aaData' && Array.isArray(val) ) {
out[prop] = val.slice();
}
else {
out[prop] = val;
}
}
}
return out;
}
/**
* Bind an event handers to allow a click or return key to activate the callback.
* This is good for accessibility since a return on the keyboard will have the
* same effect as a click, if the element has focus.
* @param {element} n Element to bind the action to
* @param {object} oData Data object to pass to the triggered function
* @param {function} fn Callback function for when the event is triggered
* @memberof DataTable#oApi
*/
function _fnBindAction( n, oData, fn )
{
$(n)
.on( 'click.DT', oData, function (e) {
$(n).trigger('blur'); // Remove focus outline for mouse users
fn(e);
} )
.on( 'keypress.DT', oData, function (e){
if ( e.which === 13 ) {
e.preventDefault();
fn(e);
}
} )
.on( 'selectstart.DT', function () {
/* Take the brutal approach to cancelling text selection */
return false;
} );
}
/**
* Register a callback function. Easily allows a callback function to be added to
* an array store of callback functions that can then all be called together.
* @param {object} oSettings dataTables settings object
* @param {string} sStore Name of the array storage for the callbacks in oSettings
* @param {function} fn Function to be called back
* @param {string} sName Identifying name for the callback (i.e. a label)
* @memberof DataTable#oApi
*/
function _fnCallbackReg( oSettings, sStore, fn, sName )
{
if ( fn )
{
oSettings[sStore].push( {
"fn": fn,
"sName": sName
} );
}
}
/**
* Fire callback functions and trigger events. Note that the loop over the
* callback array store is done backwards! Further note that you do not want to
* fire off triggers in time sensitive applications (for example cell creation)
* as its slow.
* @param {object} settings dataTables settings object
* @param {string} callbackArr Name of the array storage for the callbacks in
* oSettings
* @param {string} eventName Name of the jQuery custom event to trigger. If
* null no trigger is fired
* @param {array} args Array of arguments to pass to the callback function /
* trigger
* @memberof DataTable#oApi
*/
function _fnCallbackFire( settings, callbackArr, eventName, args )
{
var ret = [];
if ( callbackArr ) {
ret = $.map( settings[callbackArr].slice().reverse(), function (val, i) {
return val.fn.apply( settings.oInstance, args );
} );
}
if ( eventName !== null ) {
var e = $.Event( eventName+'.dt' );
$(settings.nTable).trigger( e, args );
ret.push( e.result );
}
return ret;
}
function _fnLengthOverflow ( settings )
{
var
start = settings._iDisplayStart,
end = settings.fnDisplayEnd(),
len = settings._iDisplayLength;
/* If we have space to show extra rows (backing up from the end point - then do so */
if ( start >= end )
{
start = end - len;
}
// Keep the start record on the current page
start -= (start % len);
if ( len === -1 || start < 0 )
{
start = 0;
}
settings._iDisplayStart = start;
}
function _fnRenderer( settings, type )
{
var renderer = settings.renderer;
var host = DataTable.ext.renderer[type];
if ( $.isPlainObject( renderer ) && renderer[type] ) {
// Specific renderer for this type. If available use it, otherwise use
// the default.
return host[renderer[type]] || host._;
}
else if ( typeof renderer === 'string' ) {
// Common renderer - if there is one available for this type use it,
// otherwise use the default
return host[renderer] || host._;
}
// Use the default
return host._;
}
/**
* Detect the data source being used for the table. Used to simplify the code
* a little (ajax) and to make it compress a little smaller.
*
* @param {object} settings dataTables settings object
* @returns {string} Data source
* @memberof DataTable#oApi
*/
function _fnDataSource ( settings )
{
if ( settings.oFeatures.bServerSide ) {
return 'ssp';
}
else if ( settings.ajax || settings.sAjaxSource ) {
return 'ajax';
}
return 'dom';
}
/**
* Computed structure of the DataTables API, defined by the options passed to
* `DataTable.Api.register()` when building the API.
*
* The structure is built in order to speed creation and extension of the Api
* objects since the extensions are effectively pre-parsed.
*
* The array is an array of objects with the following structure, where this
* base array represents the Api prototype base:
*
* [
* {
* name: 'data' -- string - Property name
* val: function () {}, -- function - Api method (or undefined if just an object
* methodExt: [ ... ], -- array - Array of Api object definitions to extend the method result
* propExt: [ ... ] -- array - Array of Api object definitions to extend the property
* },
* {
* name: 'row'
* val: {},
* methodExt: [ ... ],
* propExt: [
* {
* name: 'data'
* val: function () {},
* methodExt: [ ... ],
* propExt: [ ... ]
* },
* ...
* ]
* }
* ]
*
* @type {Array}
* @ignore
*/
var __apiStruct = [];
/**
* `Array.prototype` reference.
*
* @type object
* @ignore
*/
var __arrayProto = Array.prototype;
/**
* Abstraction for `context` parameter of the `Api` constructor to allow it to
* take several different forms for ease of use.
*
* Each of the input parameter types will be converted to a DataTables settings
* object where possible.
*
* @param {string|node|jQuery|object} mixed DataTable identifier. Can be one
* of:
*
* * `string` - jQuery selector. Any DataTables' matching the given selector
* with be found and used.
* * `node` - `TABLE` node which has already been formed into a DataTable.
* * `jQuery` - A jQuery object of `TABLE` nodes.
* * `object` - DataTables settings object
* * `DataTables.Api` - API instance
* @return {array|null} Matching DataTables settings objects. `null` or
* `undefined` is returned if no matching DataTable is found.
* @ignore
*/
var _toSettings = function ( mixed )
{
var idx, jq;
var settings = DataTable.settings;
var tables = $.map( settings, function (el, i) {
return el.nTable;
} );
if ( ! mixed ) {
return [];
}
else if ( mixed.nTable && mixed.oApi ) {
// DataTables settings object
return [ mixed ];
}
else if ( mixed.nodeName && mixed.nodeName.toLowerCase() === 'table' ) {
// Table node
idx = $.inArray( mixed, tables );
return idx !== -1 ? [ settings[idx] ] : null;
}
else if ( mixed && typeof mixed.settings === 'function' ) {
return mixed.settings().toArray();
}
else if ( typeof mixed === 'string' ) {
// jQuery selector
jq = $(mixed);
}
else if ( mixed instanceof $ ) {
// jQuery object (also DataTables instance)
jq = mixed;
}
if ( jq ) {
return jq.map( function(i) {
idx = $.inArray( this, tables );
return idx !== -1 ? settings[idx] : null;
} ).toArray();
}
};
/**
* DataTables API class - used to control and interface with one or more
* DataTables enhanced tables.
*
* The API class is heavily based on jQuery, presenting a chainable interface
* that you can use to interact with tables. Each instance of the API class has
* a "context" - i.e. the tables that it will operate on. This could be a single
* table, all tables on a page or a sub-set thereof.
*
* Additionally the API is designed to allow you to easily work with the data in
* the tables, retrieving and manipulating it as required. This is done by
* presenting the API class as an array like interface. The contents of the
* array depend upon the actions requested by each method (for example
* `rows().nodes()` will return an array of nodes, while `rows().data()` will
* return an array of objects or arrays depending upon your table's
* configuration). The API object has a number of array like methods (`push`,
* `pop`, `reverse` etc) as well as additional helper methods (`each`, `pluck`,
* `unique` etc) to assist your working with the data held in a table.
*
* Most methods (those which return an Api instance) are chainable, which means
* the return from a method call also has all of the methods available that the
* top level object had. For example, these two calls are equivalent:
*
* // Not chained
* api.row.add( {...} );
* api.draw();
*
* // Chained
* api.row.add( {...} ).draw();
*
* @class DataTable.Api
* @param {array|object|string|jQuery} context DataTable identifier. This is
* used to define which DataTables enhanced tables this API will operate on.
* Can be one of:
*
* * `string` - jQuery selector. Any DataTables' matching the given selector
* with be found and used.
* * `node` - `TABLE` node which has already been formed into a DataTable.
* * `jQuery` - A jQuery object of `TABLE` nodes.
* * `object` - DataTables settings object
* @param {array} [data] Data to initialise the Api instance with.
*
* @example
* // Direct initialisation during DataTables construction
* var api = $('#example').DataTable();
*
* @example
* // Initialisation using a DataTables jQuery object
* var api = $('#example').dataTable().api();
*
* @example
* // Initialisation as a constructor
* var api = new $.fn.DataTable.Api( 'table.dataTable' );
*/
_Api = function ( context, data )
{
if ( ! (this instanceof _Api) ) {
return new _Api( context, data );
}
var settings = [];
var ctxSettings = function ( o ) {
var a = _toSettings( o );
if ( a ) {
settings.push.apply( settings, a );
}
};
if ( Array.isArray( context ) ) {
for ( var i=0, ien=context.length ; i<ien ; i++ ) {
ctxSettings( context[i] );
}
}
else {
ctxSettings( context );
}
// Remove duplicates
this.context = _unique( settings );
// Initial data
if ( data ) {
$.merge( this, data );
}
// selector
this.selector = {
rows: null,
cols: null,
opts: null
};
_Api.extend( this, this, __apiStruct );
};
DataTable.Api = _Api;
// Don't destroy the existing prototype, just extend it. Required for jQuery 2's
// isPlainObject.
$.extend( _Api.prototype, {
any: function ()
{
return this.count() !== 0;
},
concat: __arrayProto.concat,
context: [], // array of table settings objects
count: function ()
{
return this.flatten().length;
},
each: function ( fn )
{
for ( var i=0, ien=this.length ; i<ien; i++ ) {
fn.call( this, this[i], i, this );
}
return this;
},
eq: function ( idx )
{
var ctx = this.context;
return ctx.length > idx ?
new _Api( ctx[idx], this[idx] ) :
null;
},
filter: function ( fn )
{
var a = [];
if ( __arrayProto.filter ) {
a = __arrayProto.filter.call( this, fn, this );
}
else {
// Compatibility for browsers without EMCA-252-5 (JS 1.6)
for ( var i=0, ien=this.length ; i<ien ; i++ ) {
if ( fn.call( this, this[i], i, this ) ) {
a.push( this[i] );
}
}
}
return new _Api( this.context, a );
},
flatten: function ()
{
var a = [];
return new _Api( this.context, a.concat.apply( a, this.toArray() ) );
},
join: __arrayProto.join,
indexOf: __arrayProto.indexOf || function (obj, start)
{
for ( var i=(start || 0), ien=this.length ; i<ien ; i++ ) {
if ( this[i] === obj ) {
return i;
}
}
return -1;
},
iterator: function ( flatten, type, fn, alwaysNew ) {
var
a = [], ret,
i, ien, j, jen,
context = this.context,
rows, items, item,
selector = this.selector;
// Argument shifting
if ( typeof flatten === 'string' ) {
alwaysNew = fn;
fn = type;
type = flatten;
flatten = false;
}
for ( i=0, ien=context.length ; i<ien ; i++ ) {
var apiInst = new _Api( context[i] );
if ( type === 'table' ) {
ret = fn.call( apiInst, context[i], i );
if ( ret !== undefined ) {
a.push( ret );
}
}
else if ( type === 'columns' || type === 'rows' ) {
// this has same length as context - one entry for each table
ret = fn.call( apiInst, context[i], this[i], i );
if ( ret !== undefined ) {
a.push( ret );
}
}
else if ( type === 'column' || type === 'column-rows' || type === 'row' || type === 'cell' ) {
// columns and rows share the same structure.
// 'this' is an array of column indexes for each context
items = this[i];
if ( type === 'column-rows' ) {
rows = _selector_row_indexes( context[i], selector.opts );
}
for ( j=0, jen=items.length ; j<jen ; j++ ) {
item = items[j];
if ( type === 'cell' ) {
ret = fn.call( apiInst, context[i], item.row, item.column, i, j );
}
else {
ret = fn.call( apiInst, context[i], item, i, j, rows );
}
if ( ret !== undefined ) {
a.push( ret );
}
}
}
}
if ( a.length || alwaysNew ) {
var api = new _Api( context, flatten ? a.concat.apply( [], a ) : a );
var apiSelector = api.selector;
apiSelector.rows = selector.rows;
apiSelector.cols = selector.cols;
apiSelector.opts = selector.opts;
return api;
}
return this;
},
lastIndexOf: __arrayProto.lastIndexOf || function (obj, start)
{
// Bit cheeky...
return this.indexOf.apply( this.toArray.reverse(), arguments );
},
length: 0,
map: function ( fn )
{
var a = [];
if ( __arrayProto.map ) {
a = __arrayProto.map.call( this, fn, this );
}
else {
// Compatibility for browsers without EMCA-252-5 (JS 1.6)
for ( var i=0, ien=this.length ; i<ien ; i++ ) {
a.push( fn.call( this, this[i], i ) );
}
}
return new _Api( this.context, a );
},
pluck: function ( prop )
{
return this.map( function ( el ) {
return el[ prop ];
} );
},
pop: __arrayProto.pop,
push: __arrayProto.push,
// Does not return an API instance
reduce: __arrayProto.reduce || function ( fn, init )
{
return _fnReduce( this, fn, init, 0, this.length, 1 );
},
reduceRight: __arrayProto.reduceRight || function ( fn, init )
{
return _fnReduce( this, fn, init, this.length-1, -1, -1 );
},
reverse: __arrayProto.reverse,
// Object with rows, columns and opts
selector: null,
shift: __arrayProto.shift,
slice: function () {
return new _Api( this.context, this );
},
sort: __arrayProto.sort, // ? name - order?
splice: __arrayProto.splice,
toArray: function ()
{
return __arrayProto.slice.call( this );
},
to$: function ()
{
return $( this );
},
toJQuery: function ()
{
return $( this );
},
unique: function ()
{
return new _Api( this.context, _unique(this) );
},
unshift: __arrayProto.unshift
} );
_Api.extend = function ( scope, obj, ext )
{
// Only extend API instances and static properties of the API
if ( ! ext.length || ! obj || ( ! (obj instanceof _Api) && ! obj.__dt_wrapper ) ) {
return;
}
var
i, ien,
struct,
methodScoping = function ( scope, fn, struc ) {
return function () {
var ret = fn.apply( scope, arguments );
// Method extension
_Api.extend( ret, ret, struc.methodExt );
return ret;
};
};
for ( i=0, ien=ext.length ; i<ien ; i++ ) {
struct = ext[i];
// Value
obj[ struct.name ] = struct.type === 'function' ?
methodScoping( scope, struct.val, struct ) :
struct.type === 'object' ?
{} :
struct.val;
obj[ struct.name ].__dt_wrapper = true;
// Property extension
_Api.extend( scope, obj[ struct.name ], struct.propExt );
}
};
// @todo - Is there need for an augment function?
// _Api.augment = function ( inst, name )
// {
// // Find src object in the structure from the name
// var parts = name.split('.');
// _Api.extend( inst, obj );
// };
// [
// {
// name: 'data' -- string - Property name
// val: function () {}, -- function - Api method (or undefined if just an object
// methodExt: [ ... ], -- array - Array of Api object definitions to extend the method result
// propExt: [ ... ] -- array - Array of Api object definitions to extend the property
// },
// {
// name: 'row'
// val: {},
// methodExt: [ ... ],
// propExt: [
// {
// name: 'data'
// val: function () {},
// methodExt: [ ... ],
// propExt: [ ... ]
// },
// ...
// ]
// }
// ]
_Api.register = _api_register = function ( name, val )
{
if ( Array.isArray( name ) ) {
for ( var j=0, jen=name.length ; j<jen ; j++ ) {
_Api.register( name[j], val );
}
return;
}
var
i, ien,
heir = name.split('.'),
struct = __apiStruct,
key, method;
var find = function ( src, name ) {
for ( var i=0, ien=src.length ; i<ien ; i++ ) {
if ( src[i].name === name ) {
return src[i];
}
}
return null;
};
for ( i=0, ien=heir.length ; i<ien ; i++ ) {
method = heir[i].indexOf('()') !== -1;
key = method ?
heir[i].replace('()', '') :
heir[i];
var src = find( struct, key );
if ( ! src ) {
src = {
name: key,
val: {},
methodExt: [],
propExt: [],
type: 'object'
};
struct.push( src );
}
if ( i === ien-1 ) {
src.val = val;
src.type = typeof val === 'function' ?
'function' :
$.isPlainObject( val ) ?
'object' :
'other';
}
else {
struct = method ?
src.methodExt :
src.propExt;
}
}
};
_Api.registerPlural = _api_registerPlural = function ( pluralName, singularName, val ) {
_Api.register( pluralName, val );
_Api.register( singularName, function () {
var ret = val.apply( this, arguments );
if ( ret === this ) {
// Returned item is the API instance that was passed in, return it
return this;
}
else if ( ret instanceof _Api ) {
// New API instance returned, want the value from the first item
// in the returned array for the singular result.
return ret.length ?
Array.isArray( ret[0] ) ?
new _Api( ret.context, ret[0] ) : // Array results are 'enhanced'
ret[0] :
undefined;
}
// Non-API return - just fire it back
return ret;
} );
};
/**
* Selector for HTML tables. Apply the given selector to the give array of
* DataTables settings objects.
*
* @param {string|integer} [selector] jQuery selector string or integer
* @param {array} Array of DataTables settings objects to be filtered
* @return {array}
* @ignore
*/
var __table_selector = function ( selector, a )
{
if ( Array.isArray(selector) ) {
return $.map( selector, function (item) {
return __table_selector(item, a);
} );
}
// Integer is used to pick out a table by index
if ( typeof selector === 'number' ) {
return [ a[ selector ] ];
}
// Perform a jQuery selector on the table nodes
var nodes = $.map( a, function (el, i) {
return el.nTable;
} );
return $(nodes)
.filter( selector )
.map( function (i) {
// Need to translate back from the table node to the settings
var idx = $.inArray( this, nodes );
return a[ idx ];
} )
.toArray();
};
/**
* Context selector for the API's context (i.e. the tables the API instance
* refers to.
*
* @name DataTable.Api#tables
* @param {string|integer} [selector] Selector to pick which tables the iterator
* should operate on. If not given, all tables in the current context are
* used. This can be given as a jQuery selector (for example `':gt(0)'`) to
* select multiple tables or as an integer to select a single table.
* @returns {DataTable.Api} Returns a new API instance if a selector is given.
*/
_api_register( 'tables()', function ( selector ) {
// A new instance is created if there was a selector specified
return selector !== undefined && selector !== null ?
new _Api( __table_selector( selector, this.context ) ) :
this;
} );
_api_register( 'table()', function ( selector ) {
var tables = this.tables( selector );
var ctx = tables.context;
// Truncate to the first matched table
return ctx.length ?
new _Api( ctx[0] ) :
tables;
} );
_api_registerPlural( 'tables().nodes()', 'table().node()' , function () {
return this.iterator( 'table', function ( ctx ) {
return ctx.nTable;
}, 1 );
} );
_api_registerPlural( 'tables().body()', 'table().body()' , function () {
return this.iterator( 'table', function ( ctx ) {
return ctx.nTBody;
}, 1 );
} );
_api_registerPlural( 'tables().header()', 'table().header()' , function () {
return this.iterator( 'table', function ( ctx ) {
return ctx.nTHead;
}, 1 );
} );
_api_registerPlural( 'tables().footer()', 'table().footer()' , function () {
return this.iterator( 'table', function ( ctx ) {
return ctx.nTFoot;
}, 1 );
} );
_api_registerPlural( 'tables().containers()', 'table().container()' , function () {
return this.iterator( 'table', function ( ctx ) {
return ctx.nTableWrapper;
}, 1 );
} );
/**
* Redraw the tables in the current context.
*/
_api_register( 'draw()', function ( paging ) {
return this.iterator( 'table', function ( settings ) {
if ( paging === 'page' ) {
_fnDraw( settings );
}
else {
if ( typeof paging === 'string' ) {
paging = paging === 'full-hold' ?
false :
true;
}
_fnReDraw( settings, paging===false );
}
} );
} );
/**
* Get the current page index.
*
* @return {integer} Current page index (zero based)
*//**
* Set the current page.
*
* Note that if you attempt to show a page which does not exist, DataTables will
* not throw an error, but rather reset the paging.
*
* @param {integer|string} action The paging action to take. This can be one of:
* * `integer` - The page index to jump to
* * `string` - An action to take:
* * `first` - Jump to first page.
* * `next` - Jump to the next page
* * `previous` - Jump to previous page
* * `last` - Jump to the last page.
* @returns {DataTables.Api} this
*/
_api_register( 'page()', function ( action ) {
if ( action === undefined ) {
return this.page.info().page; // not an expensive call
}
// else, have an action to take on all tables
return this.iterator( 'table', function ( settings ) {
_fnPageChange( settings, action );
} );
} );
/**
* Paging information for the first table in the current context.
*
* If you require paging information for another table, use the `table()` method
* with a suitable selector.
*
* @return {object} Object with the following properties set:
* * `page` - Current page index (zero based - i.e. the first page is `0`)
* * `pages` - Total number of pages
* * `start` - Display index for the first record shown on the current page
* * `end` - Display index for the last record shown on the current page
* * `length` - Display length (number of records). Note that generally `start
* + length = end`, but this is not always true, for example if there are
* only 2 records to show on the final page, with a length of 10.
* * `recordsTotal` - Full data set length
* * `recordsDisplay` - Data set length once the current filtering criterion
* are applied.
*/
_api_register( 'page.info()', function ( action ) {
if ( this.context.length === 0 ) {
return undefined;
}
var
settings = this.context[0],
start = settings._iDisplayStart,
len = settings.oFeatures.bPaginate ? settings._iDisplayLength : -1,
visRecords = settings.fnRecordsDisplay(),
all = len === -1;
return {
"page": all ? 0 : Math.floor( start / len ),
"pages": all ? 1 : Math.ceil( visRecords / len ),
"start": start,
"end": settings.fnDisplayEnd(),
"length": len,
"recordsTotal": settings.fnRecordsTotal(),
"recordsDisplay": visRecords,
"serverSide": _fnDataSource( settings ) === 'ssp'
};
} );
/**
* Get the current page length.
*
* @return {integer} Current page length. Note `-1` indicates that all records
* are to be shown.
*//**
* Set the current page length.
*
* @param {integer} Page length to set. Use `-1` to show all records.
* @returns {DataTables.Api} this
*/
_api_register( 'page.len()', function ( len ) {
// Note that we can't call this function 'length()' because `length`
// is a Javascript property of functions which defines how many arguments
// the function expects.
if ( len === undefined ) {
return this.context.length !== 0 ?
this.context[0]._iDisplayLength :
undefined;
}
// else, set the page length
return this.iterator( 'table', function ( settings ) {
_fnLengthChange( settings, len );
} );
} );
var __reload = function ( settings, holdPosition, callback ) {
// Use the draw event to trigger a callback
if ( callback ) {
var api = new _Api( settings );
api.one( 'draw', function () {
callback( api.ajax.json() );
} );
}
if ( _fnDataSource( settings ) == 'ssp' ) {
_fnReDraw( settings, holdPosition );
}
else {
_fnProcessingDisplay( settings, true );
// Cancel an existing request
var xhr = settings.jqXHR;
if ( xhr && xhr.readyState !== 4 ) {
xhr.abort();
}
// Trigger xhr
_fnBuildAjax( settings, [], function( json ) {
_fnClearTable( settings );
var data = _fnAjaxDataSrc( settings, json );
for ( var i=0, ien=data.length ; i<ien ; i++ ) {
_fnAddData( settings, data[i] );
}
_fnReDraw( settings, holdPosition );
_fnProcessingDisplay( settings, false );
} );
}
};
/**
* Get the JSON response from the last Ajax request that DataTables made to the
* server. Note that this returns the JSON from the first table in the current
* context.
*
* @return {object} JSON received from the server.
*/
_api_register( 'ajax.json()', function () {
var ctx = this.context;
if ( ctx.length > 0 ) {
return ctx[0].json;
}
// else return undefined;
} );
/**
* Get the data submitted in the last Ajax request
*/
_api_register( 'ajax.params()', function () {
var ctx = this.context;
if ( ctx.length > 0 ) {
return ctx[0].oAjaxData;
}
// else return undefined;
} );
/**
* Reload tables from the Ajax data source. Note that this function will
* automatically re-draw the table when the remote data has been loaded.
*
* @param {boolean} [reset=true] Reset (default) or hold the current paging
* position. A full re-sort and re-filter is performed when this method is
* called, which is why the pagination reset is the default action.
* @returns {DataTables.Api} this
*/
_api_register( 'ajax.reload()', function ( callback, resetPaging ) {
return this.iterator( 'table', function (settings) {
__reload( settings, resetPaging===false, callback );
} );
} );
/**
* Get the current Ajax URL. Note that this returns the URL from the first
* table in the current context.
*
* @return {string} Current Ajax source URL
*//**
* Set the Ajax URL. Note that this will set the URL for all tables in the
* current context.
*
* @param {string} url URL to set.
* @returns {DataTables.Api} this
*/
_api_register( 'ajax.url()', function ( url ) {
var ctx = this.context;
if ( url === undefined ) {
// get
if ( ctx.length === 0 ) {
return undefined;
}
ctx = ctx[0];
return ctx.ajax ?
$.isPlainObject( ctx.ajax ) ?
ctx.ajax.url :
ctx.ajax :
ctx.sAjaxSource;
}
// set
return this.iterator( 'table', function ( settings ) {
if ( $.isPlainObject( settings.ajax ) ) {
settings.ajax.url = url;
}
else {
settings.ajax = url;
}
// No need to consider sAjaxSource here since DataTables gives priority
// to `ajax` over `sAjaxSource`. So setting `ajax` here, renders any
// value of `sAjaxSource` redundant.
} );
} );
/**
* Load data from the newly set Ajax URL. Note that this method is only
* available when `ajax.url()` is used to set a URL. Additionally, this method
* has the same effect as calling `ajax.reload()` but is provided for
* convenience when setting a new URL. Like `ajax.reload()` it will
* automatically redraw the table once the remote data has been loaded.
*
* @returns {DataTables.Api} this
*/
_api_register( 'ajax.url().load()', function ( callback, resetPaging ) {
// Same as a reload, but makes sense to present it for easy access after a
// url change
return this.iterator( 'table', function ( ctx ) {
__reload( ctx, resetPaging===false, callback );
} );
} );
var _selector_run = function ( type, selector, selectFn, settings, opts )
{
var
out = [], res,
a, i, ien, j, jen,
selectorType = typeof selector;
// Can't just check for isArray here, as an API or jQuery instance might be
// given with their array like look
if ( ! selector || selectorType === 'string' || selectorType === 'function' || selector.length === undefined ) {
selector = [ selector ];
}
for ( i=0, ien=selector.length ; i<ien ; i++ ) {
// Only split on simple strings - complex expressions will be jQuery selectors
a = selector[i] && selector[i].split && ! selector[i].match(/[\[\(:]/) ?
selector[i].split(',') :
[ selector[i] ];
for ( j=0, jen=a.length ; j<jen ; j++ ) {
res = selectFn( typeof a[j] === 'string' ? (a[j]).trim() : a[j] );
if ( res && res.length ) {
out = out.concat( res );
}
}
}
// selector extensions
var ext = _ext.selector[ type ];
if ( ext.length ) {
for ( i=0, ien=ext.length ; i<ien ; i++ ) {
out = ext[i]( settings, opts, out );
}
}
return _unique( out );
};
var _selector_opts = function ( opts )
{
if ( ! opts ) {
opts = {};
}
// Backwards compatibility for 1.9- which used the terminology filter rather
// than search
if ( opts.filter && opts.search === undefined ) {
opts.search = opts.filter;
}
return $.extend( {
search: 'none',
order: 'current',
page: 'all'
}, opts );
};
var _selector_first = function ( inst )
{
// Reduce the API instance to the first item found
for ( var i=0, ien=inst.length ; i<ien ; i++ ) {
if ( inst[i].length > 0 ) {
// Assign the first element to the first item in the instance
// and truncate the instance and context
inst[0] = inst[i];
inst[0].length = 1;
inst.length = 1;
inst.context = [ inst.context[i] ];
return inst;
}
}
// Not found - return an empty instance
inst.length = 0;
return inst;
};
var _selector_row_indexes = function ( settings, opts )
{
var
i, ien, tmp, a=[],
displayFiltered = settings.aiDisplay,
displayMaster = settings.aiDisplayMaster;
var
search = opts.search, // none, applied, removed
order = opts.order, // applied, current, index (original - compatibility with 1.9)
page = opts.page; // all, current
if ( _fnDataSource( settings ) == 'ssp' ) {
// In server-side processing mode, most options are irrelevant since
// rows not shown don't exist and the index order is the applied order
// Removed is a special case - for consistency just return an empty
// array
return search === 'removed' ?
[] :
_range( 0, displayMaster.length );
}
else if ( page == 'current' ) {
// Current page implies that order=current and fitler=applied, since it is
// fairly senseless otherwise, regardless of what order and search actually
// are
for ( i=settings._iDisplayStart, ien=settings.fnDisplayEnd() ; i<ien ; i++ ) {
a.push( displayFiltered[i] );
}
}
else if ( order == 'current' || order == 'applied' ) {
if ( search == 'none') {
a = displayMaster.slice();
}
else if ( search == 'applied' ) {
a = displayFiltered.slice();
}
else if ( search == 'removed' ) {
// O(n+m) solution by creating a hash map
var displayFilteredMap = {};
for ( var i=0, ien=displayFiltered.length ; i<ien ; i++ ) {
displayFilteredMap[displayFiltered[i]] = null;
}
a = $.map( displayMaster, function (el) {
return ! displayFilteredMap.hasOwnProperty(el) ?
el :
null;
} );
}
}
else if ( order == 'index' || order == 'original' ) {
for ( i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
if ( search == 'none' ) {
a.push( i );
}
else { // applied | removed
tmp = $.inArray( i, displayFiltered );
if ((tmp === -1 && search == 'removed') ||
(tmp >= 0 && search == 'applied') )
{
a.push( i );
}
}
}
}
return a;
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Rows
*
* {} - no selector - use all available rows
* {integer} - row aoData index
* {node} - TR node
* {string} - jQuery selector to apply to the TR elements
* {array} - jQuery array of nodes, or simply an array of TR nodes
*
*/
var __row_selector = function ( settings, selector, opts )
{
var rows;
var run = function ( sel ) {
var selInt = _intVal( sel );
var i, ien;
var aoData = settings.aoData;
// Short cut - selector is a number and no options provided (default is
// all records, so no need to check if the index is in there, since it
// must be - dev error if the index doesn't exist).
if ( selInt !== null && ! opts ) {
return [ selInt ];
}
if ( ! rows ) {
rows = _selector_row_indexes( settings, opts );
}
if ( selInt !== null && $.inArray( selInt, rows ) !== -1 ) {
// Selector - integer
return [ selInt ];
}
else if ( sel === null || sel === undefined || sel === '' ) {
// Selector - none
return rows;
}
// Selector - function
if ( typeof sel === 'function' ) {
return $.map( rows, function (idx) {
var row = aoData[ idx ];
return sel( idx, row._aData, row.nTr ) ? idx : null;
} );
}
// Selector - node
if ( sel.nodeName ) {
var rowIdx = sel._DT_RowIndex; // Property added by DT for fast lookup
var cellIdx = sel._DT_CellIndex;
if ( rowIdx !== undefined ) {
// Make sure that the row is actually still present in the table
return aoData[ rowIdx ] && aoData[ rowIdx ].nTr === sel ?
[ rowIdx ] :
[];
}
else if ( cellIdx ) {
return aoData[ cellIdx.row ] && aoData[ cellIdx.row ].nTr === sel.parentNode ?
[ cellIdx.row ] :
[];
}
else {
var host = $(sel).closest('*[data-dt-row]');
return host.length ?
[ host.data('dt-row') ] :
[];
}
}
// ID selector. Want to always be able to select rows by id, regardless
// of if the tr element has been created or not, so can't rely upon
// jQuery here - hence a custom implementation. This does not match
// Sizzle's fast selector or HTML4 - in HTML5 the ID can be anything,
// but to select it using a CSS selector engine (like Sizzle or
// querySelect) it would need to need to be escaped for some characters.
// DataTables simplifies this for row selectors since you can select
// only a row. A # indicates an id any anything that follows is the id -
// unescaped.
if ( typeof sel === 'string' && sel.charAt(0) === '#' ) {
// get row index from id
var rowObj = settings.aIds[ sel.replace( /^#/, '' ) ];
if ( rowObj !== undefined ) {
return [ rowObj.idx ];
}
// need to fall through to jQuery in case there is DOM id that
// matches
}
// Get nodes in the order from the `rows` array with null values removed
var nodes = _removeEmpty(
_pluck_order( settings.aoData, rows, 'nTr' )
);
// Selector - jQuery selector string, array of nodes or jQuery object/
// As jQuery's .filter() allows jQuery objects to be passed in filter,
// it also allows arrays, so this will cope with all three options
return $(nodes)
.filter( sel )
.map( function () {
return this._DT_RowIndex;
} )
.toArray();
};
return _selector_run( 'row', selector, run, settings, opts );
};
_api_register( 'rows()', function ( selector, opts ) {
// argument shifting
if ( selector === undefined ) {
selector = '';
}
else if ( $.isPlainObject( selector ) ) {
opts = selector;
selector = '';
}
opts = _selector_opts( opts );
var inst = this.iterator( 'table', function ( settings ) {
return __row_selector( settings, selector, opts );
}, 1 );
// Want argument shifting here and in __row_selector?
inst.selector.rows = selector;
inst.selector.opts = opts;
return inst;
} );
_api_register( 'rows().nodes()', function () {
return this.iterator( 'row', function ( settings, row ) {
return settings.aoData[ row ].nTr || undefined;
}, 1 );
} );
_api_register( 'rows().data()', function () {
return this.iterator( true, 'rows', function ( settings, rows ) {
return _pluck_order( settings.aoData, rows, '_aData' );
}, 1 );
} );
_api_registerPlural( 'rows().cache()', 'row().cache()', function ( type ) {
return this.iterator( 'row', function ( settings, row ) {
var r = settings.aoData[ row ];
return type === 'search' ? r._aFilterData : r._aSortData;
}, 1 );
} );
_api_registerPlural( 'rows().invalidate()', 'row().invalidate()', function ( src ) {
return this.iterator( 'row', function ( settings, row ) {
_fnInvalidate( settings, row, src );
} );
} );
_api_registerPlural( 'rows().indexes()', 'row().index()', function () {
return this.iterator( 'row', function ( settings, row ) {
return row;
}, 1 );
} );
_api_registerPlural( 'rows().ids()', 'row().id()', function ( hash ) {
var a = [];
var context = this.context;
// `iterator` will drop undefined values, but in this case we want them
for ( var i=0, ien=context.length ; i<ien ; i++ ) {
for ( var j=0, jen=this[i].length ; j<jen ; j++ ) {
var id = context[i].rowIdFn( context[i].aoData[ this[i][j] ]._aData );
a.push( (hash === true ? '#' : '' )+ id );
}
}
return new _Api( context, a );
} );
_api_registerPlural( 'rows().remove()', 'row().remove()', function () {
var that = this;
this.iterator( 'row', function ( settings, row, thatIdx ) {
var data = settings.aoData;
var rowData = data[ row ];
var i, ien, j, jen;
var loopRow, loopCells;
data.splice( row, 1 );
// Update the cached indexes
for ( i=0, ien=data.length ; i<ien ; i++ ) {
loopRow = data[i];
loopCells = loopRow.anCells;
// Rows
if ( loopRow.nTr !== null ) {
loopRow.nTr._DT_RowIndex = i;
}
// Cells
if ( loopCells !== null ) {
for ( j=0, jen=loopCells.length ; j<jen ; j++ ) {
loopCells[j]._DT_CellIndex.row = i;
}
}
}
// Delete from the display arrays
_fnDeleteIndex( settings.aiDisplayMaster, row );
_fnDeleteIndex( settings.aiDisplay, row );
_fnDeleteIndex( that[ thatIdx ], row, false ); // maintain local indexes
// For server-side processing tables - subtract the deleted row from the count
if ( settings._iRecordsDisplay > 0 ) {
settings._iRecordsDisplay--;
}
// Check for an 'overflow' they case for displaying the table
_fnLengthOverflow( settings );
// Remove the row's ID reference if there is one
var id = settings.rowIdFn( rowData._aData );
if ( id !== undefined ) {
delete settings.aIds[ id ];
}
} );
this.iterator( 'table', function ( settings ) {
for ( var i=0, ien=settings.aoData.length ; i<ien ; i++ ) {
settings.aoData[i].idx = i;
}
} );
return this;
} );
_api_register( 'rows.add()', function ( rows ) {
var newRows = this.iterator( 'table', function ( settings ) {
var row, i, ien;
var out = [];
for ( i=0, ien=rows.length ; i<ien ; i++ ) {
row = rows[i];
if ( row.nodeName && row.nodeName.toUpperCase() === 'TR' ) {
out.push( _fnAddTr( settings, row )[0] );
}
else {
out.push( _fnAddData( settings, row ) );
}
}
return out;
}, 1 );
// Return an Api.rows() extended instance, so rows().nodes() etc can be used
var modRows = this.rows( -1 );
modRows.pop();
$.merge( modRows, newRows );
return modRows;
} );
/**
*
*/
_api_register( 'row()', function ( selector, opts ) {
return _selector_first( this.rows( selector, opts ) );
} );
_api_register( 'row().data()', function ( data ) {
var ctx = this.context;
if ( data === undefined ) {
// Get
return ctx.length && this.length ?
ctx[0].aoData[ this[0] ]._aData :
undefined;
}
// Set
var row = ctx[0].aoData[ this[0] ];
row._aData = data;
// If the DOM has an id, and the data source is an array
if ( Array.isArray( data ) && row.nTr && row.nTr.id ) {
_fnSetObjectDataFn( ctx[0].rowId )( data, row.nTr.id );
}
// Automatically invalidate
_fnInvalidate( ctx[0], this[0], 'data' );
return this;
} );
_api_register( 'row().node()', function () {
var ctx = this.context;
return ctx.length && this.length ?
ctx[0].aoData[ this[0] ].nTr || null :
null;
} );
_api_register( 'row.add()', function ( row ) {
// Allow a jQuery object to be passed in - only a single row is added from
// it though - the first element in the set
if ( row instanceof $ && row.length ) {
row = row[0];
}
var rows = this.iterator( 'table', function ( settings ) {
if ( row.nodeName && row.nodeName.toUpperCase() === 'TR' ) {
return _fnAddTr( settings, row )[0];
}
return _fnAddData( settings, row );
} );
// Return an Api.rows() extended instance, with the newly added row selected
return this.row( rows[0] );
} );
var __details_add = function ( ctx, row, data, klass )
{
// Convert to array of TR elements
var rows = [];
var addRow = function ( r, k ) {
// Recursion to allow for arrays of jQuery objects
if ( Array.isArray( r ) || r instanceof $ ) {
for ( var i=0, ien=r.length ; i<ien ; i++ ) {
addRow( r[i], k );
}
return;
}
// If we get a TR element, then just add it directly - up to the dev
// to add the correct number of columns etc
if ( r.nodeName && r.nodeName.toLowerCase() === 'tr' ) {
rows.push( r );
}
else {
// Otherwise create a row with a wrapper
var created = $('<tr><td></td></tr>').addClass( k );
$('td', created)
.addClass( k )
.html( r )
[0].colSpan = _fnVisbleColumns( ctx );
rows.push( created[0] );
}
};
addRow( data, klass );
if ( row._details ) {
row._details.detach();
}
row._details = $(rows);
// If the children were already shown, that state should be retained
if ( row._detailsShow ) {
row._details.insertAfter( row.nTr );
}
};
var __details_remove = function ( api, idx )
{
var ctx = api.context;
if ( ctx.length ) {
var row = ctx[0].aoData[ idx !== undefined ? idx : api[0] ];
if ( row && row._details ) {
row._details.remove();
row._detailsShow = undefined;
row._details = undefined;
}
}
};
var __details_display = function ( api, show ) {
var ctx = api.context;
if ( ctx.length && api.length ) {
var row = ctx[0].aoData[ api[0] ];
if ( row._details ) {
row._detailsShow = show;
if ( show ) {
row._details.insertAfter( row.nTr );
}
else {
row._details.detach();
}
__details_events( ctx[0] );
}
}
};
var __details_events = function ( settings )
{
var api = new _Api( settings );
var namespace = '.dt.DT_details';
var drawEvent = 'draw'+namespace;
var colvisEvent = 'column-visibility'+namespace;
var destroyEvent = 'destroy'+namespace;
var data = settings.aoData;
api.off( drawEvent +' '+ colvisEvent +' '+ destroyEvent );
if ( _pluck( data, '_details' ).length > 0 ) {
// On each draw, insert the required elements into the document
api.on( drawEvent, function ( e, ctx ) {
if ( settings !== ctx ) {
return;
}
api.rows( {page:'current'} ).eq(0).each( function (idx) {
// Internal data grab
var row = data[ idx ];
if ( row._detailsShow ) {
row._details.insertAfter( row.nTr );
}
} );
} );
// Column visibility change - update the colspan
api.on( colvisEvent, function ( e, ctx, idx, vis ) {
if ( settings !== ctx ) {
return;
}
// Update the colspan for the details rows (note, only if it already has
// a colspan)
var row, visible = _fnVisbleColumns( ctx );
for ( var i=0, ien=data.length ; i<ien ; i++ ) {
row = data[i];
if ( row._details ) {
row._details.children('td[colspan]').attr('colspan', visible );
}
}
} );
// Table destroyed - nuke any child rows
api.on( destroyEvent, function ( e, ctx ) {
if ( settings !== ctx ) {
return;
}
for ( var i=0, ien=data.length ; i<ien ; i++ ) {
if ( data[i]._details ) {
__details_remove( api, i );
}
}
} );
}
};
// Strings for the method names to help minification
var _emp = '';
var _child_obj = _emp+'row().child';
var _child_mth = _child_obj+'()';
// data can be:
// tr
// string
// jQuery or array of any of the above
_api_register( _child_mth, function ( data, klass ) {
var ctx = this.context;
if ( data === undefined ) {
// get
return ctx.length && this.length ?
ctx[0].aoData[ this[0] ]._details :
undefined;
}
else if ( data === true ) {
// show
this.child.show();
}
else if ( data === false ) {
// remove
__details_remove( this );
}
else if ( ctx.length && this.length ) {
// set
__details_add( ctx[0], ctx[0].aoData[ this[0] ], data, klass );
}
return this;
} );
_api_register( [
_child_obj+'.show()',
_child_mth+'.show()' // only when `child()` was called with parameters (without
], function ( show ) { // it returns an object and this method is not executed)
__details_display( this, true );
return this;
} );
_api_register( [
_child_obj+'.hide()',
_child_mth+'.hide()' // only when `child()` was called with parameters (without
], function () { // it returns an object and this method is not executed)
__details_display( this, false );
return this;
} );
_api_register( [
_child_obj+'.remove()',
_child_mth+'.remove()' // only when `child()` was called with parameters (without
], function () { // it returns an object and this method is not executed)
__details_remove( this );
return this;
} );
_api_register( _child_obj+'.isShown()', function () {
var ctx = this.context;
if ( ctx.length && this.length ) {
// _detailsShown as false or undefined will fall through to return false
return ctx[0].aoData[ this[0] ]._detailsShow || false;
}
return false;
} );
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Columns
*
* {integer} - column index (>=0 count from left, <0 count from right)
* "{integer}:visIdx" - visible column index (i.e. translate to column index) (>=0 count from left, <0 count from right)
* "{integer}:visible" - alias for {integer}:visIdx (>=0 count from left, <0 count from right)
* "{string}:name" - column name
* "{string}" - jQuery selector on column header nodes
*
*/
// can be an array of these items, comma separated list, or an array of comma
// separated lists
var __re_column_selector = /^([^:]+):(name|visIdx|visible)$/;
// r1 and r2 are redundant - but it means that the parameters match for the
// iterator callback in columns().data()
var __columnData = function ( settings, column, r1, r2, rows ) {
var a = [];
for ( var row=0, ien=rows.length ; row<ien ; row++ ) {
a.push( _fnGetCellData( settings, rows[row], column ) );
}
return a;
};
var __column_selector = function ( settings, selector, opts )
{
var
columns = settings.aoColumns,
names = _pluck( columns, 'sName' ),
nodes = _pluck( columns, 'nTh' );
var run = function ( s ) {
var selInt = _intVal( s );
// Selector - all
if ( s === '' ) {
return _range( columns.length );
}
// Selector - index
if ( selInt !== null ) {
return [ selInt >= 0 ?
selInt : // Count from left
columns.length + selInt // Count from right (+ because its a negative value)
];
}
// Selector = function
if ( typeof s === 'function' ) {
var rows = _selector_row_indexes( settings, opts );
return $.map( columns, function (col, idx) {
return s(
idx,
__columnData( settings, idx, 0, 0, rows ),
nodes[ idx ]
) ? idx : null;
} );
}
// jQuery or string selector
var match = typeof s === 'string' ?
s.match( __re_column_selector ) :
'';
if ( match ) {
switch( match[2] ) {
case 'visIdx':
case 'visible':
var idx = parseInt( match[1], 10 );
// Visible index given, convert to column index
if ( idx < 0 ) {
// Counting from the right
var visColumns = $.map( columns, function (col,i) {
return col.bVisible ? i : null;
} );
return [ visColumns[ visColumns.length + idx ] ];
}
// Counting from the left
return [ _fnVisibleToColumnIndex( settings, idx ) ];
case 'name':
// match by name. `names` is column index complete and in order
return $.map( names, function (name, i) {
return name === match[1] ? i : null;
} );
default:
return [];
}
}
// Cell in the table body
if ( s.nodeName && s._DT_CellIndex ) {
return [ s._DT_CellIndex.column ];
}
// jQuery selector on the TH elements for the columns
var jqResult = $( nodes )
.filter( s )
.map( function () {
return $.inArray( this, nodes ); // `nodes` is column index complete and in order
} )
.toArray();
if ( jqResult.length || ! s.nodeName ) {
return jqResult;
}
// Otherwise a node which might have a `dt-column` data attribute, or be
// a child or such an element
var host = $(s).closest('*[data-dt-column]');
return host.length ?
[ host.data('dt-column') ] :
[];
};
return _selector_run( 'column', selector, run, settings, opts );
};
var __setColumnVis = function ( settings, column, vis ) {
var
cols = settings.aoColumns,
col = cols[ column ],
data = settings.aoData,
row, cells, i, ien, tr;
// Get
if ( vis === undefined ) {
return col.bVisible;
}
// Set
// No change
if ( col.bVisible === vis ) {
return;
}
if ( vis ) {
// Insert column
// Need to decide if we should use appendChild or insertBefore
var insertBefore = $.inArray( true, _pluck(cols, 'bVisible'), column+1 );
for ( i=0, ien=data.length ; i<ien ; i++ ) {
tr = data[i].nTr;
cells = data[i].anCells;
if ( tr ) {
// insertBefore can act like appendChild if 2nd arg is null
tr.insertBefore( cells[ column ], cells[ insertBefore ] || null );
}
}
}
else {
// Remove column
$( _pluck( settings.aoData, 'anCells', column ) ).detach();
}
// Common actions
col.bVisible = vis;
};
_api_register( 'columns()', function ( selector, opts ) {
// argument shifting
if ( selector === undefined ) {
selector = '';
}
else if ( $.isPlainObject( selector ) ) {
opts = selector;
selector = '';
}
opts = _selector_opts( opts );
var inst = this.iterator( 'table', function ( settings ) {
return __column_selector( settings, selector, opts );
}, 1 );
// Want argument shifting here and in _row_selector?
inst.selector.cols = selector;
inst.selector.opts = opts;
return inst;
} );
_api_registerPlural( 'columns().header()', 'column().header()', function ( selector, opts ) {
return this.iterator( 'column', function ( settings, column ) {
return settings.aoColumns[column].nTh;
}, 1 );
} );
_api_registerPlural( 'columns().footer()', 'column().footer()', function ( selector, opts ) {
return this.iterator( 'column', function ( settings, column ) {
return settings.aoColumns[column].nTf;
}, 1 );
} );
_api_registerPlural( 'columns().data()', 'column().data()', function () {
return this.iterator( 'column-rows', __columnData, 1 );
} );
_api_registerPlural( 'columns().dataSrc()', 'column().dataSrc()', function () {
return this.iterator( 'column', function ( settings, column ) {
return settings.aoColumns[column].mData;
}, 1 );
} );
_api_registerPlural( 'columns().cache()', 'column().cache()', function ( type ) {
return this.iterator( 'column-rows', function ( settings, column, i, j, rows ) {
return _pluck_order( settings.aoData, rows,
type === 'search' ? '_aFilterData' : '_aSortData', column
);
}, 1 );
} );
_api_registerPlural( 'columns().nodes()', 'column().nodes()', function () {
return this.iterator( 'column-rows', function ( settings, column, i, j, rows ) {
return _pluck_order( settings.aoData, rows, 'anCells', column ) ;
}, 1 );
} );
_api_registerPlural( 'columns().visible()', 'column().visible()', function ( vis, calc ) {
var that = this;
var ret = this.iterator( 'column', function ( settings, column ) {
if ( vis === undefined ) {
return settings.aoColumns[ column ].bVisible;
} // else
__setColumnVis( settings, column, vis );
} );
// Group the column visibility changes
if ( vis !== undefined ) {
this.iterator( 'table', function ( settings ) {
// Redraw the header after changes
_fnDrawHead( settings, settings.aoHeader );
_fnDrawHead( settings, settings.aoFooter );
// Update colspan for no records display. Child rows and extensions will use their own
// listeners to do this - only need to update the empty table item here
if ( ! settings.aiDisplay.length ) {
$(settings.nTBody).find('td[colspan]').attr('colspan', _fnVisbleColumns(settings));
}
_fnSaveState( settings );
// Second loop once the first is done for events
that.iterator( 'column', function ( settings, column ) {
_fnCallbackFire( settings, null, 'column-visibility', [settings, column, vis, calc] );
} );
if ( calc === undefined || calc ) {
that.columns.adjust();
}
});
}
return ret;
} );
_api_registerPlural( 'columns().indexes()', 'column().index()', function ( type ) {
return this.iterator( 'column', function ( settings, column ) {
return type === 'visible' ?
_fnColumnIndexToVisible( settings, column ) :
column;
}, 1 );
} );
_api_register( 'columns.adjust()', function () {
return this.iterator( 'table', function ( settings ) {
_fnAdjustColumnSizing( settings );
}, 1 );
} );
_api_register( 'column.index()', function ( type, idx ) {
if ( this.context.length !== 0 ) {
var ctx = this.context[0];
if ( type === 'fromVisible' || type === 'toData' ) {
return _fnVisibleToColumnIndex( ctx, idx );
}
else if ( type === 'fromData' || type === 'toVisible' ) {
return _fnColumnIndexToVisible( ctx, idx );
}
}
} );
_api_register( 'column()', function ( selector, opts ) {
return _selector_first( this.columns( selector, opts ) );
} );
var __cell_selector = function ( settings, selector, opts )
{
var data = settings.aoData;
var rows = _selector_row_indexes( settings, opts );
var cells = _removeEmpty( _pluck_order( data, rows, 'anCells' ) );
var allCells = $(_flatten( [], cells ));
var row;
var columns = settings.aoColumns.length;
var a, i, ien, j, o, host;
var run = function ( s ) {
var fnSelector = typeof s === 'function';
if ( s === null || s === undefined || fnSelector ) {
// All cells and function selectors
a = [];
for ( i=0, ien=rows.length ; i<ien ; i++ ) {
row = rows[i];
for ( j=0 ; j<columns ; j++ ) {
o = {
row: row,
column: j
};
if ( fnSelector ) {
// Selector - function
host = data[ row ];
if ( s( o, _fnGetCellData(settings, row, j), host.anCells ? host.anCells[j] : null ) ) {
a.push( o );
}
}
else {
// Selector - all
a.push( o );
}
}
}
return a;
}
// Selector - index
if ( $.isPlainObject( s ) ) {
// Valid cell index and its in the array of selectable rows
return s.column !== undefined && s.row !== undefined && $.inArray( s.row, rows ) !== -1 ?
[s] :
[];
}
// Selector - jQuery filtered cells
var jqResult = allCells
.filter( s )
.map( function (i, el) {
return { // use a new object, in case someone changes the values
row: el._DT_CellIndex.row,
column: el._DT_CellIndex.column
};
} )
.toArray();
if ( jqResult.length || ! s.nodeName ) {
return jqResult;
}
// Otherwise the selector is a node, and there is one last option - the
// element might be a child of an element which has dt-row and dt-column
// data attributes
host = $(s).closest('*[data-dt-row]');
return host.length ?
[ {
row: host.data('dt-row'),
column: host.data('dt-column')
} ] :
[];
};
return _selector_run( 'cell', selector, run, settings, opts );
};
_api_register( 'cells()', function ( rowSelector, columnSelector, opts ) {
// Argument shifting
if ( $.isPlainObject( rowSelector ) ) {
// Indexes
if ( rowSelector.row === undefined ) {
// Selector options in first parameter
opts = rowSelector;
rowSelector = null;
}
else {
// Cell index objects in first parameter
opts = columnSelector;
columnSelector = null;
}
}
if ( $.isPlainObject( columnSelector ) ) {
opts = columnSelector;
columnSelector = null;
}
// Cell selector
if ( columnSelector === null || columnSelector === undefined ) {
return this.iterator( 'table', function ( settings ) {
return __cell_selector( settings, rowSelector, _selector_opts( opts ) );
} );
}
// The default built in options need to apply to row and columns
var internalOpts = opts ? {
page: opts.page,
order: opts.order,
search: opts.search
} : {};
// Row + column selector
var columns = this.columns( columnSelector, internalOpts );
var rows = this.rows( rowSelector, internalOpts );
var i, ien, j, jen;
var cellsNoOpts = this.iterator( 'table', function ( settings, idx ) {
var a = [];
for ( i=0, ien=rows[idx].length ; i<ien ; i++ ) {
for ( j=0, jen=columns[idx].length ; j<jen ; j++ ) {
a.push( {
row: rows[idx][i],
column: columns[idx][j]
} );
}
}
return a;
}, 1 );
// There is currently only one extension which uses a cell selector extension
// It is a _major_ performance drag to run this if it isn't needed, so this is
// an extension specific check at the moment
var cells = opts && opts.selected ?
this.cells( cellsNoOpts, opts ) :
cellsNoOpts;
$.extend( cells.selector, {
cols: columnSelector,
rows: rowSelector,
opts: opts
} );
return cells;
} );
_api_registerPlural( 'cells().nodes()', 'cell().node()', function () {
return this.iterator( 'cell', function ( settings, row, column ) {
var data = settings.aoData[ row ];
return data && data.anCells ?
data.anCells[ column ] :
undefined;
}, 1 );
} );
_api_register( 'cells().data()', function () {
return this.iterator( 'cell', function ( settings, row, column ) {
return _fnGetCellData( settings, row, column );
}, 1 );
} );
_api_registerPlural( 'cells().cache()', 'cell().cache()', function ( type ) {
type = type === 'search' ? '_aFilterData' : '_aSortData';
return this.iterator( 'cell', function ( settings, row, column ) {
return settings.aoData[ row ][ type ][ column ];
}, 1 );
} );
_api_registerPlural( 'cells().render()', 'cell().render()', function ( type ) {
return this.iterator( 'cell', function ( settings, row, column ) {
return _fnGetCellData( settings, row, column, type );
}, 1 );
} );
_api_registerPlural( 'cells().indexes()', 'cell().index()', function () {
return this.iterator( 'cell', function ( settings, row, column ) {
return {
row: row,
column: column,
columnVisible: _fnColumnIndexToVisible( settings, column )
};
}, 1 );
} );
_api_registerPlural( 'cells().invalidate()', 'cell().invalidate()', function ( src ) {
return this.iterator( 'cell', function ( settings, row, column ) {
_fnInvalidate( settings, row, src, column );
} );
} );
_api_register( 'cell()', function ( rowSelector, columnSelector, opts ) {
return _selector_first( this.cells( rowSelector, columnSelector, opts ) );
} );
_api_register( 'cell().data()', function ( data ) {
var ctx = this.context;
var cell = this[0];
if ( data === undefined ) {
// Get
return ctx.length && cell.length ?
_fnGetCellData( ctx[0], cell[0].row, cell[0].column ) :
undefined;
}
// Set
_fnSetCellData( ctx[0], cell[0].row, cell[0].column, data );
_fnInvalidate( ctx[0], cell[0].row, 'data', cell[0].column );
return this;
} );
/**
* Get current ordering (sorting) that has been applied to the table.
*
* @returns {array} 2D array containing the sorting information for the first
* table in the current context. Each element in the parent array represents
* a column being sorted upon (i.e. multi-sorting with two columns would have
* 2 inner arrays). The inner arrays may have 2 or 3 elements. The first is
* the column index that the sorting condition applies to, the second is the
* direction of the sort (`desc` or `asc`) and, optionally, the third is the
* index of the sorting order from the `column.sorting` initialisation array.
*//**
* Set the ordering for the table.
*
* @param {integer} order Column index to sort upon.
* @param {string} direction Direction of the sort to be applied (`asc` or `desc`)
* @returns {DataTables.Api} this
*//**
* Set the ordering for the table.
*
* @param {array} order 1D array of sorting information to be applied.
* @param {array} [...] Optional additional sorting conditions
* @returns {DataTables.Api} this
*//**
* Set the ordering for the table.
*
* @param {array} order 2D array of sorting information to be applied.
* @returns {DataTables.Api} this
*/
_api_register( 'order()', function ( order, dir ) {
var ctx = this.context;
if ( order === undefined ) {
// get
return ctx.length !== 0 ?
ctx[0].aaSorting :
undefined;
}
// set
if ( typeof order === 'number' ) {
// Simple column / direction passed in
order = [ [ order, dir ] ];
}
else if ( order.length && ! Array.isArray( order[0] ) ) {
// Arguments passed in (list of 1D arrays)
order = Array.prototype.slice.call( arguments );
}
// otherwise a 2D array was passed in
return this.iterator( 'table', function ( settings ) {
settings.aaSorting = order.slice();
} );
} );
/**
* Attach a sort listener to an element for a given column
*
* @param {node|jQuery|string} node Identifier for the element(s) to attach the
* listener to. This can take the form of a single DOM node, a jQuery
* collection of nodes or a jQuery selector which will identify the node(s).
* @param {integer} column the column that a click on this node will sort on
* @param {function} [callback] callback function when sort is run
* @returns {DataTables.Api} this
*/
_api_register( 'order.listener()', function ( node, column, callback ) {
return this.iterator( 'table', function ( settings ) {
_fnSortAttachListener( settings, node, column, callback );
} );
} );
_api_register( 'order.fixed()', function ( set ) {
if ( ! set ) {
var ctx = this.context;
var fixed = ctx.length ?
ctx[0].aaSortingFixed :
undefined;
return Array.isArray( fixed ) ?
{ pre: fixed } :
fixed;
}
return this.iterator( 'table', function ( settings ) {
settings.aaSortingFixed = $.extend( true, {}, set );
} );
} );
// Order by the selected column(s)
_api_register( [
'columns().order()',
'column().order()'
], function ( dir ) {
var that = this;
return this.iterator( 'table', function ( settings, i ) {
var sort = [];
$.each( that[i], function (j, col) {
sort.push( [ col, dir ] );
} );
settings.aaSorting = sort;
} );
} );
_api_register( 'search()', function ( input, regex, smart, caseInsen ) {
var ctx = this.context;
if ( input === undefined ) {
// get
return ctx.length !== 0 ?
ctx[0].oPreviousSearch.sSearch :
undefined;
}
// set
return this.iterator( 'table', function ( settings ) {
if ( ! settings.oFeatures.bFilter ) {
return;
}
_fnFilterComplete( settings, $.extend( {}, settings.oPreviousSearch, {
"sSearch": input+"",
"bRegex": regex === null ? false : regex,
"bSmart": smart === null ? true : smart,
"bCaseInsensitive": caseInsen === null ? true : caseInsen
} ), 1 );
} );
} );
_api_registerPlural(
'columns().search()',
'column().search()',
function ( input, regex, smart, caseInsen ) {
return this.iterator( 'column', function ( settings, column ) {
var preSearch = settings.aoPreSearchCols;
if ( input === undefined ) {
// get
return preSearch[ column ].sSearch;
}
// set
if ( ! settings.oFeatures.bFilter ) {
return;
}
$.extend( preSearch[ column ], {
"sSearch": input+"",
"bRegex": regex === null ? false : regex,
"bSmart": smart === null ? true : smart,
"bCaseInsensitive": caseInsen === null ? true : caseInsen
} );
_fnFilterComplete( settings, settings.oPreviousSearch, 1 );
} );
}
);
/*
* State API methods
*/
_api_register( 'state()', function () {
return this.context.length ?
this.context[0].oSavedState :
null;
} );
_api_register( 'state.clear()', function () {
return this.iterator( 'table', function ( settings ) {
// Save an empty object
settings.fnStateSaveCallback.call( settings.oInstance, settings, {} );
} );
} );
_api_register( 'state.loaded()', function () {
return this.context.length ?
this.context[0].oLoadedState :
null;
} );
_api_register( 'state.save()', function () {
return this.iterator( 'table', function ( settings ) {
_fnSaveState( settings );
} );
} );
/**
* Provide a common method for plug-ins to check the version of DataTables being
* used, in order to ensure compatibility.
*
* @param {string} version Version string to check for, in the format "X.Y.Z".
* Note that the formats "X" and "X.Y" are also acceptable.
* @returns {boolean} true if this version of DataTables is greater or equal to
* the required version, or false if this version of DataTales is not
* suitable
* @static
* @dtopt API-Static
*
* @example
* alert( $.fn.dataTable.versionCheck( '1.9.0' ) );
*/
DataTable.versionCheck = DataTable.fnVersionCheck = function( version )
{
var aThis = DataTable.version.split('.');
var aThat = version.split('.');
var iThis, iThat;
for ( var i=0, iLen=aThat.length ; i<iLen ; i++ ) {
iThis = parseInt( aThis[i], 10 ) || 0;
iThat = parseInt( aThat[i], 10 ) || 0;
// Parts are the same, keep comparing
if (iThis === iThat) {
continue;
}
// Parts are different, return immediately
return iThis > iThat;
}
return true;
};
/**
* Check if a `<table>` node is a DataTable table already or not.
*
* @param {node|jquery|string} table Table node, jQuery object or jQuery
* selector for the table to test. Note that if more than more than one
* table is passed on, only the first will be checked
* @returns {boolean} true the table given is a DataTable, or false otherwise
* @static
* @dtopt API-Static
*
* @example
* if ( ! $.fn.DataTable.isDataTable( '#example' ) ) {
* $('#example').dataTable();
* }
*/
DataTable.isDataTable = DataTable.fnIsDataTable = function ( table )
{
var t = $(table).get(0);
var is = false;
if ( table instanceof DataTable.Api ) {
return true;
}
$.each( DataTable.settings, function (i, o) {
var head = o.nScrollHead ? $('table', o.nScrollHead)[0] : null;
var foot = o.nScrollFoot ? $('table', o.nScrollFoot)[0] : null;
if ( o.nTable === t || head === t || foot === t ) {
is = true;
}
} );
return is;
};
/**
* Get all DataTable tables that have been initialised - optionally you can
* select to get only currently visible tables.
*
* @param {boolean} [visible=false] Flag to indicate if you want all (default)
* or visible tables only.
* @returns {array} Array of `table` nodes (not DataTable instances) which are
* DataTables
* @static
* @dtopt API-Static
*
* @example
* $.each( $.fn.dataTable.tables(true), function () {
* $(table).DataTable().columns.adjust();
* } );
*/
DataTable.tables = DataTable.fnTables = function ( visible )
{
var api = false;
if ( $.isPlainObject( visible ) ) {
api = visible.api;
visible = visible.visible;
}
var a = $.map( DataTable.settings, function (o) {
if ( !visible || (visible && $(o.nTable).is(':visible')) ) {
return o.nTable;
}
} );
return api ?
new _Api( a ) :
a;
};
/**
* Convert from camel case parameters to Hungarian notation. This is made public
* for the extensions to provide the same ability as DataTables core to accept
* either the 1.9 style Hungarian notation, or the 1.10+ style camelCase
* parameters.
*
* @param {object} src The model object which holds all parameters that can be
* mapped.
* @param {object} user The object to convert from camel case to Hungarian.
* @param {boolean} force When set to `true`, properties which already have a
* Hungarian value in the `user` object will be overwritten. Otherwise they
* won't be.
*/
DataTable.camelToHungarian = _fnCamelToHungarian;
/**
*
*/
_api_register( '$()', function ( selector, opts ) {
var
rows = this.rows( opts ).nodes(), // Get all rows
jqRows = $(rows);
return $( [].concat(
jqRows.filter( selector ).toArray(),
jqRows.find( selector ).toArray()
) );
} );
// jQuery functions to operate on the tables
$.each( [ 'on', 'one', 'off' ], function (i, key) {
_api_register( key+'()', function ( /* event, handler */ ) {
var args = Array.prototype.slice.call(arguments);
// Add the `dt` namespace automatically if it isn't already present
args[0] = $.map( args[0].split( /\s/ ), function ( e ) {
return ! e.match(/\.dt\b/) ?
e+'.dt' :
e;
} ).join( ' ' );
var inst = $( this.tables().nodes() );
inst[key].apply( inst, args );
return this;
} );
} );
_api_register( 'clear()', function () {
return this.iterator( 'table', function ( settings ) {
_fnClearTable( settings );
} );
} );
_api_register( 'settings()', function () {
return new _Api( this.context, this.context );
} );
_api_register( 'init()', function () {
var ctx = this.context;
return ctx.length ? ctx[0].oInit : null;
} );
_api_register( 'data()', function () {
return this.iterator( 'table', function ( settings ) {
return _pluck( settings.aoData, '_aData' );
} ).flatten();
} );
_api_register( 'destroy()', function ( remove ) {
remove = remove || false;
return this.iterator( 'table', function ( settings ) {
var orig = settings.nTableWrapper.parentNode;
var classes = settings.oClasses;
var table = settings.nTable;
var tbody = settings.nTBody;
var thead = settings.nTHead;
var tfoot = settings.nTFoot;
var jqTable = $(table);
var jqTbody = $(tbody);
var jqWrapper = $(settings.nTableWrapper);
var rows = $.map( settings.aoData, function (r) { return r.nTr; } );
var i, ien;
// Flag to note that the table is currently being destroyed - no action
// should be taken
settings.bDestroying = true;
// Fire off the destroy callbacks for plug-ins etc
_fnCallbackFire( settings, "aoDestroyCallback", "destroy", [settings] );
// If not being removed from the document, make all columns visible
if ( ! remove ) {
new _Api( settings ).columns().visible( true );
}
// Blitz all `DT` namespaced events (these are internal events, the
// lowercase, `dt` events are user subscribed and they are responsible
// for removing them
jqWrapper.off('.DT').find(':not(tbody *)').off('.DT');
$(window).off('.DT-'+settings.sInstance);
// When scrolling we had to break the table up - restore it
if ( table != thead.parentNode ) {
jqTable.children('thead').detach();
jqTable.append( thead );
}
if ( tfoot && table != tfoot.parentNode ) {
jqTable.children('tfoot').detach();
jqTable.append( tfoot );
}
settings.aaSorting = [];
settings.aaSortingFixed = [];
_fnSortingClasses( settings );
$( rows ).removeClass( settings.asStripeClasses.join(' ') );
$('th, td', thead).removeClass( classes.sSortable+' '+
classes.sSortableAsc+' '+classes.sSortableDesc+' '+classes.sSortableNone
);
// Add the TR elements back into the table in their original order
jqTbody.children().detach();
jqTbody.append( rows );
// Remove the DataTables generated nodes, events and classes
var removedMethod = remove ? 'remove' : 'detach';
jqTable[ removedMethod ]();
jqWrapper[ removedMethod ]();
// If we need to reattach the table to the document
if ( ! remove && orig ) {
// insertBefore acts like appendChild if !arg[1]
orig.insertBefore( table, settings.nTableReinsertBefore );
// Restore the width of the original table - was read from the style property,
// so we can restore directly to that
jqTable
.css( 'width', settings.sDestroyWidth )
.removeClass( classes.sTable );
// If the were originally stripe classes - then we add them back here.
// Note this is not fool proof (for example if not all rows had stripe
// classes - but it's a good effort without getting carried away
ien = settings.asDestroyStripes.length;
if ( ien ) {
jqTbody.children().each( function (i) {
$(this).addClass( settings.asDestroyStripes[i % ien] );
} );
}
}
/* Remove the settings object from the settings array */
var idx = $.inArray( settings, DataTable.settings );
if ( idx !== -1 ) {
DataTable.settings.splice( idx, 1 );
}
} );
} );
// Add the `every()` method for rows, columns and cells in a compact form
$.each( [ 'column', 'row', 'cell' ], function ( i, type ) {
_api_register( type+'s().every()', function ( fn ) {
var opts = this.selector.opts;
var api = this;
return this.iterator( type, function ( settings, arg1, arg2, arg3, arg4 ) {
// Rows and columns:
// arg1 - index
// arg2 - table counter
// arg3 - loop counter
// arg4 - undefined
// Cells:
// arg1 - row index
// arg2 - column index
// arg3 - table counter
// arg4 - loop counter
fn.call(
api[ type ](
arg1,
type==='cell' ? arg2 : opts,
type==='cell' ? opts : undefined
),
arg1, arg2, arg3, arg4
);
} );
} );
} );
// i18n method for extensions to be able to use the language object from the
// DataTable
_api_register( 'i18n()', function ( token, def, plural ) {
var ctx = this.context[0];
var resolved = _fnGetObjectDataFn( token )( ctx.oLanguage );
if ( resolved === undefined ) {
resolved = def;
}
if ( plural !== undefined && $.isPlainObject( resolved ) ) {
resolved = resolved[ plural ] !== undefined ?
resolved[ plural ] :
resolved._;
}
return resolved.replace( '%d', plural ); // nb: plural might be undefined,
} );
/**
* Version string for plug-ins to check compatibility. Allowed format is
* `a.b.c-d` where: a:int, b:int, c:int, d:string(dev|beta|alpha). `d` is used
* only for non-release builds. See http://semver.org/ for more information.
* @member
* @type string
* @default Version number
*/
DataTable.version = "1.10.24";
/**
* Private data store, containing all of the settings objects that are
* created for the tables on a given page.
*
* Note that the `DataTable.settings` object is aliased to
* `jQuery.fn.dataTableExt` through which it may be accessed and
* manipulated, or `jQuery.fn.dataTable.settings`.
* @member
* @type array
* @default []
* @private
*/
DataTable.settings = [];
/**
* Object models container, for the various models that DataTables has
* available to it. These models define the objects that are used to hold
* the active state and configuration of the table.
* @namespace
*/
DataTable.models = {};
/**
* Template object for the way in which DataTables holds information about
* search information for the global filter and individual column filters.
* @namespace
*/
DataTable.models.oSearch = {
/**
* Flag to indicate if the filtering should be case insensitive or not
* @type boolean
* @default true
*/
"bCaseInsensitive": true,
/**
* Applied search term
* @type string
* @default <i>Empty string</i>
*/
"sSearch": "",
/**
* Flag to indicate if the search term should be interpreted as a
* regular expression (true) or not (false) and therefore and special
* regex characters escaped.
* @type boolean
* @default false
*/
"bRegex": false,
/**
* Flag to indicate if DataTables is to use its smart filtering or not.
* @type boolean
* @default true
*/
"bSmart": true
};
/**
* Template object for the way in which DataTables holds information about
* each individual row. This is the object format used for the settings
* aoData array.
* @namespace
*/
DataTable.models.oRow = {
/**
* TR element for the row
* @type node
* @default null
*/
"nTr": null,
/**
* Array of TD elements for each row. This is null until the row has been
* created.
* @type array nodes
* @default []
*/
"anCells": null,
/**
* Data object from the original data source for the row. This is either
* an array if using the traditional form of DataTables, or an object if
* using mData options. The exact type will depend on the passed in
* data from the data source, or will be an array if using DOM a data
* source.
* @type array|object
* @default []
*/
"_aData": [],
/**
* Sorting data cache - this array is ostensibly the same length as the
* number of columns (although each index is generated only as it is
* needed), and holds the data that is used for sorting each column in the
* row. We do this cache generation at the start of the sort in order that
* the formatting of the sort data need be done only once for each cell
* per sort. This array should not be read from or written to by anything
* other than the master sorting methods.
* @type array
* @default null
* @private
*/
"_aSortData": null,
/**
* Per cell filtering data cache. As per the sort data cache, used to
* increase the performance of the filtering in DataTables
* @type array
* @default null
* @private
*/
"_aFilterData": null,
/**
* Filtering data cache. This is the same as the cell filtering cache, but
* in this case a string rather than an array. This is easily computed with
* a join on `_aFilterData`, but is provided as a cache so the join isn't
* needed on every search (memory traded for performance)
* @type array
* @default null
* @private
*/
"_sFilterRow": null,
/**
* Cache of the class name that DataTables has applied to the row, so we
* can quickly look at this variable rather than needing to do a DOM check
* on className for the nTr property.
* @type string
* @default <i>Empty string</i>
* @private
*/
"_sRowStripe": "",
/**
* Denote if the original data source was from the DOM, or the data source
* object. This is used for invalidating data, so DataTables can
* automatically read data from the original source, unless uninstructed
* otherwise.
* @type string
* @default null
* @private
*/
"src": null,
/**
* Index in the aoData array. This saves an indexOf lookup when we have the
* object, but want to know the index
* @type integer
* @default -1
* @private
*/
"idx": -1
};
/**
* Template object for the column information object in DataTables. This object
* is held in the settings aoColumns array and contains all the information that
* DataTables needs about each individual column.
*
* Note that this object is related to {@link DataTable.defaults.column}
* but this one is the internal data store for DataTables's cache of columns.
* It should NOT be manipulated outside of DataTables. Any configuration should
* be done through the initialisation options.
* @namespace
*/
DataTable.models.oColumn = {
/**
* Column index. This could be worked out on-the-fly with $.inArray, but it
* is faster to just hold it as a variable
* @type integer
* @default null
*/
"idx": null,
/**
* A list of the columns that sorting should occur on when this column
* is sorted. That this property is an array allows multi-column sorting
* to be defined for a column (for example first name / last name columns
* would benefit from this). The values are integers pointing to the
* columns to be sorted on (typically it will be a single integer pointing
* at itself, but that doesn't need to be the case).
* @type array
*/
"aDataSort": null,
/**
* Define the sorting directions that are applied to the column, in sequence
* as the column is repeatedly sorted upon - i.e. the first value is used
* as the sorting direction when the column if first sorted (clicked on).
* Sort it again (click again) and it will move on to the next index.
* Repeat until loop.
* @type array
*/
"asSorting": null,
/**
* Flag to indicate if the column is searchable, and thus should be included
* in the filtering or not.
* @type boolean
*/
"bSearchable": null,
/**
* Flag to indicate if the column is sortable or not.
* @type boolean
*/
"bSortable": null,
/**
* Flag to indicate if the column is currently visible in the table or not
* @type boolean
*/
"bVisible": null,
/**
* Store for manual type assignment using the `column.type` option. This
* is held in store so we can manipulate the column's `sType` property.
* @type string
* @default null
* @private
*/
"_sManualType": null,
/**
* Flag to indicate if HTML5 data attributes should be used as the data
* source for filtering or sorting. True is either are.
* @type boolean
* @default false
* @private
*/
"_bAttrSrc": false,
/**
* Developer definable function that is called whenever a cell is created (Ajax source,
* etc) or processed for input (DOM source). This can be used as a compliment to mRender
* allowing you to modify the DOM element (add background colour for example) when the
* element is available.
* @type function
* @param {element} nTd The TD node that has been created
* @param {*} sData The Data for the cell
* @param {array|object} oData The data for the whole row
* @param {int} iRow The row index for the aoData data store
* @default null
*/
"fnCreatedCell": null,
/**
* Function to get data from a cell in a column. You should <b>never</b>
* access data directly through _aData internally in DataTables - always use
* the method attached to this property. It allows mData to function as
* required. This function is automatically assigned by the column
* initialisation method
* @type function
* @param {array|object} oData The data array/object for the array
* (i.e. aoData[]._aData)
* @param {string} sSpecific The specific data type you want to get -
* 'display', 'type' 'filter' 'sort'
* @returns {*} The data for the cell from the given row's data
* @default null
*/
"fnGetData": null,
/**
* Function to set data for a cell in the column. You should <b>never</b>
* set the data directly to _aData internally in DataTables - always use
* this method. It allows mData to function as required. This function
* is automatically assigned by the column initialisation method
* @type function
* @param {array|object} oData The data array/object for the array
* (i.e. aoData[]._aData)
* @param {*} sValue Value to set
* @default null
*/
"fnSetData": null,
/**
* Property to read the value for the cells in the column from the data
* source array / object. If null, then the default content is used, if a
* function is given then the return from the function is used.
* @type function|int|string|null
* @default null
*/
"mData": null,
/**
* Partner property to mData which is used (only when defined) to get
* the data - i.e. it is basically the same as mData, but without the
* 'set' option, and also the data fed to it is the result from mData.
* This is the rendering method to match the data method of mData.
* @type function|int|string|null
* @default null
*/
"mRender": null,
/**
* Unique header TH/TD element for this column - this is what the sorting
* listener is attached to (if sorting is enabled.)
* @type node
* @default null
*/
"nTh": null,
/**
* Unique footer TH/TD element for this column (if there is one). Not used
* in DataTables as such, but can be used for plug-ins to reference the
* footer for each column.
* @type node
* @default null
*/
"nTf": null,
/**
* The class to apply to all TD elements in the table's TBODY for the column
* @type string
* @default null
*/
"sClass": null,
/**
* When DataTables calculates the column widths to assign to each column,
* it finds the longest string in each column and then constructs a
* temporary table and reads the widths from that. The problem with this
* is that "mmm" is much wider then "iiii", but the latter is a longer
* string - thus the calculation can go wrong (doing it properly and putting
* it into an DOM object and measuring that is horribly(!) slow). Thus as
* a "work around" we provide this option. It will append its value to the
* text that is found to be the longest string for the column - i.e. padding.
* @type string
*/
"sContentPadding": null,
/**
* Allows a default value to be given for a column's data, and will be used
* whenever a null data source is encountered (this can be because mData
* is set to null, or because the data source itself is null).
* @type string
* @default null
*/
"sDefaultContent": null,
/**
* Name for the column, allowing reference to the column by name as well as
* by index (needs a lookup to work by name).
* @type string
*/
"sName": null,
/**
* Custom sorting data type - defines which of the available plug-ins in
* afnSortData the custom sorting will use - if any is defined.
* @type string
* @default std
*/
"sSortDataType": 'std',
/**
* Class to be applied to the header element when sorting on this column
* @type string
* @default null
*/
"sSortingClass": null,
/**
* Class to be applied to the header element when sorting on this column -
* when jQuery UI theming is used.
* @type string
* @default null
*/
"sSortingClassJUI": null,
/**
* Title of the column - what is seen in the TH element (nTh).
* @type string
*/
"sTitle": null,
/**
* Column sorting and filtering type
* @type string
* @default null
*/
"sType": null,
/**
* Width of the column
* @type string
* @default null
*/
"sWidth": null,
/**
* Width of the column when it was first "encountered"
* @type string
* @default null
*/
"sWidthOrig": null
};
/*
* Developer note: The properties of the object below are given in Hungarian
* notation, that was used as the interface for DataTables prior to v1.10, however
* from v1.10 onwards the primary interface is camel case. In order to avoid
* breaking backwards compatibility utterly with this change, the Hungarian
* version is still, internally the primary interface, but is is not documented
* - hence the @name tags in each doc comment. This allows a Javascript function
* to create a map from Hungarian notation to camel case (going the other direction
* would require each property to be listed, which would add around 3K to the size
* of DataTables, while this method is about a 0.5K hit).
*
* Ultimately this does pave the way for Hungarian notation to be dropped
* completely, but that is a massive amount of work and will break current
* installs (therefore is on-hold until v2).
*/
/**
* Initialisation options that can be given to DataTables at initialisation
* time.
* @namespace
*/
DataTable.defaults = {
/**
* An array of data to use for the table, passed in at initialisation which
* will be used in preference to any data which is already in the DOM. This is
* particularly useful for constructing tables purely in Javascript, for
* example with a custom Ajax call.
* @type array
* @default null
*
* @dtopt Option
* @name DataTable.defaults.data
*
* @example
* // Using a 2D array data source
* $(document).ready( function () {
* $('#example').dataTable( {
* "data": [
* ['Trident', 'Internet Explorer 4.0', 'Win 95+', 4, 'X'],
* ['Trident', 'Internet Explorer 5.0', 'Win 95+', 5, 'C'],
* ],
* "columns": [
* { "title": "Engine" },
* { "title": "Browser" },
* { "title": "Platform" },
* { "title": "Version" },
* { "title": "Grade" }
* ]
* } );
* } );
*
* @example
* // Using an array of objects as a data source (`data`)
* $(document).ready( function () {
* $('#example').dataTable( {
* "data": [
* {
* "engine": "Trident",
* "browser": "Internet Explorer 4.0",
* "platform": "Win 95+",
* "version": 4,
* "grade": "X"
* },
* {
* "engine": "Trident",
* "browser": "Internet Explorer 5.0",
* "platform": "Win 95+",
* "version": 5,
* "grade": "C"
* }
* ],
* "columns": [
* { "title": "Engine", "data": "engine" },
* { "title": "Browser", "data": "browser" },
* { "title": "Platform", "data": "platform" },
* { "title": "Version", "data": "version" },
* { "title": "Grade", "data": "grade" }
* ]
* } );
* } );
*/
"aaData": null,
/**
* If ordering is enabled, then DataTables will perform a first pass sort on
* initialisation. You can define which column(s) the sort is performed
* upon, and the sorting direction, with this variable. The `sorting` array
* should contain an array for each column to be sorted initially containing
* the column's index and a direction string ('asc' or 'desc').
* @type array
* @default [[0,'asc']]
*
* @dtopt Option
* @name DataTable.defaults.order
*
* @example
* // Sort by 3rd column first, and then 4th column
* $(document).ready( function() {
* $('#example').dataTable( {
* "order": [[2,'asc'], [3,'desc']]
* } );
* } );
*
* // No initial sorting
* $(document).ready( function() {
* $('#example').dataTable( {
* "order": []
* } );
* } );
*/
"aaSorting": [[0,'asc']],
/**
* This parameter is basically identical to the `sorting` parameter, but
* cannot be overridden by user interaction with the table. What this means
* is that you could have a column (visible or hidden) which the sorting
* will always be forced on first - any sorting after that (from the user)
* will then be performed as required. This can be useful for grouping rows
* together.
* @type array
* @default null
*
* @dtopt Option
* @name DataTable.defaults.orderFixed
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "orderFixed": [[0,'asc']]
* } );
* } )
*/
"aaSortingFixed": [],
/**
* DataTables can be instructed to load data to display in the table from a
* Ajax source. This option defines how that Ajax call is made and where to.
*
* The `ajax` property has three different modes of operation, depending on
* how it is defined. These are:
*
* * `string` - Set the URL from where the data should be loaded from.
* * `object` - Define properties for `jQuery.ajax`.
* * `function` - Custom data get function
*
* `string`
* --------
*
* As a string, the `ajax` property simply defines the URL from which
* DataTables will load data.
*
* `object`
* --------
*
* As an object, the parameters in the object are passed to
* [jQuery.ajax](http://api.jquery.com/jQuery.ajax/) allowing fine control
* of the Ajax request. DataTables has a number of default parameters which
* you can override using this option. Please refer to the jQuery
* documentation for a full description of the options available, although
* the following parameters provide additional options in DataTables or
* require special consideration:
*
* * `data` - As with jQuery, `data` can be provided as an object, but it
* can also be used as a function to manipulate the data DataTables sends
* to the server. The function takes a single parameter, an object of
* parameters with the values that DataTables has readied for sending. An
* object may be returned which will be merged into the DataTables
* defaults, or you can add the items to the object that was passed in and
* not return anything from the function. This supersedes `fnServerParams`
* from DataTables 1.9-.
*
* * `dataSrc` - By default DataTables will look for the property `data` (or
* `aaData` for compatibility with DataTables 1.9-) when obtaining data
* from an Ajax source or for server-side processing - this parameter
* allows that property to be changed. You can use Javascript dotted
* object notation to get a data source for multiple levels of nesting, or
* it my be used as a function. As a function it takes a single parameter,
* the JSON returned from the server, which can be manipulated as
* required, with the returned value being that used by DataTables as the
* data source for the table. This supersedes `sAjaxDataProp` from
* DataTables 1.9-.
*
* * `success` - Should not be overridden it is used internally in
* DataTables. To manipulate / transform the data returned by the server
* use `ajax.dataSrc`, or use `ajax` as a function (see below).
*
* `function`
* ----------
*
* As a function, making the Ajax call is left up to yourself allowing
* complete control of the Ajax request. Indeed, if desired, a method other
* than Ajax could be used to obtain the required data, such as Web storage
* or an AIR database.
*
* The function is given four parameters and no return is required. The
* parameters are:
*
* 1. _object_ - Data to send to the server
* 2. _function_ - Callback function that must be executed when the required
* data has been obtained. That data should be passed into the callback
* as the only parameter
* 3. _object_ - DataTables settings object for the table
*
* Note that this supersedes `fnServerData` from DataTables 1.9-.
*
* @type string|object|function
* @default null
*
* @dtopt Option
* @name DataTable.defaults.ajax
* @since 1.10.0
*
* @example
* // Get JSON data from a file via Ajax.
* // Note DataTables expects data in the form `{ data: [ ...data... ] }` by default).
* $('#example').dataTable( {
* "ajax": "data.json"
* } );
*
* @example
* // Get JSON data from a file via Ajax, using `dataSrc` to change
* // `data` to `tableData` (i.e. `{ tableData: [ ...data... ] }`)
* $('#example').dataTable( {
* "ajax": {
* "url": "data.json",
* "dataSrc": "tableData"
* }
* } );
*
* @example
* // Get JSON data from a file via Ajax, using `dataSrc` to read data
* // from a plain array rather than an array in an object
* $('#example').dataTable( {
* "ajax": {
* "url": "data.json",
* "dataSrc": ""
* }
* } );
*
* @example
* // Manipulate the data returned from the server - add a link to data
* // (note this can, should, be done using `render` for the column - this
* // is just a simple example of how the data can be manipulated).
* $('#example').dataTable( {
* "ajax": {
* "url": "data.json",
* "dataSrc": function ( json ) {
* for ( var i=0, ien=json.length ; i<ien ; i++ ) {
* json[i][0] = '<a href="/message/'+json[i][0]+'>View message</a>';
* }
* return json;
* }
* }
* } );
*
* @example
* // Add data to the request
* $('#example').dataTable( {
* "ajax": {
* "url": "data.json",
* "data": function ( d ) {
* return {
* "extra_search": $('#extra').val()
* };
* }
* }
* } );
*
* @example
* // Send request as POST
* $('#example').dataTable( {
* "ajax": {
* "url": "data.json",
* "type": "POST"
* }
* } );
*
* @example
* // Get the data from localStorage (could interface with a form for
* // adding, editing and removing rows).
* $('#example').dataTable( {
* "ajax": function (data, callback, settings) {
* callback(
* JSON.parse( localStorage.getItem('dataTablesData') )
* );
* }
* } );
*/
"ajax": null,
/**
* This parameter allows you to readily specify the entries in the length drop
* down menu that DataTables shows when pagination is enabled. It can be
* either a 1D array of options which will be used for both the displayed
* option and the value, or a 2D array which will use the array in the first
* position as the value, and the array in the second position as the
* displayed options (useful for language strings such as 'All').
*
* Note that the `pageLength` property will be automatically set to the
* first value given in this array, unless `pageLength` is also provided.
* @type array
* @default [ 10, 25, 50, 100 ]
*
* @dtopt Option
* @name DataTable.defaults.lengthMenu
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]]
* } );
* } );
*/
"aLengthMenu": [ 10, 25, 50, 100 ],
/**
* The `columns` option in the initialisation parameter allows you to define
* details about the way individual columns behave. For a full list of
* column options that can be set, please see
* {@link DataTable.defaults.column}. Note that if you use `columns` to
* define your columns, you must have an entry in the array for every single
* column that you have in your table (these can be null if you don't which
* to specify any options).
* @member
*
* @name DataTable.defaults.column
*/
"aoColumns": null,
/**
* Very similar to `columns`, `columnDefs` allows you to target a specific
* column, multiple columns, or all columns, using the `targets` property of
* each object in the array. This allows great flexibility when creating
* tables, as the `columnDefs` arrays can be of any length, targeting the
* columns you specifically want. `columnDefs` may use any of the column
* options available: {@link DataTable.defaults.column}, but it _must_
* have `targets` defined in each object in the array. Values in the `targets`
* array may be:
* <ul>
* <li>a string - class name will be matched on the TH for the column</li>
* <li>0 or a positive integer - column index counting from the left</li>
* <li>a negative integer - column index counting from the right</li>
* <li>the string "_all" - all columns (i.e. assign a default)</li>
* </ul>
* @member
*
* @name DataTable.defaults.columnDefs
*/
"aoColumnDefs": null,
/**
* Basically the same as `search`, this parameter defines the individual column
* filtering state at initialisation time. The array must be of the same size
* as the number of columns, and each element be an object with the parameters
* `search` and `escapeRegex` (the latter is optional). 'null' is also
* accepted and the default will be used.
* @type array
* @default []
*
* @dtopt Option
* @name DataTable.defaults.searchCols
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "searchCols": [
* null,
* { "search": "My filter" },
* null,
* { "search": "^[0-9]", "escapeRegex": false }
* ]
* } );
* } )
*/
"aoSearchCols": [],
/**
* An array of CSS classes that should be applied to displayed rows. This
* array may be of any length, and DataTables will apply each class
* sequentially, looping when required.
* @type array
* @default null <i>Will take the values determined by the `oClasses.stripe*`
* options</i>
*
* @dtopt Option
* @name DataTable.defaults.stripeClasses
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "stripeClasses": [ 'strip1', 'strip2', 'strip3' ]
* } );
* } )
*/
"asStripeClasses": null,
/**
* Enable or disable automatic column width calculation. This can be disabled
* as an optimisation (it takes some time to calculate the widths) if the
* tables widths are passed in using `columns`.
* @type boolean
* @default true
*
* @dtopt Features
* @name DataTable.defaults.autoWidth
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "autoWidth": false
* } );
* } );
*/
"bAutoWidth": true,
/**
* Deferred rendering can provide DataTables with a huge speed boost when you
* are using an Ajax or JS data source for the table. This option, when set to
* true, will cause DataTables to defer the creation of the table elements for
* each row until they are needed for a draw - saving a significant amount of
* time.
* @type boolean
* @default false
*
* @dtopt Features
* @name DataTable.defaults.deferRender
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "ajax": "sources/arrays.txt",
* "deferRender": true
* } );
* } );
*/
"bDeferRender": false,
/**
* Replace a DataTable which matches the given selector and replace it with
* one which has the properties of the new initialisation object passed. If no
* table matches the selector, then the new DataTable will be constructed as
* per normal.
* @type boolean
* @default false
*
* @dtopt Options
* @name DataTable.defaults.destroy
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "srollY": "200px",
* "paginate": false
* } );
*
* // Some time later....
* $('#example').dataTable( {
* "filter": false,
* "destroy": true
* } );
* } );
*/
"bDestroy": false,
/**
* Enable or disable filtering of data. Filtering in DataTables is "smart" in
* that it allows the end user to input multiple words (space separated) and
* will match a row containing those words, even if not in the order that was
* specified (this allow matching across multiple columns). Note that if you
* wish to use filtering in DataTables this must remain 'true' - to remove the
* default filtering input box and retain filtering abilities, please use
* {@link DataTable.defaults.dom}.
* @type boolean
* @default true
*
* @dtopt Features
* @name DataTable.defaults.searching
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "searching": false
* } );
* } );
*/
"bFilter": true,
/**
* Enable or disable the table information display. This shows information
* about the data that is currently visible on the page, including information
* about filtered data if that action is being performed.
* @type boolean
* @default true
*
* @dtopt Features
* @name DataTable.defaults.info
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "info": false
* } );
* } );
*/
"bInfo": true,
/**
* Allows the end user to select the size of a formatted page from a select
* menu (sizes are 10, 25, 50 and 100). Requires pagination (`paginate`).
* @type boolean
* @default true
*
* @dtopt Features
* @name DataTable.defaults.lengthChange
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "lengthChange": false
* } );
* } );
*/
"bLengthChange": true,
/**
* Enable or disable pagination.
* @type boolean
* @default true
*
* @dtopt Features
* @name DataTable.defaults.paging
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "paging": false
* } );
* } );
*/
"bPaginate": true,
/**
* Enable or disable the display of a 'processing' indicator when the table is
* being processed (e.g. a sort). This is particularly useful for tables with
* large amounts of data where it can take a noticeable amount of time to sort
* the entries.
* @type boolean
* @default false
*
* @dtopt Features
* @name DataTable.defaults.processing
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "processing": true
* } );
* } );
*/
"bProcessing": false,
/**
* Retrieve the DataTables object for the given selector. Note that if the
* table has already been initialised, this parameter will cause DataTables
* to simply return the object that has already been set up - it will not take
* account of any changes you might have made to the initialisation object
* passed to DataTables (setting this parameter to true is an acknowledgement
* that you understand this). `destroy` can be used to reinitialise a table if
* you need.
* @type boolean
* @default false
*
* @dtopt Options
* @name DataTable.defaults.retrieve
*
* @example
* $(document).ready( function() {
* initTable();
* tableActions();
* } );
*
* function initTable ()
* {
* return $('#example').dataTable( {
* "scrollY": "200px",
* "paginate": false,
* "retrieve": true
* } );
* }
*
* function tableActions ()
* {
* var table = initTable();
* // perform API operations with oTable
* }
*/
"bRetrieve": false,
/**
* When vertical (y) scrolling is enabled, DataTables will force the height of
* the table's viewport to the given height at all times (useful for layout).
* However, this can look odd when filtering data down to a small data set,
* and the footer is left "floating" further down. This parameter (when
* enabled) will cause DataTables to collapse the table's viewport down when
* the result set will fit within the given Y height.
* @type boolean
* @default false
*
* @dtopt Options
* @name DataTable.defaults.scrollCollapse
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "scrollY": "200",
* "scrollCollapse": true
* } );
* } );
*/
"bScrollCollapse": false,
/**
* Configure DataTables to use server-side processing. Note that the
* `ajax` parameter must also be given in order to give DataTables a
* source to obtain the required data for each draw.
* @type boolean
* @default false
*
* @dtopt Features
* @dtopt Server-side
* @name DataTable.defaults.serverSide
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "serverSide": true,
* "ajax": "xhr.php"
* } );
* } );
*/
"bServerSide": false,
/**
* Enable or disable sorting of columns. Sorting of individual columns can be
* disabled by the `sortable` option for each column.
* @type boolean
* @default true
*
* @dtopt Features
* @name DataTable.defaults.ordering
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "ordering": false
* } );
* } );
*/
"bSort": true,
/**
* Enable or display DataTables' ability to sort multiple columns at the
* same time (activated by shift-click by the user).
* @type boolean
* @default true
*
* @dtopt Options
* @name DataTable.defaults.orderMulti
*
* @example
* // Disable multiple column sorting ability
* $(document).ready( function () {
* $('#example').dataTable( {
* "orderMulti": false
* } );
* } );
*/
"bSortMulti": true,
/**
* Allows control over whether DataTables should use the top (true) unique
* cell that is found for a single column, or the bottom (false - default).
* This is useful when using complex headers.
* @type boolean
* @default false
*
* @dtopt Options
* @name DataTable.defaults.orderCellsTop
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "orderCellsTop": true
* } );
* } );
*/
"bSortCellsTop": false,
/**
* Enable or disable the addition of the classes `sorting\_1`, `sorting\_2` and
* `sorting\_3` to the columns which are currently being sorted on. This is
* presented as a feature switch as it can increase processing time (while
* classes are removed and added) so for large data sets you might want to
* turn this off.
* @type boolean
* @default true
*
* @dtopt Features
* @name DataTable.defaults.orderClasses
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "orderClasses": false
* } );
* } );
*/
"bSortClasses": true,
/**
* Enable or disable state saving. When enabled HTML5 `localStorage` will be
* used to save table display information such as pagination information,
* display length, filtering and sorting. As such when the end user reloads
* the page the display display will match what thy had previously set up.
*
* Due to the use of `localStorage` the default state saving is not supported
* in IE6 or 7. If state saving is required in those browsers, use
* `stateSaveCallback` to provide a storage solution such as cookies.
* @type boolean
* @default false
*
* @dtopt Features
* @name DataTable.defaults.stateSave
*
* @example
* $(document).ready( function () {
* $('#example').dataTable( {
* "stateSave": true
* } );
* } );
*/
"bStateSave": false,
/**
* This function is called when a TR element is created (and all TD child
* elements have been inserted), or registered if using a DOM source, allowing
* manipulation of the TR element (adding classes etc).
* @type function
* @param {node} row "TR" element for the current row
* @param {array} data Raw data array for this row
* @param {int} dataIndex The index of this row in the internal aoData array
*
* @dtopt Callbacks
* @name DataTable.defaults.createdRow
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "createdRow": function( row, data, dataIndex ) {
* // Bold the grade for all 'A' grade browsers
* if ( data[4] == "A" )
* {
* $('td:eq(4)', row).html( '<b>A</b>' );
* }
* }
* } );
* } );
*/
"fnCreatedRow": null,
/**
* This function is called on every 'draw' event, and allows you to
* dynamically modify any aspect you want about the created DOM.
* @type function
* @param {object} settings DataTables settings object
*
* @dtopt Callbacks
* @name DataTable.defaults.drawCallback
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "drawCallback": function( settings ) {
* alert( 'DataTables has redrawn the table' );
* }
* } );
* } );
*/
"fnDrawCallback": null,
/**
* Identical to fnHeaderCallback() but for the table footer this function
* allows you to modify the table footer on every 'draw' event.
* @type function
* @param {node} foot "TR" element for the footer
* @param {array} data Full table data (as derived from the original HTML)
* @param {int} start Index for the current display starting point in the
* display array
* @param {int} end Index for the current display ending point in the
* display array
* @param {array int} display Index array to translate the visual position
* to the full data array
*
* @dtopt Callbacks
* @name DataTable.defaults.footerCallback
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "footerCallback": function( tfoot, data, start, end, display ) {
* tfoot.getElementsByTagName('th')[0].innerHTML = "Starting index is "+start;
* }
* } );
* } )
*/
"fnFooterCallback": null,
/**
* When rendering large numbers in the information element for the table
* (i.e. "Showing 1 to 10 of 57 entries") DataTables will render large numbers
* to have a comma separator for the 'thousands' units (e.g. 1 million is
* rendered as "1,000,000") to help readability for the end user. This
* function will override the default method DataTables uses.
* @type function
* @member
* @param {int} toFormat number to be formatted
* @returns {string} formatted string for DataTables to show the number
*
* @dtopt Callbacks
* @name DataTable.defaults.formatNumber
*
* @example
* // Format a number using a single quote for the separator (note that
* // this can also be done with the language.thousands option)
* $(document).ready( function() {
* $('#example').dataTable( {
* "formatNumber": function ( toFormat ) {
* return toFormat.toString().replace(
* /\B(?=(\d{3})+(?!\d))/g, "'"
* );
* };
* } );
* } );
*/
"fnFormatNumber": function ( toFormat ) {
return toFormat.toString().replace(
/\B(?=(\d{3})+(?!\d))/g,
this.oLanguage.sThousands
);
},
/**
* This function is called on every 'draw' event, and allows you to
* dynamically modify the header row. This can be used to calculate and
* display useful information about the table.
* @type function
* @param {node} head "TR" element for the header
* @param {array} data Full table data (as derived from the original HTML)
* @param {int} start Index for the current display starting point in the
* display array
* @param {int} end Index for the current display ending point in the
* display array
* @param {array int} display Index array to translate the visual position
* to the full data array
*
* @dtopt Callbacks
* @name DataTable.defaults.headerCallback
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "fheaderCallback": function( head, data, start, end, display ) {
* head.getElementsByTagName('th')[0].innerHTML = "Displaying "+(end-start)+" records";
* }
* } );
* } )
*/
"fnHeaderCallback": null,
/**
* The information element can be used to convey information about the current
* state of the table. Although the internationalisation options presented by
* DataTables are quite capable of dealing with most customisations, there may
* be times where you wish to customise the string further. This callback
* allows you to do exactly that.
* @type function
* @param {object} oSettings DataTables settings object
* @param {int} start Starting position in data for the draw
* @param {int} end End position in data for the draw
* @param {int} max Total number of rows in the table (regardless of
* filtering)
* @param {int} total Total number of rows in the data set, after filtering
* @param {string} pre The string that DataTables has formatted using it's
* own rules
* @returns {string} The string to be displayed in the information element.
*
* @dtopt Callbacks
* @name DataTable.defaults.infoCallback
*
* @example
* $('#example').dataTable( {
* "infoCallback": function( settings, start, end, max, total, pre ) {
* return start +" to "+ end;
* }
* } );
*/
"fnInfoCallback": null,
/**
* Called when the table has been initialised. Normally DataTables will
* initialise sequentially and there will be no need for this function,
* however, this does not hold true when using external language information
* since that is obtained using an async XHR call.
* @type function
* @param {object} settings DataTables settings object
* @param {object} json The JSON object request from the server - only
* present if client-side Ajax sourced data is used
*
* @dtopt Callbacks
* @name DataTable.defaults.initComplete
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "initComplete": function(settings, json) {
* alert( 'DataTables has finished its initialisation.' );
* }
* } );
* } )
*/
"fnInitComplete": null,
/**
* Called at the very start of each table draw and can be used to cancel the
* draw by returning false, any other return (including undefined) results in
* the full draw occurring).
* @type function
* @param {object} settings DataTables settings object
* @returns {boolean} False will cancel the draw, anything else (including no
* return) will allow it to complete.
*
* @dtopt Callbacks
* @name DataTable.defaults.preDrawCallback
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "preDrawCallback": function( settings ) {
* if ( $('#test').val() == 1 ) {
* return false;
* }
* }
* } );
* } );
*/
"fnPreDrawCallback": null,
/**
* This function allows you to 'post process' each row after it have been
* generated for each table draw, but before it is rendered on screen. This
* function might be used for setting the row class name etc.
* @type function
* @param {node} row "TR" element for the current row
* @param {array} data Raw data array for this row
* @param {int} displayIndex The display index for the current table draw
* @param {int} displayIndexFull The index of the data in the full list of
* rows (after filtering)
*
* @dtopt Callbacks
* @name DataTable.defaults.rowCallback
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "rowCallback": function( row, data, displayIndex, displayIndexFull ) {
* // Bold the grade for all 'A' grade browsers
* if ( data[4] == "A" ) {
* $('td:eq(4)', row).html( '<b>A</b>' );
* }
* }
* } );
* } );
*/
"fnRowCallback": null,
/**
* __Deprecated__ The functionality provided by this parameter has now been
* superseded by that provided through `ajax`, which should be used instead.
*
* This parameter allows you to override the default function which obtains
* the data from the server so something more suitable for your application.
* For example you could use POST data, or pull information from a Gears or
* AIR database.
* @type function
* @member
* @param {string} source HTTP source to obtain the data from (`ajax`)
* @param {array} data A key/value pair object containing the data to send
* to the server
* @param {function} callback to be called on completion of the data get
* process that will draw the data on the page.
* @param {object} settings DataTables settings object
*
* @dtopt Callbacks
* @dtopt Server-side
* @name DataTable.defaults.serverData
*
* @deprecated 1.10. Please use `ajax` for this functionality now.
*/
"fnServerData": null,
/**
* __Deprecated__ The functionality provided by this parameter has now been
* superseded by that provided through `ajax`, which should be used instead.
*
* It is often useful to send extra data to the server when making an Ajax
* request - for example custom filtering information, and this callback
* function makes it trivial to send extra information to the server. The
* passed in parameter is the data set that has been constructed by
* DataTables, and you can add to this or modify it as you require.
* @type function
* @param {array} data Data array (array of objects which are name/value
* pairs) that has been constructed by DataTables and will be sent to the
* server. In the case of Ajax sourced data with server-side processing
* this will be an empty array, for server-side processing there will be a
* significant number of parameters!
* @returns {undefined} Ensure that you modify the data array passed in,
* as this is passed by reference.
*
* @dtopt Callbacks
* @dtopt Server-side
* @name DataTable.defaults.serverParams
*
* @deprecated 1.10. Please use `ajax` for this functionality now.
*/
"fnServerParams": null,
/**
* Load the table state. With this function you can define from where, and how, the
* state of a table is loaded. By default DataTables will load from `localStorage`
* but you might wish to use a server-side database or cookies.
* @type function
* @member
* @param {object} settings DataTables settings object
* @param {object} callback Callback that can be executed when done. It
* should be passed the loaded state object.
* @return {object} The DataTables state object to be loaded
*
* @dtopt Callbacks
* @name DataTable.defaults.stateLoadCallback
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "stateSave": true,
* "stateLoadCallback": function (settings, callback) {
* $.ajax( {
* "url": "/state_load",
* "dataType": "json",
* "success": function (json) {
* callback( json );
* }
* } );
* }
* } );
* } );
*/
"fnStateLoadCallback": function ( settings ) {
try {
return JSON.parse(
(settings.iStateDuration === -1 ? sessionStorage : localStorage).getItem(
'DataTables_'+settings.sInstance+'_'+location.pathname
)
);
} catch (e) {
return {};
}
},
/**
* Callback which allows modification of the saved state prior to loading that state.
* This callback is called when the table is loading state from the stored data, but
* prior to the settings object being modified by the saved state. Note that for
* plug-in authors, you should use the `stateLoadParams` event to load parameters for
* a plug-in.
* @type function
* @param {object} settings DataTables settings object
* @param {object} data The state object that is to be loaded
*
* @dtopt Callbacks
* @name DataTable.defaults.stateLoadParams
*
* @example
* // Remove a saved filter, so filtering is never loaded
* $(document).ready( function() {
* $('#example').dataTable( {
* "stateSave": true,
* "stateLoadParams": function (settings, data) {
* data.oSearch.sSearch = "";
* }
* } );
* } );
*
* @example
* // Disallow state loading by returning false
* $(document).ready( function() {
* $('#example').dataTable( {
* "stateSave": true,
* "stateLoadParams": function (settings, data) {
* return false;
* }
* } );
* } );
*/
"fnStateLoadParams": null,
/**
* Callback that is called when the state has been loaded from the state saving method
* and the DataTables settings object has been modified as a result of the loaded state.
* @type function
* @param {object} settings DataTables settings object
* @param {object} data The state object that was loaded
*
* @dtopt Callbacks
* @name DataTable.defaults.stateLoaded
*
* @example
* // Show an alert with the filtering value that was saved
* $(document).ready( function() {
* $('#example').dataTable( {
* "stateSave": true,
* "stateLoaded": function (settings, data) {
* alert( 'Saved filter was: '+data.oSearch.sSearch );
* }
* } );
* } );
*/
"fnStateLoaded": null,
/**
* Save the table state. This function allows you to define where and how the state
* information for the table is stored By default DataTables will use `localStorage`
* but you might wish to use a server-side database or cookies.
* @type function
* @member
* @param {object} settings DataTables settings object
* @param {object} data The state object to be saved
*
* @dtopt Callbacks
* @name DataTable.defaults.stateSaveCallback
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "stateSave": true,
* "stateSaveCallback": function (settings, data) {
* // Send an Ajax request to the server with the state object
* $.ajax( {
* "url": "/state_save",
* "data": data,
* "dataType": "json",
* "method": "POST"
* "success": function () {}
* } );
* }
* } );
* } );
*/
"fnStateSaveCallback": function ( settings, data ) {
try {
(settings.iStateDuration === -1 ? sessionStorage : localStorage).setItem(
'DataTables_'+settings.sInstance+'_'+location.pathname,
JSON.stringify( data )
);
} catch (e) {}
},
/**
* Callback which allows modification of the state to be saved. Called when the table
* has changed state a new state save is required. This method allows modification of
* the state saving object prior to actually doing the save, including addition or
* other state properties or modification. Note that for plug-in authors, you should
* use the `stateSaveParams` event to save parameters for a plug-in.
* @type function
* @param {object} settings DataTables settings object
* @param {object} data The state object to be saved
*
* @dtopt Callbacks
* @name DataTable.defaults.stateSaveParams
*
* @example
* // Remove a saved filter, so filtering is never saved
* $(document).ready( function() {
* $('#example').dataTable( {
* "stateSave": true,
* "stateSaveParams": function (settings, data) {
* data.oSearch.sSearch = "";
* }
* } );
* } );
*/
"fnStateSaveParams": null,
/**
* Duration for which the saved state information is considered valid. After this period
* has elapsed the state will be returned to the default.
* Value is given in seconds.
* @type int
* @default 7200 <i>(2 hours)</i>
*
* @dtopt Options
* @name DataTable.defaults.stateDuration
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "stateDuration": 60*60*24; // 1 day
* } );
* } )
*/
"iStateDuration": 7200,
/**
* When enabled DataTables will not make a request to the server for the first
* page draw - rather it will use the data already on the page (no sorting etc
* will be applied to it), thus saving on an XHR at load time. `deferLoading`
* is used to indicate that deferred loading is required, but it is also used
* to tell DataTables how many records there are in the full table (allowing
* the information element and pagination to be displayed correctly). In the case
* where a filtering is applied to the table on initial load, this can be
* indicated by giving the parameter as an array, where the first element is
* the number of records available after filtering and the second element is the
* number of records without filtering (allowing the table information element
* to be shown correctly).
* @type int | array
* @default null
*
* @dtopt Options
* @name DataTable.defaults.deferLoading
*
* @example
* // 57 records available in the table, no filtering applied
* $(document).ready( function() {
* $('#example').dataTable( {
* "serverSide": true,
* "ajax": "scripts/server_processing.php",
* "deferLoading": 57
* } );
* } );
*
* @example
* // 57 records after filtering, 100 without filtering (an initial filter applied)
* $(document).ready( function() {
* $('#example').dataTable( {
* "serverSide": true,
* "ajax": "scripts/server_processing.php",
* "deferLoading": [ 57, 100 ],
* "search": {
* "search": "my_filter"
* }
* } );
* } );
*/
"iDeferLoading": null,
/**
* Number of rows to display on a single page when using pagination. If
* feature enabled (`lengthChange`) then the end user will be able to override
* this to a custom setting using a pop-up menu.
* @type int
* @default 10
*
* @dtopt Options
* @name DataTable.defaults.pageLength
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "pageLength": 50
* } );
* } )
*/
"iDisplayLength": 10,
/**
* Define the starting point for data display when using DataTables with
* pagination. Note that this parameter is the number of records, rather than
* the page number, so if you have 10 records per page and want to start on
* the third page, it should be "20".
* @type int
* @default 0
*
* @dtopt Options
* @name DataTable.defaults.displayStart
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "displayStart": 20
* } );
* } )
*/
"iDisplayStart": 0,
/**
* By default DataTables allows keyboard navigation of the table (sorting, paging,
* and filtering) by adding a `tabindex` attribute to the required elements. This
* allows you to tab through the controls and press the enter key to activate them.
* The tabindex is default 0, meaning that the tab follows the flow of the document.
* You can overrule this using this parameter if you wish. Use a value of -1 to
* disable built-in keyboard navigation.
* @type int
* @default 0
*
* @dtopt Options
* @name DataTable.defaults.tabIndex
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "tabIndex": 1
* } );
* } );
*/
"iTabIndex": 0,
/**
* Classes that DataTables assigns to the various components and features
* that it adds to the HTML table. This allows classes to be configured
* during initialisation in addition to through the static
* {@link DataTable.ext.oStdClasses} object).
* @namespace
* @name DataTable.defaults.classes
*/
"oClasses": {},
/**
* All strings that DataTables uses in the user interface that it creates
* are defined in this object, allowing you to modified them individually or
* completely replace them all as required.
* @namespace
* @name DataTable.defaults.language
*/
"oLanguage": {
/**
* Strings that are used for WAI-ARIA labels and controls only (these are not
* actually visible on the page, but will be read by screenreaders, and thus
* must be internationalised as well).
* @namespace
* @name DataTable.defaults.language.aria
*/
"oAria": {
/**
* ARIA label that is added to the table headers when the column may be
* sorted ascending by activing the column (click or return when focused).
* Note that the column header is prefixed to this string.
* @type string
* @default : activate to sort column ascending
*
* @dtopt Language
* @name DataTable.defaults.language.aria.sortAscending
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "aria": {
* "sortAscending": " - click/return to sort ascending"
* }
* }
* } );
* } );
*/
"sSortAscending": ": activate to sort column ascending",
/**
* ARIA label that is added to the table headers when the column may be
* sorted descending by activing the column (click or return when focused).
* Note that the column header is prefixed to this string.
* @type string
* @default : activate to sort column ascending
*
* @dtopt Language
* @name DataTable.defaults.language.aria.sortDescending
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "aria": {
* "sortDescending": " - click/return to sort descending"
* }
* }
* } );
* } );
*/
"sSortDescending": ": activate to sort column descending"
},
/**
* Pagination string used by DataTables for the built-in pagination
* control types.
* @namespace
* @name DataTable.defaults.language.paginate
*/
"oPaginate": {
/**
* Text to use when using the 'full_numbers' type of pagination for the
* button to take the user to the first page.
* @type string
* @default First
*
* @dtopt Language
* @name DataTable.defaults.language.paginate.first
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "paginate": {
* "first": "First page"
* }
* }
* } );
* } );
*/
"sFirst": "First",
/**
* Text to use when using the 'full_numbers' type of pagination for the
* button to take the user to the last page.
* @type string
* @default Last
*
* @dtopt Language
* @name DataTable.defaults.language.paginate.last
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "paginate": {
* "last": "Last page"
* }
* }
* } );
* } );
*/
"sLast": "Last",
/**
* Text to use for the 'next' pagination button (to take the user to the
* next page).
* @type string
* @default Next
*
* @dtopt Language
* @name DataTable.defaults.language.paginate.next
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "paginate": {
* "next": "Next page"
* }
* }
* } );
* } );
*/
"sNext": "Next",
/**
* Text to use for the 'previous' pagination button (to take the user to
* the previous page).
* @type string
* @default Previous
*
* @dtopt Language
* @name DataTable.defaults.language.paginate.previous
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "paginate": {
* "previous": "Previous page"
* }
* }
* } );
* } );
*/
"sPrevious": "Previous"
},
/**
* This string is shown in preference to `zeroRecords` when the table is
* empty of data (regardless of filtering). Note that this is an optional
* parameter - if it is not given, the value of `zeroRecords` will be used
* instead (either the default or given value).
* @type string
* @default No data available in table
*
* @dtopt Language
* @name DataTable.defaults.language.emptyTable
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "emptyTable": "No data available in table"
* }
* } );
* } );
*/
"sEmptyTable": "No data available in table",
/**
* This string gives information to the end user about the information
* that is current on display on the page. The following tokens can be
* used in the string and will be dynamically replaced as the table
* display updates. This tokens can be placed anywhere in the string, or
* removed as needed by the language requires:
*
* * `\_START\_` - Display index of the first record on the current page
* * `\_END\_` - Display index of the last record on the current page
* * `\_TOTAL\_` - Number of records in the table after filtering
* * `\_MAX\_` - Number of records in the table without filtering
* * `\_PAGE\_` - Current page number
* * `\_PAGES\_` - Total number of pages of data in the table
*
* @type string
* @default Showing _START_ to _END_ of _TOTAL_ entries
*
* @dtopt Language
* @name DataTable.defaults.language.info
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "info": "Showing page _PAGE_ of _PAGES_"
* }
* } );
* } );
*/
"sInfo": "Showing _START_ to _END_ of _TOTAL_ entries",
/**
* Display information string for when the table is empty. Typically the
* format of this string should match `info`.
* @type string
* @default Showing 0 to 0 of 0 entries
*
* @dtopt Language
* @name DataTable.defaults.language.infoEmpty
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "infoEmpty": "No entries to show"
* }
* } );
* } );
*/
"sInfoEmpty": "Showing 0 to 0 of 0 entries",
/**
* When a user filters the information in a table, this string is appended
* to the information (`info`) to give an idea of how strong the filtering
* is. The variable _MAX_ is dynamically updated.
* @type string
* @default (filtered from _MAX_ total entries)
*
* @dtopt Language
* @name DataTable.defaults.language.infoFiltered
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "infoFiltered": " - filtering from _MAX_ records"
* }
* } );
* } );
*/
"sInfoFiltered": "(filtered from _MAX_ total entries)",
/**
* If can be useful to append extra information to the info string at times,
* and this variable does exactly that. This information will be appended to
* the `info` (`infoEmpty` and `infoFiltered` in whatever combination they are
* being used) at all times.
* @type string
* @default <i>Empty string</i>
*
* @dtopt Language
* @name DataTable.defaults.language.infoPostFix
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "infoPostFix": "All records shown are derived from real information."
* }
* } );
* } );
*/
"sInfoPostFix": "",
/**
* This decimal place operator is a little different from the other
* language options since DataTables doesn't output floating point
* numbers, so it won't ever use this for display of a number. Rather,
* what this parameter does is modify the sort methods of the table so
* that numbers which are in a format which has a character other than
* a period (`.`) as a decimal place will be sorted numerically.
*
* Note that numbers with different decimal places cannot be shown in
* the same table and still be sortable, the table must be consistent.
* However, multiple different tables on the page can use different
* decimal place characters.
* @type string
* @default
*
* @dtopt Language
* @name DataTable.defaults.language.decimal
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "decimal": ","
* "thousands": "."
* }
* } );
* } );
*/
"sDecimal": "",
/**
* DataTables has a build in number formatter (`formatNumber`) which is
* used to format large numbers that are used in the table information.
* By default a comma is used, but this can be trivially changed to any
* character you wish with this parameter.
* @type string
* @default ,
*
* @dtopt Language
* @name DataTable.defaults.language.thousands
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "thousands": "'"
* }
* } );
* } );
*/
"sThousands": ",",
/**
* Detail the action that will be taken when the drop down menu for the
* pagination length option is changed. The '_MENU_' variable is replaced
* with a default select list of 10, 25, 50 and 100, and can be replaced
* with a custom select box if required.
* @type string
* @default Show _MENU_ entries
*
* @dtopt Language
* @name DataTable.defaults.language.lengthMenu
*
* @example
* // Language change only
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "lengthMenu": "Display _MENU_ records"
* }
* } );
* } );
*
* @example
* // Language and options change
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "lengthMenu": 'Display <select>'+
* '<option value="10">10</option>'+
* '<option value="20">20</option>'+
* '<option value="30">30</option>'+
* '<option value="40">40</option>'+
* '<option value="50">50</option>'+
* '<option value="-1">All</option>'+
* '</select> records'
* }
* } );
* } );
*/
"sLengthMenu": "Show _MENU_ entries",
/**
* When using Ajax sourced data and during the first draw when DataTables is
* gathering the data, this message is shown in an empty row in the table to
* indicate to the end user the the data is being loaded. Note that this
* parameter is not used when loading data by server-side processing, just
* Ajax sourced data with client-side processing.
* @type string
* @default Loading...
*
* @dtopt Language
* @name DataTable.defaults.language.loadingRecords
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "loadingRecords": "Please wait - loading..."
* }
* } );
* } );
*/
"sLoadingRecords": "Loading...",
/**
* Text which is displayed when the table is processing a user action
* (usually a sort command or similar).
* @type string
* @default Processing...
*
* @dtopt Language
* @name DataTable.defaults.language.processing
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "processing": "DataTables is currently busy"
* }
* } );
* } );
*/
"sProcessing": "Processing...",
/**
* Details the actions that will be taken when the user types into the
* filtering input text box. The variable "_INPUT_", if used in the string,
* is replaced with the HTML text box for the filtering input allowing
* control over where it appears in the string. If "_INPUT_" is not given
* then the input box is appended to the string automatically.
* @type string
* @default Search:
*
* @dtopt Language
* @name DataTable.defaults.language.search
*
* @example
* // Input text box will be appended at the end automatically
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "search": "Filter records:"
* }
* } );
* } );
*
* @example
* // Specify where the filter should appear
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "search": "Apply filter _INPUT_ to table"
* }
* } );
* } );
*/
"sSearch": "Search:",
/**
* Assign a `placeholder` attribute to the search `input` element
* @type string
* @default
*
* @dtopt Language
* @name DataTable.defaults.language.searchPlaceholder
*/
"sSearchPlaceholder": "",
/**
* All of the language information can be stored in a file on the
* server-side, which DataTables will look up if this parameter is passed.
* It must store the URL of the language file, which is in a JSON format,
* and the object has the same properties as the oLanguage object in the
* initialiser object (i.e. the above parameters). Please refer to one of
* the example language files to see how this works in action.
* @type string
* @default <i>Empty string - i.e. disabled</i>
*
* @dtopt Language
* @name DataTable.defaults.language.url
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "url": "http://www.sprymedia.co.uk/dataTables/lang.txt"
* }
* } );
* } );
*/
"sUrl": "",
/**
* Text shown inside the table records when the is no information to be
* displayed after filtering. `emptyTable` is shown when there is simply no
* information in the table at all (regardless of filtering).
* @type string
* @default No matching records found
*
* @dtopt Language
* @name DataTable.defaults.language.zeroRecords
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "language": {
* "zeroRecords": "No records to display"
* }
* } );
* } );
*/
"sZeroRecords": "No matching records found"
},
/**
* This parameter allows you to have define the global filtering state at
* initialisation time. As an object the `search` parameter must be
* defined, but all other parameters are optional. When `regex` is true,
* the search string will be treated as a regular expression, when false
* (default) it will be treated as a straight string. When `smart`
* DataTables will use it's smart filtering methods (to word match at
* any point in the data), when false this will not be done.
* @namespace
* @extends DataTable.models.oSearch
*
* @dtopt Options
* @name DataTable.defaults.search
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "search": {"search": "Initial search"}
* } );
* } )
*/
"oSearch": $.extend( {}, DataTable.models.oSearch ),
/**
* __Deprecated__ The functionality provided by this parameter has now been
* superseded by that provided through `ajax`, which should be used instead.
*
* By default DataTables will look for the property `data` (or `aaData` for
* compatibility with DataTables 1.9-) when obtaining data from an Ajax
* source or for server-side processing - this parameter allows that
* property to be changed. You can use Javascript dotted object notation to
* get a data source for multiple levels of nesting.
* @type string
* @default data
*
* @dtopt Options
* @dtopt Server-side
* @name DataTable.defaults.ajaxDataProp
*
* @deprecated 1.10. Please use `ajax` for this functionality now.
*/
"sAjaxDataProp": "data",
/**
* __Deprecated__ The functionality provided by this parameter has now been
* superseded by that provided through `ajax`, which should be used instead.
*
* You can instruct DataTables to load data from an external
* source using this parameter (use aData if you want to pass data in you
* already have). Simply provide a url a JSON object can be obtained from.
* @type string
* @default null
*
* @dtopt Options
* @dtopt Server-side
* @name DataTable.defaults.ajaxSource
*
* @deprecated 1.10. Please use `ajax` for this functionality now.
*/
"sAjaxSource": null,
/**
* This initialisation variable allows you to specify exactly where in the
* DOM you want DataTables to inject the various controls it adds to the page
* (for example you might want the pagination controls at the top of the
* table). DIV elements (with or without a custom class) can also be added to
* aid styling. The follow syntax is used:
* <ul>
* <li>The following options are allowed:
* <ul>
* <li>'l' - Length changing</li>
* <li>'f' - Filtering input</li>
* <li>'t' - The table!</li>
* <li>'i' - Information</li>
* <li>'p' - Pagination</li>
* <li>'r' - pRocessing</li>
* </ul>
* </li>
* <li>The following constants are allowed:
* <ul>
* <li>'H' - jQueryUI theme "header" classes ('fg-toolbar ui-widget-header ui-corner-tl ui-corner-tr ui-helper-clearfix')</li>
* <li>'F' - jQueryUI theme "footer" classes ('fg-toolbar ui-widget-header ui-corner-bl ui-corner-br ui-helper-clearfix')</li>
* </ul>
* </li>
* <li>The following syntax is expected:
* <ul>
* <li>'<' and '>' - div elements</li>
* <li>'<"class" and '>' - div with a class</li>
* <li>'<"#id" and '>' - div with an ID</li>
* </ul>
* </li>
* <li>Examples:
* <ul>
* <li>'<"wrapper"flipt>'</li>
* <li>'<lf<t>ip>'</li>
* </ul>
* </li>
* </ul>
* @type string
* @default lfrtip <i>(when `jQueryUI` is false)</i> <b>or</b>
* <"H"lfr>t<"F"ip> <i>(when `jQueryUI` is true)</i>
*
* @dtopt Options
* @name DataTable.defaults.dom
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "dom": '<"top"i>rt<"bottom"flp><"clear">'
* } );
* } );
*/
"sDom": "lfrtip",
/**
* Search delay option. This will throttle full table searches that use the
* DataTables provided search input element (it does not effect calls to
* `dt-api search()`, providing a delay before the search is made.
* @type integer
* @default 0
*
* @dtopt Options
* @name DataTable.defaults.searchDelay
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "searchDelay": 200
* } );
* } )
*/
"searchDelay": null,
/**
* DataTables features six different built-in options for the buttons to
* display for pagination control:
*
* * `numbers` - Page number buttons only
* * `simple` - 'Previous' and 'Next' buttons only
* * 'simple_numbers` - 'Previous' and 'Next' buttons, plus page numbers
* * `full` - 'First', 'Previous', 'Next' and 'Last' buttons
* * `full_numbers` - 'First', 'Previous', 'Next' and 'Last' buttons, plus page numbers
* * `first_last_numbers` - 'First' and 'Last' buttons, plus page numbers
*
* Further methods can be added using {@link DataTable.ext.oPagination}.
* @type string
* @default simple_numbers
*
* @dtopt Options
* @name DataTable.defaults.pagingType
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "pagingType": "full_numbers"
* } );
* } )
*/
"sPaginationType": "simple_numbers",
/**
* Enable horizontal scrolling. When a table is too wide to fit into a
* certain layout, or you have a large number of columns in the table, you
* can enable x-scrolling to show the table in a viewport, which can be
* scrolled. This property can be `true` which will allow the table to
* scroll horizontally when needed, or any CSS unit, or a number (in which
* case it will be treated as a pixel measurement). Setting as simply `true`
* is recommended.
* @type boolean|string
* @default <i>blank string - i.e. disabled</i>
*
* @dtopt Features
* @name DataTable.defaults.scrollX
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "scrollX": true,
* "scrollCollapse": true
* } );
* } );
*/
"sScrollX": "",
/**
* This property can be used to force a DataTable to use more width than it
* might otherwise do when x-scrolling is enabled. For example if you have a
* table which requires to be well spaced, this parameter is useful for
* "over-sizing" the table, and thus forcing scrolling. This property can by
* any CSS unit, or a number (in which case it will be treated as a pixel
* measurement).
* @type string
* @default <i>blank string - i.e. disabled</i>
*
* @dtopt Options
* @name DataTable.defaults.scrollXInner
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "scrollX": "100%",
* "scrollXInner": "110%"
* } );
* } );
*/
"sScrollXInner": "",
/**
* Enable vertical scrolling. Vertical scrolling will constrain the DataTable
* to the given height, and enable scrolling for any data which overflows the
* current viewport. This can be used as an alternative to paging to display
* a lot of data in a small area (although paging and scrolling can both be
* enabled at the same time). This property can be any CSS unit, or a number
* (in which case it will be treated as a pixel measurement).
* @type string
* @default <i>blank string - i.e. disabled</i>
*
* @dtopt Features
* @name DataTable.defaults.scrollY
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "scrollY": "200px",
* "paginate": false
* } );
* } );
*/
"sScrollY": "",
/**
* __Deprecated__ The functionality provided by this parameter has now been
* superseded by that provided through `ajax`, which should be used instead.
*
* Set the HTTP method that is used to make the Ajax call for server-side
* processing or Ajax sourced data.
* @type string
* @default GET
*
* @dtopt Options
* @dtopt Server-side
* @name DataTable.defaults.serverMethod
*
* @deprecated 1.10. Please use `ajax` for this functionality now.
*/
"sServerMethod": "GET",
/**
* DataTables makes use of renderers when displaying HTML elements for
* a table. These renderers can be added or modified by plug-ins to
* generate suitable mark-up for a site. For example the Bootstrap
* integration plug-in for DataTables uses a paging button renderer to
* display pagination buttons in the mark-up required by Bootstrap.
*
* For further information about the renderers available see
* DataTable.ext.renderer
* @type string|object
* @default null
*
* @name DataTable.defaults.renderer
*
*/
"renderer": null,
/**
* Set the data property name that DataTables should use to get a row's id
* to set as the `id` property in the node.
* @type string
* @default DT_RowId
*
* @name DataTable.defaults.rowId
*/
"rowId": "DT_RowId"
};
_fnHungarianMap( DataTable.defaults );
/*
* Developer note - See note in model.defaults.js about the use of Hungarian
* notation and camel case.
*/
/**
* Column options that can be given to DataTables at initialisation time.
* @namespace
*/
DataTable.defaults.column = {
/**
* Define which column(s) an order will occur on for this column. This
* allows a column's ordering to take multiple columns into account when
* doing a sort or use the data from a different column. For example first
* name / last name columns make sense to do a multi-column sort over the
* two columns.
* @type array|int
* @default null <i>Takes the value of the column index automatically</i>
*
* @name DataTable.defaults.column.orderData
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "orderData": [ 0, 1 ], "targets": [ 0 ] },
* { "orderData": [ 1, 0 ], "targets": [ 1 ] },
* { "orderData": 2, "targets": [ 2 ] }
* ]
* } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* { "orderData": [ 0, 1 ] },
* { "orderData": [ 1, 0 ] },
* { "orderData": 2 },
* null,
* null
* ]
* } );
* } );
*/
"aDataSort": null,
"iDataSort": -1,
/**
* You can control the default ordering direction, and even alter the
* behaviour of the sort handler (i.e. only allow ascending ordering etc)
* using this parameter.
* @type array
* @default [ 'asc', 'desc' ]
*
* @name DataTable.defaults.column.orderSequence
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "orderSequence": [ "asc" ], "targets": [ 1 ] },
* { "orderSequence": [ "desc", "asc", "asc" ], "targets": [ 2 ] },
* { "orderSequence": [ "desc" ], "targets": [ 3 ] }
* ]
* } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* null,
* { "orderSequence": [ "asc" ] },
* { "orderSequence": [ "desc", "asc", "asc" ] },
* { "orderSequence": [ "desc" ] },
* null
* ]
* } );
* } );
*/
"asSorting": [ 'asc', 'desc' ],
/**
* Enable or disable filtering on the data in this column.
* @type boolean
* @default true
*
* @name DataTable.defaults.column.searchable
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "searchable": false, "targets": [ 0 ] }
* ] } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* { "searchable": false },
* null,
* null,
* null,
* null
* ] } );
* } );
*/
"bSearchable": true,
/**
* Enable or disable ordering on this column.
* @type boolean
* @default true
*
* @name DataTable.defaults.column.orderable
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "orderable": false, "targets": [ 0 ] }
* ] } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* { "orderable": false },
* null,
* null,
* null,
* null
* ] } );
* } );
*/
"bSortable": true,
/**
* Enable or disable the display of this column.
* @type boolean
* @default true
*
* @name DataTable.defaults.column.visible
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "visible": false, "targets": [ 0 ] }
* ] } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* { "visible": false },
* null,
* null,
* null,
* null
* ] } );
* } );
*/
"bVisible": true,
/**
* Developer definable function that is called whenever a cell is created (Ajax source,
* etc) or processed for input (DOM source). This can be used as a compliment to mRender
* allowing you to modify the DOM element (add background colour for example) when the
* element is available.
* @type function
* @param {element} td The TD node that has been created
* @param {*} cellData The Data for the cell
* @param {array|object} rowData The data for the whole row
* @param {int} row The row index for the aoData data store
* @param {int} col The column index for aoColumns
*
* @name DataTable.defaults.column.createdCell
* @dtopt Columns
*
* @example
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [ {
* "targets": [3],
* "createdCell": function (td, cellData, rowData, row, col) {
* if ( cellData == "1.7" ) {
* $(td).css('color', 'blue')
* }
* }
* } ]
* });
* } );
*/
"fnCreatedCell": null,
/**
* This parameter has been replaced by `data` in DataTables to ensure naming
* consistency. `dataProp` can still be used, as there is backwards
* compatibility in DataTables for this option, but it is strongly
* recommended that you use `data` in preference to `dataProp`.
* @name DataTable.defaults.column.dataProp
*/
/**
* This property can be used to read data from any data source property,
* including deeply nested objects / properties. `data` can be given in a
* number of different ways which effect its behaviour:
*
* * `integer` - treated as an array index for the data source. This is the
* default that DataTables uses (incrementally increased for each column).
* * `string` - read an object property from the data source. There are
* three 'special' options that can be used in the string to alter how
* DataTables reads the data from the source object:
* * `.` - Dotted Javascript notation. Just as you use a `.` in
* Javascript to read from nested objects, so to can the options
* specified in `data`. For example: `browser.version` or
* `browser.name`. If your object parameter name contains a period, use
* `\\` to escape it - i.e. `first\\.name`.
* * `[]` - Array notation. DataTables can automatically combine data
* from and array source, joining the data with the characters provided
* between the two brackets. For example: `name[, ]` would provide a
* comma-space separated list from the source array. If no characters
* are provided between the brackets, the original array source is
* returned.
* * `()` - Function notation. Adding `()` to the end of a parameter will
* execute a function of the name given. For example: `browser()` for a
* simple function on the data source, `browser.version()` for a
* function in a nested property or even `browser().version` to get an
* object property if the function called returns an object. Note that
* function notation is recommended for use in `render` rather than
* `data` as it is much simpler to use as a renderer.
* * `null` - use the original data source for the row rather than plucking
* data directly from it. This action has effects on two other
* initialisation options:
* * `defaultContent` - When null is given as the `data` option and
* `defaultContent` is specified for the column, the value defined by
* `defaultContent` will be used for the cell.
* * `render` - When null is used for the `data` option and the `render`
* option is specified for the column, the whole data source for the
* row is used for the renderer.
* * `function` - the function given will be executed whenever DataTables
* needs to set or get the data for a cell in the column. The function
* takes three parameters:
* * Parameters:
* * `{array|object}` The data source for the row
* * `{string}` The type call data requested - this will be 'set' when
* setting data or 'filter', 'display', 'type', 'sort' or undefined
* when gathering data. Note that when `undefined` is given for the
* type DataTables expects to get the raw data for the object back<
* * `{*}` Data to set when the second parameter is 'set'.
* * Return:
* * The return value from the function is not required when 'set' is
* the type of call, but otherwise the return is what will be used
* for the data requested.
*
* Note that `data` is a getter and setter option. If you just require
* formatting of data for output, you will likely want to use `render` which
* is simply a getter and thus simpler to use.
*
* Note that prior to DataTables 1.9.2 `data` was called `mDataProp`. The
* name change reflects the flexibility of this property and is consistent
* with the naming of mRender. If 'mDataProp' is given, then it will still
* be used by DataTables, as it automatically maps the old name to the new
* if required.
*
* @type string|int|function|null
* @default null <i>Use automatically calculated column index</i>
*
* @name DataTable.defaults.column.data
* @dtopt Columns
*
* @example
* // Read table data from objects
* // JSON structure for each row:
* // {
* // "engine": {value},
* // "browser": {value},
* // "platform": {value},
* // "version": {value},
* // "grade": {value}
* // }
* $(document).ready( function() {
* $('#example').dataTable( {
* "ajaxSource": "sources/objects.txt",
* "columns": [
* { "data": "engine" },
* { "data": "browser" },
* { "data": "platform" },
* { "data": "version" },
* { "data": "grade" }
* ]
* } );
* } );
*
* @example
* // Read information from deeply nested objects
* // JSON structure for each row:
* // {
* // "engine": {value},
* // "browser": {value},
* // "platform": {
* // "inner": {value}
* // },
* // "details": [
* // {value}, {value}
* // ]
* // }
* $(document).ready( function() {
* $('#example').dataTable( {
* "ajaxSource": "sources/deep.txt",
* "columns": [
* { "data": "engine" },
* { "data": "browser" },
* { "data": "platform.inner" },
* { "data": "details.0" },
* { "data": "details.1" }
* ]
* } );
* } );
*
* @example
* // Using `data` as a function to provide different information for
* // sorting, filtering and display. In this case, currency (price)
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [ {
* "targets": [ 0 ],
* "data": function ( source, type, val ) {
* if (type === 'set') {
* source.price = val;
* // Store the computed dislay and filter values for efficiency
* source.price_display = val=="" ? "" : "$"+numberFormat(val);
* source.price_filter = val=="" ? "" : "$"+numberFormat(val)+" "+val;
* return;
* }
* else if (type === 'display') {
* return source.price_display;
* }
* else if (type === 'filter') {
* return source.price_filter;
* }
* // 'sort', 'type' and undefined all just use the integer
* return source.price;
* }
* } ]
* } );
* } );
*
* @example
* // Using default content
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [ {
* "targets": [ 0 ],
* "data": null,
* "defaultContent": "Click to edit"
* } ]
* } );
* } );
*
* @example
* // Using array notation - outputting a list from an array
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [ {
* "targets": [ 0 ],
* "data": "name[, ]"
* } ]
* } );
* } );
*
*/
"mData": null,
/**
* This property is the rendering partner to `data` and it is suggested that
* when you want to manipulate data for display (including filtering,
* sorting etc) without altering the underlying data for the table, use this
* property. `render` can be considered to be the the read only companion to
* `data` which is read / write (then as such more complex). Like `data`
* this option can be given in a number of different ways to effect its
* behaviour:
*
* * `integer` - treated as an array index for the data source. This is the
* default that DataTables uses (incrementally increased for each column).
* * `string` - read an object property from the data source. There are
* three 'special' options that can be used in the string to alter how
* DataTables reads the data from the source object:
* * `.` - Dotted Javascript notation. Just as you use a `.` in
* Javascript to read from nested objects, so to can the options
* specified in `data`. For example: `browser.version` or
* `browser.name`. If your object parameter name contains a period, use
* `\\` to escape it - i.e. `first\\.name`.
* * `[]` - Array notation. DataTables can automatically combine data
* from and array source, joining the data with the characters provided
* between the two brackets. For example: `name[, ]` would provide a
* comma-space separated list from the source array. If no characters
* are provided between the brackets, the original array source is
* returned.
* * `()` - Function notation. Adding `()` to the end of a parameter will
* execute a function of the name given. For example: `browser()` for a
* simple function on the data source, `browser.version()` for a
* function in a nested property or even `browser().version` to get an
* object property if the function called returns an object.
* * `object` - use different data for the different data types requested by
* DataTables ('filter', 'display', 'type' or 'sort'). The property names
* of the object is the data type the property refers to and the value can
* defined using an integer, string or function using the same rules as
* `render` normally does. Note that an `_` option _must_ be specified.
* This is the default value to use if you haven't specified a value for
* the data type requested by DataTables.
* * `function` - the function given will be executed whenever DataTables
* needs to set or get the data for a cell in the column. The function
* takes three parameters:
* * Parameters:
* * {array|object} The data source for the row (based on `data`)
* * {string} The type call data requested - this will be 'filter',
* 'display', 'type' or 'sort'.
* * {array|object} The full data source for the row (not based on
* `data`)
* * Return:
* * The return value from the function is what will be used for the
* data requested.
*
* @type string|int|function|object|null
* @default null Use the data source value.
*
* @name DataTable.defaults.column.render
* @dtopt Columns
*
* @example
* // Create a comma separated list from an array of objects
* $(document).ready( function() {
* $('#example').dataTable( {
* "ajaxSource": "sources/deep.txt",
* "columns": [
* { "data": "engine" },
* { "data": "browser" },
* {
* "data": "platform",
* "render": "[, ].name"
* }
* ]
* } );
* } );
*
* @example
* // Execute a function to obtain data
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [ {
* "targets": [ 0 ],
* "data": null, // Use the full data source object for the renderer's source
* "render": "browserName()"
* } ]
* } );
* } );
*
* @example
* // As an object, extracting different data for the different types
* // This would be used with a data source such as:
* // { "phone": 5552368, "phone_filter": "5552368 555-2368", "phone_display": "555-2368" }
* // Here the `phone` integer is used for sorting and type detection, while `phone_filter`
* // (which has both forms) is used for filtering for if a user inputs either format, while
* // the formatted phone number is the one that is shown in the table.
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [ {
* "targets": [ 0 ],
* "data": null, // Use the full data source object for the renderer's source
* "render": {
* "_": "phone",
* "filter": "phone_filter",
* "display": "phone_display"
* }
* } ]
* } );
* } );
*
* @example
* // Use as a function to create a link from the data source
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [ {
* "targets": [ 0 ],
* "data": "download_link",
* "render": function ( data, type, full ) {
* return '<a href="'+data+'">Download</a>';
* }
* } ]
* } );
* } );
*/
"mRender": null,
/**
* Change the cell type created for the column - either TD cells or TH cells. This
* can be useful as TH cells have semantic meaning in the table body, allowing them
* to act as a header for a row (you may wish to add scope='row' to the TH elements).
* @type string
* @default td
*
* @name DataTable.defaults.column.cellType
* @dtopt Columns
*
* @example
* // Make the first column use TH cells
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [ {
* "targets": [ 0 ],
* "cellType": "th"
* } ]
* } );
* } );
*/
"sCellType": "td",
/**
* Class to give to each cell in this column.
* @type string
* @default <i>Empty string</i>
*
* @name DataTable.defaults.column.class
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "class": "my_class", "targets": [ 0 ] }
* ]
* } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* { "class": "my_class" },
* null,
* null,
* null,
* null
* ]
* } );
* } );
*/
"sClass": "",
/**
* When DataTables calculates the column widths to assign to each column,
* it finds the longest string in each column and then constructs a
* temporary table and reads the widths from that. The problem with this
* is that "mmm" is much wider then "iiii", but the latter is a longer
* string - thus the calculation can go wrong (doing it properly and putting
* it into an DOM object and measuring that is horribly(!) slow). Thus as
* a "work around" we provide this option. It will append its value to the
* text that is found to be the longest string for the column - i.e. padding.
* Generally you shouldn't need this!
* @type string
* @default <i>Empty string<i>
*
* @name DataTable.defaults.column.contentPadding
* @dtopt Columns
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* null,
* null,
* null,
* {
* "contentPadding": "mmm"
* }
* ]
* } );
* } );
*/
"sContentPadding": "",
/**
* Allows a default value to be given for a column's data, and will be used
* whenever a null data source is encountered (this can be because `data`
* is set to null, or because the data source itself is null).
* @type string
* @default null
*
* @name DataTable.defaults.column.defaultContent
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* {
* "data": null,
* "defaultContent": "Edit",
* "targets": [ -1 ]
* }
* ]
* } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* null,
* null,
* null,
* {
* "data": null,
* "defaultContent": "Edit"
* }
* ]
* } );
* } );
*/
"sDefaultContent": null,
/**
* This parameter is only used in DataTables' server-side processing. It can
* be exceptionally useful to know what columns are being displayed on the
* client side, and to map these to database fields. When defined, the names
* also allow DataTables to reorder information from the server if it comes
* back in an unexpected order (i.e. if you switch your columns around on the
* client-side, your server-side code does not also need updating).
* @type string
* @default <i>Empty string</i>
*
* @name DataTable.defaults.column.name
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "name": "engine", "targets": [ 0 ] },
* { "name": "browser", "targets": [ 1 ] },
* { "name": "platform", "targets": [ 2 ] },
* { "name": "version", "targets": [ 3 ] },
* { "name": "grade", "targets": [ 4 ] }
* ]
* } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* { "name": "engine" },
* { "name": "browser" },
* { "name": "platform" },
* { "name": "version" },
* { "name": "grade" }
* ]
* } );
* } );
*/
"sName": "",
/**
* Defines a data source type for the ordering which can be used to read
* real-time information from the table (updating the internally cached
* version) prior to ordering. This allows ordering to occur on user
* editable elements such as form inputs.
* @type string
* @default std
*
* @name DataTable.defaults.column.orderDataType
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "orderDataType": "dom-text", "targets": [ 2, 3 ] },
* { "type": "numeric", "targets": [ 3 ] },
* { "orderDataType": "dom-select", "targets": [ 4 ] },
* { "orderDataType": "dom-checkbox", "targets": [ 5 ] }
* ]
* } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* null,
* null,
* { "orderDataType": "dom-text" },
* { "orderDataType": "dom-text", "type": "numeric" },
* { "orderDataType": "dom-select" },
* { "orderDataType": "dom-checkbox" }
* ]
* } );
* } );
*/
"sSortDataType": "std",
/**
* The title of this column.
* @type string
* @default null <i>Derived from the 'TH' value for this column in the
* original HTML table.</i>
*
* @name DataTable.defaults.column.title
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "title": "My column title", "targets": [ 0 ] }
* ]
* } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* { "title": "My column title" },
* null,
* null,
* null,
* null
* ]
* } );
* } );
*/
"sTitle": null,
/**
* The type allows you to specify how the data for this column will be
* ordered. Four types (string, numeric, date and html (which will strip
* HTML tags before ordering)) are currently available. Note that only date
* formats understood by Javascript's Date() object will be accepted as type
* date. For example: "Mar 26, 2008 5:03 PM". May take the values: 'string',
* 'numeric', 'date' or 'html' (by default). Further types can be adding
* through plug-ins.
* @type string
* @default null <i>Auto-detected from raw data</i>
*
* @name DataTable.defaults.column.type
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "type": "html", "targets": [ 0 ] }
* ]
* } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* { "type": "html" },
* null,
* null,
* null,
* null
* ]
* } );
* } );
*/
"sType": null,
/**
* Defining the width of the column, this parameter may take any CSS value
* (3em, 20px etc). DataTables applies 'smart' widths to columns which have not
* been given a specific width through this interface ensuring that the table
* remains readable.
* @type string
* @default null <i>Automatic</i>
*
* @name DataTable.defaults.column.width
* @dtopt Columns
*
* @example
* // Using `columnDefs`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columnDefs": [
* { "width": "20%", "targets": [ 0 ] }
* ]
* } );
* } );
*
* @example
* // Using `columns`
* $(document).ready( function() {
* $('#example').dataTable( {
* "columns": [
* { "width": "20%" },
* null,
* null,
* null,
* null
* ]
* } );
* } );
*/
"sWidth": null
};
_fnHungarianMap( DataTable.defaults.column );
/**
* DataTables settings object - this holds all the information needed for a
* given table, including configuration, data and current application of the
* table options. DataTables does not have a single instance for each DataTable
* with the settings attached to that instance, but rather instances of the
* DataTable "class" are created on-the-fly as needed (typically by a
* $().dataTable() call) and the settings object is then applied to that
* instance.
*
* Note that this object is related to {@link DataTable.defaults} but this
* one is the internal data store for DataTables's cache of columns. It should
* NOT be manipulated outside of DataTables. Any configuration should be done
* through the initialisation options.
* @namespace
* @todo Really should attach the settings object to individual instances so we
* don't need to create new instances on each $().dataTable() call (if the
* table already exists). It would also save passing oSettings around and
* into every single function. However, this is a very significant
* architecture change for DataTables and will almost certainly break
* backwards compatibility with older installations. This is something that
* will be done in 2.0.
*/
DataTable.models.oSettings = {
/**
* Primary features of DataTables and their enablement state.
* @namespace
*/
"oFeatures": {
/**
* Flag to say if DataTables should automatically try to calculate the
* optimum table and columns widths (true) or not (false).
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bAutoWidth": null,
/**
* Delay the creation of TR and TD elements until they are actually
* needed by a driven page draw. This can give a significant speed
* increase for Ajax source and Javascript source data, but makes no
* difference at all fro DOM and server-side processing tables.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bDeferRender": null,
/**
* Enable filtering on the table or not. Note that if this is disabled
* then there is no filtering at all on the table, including fnFilter.
* To just remove the filtering input use sDom and remove the 'f' option.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bFilter": null,
/**
* Table information element (the 'Showing x of y records' div) enable
* flag.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bInfo": null,
/**
* Present a user control allowing the end user to change the page size
* when pagination is enabled.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bLengthChange": null,
/**
* Pagination enabled or not. Note that if this is disabled then length
* changing must also be disabled.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bPaginate": null,
/**
* Processing indicator enable flag whenever DataTables is enacting a
* user request - typically an Ajax request for server-side processing.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bProcessing": null,
/**
* Server-side processing enabled flag - when enabled DataTables will
* get all data from the server for every draw - there is no filtering,
* sorting or paging done on the client-side.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bServerSide": null,
/**
* Sorting enablement flag.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bSort": null,
/**
* Multi-column sorting
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bSortMulti": null,
/**
* Apply a class to the columns which are being sorted to provide a
* visual highlight or not. This can slow things down when enabled since
* there is a lot of DOM interaction.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bSortClasses": null,
/**
* State saving enablement flag.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bStateSave": null
},
/**
* Scrolling settings for a table.
* @namespace
*/
"oScroll": {
/**
* When the table is shorter in height than sScrollY, collapse the
* table container down to the height of the table (when true).
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bCollapse": null,
/**
* Width of the scrollbar for the web-browser's platform. Calculated
* during table initialisation.
* @type int
* @default 0
*/
"iBarWidth": 0,
/**
* Viewport width for horizontal scrolling. Horizontal scrolling is
* disabled if an empty string.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
*/
"sX": null,
/**
* Width to expand the table to when using x-scrolling. Typically you
* should not need to use this.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
* @deprecated
*/
"sXInner": null,
/**
* Viewport height for vertical scrolling. Vertical scrolling is disabled
* if an empty string.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
*/
"sY": null
},
/**
* Language information for the table.
* @namespace
* @extends DataTable.defaults.oLanguage
*/
"oLanguage": {
/**
* Information callback function. See
* {@link DataTable.defaults.fnInfoCallback}
* @type function
* @default null
*/
"fnInfoCallback": null
},
/**
* Browser support parameters
* @namespace
*/
"oBrowser": {
/**
* Indicate if the browser incorrectly calculates width:100% inside a
* scrolling element (IE6/7)
* @type boolean
* @default false
*/
"bScrollOversize": false,
/**
* Determine if the vertical scrollbar is on the right or left of the
* scrolling container - needed for rtl language layout, although not
* all browsers move the scrollbar (Safari).
* @type boolean
* @default false
*/
"bScrollbarLeft": false,
/**
* Flag for if `getBoundingClientRect` is fully supported or not
* @type boolean
* @default false
*/
"bBounding": false,
/**
* Browser scrollbar width
* @type integer
* @default 0
*/
"barWidth": 0
},
"ajax": null,
/**
* Array referencing the nodes which are used for the features. The
* parameters of this object match what is allowed by sDom - i.e.
* <ul>
* <li>'l' - Length changing</li>
* <li>'f' - Filtering input</li>
* <li>'t' - The table!</li>
* <li>'i' - Information</li>
* <li>'p' - Pagination</li>
* <li>'r' - pRocessing</li>
* </ul>
* @type array
* @default []
*/
"aanFeatures": [],
/**
* Store data information - see {@link DataTable.models.oRow} for detailed
* information.
* @type array
* @default []
*/
"aoData": [],
/**
* Array of indexes which are in the current display (after filtering etc)
* @type array
* @default []
*/
"aiDisplay": [],
/**
* Array of indexes for display - no filtering
* @type array
* @default []
*/
"aiDisplayMaster": [],
/**
* Map of row ids to data indexes
* @type object
* @default {}
*/
"aIds": {},
/**
* Store information about each column that is in use
* @type array
* @default []
*/
"aoColumns": [],
/**
* Store information about the table's header
* @type array
* @default []
*/
"aoHeader": [],
/**
* Store information about the table's footer
* @type array
* @default []
*/
"aoFooter": [],
/**
* Store the applied global search information in case we want to force a
* research or compare the old search to a new one.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @namespace
* @extends DataTable.models.oSearch
*/
"oPreviousSearch": {},
/**
* Store the applied search for each column - see
* {@link DataTable.models.oSearch} for the format that is used for the
* filtering information for each column.
* @type array
* @default []
*/
"aoPreSearchCols": [],
/**
* Sorting that is applied to the table. Note that the inner arrays are
* used in the following manner:
* <ul>
* <li>Index 0 - column number</li>
* <li>Index 1 - current sorting direction</li>
* </ul>
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type array
* @todo These inner arrays should really be objects
*/
"aaSorting": null,
/**
* Sorting that is always applied to the table (i.e. prefixed in front of
* aaSorting).
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type array
* @default []
*/
"aaSortingFixed": [],
/**
* Classes to use for the striping of a table.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type array
* @default []
*/
"asStripeClasses": null,
/**
* If restoring a table - we should restore its striping classes as well
* @type array
* @default []
*/
"asDestroyStripes": [],
/**
* If restoring a table - we should restore its width
* @type int
* @default 0
*/
"sDestroyWidth": 0,
/**
* Callback functions array for every time a row is inserted (i.e. on a draw).
* @type array
* @default []
*/
"aoRowCallback": [],
/**
* Callback functions for the header on each draw.
* @type array
* @default []
*/
"aoHeaderCallback": [],
/**
* Callback function for the footer on each draw.
* @type array
* @default []
*/
"aoFooterCallback": [],
/**
* Array of callback functions for draw callback functions
* @type array
* @default []
*/
"aoDrawCallback": [],
/**
* Array of callback functions for row created function
* @type array
* @default []
*/
"aoRowCreatedCallback": [],
/**
* Callback functions for just before the table is redrawn. A return of
* false will be used to cancel the draw.
* @type array
* @default []
*/
"aoPreDrawCallback": [],
/**
* Callback functions for when the table has been initialised.
* @type array
* @default []
*/
"aoInitComplete": [],
/**
* Callbacks for modifying the settings to be stored for state saving, prior to
* saving state.
* @type array
* @default []
*/
"aoStateSaveParams": [],
/**
* Callbacks for modifying the settings that have been stored for state saving
* prior to using the stored values to restore the state.
* @type array
* @default []
*/
"aoStateLoadParams": [],
/**
* Callbacks for operating on the settings object once the saved state has been
* loaded
* @type array
* @default []
*/
"aoStateLoaded": [],
/**
* Cache the table ID for quick access
* @type string
* @default <i>Empty string</i>
*/
"sTableId": "",
/**
* The TABLE node for the main table
* @type node
* @default null
*/
"nTable": null,
/**
* Permanent ref to the thead element
* @type node
* @default null
*/
"nTHead": null,
/**
* Permanent ref to the tfoot element - if it exists
* @type node
* @default null
*/
"nTFoot": null,
/**
* Permanent ref to the tbody element
* @type node
* @default null
*/
"nTBody": null,
/**
* Cache the wrapper node (contains all DataTables controlled elements)
* @type node
* @default null
*/
"nTableWrapper": null,
/**
* Indicate if when using server-side processing the loading of data
* should be deferred until the second draw.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
* @default false
*/
"bDeferLoading": false,
/**
* Indicate if all required information has been read in
* @type boolean
* @default false
*/
"bInitialised": false,
/**
* Information about open rows. Each object in the array has the parameters
* 'nTr' and 'nParent'
* @type array
* @default []
*/
"aoOpenRows": [],
/**
* Dictate the positioning of DataTables' control elements - see
* {@link DataTable.model.oInit.sDom}.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
* @default null
*/
"sDom": null,
/**
* Search delay (in mS)
* @type integer
* @default null
*/
"searchDelay": null,
/**
* Which type of pagination should be used.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
* @default two_button
*/
"sPaginationType": "two_button",
/**
* The state duration (for `stateSave`) in seconds.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type int
* @default 0
*/
"iStateDuration": 0,
/**
* Array of callback functions for state saving. Each array element is an
* object with the following parameters:
* <ul>
* <li>function:fn - function to call. Takes two parameters, oSettings
* and the JSON string to save that has been thus far created. Returns
* a JSON string to be inserted into a json object
* (i.e. '"param": [ 0, 1, 2]')</li>
* <li>string:sName - name of callback</li>
* </ul>
* @type array
* @default []
*/
"aoStateSave": [],
/**
* Array of callback functions for state loading. Each array element is an
* object with the following parameters:
* <ul>
* <li>function:fn - function to call. Takes two parameters, oSettings
* and the object stored. May return false to cancel state loading</li>
* <li>string:sName - name of callback</li>
* </ul>
* @type array
* @default []
*/
"aoStateLoad": [],
/**
* State that was saved. Useful for back reference
* @type object
* @default null
*/
"oSavedState": null,
/**
* State that was loaded. Useful for back reference
* @type object
* @default null
*/
"oLoadedState": null,
/**
* Source url for AJAX data for the table.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
* @default null
*/
"sAjaxSource": null,
/**
* Property from a given object from which to read the table data from. This
* can be an empty string (when not server-side processing), in which case
* it is assumed an an array is given directly.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
*/
"sAjaxDataProp": null,
/**
* Note if draw should be blocked while getting data
* @type boolean
* @default true
*/
"bAjaxDataGet": true,
/**
* The last jQuery XHR object that was used for server-side data gathering.
* This can be used for working with the XHR information in one of the
* callbacks
* @type object
* @default null
*/
"jqXHR": null,
/**
* JSON returned from the server in the last Ajax request
* @type object
* @default undefined
*/
"json": undefined,
/**
* Data submitted as part of the last Ajax request
* @type object
* @default undefined
*/
"oAjaxData": undefined,
/**
* Function to get the server-side data.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type function
*/
"fnServerData": null,
/**
* Functions which are called prior to sending an Ajax request so extra
* parameters can easily be sent to the server
* @type array
* @default []
*/
"aoServerParams": [],
/**
* Send the XHR HTTP method - GET or POST (could be PUT or DELETE if
* required).
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type string
*/
"sServerMethod": null,
/**
* Format numbers for display.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type function
*/
"fnFormatNumber": null,
/**
* List of options that can be used for the user selectable length menu.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type array
* @default []
*/
"aLengthMenu": null,
/**
* Counter for the draws that the table does. Also used as a tracker for
* server-side processing
* @type int
* @default 0
*/
"iDraw": 0,
/**
* Indicate if a redraw is being done - useful for Ajax
* @type boolean
* @default false
*/
"bDrawing": false,
/**
* Draw index (iDraw) of the last error when parsing the returned data
* @type int
* @default -1
*/
"iDrawError": -1,
/**
* Paging display length
* @type int
* @default 10
*/
"_iDisplayLength": 10,
/**
* Paging start point - aiDisplay index
* @type int
* @default 0
*/
"_iDisplayStart": 0,
/**
* Server-side processing - number of records in the result set
* (i.e. before filtering), Use fnRecordsTotal rather than
* this property to get the value of the number of records, regardless of
* the server-side processing setting.
* @type int
* @default 0
* @private
*/
"_iRecordsTotal": 0,
/**
* Server-side processing - number of records in the current display set
* (i.e. after filtering). Use fnRecordsDisplay rather than
* this property to get the value of the number of records, regardless of
* the server-side processing setting.
* @type boolean
* @default 0
* @private
*/
"_iRecordsDisplay": 0,
/**
* The classes to use for the table
* @type object
* @default {}
*/
"oClasses": {},
/**
* Flag attached to the settings object so you can check in the draw
* callback if filtering has been done in the draw. Deprecated in favour of
* events.
* @type boolean
* @default false
* @deprecated
*/
"bFiltered": false,
/**
* Flag attached to the settings object so you can check in the draw
* callback if sorting has been done in the draw. Deprecated in favour of
* events.
* @type boolean
* @default false
* @deprecated
*/
"bSorted": false,
/**
* Indicate that if multiple rows are in the header and there is more than
* one unique cell per column, if the top one (true) or bottom one (false)
* should be used for sorting / title by DataTables.
* Note that this parameter will be set by the initialisation routine. To
* set a default use {@link DataTable.defaults}.
* @type boolean
*/
"bSortCellsTop": null,
/**
* Initialisation object that is used for the table
* @type object
* @default null
*/
"oInit": null,
/**
* Destroy callback functions - for plug-ins to attach themselves to the
* destroy so they can clean up markup and events.
* @type array
* @default []
*/
"aoDestroyCallback": [],
/**
* Get the number of records in the current record set, before filtering
* @type function
*/
"fnRecordsTotal": function ()
{
return _fnDataSource( this ) == 'ssp' ?
this._iRecordsTotal * 1 :
this.aiDisplayMaster.length;
},
/**
* Get the number of records in the current record set, after filtering
* @type function
*/
"fnRecordsDisplay": function ()
{
return _fnDataSource( this ) == 'ssp' ?
this._iRecordsDisplay * 1 :
this.aiDisplay.length;
},
/**
* Get the display end point - aiDisplay index
* @type function
*/
"fnDisplayEnd": function ()
{
var
len = this._iDisplayLength,
start = this._iDisplayStart,
calc = start + len,
records = this.aiDisplay.length,
features = this.oFeatures,
paginate = features.bPaginate;
if ( features.bServerSide ) {
return paginate === false || len === -1 ?
start + records :
Math.min( start+len, this._iRecordsDisplay );
}
else {
return ! paginate || calc>records || len===-1 ?
records :
calc;
}
},
/**
* The DataTables object for this table
* @type object
* @default null
*/
"oInstance": null,
/**
* Unique identifier for each instance of the DataTables object. If there
* is an ID on the table node, then it takes that value, otherwise an
* incrementing internal counter is used.
* @type string
* @default null
*/
"sInstance": null,
/**
* tabindex attribute value that is added to DataTables control elements, allowing
* keyboard navigation of the table and its controls.
*/
"iTabIndex": 0,
/**
* DIV container for the footer scrolling table if scrolling
*/
"nScrollHead": null,
/**
* DIV container for the footer scrolling table if scrolling
*/
"nScrollFoot": null,
/**
* Last applied sort
* @type array
* @default []
*/
"aLastSort": [],
/**
* Stored plug-in instances
* @type object
* @default {}
*/
"oPlugins": {},
/**
* Function used to get a row's id from the row's data
* @type function
* @default null
*/
"rowIdFn": null,
/**
* Data location where to store a row's id
* @type string
* @default null
*/
"rowId": null
};
/**
* Extension object for DataTables that is used to provide all extension
* options.
*
* Note that the `DataTable.ext` object is available through
* `jQuery.fn.dataTable.ext` where it may be accessed and manipulated. It is
* also aliased to `jQuery.fn.dataTableExt` for historic reasons.
* @namespace
* @extends DataTable.models.ext
*/
/**
* DataTables extensions
*
* This namespace acts as a collection area for plug-ins that can be used to
* extend DataTables capabilities. Indeed many of the build in methods
* use this method to provide their own capabilities (sorting methods for
* example).
*
* Note that this namespace is aliased to `jQuery.fn.dataTableExt` for legacy
* reasons
*
* @namespace
*/
DataTable.ext = _ext = {
/**
* Buttons. For use with the Buttons extension for DataTables. This is
* defined here so other extensions can define buttons regardless of load
* order. It is _not_ used by DataTables core.
*
* @type object
* @default {}
*/
buttons: {},
/**
* Element class names
*
* @type object
* @default {}
*/
classes: {},
/**
* DataTables build type (expanded by the download builder)
*
* @type string
*/
build:"dt/dt-1.10.24",
/**
* Error reporting.
*
* How should DataTables report an error. Can take the value 'alert',
* 'throw', 'none' or a function.
*
* @type string|function
* @default alert
*/
errMode: "alert",
/**
* Feature plug-ins.
*
* This is an array of objects which describe the feature plug-ins that are
* available to DataTables. These feature plug-ins are then available for
* use through the `dom` initialisation option.
*
* Each feature plug-in is described by an object which must have the
* following properties:
*
* * `fnInit` - function that is used to initialise the plug-in,
* * `cFeature` - a character so the feature can be enabled by the `dom`
* instillation option. This is case sensitive.
*
* The `fnInit` function has the following input parameters:
*
* 1. `{object}` DataTables settings object: see
* {@link DataTable.models.oSettings}
*
* And the following return is expected:
*
* * {node|null} The element which contains your feature. Note that the
* return may also be void if your plug-in does not require to inject any
* DOM elements into DataTables control (`dom`) - for example this might
* be useful when developing a plug-in which allows table control via
* keyboard entry
*
* @type array
*
* @example
* $.fn.dataTable.ext.features.push( {
* "fnInit": function( oSettings ) {
* return new TableTools( { "oDTSettings": oSettings } );
* },
* "cFeature": "T"
* } );
*/
feature: [],
/**
* Row searching.
*
* This method of searching is complimentary to the default type based
* searching, and a lot more comprehensive as it allows you complete control
* over the searching logic. Each element in this array is a function
* (parameters described below) that is called for every row in the table,
* and your logic decides if it should be included in the searching data set
* or not.
*
* Searching functions have the following input parameters:
*
* 1. `{object}` DataTables settings object: see
* {@link DataTable.models.oSettings}
* 2. `{array|object}` Data for the row to be processed (same as the
* original format that was passed in as the data source, or an array
* from a DOM data source
* 3. `{int}` Row index ({@link DataTable.models.oSettings.aoData}), which
* can be useful to retrieve the `TR` element if you need DOM interaction.
*
* And the following return is expected:
*
* * {boolean} Include the row in the searched result set (true) or not
* (false)
*
* Note that as with the main search ability in DataTables, technically this
* is "filtering", since it is subtractive. However, for consistency in
* naming we call it searching here.
*
* @type array
* @default []
*
* @example
* // The following example shows custom search being applied to the
* // fourth column (i.e. the data[3] index) based on two input values
* // from the end-user, matching the data in a certain range.
* $.fn.dataTable.ext.search.push(
* function( settings, data, dataIndex ) {
* var min = document.getElementById('min').value * 1;
* var max = document.getElementById('max').value * 1;
* var version = data[3] == "-" ? 0 : data[3]*1;
*
* if ( min == "" && max == "" ) {
* return true;
* }
* else if ( min == "" && version < max ) {
* return true;
* }
* else if ( min < version && "" == max ) {
* return true;
* }
* else if ( min < version && version < max ) {
* return true;
* }
* return false;
* }
* );
*/
search: [],
/**
* Selector extensions
*
* The `selector` option can be used to extend the options available for the
* selector modifier options (`selector-modifier` object data type) that
* each of the three built in selector types offer (row, column and cell +
* their plural counterparts). For example the Select extension uses this
* mechanism to provide an option to select only rows, columns and cells
* that have been marked as selected by the end user (`{selected: true}`),
* which can be used in conjunction with the existing built in selector
* options.
*
* Each property is an array to which functions can be pushed. The functions
* take three attributes:
*
* * Settings object for the host table
* * Options object (`selector-modifier` object type)
* * Array of selected item indexes
*
* The return is an array of the resulting item indexes after the custom
* selector has been applied.
*
* @type object
*/
selector: {
cell: [],
column: [],
row: []
},
/**
* Internal functions, exposed for used in plug-ins.
*
* Please note that you should not need to use the internal methods for
* anything other than a plug-in (and even then, try to avoid if possible).
* The internal function may change between releases.
*
* @type object
* @default {}
*/
internal: {},
/**
* Legacy configuration options. Enable and disable legacy options that
* are available in DataTables.
*
* @type object
*/
legacy: {
/**
* Enable / disable DataTables 1.9 compatible server-side processing
* requests
*
* @type boolean
* @default null
*/
ajax: null
},
/**
* Pagination plug-in methods.
*
* Each entry in this object is a function and defines which buttons should
* be shown by the pagination rendering method that is used for the table:
* {@link DataTable.ext.renderer.pageButton}. The renderer addresses how the
* buttons are displayed in the document, while the functions here tell it
* what buttons to display. This is done by returning an array of button
* descriptions (what each button will do).
*
* Pagination types (the four built in options and any additional plug-in
* options defined here) can be used through the `paginationType`
* initialisation parameter.
*
* The functions defined take two parameters:
*
* 1. `{int} page` The current page index
* 2. `{int} pages` The number of pages in the table
*
* Each function is expected to return an array where each element of the
* array can be one of:
*
* * `first` - Jump to first page when activated
* * `last` - Jump to last page when activated
* * `previous` - Show previous page when activated
* * `next` - Show next page when activated
* * `{int}` - Show page of the index given
* * `{array}` - A nested array containing the above elements to add a
* containing 'DIV' element (might be useful for styling).
*
* Note that DataTables v1.9- used this object slightly differently whereby
* an object with two functions would be defined for each plug-in. That
* ability is still supported by DataTables 1.10+ to provide backwards
* compatibility, but this option of use is now decremented and no longer
* documented in DataTables 1.10+.
*
* @type object
* @default {}
*
* @example
* // Show previous, next and current page buttons only
* $.fn.dataTableExt.oPagination.current = function ( page, pages ) {
* return [ 'previous', page, 'next' ];
* };
*/
pager: {},
renderer: {
pageButton: {},
header: {}
},
/**
* Ordering plug-ins - custom data source
*
* The extension options for ordering of data available here is complimentary
* to the default type based ordering that DataTables typically uses. It
* allows much greater control over the the data that is being used to
* order a column, but is necessarily therefore more complex.
*
* This type of ordering is useful if you want to do ordering based on data
* live from the DOM (for example the contents of an 'input' element) rather
* than just the static string that DataTables knows of.
*
* The way these plug-ins work is that you create an array of the values you
* wish to be ordering for the column in question and then return that
* array. The data in the array much be in the index order of the rows in
* the table (not the currently ordering order!). Which order data gathering
* function is run here depends on the `dt-init columns.orderDataType`
* parameter that is used for the column (if any).
*
* The functions defined take two parameters:
*
* 1. `{object}` DataTables settings object: see
* {@link DataTable.models.oSettings}
* 2. `{int}` Target column index
*
* Each function is expected to return an array:
*
* * `{array}` Data for the column to be ordering upon
*
* @type array
*
* @example
* // Ordering using `input` node values
* $.fn.dataTable.ext.order['dom-text'] = function ( settings, col )
* {
* return this.api().column( col, {order:'index'} ).nodes().map( function ( td, i ) {
* return $('input', td).val();
* } );
* }
*/
order: {},
/**
* Type based plug-ins.
*
* Each column in DataTables has a type assigned to it, either by automatic
* detection or by direct assignment using the `type` option for the column.
* The type of a column will effect how it is ordering and search (plug-ins
* can also make use of the column type if required).
*
* @namespace
*/
type: {
/**
* Type detection functions.
*
* The functions defined in this object are used to automatically detect
* a column's type, making initialisation of DataTables super easy, even
* when complex data is in the table.
*
* The functions defined take two parameters:
*
* 1. `{*}` Data from the column cell to be analysed
* 2. `{settings}` DataTables settings object. This can be used to
* perform context specific type detection - for example detection
* based on language settings such as using a comma for a decimal
* place. Generally speaking the options from the settings will not
* be required
*
* Each function is expected to return:
*
* * `{string|null}` Data type detected, or null if unknown (and thus
* pass it on to the other type detection functions.
*
* @type array
*
* @example
* // Currency type detection plug-in:
* $.fn.dataTable.ext.type.detect.push(
* function ( data, settings ) {
* // Check the numeric part
* if ( ! data.substring(1).match(/[0-9]/) ) {
* return null;
* }
*
* // Check prefixed by currency
* if ( data.charAt(0) == '$' || data.charAt(0) == '£' ) {
* return 'currency';
* }
* return null;
* }
* );
*/
detect: [],
/**
* Type based search formatting.
*
* The type based searching functions can be used to pre-format the
* data to be search on. For example, it can be used to strip HTML
* tags or to de-format telephone numbers for numeric only searching.
*
* Note that is a search is not defined for a column of a given type,
* no search formatting will be performed.
*
* Pre-processing of searching data plug-ins - When you assign the sType
* for a column (or have it automatically detected for you by DataTables
* or a type detection plug-in), you will typically be using this for
* custom sorting, but it can also be used to provide custom searching
* by allowing you to pre-processing the data and returning the data in
* the format that should be searched upon. This is done by adding
* functions this object with a parameter name which matches the sType
* for that target column. This is the corollary of <i>afnSortData</i>
* for searching data.
*
* The functions defined take a single parameter:
*
* 1. `{*}` Data from the column cell to be prepared for searching
*
* Each function is expected to return:
*
* * `{string|null}` Formatted string that will be used for the searching.
*
* @type object
* @default {}
*
* @example
* $.fn.dataTable.ext.type.search['title-numeric'] = function ( d ) {
* return d.replace(/\n/g," ").replace( /<.*?>/g, "" );
* }
*/
search: {},
/**
* Type based ordering.
*
* The column type tells DataTables what ordering to apply to the table
* when a column is sorted upon. The order for each type that is defined,
* is defined by the functions available in this object.
*
* Each ordering option can be described by three properties added to
* this object:
*
* * `{type}-pre` - Pre-formatting function
* * `{type}-asc` - Ascending order function
* * `{type}-desc` - Descending order function
*
* All three can be used together, only `{type}-pre` or only
* `{type}-asc` and `{type}-desc` together. It is generally recommended
* that only `{type}-pre` is used, as this provides the optimal
* implementation in terms of speed, although the others are provided
* for compatibility with existing Javascript sort functions.
*
* `{type}-pre`: Functions defined take a single parameter:
*
* 1. `{*}` Data from the column cell to be prepared for ordering
*
* And return:
*
* * `{*}` Data to be sorted upon
*
* `{type}-asc` and `{type}-desc`: Functions are typical Javascript sort
* functions, taking two parameters:
*
* 1. `{*}` Data to compare to the second parameter
* 2. `{*}` Data to compare to the first parameter
*
* And returning:
*
* * `{*}` Ordering match: <0 if first parameter should be sorted lower
* than the second parameter, ===0 if the two parameters are equal and
* >0 if the first parameter should be sorted height than the second
* parameter.
*
* @type object
* @default {}
*
* @example
* // Numeric ordering of formatted numbers with a pre-formatter
* $.extend( $.fn.dataTable.ext.type.order, {
* "string-pre": function(x) {
* a = (a === "-" || a === "") ? 0 : a.replace( /[^\d\-\.]/g, "" );
* return parseFloat( a );
* }
* } );
*
* @example
* // Case-sensitive string ordering, with no pre-formatting method
* $.extend( $.fn.dataTable.ext.order, {
* "string-case-asc": function(x,y) {
* return ((x < y) ? -1 : ((x > y) ? 1 : 0));
* },
* "string-case-desc": function(x,y) {
* return ((x < y) ? 1 : ((x > y) ? -1 : 0));
* }
* } );
*/
order: {}
},
/**
* Unique DataTables instance counter
*
* @type int
* @private
*/
_unique: 0,
//
// Depreciated
// The following properties are retained for backwards compatiblity only.
// The should not be used in new projects and will be removed in a future
// version
//
/**
* Version check function.
* @type function
* @depreciated Since 1.10
*/
fnVersionCheck: DataTable.fnVersionCheck,
/**
* Index for what 'this' index API functions should use
* @type int
* @deprecated Since v1.10
*/
iApiIndex: 0,
/**
* jQuery UI class container
* @type object
* @deprecated Since v1.10
*/
oJUIClasses: {},
/**
* Software version
* @type string
* @deprecated Since v1.10
*/
sVersion: DataTable.version
};
//
// Backwards compatibility. Alias to pre 1.10 Hungarian notation counter parts
//
$.extend( _ext, {
afnFiltering: _ext.search,
aTypes: _ext.type.detect,
ofnSearch: _ext.type.search,
oSort: _ext.type.order,
afnSortData: _ext.order,
aoFeatures: _ext.feature,
oApi: _ext.internal,
oStdClasses: _ext.classes,
oPagination: _ext.pager
} );
$.extend( DataTable.ext.classes, {
"sTable": "dataTable",
"sNoFooter": "no-footer",
/* Paging buttons */
"sPageButton": "paginate_button",
"sPageButtonActive": "current",
"sPageButtonDisabled": "disabled",
/* Striping classes */
"sStripeOdd": "odd",
"sStripeEven": "even",
/* Empty row */
"sRowEmpty": "dataTables_empty",
/* Features */
"sWrapper": "dataTables_wrapper",
"sFilter": "dataTables_filter",
"sInfo": "dataTables_info",
"sPaging": "dataTables_paginate paging_", /* Note that the type is postfixed */
"sLength": "dataTables_length",
"sProcessing": "dataTables_processing",
/* Sorting */
"sSortAsc": "sorting_asc",
"sSortDesc": "sorting_desc",
"sSortable": "sorting", /* Sortable in both directions */
"sSortableAsc": "sorting_desc_disabled",
"sSortableDesc": "sorting_asc_disabled",
"sSortableNone": "sorting_disabled",
"sSortColumn": "sorting_", /* Note that an int is postfixed for the sorting order */
/* Filtering */
"sFilterInput": "",
/* Page length */
"sLengthSelect": "",
/* Scrolling */
"sScrollWrapper": "dataTables_scroll",
"sScrollHead": "dataTables_scrollHead",
"sScrollHeadInner": "dataTables_scrollHeadInner",
"sScrollBody": "dataTables_scrollBody",
"sScrollFoot": "dataTables_scrollFoot",
"sScrollFootInner": "dataTables_scrollFootInner",
/* Misc */
"sHeaderTH": "",
"sFooterTH": "",
// Deprecated
"sSortJUIAsc": "",
"sSortJUIDesc": "",
"sSortJUI": "",
"sSortJUIAscAllowed": "",
"sSortJUIDescAllowed": "",
"sSortJUIWrapper": "",
"sSortIcon": "",
"sJUIHeader": "",
"sJUIFooter": ""
} );
var extPagination = DataTable.ext.pager;
function _numbers ( page, pages ) {
var
numbers = [],
buttons = extPagination.numbers_length,
half = Math.floor( buttons / 2 ),
i = 1;
if ( pages <= buttons ) {
numbers = _range( 0, pages );
}
else if ( page <= half ) {
numbers = _range( 0, buttons-2 );
numbers.push( 'ellipsis' );
numbers.push( pages-1 );
}
else if ( page >= pages - 1 - half ) {
numbers = _range( pages-(buttons-2), pages );
numbers.splice( 0, 0, 'ellipsis' ); // no unshift in ie6
numbers.splice( 0, 0, 0 );
}
else {
numbers = _range( page-half+2, page+half-1 );
numbers.push( 'ellipsis' );
numbers.push( pages-1 );
numbers.splice( 0, 0, 'ellipsis' );
numbers.splice( 0, 0, 0 );
}
numbers.DT_el = 'span';
return numbers;
}
$.extend( extPagination, {
simple: function ( page, pages ) {
return [ 'previous', 'next' ];
},
full: function ( page, pages ) {
return [ 'first', 'previous', 'next', 'last' ];
},
numbers: function ( page, pages ) {
return [ _numbers(page, pages) ];
},
simple_numbers: function ( page, pages ) {
return [ 'previous', _numbers(page, pages), 'next' ];
},
full_numbers: function ( page, pages ) {
return [ 'first', 'previous', _numbers(page, pages), 'next', 'last' ];
},
first_last_numbers: function (page, pages) {
return ['first', _numbers(page, pages), 'last'];
},
// For testing and plug-ins to use
_numbers: _numbers,
// Number of number buttons (including ellipsis) to show. _Must be odd!_
numbers_length: 7
} );
$.extend( true, DataTable.ext.renderer, {
pageButton: {
_: function ( settings, host, idx, buttons, page, pages ) {
var classes = settings.oClasses;
var lang = settings.oLanguage.oPaginate;
var aria = settings.oLanguage.oAria.paginate || {};
var btnDisplay, btnClass, counter=0;
var attach = function( container, buttons ) {
var i, ien, node, button, tabIndex;
var disabledClass = classes.sPageButtonDisabled;
var clickHandler = function ( e ) {
_fnPageChange( settings, e.data.action, true );
};
for ( i=0, ien=buttons.length ; i<ien ; i++ ) {
button = buttons[i];
if ( Array.isArray( button ) ) {
var inner = $( '<'+(button.DT_el || 'div')+'/>' )
.appendTo( container );
attach( inner, button );
}
else {
btnDisplay = null;
btnClass = button;
tabIndex = settings.iTabIndex;
switch ( button ) {
case 'ellipsis':
container.append('<span class="ellipsis">…</span>');
break;
case 'first':
btnDisplay = lang.sFirst;
if ( page === 0 ) {
tabIndex = -1;
btnClass += ' ' + disabledClass;
}
break;
case 'previous':
btnDisplay = lang.sPrevious;
if ( page === 0 ) {
tabIndex = -1;
btnClass += ' ' + disabledClass;
}
break;
case 'next':
btnDisplay = lang.sNext;
if ( pages === 0 || page === pages-1 ) {
tabIndex = -1;
btnClass += ' ' + disabledClass;
}
break;
case 'last':
btnDisplay = lang.sLast;
if ( pages === 0 || page === pages-1 ) {
tabIndex = -1;
btnClass += ' ' + disabledClass;
}
break;
default:
btnDisplay = settings.fnFormatNumber( button + 1 );
btnClass = page === button ?
classes.sPageButtonActive : '';
break;
}
if ( btnDisplay !== null ) {
node = $('<a>', {
'class': classes.sPageButton+' '+btnClass,
'aria-controls': settings.sTableId,
'aria-label': aria[ button ],
'data-dt-idx': counter,
'tabindex': tabIndex,
'id': idx === 0 && typeof button === 'string' ?
settings.sTableId +'_'+ button :
null
} )
.html( btnDisplay )
.appendTo( container );
_fnBindAction(
node, {action: button}, clickHandler
);
counter++;
}
}
}
};
// IE9 throws an 'unknown error' if document.activeElement is used
// inside an iframe or frame. Try / catch the error. Not good for
// accessibility, but neither are frames.
var activeEl;
try {
// Because this approach is destroying and recreating the paging
// elements, focus is lost on the select button which is bad for
// accessibility. So we want to restore focus once the draw has
// completed
activeEl = $(host).find(document.activeElement).data('dt-idx');
}
catch (e) {}
attach( $(host).empty(), buttons );
if ( activeEl !== undefined ) {
$(host).find( '[data-dt-idx='+activeEl+']' ).trigger('focus');
}
}
}
} );
// Built in type detection. See model.ext.aTypes for information about
// what is required from this methods.
$.extend( DataTable.ext.type.detect, [
// Plain numbers - first since V8 detects some plain numbers as dates
// e.g. Date.parse('55') (but not all, e.g. Date.parse('22')...).
function ( d, settings )
{
var decimal = settings.oLanguage.sDecimal;
return _isNumber( d, decimal ) ? 'num'+decimal : null;
},
// Dates (only those recognised by the browser's Date.parse)
function ( d, settings )
{
// V8 tries _very_ hard to make a string passed into `Date.parse()`
// valid, so we need to use a regex to restrict date formats. Use a
// plug-in for anything other than ISO8601 style strings
if ( d && !(d instanceof Date) && ! _re_date.test(d) ) {
return null;
}
var parsed = Date.parse(d);
return (parsed !== null && !isNaN(parsed)) || _empty(d) ? 'date' : null;
},
// Formatted numbers
function ( d, settings )
{
var decimal = settings.oLanguage.sDecimal;
return _isNumber( d, decimal, true ) ? 'num-fmt'+decimal : null;
},
// HTML numeric
function ( d, settings )
{
var decimal = settings.oLanguage.sDecimal;
return _htmlNumeric( d, decimal ) ? 'html-num'+decimal : null;
},
// HTML numeric, formatted
function ( d, settings )
{
var decimal = settings.oLanguage.sDecimal;
return _htmlNumeric( d, decimal, true ) ? 'html-num-fmt'+decimal : null;
},
// HTML (this is strict checking - there must be html)
function ( d, settings )
{
return _empty( d ) || (typeof d === 'string' && d.indexOf('<') !== -1) ?
'html' : null;
}
] );
// Filter formatting functions. See model.ext.ofnSearch for information about
// what is required from these methods.
//
// Note that additional search methods are added for the html numbers and
// html formatted numbers by `_addNumericSort()` when we know what the decimal
// place is
$.extend( DataTable.ext.type.search, {
html: function ( data ) {
return _empty(data) ?
data :
typeof data === 'string' ?
data
.replace( _re_new_lines, " " )
.replace( _re_html, "" ) :
'';
},
string: function ( data ) {
return _empty(data) ?
data :
typeof data === 'string' ?
data.replace( _re_new_lines, " " ) :
data;
}
} );
var __numericReplace = function ( d, decimalPlace, re1, re2 ) {
if ( d !== 0 && (!d || d === '-') ) {
return -Infinity;
}
// If a decimal place other than `.` is used, it needs to be given to the
// function so we can detect it and replace with a `.` which is the only
// decimal place Javascript recognises - it is not locale aware.
if ( decimalPlace ) {
d = _numToDecimal( d, decimalPlace );
}
if ( d.replace ) {
if ( re1 ) {
d = d.replace( re1, '' );
}
if ( re2 ) {
d = d.replace( re2, '' );
}
}
return d * 1;
};
// Add the numeric 'deformatting' functions for sorting and search. This is done
// in a function to provide an easy ability for the language options to add
// additional methods if a non-period decimal place is used.
function _addNumericSort ( decimalPlace ) {
$.each(
{
// Plain numbers
"num": function ( d ) {
return __numericReplace( d, decimalPlace );
},
// Formatted numbers
"num-fmt": function ( d ) {
return __numericReplace( d, decimalPlace, _re_formatted_numeric );
},
// HTML numeric
"html-num": function ( d ) {
return __numericReplace( d, decimalPlace, _re_html );
},
// HTML numeric, formatted
"html-num-fmt": function ( d ) {
return __numericReplace( d, decimalPlace, _re_html, _re_formatted_numeric );
}
},
function ( key, fn ) {
// Add the ordering method
_ext.type.order[ key+decimalPlace+'-pre' ] = fn;
// For HTML types add a search formatter that will strip the HTML
if ( key.match(/^html\-/) ) {
_ext.type.search[ key+decimalPlace ] = _ext.type.search.html;
}
}
);
}
// Default sort methods
$.extend( _ext.type.order, {
// Dates
"date-pre": function ( d ) {
var ts = Date.parse( d );
return isNaN(ts) ? -Infinity : ts;
},
// html
"html-pre": function ( a ) {
return _empty(a) ?
'' :
a.replace ?
a.replace( /<.*?>/g, "" ).toLowerCase() :
a+'';
},
// string
"string-pre": function ( a ) {
// This is a little complex, but faster than always calling toString,
// http://jsperf.com/tostring-v-check
return _empty(a) ?
'' :
typeof a === 'string' ?
a.toLowerCase() :
! a.toString ?
'' :
a.toString();
},
// string-asc and -desc are retained only for compatibility with the old
// sort methods
"string-asc": function ( x, y ) {
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
},
"string-desc": function ( x, y ) {
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}
} );
// Numeric sorting types - order doesn't matter here
_addNumericSort( '' );
$.extend( true, DataTable.ext.renderer, {
header: {
_: function ( settings, cell, column, classes ) {
// No additional mark-up required
// Attach a sort listener to update on sort - note that using the
// `DT` namespace will allow the event to be removed automatically
// on destroy, while the `dt` namespaced event is the one we are
// listening for
$(settings.nTable).on( 'order.dt.DT', function ( e, ctx, sorting, columns ) {
if ( settings !== ctx ) { // need to check this this is the host
return; // table, not a nested one
}
var colIdx = column.idx;
cell
.removeClass(
classes.sSortAsc +' '+
classes.sSortDesc
)
.addClass( columns[ colIdx ] == 'asc' ?
classes.sSortAsc : columns[ colIdx ] == 'desc' ?
classes.sSortDesc :
column.sSortingClass
);
} );
},
jqueryui: function ( settings, cell, column, classes ) {
$('<div/>')
.addClass( classes.sSortJUIWrapper )
.append( cell.contents() )
.append( $('<span/>')
.addClass( classes.sSortIcon+' '+column.sSortingClassJUI )
)
.appendTo( cell );
// Attach a sort listener to update on sort
$(settings.nTable).on( 'order.dt.DT', function ( e, ctx, sorting, columns ) {
if ( settings !== ctx ) {
return;
}
var colIdx = column.idx;
cell
.removeClass( classes.sSortAsc +" "+classes.sSortDesc )
.addClass( columns[ colIdx ] == 'asc' ?
classes.sSortAsc : columns[ colIdx ] == 'desc' ?
classes.sSortDesc :
column.sSortingClass
);
cell
.find( 'span.'+classes.sSortIcon )
.removeClass(
classes.sSortJUIAsc +" "+
classes.sSortJUIDesc +" "+
classes.sSortJUI +" "+
classes.sSortJUIAscAllowed +" "+
classes.sSortJUIDescAllowed
)
.addClass( columns[ colIdx ] == 'asc' ?
classes.sSortJUIAsc : columns[ colIdx ] == 'desc' ?
classes.sSortJUIDesc :
column.sSortingClassJUI
);
} );
}
}
} );
/*
* Public helper functions. These aren't used internally by DataTables, or
* called by any of the options passed into DataTables, but they can be used
* externally by developers working with DataTables. They are helper functions
* to make working with DataTables a little bit easier.
*/
var __htmlEscapeEntities = function ( d ) {
return typeof d === 'string' ?
d
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"') :
d;
};
/**
* Helpers for `columns.render`.
*
* The options defined here can be used with the `columns.render` initialisation
* option to provide a display renderer. The following functions are defined:
*
* * `number` - Will format numeric data (defined by `columns.data`) for
* display, retaining the original unformatted data for sorting and filtering.
* It takes 5 parameters:
* * `string` - Thousands grouping separator
* * `string` - Decimal point indicator
* * `integer` - Number of decimal points to show
* * `string` (optional) - Prefix.
* * `string` (optional) - Postfix (/suffix).
* * `text` - Escape HTML to help prevent XSS attacks. It has no optional
* parameters.
*
* @example
* // Column definition using the number renderer
* {
* data: "salary",
* render: $.fn.dataTable.render.number( '\'', '.', 0, '$' )
* }
*
* @namespace
*/
DataTable.render = {
number: function ( thousands, decimal, precision, prefix, postfix ) {
return {
display: function ( d ) {
if ( typeof d !== 'number' && typeof d !== 'string' ) {
return d;
}
var negative = d < 0 ? '-' : '';
var flo = parseFloat( d );
// If NaN then there isn't much formatting that we can do - just
// return immediately, escaping any HTML (this was supposed to
// be a number after all)
if ( isNaN( flo ) ) {
return __htmlEscapeEntities( d );
}
flo = flo.toFixed( precision );
d = Math.abs( flo );
var intPart = parseInt( d, 10 );
var floatPart = precision ?
decimal+(d - intPart).toFixed( precision ).substring( 2 ):
'';
return negative + (prefix||'') +
intPart.toString().replace(
/\B(?=(\d{3})+(?!\d))/g, thousands
) +
floatPart +
(postfix||'');
}
};
},
text: function () {
return {
display: __htmlEscapeEntities,
filter: __htmlEscapeEntities
};
}
};
/*
* This is really a good bit rubbish this method of exposing the internal methods
* publicly... - To be fixed in 2.0 using methods on the prototype
*/
/**
* Create a wrapper function for exporting an internal functions to an external API.
* @param {string} fn API function name
* @returns {function} wrapped function
* @memberof DataTable#internal
*/
function _fnExternApiFunc (fn)
{
return function() {
var args = [_fnSettingsFromNode( this[DataTable.ext.iApiIndex] )].concat(
Array.prototype.slice.call(arguments)
);
return DataTable.ext.internal[fn].apply( this, args );
};
}
/**
* Reference to internal functions for use by plug-in developers. Note that
* these methods are references to internal functions and are considered to be
* private. If you use these methods, be aware that they are liable to change
* between versions.
* @namespace
*/
$.extend( DataTable.ext.internal, {
_fnExternApiFunc: _fnExternApiFunc,
_fnBuildAjax: _fnBuildAjax,
_fnAjaxUpdate: _fnAjaxUpdate,
_fnAjaxParameters: _fnAjaxParameters,
_fnAjaxUpdateDraw: _fnAjaxUpdateDraw,
_fnAjaxDataSrc: _fnAjaxDataSrc,
_fnAddColumn: _fnAddColumn,
_fnColumnOptions: _fnColumnOptions,
_fnAdjustColumnSizing: _fnAdjustColumnSizing,
_fnVisibleToColumnIndex: _fnVisibleToColumnIndex,
_fnColumnIndexToVisible: _fnColumnIndexToVisible,
_fnVisbleColumns: _fnVisbleColumns,
_fnGetColumns: _fnGetColumns,
_fnColumnTypes: _fnColumnTypes,
_fnApplyColumnDefs: _fnApplyColumnDefs,
_fnHungarianMap: _fnHungarianMap,
_fnCamelToHungarian: _fnCamelToHungarian,
_fnLanguageCompat: _fnLanguageCompat,
_fnBrowserDetect: _fnBrowserDetect,
_fnAddData: _fnAddData,
_fnAddTr: _fnAddTr,
_fnNodeToDataIndex: _fnNodeToDataIndex,
_fnNodeToColumnIndex: _fnNodeToColumnIndex,
_fnGetCellData: _fnGetCellData,
_fnSetCellData: _fnSetCellData,
_fnSplitObjNotation: _fnSplitObjNotation,
_fnGetObjectDataFn: _fnGetObjectDataFn,
_fnSetObjectDataFn: _fnSetObjectDataFn,
_fnGetDataMaster: _fnGetDataMaster,
_fnClearTable: _fnClearTable,
_fnDeleteIndex: _fnDeleteIndex,
_fnInvalidate: _fnInvalidate,
_fnGetRowElements: _fnGetRowElements,
_fnCreateTr: _fnCreateTr,
_fnBuildHead: _fnBuildHead,
_fnDrawHead: _fnDrawHead,
_fnDraw: _fnDraw,
_fnReDraw: _fnReDraw,
_fnAddOptionsHtml: _fnAddOptionsHtml,
_fnDetectHeader: _fnDetectHeader,
_fnGetUniqueThs: _fnGetUniqueThs,
_fnFeatureHtmlFilter: _fnFeatureHtmlFilter,
_fnFilterComplete: _fnFilterComplete,
_fnFilterCustom: _fnFilterCustom,
_fnFilterColumn: _fnFilterColumn,
_fnFilter: _fnFilter,
_fnFilterCreateSearch: _fnFilterCreateSearch,
_fnEscapeRegex: _fnEscapeRegex,
_fnFilterData: _fnFilterData,
_fnFeatureHtmlInfo: _fnFeatureHtmlInfo,
_fnUpdateInfo: _fnUpdateInfo,
_fnInfoMacros: _fnInfoMacros,
_fnInitialise: _fnInitialise,
_fnInitComplete: _fnInitComplete,
_fnLengthChange: _fnLengthChange,
_fnFeatureHtmlLength: _fnFeatureHtmlLength,
_fnFeatureHtmlPaginate: _fnFeatureHtmlPaginate,
_fnPageChange: _fnPageChange,
_fnFeatureHtmlProcessing: _fnFeatureHtmlProcessing,
_fnProcessingDisplay: _fnProcessingDisplay,
_fnFeatureHtmlTable: _fnFeatureHtmlTable,
_fnScrollDraw: _fnScrollDraw,
_fnApplyToChildren: _fnApplyToChildren,
_fnCalculateColumnWidths: _fnCalculateColumnWidths,
_fnThrottle: _fnThrottle,
_fnConvertToWidth: _fnConvertToWidth,
_fnGetWidestNode: _fnGetWidestNode,
_fnGetMaxLenString: _fnGetMaxLenString,
_fnStringToCss: _fnStringToCss,
_fnSortFlatten: _fnSortFlatten,
_fnSort: _fnSort,
_fnSortAria: _fnSortAria,
_fnSortListener: _fnSortListener,
_fnSortAttachListener: _fnSortAttachListener,
_fnSortingClasses: _fnSortingClasses,
_fnSortData: _fnSortData,
_fnSaveState: _fnSaveState,
_fnLoadState: _fnLoadState,
_fnSettingsFromNode: _fnSettingsFromNode,
_fnLog: _fnLog,
_fnMap: _fnMap,
_fnBindAction: _fnBindAction,
_fnCallbackReg: _fnCallbackReg,
_fnCallbackFire: _fnCallbackFire,
_fnLengthOverflow: _fnLengthOverflow,
_fnRenderer: _fnRenderer,
_fnDataSource: _fnDataSource,
_fnRowAttributes: _fnRowAttributes,
_fnExtend: _fnExtend,
_fnCalculateEnd: function () {} // Used by a lot of plug-ins, but redundant
// in 1.10, so this dead-end function is
// added to prevent errors
} );
// jQuery access
$.fn.dataTable = DataTable;
// Provide access to the host jQuery object (circular reference)
DataTable.$ = $;
// Legacy aliases
$.fn.dataTableSettings = DataTable.settings;
$.fn.dataTableExt = DataTable.ext;
// With a capital `D` we return a DataTables API instance rather than a
// jQuery object
$.fn.DataTable = function ( opts ) {
return $(this).dataTable( opts ).api();
};
// All properties that are available to $.fn.dataTable should also be
// available on $.fn.DataTable
$.each( DataTable, function ( prop, val ) {
$.fn.DataTable[ prop ] = val;
} );
// Information about events fired by DataTables - for documentation.
/**
* Draw event, fired whenever the table is redrawn on the page, at the same
* point as fnDrawCallback. This may be useful for binding events or
* performing calculations when the table is altered at all.
* @name DataTable#draw.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
* Search event, fired when the searching applied to the table (using the
* built-in global search, or column filters) is altered.
* @name DataTable#search.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
* Page change event, fired when the paging of the table is altered.
* @name DataTable#page.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
* Order event, fired when the ordering applied to the table is altered.
* @name DataTable#order.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
* DataTables initialisation complete event, fired when the table is fully
* drawn, including Ajax data loaded, if Ajax data is required.
* @name DataTable#init.dt
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
* @param {object} json The JSON object request from the server - only
* present if client-side Ajax sourced data is used</li></ol>
*/
/**
* State save event, fired when the table has changed state a new state save
* is required. This event allows modification of the state saving object
* prior to actually doing the save, including addition or other state
* properties (for plug-ins) or modification of a DataTables core property.
* @name DataTable#stateSaveParams.dt
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
* @param {object} json The state information to be saved
*/
/**
* State load event, fired when the table is loading state from the stored
* data, but prior to the settings object being modified by the saved state
* - allowing modification of the saved state is required or loading of
* state for a plug-in.
* @name DataTable#stateLoadParams.dt
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
* @param {object} json The saved state information
*/
/**
* State loaded event, fired when state has been loaded from stored data and
* the settings object has been modified by the loaded data.
* @name DataTable#stateLoaded.dt
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
* @param {object} json The saved state information
*/
/**
* Processing event, fired when DataTables is doing some kind of processing
* (be it, order, search or anything else). It can be used to indicate to
* the end user that there is something happening, or that something has
* finished.
* @name DataTable#processing.dt
* @event
* @param {event} e jQuery event object
* @param {object} oSettings DataTables settings object
* @param {boolean} bShow Flag for if DataTables is doing processing or not
*/
/**
* Ajax (XHR) event, fired whenever an Ajax request is completed from a
* request to made to the server for new data. This event is called before
* DataTables processed the returned data, so it can also be used to pre-
* process the data returned from the server, if needed.
*
* Note that this trigger is called in `fnServerData`, if you override
* `fnServerData` and which to use this event, you need to trigger it in you
* success function.
* @name DataTable#xhr.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
* @param {object} json JSON returned from the server
*
* @example
* // Use a custom property returned from the server in another DOM element
* $('#table').dataTable().on('xhr.dt', function (e, settings, json) {
* $('#status').html( json.status );
* } );
*
* @example
* // Pre-process the data returned from the server
* $('#table').dataTable().on('xhr.dt', function (e, settings, json) {
* for ( var i=0, ien=json.aaData.length ; i<ien ; i++ ) {
* json.aaData[i].sum = json.aaData[i].one + json.aaData[i].two;
* }
* // Note no return - manipulate the data directly in the JSON object.
* } );
*/
/**
* Destroy event, fired when the DataTable is destroyed by calling fnDestroy
* or passing the bDestroy:true parameter in the initialisation object. This
* can be used to remove bound events, added DOM nodes, etc.
* @name DataTable#destroy.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
* Page length change event, fired when number of records to show on each
* page (the length) is changed.
* @name DataTable#length.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
* @param {integer} len New length
*/
/**
* Column sizing has changed.
* @name DataTable#column-sizing.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
*/
/**
* Column visibility has changed.
* @name DataTable#column-visibility.dt
* @event
* @param {event} e jQuery event object
* @param {object} o DataTables settings object {@link DataTable.models.oSettings}
* @param {int} column Column index
* @param {bool} vis `false` if column now hidden, or `true` if visible
*/
return $.fn.dataTable;
}));
|
(function() {
var callWithJQuery,
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
slice = [].slice,
bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
hasProp = {}.hasOwnProperty;
callWithJQuery = function(pivotModule) {
if (typeof exports === "object" && typeof module === "object") {
return pivotModule(require("jquery"));
} else if (typeof define === "function" && define.amd) {
return define(["jquery"], pivotModule);
} else {
return pivotModule(jQuery);
}
};
callWithJQuery(function($) {
/*
Utilities
*/
var PivotData, addSeparators, aggregatorTemplates, aggregators, dayNamesEn, derivers, getSort, locales, mthNamesEn, naturalSort, numberFormat, pivotTableRenderer, rd, renderers, rx, rz, sortAs, usFmt, usFmtInt, usFmtPct, zeroPad;
addSeparators = function(nStr, thousandsSep, decimalSep) {
var rgx, x, x1, x2;
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? decimalSep + x[1] : '';
rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + thousandsSep + '$2');
}
return x1 + x2;
};
numberFormat = function(opts) {
var defaults;
defaults = {
digitsAfterDecimal: 2,
scaler: 1,
thousandsSep: ",",
decimalSep: ".",
prefix: "",
suffix: ""
};
opts = $.extend({}, defaults, opts);
return function(x) {
var result;
if (isNaN(x) || !isFinite(x)) {
return "";
}
result = addSeparators((opts.scaler * x).toFixed(opts.digitsAfterDecimal), opts.thousandsSep, opts.decimalSep);
return "" + opts.prefix + result + opts.suffix;
};
};
usFmt = numberFormat();
usFmtInt = numberFormat({
digitsAfterDecimal: 0
});
usFmtPct = numberFormat({
digitsAfterDecimal: 1,
scaler: 100,
suffix: "%"
});
aggregatorTemplates = {
count: function(formatter) {
if (formatter == null) {
formatter = usFmtInt;
}
return function() {
return function(data, rowKey, colKey) {
return {
count: 0,
push: function() {
return this.count++;
},
value: function() {
return this.count;
},
format: formatter
};
};
};
},
uniques: function(fn, formatter) {
if (formatter == null) {
formatter = usFmtInt;
}
return function(arg) {
var attr;
attr = arg[0];
return function(data, rowKey, colKey) {
return {
uniq: [],
push: function(record) {
var ref;
if (ref = record[attr], indexOf.call(this.uniq, ref) < 0) {
return this.uniq.push(record[attr]);
}
},
value: function() {
return fn(this.uniq);
},
format: formatter,
numInputs: attr != null ? 0 : 1
};
};
};
},
sum: function(formatter) {
if (formatter == null) {
formatter = usFmt;
}
return function(arg) {
var attr;
attr = arg[0];
return function(data, rowKey, colKey) {
return {
sum: 0,
push: function(record) {
if (!isNaN(parseFloat(record[attr]))) {
return this.sum += parseFloat(record[attr]);
}
},
value: function() {
return this.sum;
},
format: formatter,
numInputs: attr != null ? 0 : 1
};
};
};
},
extremes: function(mode, formatter) {
if (formatter == null) {
formatter = usFmt;
}
return function(arg) {
var attr;
attr = arg[0];
return function(data, rowKey, colKey) {
return {
val: null,
sorter: getSort(data != null ? data.sorters : void 0, attr),
push: function(record) {
var ref, ref1, ref2, x;
x = record[attr];
if (mode === "min" || mode === "max") {
x = parseFloat(x);
if (!isNaN(x)) {
this.val = Math[mode](x, (ref = this.val) != null ? ref : x);
}
}
if (mode === "first") {
if (this.sorter(x, (ref1 = this.val) != null ? ref1 : x) <= 0) {
this.val = x;
}
}
if (mode === "last") {
if (this.sorter(x, (ref2 = this.val) != null ? ref2 : x) >= 0) {
return this.val = x;
}
}
},
value: function() {
return this.val;
},
format: function(x) {
if (isNaN(x)) {
return x;
} else {
return formatter(x);
}
},
numInputs: attr != null ? 0 : 1
};
};
};
},
quantile: function(q, formatter) {
if (formatter == null) {
formatter = usFmt;
}
return function(arg) {
var attr;
attr = arg[0];
return function(data, rowKey, colKey) {
return {
vals: [],
push: function(record) {
var x;
x = parseFloat(record[attr]);
if (!isNaN(x)) {
return this.vals.push(x);
}
},
value: function() {
var i;
if (this.vals.length === 0) {
return null;
}
this.vals.sort(function(a, b) {
return a - b;
});
i = (this.vals.length - 1) * q;
return (this.vals[Math.floor(i)] + this.vals[Math.ceil(i)]) / 2.0;
},
format: formatter,
numInputs: attr != null ? 0 : 1
};
};
};
},
runningStat: function(mode, ddof, formatter) {
if (mode == null) {
mode = "mean";
}
if (ddof == null) {
ddof = 1;
}
if (formatter == null) {
formatter = usFmt;
}
return function(arg) {
var attr;
attr = arg[0];
return function(data, rowKey, colKey) {
return {
n: 0.0,
m: 0.0,
s: 0.0,
push: function(record) {
var m_new, x;
x = parseFloat(record[attr]);
if (isNaN(x)) {
return;
}
this.n += 1.0;
if (this.n === 1.0) {
return this.m = x;
} else {
m_new = this.m + (x - this.m) / this.n;
this.s = this.s + (x - this.m) * (x - m_new);
return this.m = m_new;
}
},
value: function() {
if (mode === "mean") {
if (this.n === 0) {
return 0 / 0;
} else {
return this.m;
}
}
if (this.n <= ddof) {
return 0;
}
switch (mode) {
case "var":
return this.s / (this.n - ddof);
case "stdev":
return Math.sqrt(this.s / (this.n - ddof));
}
},
format: formatter,
numInputs: attr != null ? 0 : 1
};
};
};
},
sumOverSum: function(formatter) {
if (formatter == null) {
formatter = usFmt;
}
return function(arg) {
var denom, num;
num = arg[0], denom = arg[1];
return function(data, rowKey, colKey) {
return {
sumNum: 0,
sumDenom: 0,
push: function(record) {
if (!isNaN(parseFloat(record[num]))) {
this.sumNum += parseFloat(record[num]);
}
if (!isNaN(parseFloat(record[denom]))) {
return this.sumDenom += parseFloat(record[denom]);
}
},
value: function() {
return this.sumNum / this.sumDenom;
},
format: formatter,
numInputs: (num != null) && (denom != null) ? 0 : 2
};
};
};
},
sumOverSumBound80: function(upper, formatter) {
if (upper == null) {
upper = true;
}
if (formatter == null) {
formatter = usFmt;
}
return function(arg) {
var denom, num;
num = arg[0], denom = arg[1];
return function(data, rowKey, colKey) {
return {
sumNum: 0,
sumDenom: 0,
push: function(record) {
if (!isNaN(parseFloat(record[num]))) {
this.sumNum += parseFloat(record[num]);
}
if (!isNaN(parseFloat(record[denom]))) {
return this.sumDenom += parseFloat(record[denom]);
}
},
value: function() {
var sign;
sign = upper ? 1 : -1;
return (0.821187207574908 / this.sumDenom + this.sumNum / this.sumDenom + 1.2815515655446004 * sign * Math.sqrt(0.410593603787454 / (this.sumDenom * this.sumDenom) + (this.sumNum * (1 - this.sumNum / this.sumDenom)) / (this.sumDenom * this.sumDenom))) / (1 + 1.642374415149816 / this.sumDenom);
},
format: formatter,
numInputs: (num != null) && (denom != null) ? 0 : 2
};
};
};
},
fractionOf: function(wrapped, type, formatter) {
if (type == null) {
type = "total";
}
if (formatter == null) {
formatter = usFmtPct;
}
return function() {
var x;
x = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return function(data, rowKey, colKey) {
return {
selector: {
total: [[], []],
row: [rowKey, []],
col: [[], colKey]
}[type],
inner: wrapped.apply(null, x)(data, rowKey, colKey),
push: function(record) {
return this.inner.push(record);
},
format: formatter,
value: function() {
return this.inner.value() / data.getAggregator.apply(data, this.selector).inner.value();
},
numInputs: wrapped.apply(null, x)().numInputs
};
};
};
}
};
aggregatorTemplates.countUnique = function(f) {
return aggregatorTemplates.uniques((function(x) {
return x.length;
}), f);
};
aggregatorTemplates.listUnique = function(s) {
return aggregatorTemplates.uniques((function(x) {
return x.join(s);
}), (function(x) {
return x;
}));
};
aggregatorTemplates.max = function(f) {
return aggregatorTemplates.extremes('max', f);
};
aggregatorTemplates.min = function(f) {
return aggregatorTemplates.extremes('min', f);
};
aggregatorTemplates.first = function(f) {
return aggregatorTemplates.extremes('first', f);
};
aggregatorTemplates.last = function(f) {
return aggregatorTemplates.extremes('last', f);
};
aggregatorTemplates.median = function(f) {
return aggregatorTemplates.quantile(0.5, f);
};
aggregatorTemplates.average = function(f) {
return aggregatorTemplates.runningStat("mean", 1, f);
};
aggregatorTemplates["var"] = function(ddof, f) {
return aggregatorTemplates.runningStat("var", ddof, f);
};
aggregatorTemplates.stdev = function(ddof, f) {
return aggregatorTemplates.runningStat("stdev", ddof, f);
};
aggregators = (function(tpl) {
return {
"Count": tpl.count(usFmtInt),
"Count Unique Values": tpl.countUnique(usFmtInt),
"List Unique Values": tpl.listUnique(", "),
"Sum": tpl.sum(usFmt),
"Integer Sum": tpl.sum(usFmtInt),
"Average": tpl.average(usFmt),
"Median": tpl.median(usFmt),
"Sample Variance": tpl["var"](1, usFmt),
"Sample Standard Deviation": tpl.stdev(1, usFmt),
"Minimum": tpl.min(usFmt),
"Maximum": tpl.max(usFmt),
"First": tpl.first(usFmt),
"Last": tpl.last(usFmt),
"Sum over Sum": tpl.sumOverSum(usFmt),
"80% Upper Bound": tpl.sumOverSumBound80(true, usFmt),
"80% Lower Bound": tpl.sumOverSumBound80(false, usFmt),
"Sum as Fraction of Total": tpl.fractionOf(tpl.sum(), "total", usFmtPct),
"Sum as Fraction of Rows": tpl.fractionOf(tpl.sum(), "row", usFmtPct),
"Sum as Fraction of Columns": tpl.fractionOf(tpl.sum(), "col", usFmtPct),
"Count as Fraction of Total": tpl.fractionOf(tpl.count(), "total", usFmtPct),
"Count as Fraction of Rows": tpl.fractionOf(tpl.count(), "row", usFmtPct),
"Count as Fraction of Columns": tpl.fractionOf(tpl.count(), "col", usFmtPct)
};
})(aggregatorTemplates);
renderers = {
"Table": function(data, opts) {
return pivotTableRenderer(data, opts);
},
"Table Barchart": function(data, opts) {
return $(pivotTableRenderer(data, opts)).barchart();
},
"Heatmap": function(data, opts) {
return $(pivotTableRenderer(data, opts)).heatmap("heatmap", opts);
},
"Row Heatmap": function(data, opts) {
return $(pivotTableRenderer(data, opts)).heatmap("rowheatmap", opts);
},
"Col Heatmap": function(data, opts) {
return $(pivotTableRenderer(data, opts)).heatmap("colheatmap", opts);
}
};
locales = {
en: {
aggregators: aggregators,
renderers: renderers,
localeStrings: {
renderError: "An error occurred rendering the PivotTable results.",
computeError: "An error occurred computing the PivotTable results.",
uiRenderError: "An error occurred rendering the PivotTable UI.",
selectAll: "Select All",
selectNone: "Select None",
tooMany: "(too many to list)",
filterResults: "Filter values",
apply: "Apply",
cancel: "Cancel",
totals: "Totals",
vs: "vs",
by: "by"
}
}
};
mthNamesEn = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
dayNamesEn = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
zeroPad = function(number) {
return ("0" + number).substr(-2, 2);
};
derivers = {
bin: function(col, binWidth) {
return function(record) {
return record[col] - record[col] % binWidth;
};
},
dateFormat: function(col, formatString, utcOutput, mthNames, dayNames) {
var utc;
if (utcOutput == null) {
utcOutput = false;
}
if (mthNames == null) {
mthNames = mthNamesEn;
}
if (dayNames == null) {
dayNames = dayNamesEn;
}
utc = utcOutput ? "UTC" : "";
return function(record) {
var date;
date = new Date(Date.parse(record[col]));
if (isNaN(date)) {
return "";
}
return formatString.replace(/%(.)/g, function(m, p) {
switch (p) {
case "y":
return date["get" + utc + "FullYear"]();
case "m":
return zeroPad(date["get" + utc + "Month"]() + 1);
case "n":
return mthNames[date["get" + utc + "Month"]()];
case "d":
return zeroPad(date["get" + utc + "Date"]());
case "w":
return dayNames[date["get" + utc + "Day"]()];
case "x":
return date["get" + utc + "Day"]();
case "H":
return zeroPad(date["get" + utc + "Hours"]());
case "M":
return zeroPad(date["get" + utc + "Minutes"]());
case "S":
return zeroPad(date["get" + utc + "Seconds"]());
default:
return "%" + p;
}
});
};
}
};
rx = /(\d+)|(\D+)/g;
rd = /\d/;
rz = /^0/;
naturalSort = (function(_this) {
return function(as, bs) {
var a, a1, b, b1, nas, nbs;
if ((bs != null) && (as == null)) {
return -1;
}
if ((as != null) && (bs == null)) {
return 1;
}
if (typeof as === "number" && isNaN(as)) {
return -1;
}
if (typeof bs === "number" && isNaN(bs)) {
return 1;
}
nas = +as;
nbs = +bs;
if (nas < nbs) {
return -1;
}
if (nas > nbs) {
return 1;
}
if (typeof as === "number" && typeof bs !== "number") {
return -1;
}
if (typeof bs === "number" && typeof as !== "number") {
return 1;
}
if (typeof as === "number" && typeof bs === "number") {
return 0;
}
if (isNaN(nbs) && !isNaN(nas)) {
return -1;
}
if (isNaN(nas) && !isNaN(nbs)) {
return 1;
}
a = String(as);
b = String(bs);
if (a === b) {
return 0;
}
if (!(rd.test(a) && rd.test(b))) {
return (a > b ? 1 : -1);
}
a = a.match(rx);
b = b.match(rx);
while (a.length && b.length) {
a1 = a.shift();
b1 = b.shift();
if (a1 !== b1) {
if (rd.test(a1) && rd.test(b1)) {
return a1.replace(rz, ".0") - b1.replace(rz, ".0");
} else {
return (a1 > b1 ? 1 : -1);
}
}
}
return a.length - b.length;
};
})(this);
sortAs = function(order) {
var i, l_mapping, mapping, x;
mapping = {};
l_mapping = {};
for (i in order) {
x = order[i];
mapping[x] = i;
if (typeof x === "string") {
l_mapping[x.toLowerCase()] = i;
}
}
return function(a, b) {
if ((mapping[a] != null) && (mapping[b] != null)) {
return mapping[a] - mapping[b];
} else if (mapping[a] != null) {
return -1;
} else if (mapping[b] != null) {
return 1;
} else if ((l_mapping[a] != null) && (l_mapping[b] != null)) {
return l_mapping[a] - l_mapping[b];
} else if (l_mapping[a] != null) {
return -1;
} else if (l_mapping[b] != null) {
return 1;
} else {
return naturalSort(a, b);
}
};
};
getSort = function(sorters, attr) {
var sort;
if (sorters != null) {
if ($.isFunction(sorters)) {
sort = sorters(attr);
if ($.isFunction(sort)) {
return sort;
}
} else if (sorters[attr] != null) {
return sorters[attr];
}
}
return naturalSort;
};
/*
Data Model class
*/
PivotData = (function() {
function PivotData(input, opts) {
var ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9;
if (opts == null) {
opts = {};
}
this.getAggregator = bind(this.getAggregator, this);
this.getRowKeys = bind(this.getRowKeys, this);
this.getColKeys = bind(this.getColKeys, this);
this.sortKeys = bind(this.sortKeys, this);
this.arrSort = bind(this.arrSort, this);
this.input = input;
this.aggregator = (ref = opts.aggregator) != null ? ref : aggregatorTemplates.count()();
this.aggregatorName = (ref1 = opts.aggregatorName) != null ? ref1 : "Count";
this.colAttrs = (ref2 = opts.cols) != null ? ref2 : [];
this.rowAttrs = (ref3 = opts.rows) != null ? ref3 : [];
this.valAttrs = (ref4 = opts.vals) != null ? ref4 : [];
this.sorters = (ref5 = opts.sorters) != null ? ref5 : {};
this.rowOrder = (ref6 = opts.rowOrder) != null ? ref6 : "key_a_to_z";
this.colOrder = (ref7 = opts.colOrder) != null ? ref7 : "key_a_to_z";
this.derivedAttributes = (ref8 = opts.derivedAttributes) != null ? ref8 : {};
this.filter = (ref9 = opts.filter) != null ? ref9 : (function() {
return true;
});
this.tree = {};
this.rowKeys = [];
this.colKeys = [];
this.rowTotals = {};
this.colTotals = {};
this.allTotal = this.aggregator(this, [], []);
this.sorted = false;
PivotData.forEachRecord(this.input, this.derivedAttributes, (function(_this) {
return function(record) {
if (_this.filter(record)) {
return _this.processRecord(record);
}
};
})(this));
}
PivotData.forEachRecord = function(input, derivedAttributes, f) {
var addRecord, compactRecord, i, j, k, l, len1, record, ref, results, results1, tblCols;
if ($.isEmptyObject(derivedAttributes)) {
addRecord = f;
} else {
addRecord = function(record) {
var k, ref, v;
for (k in derivedAttributes) {
v = derivedAttributes[k];
record[k] = (ref = v(record)) != null ? ref : record[k];
}
return f(record);
};
}
if ($.isFunction(input)) {
return input(addRecord);
} else if ($.isArray(input)) {
if ($.isArray(input[0])) {
results = [];
for (i in input) {
if (!hasProp.call(input, i)) continue;
compactRecord = input[i];
if (!(i > 0)) {
continue;
}
record = {};
ref = input[0];
for (j in ref) {
if (!hasProp.call(ref, j)) continue;
k = ref[j];
record[k] = compactRecord[j];
}
results.push(addRecord(record));
}
return results;
} else {
results1 = [];
for (l = 0, len1 = input.length; l < len1; l++) {
record = input[l];
results1.push(addRecord(record));
}
return results1;
}
} else if (input instanceof $) {
tblCols = [];
$("thead > tr > th", input).each(function(i) {
return tblCols.push($(this).text());
});
return $("tbody > tr", input).each(function(i) {
record = {};
$("td", this).each(function(j) {
return record[tblCols[j]] = $(this).text();
});
return addRecord(record);
});
} else {
throw new Error("unknown input format");
}
};
PivotData.prototype.forEachMatchingRecord = function(criteria, callback) {
return PivotData.forEachRecord(this.input, this.derivedAttributes, (function(_this) {
return function(record) {
var k, ref, v;
if (!_this.filter(record)) {
return;
}
for (k in criteria) {
v = criteria[k];
if (v !== ((ref = record[k]) != null ? ref : "null")) {
return;
}
}
return callback(record);
};
})(this));
};
PivotData.prototype.arrSort = function(attrs) {
var a, sortersArr;
sortersArr = (function() {
var l, len1, results;
results = [];
for (l = 0, len1 = attrs.length; l < len1; l++) {
a = attrs[l];
results.push(getSort(this.sorters, a));
}
return results;
}).call(this);
return function(a, b) {
var comparison, i, sorter;
for (i in sortersArr) {
if (!hasProp.call(sortersArr, i)) continue;
sorter = sortersArr[i];
comparison = sorter(a[i], b[i]);
if (comparison !== 0) {
return comparison;
}
}
return 0;
};
};
PivotData.prototype.sortKeys = function() {
var v;
if (!this.sorted) {
this.sorted = true;
v = (function(_this) {
return function(r, c) {
return _this.getAggregator(r, c).value();
};
})(this);
switch (this.rowOrder) {
case "value_a_to_z":
this.rowKeys.sort((function(_this) {
return function(a, b) {
return naturalSort(v(a, []), v(b, []));
};
})(this));
break;
case "value_z_to_a":
this.rowKeys.sort((function(_this) {
return function(a, b) {
return -naturalSort(v(a, []), v(b, []));
};
})(this));
break;
default:
this.rowKeys.sort(this.arrSort(this.rowAttrs));
}
switch (this.colOrder) {
case "value_a_to_z":
return this.colKeys.sort((function(_this) {
return function(a, b) {
return naturalSort(v([], a), v([], b));
};
})(this));
case "value_z_to_a":
return this.colKeys.sort((function(_this) {
return function(a, b) {
return -naturalSort(v([], a), v([], b));
};
})(this));
default:
return this.colKeys.sort(this.arrSort(this.colAttrs));
}
}
};
PivotData.prototype.getColKeys = function() {
this.sortKeys();
return this.colKeys;
};
PivotData.prototype.getRowKeys = function() {
this.sortKeys();
return this.rowKeys;
};
PivotData.prototype.processRecord = function(record) {
var colKey, flatColKey, flatRowKey, l, len1, len2, n, ref, ref1, ref2, ref3, rowKey, x;
colKey = [];
rowKey = [];
ref = this.colAttrs;
for (l = 0, len1 = ref.length; l < len1; l++) {
x = ref[l];
colKey.push((ref1 = record[x]) != null ? ref1 : "null");
}
ref2 = this.rowAttrs;
for (n = 0, len2 = ref2.length; n < len2; n++) {
x = ref2[n];
rowKey.push((ref3 = record[x]) != null ? ref3 : "null");
}
flatRowKey = rowKey.join(String.fromCharCode(0));
flatColKey = colKey.join(String.fromCharCode(0));
this.allTotal.push(record);
if (rowKey.length !== 0) {
if (!this.rowTotals[flatRowKey]) {
this.rowKeys.push(rowKey);
this.rowTotals[flatRowKey] = this.aggregator(this, rowKey, []);
}
this.rowTotals[flatRowKey].push(record);
}
if (colKey.length !== 0) {
if (!this.colTotals[flatColKey]) {
this.colKeys.push(colKey);
this.colTotals[flatColKey] = this.aggregator(this, [], colKey);
}
this.colTotals[flatColKey].push(record);
}
if (colKey.length !== 0 && rowKey.length !== 0) {
if (!this.tree[flatRowKey]) {
this.tree[flatRowKey] = {};
}
if (!this.tree[flatRowKey][flatColKey]) {
this.tree[flatRowKey][flatColKey] = this.aggregator(this, rowKey, colKey);
}
return this.tree[flatRowKey][flatColKey].push(record);
}
};
PivotData.prototype.getAggregator = function(rowKey, colKey) {
var agg, flatColKey, flatRowKey;
flatRowKey = rowKey.join(String.fromCharCode(0));
flatColKey = colKey.join(String.fromCharCode(0));
if (rowKey.length === 0 && colKey.length === 0) {
agg = this.allTotal;
} else if (rowKey.length === 0) {
agg = this.colTotals[flatColKey];
} else if (colKey.length === 0) {
agg = this.rowTotals[flatRowKey];
} else {
agg = this.tree[flatRowKey][flatColKey];
}
return agg != null ? agg : {
value: (function() {
return null;
}),
format: function() {
return "";
}
};
};
return PivotData;
})();
$.pivotUtilities = {
aggregatorTemplates: aggregatorTemplates,
aggregators: aggregators,
renderers: renderers,
derivers: derivers,
locales: locales,
naturalSort: naturalSort,
numberFormat: numberFormat,
sortAs: sortAs,
PivotData: PivotData
};
/*
Default Renderer for hierarchical table layout
*/
pivotTableRenderer = function(pivotData, opts) {
var aggregator, c, colAttrs, colKey, colKeys, defaults, getClickHandler, i, j, r, result, rowAttrs, rowKey, rowKeys, spanSize, tbody, td, th, thead, totalAggregator, tr, txt, val, x;
defaults = {
table: {
clickCallback: null
},
localeStrings: {
totals: "Totals"
}
};
opts = $.extend(true, {}, defaults, opts);
colAttrs = pivotData.colAttrs;
rowAttrs = pivotData.rowAttrs;
rowKeys = pivotData.getRowKeys();
colKeys = pivotData.getColKeys();
if (opts.table.clickCallback) {
getClickHandler = function(value, rowValues, colValues) {
var attr, filters, i;
filters = {};
for (i in colAttrs) {
if (!hasProp.call(colAttrs, i)) continue;
attr = colAttrs[i];
if (colValues[i] != null) {
filters[attr] = colValues[i];
}
}
for (i in rowAttrs) {
if (!hasProp.call(rowAttrs, i)) continue;
attr = rowAttrs[i];
if (rowValues[i] != null) {
filters[attr] = rowValues[i];
}
}
return function(e) {
return opts.table.clickCallback(e, value, filters, pivotData);
};
};
}
result = document.createElement("table");
result.className = "pvtTable";
spanSize = function(arr, i, j) {
var l, len, n, noDraw, ref, ref1, stop, x;
if (i !== 0) {
noDraw = true;
for (x = l = 0, ref = j; 0 <= ref ? l <= ref : l >= ref; x = 0 <= ref ? ++l : --l) {
if (arr[i - 1][x] !== arr[i][x]) {
noDraw = false;
}
}
if (noDraw) {
return -1;
}
}
len = 0;
while (i + len < arr.length) {
stop = false;
for (x = n = 0, ref1 = j; 0 <= ref1 ? n <= ref1 : n >= ref1; x = 0 <= ref1 ? ++n : --n) {
if (arr[i][x] !== arr[i + len][x]) {
stop = true;
}
}
if (stop) {
break;
}
len++;
}
return len;
};
thead = document.createElement("thead");
for (j in colAttrs) {
if (!hasProp.call(colAttrs, j)) continue;
c = colAttrs[j];
tr = document.createElement("tr");
if (parseInt(j) === 0 && rowAttrs.length !== 0) {
th = document.createElement("th");
th.setAttribute("colspan", rowAttrs.length);
th.setAttribute("rowspan", colAttrs.length);
tr.appendChild(th);
}
th = document.createElement("th");
th.className = "pvtAxisLabel";
th.textContent = c;
tr.appendChild(th);
for (i in colKeys) {
if (!hasProp.call(colKeys, i)) continue;
colKey = colKeys[i];
x = spanSize(colKeys, parseInt(i), parseInt(j));
if (x !== -1) {
th = document.createElement("th");
th.className = "pvtColLabel";
th.textContent = colKey[j];
th.setAttribute("colspan", x);
if (parseInt(j) === colAttrs.length - 1 && rowAttrs.length !== 0) {
th.setAttribute("rowspan", 2);
}
tr.appendChild(th);
}
}
if (parseInt(j) === 0) {
th = document.createElement("th");
th.className = "pvtTotalLabel pvtRowTotalLabel";
th.innerHTML = opts.localeStrings.totals;
th.setAttribute("rowspan", colAttrs.length + (rowAttrs.length === 0 ? 0 : 1));
tr.appendChild(th);
}
thead.appendChild(tr);
}
if (rowAttrs.length !== 0) {
tr = document.createElement("tr");
for (i in rowAttrs) {
if (!hasProp.call(rowAttrs, i)) continue;
r = rowAttrs[i];
th = document.createElement("th");
th.className = "pvtAxisLabel";
th.textContent = r;
tr.appendChild(th);
}
th = document.createElement("th");
if (colAttrs.length === 0) {
th.className = "pvtTotalLabel pvtRowTotalLabel";
th.innerHTML = opts.localeStrings.totals;
}
tr.appendChild(th);
thead.appendChild(tr);
}
result.appendChild(thead);
tbody = document.createElement("tbody");
for (i in rowKeys) {
if (!hasProp.call(rowKeys, i)) continue;
rowKey = rowKeys[i];
tr = document.createElement("tr");
for (j in rowKey) {
if (!hasProp.call(rowKey, j)) continue;
txt = rowKey[j];
x = spanSize(rowKeys, parseInt(i), parseInt(j));
if (x !== -1) {
th = document.createElement("th");
th.className = "pvtRowLabel";
th.textContent = txt;
th.setAttribute("rowspan", x);
if (parseInt(j) === rowAttrs.length - 1 && colAttrs.length !== 0) {
th.setAttribute("colspan", 2);
}
tr.appendChild(th);
}
}
for (j in colKeys) {
if (!hasProp.call(colKeys, j)) continue;
colKey = colKeys[j];
aggregator = pivotData.getAggregator(rowKey, colKey);
val = aggregator.value();
td = document.createElement("td");
td.className = "pvtVal row" + i + " col" + j;
td.textContent = aggregator.format(val);
td.setAttribute("data-value", val);
if (getClickHandler != null) {
td.onclick = getClickHandler(val, rowKey, colKey);
}
tr.appendChild(td);
}
totalAggregator = pivotData.getAggregator(rowKey, []);
val = totalAggregator.value();
td = document.createElement("td");
td.className = "pvtTotal rowTotal";
td.textContent = totalAggregator.format(val);
td.setAttribute("data-value", val);
if (getClickHandler != null) {
td.onclick = getClickHandler(val, rowKey, []);
}
td.setAttribute("data-for", "row" + i);
tr.appendChild(td);
tbody.appendChild(tr);
}
tr = document.createElement("tr");
th = document.createElement("th");
th.className = "pvtTotalLabel pvtColTotalLabel";
th.innerHTML = opts.localeStrings.totals;
th.setAttribute("colspan", rowAttrs.length + (colAttrs.length === 0 ? 0 : 1));
tr.appendChild(th);
for (j in colKeys) {
if (!hasProp.call(colKeys, j)) continue;
colKey = colKeys[j];
totalAggregator = pivotData.getAggregator([], colKey);
val = totalAggregator.value();
td = document.createElement("td");
td.className = "pvtTotal colTotal";
td.textContent = totalAggregator.format(val);
td.setAttribute("data-value", val);
if (getClickHandler != null) {
td.onclick = getClickHandler(val, [], colKey);
}
td.setAttribute("data-for", "col" + j);
tr.appendChild(td);
}
totalAggregator = pivotData.getAggregator([], []);
val = totalAggregator.value();
td = document.createElement("td");
td.className = "pvtGrandTotal";
td.textContent = totalAggregator.format(val);
td.setAttribute("data-value", val);
if (getClickHandler != null) {
td.onclick = getClickHandler(val, [], []);
}
tr.appendChild(td);
tbody.appendChild(tr);
result.appendChild(tbody);
result.setAttribute("data-numrows", rowKeys.length);
result.setAttribute("data-numcols", colKeys.length);
return result;
};
/*
Pivot Table core: create PivotData object and call Renderer on it
*/
$.fn.pivot = function(input, inputOpts, locale) {
var defaults, e, localeDefaults, localeStrings, opts, pivotData, result, x;
if (locale == null) {
locale = "en";
}
if (locales[locale] == null) {
locale = "en";
}
defaults = {
cols: [],
rows: [],
vals: [],
rowOrder: "key_a_to_z",
colOrder: "key_a_to_z",
dataClass: PivotData,
filter: function() {
return true;
},
aggregator: aggregatorTemplates.count()(),
aggregatorName: "Count",
sorters: {},
derivedAttributes: {},
renderer: pivotTableRenderer
};
localeStrings = $.extend(true, {}, locales.en.localeStrings, locales[locale].localeStrings);
localeDefaults = {
rendererOptions: {
localeStrings: localeStrings
},
localeStrings: localeStrings
};
opts = $.extend(true, {}, localeDefaults, $.extend({}, defaults, inputOpts));
result = null;
try {
pivotData = new opts.dataClass(input, opts);
try {
result = opts.renderer(pivotData, opts.rendererOptions);
} catch (_error) {
e = _error;
if (typeof console !== "undefined" && console !== null) {
console.error(e.stack);
}
result = $("<span>").html(opts.localeStrings.renderError);
}
} catch (_error) {
e = _error;
if (typeof console !== "undefined" && console !== null) {
console.error(e.stack);
}
result = $("<span>").html(opts.localeStrings.computeError);
}
x = this[0];
while (x.hasChildNodes()) {
x.removeChild(x.lastChild);
}
return this.append(result);
};
/*
Pivot Table UI: calls Pivot Table core above with options set by user
*/
$.fn.pivotUI = function(input, inputOpts, overwrite, locale) {
var a, aggregator, attr, attrLength, attrValues, c, colOrderArrow, defaults, e, existingOpts, fn1, i, initialRender, l, len1, len2, len3, localeDefaults, localeStrings, materializedInput, n, o, opts, ordering, pivotTable, recordsProcessed, ref, ref1, ref2, ref3, refresh, refreshDelayed, renderer, rendererControl, rowOrderArrow, shownAttributes, shownInAggregators, shownInDragDrop, tr1, tr2, uiTable, unused, unusedAttrsVerticalAutoCutoff, unusedAttrsVerticalAutoOverride, x;
if (overwrite == null) {
overwrite = false;
}
if (locale == null) {
locale = "en";
}
if (locales[locale] == null) {
locale = "en";
}
defaults = {
derivedAttributes: {},
aggregators: locales[locale].aggregators,
renderers: locales[locale].renderers,
hiddenAttributes: [],
hiddenFromAggregators: [],
hiddenFromDragDrop: [],
menuLimit: 500,
cols: [],
rows: [],
vals: [],
rowOrder: "key_a_to_z",
colOrder: "key_a_to_z",
dataClass: PivotData,
exclusions: {},
inclusions: {},
unusedAttrsVertical: 85,
autoSortUnusedAttrs: false,
onRefresh: null,
filter: function() {
return true;
},
sorters: {}
};
localeStrings = $.extend(true, {}, locales.en.localeStrings, locales[locale].localeStrings);
localeDefaults = {
rendererOptions: {
localeStrings: localeStrings
},
localeStrings: localeStrings
};
existingOpts = this.data("pivotUIOptions");
if ((existingOpts == null) || overwrite) {
opts = $.extend(true, {}, localeDefaults, $.extend({}, defaults, inputOpts));
} else {
opts = existingOpts;
}
try {
attrValues = {};
materializedInput = [];
recordsProcessed = 0;
PivotData.forEachRecord(input, opts.derivedAttributes, function(record) {
var attr, base, ref, value;
if (!opts.filter(record)) {
return;
}
materializedInput.push(record);
for (attr in record) {
if (!hasProp.call(record, attr)) continue;
if (attrValues[attr] == null) {
attrValues[attr] = {};
if (recordsProcessed > 0) {
attrValues[attr]["null"] = recordsProcessed;
}
}
}
for (attr in attrValues) {
value = (ref = record[attr]) != null ? ref : "null";
if ((base = attrValues[attr])[value] == null) {
base[value] = 0;
}
attrValues[attr][value]++;
}
return recordsProcessed++;
});
uiTable = $("<table>", {
"class": "pvtUi"
}).attr("cellpadding", 5);
rendererControl = $("<td>");
renderer = $("<select>").addClass('pvtRenderer').appendTo(rendererControl).bind("change", function() {
return refresh();
});
ref = opts.renderers;
for (x in ref) {
if (!hasProp.call(ref, x)) continue;
$("<option>").val(x).html(x).appendTo(renderer);
}
unused = $("<td>").addClass('pvtAxisContainer pvtUnused');
shownAttributes = (function() {
var results;
results = [];
for (a in attrValues) {
if (indexOf.call(opts.hiddenAttributes, a) < 0) {
results.push(a);
}
}
return results;
})();
shownInAggregators = (function() {
var l, len1, results;
results = [];
for (l = 0, len1 = shownAttributes.length; l < len1; l++) {
c = shownAttributes[l];
if (indexOf.call(opts.hiddenFromAggregators, c) < 0) {
results.push(c);
}
}
return results;
})();
shownInDragDrop = (function() {
var l, len1, results;
results = [];
for (l = 0, len1 = shownAttributes.length; l < len1; l++) {
c = shownAttributes[l];
if (indexOf.call(opts.hiddenFromDragDrop, c) < 0) {
results.push(c);
}
}
return results;
})();
unusedAttrsVerticalAutoOverride = false;
if (opts.unusedAttrsVertical === "auto") {
unusedAttrsVerticalAutoCutoff = 120;
} else {
unusedAttrsVerticalAutoCutoff = parseInt(opts.unusedAttrsVertical);
}
if (!isNaN(unusedAttrsVerticalAutoCutoff)) {
attrLength = 0;
for (l = 0, len1 = shownInDragDrop.length; l < len1; l++) {
a = shownInDragDrop[l];
attrLength += a.length;
}
unusedAttrsVerticalAutoOverride = attrLength > unusedAttrsVerticalAutoCutoff;
}
if (opts.unusedAttrsVertical === true || unusedAttrsVerticalAutoOverride) {
unused.addClass('pvtVertList');
} else {
unused.addClass('pvtHorizList');
}
fn1 = function(attr) {
var attrElem, checkContainer, closeFilterBox, controls, filterItem, filterItemExcluded, finalButtons, hasExcludedItem, len2, n, placeholder, ref1, sorter, triangleLink, v, value, valueCount, valueList, values;
values = (function() {
var results;
results = [];
for (v in attrValues[attr]) {
results.push(v);
}
return results;
})();
hasExcludedItem = false;
valueList = $("<div>").addClass('pvtFilterBox').hide();
valueList.append($("<h4>").append($("<span>").text(attr), $("<span>").addClass("count").text("(" + values.length + ")")));
if (values.length > opts.menuLimit) {
valueList.append($("<p>").html(opts.localeStrings.tooMany));
} else {
if (values.length > 5) {
controls = $("<p>").appendTo(valueList);
sorter = getSort(opts.sorters, attr);
placeholder = opts.localeStrings.filterResults;
$("<input>", {
type: "text"
}).appendTo(controls).attr({
placeholder: placeholder,
"class": "pvtSearch"
}).bind("keyup", function() {
var accept, accept_gen, filter;
filter = $(this).val().toLowerCase().trim();
accept_gen = function(prefix, accepted) {
return function(v) {
var real_filter, ref1;
real_filter = filter.substring(prefix.length).trim();
if (real_filter.length === 0) {
return true;
}
return ref1 = Math.sign(sorter(v.toLowerCase(), real_filter)), indexOf.call(accepted, ref1) >= 0;
};
};
accept = filter.startsWith(">=") ? accept_gen(">=", [1, 0]) : filter.startsWith("<=") ? accept_gen("<=", [-1, 0]) : filter.startsWith(">") ? accept_gen(">", [1]) : filter.startsWith("<") ? accept_gen("<", [-1]) : filter.startsWith("~") ? function(v) {
if (filter.substring(1).trim().length === 0) {
return true;
}
return v.toLowerCase().match(filter.substring(1));
} : function(v) {
return v.toLowerCase().indexOf(filter) !== -1;
};
return valueList.find('.pvtCheckContainer p label span.value').each(function() {
if (accept($(this).text())) {
return $(this).parent().parent().show();
} else {
return $(this).parent().parent().hide();
}
});
});
controls.append($("<br>"));
$("<button>", {
type: "button"
}).appendTo(controls).html(opts.localeStrings.selectAll).bind("click", function() {
valueList.find("input:visible:not(:checked)").prop("checked", true).toggleClass("changed");
return false;
});
$("<button>", {
type: "button"
}).appendTo(controls).html(opts.localeStrings.selectNone).bind("click", function() {
valueList.find("input:visible:checked").prop("checked", false).toggleClass("changed");
return false;
});
}
checkContainer = $("<div>").addClass("pvtCheckContainer").appendTo(valueList);
ref1 = values.sort(getSort(opts.sorters, attr));
for (n = 0, len2 = ref1.length; n < len2; n++) {
value = ref1[n];
valueCount = attrValues[attr][value];
filterItem = $("<label>");
filterItemExcluded = false;
if (opts.inclusions[attr]) {
filterItemExcluded = (indexOf.call(opts.inclusions[attr], value) < 0);
} else if (opts.exclusions[attr]) {
filterItemExcluded = (indexOf.call(opts.exclusions[attr], value) >= 0);
}
hasExcludedItem || (hasExcludedItem = filterItemExcluded);
$("<input>").attr("type", "checkbox").addClass('pvtFilter').attr("checked", !filterItemExcluded).data("filter", [attr, value]).appendTo(filterItem).bind("change", function() {
return $(this).toggleClass("changed");
});
filterItem.append($("<span>").addClass("value").text(value));
filterItem.append($("<span>").addClass("count").text("(" + valueCount + ")"));
checkContainer.append($("<p>").append(filterItem));
}
}
closeFilterBox = function() {
if (valueList.find("[type='checkbox']").length > valueList.find("[type='checkbox']:checked").length) {
attrElem.addClass("pvtFilteredAttribute");
} else {
attrElem.removeClass("pvtFilteredAttribute");
}
valueList.find('.pvtSearch').val('');
valueList.find('.pvtCheckContainer p').show();
return valueList.hide();
};
finalButtons = $("<p>").appendTo(valueList);
if (values.length <= opts.menuLimit) {
$("<button>", {
type: "button"
}).text(opts.localeStrings.apply).appendTo(finalButtons).bind("click", function() {
if (valueList.find(".changed").removeClass("changed").length) {
refresh();
}
return closeFilterBox();
});
}
$("<button>", {
type: "button"
}).text(opts.localeStrings.cancel).appendTo(finalButtons).bind("click", function() {
valueList.find(".changed:checked").removeClass("changed").prop("checked", false);
valueList.find(".changed:not(:checked)").removeClass("changed").prop("checked", true);
return closeFilterBox();
});
triangleLink = $("<span>").addClass('pvtTriangle').html(" ▾").bind("click", function(e) {
var left, ref2, top;
ref2 = $(e.currentTarget).position(), left = ref2.left, top = ref2.top;
return valueList.css({
left: left + 10,
top: top + 10
}).show();
});
attrElem = $("<li>").addClass("axis_" + i).append($("<span>").addClass('pvtAttr').text(attr).data("attrName", attr).append(triangleLink));
if (hasExcludedItem) {
attrElem.addClass('pvtFilteredAttribute');
}
return unused.append(attrElem).append(valueList);
};
for (i in shownInDragDrop) {
if (!hasProp.call(shownInDragDrop, i)) continue;
attr = shownInDragDrop[i];
fn1(attr);
}
tr1 = $("<tr>").appendTo(uiTable);
aggregator = $("<select>").addClass('pvtAggregator').bind("change", function() {
return refresh();
});
ref1 = opts.aggregators;
for (x in ref1) {
if (!hasProp.call(ref1, x)) continue;
aggregator.append($("<option>").val(x).html(x));
}
ordering = {
key_a_to_z: {
rowSymbol: "↕",
colSymbol: "↔",
next: "value_a_to_z"
},
value_a_to_z: {
rowSymbol: "↓",
colSymbol: "→",
next: "value_z_to_a"
},
value_z_to_a: {
rowSymbol: "↑",
colSymbol: "←",
next: "key_a_to_z"
}
};
rowOrderArrow = $("<a>", {
role: "button"
}).addClass("pvtRowOrder").data("order", opts.rowOrder).html(ordering[opts.rowOrder].rowSymbol).bind("click", function() {
$(this).data("order", ordering[$(this).data("order")].next);
$(this).html(ordering[$(this).data("order")].rowSymbol);
return refresh();
});
colOrderArrow = $("<a>", {
role: "button"
}).addClass("pvtColOrder").data("order", opts.colOrder).html(ordering[opts.colOrder].colSymbol).bind("click", function() {
$(this).data("order", ordering[$(this).data("order")].next);
$(this).html(ordering[$(this).data("order")].colSymbol);
return refresh();
});
$("<td>").addClass('pvtVals').appendTo(tr1).append(aggregator).append(rowOrderArrow).append(colOrderArrow).append($("<br>"));
$("<td>").addClass('pvtAxisContainer pvtHorizList pvtCols').appendTo(tr1);
tr2 = $("<tr>").appendTo(uiTable);
tr2.append($("<td>").addClass('pvtAxisContainer pvtRows').attr("valign", "top"));
pivotTable = $("<td>").attr("valign", "top").addClass('pvtRendererArea').appendTo(tr2);
if (opts.unusedAttrsVertical === true || unusedAttrsVerticalAutoOverride) {
uiTable.find('tr:nth-child(1)').prepend(rendererControl);
uiTable.find('tr:nth-child(2)').prepend(unused);
} else {
uiTable.prepend($("<tr>").append(rendererControl).append(unused));
}
this.html(uiTable);
ref2 = opts.cols;
for (n = 0, len2 = ref2.length; n < len2; n++) {
x = ref2[n];
this.find(".pvtCols").append(this.find(".axis_" + ($.inArray(x, shownInDragDrop))));
}
ref3 = opts.rows;
for (o = 0, len3 = ref3.length; o < len3; o++) {
x = ref3[o];
this.find(".pvtRows").append(this.find(".axis_" + ($.inArray(x, shownInDragDrop))));
}
if (opts.aggregatorName != null) {
this.find(".pvtAggregator").val(opts.aggregatorName);
}
if (opts.rendererName != null) {
this.find(".pvtRenderer").val(opts.rendererName);
}
initialRender = true;
refreshDelayed = (function(_this) {
return function() {
var exclusions, inclusions, len4, newDropdown, numInputsToProcess, pivotUIOptions, pvtVals, ref4, ref5, subopts, t, u, unusedAttrsContainer, vals;
subopts = {
derivedAttributes: opts.derivedAttributes,
localeStrings: opts.localeStrings,
rendererOptions: opts.rendererOptions,
sorters: opts.sorters,
cols: [],
rows: [],
dataClass: opts.dataClass
};
numInputsToProcess = (ref4 = opts.aggregators[aggregator.val()]([])().numInputs) != null ? ref4 : 0;
vals = [];
_this.find(".pvtRows li span.pvtAttr").each(function() {
return subopts.rows.push($(this).data("attrName"));
});
_this.find(".pvtCols li span.pvtAttr").each(function() {
return subopts.cols.push($(this).data("attrName"));
});
_this.find(".pvtVals select.pvtAttrDropdown").each(function() {
if (numInputsToProcess === 0) {
return $(this).remove();
} else {
numInputsToProcess--;
if ($(this).val() !== "") {
return vals.push($(this).val());
}
}
});
if (numInputsToProcess !== 0) {
pvtVals = _this.find(".pvtVals");
for (x = t = 0, ref5 = numInputsToProcess; 0 <= ref5 ? t < ref5 : t > ref5; x = 0 <= ref5 ? ++t : --t) {
newDropdown = $("<select>").addClass('pvtAttrDropdown').append($("<option>")).bind("change", function() {
return refresh();
});
for (u = 0, len4 = shownInAggregators.length; u < len4; u++) {
attr = shownInAggregators[u];
newDropdown.append($("<option>").val(attr).text(attr));
}
pvtVals.append(newDropdown);
}
}
if (initialRender) {
vals = opts.vals;
i = 0;
_this.find(".pvtVals select.pvtAttrDropdown").each(function() {
$(this).val(vals[i]);
return i++;
});
initialRender = false;
}
subopts.aggregatorName = aggregator.val();
subopts.vals = vals;
subopts.aggregator = opts.aggregators[aggregator.val()](vals);
subopts.renderer = opts.renderers[renderer.val()];
subopts.rowOrder = rowOrderArrow.data("order");
subopts.colOrder = colOrderArrow.data("order");
exclusions = {};
_this.find('input.pvtFilter').not(':checked').each(function() {
var filter;
filter = $(this).data("filter");
if (exclusions[filter[0]] != null) {
return exclusions[filter[0]].push(filter[1]);
} else {
return exclusions[filter[0]] = [filter[1]];
}
});
inclusions = {};
_this.find('input.pvtFilter:checked').each(function() {
var filter;
filter = $(this).data("filter");
if (exclusions[filter[0]] != null) {
if (inclusions[filter[0]] != null) {
return inclusions[filter[0]].push(filter[1]);
} else {
return inclusions[filter[0]] = [filter[1]];
}
}
});
subopts.filter = function(record) {
var excludedItems, k, ref6, ref7;
if (!opts.filter(record)) {
return false;
}
for (k in exclusions) {
excludedItems = exclusions[k];
if (ref6 = "" + ((ref7 = record[k]) != null ? ref7 : 'null'), indexOf.call(excludedItems, ref6) >= 0) {
return false;
}
}
return true;
};
pivotTable.pivot(materializedInput, subopts);
pivotUIOptions = $.extend({}, opts, {
cols: subopts.cols,
rows: subopts.rows,
colOrder: subopts.colOrder,
rowOrder: subopts.rowOrder,
vals: vals,
exclusions: exclusions,
inclusions: inclusions,
inclusionsInfo: inclusions,
aggregatorName: aggregator.val(),
rendererName: renderer.val()
});
_this.data("pivotUIOptions", pivotUIOptions);
if (opts.autoSortUnusedAttrs) {
unusedAttrsContainer = _this.find("td.pvtUnused.pvtAxisContainer");
$(unusedAttrsContainer).children("li").sort(function(a, b) {
return naturalSort($(a).text(), $(b).text());
}).appendTo(unusedAttrsContainer);
}
pivotTable.css("opacity", 1);
if (opts.onRefresh != null) {
return opts.onRefresh(pivotUIOptions);
}
};
})(this);
refresh = (function(_this) {
return function() {
pivotTable.css("opacity", 0.5);
return setTimeout(refreshDelayed, 10);
};
})(this);
refresh();
this.find(".pvtAxisContainer").sortable({
update: function(e, ui) {
if (ui.sender == null) {
return refresh();
}
},
connectWith: this.find(".pvtAxisContainer"),
items: 'li',
placeholder: 'pvtPlaceholder'
});
} catch (_error) {
e = _error;
if (typeof console !== "undefined" && console !== null) {
console.error(e.stack);
}
this.html(opts.localeStrings.uiRenderError);
}
return this;
};
/*
Heatmap post-processing
*/
$.fn.heatmap = function(scope, opts) {
var colorScaleGenerator, heatmapper, i, j, l, n, numCols, numRows, ref, ref1, ref2;
if (scope == null) {
scope = "heatmap";
}
numRows = this.data("numrows");
numCols = this.data("numcols");
colorScaleGenerator = opts != null ? (ref = opts.heatmap) != null ? ref.colorScaleGenerator : void 0 : void 0;
if (colorScaleGenerator == null) {
colorScaleGenerator = function(values) {
var max, min;
min = Math.min.apply(Math, values);
max = Math.max.apply(Math, values);
return function(x) {
var nonRed;
nonRed = 255 - Math.round(255 * (x - min) / (max - min));
return "rgb(255," + nonRed + "," + nonRed + ")";
};
};
}
heatmapper = (function(_this) {
return function(scope) {
var colorScale, forEachCell, values;
forEachCell = function(f) {
return _this.find(scope).each(function() {
var x;
x = $(this).data("value");
if ((x != null) && isFinite(x)) {
return f(x, $(this));
}
});
};
values = [];
forEachCell(function(x) {
return values.push(x);
});
colorScale = colorScaleGenerator(values);
return forEachCell(function(x, elem) {
return elem.css("background-color", colorScale(x));
});
};
})(this);
switch (scope) {
case "heatmap":
heatmapper(".pvtVal");
break;
case "rowheatmap":
for (i = l = 0, ref1 = numRows; 0 <= ref1 ? l < ref1 : l > ref1; i = 0 <= ref1 ? ++l : --l) {
heatmapper(".pvtVal.row" + i);
}
break;
case "colheatmap":
for (j = n = 0, ref2 = numCols; 0 <= ref2 ? n < ref2 : n > ref2; j = 0 <= ref2 ? ++n : --n) {
heatmapper(".pvtVal.col" + j);
}
}
heatmapper(".pvtTotal.rowTotal");
heatmapper(".pvtTotal.colTotal");
return this;
};
/*
Barchart post-processing
*/
return $.fn.barchart = function(opts) {
var barcharter, i, l, numCols, numRows, ref;
numRows = this.data("numrows");
numCols = this.data("numcols");
barcharter = (function(_this) {
return function(scope) {
var forEachCell, max, min, range, scaler, values;
forEachCell = function(f) {
return _this.find(scope).each(function() {
var x;
x = $(this).data("value");
if ((x != null) && isFinite(x)) {
return f(x, $(this));
}
});
};
values = [];
forEachCell(function(x) {
return values.push(x);
});
max = Math.max.apply(Math, values);
if (max < 0) {
max = 0;
}
range = max;
min = Math.min.apply(Math, values);
if (min < 0) {
range = max - min;
}
scaler = function(x) {
return 100 * x / (1.4 * range);
};
return forEachCell(function(x, elem) {
var bBase, bgColor, text, wrapper;
text = elem.text();
wrapper = $("<div>").css({
"position": "relative",
"height": "55px"
});
bgColor = "gray";
bBase = 0;
if (min < 0) {
bBase = scaler(-min);
}
if (x < 0) {
bBase += scaler(x);
bgColor = "darkred";
x = -x;
}
wrapper.append($("<div>").css({
"position": "absolute",
"bottom": bBase + "%",
"left": 0,
"right": 0,
"height": scaler(x) + "%",
"background-color": bgColor
}));
wrapper.append($("<div>").text(text).css({
"position": "relative",
"padding-left": "5px",
"padding-right": "5px"
}));
return elem.css({
"padding": 0,
"padding-top": "5px",
"text-align": "center"
}).html(wrapper);
});
};
})(this);
for (i = l = 0, ref = numRows; 0 <= ref ? l < ref : l > ref; i = 0 <= ref ? ++l : --l) {
barcharter(".pvtVal.row" + i);
}
barcharter(".pvtTotal.colTotal");
return this;
};
});
}).call(this);
//# sourceMappingURL=pivot.js.map |
var plugin = Echo.Plugin.manifest("VipReplies", "Echo.StreamServer.Controls.Stream.Item");
plugin.events = {
"Echo.StreamServer.Controls.Submit.onPostComplete": function(topic, args) {
var question = args.inReplyTo;
var answer = args.postData.content[0];
if (!question || this.config.get("view") === "public" ||
!this.component.user.any("role", ["vip"])) return;
this._markQuestionAsAnswered(question);
this._copyAnswer(question, answer);
}
};
plugin.methods._request = function(content) {
var item = this.component;
Echo.StreamServer.API.request({
"endpoint": "submit",
"submissionProxyURL": this.component.config.get("submissionProxyURL"),
"data": {
"appkey": item.config.get("appkey"),
"content": content,
"target-query": item.config.get("parent.query", ""),
"sessionID": item.user.get("sessionID", "")
}
}).send();
};
plugin.methods._markQuestionAsAnswered = function(question) {
this._request({
"verbs": ["http://activitystrea.ms/schema/1.0/mark"],
"targets": [{"id": question.object.id}],
"object": {
"objectTypes": [
"http://activitystrea.ms/schema/1.0/marker"
],
"content": this.config.get("answeredQuestionMarker", "answered")
}
});
};
plugin.methods._copyAnswer = function(question, answer) {
var copyTo = this.config.get("copyTo");
if (!copyTo) return;
var title = question.actor.title || "Guest";
var avatar = question.actor.avatar || this.component.user.get("defaultAvatar");
var content = this.substitute({
"template": '<div class="{plugin.class:special-quest-reply}">' +
'<div class="{plugin.class:reply}">{data:answerContent}</div>' +
'<div class="{plugin.class:question-quote}">' +
'<span class="{plugin.class:author} echo-linkColor">{data:title}</span> asks: ' +
'<span class="text">"{data:questionContent}"</span>' +
'</div>' +
'</div>',
"data": {
"answerContent": Echo.Utils.stripTags(answer.object.content),
"questionContent": Echo.Utils.stripTags(question.object.content),
"title": title
}
});
this._request({
"verbs": ["http://activitystrea.ms/schema/1.0/post"],
"targets": [{"id": copyTo.target}],
"object": {
"objectTypes": [
"http://activitystrea.ms/schema/1.0/comment"
],
"content": content
}
});
};
plugin.css =
".{class:data} .{plugin.class:question-quote} { background: #EEEEEE; padding: 10px; margin-bottom: 10px; }" +
".{class:data} .{plugin.class:question-quote} .{plugin.class:author} { color: #476CB8; }" +
".{class:data} .{plugin.class:special-quest-reply} .{plugin.class:reply} { font-size: 14px; margin-bottom: 10px; }";
Echo.Plugin.create(plugin);
|
# Test maw package ability to equalize.
# maw_05a - well and aquifer start at 4; should be now flow
# maw_05b - well starts at 3.5 and aquifer starts at 4; should equalize
# maw_05c - well starts at or below 3.0; not working yet
import os
import pytest
import sys
import numpy as np
try:
import flopy
except:
msg = "Error. FloPy package is not available.\n"
msg += "Try installing using the following command:\n"
msg += " pip install flopy"
raise Exception(msg)
from framework import testing_framework
from simulation import Simulation
ex = ["maw_05a", "maw_05b", "maw_05c"]
mawstrt = [4.0, 3.5, 2.5] # add 3.0
exdirs = []
for s in ex:
exdirs.append(os.path.join("temp", s))
def build_model(idx, dir):
lx = 7.0
lz = 4.0
nlay = 4
nrow = 1
ncol = 7
nper = 1
delc = 1.0
delr = lx / ncol
delz = lz / nlay
top = 4.0
botm = [3.0, 2.0, 1.0, 0.0]
perlen = [10.0]
nstp = [50]
tsmult = [1.0]
Kh = 1.0
Kv = 1.0
tdis_rc = []
for i in range(nper):
tdis_rc.append((perlen[i], nstp[i], tsmult[i]))
nouter, ninner = 700, 10
hclose, rclose, relax = 1e-8, 1e-6, 0.97
name = ex[idx]
# build MODFLOW 6 files
ws = dir
sim = flopy.mf6.MFSimulation(
sim_name=name, version="mf6", exe_name="mf6", sim_ws=ws
)
# create tdis package
tdis = flopy.mf6.ModflowTdis(
sim, time_units="DAYS", nper=nper, perioddata=tdis_rc
)
# create gwf model
gwfname = "gwf_" + name
newtonoptions = "NEWTON UNDER_RELAXATION"
gwf = flopy.mf6.ModflowGwf(
sim, modelname=gwfname, newtonoptions=newtonoptions
)
imsgwf = flopy.mf6.ModflowIms(
sim,
print_option="ALL",
outer_dvclose=hclose,
outer_maximum=nouter,
under_relaxation="SIMPLE",
under_relaxation_gamma=0.1,
inner_maximum=ninner,
inner_dvclose=hclose,
rcloserecord=rclose,
linear_acceleration="BICGSTAB",
scaling_method="NONE",
reordering_method="NONE",
relaxation_factor=relax,
filename="{}.ims".format(gwfname),
)
dis = flopy.mf6.ModflowGwfdis(
gwf,
nlay=nlay,
nrow=nrow,
ncol=ncol,
delr=delr,
delc=delc,
top=top,
botm=botm,
)
# initial conditions
strt = 4.0
ic = flopy.mf6.ModflowGwfic(gwf, strt=strt)
# node property flow
npf = flopy.mf6.ModflowGwfnpf(
gwf,
xt3doptions=False,
save_flows=True,
save_specific_discharge=True,
icelltype=1,
k=Kh,
k33=Kv,
)
sto = flopy.mf6.ModflowGwfsto(gwf, sy=0.3, ss=0.0, iconvert=1)
mawradius = 0.1
mawbottom = 0.0
mstrt = mawstrt[idx]
mawcondeqn = "THIEM"
mawngwfnodes = nlay
# <wellno> <radius> <bottom> <strt> <condeqn> <ngwfnodes>
mawpackagedata = [
[0, mawradius, mawbottom, mstrt, mawcondeqn, mawngwfnodes]
]
# <wellno> <icon> <cellid(ncelldim)> <scrn_top> <scrn_bot> <hk_skin> <radius_skin>
mawconnectiondata = [
[0, icon, (icon, 0, 0), top, mawbottom, -999.0, -999.0]
for icon in range(nlay)
]
# <wellno> <mawsetting>
mawperioddata = [[0, "STATUS", "ACTIVE"]]
maw = flopy.mf6.ModflowGwfmaw(
gwf,
print_input=True,
print_head=True,
print_flows=True,
save_flows=True,
head_filerecord="{}.maw.bin".format(gwfname),
budget_filerecord="{}.maw.bud".format(gwfname),
packagedata=mawpackagedata,
connectiondata=mawconnectiondata,
perioddata=mawperioddata,
pname="MAW-1",
)
opth = "{}.maw.obs".format(gwfname)
obsdata = {
"{}.maw.obs.csv".format(gwfname): [
("whead", "head", (0,)),
]
}
maw.obs.initialize(
filename=opth, digits=20, print_input=True, continuous=obsdata
)
# output control
oc = flopy.mf6.ModflowGwfoc(
gwf,
budget_filerecord="{}.cbc".format(gwfname),
head_filerecord="{}.hds".format(gwfname),
headprintrecord=[("COLUMNS", 10, "WIDTH", 15, "DIGITS", 6, "GENERAL")],
saverecord=[
(
"HEAD",
"ALL",
),
(
"BUDGET",
"ALL",
),
],
printrecord=[
(
"HEAD",
"ALL",
),
(
"BUDGET",
"ALL",
),
],
)
return sim, None
def eval_results(sim):
print("evaluating results...")
# calculate volume of water and make sure it is conserved
name = ex[sim.idxsim]
gwfname = "gwf_" + name
fname = gwfname + ".maw.bin"
fname = os.path.join(sim.simpath, fname)
assert os.path.isfile(fname)
bobj = flopy.utils.HeadFile(fname, text="HEAD")
stage = bobj.get_alldata().flatten()
fname = gwfname + ".hds"
fname = os.path.join(sim.simpath, fname)
assert os.path.isfile(fname)
hobj = flopy.utils.HeadFile(fname)
head = hobj.get_alldata()
# calculate initial volume of water in well and aquifer
v0maw = mawstrt[sim.idxsim] * np.pi * 0.1**2
v0gwf = 4 * 7 * 0.3
v0 = v0maw + v0gwf
top = [4.0, 3.0, 2.0, 1.0]
botm = [3.0, 2.0, 1.0, 0.0]
nlay = 4
ncol = 7
print(
"Initial volumes\n"
+ " Groundwater: {}\n".format(v0gwf)
+ " Well: {}\n".format(v0maw)
+ " Total: {}".format(v0)
)
# calculate current volume of water in well and aquifer and compare with
# initial volume
for kstp, mawstage in enumerate(stage):
vgwf = 0
for k in range(nlay):
for j in range(ncol):
tp = min(head[kstp, k, 0, j], top[k])
dz = tp - botm[k]
vgwf += 0.3 * max(0.0, dz)
vmaw = stage[kstp] * np.pi * 0.1**2
vnow = vmaw + vgwf
errmsg = (
"kstp {}: \n".format(kstp + 1)
+ " Groundwater: {}\n".format(vgwf)
+ " Well: {}\n".format(vmaw)
+ " Total: {}\n".format(vnow)
+ " Initial Total: {}".format(v0)
)
assert np.allclose(v0, vnow), errmsg
print(
"kstp {}: \n".format(kstp + 1)
+ " Groundwater: {}\n".format(vgwf)
+ " Well: {}\n".format(vmaw)
+ " Total: {}\n".format(vnow)
+ " Initial Total: {}".format(v0)
)
return
# - No need to change any code below
@pytest.mark.parametrize(
"idx, dir",
list(enumerate(exdirs)),
)
def test_mf6model(idx, dir):
# initialize testing framework
test = testing_framework()
# build the model
test.build_mf6_models(build_model, idx, dir)
# run the test model
test.run_mf6(Simulation(dir, exfunc=eval_results, idxsim=idx))
def main():
# initialize testing framework
test = testing_framework()
# run the test model
for idx, dir in enumerate(exdirs):
test.build_mf6_models(build_model, idx, dir)
sim = Simulation(dir, exfunc=eval_results, idxsim=idx)
test.run_mf6(sim)
if __name__ == "__main__":
# print message
print("standalone run of {}".format(os.path.basename(__file__)))
# run main routine
main()
|
"""Transformers for generating edge confidence maps and part affinity fields."""
import numpy as np
import tensorflow as tf
import attr
from typing import List, Text, Optional, Tuple
import sleap
from sleap.nn.data.utils import (
expand_to_rank,
make_grid_vectors,
gaussian_pdf,
ensure_list,
)
def distance_to_edge(
points: tf.Tensor, edge_source: tf.Tensor, edge_destination: tf.Tensor
) -> tf.Tensor:
"""Compute pairwise distance between points and undirected edges.
Args:
points: Tensor of dtype tf.float32 of shape (d_0, ..., d_n, 2) where the last
axis corresponds to x- and y-coordinates. Distances will be broadcast across
all point dimensions.
edge_source: Tensor of dtype tf.float32 of shape (n_edges, 2) where the last
axis corresponds to x- and y-coordinates of the source points of each edge.
edge_destination: Tensor of dtype tf.float32 of shape (n_edges, 2) where the
last axis corresponds to x- and y-coordinates of the source points of each
edge.
Returns:
A tensor of dtype tf.float32 of shape (d_0, ..., d_n, n_edges) where the first
axes correspond to the initial dimensions of `points`, and the last indicates
the distance of each point to each edge.
"""
# Ensure all points are at least rank 2.
points = expand_to_rank(points, 2)
edge_source = expand_to_rank(edge_source, 2)
edge_destination = expand_to_rank(edge_destination, 2)
# Compute number of point dimensions.
n_pt_dims = tf.rank(points) - 1
# Direction vector.
direction_vector = edge_destination - edge_source # (n_edges, 2)
# Edge length.
edge_length = tf.maximum(
tf.reduce_sum(tf.square(direction_vector), axis=1), 1
) # (n_edges,)
# Adjust query points relative to edge source point.
source_relative_points = tf.expand_dims(points, axis=-2) - expand_to_rank(
edge_source, n_pt_dims + 2
) # (..., n_edges, 2)
# Project points to edge line.
line_projections = tf.reduce_sum(
source_relative_points * expand_to_rank(direction_vector, n_pt_dims + 2), axis=3
) / expand_to_rank(
edge_length, n_pt_dims + 1
) # (..., n_edges)
# Crop to line segment.
line_projections = tf.clip_by_value(line_projections, 0, 1) # (..., n_edges)
# Compute distance from each point to the edge.
distances = tf.reduce_sum(
tf.square(
(
tf.expand_dims(line_projections, -1)
* expand_to_rank(direction_vector, n_pt_dims + 2)
)
- source_relative_points
),
axis=-1,
) # (..., n_edges)
return distances
def make_edge_maps(
xv: tf.Tensor,
yv: tf.Tensor,
edge_source: tf.Tensor,
edge_destination: tf.Tensor,
sigma: float,
) -> tf.Tensor:
"""Generate confidence maps for a set of undirected edges.
Args:
xv: Sampling grid vector for x-coordinates of shape (grid_width,) and dtype
tf.float32. This can be generated by
`sleap.nn.data.utils.make_grid_vectors`.
yv: Sampling grid vector for y-coordinates of shape (grid_height,) and dtype
tf.float32. This can be generated by
`sleap.nn.data.utils.make_grid_vectors`.
edge_source: Tensor of dtype tf.float32 of shape (n_edges, 2) where the last
axis corresponds to x- and y-coordinates of the source points of each edge.
edge_destination: Tensor of dtype tf.float32 of shape (n_edges, 2) where the
last axis corresponds to x- and y-coordinates of the destination points of
each edge.
sigma: Standard deviation of the 2D Gaussian distribution sampled to generate
confidence maps.
Returns:
A set of confidence maps corresponding to the probability of each point on a
sampling grid being on each edge. These will be in a tensor of shape
(grid_height, grid_width, n_edges) of dtype tf.float32.
"""
sampling_grid = tf.stack(tf.meshgrid(xv, yv), axis=-1) # (height, width, 2)
distances = distance_to_edge(
sampling_grid, edge_source=edge_source, edge_destination=edge_destination
)
edge_maps = gaussian_pdf(distances, sigma=sigma)
return edge_maps
def make_pafs(
xv: tf.Tensor,
yv: tf.Tensor,
edge_source: tf.Tensor,
edge_destination: tf.Tensor,
sigma: float,
) -> tf.Tensor:
"""Generate part affinity fields for a set of directed edges.
Args:
xv: Sampling grid vector for x-coordinates of shape (grid_width,) and dtype
tf.float32. This can be generated by
`sleap.nn.data.utils.make_grid_vectors`.
yv: Sampling grid vector for y-coordinates of shape (grid_height,) and dtype
tf.float32. This can be generated by
`sleap.nn.data.utils.make_grid_vectors`.
edge_source: Tensor of dtype tf.float32 of shape (n_edges, 2) where the last
axis corresponds to x- and y-coordinates of the source points of each edge.
edge_destination: Tensor of dtype tf.float32 of shape (n_edges, 2) where the
last axis corresponds to x- and y-coordinates of the destination points of
each edge.
sigma: Standard deviation of the 2D Gaussian distribution sampled to generate
the edge maps for masking the PAFs.
Returns:
A set of part affinity fields corresponding to the unit vector pointing along
the direction of each edge weighted by the probability of each point on a
sampling grid being on each edge. These will be in a tensor of shape
(grid_height, grid_width, n_edges, 2) of dtype tf.float32. The last axis
corresponds to the x- and y-coordinates of the unit vectors.
"""
unit_vectors = edge_destination - edge_source
unit_vectors = unit_vectors / tf.linalg.norm(unit_vectors, axis=-1, keepdims=True)
edge_confidence_map = make_edge_maps(
xv=xv,
yv=yv,
edge_source=edge_source,
edge_destination=edge_destination,
sigma=sigma,
)
pafs = tf.expand_dims(edge_confidence_map, axis=-1) * expand_to_rank(
unit_vectors, 4
)
return pafs
def make_multi_pafs(
xv: tf.Tensor,
yv: tf.Tensor,
edge_sources: tf.Tensor,
edge_destinations: tf.Tensor,
sigma: float,
) -> tf.Tensor:
"""Make multiple instance PAFs with max reduction.
Args:
xv: Sampling grid vector for x-coordinates of shape (grid_width,) and dtype
tf.float32. This can be generated by
`sleap.nn.data.utils.make_grid_vectors`.
yv: Sampling grid vector for y-coordinates of shape (grid_height,) and dtype
tf.float32. This can be generated by
`sleap.nn.data.utils.make_grid_vectors`.
edge_sources: Tensor of dtype tf.float32 of shape (n_instances, n_edges, 2)
where the last axis corresponds to x- and y-coordinates of the source points
of each edge.
edge_destinations: Tensor of dtype tf.float32 of shape (n_instances, n_edges, 2)
where the last axis corresponds to x- and y-coordinates of the destination
points of each edge.
sigma: Standard deviation of the 2D Gaussian distribution sampled to generate
the edge maps for masking the PAFs.
Returns:
A set of part affinity fields generated for each instance. These will be in a
tensor of shape (grid_height, grid_width, n_edges, 2). If multiple instance
PAFs are defined on the same pixel, they will be summed.
"""
grid_height = tf.shape(yv)[0]
grid_width = tf.shape(xv)[0]
n_edges = tf.shape(edge_sources)[1]
n_instances = tf.shape(edge_sources)[0]
pafs = tf.zeros((grid_height, grid_width, n_edges, 2), tf.float32)
for i in range(n_instances):
paf = make_pafs(
xv=xv,
yv=yv,
edge_source=tf.gather(edge_sources, i, axis=0),
edge_destination=tf.gather(edge_destinations, i, axis=0),
sigma=sigma,
)
pafs += tf.where(tf.math.is_nan(paf), 0., paf)
return pafs
def get_edge_points(
instances: tf.Tensor, edge_inds: tf.Tensor
) -> Tuple[tf.Tensor, tf.Tensor]:
"""Return the points in each instance that form a directed graph.
Args:
instances: A tensor of shape (n_instances, n_nodes, 2) and dtype tf.float32
containing instance points where the last axis corresponds to (x, y) pixel
coordinates on the image. This must be rank-3 even if a single instance is
present.
edge_inds: A tensor of shape (n_edges, 2) and dtype tf.int32 containing the node
indices that define a directed graph, where the last axis corresponds to the
source and destination node indices.
Returns:
Tuple of (edge_sources, edge_destinations) containing the edge and destination
points respectively. Both will be tensors of shape (n_instances, n_edges, 2),
where the last axis corresponds to (x, y) pixel coordinates on the image.
"""
source_inds = tf.cast(tf.gather(edge_inds, 0, axis=1), tf.int32)
destination_inds = tf.cast(tf.gather(edge_inds, 1, axis=1), tf.int32)
edge_sources = tf.gather(instances, source_inds, axis=1)
edge_destinations = tf.gather(instances, destination_inds, axis=1)
return edge_sources, edge_destinations
@attr.s(auto_attribs=True)
class PartAffinityFieldsGenerator:
"""Transformer to generate part affinity fields.
Attributes:
sigma: Standard deviation of the 2D Gaussian distribution sampled to weight the
part affinity fields by their distance to the edges. This defines the spread
in units of the input image's grid, i.e., it does not take scaling in
previous steps into account.
output_stride: Relative stride of the generated confidence maps. This is
effectively the reciprocal of the output scale, i.e., increase this to
generate confidence maps that are smaller than the input images.
skeletons: List of `sleap.Skeleton`s to use for looking up the index of the
edges.
flatten_channels: If False, the generated tensors are of shape
[height, width, n_edges, 2]. If True, generated tensors are of shape
[height, width, n_edges * 2] by flattening the last 2 axes.
"""
sigma: float = attr.ib(default=1.0, converter=float)
output_stride: int = attr.ib(default=1, converter=int)
skeletons: Optional[List[sleap.Skeleton]] = attr.ib(
default=None, converter=attr.converters.optional(ensure_list)
)
flatten_channels: bool = False
@property
def input_keys(self) -> List[Text]:
"""Return the keys that incoming elements are expected to have."""
return ["image", "instances", "skeleton_inds"]
@property
def output_keys(self) -> List[Text]:
"""Return the keys that outgoing elements will have."""
return self.input_keys + ["part_affinity_fields"]
def transform_dataset(self, input_ds: tf.data.Dataset) -> tf.data.Dataset:
"""Create a dataset that contains the generated confidence maps.
Args:
input_ds: A dataset with elements that contain the keys "image",
"instances" and "skeleton_inds".
Returns:
A `tf.data.Dataset` with the same keys as the input, as well as
"part_affinity_fields".
The "part_affinity_fields" key will be a tensor of shape
(grid_height, grid_width, n_edges, 2) containing the combined part affinity
fields of all instances in the frame.
If the `flatten_channels` attribute is set to True, the last 2 axes of the
"part_affinity_fields" are flattened to produce a tensor of shape
(grid_height, grid_width, n_edges * 2). This is a convenient form when
training models as a rank-4 (batched) tensor will generally be expected.
Notes:
The output stride is relative to the current scale of the image. To map
points on the part affinity fields to the raw image, first multiply them by
the output stride, and then scale the x- and y-coordinates by the "scale"
key.
Importantly, the sigma will be proportional to the current image grid, not
the original grid prior to scaling operations.
"""
# Infer image dimensions to generate sampling grid.
test_example = next(iter(input_ds))
image_height = test_example["image"].shape[0]
image_width = test_example["image"].shape[1]
# Generate sampling grid vectors.
xv, yv = make_grid_vectors(
image_height=image_height,
image_width=image_width,
output_stride=self.output_stride,
)
grid_height = len(yv)
grid_width = len(xv)
# Pull out edge indices.
# TODO: Multi-skeleton support.
edge_inds = tf.cast(self.skeletons[0].edge_inds, dtype=tf.int32)
n_edges = len(edge_inds)
def generate_pafs(example):
"""Local processing function for dataset mapping."""
edge_sources, edge_destinations = get_edge_points(
example["instances"], edge_inds
)
edge_sources = tf.ensure_shape(edge_sources, (None, n_edges, 2))
edge_destinations = tf.ensure_shape(edge_destinations, (None, n_edges, 2))
pafs = make_multi_pafs(
xv=xv,
yv=yv,
edge_sources=edge_sources,
edge_destinations=edge_destinations,
sigma=self.sigma,
)
pafs = tf.ensure_shape(pafs, (grid_height, grid_width, n_edges, 2))
if self.flatten_channels:
pafs = tf.reshape(pafs, [grid_height, grid_width, n_edges * 2])
pafs = tf.ensure_shape(pafs, (grid_height, grid_width, n_edges * 2))
example["part_affinity_fields"] = pafs
return example
# Map transformation.
output_ds = input_ds.map(
generate_pafs, num_parallel_calls=tf.data.experimental.AUTOTUNE
)
return output_ds
|
import { useCallback, useReducer, useEffect, useContext, useState } from 'react'
import { ClientStore } from './stores'
import { uuid, reducer } from './utils'
const useAsync = (actions, initialState = {}) => {
const [id] = useState(uuid())
const client = useContext(ClientStore.Context)
const memoizedReducer = useCallback(reducer(id, actions, client), [])
const [state, dispatch] = useReducer(memoizedReducer, initialState)
useEffect(() => {
client.dispatchs = {
...client.dispatchs,
[id]: dispatch
}
if (!client.connect) return
client.connect({ state, dispatch })
return () => {
client.dispatchs[id] = null
}
}, [state])
return [state, dispatch]
}
export default useAsync
|
from .resources import api_resources
from .queue import api_queue
from .notes import api_notes
from .decks import api_decks |
fuse.dom.HTMLInputElement.plugin.coffee = fuse.Function.IDENTITY;
|
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
from pandas import Series, DataFrame
import pandas as pd
import numpy as np
import os
import matplotlib.pylab as plt
from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import classification_report
import sklearn.metrics
os.chdir("C:\TREES")
#Load the dataset
AH_data = pd.read_csv("health.csv")
data_clean = AH_data.dropna()
data_clean.dtypes
print(data_clean.describe())
predictors = data_clean[['BIO_SEX','HISPANIC','WHITE','BLACK','NAMERICAN','ASIAN',
'age','ALCEVR1','ALCPROBS1','marever1','cocever1','inhever1','cigavail','DEP1',
'ESTEEM1','VIOL1','PASSIST','DEVIANT1','SCHCONN1','GPA1','EXPEL1','FAMCONCT','PARACTV',
'PARPRES']]
targets = data_clean.TREG1
pred_train, pred_test, tar_train, tar_test=train_test_split(predictors, targets, test_size=.4)
print(pred_train.shape)
print(pred_test.shape)
print(tar_train.shape)
print(tar_test.shape)
classifier=DecisionTreeClassifier()
classifier=classifier.fit(pred_train,tar_train)
predictions=classifier.predict(pred_test)
print(sklearn.metrics.confusion_matrix(tar_test,predictions))
print(sklearn.metrics.accuracy_score(tar_test, predictions))
#Displaying the decision tree
from sklearn import tree
#from StringIO import StringIO
from io import StringIO
#from StringIO import StringIO
from IPython.display import Image
with open("fruit_classifier.txt", "w") as f:
f = tree.export_graphviz(classifier, out_file=f)
|
import { createError, REV_CONFLICT } from '../errors';
import isDeleted from './isDeleted';
import { parseDoc as parseDoc } from './parseDoc';
import calculateWinningRev from '../../deps/merge/winningRev';
import merge from '../../deps/merge/index';
import revExists from '../../deps/merge/revExists';
function updateDoc(revLimit, prev, docInfo, results,
i, cb, writeDoc, newEdits) {
if (revExists(prev.rev_tree, docInfo.metadata.rev)) {
results[i] = docInfo;
return cb();
}
// sometimes this is pre-calculated. historically not always
var previousWinningRev = prev.winningRev || calculateWinningRev(prev);
var previouslyDeleted = 'deleted' in prev ? prev.deleted :
isDeleted(prev, previousWinningRev);
var deleted = 'deleted' in docInfo.metadata ? docInfo.metadata.deleted :
isDeleted(docInfo.metadata);
var isRoot = /^1-/.test(docInfo.metadata.rev);
if (previouslyDeleted && !deleted && newEdits && isRoot) {
var newDoc = docInfo.data;
newDoc._rev = previousWinningRev;
newDoc._id = docInfo.metadata.id;
docInfo = parseDoc(newDoc, newEdits);
}
var merged = merge(prev.rev_tree, docInfo.metadata.rev_tree[0], revLimit);
var inConflict = newEdits && (((previouslyDeleted && deleted) ||
(!previouslyDeleted && merged.conflicts !== 'new_leaf') ||
(previouslyDeleted && !deleted && merged.conflicts === 'new_branch')));
if (inConflict) {
var err = createError(REV_CONFLICT);
results[i] = err;
return cb();
}
var newRev = docInfo.metadata.rev;
docInfo.metadata.rev_tree = merged.tree;
/* istanbul ignore else */
if (prev.rev_map) {
docInfo.metadata.rev_map = prev.rev_map; // used only by leveldb
}
// recalculate
var winningRev = calculateWinningRev(docInfo.metadata);
var winningRevIsDeleted = isDeleted(docInfo.metadata, winningRev);
// calculate the total number of documents that were added/removed,
// from the perspective of total_rows/doc_count
var delta = (previouslyDeleted === winningRevIsDeleted) ? 0 :
previouslyDeleted < winningRevIsDeleted ? -1 : 1;
var newRevIsDeleted;
if (newRev === winningRev) {
// if the new rev is the same as the winning rev, we can reuse that value
newRevIsDeleted = winningRevIsDeleted;
} else {
// if they're not the same, then we need to recalculate
newRevIsDeleted = isDeleted(docInfo.metadata, newRev);
}
writeDoc(docInfo, winningRev, winningRevIsDeleted, newRevIsDeleted,
true, delta, i, cb);
}
export default updateDoc;
|
// Copyright 2006 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Class for parsing and formatting URIs.
*
* Use new goog.Uri(string) to parse a URI string.
*
* e.g: <code>var myUri = new goog.Uri(window.location);</code>
*
* Implements RFC 3986 for parsing/formatting URIs.
* http://www.ietf.org/rfc/rfc3986.txt
*
* Some changes have been made to the interface (more like .NETs), though the
* internal representation is now of un-encoded parts, this will change the
* behavior slightly.
*
*/
goog.provide('goog.Uri');
goog.provide('goog.Uri.QueryData');
goog.require('goog.uri.utils');
goog.require('goog.uri.utils.ComponentIndex');
/**
* This class contains setters and getters for the parts of the URI.
* The <code>getXyz</code>/<code>setXyz</code> methods return the decoded part
* -- so<code>new goog.Uri('/foo%20bar').getPath()</code> will return the
* decoded path, <code>/foo bar</code>.
*
* Reserved characters (see RFC 3986 section 2.2) can be present in
* their percent-encoded form in scheme, domain, and path URI components and
* will not be auto-decoded. For example:
* <code>new goog.Uri('rel%61tive/path%2fto/resource').getPath()</code> will
* return <code>relative/path%2fto/resource</code>.
*
* The constructor accepts an optional unparsed, raw URI string. The parser
* is relaxed, so special characters that aren't escaped but don't cause
* ambiguities will not cause parse failures.
*
* All setters return <code>this</code> and so may be chained, a la
* <code>new goog.Uri('/foo').setFragment('part').toString()</code>.
*
* @param {*=} uri Optional string URI to parse, or if a goog.Uri is
* passed, a clone is created.
*
* @constructor
*/
goog.Uri = function(uri) {
// Parse in the uri string
var m;
if (uri instanceof goog.Uri) {
this.setScheme(uri.getScheme());
this.setUserInfo(uri.getUserInfo());
this.setDomain(uri.getDomain());
this.setPort(uri.getPort());
this.setPath(uri.getPath());
this.setQueryData(uri.getQueryData().clone());
this.setFragment(uri.getFragment());
} else if (uri && (m = goog.uri.utils.split(String(uri)))) {
// Set the parts -- decoding as we do so.
// COMPATABILITY NOTE - In IE, unmatched fields may be empty strings,
// whereas in other browsers they will be undefined.
this.setScheme(m[goog.uri.utils.ComponentIndex.SCHEME] || '', true);
this.setUserInfo(m[goog.uri.utils.ComponentIndex.USER_INFO] || '', true);
this.setDomain(m[goog.uri.utils.ComponentIndex.DOMAIN] || '', true);
this.setPort(m[goog.uri.utils.ComponentIndex.PORT]);
this.setPath(m[goog.uri.utils.ComponentIndex.PATH] || '', true);
this.setQueryData(m[goog.uri.utils.ComponentIndex.QUERY_DATA] || '', true);
this.setFragment(m[goog.uri.utils.ComponentIndex.FRAGMENT] || '', true);
} else {
this.queryData_ = new goog.Uri.QueryData(null, null);
}
};
/**
* Scheme such as "http".
* @type {string}
* @private
*/
goog.Uri.prototype.scheme_ = '';
/**
* User credentials in the form "username:password".
* @type {string}
* @private
*/
goog.Uri.prototype.userInfo_ = '';
/**
* Domain part, e.g. "www.google.com".
* @type {string}
* @private
*/
goog.Uri.prototype.domain_ = '';
/**
* Port, e.g. 8080.
* @type {?number}
* @private
*/
goog.Uri.prototype.port_ = null;
/**
* Path, e.g. "/tests/img.png".
* @type {string}
* @private
*/
goog.Uri.prototype.path_ = '';
/**
* Object representing query data.
* @type {!goog.Uri.QueryData}
* @private
*/
goog.Uri.prototype.queryData_;
/**
* The fragment without the #.
* @type {string}
* @private
*/
goog.Uri.prototype.fragment_ = '';
/**
* @return {string} The string form of the url.
* @override
*/
goog.Uri.prototype.toString = function() {
var out = [];
var scheme = this.getScheme();
if (scheme) {
out.push(goog.Uri.encodeSpecialChars_(
scheme, goog.Uri.reDisallowedInSchemeOrUserInfo_, true), ':');
}
var domain = this.getDomain();
if (domain) {
out.push('//');
var userInfo = this.getUserInfo();
if (userInfo) {
out.push(goog.Uri.encodeSpecialChars_(
userInfo, goog.Uri.reDisallowedInSchemeOrUserInfo_, true), '@');
}
out.push(goog.Uri.removeDoubleEncoding_(encodeURIComponent(domain)));
var port = this.getPort();
if (port != null) {
out.push(':', String(port));
}
}
var path = this.getPath();
if (path) {
if (this.hasDomain() && path.charAt(0) != '/') {
out.push('/');
}
out.push(goog.Uri.encodeSpecialChars_(
path,
path.charAt(0) == '/' ?
goog.Uri.reDisallowedInAbsolutePath_ :
goog.Uri.reDisallowedInRelativePath_,
true));
}
var query = this.getEncodedQuery();
if (query) {
out.push('?', query);
}
var fragment = this.getFragment();
if (fragment) {
out.push('#', goog.Uri.encodeSpecialChars_(
fragment, goog.Uri.reDisallowedInFragment_));
}
return out.join('');
};
/**
* Resolves the given relative URI (a goog.Uri object), using the URI
* represented by this instance as the base URI.
*
* There are several kinds of relative URIs:<br>
* 1. foo - replaces the last part of the path, the whole query and fragment<br>
* 2. /foo - replaces the the path, the query and fragment<br>
* 3. //foo - replaces everything from the domain on. foo is a domain name<br>
* 4. ?foo - replace the query and fragment<br>
* 5. #foo - replace the fragment only
*
* Additionally, if relative URI has a non-empty path, all ".." and "."
* segments will be resolved, as described in RFC 3986.
*
* @param {goog.Uri} relativeUri The relative URI to resolve.
* @return {!goog.Uri} The resolved URI.
*/
goog.Uri.prototype.resolve = function(relativeUri) {
var absoluteUri = this.clone();
if (absoluteUri.scheme_ === 'data') {
// Cannot have a relative URI to a data URI.
absoluteUri = new goog.Uri();
}
// we satisfy these conditions by looking for the first part of relativeUri
// that is not blank and applying defaults to the rest
var overridden = relativeUri.hasScheme();
if (overridden) {
absoluteUri.setScheme(relativeUri.getScheme());
} else {
overridden = relativeUri.hasUserInfo();
}
if (overridden) {
absoluteUri.setUserInfo(relativeUri.getUserInfo());
} else {
overridden = relativeUri.hasDomain();
}
if (overridden) {
absoluteUri.setDomain(relativeUri.getDomain());
} else {
overridden = relativeUri.hasPort();
}
var path = relativeUri.getPath();
if (overridden) {
absoluteUri.setPort(relativeUri.getPort());
} else {
overridden = relativeUri.hasPath();
if (overridden) {
// resolve path properly
if (path.charAt(0) != '/') {
// path is relative
if (this.hasDomain() && !this.hasPath()) {
// RFC 3986, section 5.2.3, case 1
path = '/' + path;
} else {
// RFC 3986, section 5.2.3, case 2
var lastSlashIndex = absoluteUri.getPath().lastIndexOf('/');
if (lastSlashIndex != -1) {
path = absoluteUri.getPath().substr(0, lastSlashIndex + 1) + path;
}
}
}
path = goog.Uri.removeDotSegments(path);
}
}
if (overridden) {
absoluteUri.setPath(path);
} else {
overridden = relativeUri.hasQuery();
}
if (overridden) {
absoluteUri.setQueryData(relativeUri.getQueryData().clone());
} else {
overridden = relativeUri.hasFragment();
}
if (overridden) {
absoluteUri.setFragment(relativeUri.getFragment());
}
return absoluteUri;
};
/**
* Clones the URI instance.
* @return {!goog.Uri} New instance of the URI object.
*/
goog.Uri.prototype.clone = function() {
return new goog.Uri(this);
};
/**
* @return {string} The encoded scheme/protocol for the URI.
*/
goog.Uri.prototype.getScheme = function() {
return this.scheme_;
};
/**
* Sets the scheme/protocol.
* @param {string} newScheme New scheme value.
* @param {boolean=} decode Optional param for whether to decode new value.
* @return {!goog.Uri} Reference to this URI object.
*/
goog.Uri.prototype.setScheme = function(newScheme, decode) {
this.scheme_ = decode ? goog.Uri.decodeOrEmpty_(newScheme, true) :
newScheme;
// remove an : at the end of the scheme so somebody can pass in
// window.location.protocol
if (this.scheme_) {
this.scheme_ = this.scheme_.replace(/:$/, '');
}
return this;
};
/**
* @return {boolean} Whether the scheme has been set.
*/
goog.Uri.prototype.hasScheme = function() {
return !!this.scheme_;
};
/**
* @return {string} The decoded user info.
*/
goog.Uri.prototype.getUserInfo = function() {
return this.userInfo_;
};
/**
* Sets the userInfo.
* @param {string} newUserInfo New userInfo value.
* @param {boolean=} decode Optional param for whether to decode new value.
* @return {!goog.Uri} Reference to this URI object.
*/
goog.Uri.prototype.setUserInfo = function(newUserInfo, decode) {
this.userInfo_ = decode ? goog.Uri.decodeOrEmpty_(newUserInfo) :
newUserInfo;
return this;
};
/**
* @return {boolean} Whether the user info has been set.
*/
goog.Uri.prototype.hasUserInfo = function() {
return !!this.userInfo_;
};
/**
* @return {string} The decoded domain.
*/
goog.Uri.prototype.getDomain = function() {
return this.domain_;
};
/**
* Sets the domain.
* @param {string} newDomain New domain value.
* @param {boolean=} decode Optional param for whether to decode new value.
* @return {!goog.Uri} Reference to this URI object.
*/
goog.Uri.prototype.setDomain = function(newDomain, decode) {
this.domain_ = decode ? goog.Uri.decodeOrEmpty_(newDomain, true) :
newDomain;
return this;
};
/**
* @return {boolean} Whether the domain has been set.
*/
goog.Uri.prototype.hasDomain = function() {
return !!this.domain_;
};
/**
* @return {?number} The port number.
*/
goog.Uri.prototype.getPort = function() {
return this.port_;
};
/**
* Sets the port number.
* @param {*} newPort Port number. Will be explicitly casted to a number.
* @return {!goog.Uri} Reference to this URI object.
*/
goog.Uri.prototype.setPort = function(newPort) {
if (newPort) {
newPort = Number(newPort);
if (isNaN(newPort) || newPort < 0) {
throw Error('Bad port number ' + newPort);
}
this.port_ = newPort;
} else {
this.port_ = null;
}
return this;
};
/**
* @return {boolean} Whether the port has been set.
*/
goog.Uri.prototype.hasPort = function() {
return this.port_ != null;
};
/**
* @return {string} The decoded path.
*/
goog.Uri.prototype.getPath = function() {
return this.path_;
};
/**
* Sets the path.
* @param {string} newPath New path value.
* @param {boolean=} decode Optional param for whether to decode new value.
* @return {!goog.Uri} Reference to this URI object.
*/
goog.Uri.prototype.setPath = function(newPath, decode) {
this.path_ = decode ? goog.Uri.decodeOrEmpty_(newPath, true) : newPath;
return this;
};
/**
* @return {boolean} Whether the path has been set.
*/
goog.Uri.prototype.hasPath = function() {
return !!this.path_;
};
/**
* @return {boolean} Whether the query string has been set.
*/
goog.Uri.prototype.hasQuery = function() {
return this.queryData_.toString() !== '';
};
/**
* Sets the query data.
* @param {goog.Uri.QueryData|string|undefined} queryData QueryData object.
* @param {boolean=} decode Optional param for whether to decode new value.
* Applies only if queryData is a string.
* @return {!goog.Uri} Reference to this URI object.
*/
goog.Uri.prototype.setQueryData = function(queryData, decode) {
if (queryData instanceof goog.Uri.QueryData) {
this.queryData_ = queryData;
} else {
if (!decode) {
// QueryData accepts encoded query string, so encode it if
// decode flag is not true.
queryData = goog.Uri.encodeSpecialChars_(queryData,
goog.Uri.reDisallowedInQuery_);
}
this.queryData_ = new goog.Uri.QueryData(queryData, null);
}
return this;
};
/**
* @return {string} The encoded URI query, not including the ?.
*/
goog.Uri.prototype.getEncodedQuery = function() {
return this.queryData_.toString();
};
/**
* @return {string} The decoded URI query, not including the ?.
*/
goog.Uri.prototype.getDecodedQuery = function() {
return this.queryData_.toDecodedString();
};
/**
* Returns the query data.
* @return {!goog.Uri.QueryData} QueryData object.
*/
goog.Uri.prototype.getQueryData = function() {
return this.queryData_;
};
/**
* @return {string} The URI fragment, not including the #.
*/
goog.Uri.prototype.getFragment = function() {
return this.fragment_;
};
/**
* Sets the URI fragment.
* @param {string} newFragment New fragment value.
* @param {boolean=} decode Optional param for whether to decode new value.
* @return {!goog.Uri} Reference to this URI object.
*/
goog.Uri.prototype.setFragment = function(newFragment, decode) {
this.fragment_ = decode ? goog.Uri.decodeOrEmpty_(newFragment) :
newFragment;
return this;
};
/**
* @return {boolean} Whether the URI has a fragment set.
*/
goog.Uri.prototype.hasFragment = function() {
return !!this.fragment_;
};
//==============================================================================
// Static members
//==============================================================================
/**
* Removes dot segments in given path component, as described in
* RFC 3986, section 5.2.4.
*
* @param {string} path A non-empty path component.
* @return {string} Path component with removed dot segments.
*/
goog.Uri.removeDotSegments = function(path) {
if (path == '..' || path == '.') {
return '';
} else if (path.indexOf('./') == -1 &&
path.indexOf('/.') == -1) {
// This optimization detects uris which do not contain dot-segments,
// and as a consequence do not require any processing.
return path;
} else {
var leadingSlash = (path.lastIndexOf('/', 0) == 0);
var segments = path.split('/');
var out = [];
for (var pos = 0; pos < segments.length; ) {
var segment = segments[pos++];
if (segment == '.') {
if (leadingSlash && pos == segments.length) {
out.push('');
}
} else if (segment == '..') {
if (out.length > 1 || out.length == 1 && out[0] != '') {
out.pop();
}
if (leadingSlash && pos == segments.length) {
out.push('');
}
} else {
out.push(segment);
leadingSlash = true;
}
}
return out.join('/');
}
};
/**
* Decodes a value or returns the empty string if it isn't defined or empty.
* @param {string|undefined} val Value to decode.
* @param {boolean=} preserveReserved If true, restricted characters will
* not be decoded.
* @return {string} Decoded value.
* @private
*/
goog.Uri.decodeOrEmpty_ = function(val, preserveReserved) {
// Don't use UrlDecode() here because val is not a query parameter.
if (!val) {
return '';
}
return preserveReserved ? decodeURI(val) : decodeURIComponent(val);
};
/**
* If unescapedPart is non null, then escapes any characters in it that aren't
* valid characters in a url and also escapes any special characters that
* appear in extra.
*
* @param {*} unescapedPart The string to encode.
* @param {RegExp} extra A character set of characters in [\01-\177].
* @param {boolean=} removeDoubleEncoding If true, remove double percent
* encoding.
* @return {?string} null iff unescapedPart == null.
* @private
*/
goog.Uri.encodeSpecialChars_ = function(unescapedPart, extra,
removeDoubleEncoding) {
if (goog.isString(unescapedPart)) {
var encoded = encodeURI(unescapedPart).
replace(extra, goog.Uri.encodeChar_);
if (removeDoubleEncoding) {
// encodeURI double-escapes %XX sequences used to represent restricted
// characters in some URI components, remove the double escaping here.
encoded = goog.Uri.removeDoubleEncoding_(encoded);
}
return encoded;
}
return null;
};
/**
* Converts a character in [\01-\177] to its unicode character equivalent.
* @param {string} ch One character string.
* @return {string} Encoded string.
* @private
*/
goog.Uri.encodeChar_ = function(ch) {
var n = ch.charCodeAt(0);
return '%' + ((n >> 4) & 0xf).toString(16) + (n & 0xf).toString(16);
};
/**
* Removes double percent-encoding from a string.
* @param {string} doubleEncodedString String
* @return {string} String with double encoding removed.
* @private
*/
goog.Uri.removeDoubleEncoding_ = function(doubleEncodedString) {
return doubleEncodedString.replace(/%25([0-9a-fA-F]{2})/g, '%$1');
};
/**
* Regular expression for characters that are disallowed in the scheme or
* userInfo part of the URI.
* @type {RegExp}
* @private
*/
goog.Uri.reDisallowedInSchemeOrUserInfo_ = /[#\/\?@]/g;
/**
* Regular expression for characters that are disallowed in a relative path.
* Colon is included due to RFC 3986 3.3.
* @type {RegExp}
* @private
*/
goog.Uri.reDisallowedInRelativePath_ = /[\#\?:]/g;
/**
* Regular expression for characters that are disallowed in an absolute path.
* @type {RegExp}
* @private
*/
goog.Uri.reDisallowedInAbsolutePath_ = /[\#\?]/g;
/**
* Regular expression for characters that are disallowed in the query.
* @type {RegExp}
* @private
*/
goog.Uri.reDisallowedInQuery_ = /[\#\?@]/g;
/**
* Regular expression for characters that are disallowed in the fragment.
* @type {RegExp}
* @private
*/
goog.Uri.reDisallowedInFragment_ = /#/g;
/**
* Class used to represent URI query parameters. It is essentially a hash of
* name-value pairs, though a name can be present more than once.
*
* Has the same interface as the collections in goog.structs.
*
* @param {?string=} query Optional encoded query string to parse into
* the object.
* @param {goog.Uri=} uri Optional uri object that should have its
* cache invalidated when this object updates. Deprecated -- this
* is no longer required.
* @constructor
* @final
*/
goog.Uri.QueryData = function(query, uri) {
/**
* Encoded query string, or null if it requires computing from the key map.
* @type {?string}
* @private
*/
this.encodedQuery_ = query || null;
};
/**
* If the underlying key map is not yet initialized, it parses the
* query string and fills the map with parsed data.
* @private
*/
goog.Uri.QueryData.prototype.ensureKeyMapInitialized_ = function() {
if (!this.keyMap_) {
this.keyMap_ = {};
this.count_ = 0;
if (this.encodedQuery_) {
var pairs = this.encodedQuery_.split('&');
for (var i = 0; i < pairs.length; i++) {
var indexOfEquals = pairs[i].indexOf('=');
var name = null;
var value = null;
if (indexOfEquals >= 0) {
name = pairs[i].substring(0, indexOfEquals);
value = pairs[i].substring(indexOfEquals + 1);
} else {
name = pairs[i];
}
name = decodeURIComponent(name.replace(/\+/g, ' '));
value = value || '';
this.add(name, decodeURIComponent(value.replace(/\+/g, ' ')));
}
}
}
};
/**
* The map containing name/value or name/array-of-values pairs.
* May be null if it requires parsing from the query string.
*
* We need to use a Map because we cannot guarantee that the key names will
* not be problematic for IE.
*
* @type {Object.<string, !Array.<string>>}
* @private
*/
goog.Uri.QueryData.prototype.keyMap_ = null;
/**
* The number of params, or null if it requires computing.
* @type {?number}
* @private
*/
goog.Uri.QueryData.prototype.count_ = null;
/**
* @return {?number} The number of parameters.
*/
goog.Uri.QueryData.prototype.getCount = function() {
this.ensureKeyMapInitialized_();
return this.count_;
};
/**
* Adds a key value pair.
* @param {string} key Name.
* @param {*} value Value.
* @return {!goog.Uri.QueryData} Instance of this object.
*/
goog.Uri.QueryData.prototype.add = function(key, value) {
this.ensureKeyMapInitialized_();
// Invalidate the cache.
this.encodedQuery_ = null;
var values = this.keyMap_.hasOwnProperty(key) && this.keyMap_[key];
if (!values) {
this.keyMap_[key] = (values = []);
}
values.push(value);
this.count_++;
return this;
};
/**
* @return {string} Encoded query string.
* @override
*/
goog.Uri.QueryData.prototype.toString = function() {
if (this.encodedQuery_) {
return this.encodedQuery_;
}
if (!this.keyMap_) {
return '';
}
var sb = [];
for (var key in this.keyMap_) {
var encodedKey = encodeURIComponent(key);
var val = this.keyMap_[key];
for (var j = 0; j < val.length; j++) {
var param = encodedKey;
// Ensure that null and undefined are encoded into the url as
// literal strings.
if (val[j] !== '') {
param += '=' + encodeURIComponent(val[j]);
}
sb.push(param);
}
}
return this.encodedQuery_ = sb.join('&');
};
/**
* @return {string} Decoded query string.
*/
goog.Uri.QueryData.prototype.toDecodedString = function() {
return goog.Uri.decodeOrEmpty_(this.toString());
};
/**
* Clone the query data instance.
* @return {!goog.Uri.QueryData} New instance of the QueryData object.
*/
goog.Uri.QueryData.prototype.clone = function() {
var rv = new goog.Uri.QueryData();
rv.encodedQuery_ = this.encodedQuery_;
if (this.keyMap_) {
var cloneMap = {};
for (var key in this.keyMap_) {
cloneMap[key] = this.keyMap_[key].concat();
}
rv.keyMap_ = cloneMap;
rv.count_ = this.count_;
}
return rv;
};
|
#!/usr/bin/env python3 -u
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Train a new model on one or across multiple GPUs.
"""
import collections
import math
import random
import numpy as np
import torch
from fairseq import checkpoint_utils, distributed_utils, options, progress_bar, tasks, utils
from fairseq.data import iterators
from fairseq.trainer import Trainer
from fairseq.meters import AverageMeter, StopwatchMeter
fb_pathmgr_registerd = False
def main(args, init_distributed=False):
utils.import_user_module(args)
try:
from fairseq.fb_pathmgr import fb_pathmgr
global fb_pathmgr_registerd
if not fb_pathmgr_registerd:
fb_pathmgr.register()
fb_pathmgr_registerd = True
except (ModuleNotFoundError, ImportError):
pass
assert args.max_tokens is not None or args.max_sentences is not None, \
'Must specify batch size either with --max-tokens or --max-sentences'
# Initialize CUDA and distributed training
if torch.cuda.is_available() and not args.cpu:
torch.cuda.set_device(args.device_id)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if init_distributed:
args.distributed_rank = distributed_utils.distributed_init(args)
if distributed_utils.is_master(args):
checkpoint_utils.verify_checkpoint_directory(args.save_dir)
# Print args
print(args)
# Setup task, e.g., translation, language modeling, etc.
task = tasks.setup_task(args)
# Load valid dataset (we load training data below, based on the latest checkpoint)
for valid_sub_split in args.valid_subset.split(','):
task.load_dataset(valid_sub_split, combine=False, epoch=0)
# Build model and criterion
model = task.build_model(args)
criterion = task.build_criterion(args)
print(model)
print('| model {}, criterion {}'.format(args.arch, criterion.__class__.__name__))
print('| num. model params: {} (num. trained: {})'.format(
sum(p.numel() for p in model.parameters()),
sum(p.numel() for p in model.parameters() if p.requires_grad),
))
# Build trainer
trainer = Trainer(args, task, model, criterion)
print('| training on {} GPUs'.format(args.distributed_world_size))
print('| max tokens per GPU = {} and max sentences per GPU = {}'.format(
args.max_tokens,
args.max_sentences,
))
# Load the latest checkpoint if one is available and restore the
# corresponding train iterator
extra_state, epoch_itr = checkpoint_utils.load_checkpoint(args, trainer)
# Train until the learning rate gets too small
max_epoch = args.max_epoch or math.inf
max_update = args.max_update or math.inf
lr = trainer.get_lr()
train_meter = StopwatchMeter()
train_meter.start()
valid_subsets = args.valid_subset.split(',')
while lr > args.min_lr and epoch_itr.epoch < max_epoch and trainer.get_num_updates() < max_update:
# train for one epoch
train(args, trainer, task, epoch_itr)
if not args.disable_validation and epoch_itr.epoch % args.validate_interval == 0:
valid_losses = validate(args, trainer, task, epoch_itr, valid_subsets)
else:
valid_losses = [None]
# only use first validation loss to update the learning rate
lr = trainer.lr_step(epoch_itr.epoch, valid_losses[0])
# save checkpoint
if epoch_itr.epoch % args.save_interval == 0:
checkpoint_utils.save_checkpoint(args, trainer, epoch_itr, valid_losses[0])
reload_dataset = ':' in getattr(args, 'data', '')
# sharded data: get train iterator for next epoch
epoch_itr = trainer.get_train_iterator(epoch_itr.epoch, load_dataset=reload_dataset)
train_meter.stop()
print('| done training in {:.1f} seconds'.format(train_meter.sum))
def train(args, trainer, task, epoch_itr):
"""Train the model for one epoch."""
# Update parameters every N batches
update_freq = args.update_freq[epoch_itr.epoch - 1] \
if epoch_itr.epoch <= len(args.update_freq) else args.update_freq[-1]
# Initialize data iterator
itr = epoch_itr.next_epoch_itr(
fix_batches_to_gpus=args.fix_batches_to_gpus,
shuffle=(epoch_itr.epoch >= args.curriculum),
)
itr = iterators.GroupedIterator(itr, update_freq)
progress = progress_bar.build_progress_bar(
args, itr, epoch_itr.epoch, no_progress_bar='simple',
)
extra_meters = collections.defaultdict(lambda: AverageMeter())
valid_subsets = args.valid_subset.split(',')
max_update = args.max_update or math.inf
for i, samples in enumerate(progress, start=epoch_itr.iterations_in_epoch):
log_output = trainer.train_step(samples)
if log_output is None:
continue
# log mid-epoch stats
stats = get_training_stats(trainer)
for k, v in log_output.items():
if k in ['loss', 'nll_loss', 'ntokens', 'nsentences', 'sample_size']:
continue # these are already logged above
if 'loss' in k or k == 'accuracy':
extra_meters[k].update(v, log_output['sample_size'])
else:
extra_meters[k].update(v)
stats[k] = extra_meters[k].avg
progress.log(stats, tag='train', step=stats['num_updates'])
# ignore the first mini-batch in words-per-second and updates-per-second calculation
if i == 0:
trainer.get_meter('wps').reset()
trainer.get_meter('ups').reset()
num_updates = trainer.get_num_updates()
if (
not args.disable_validation
and args.save_interval_updates > 0
and num_updates % args.save_interval_updates == 0
and num_updates > 0
):
valid_losses = validate(args, trainer, task, epoch_itr, valid_subsets)
checkpoint_utils.save_checkpoint(args, trainer, epoch_itr, valid_losses[0])
if num_updates >= max_update:
break
# log end-of-epoch stats
stats = get_training_stats(trainer)
for k, meter in extra_meters.items():
stats[k] = meter.avg
progress.print(stats, tag='train', step=stats['num_updates'])
# reset training meters
for k in [
'train_loss', 'train_nll_loss', 'wps', 'ups', 'wpb', 'bsz', 'gnorm', 'clip',
]:
meter = trainer.get_meter(k)
if meter is not None:
meter.reset()
def get_training_stats(trainer):
stats = collections.OrderedDict()
stats['loss'] = trainer.get_meter('train_loss')
if trainer.get_meter('train_nll_loss').count > 0:
nll_loss = trainer.get_meter('train_nll_loss')
stats['nll_loss'] = nll_loss
else:
nll_loss = trainer.get_meter('train_loss')
stats['ppl'] = utils.get_perplexity(nll_loss.avg)
stats['wps'] = trainer.get_meter('wps')
stats['ups'] = trainer.get_meter('ups')
stats['wpb'] = trainer.get_meter('wpb')
stats['bsz'] = trainer.get_meter('bsz')
stats['num_updates'] = trainer.get_num_updates()
stats['lr'] = trainer.get_lr()
stats['gnorm'] = trainer.get_meter('gnorm')
stats['clip'] = trainer.get_meter('clip')
stats['oom'] = trainer.get_meter('oom')
if trainer.get_meter('loss_scale') is not None:
stats['loss_scale'] = trainer.get_meter('loss_scale')
stats['wall'] = round(trainer.get_meter('wall').elapsed_time)
stats['train_wall'] = trainer.get_meter('train_wall')
return stats
def validate(args, trainer, task, epoch_itr, subsets):
"""Evaluate the model on the validation set(s) and return the losses."""
if args.fixed_validation_seed is not None:
# set fixed seed for every validation
utils.set_torch_seed(args.fixed_validation_seed)
valid_losses = []
for subset in subsets:
# Initialize data iterator
itr = task.get_batch_iterator(
dataset=task.dataset(subset),
max_tokens=args.max_tokens_valid,
max_sentences=args.max_sentences_valid,
max_positions=utils.resolve_max_positions(
task.max_positions(),
trainer.get_model().max_positions(),
),
ignore_invalid_inputs=args.skip_invalid_size_inputs_valid_test,
required_batch_size_multiple=args.required_batch_size_multiple,
seed=args.seed,
num_shards=args.distributed_world_size,
shard_id=args.distributed_rank,
num_workers=args.num_workers,
).next_epoch_itr(shuffle=False)
progress = progress_bar.build_progress_bar(
args, itr, epoch_itr.epoch,
prefix='valid on \'{}\' subset'.format(subset),
no_progress_bar='simple'
)
# reset validation loss meters
for k in ['valid_loss', 'valid_nll_loss']:
meter = trainer.get_meter(k)
if meter is not None:
meter.reset()
extra_meters = collections.defaultdict(lambda: AverageMeter())
for sample in progress:
log_output = trainer.valid_step(sample)
for k, v in log_output.items():
if k in ['loss', 'nll_loss', 'ntokens', 'nsentences', 'sample_size']:
continue
extra_meters[k].update(v)
# log validation stats
stats = get_valid_stats(trainer, args, extra_meters)
for k, meter in extra_meters.items():
stats[k] = meter.avg
progress.print(stats, tag=subset, step=trainer.get_num_updates())
valid_losses.append(
stats[args.best_checkpoint_metric].avg
if args.best_checkpoint_metric == 'loss'
else stats[args.best_checkpoint_metric]
)
return valid_losses
def get_valid_stats(trainer, args, extra_meters=None):
stats = collections.OrderedDict()
stats['loss'] = trainer.get_meter('valid_loss')
if trainer.get_meter('valid_nll_loss').count > 0:
nll_loss = trainer.get_meter('valid_nll_loss')
stats['nll_loss'] = nll_loss
else:
nll_loss = stats['loss']
stats['ppl'] = utils.get_perplexity(nll_loss.avg)
stats['num_updates'] = trainer.get_num_updates()
if hasattr(checkpoint_utils.save_checkpoint, 'best'):
key = 'best_{0}'.format(args.best_checkpoint_metric)
best_function = max if args.maximize_best_checkpoint_metric else min
current_metric = None
if args.best_checkpoint_metric == 'loss':
current_metric = stats['loss'].avg
elif args.best_checkpoint_metric in extra_meters:
current_metric = extra_meters[args.best_checkpoint_metric].avg
elif args.best_checkpoint_metric in stats:
current_metric = stats[args.best_checkpoint_metric]
else:
raise ValueError("best_checkpoint_metric not found in logs")
stats[key] = best_function(
checkpoint_utils.save_checkpoint.best,
current_metric,
)
return stats
def distributed_main(i, args, start_rank=0):
args.device_id = i
if args.distributed_rank is None: # torch.multiprocessing.spawn
args.distributed_rank = start_rank + i
main(args, init_distributed=True)
def cli_main():
parser = options.get_training_parser()
args = options.parse_args_and_arch(parser)
if args.distributed_init_method is None:
distributed_utils.infer_init_method(args)
if args.distributed_init_method is not None:
# distributed training
if torch.cuda.device_count() > 1 and not args.distributed_no_spawn:
start_rank = args.distributed_rank
args.distributed_rank = None # assign automatically
torch.multiprocessing.spawn(
fn=distributed_main,
args=(args, start_rank),
nprocs=torch.cuda.device_count(),
)
else:
distributed_main(args.device_id, args)
elif args.distributed_world_size > 1:
# fallback for single node with multiple GPUs
assert args.distributed_world_size <= torch.cuda.device_count()
port = random.randint(10000, 20000)
args.distributed_init_method = 'tcp://localhost:{port}'.format(port=port)
args.distributed_rank = None # set based on device id
if max(args.update_freq) > 1 and args.ddp_backend != 'no_c10d':
print('| NOTE: you may get better performance with: --ddp-backend=no_c10d')
torch.multiprocessing.spawn(
fn=distributed_main,
args=(args, ),
nprocs=args.distributed_world_size,
)
else:
# single GPU training
main(args)
if __name__ == '__main__':
cli_main()
|
const encryptPW |
// RealShowHide v0.1 by Simkin Andrew - http://RealAdmin.ru
(function( $ ) {
$.fn.RealShowHide = function(options) {
var settings = $.extend( {
'speed' : undefined,
'dataName' : 'element'
}, options);
this.click(function(e){
var block = $(e.target).data(settings['dataName']);
if (block===undefined) return;
$(block).slideToggle(settings['speed']);
return;
});
return this;
};
})(jQuery);
|
let images = {
greenFrog: 'http://i.imgur.com/jM2kzrd.png',
redFrog: 'http://i.imgur.com/0kcX1In.png',
yellowFrog: 'http://i.imgur.com/8gFtBGN.png',
greenLilly: 'http://i.imgur.com/P85vO4u.png',
redLilly: 'http://i.imgur.com/RlKQ52D.png',
yellowLilly: 'http://i.imgur.com/7sC9O25.png'
}
export default images |
from rest_framework import mixins
from rest_framework import generics
from .models import Employee
from .serializers import EmployeeSerializer
class EmployeeList(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView):
queryset = Employee.objects.all()
serializer_class = EmployeeSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
class EmployeeDetail(mixins.RetrieveModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView):
queryset = Employee.objects.all()
serializer_class = EmployeeSerializer
lookup_field = 'email'
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
|
from decimal import Decimal
from io import BytesIO
from unittest.mock import MagicMock, Mock
import pytest
from django.contrib.auth.models import AnonymousUser, Group, Permission
from django.contrib.sites.models import Site
from django.core.files import File
from django.core.files.uploadedfile import SimpleUploadedFile
from django.utils.encoding import smart_text
from PIL import Image
from prices import Price
from saleor.cart import utils
from saleor.cart.models import Cart
from saleor.checkout.core import Checkout
from saleor.discount.models import Sale, Voucher
from saleor.order import GroupStatus
from saleor.order.models import DeliveryGroup, Order, OrderLine
from saleor.order.utils import recalculate_order
from saleor.product.models import (
AttributeChoiceValue, Category, Product, ProductAttribute, ProductClass,
ProductImage, ProductVariant, Stock, StockLocation)
from saleor.shipping.models import ShippingMethod
from saleor.site.models import AuthorizationKey, SiteSettings
from saleor.userprofile.models import Address, User
@pytest.fixture(autouse=True)
def site_settings(db, settings):
'''
This fixture is autouse set to True because
django.contrib.sites.models.Site and saleor.site.models.SiteSettings has
OneToOne relationship and Site should never exist without SiteSettings.
'''
site = Site.objects.get_or_create(name="mirumee.com", domain="mirumee.com")[0]
obj = SiteSettings.objects.get_or_create(site=site)[0]
settings.SITE_ID = site.pk
return obj
@pytest.fixture
def cart(db): # pylint: disable=W0613
return Cart.objects.create()
@pytest.fixture
def customer_user(db): # pylint: disable=W0613
return User.objects.create_user('[email protected]', 'password')
@pytest.fixture
def request_cart(cart, monkeypatch):
# FIXME: Fixtures should not have any side effects
monkeypatch.setattr(
utils, 'get_cart_from_request',
lambda request, cart_queryset=None: cart)
cart.discounts = Sale.objects.all()
return cart
@pytest.fixture
def request_cart_with_item(product_in_stock, request_cart):
variant = product_in_stock.variants.get()
# Prepare some data
request_cart.add(variant)
return request_cart
@pytest.fixture
def order(billing_address):
return Order.objects.create(billing_address=billing_address)
@pytest.fixture()
def admin_user(db): # pylint: disable=W0613
"""A Django admin user.
"""
return User.objects.create_superuser('[email protected]', 'password')
@pytest.fixture()
def admin_client(admin_user):
"""A Django test client logged in as an admin user."""
from django.test.client import Client
client = Client()
client.login(username=admin_user.email, password='password')
return client
@pytest.fixture()
def staff_user(db):
"""A Django staff user"""
return User.objects.create_user(
email='[email protected]', password='password', is_staff=True,
is_active=True)
@pytest.fixture()
def staff_client(client, staff_user):
"""A Django test client logged in as an staff member"""
client.login(username=staff_user.email, password='password')
return client
@pytest.fixture()
def authorized_client(client, customer_user):
client.login(username=customer_user.email, password='password')
return client
@pytest.fixture
def billing_address(db): # pylint: disable=W0613
return Address.objects.create(
first_name='John', last_name='Doe',
company_name='Mirumee Software',
street_address_1='Tęczowa 7',
city='Wrocław',
postal_code='53-601',
country='PL',
phone='+48713988102')
@pytest.fixture
def shipping_method(db): # pylint: disable=W0613
shipping_method = ShippingMethod.objects.create(name='DHL')
shipping_method.price_per_country.create(price=10)
return shipping_method
@pytest.fixture
def color_attribute(db): # pylint: disable=W0613
attribute = ProductAttribute.objects.create(
slug='color', name='Color')
AttributeChoiceValue.objects.create(
attribute=attribute, name='Red', slug='red')
AttributeChoiceValue.objects.create(
attribute=attribute, name='Blue', slug='blue')
return attribute
@pytest.fixture
def size_attribute(db): # pylint: disable=W0613
attribute = ProductAttribute.objects.create(slug='size', name='Size')
AttributeChoiceValue.objects.create(
attribute=attribute, name='Small', slug='small')
AttributeChoiceValue.objects.create(
attribute=attribute, name='Big', slug='big')
return attribute
@pytest.fixture
def default_category(db): # pylint: disable=W0613
return Category.objects.create(name='Default', slug='default')
@pytest.fixture
def default_stock_location(db):
return StockLocation.objects.create(name='Warehouse 1')
@pytest.fixture
def staff_group():
return Group.objects.create(name='test')
@pytest.fixture
def permission_view_product():
return Permission.objects.get(codename='view_product')
@pytest.fixture
def permission_edit_product():
return Permission.objects.get(codename='edit_product')
@pytest.fixture
def permission_view_category():
return Permission.objects.get(codename='view_category')
@pytest.fixture
def permission_edit_category():
return Permission.objects.get(codename='edit_category')
@pytest.fixture
def permission_view_stock_location():
return Permission.objects.get(codename='view_stock_location')
@pytest.fixture
def permission_edit_stock_location():
return Permission.objects.get(codename='edit_stock_location')
@pytest.fixture
def permission_view_sale():
return Permission.objects.get(codename='view_sale')
@pytest.fixture
def permission_edit_sale():
return Permission.objects.get(codename='edit_sale')
@pytest.fixture
def permission_view_voucher():
return Permission.objects.get(codename='view_voucher')
@pytest.fixture
def permission_edit_voucher():
return Permission.objects.get(codename='edit_voucher')
@pytest.fixture
def permission_view_order():
return Permission.objects.get(codename='view_order')
@pytest.fixture
def permission_edit_order():
return Permission.objects.get(codename='edit_order')
@pytest.fixture
def permission_view_user():
return Permission.objects.get(codename='view_user')
@pytest.fixture
def product_class(color_attribute, size_attribute):
product_class = ProductClass.objects.create(name='Default Class',
has_variants=False,
is_shipping_required=True)
product_class.product_attributes.add(color_attribute)
product_class.variant_attributes.add(size_attribute)
return product_class
@pytest.fixture
def product_in_stock(product_class, default_category):
product_attr = product_class.product_attributes.first()
attr_value = product_attr.values.first()
attributes = {smart_text(product_attr.pk): smart_text(attr_value.pk)}
product = Product.objects.create(
name='Test product', price=Decimal('10.00'),
product_class=product_class, attributes=attributes)
product.categories.add(default_category)
variant_attr = product_class.variant_attributes.first()
variant_attr_value = variant_attr.values.first()
variant_attributes = {
smart_text(variant_attr.pk): smart_text(variant_attr_value.pk)
}
variant = ProductVariant.objects.create(
product=product, sku='123', attributes=variant_attributes)
warehouse_1 = StockLocation.objects.create(name='Warehouse 1')
warehouse_2 = StockLocation.objects.create(name='Warehouse 2')
warehouse_3 = StockLocation.objects.create(name='Warehouse 3')
Stock.objects.create(
variant=variant, cost_price=1, quantity=5, quantity_allocated=5,
location=warehouse_1)
Stock.objects.create(
variant=variant, cost_price=100, quantity=5, quantity_allocated=5,
location=warehouse_2)
Stock.objects.create(
variant=variant, cost_price=10, quantity=5, quantity_allocated=0,
location=warehouse_3)
return product
@pytest.fixture
def product_list(product_class, default_category):
product_attr = product_class.product_attributes.first()
attr_value = product_attr.values.first()
attributes = {smart_text(product_attr.pk): smart_text(attr_value.pk)}
product_1 = Product.objects.create(
name='Test product 1', price=Decimal('10.00'),
product_class=product_class, attributes=attributes, is_published=True)
product_1.categories.add(default_category)
product_2 = Product.objects.create(
name='Test product 2', price=Decimal('20.00'),
product_class=product_class, attributes=attributes, is_published=False)
product_2.categories.add(default_category)
product_3 = Product.objects.create(
name='Test product 3', price=Decimal('20.00'),
product_class=product_class, attributes=attributes, is_published=True)
product_3.categories.add(default_category)
return [product_1, product_2, product_3]
@pytest.fixture
def order_list(admin_user, billing_address):
data = {
'billing_address': billing_address, 'user': admin_user,
'user_email': admin_user.email, 'total': Price(123, currency='USD')}
order = Order.objects.create(**data)
order1 = Order.objects.create(**data)
order2 = Order.objects.create(**data)
return [order, order1, order2]
@pytest.fixture
def stock_location():
warehouse_1 = StockLocation.objects.create(name='Warehouse 1')
return warehouse_1
@pytest.fixture
def product_image():
img_data = BytesIO()
image = Image.new('RGB', size=(1, 1))
image.save(img_data, format='JPEG')
return SimpleUploadedFile('product.jpg', img_data.getvalue())
@pytest.fixture
def product_with_image(product_in_stock, product_image):
product = product_in_stock
ProductImage.objects.create(product=product, image=product_image)
return product
@pytest.fixture
def unavailable_product(product_class, default_category):
product = Product.objects.create(
name='Test product', price=Decimal('10.00'),
product_class=product_class,
is_published=False)
product.categories.add(default_category)
return product
@pytest.fixture
def product_with_images(product_class, default_category):
product = Product.objects.create(
name='Test product', price=Decimal('10.00'),
product_class=product_class)
product.categories.add(default_category)
file_mock_0 = MagicMock(spec=File, name='FileMock0')
file_mock_0.name = 'image0.jpg'
file_mock_1 = MagicMock(spec=File, name='FileMock1')
file_mock_1.name = 'image1.jpg'
product.images.create(image=file_mock_0)
product.images.create(image=file_mock_1)
return product
@pytest.fixture
def anonymous_checkout():
return Checkout((), AnonymousUser(), 'tracking_code')
@pytest.fixture
def voucher(db): # pylint: disable=W0613
return Voucher.objects.create(code='mirumee', discount_value=20)
@pytest.fixture()
def order_with_lines(order, product_class):
group = DeliveryGroup.objects.create(order=order)
product = Product.objects.create(
name='Test product', price=Decimal('10.00'),
product_class=product_class)
OrderLine.objects.create(
delivery_group=group,
product=product,
product_name=product.name,
product_sku='SKU_%d' % (product.pk,),
quantity=1,
unit_price_net=Decimal('10.00'),
unit_price_gross=Decimal('10.00'),
)
product = Product.objects.create(
name='Test product 2', price=Decimal('20.00'),
product_class=product_class)
OrderLine.objects.create(
delivery_group=group,
product=product,
product_name=product.name,
product_sku='SKU_%d' % (product.pk,),
quantity=1,
unit_price_net=Decimal('20.00'),
unit_price_gross=Decimal('20.00'),
)
product = Product.objects.create(
name='Test product 3', price=Decimal('30.00'),
product_class=product_class)
OrderLine.objects.create(
delivery_group=group,
product=product,
product_name=product.name,
product_sku='SKU_%d' % (product.pk,),
quantity=1,
unit_price_net=Decimal('30.00'),
unit_price_gross=Decimal('30.00'),
)
return order
@pytest.fixture()
def order_with_lines_and_stock(order, product_class):
group = DeliveryGroup.objects.create(order=order)
product = Product.objects.create(
name='Test product', price=Decimal('10.00'),
product_class=product_class)
variant = ProductVariant.objects.create(product=product, sku='SKU_A')
warehouse = StockLocation.objects.create(name='Warehouse 1')
stock = Stock.objects.create(
variant=variant, cost_price=1, quantity=5, quantity_allocated=3,
location=warehouse)
OrderLine.objects.create(
delivery_group=group,
product=product,
product_name=product.name,
product_sku='SKU_A',
quantity=3,
unit_price_net=Decimal('30.00'),
unit_price_gross=Decimal('30.00'),
stock=stock,
stock_location=stock.location.name
)
product = Product.objects.create(
name='Test product 2', price=Decimal('20.00'),
product_class=product_class)
variant = ProductVariant.objects.create(product=product, sku='SKU_B')
stock = Stock.objects.create(
variant=variant, cost_price=2, quantity=2, quantity_allocated=2,
location=warehouse)
OrderLine.objects.create(
delivery_group=group,
product=product,
product_name=product.name,
product_sku='SKU_B',
quantity=2,
unit_price_net=Decimal('20.00'),
unit_price_gross=Decimal('20.00'),
stock=stock,
stock_location=stock.location.name
)
recalculate_order(order)
order.refresh_from_db()
return order
@pytest.fixture()
def order_with_variant_from_different_stocks(order_with_lines_and_stock):
line = OrderLine.objects.get(product_sku='SKU_A')
variant = ProductVariant.objects.get(sku=line.product_sku)
warehouse_2 = StockLocation.objects.create(name='Warehouse 2')
stock = Stock.objects.create(
variant=variant, cost_price=1, quantity=5, quantity_allocated=2,
location=warehouse_2)
OrderLine.objects.create(
delivery_group=line.delivery_group,
product=variant.product,
product_name=variant.product.name,
product_sku=line.product_sku,
quantity=2,
unit_price_net=Decimal('30.00'),
unit_price_gross=Decimal('30.00'),
stock=stock,
stock_location=stock.location.name
)
warehouse_2 = StockLocation.objects.create(name='Warehouse 3')
Stock.objects.create(
variant=variant, cost_price=1, quantity=5, quantity_allocated=0,
location=warehouse_2)
return order_with_lines_and_stock
@pytest.fixture()
def delivery_group(order, product_class):
group = DeliveryGroup.objects.create(order=order)
product = Product.objects.create(
name='Test product', price=Decimal('10.00'),
product_class=product_class)
variant = ProductVariant.objects.create(product=product, sku='SKU_A')
warehouse = StockLocation.objects.create(name='Warehouse 1')
stock = Stock.objects.create(
variant=variant, cost_price=1, quantity=5, quantity_allocated=3,
location=warehouse)
OrderLine.objects.create(
delivery_group=group,
product=product,
product_name=product.name,
product_sku='SKU_A',
quantity=3,
unit_price_net=Decimal('30.00'),
unit_price_gross=Decimal('30.00'),
stock=stock,
stock_location=stock.location.name)
recalculate_order(order)
order.refresh_from_db()
return group
@pytest.fixture()
def sale(db, default_category):
sale = Sale.objects.create(name="Sale", value=5)
sale.categories.add(default_category)
return sale
@pytest.fixture
def authorization_key(db, site_settings):
return AuthorizationKey.objects.create(
site_settings=site_settings, name='Backend', key='Key',
password='Password')
@pytest.fixture
def permission_view_staff():
return Permission.objects.get(codename='view_staff')
@pytest.fixture
def permission_edit_staff():
return Permission.objects.get(codename='edit_staff')
@pytest.fixture
def permission_view_group():
return Permission.objects.get(codename='view_group')
@pytest.fixture
def permission_edit_group():
return Permission.objects.get(codename='edit_group')
@pytest.fixture
def permission_view_properties():
return Permission.objects.get(codename='view_properties')
@pytest.fixture
def permission_edit_properties():
return Permission.objects.get(codename='edit_properties')
@pytest.fixture
def permission_view_shipping():
return Permission.objects.get(codename='view_shipping')
@pytest.fixture
def permission_edit_shipping():
return Permission.objects.get(codename='edit_shipping')
@pytest.fixture
def permission_view_user():
return Permission.objects.get(codename='view_user')
@pytest.fixture
def permission_edit_user():
return Permission.objects.get(codename='edit_user')
@pytest.fixture
def permission_edit_settings():
return Permission.objects.get(codename='edit_settings')
@pytest.fixture
def permission_impersonate_user():
return Permission.objects.get(codename='impersonate_user')
@pytest.fixture
def open_orders(billing_address):
orders = []
group_data = lambda orders, status: {'order': orders[-1], 'status': status}
orders.append(Order.objects.create(billing_address=billing_address))
DeliveryGroup.objects.create(**group_data(orders, GroupStatus.NEW))
orders.append(Order.objects.create(billing_address=billing_address))
DeliveryGroup.objects.create(**group_data(orders, GroupStatus.NEW))
DeliveryGroup.objects.create(**group_data(orders, GroupStatus.CANCELLED))
orders.append(Order.objects.create(billing_address=billing_address))
DeliveryGroup.objects.create(**group_data(orders, GroupStatus.NEW))
DeliveryGroup.objects.create(**group_data(orders, GroupStatus.SHIPPED))
orders.append(Order.objects.create(billing_address=billing_address))
DeliveryGroup.objects.create(**group_data(orders, GroupStatus.NEW))
DeliveryGroup.objects.create(**group_data(orders, GroupStatus.SHIPPED))
DeliveryGroup.objects.create(**group_data(orders, GroupStatus.CANCELLED))
return orders
@pytest.fixture
def closed_orders(billing_address):
orders = []
group_data = lambda orders, status: {'order': orders[-1], 'status': status}
orders.append(Order.objects.create(billing_address=billing_address))
DeliveryGroup.objects.create(**group_data(orders, GroupStatus.SHIPPED))
orders.append(Order.objects.create(billing_address=billing_address))
DeliveryGroup.objects.create(**group_data(orders, GroupStatus.SHIPPED))
DeliveryGroup.objects.create(**group_data(orders, GroupStatus.CANCELLED))
orders.append(Order.objects.create(billing_address=billing_address))
DeliveryGroup.objects.create(**group_data(orders, GroupStatus.CANCELLED))
# empty order is considered as closed
orders.append(Order.objects.create(billing_address=billing_address))
return orders
|
import { assert, expect } from 'chai';
import enable from '../src/enable.js';
import updateImage from '../src/updateImage.js';
import disable from '../src/disable.js';
import { getEnabledElement } from '../src/enabledElements.js';
import metaData from '../src/metaData.js';
import {
addLayer,
removeLayer,
getLayer,
getLayers,
getVisibleLayers,
setActiveLayer,
getActiveLayer
} from '../src/layers.js';
describe('layers', function () {
beforeEach(function () {
// Arrange
this.element = document.createElement('div');
const height = 2;
const width = 2;
const getPixelData = () => new Uint8Array([0, 255, 255, 0]);
this.image1 = {
imageId: 'exampleImageId1',
minPixelValue: 0,
maxPixelValue: 255,
slope: 1.0,
intercept: 0,
windowCenter: 127,
windowWidth: 256,
getPixelData,
rows: height,
columns: width,
height,
width,
color: false,
sizeInBytes: width * height * 2
};
const getPixelData2 = () => new Uint8Array([5, 6, 7, 8]);
this.image2 = {
imageId: 'exampleImageId2',
minPixelValue: 0,
maxPixelValue: 255,
slope: 1.0,
intercept: 0,
windowCenter: 127,
windowWidth: 256,
getPixelData: getPixelData2,
rows: height,
columns: width,
height,
width,
color: false,
sizeInBytes: width * height * 2
};
const imagePlaneMetadata = {
exampleImageId1: {
columnPixelSpacing: 1,
rowPixelSpacing: 1
},
exampleImageId2: {
columnPixelSpacing: 2,
rowPixelSpacing: 2
}
};
metaData.addProvider((type, imageId) => {
if (type === 'imagePlane') {
return imagePlaneMetadata[imageId];
}
});
enable(this.element);
});
it('addLayers: should add one layer', function () {
// Arrange
addLayer(this.element, this.image1);
updateImage(this.element);
// Act
const enabledElement = getEnabledElement(this.element);
// Assert
expect(enabledElement.layers).to.be.an('array');
expect(enabledElement.layers.length).to.equal(1);
});
it('addLayers: should fire CornerstoneLayerAdded', function (done) {
// Arrange
$(this.element).on('CornerstoneLayerAdded', (event, eventData) => {
// Assert
expect(eventData).to.be.an('object');
expect(eventData);
done();
});
// Act
addLayer(this.element, this.image1);
updateImage(this.element);
});
it('addLayers: should add two layers', function () {
// Arrange
addLayer(this.element, this.image1);
addLayer(this.element, this.image2);
updateImage(this.element);
// Act
const enabledElement = getEnabledElement(this.element);
// Assert
expect(enabledElement.layers).to.be.an('array');
expect(enabledElement.layers.length).to.equal(2);
});
it('should retrieve both of the two layers', function () {
// Arrange
addLayer(this.element, this.image1);
addLayer(this.element, this.image2);
updateImage(this.element);
// Act
const layers = getLayers(this.element);
// Assert
expect(layers).to.be.an('array');
expect(layers.length).to.equal(2);
});
it('should remove one of the two layers', function () {
// Arrange
const layerId1 = addLayer(this.element, this.image1);
const layerId2 = addLayer(this.element, this.image2);
updateImage(this.element);
// Act
removeLayer(this.element, layerId1);
const layers = getLayers(this.element);
// Assert
expect(layers).to.be.an('array');
expect(layers.length).to.equal(1);
expect(layers[0].layerId).to.equal(layerId2);
});
it('should remove both of the two layers', function () {
// Arrange
const layerId1 = addLayer(this.element, this.image1);
const layerId2 = addLayer(this.element, this.image2);
updateImage(this.element);
// Act
removeLayer(this.element, layerId2);
removeLayer(this.element, layerId1);
const layers = getLayers(this.element);
// Assert
expect(layers).to.be.an('array');
expect(layers.length).to.equal(0);
});
it('should retrieve only the visible layers', function () {
// Arrange
addLayer(this.element, this.image1, {
visible: false
});
const layerId2 = addLayer(this.element, this.image2);
addLayer(this.element, this.image1, {
opacity: 0
});
const layerId4 = addLayer(this.element, this.image2, {
opacity: 0.2
});
updateImage(this.element);
// Act
const layers = getVisibleLayers(this.element);
// Assert
expect(layers).to.be.an('array');
expect(layers.length).to.equal(2);
expect(layers[0].layerId).to.equal(layerId2);
expect(layers[1].layerId).to.equal(layerId4);
});
it('should correctly retrieve the layers by ID', function () {
// Arrange
const layerId1 = addLayer(this.element, this.image1);
const layerId2 = addLayer(this.element, this.image2);
updateImage(this.element);
// Act
const layer1 = getLayer(this.element, layerId1);
const layer2 = getLayer(this.element, layerId2);
// Assert
expect(layer1).to.be.an('object');
expect(layer1.layerId).to.equal(layerId1);
expect(layer2).to.be.an('object');
expect(layer2.layerId).to.equal(layerId2);
});
it('should correctly set and retrieve the active layer', function (done) {
// Arrange
addLayer(this.element, this.image1);
const layerId2 = addLayer(this.element, this.image2);
$(this.element).on('CornerstoneActiveLayerChanged', (event, eventData) => {
// Assert
expect(eventData.layerId).to.equal(layerId2);
done();
});
updateImage(this.element);
// Act
setActiveLayer(this.element, layerId2);
const activeLayer = getActiveLayer(this.element);
// Assert
expect(activeLayer).to.be.an('object');
expect(activeLayer.layerId).to.equal(layerId2);
});
it('should fail silently if the layer is already enabled', function () {
// Arrange
addLayer(this.element, this.image1);
const layerId2 = addLayer(this.element, this.image2);
updateImage(this.element);
// Act
setActiveLayer(this.element, layerId2);
setActiveLayer(this.element, layerId2);
// TODO: See how we can assert that this is working
});
it('should throw an error if the layer does not exist', function () {
// Arrange
addLayer(this.element, this.image1);
addLayer(this.element, this.image2);
updateImage(this.element);
// Assert
assert.throws(() => {
// Act
setActiveLayer(this.element, 'invalidLayerId');
});
});
afterEach(function () {
disable(this.element);
});
});
|
const date = new Date();
const months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
const beginYear = 2019;
const endYear = 2044;
const renderCalendar = () => {
date.setDate(1);
const monthDays = document.querySelector('.days');
const lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
const prevLastDay = new Date(date.getFullYear(), date.getMonth(), 0).getDate();
const firstDayIndex = date.getDay();
const lastDayIndex = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDay();
const nextDays = 7 - lastDayIndex - 1;
document.querySelector('.date h1').innerHTML = months[date.getMonth()] + ' ' + date.getFullYear();
document.querySelector('#currentDate').innerHTML = '<button class="todayBtn" onclick=location.reload()>Today</button> is: ' + new Date().toLocaleDateString({ month: 'long' });
let days = '';
for (let x = firstDayIndex; x > 0; x--) {
days += `<div class="prev-date">${prevLastDay - x + 1}</div>`;
}
for (let i = 1; i <= lastDay; i++) {
if (
i === new Date().getDate() &&
date.getMonth() === new Date().getMonth() &&
date.getFullYear() === new Date().getFullYear()
) {
days += `<div class="today">${i}</div>`;
} else {
days += `<div>${i}</div>`;
}
}
for (let j = 1; j <= nextDays; j++) {
days += `<div class="next-date">${j}</div>`;
monthDays.innerHTML = days;
}
if (lastDay + nextDays < 36) {
const expanded = document.querySelectorAll(".days div");
for (let e = 0; e < expanded.length; e++) {
expanded[e].classList.add('expanded');
}
}
};
const selectMonthEl = document.querySelector('#monthList');
let monthOptions = '';
for (let m = 0; m < months.length; m++) {
let currentMonth = '';
if (m === date.getMonth()) {
currentMonth = 'selected';
}
monthOptions += '<option value=' + m + ' ' + currentMonth + ' >' + months[m] + '</option>';
}
selectMonthEl.innerHTML = monthOptions;
const selectYearEl = document.querySelector('#yearList');
let yearOptions = '';
for (let y = beginYear; y <= endYear; y++) {
let currentYear = '';
if (y === date.getFullYear()) {
currentYear = 'selected'
}
yearOptions += '<option value="' + y + '" ' + currentYear + ' >' + y + '</option>';
}
selectYearEl.innerHTML = yearOptions;
document.querySelector('.prev').addEventListener('click', () => {
date.setMonth(date.getMonth() - 1);
renderCalendar();
for (i = 0; i < months.length; i++) {
selectMonthEl.children[i].removeAttribute('selected');
}
newMonth = date.getMonth();
selectMonthEl.children[newMonth].setAttribute('selected', 'selected');
const totalYears = endYear - beginYear;
for (j = 0; j < totalYears; j++) {
selectYearEl.children[j].removeAttribute('selected');
}
newYear = date.getFullYear() - beginYear;
selectYearEl.children[newYear].setAttribute('selected', 'selected');
console.log(newYear);
});
document.querySelector('.next').addEventListener('click', () => {
date.setMonth(date.getMonth() + 1);
renderCalendar();
for (i = 0; i < months.length; i++) {
selectMonthEl.children[i].removeAttribute('selected');
}
newMonth = date.getMonth();
selectMonthEl.children[newMonth].setAttribute('selected', 'selected');
const totalYears = endYear - beginYear;
for (j = 0; j < totalYears; j++) {
selectYearEl.children[j].removeAttribute('selected');
}
newYear = date.getFullYear() - beginYear;
selectYearEl.children[newYear].setAttribute('selected', 'selected');
});
function getSelectedMonth() {
const select = document.querySelector('#monthList');
const selectedMonth = select.options[select.selectedIndex].value;
date.setMonth(selectedMonth);
renderCalendar();
}
function getSelectedYear() {
const select = document.querySelector('#yearList');
const selectedYear = select.options[select.selectedIndex].textContent;
date.setFullYear(selectedYear);
renderCalendar();
}
renderCalendar();
|
$('#addQuestionButton').on('click', function() {
let selectedValue = $('select[name=selector]').val();
let index = $(this).attr('index');
jsRoutes.controllers.Questionnaires.appendQuestion(index, selectedValue).ajax({
success: function(data) {
$('#questionsContent').append(data);
$('#addQuestionButton').attr('index', parseInt(index) + 1);
fixQuestionIndexes();
enableDisableSubmitButton();
},
error: function() {}
});
});
function addNewChoiceInput(id, counter, index) {
$('#' + id).append(
"<div id=\"choice-" + index + "-" + (parseInt(counter) + 1) + "\">" +
"<label>Choice <span class=\"choice-label-" + index + "\">" + (parseInt(counter) + 1) + "</span></label>" +
"<div class=\"input-group\">" +
"<input type=\"text\" class=\"form-control picker has-error\" name=\"questions[" + index +"].offeredAnswers[" + counter +"].answer\">" +
"<span class=\"input-group-btn\">" +
"<a class=\"btn btn-danger\" onclick=\"removeChoice('choice-" + index + "-" + (parseInt(counter) + 1) + "')\">X</a>" +
"</span>" +
"</div>" +
"</div>"
);
$('#' + id + '-button').empty();
$('#' + id + '-button').append(
"<a class=\"btn btn-success btn-sm\" onclick=\"addNewChoiceInput('" + id + "', " + (parseInt(counter) + 1) + ", " + index + ")\">" +
"Add new choice <span class=\"glyphicon glyphicon-plus\"></span></a>"
);
enableDisableSubmitButton();
}
$('body').on('keyup', '.picker', function() {
enableDisableSubmitButton();
});
function enableDisableSubmitButton() {
const $inputPickers = $('input.picker').filter(function() {return $(this).val() == "";});
const $textareaPickers = $('textarea.picker').filter(function() {return $(this).val() == "";});
$('input.picker').each(function() {
if ($(this).val() != "") {
$(this).parent().parent().removeClass('has-error');
$(this).parent().removeClass('has-error');
$(this).removeClass('has-error');
} else {
$(this).parent().parent().addClass('has-error');
$(this).parent().addClass('has-error');
$(this).addClass('has-error');
}
});
$('textarea.picker').each(function() {
if ($(this).val() != "") {
$(this).parent().removeClass('has-error');
$(this).removeClass('has-error');
} else {
$(this).parent().addClass('has-error');
$(this).addClass('has-error');
}
});
$("#submitQuestionnaireButton").prop("disabled", $inputPickers.length > 0 || $textareaPickers.length > 0);
}
$('body').on('keyup', '.selector', function() {
enableDisableSaveButton();
});
$('.selector-parent').on('change', function() {
enableDisableSaveButton();
}).change();
function enableDisableSaveButton() {
const $textareaSelectors = $('textarea.selector').filter(function() {return $(this).val() == "";});
let $checkerSelectors = 0;
$('textarea.selector').each(function() {
if ($(this).val() != "") {
$(this).parent().removeClass('has-error');
$(this).removeClass('has-error');
} else {
$(this).parent().addClass('has-error');
$(this).addClass('has-error');
}
});
$('.selector-parent').each(function(i, element) {
let isChecked = false;
$(element).children().each(function(i, child) {
if ($(":first-child", child).is(':checked')) {
isChecked = true;
}
});
if (!isChecked) {
$checkerSelectors += 1;
$(element).parent().addClass('has-error');
} else {
$(element).parent().removeClass('has-error');
}
});
$("#saveQuestionnaireButton").prop("disabled", $textareaSelectors.length > 0 || $checkerSelectors > 0);
}
function removeQuestion(id) {
if (confirm('Are you sure?')) {
$('#' + id).remove();
fixQuestionIndexes();
}
}
function removeChoice(id) {
if (confirm('Are you sure?')) {
$('#' + id).remove();
fixChoiceIndexLabels('.choice-label-' + id.split('-')[1]);
}
}
function fixQuestionIndexes() {
$('.question-index-label').each(function(i, element) {
$(element).text(i + 1);
});
}
function fixChoiceIndexLabels(className) {
$(className).each(function(i, element) {
$(element).text(i + 1);
});
}
|
import n2
import numpy as np
from pathlib import Path
import tqdm
class KNNClassifier(object):
def __init__(self, fingerprint_kind, dimension, verbose):
self.fingerprint_kind = fingerprint_kind
self.dimension = dimension
self.verbose=verbose
def build_ann_index(self, fingerprints, nthreads=1, overWrite=False):
"""WARNING: set threads correctly! I set it to 1 so you don't run out of memory.
This builds an approximate nearest neighbors index, used to build a kNN graph.
n2 is a good choice because it is fast and also allows streaming upload. Further,
it outperforms many other libraries according to ann_benchmarks. n2 is awesome.
It does not, however, offer dice, jaccard, or tanimoto. In practice cosine works fine."""
index_file = Path("../processed_data/"+self.fingerprint_kind+'_n2_index.hnsw')
if index_file.is_file() and not overWrite:
raise Exception('Index file exists already. Set `overWrite` to true to re-write it')
else:
pass
if not isinstance(fingerprints, np.ndarray):
if self.verbose:
print('converting to numpy')
fingerprints = fingerprints.toarray()
if self.verbose:
print('adding vector data to n2')
index = n2.HnswIndex(self.dimension, "angular")
for fp in tqdm.tqdm(fingerprints,smoothing=0):
index.add_data(fp)
if self.verbose:
print(f'building index with {nthreads}')
index.build(n_threads=nthreads)
index.save('../processed_data/'+self.fingerprint_kind+'_n2_index.hnsw')
|
module.exports = {
computate_engine: {
dialect: 'sqlite',
storage: 'storage/database/compute_engine.db'
},
utility: {
dialect: 'sqlite',
storage: 'storage/database/utility.db'
}
}; |
const router = require('express').Router();
const User = require('../models/User');
const CryptoJS = require('crypto-js');
const jwt = require('jsonwebtoken');
// Register
router.post('/register', async (req, res) => {
const { username, email, password } = req.body;
const newUser = new User({
username: username,
email: email,
password: CryptoJS.AES.encrypt(
password,
process.env.SECRET_KEY
).toString(),
});
try {
const user = await newUser.save();
res.json(user);
} catch (err) {
res.status(500).json(err);
}
});
// Login
router.post('/login', async (req, res) => {
const { email } = req.body;
try {
const user = await User.findOne({ email: email });
!user && res.status(401).json('Wrong password or username!');
const bytes = CryptoJS.AES.decrypt(
user.password,
process.env.SECRET_KEY
);
const originalPassword = bytes.toString(CryptoJS.enc.Utf8);
originalPassword !== req.body.password &&
res.status(401).json('Wrong password or username!');
const accessToken = jwt.sign(
{
id: user._id,
isAdmin: user.isAdmin,
},
process.env.SECRET_KEY,
{ expiresIn: '999999d' }
);
const { password, ...info } = user._doc;
res.status(200).json({ ...info, accessToken });
} catch (err) {
res.status(500).json(err);
}
});
module.exports = router;
|
var React = require("react");
//Children
var Saved = require("./children/Saved.js");
var Search = require("./children/Search.js");
var Results = require("./children/Results.js");
var helpers = require("./utils/helpers.js");
var Main = React.createClass({
getInitialState: function(){
return ({
search: "",
results: [],
saved: []
})
},
//Do this right after the page renders
componentDidMount: function(){
console.log("componentDidMount");
helpers.fetchHistory().then(function(response) {
console.log(response);
if (response !== this.state.saved) {
console.log("Saved", response.data);
this.setState({ saved: response.data });
}
}.bind(this));
},
//Do this after component changes - Search is made
componentDidUpdate: function(){
if (this.state.search !== ""){
console.log("componentDidUpdate");
helpers.runQuery(this.state.search).then(function(data){
if (data !== this.state.results) {
console.log("Result: " + data);
this.setState({ results: data });
// After we've received the result... then post the search term to our history.
helpers.saveSearch(this.state.search).then(function() {
console.log("search saved!");
// After we've done the post... then get the updated history
helpers.fetchHistory().then(function(response) {
console.log("Current Saved History", response);
this.setState({ saved: response });
}.bind(this));
}.bind(this));
}
}.bind(this))
}
},
//Take search from the Child Search
setTerm: function(term) {
return this.setState({ search: term });
},
saveBtnUpdate: function(){
helpers.fetchHistory().then(function(response) {
console.log("Current Saved History", response.data);
this.setState({ saved: response.data });
}.bind(this));
},
// clearResults: function(){
// return this.setState({results: []});
// },
render: function(){
return(
<div>
<div className="container">
<div className="row">
<div className="jumbotron">
<h2 className="text-center">New York Times React App</h2>
</div>
</div>
</div>
<div>
<Search setTerm={this.setTerm} searchResults={this.state.results}/>
<Results searchResults={this.state.results} saveBtnUpdate={this.saveBtnUpdate} />
<Saved savedArticles={this.state.saved} />
</div>
</div>
);
}
});
module.exports = Main;
|
# Generated by Django 3.1.4 on 2020-12-22 02:41
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import logs.models
class Migration(migrations.Migration):
dependencies = [
('network', '0007_auto_20201029_0200'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('logs', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='log',
name='created_on',
field=models.DateTimeField(default=django.utils.timezone.now),
),
migrations.AlterField(
model_name='log',
name='duration',
field=models.DurationField(default=0, help_text='How long you volunteered for (in the form HH:MM)', validators=[logs.models.duration_validator]),
),
migrations.AlterField(
model_name='log',
name='nonprofit',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='log', to='network.nonprofit'),
),
migrations.AlterField(
model_name='log',
name='user',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='log', to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='log',
name='verified',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='verified_log', to=settings.AUTH_USER_MODEL),
),
]
|
class TimeLimitExceeded(Exception):
pass
class NotEnoughMemoryError(Exception):
pass
class NoGPUError(Exception):
pass
class NoValidFeatures(Exception):
pass
|
export default {
elem: 'svg',
attrs: {
xmlns: 'http://www.w3.org/2000/svg',
viewBox: '0 0 32 32',
width: 20,
height: 20,
},
content: [
{
elem: 'path',
attrs: {
d:
'M12 21H4V4h18v8h2V4a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v17a2 2 0 0 0 2 2h8z',
},
},
{
elem: 'path',
attrs: {
d:
'M30 28.58l-3.11-3.11a6 6 0 1 0-1.42 1.42L28.58 30zM22 26a4 4 0 1 1 4-4 4 4 0 0 1-4 4z',
},
},
],
name: 'magnify',
size: 20,
};
|
import chalk from 'chalk';
import knex from 'knex';
import rmfr from 'rmfr';
import path from 'path';
import fs from 'fs';
import { identity, indexBy, isEmpty, map } from 'ramda';
import { extractSchema } from 'extract-pg-schema';
import defaultTypeMap from './defaultTypeMap';
import { logger } from './logger';
import processSchema from './processSchema';
import { nameIdentity } from './Config';
const labelAsGenerated = (lines) => [
"// Automatically generated. Don't change this file manually.",
'',
...lines,
];
const addEmptyLineAtEnd = (lines) => [...lines, ''];
const defaultHooks = [labelAsGenerated, addEmptyLineAtEnd];
/**
* @param {import('./Config').default} config
*/
const processDatabase = async ({
connection,
preDeleteModelFolder = false,
customTypeMap = {},
modelHooks = [],
modelNominator = nameIdentity,
propertyNominator = (propertyName) =>
propertyName.indexOf(' ') !== -1 ? `'${propertyName}'` : propertyName,
initializerNominator = (modelName) => `${modelName}Initializer`,
idNominator = (modelName) => `${modelName}Id`,
typeHooks = [],
typeNominator = nameIdentity,
fileNominator = identity,
schemas,
...unknownProps
}) => {
if (!isEmpty(unknownProps)) {
console.warn(
`Unknown configuration properties: ${Object.keys(unknownProps).join(
', '
)}`
);
}
const typeMap = { ...defaultTypeMap, ...customTypeMap };
/** @type {import('./Config').Nominators} */
const nominators = {
modelNominator,
propertyNominator,
initializerNominator,
idNominator,
typeNominator,
fileNominator,
};
const modelProcessChain = [...defaultHooks, ...modelHooks];
const typeProcessChain = [...defaultHooks, ...typeHooks];
logger.log(
`Connecting to ${chalk.greenBright(connection.database)} on ${
connection.host
}`
);
const knexConfig = {
client: 'pg',
connection,
};
const schemaFolderMap = map(
(s) => path.resolve(s.modelFolder),
indexBy((s) => s.name, schemas)
);
for (const schemaConfig of schemas) {
if (preDeleteModelFolder) {
logger.log(` - Clearing old files in ${schemaConfig.modelFolder}`);
await rmfr(schemaConfig.modelFolder, { glob: true });
}
if (!fs.existsSync(schemaConfig.modelFolder)) {
fs.mkdirSync(schemaConfig.modelFolder);
}
const db = knex(knexConfig);
const schema = await extractSchema(schemaConfig.name, db);
await processSchema(
schemaConfig,
schema,
typeMap,
nominators,
modelProcessChain,
typeProcessChain,
schemaFolderMap
);
}
};
export default processDatabase;
|
var assert = require("assert");
var mockery = require("mockery");
describe("cmd build module", function() {
var cmdBuild;
var buildArgs;
var cmdBuildPath = "../../lib/cli/cmd_build";
beforeEach(function() {
buildArgs = {};
mockery.enable({
useCleanCache: true,
warnOnReplace: false,
warnOnUnregistered: false
});
mockery.registerAllowable(cmdBuildPath);
mockery.registerMock("../../index", {
build: function(system, options) {
buildArgs.system = system;
buildArgs.options = options;
return { then: function() {} };
}
});
cmdBuild = require(cmdBuildPath);
});
afterEach(function() {
mockery.disable();
mockery.deregisterAll();
});
it("exposes the right command", function() {
assert.deepEqual(cmdBuild.command, ["build", "*"]);
});
it("defaults config option to package.json!npm", function() {
assert.equal(cmdBuild.builder.config.default, "package.json!npm");
});
it("handler calls steal.build", function() {
cmdBuild.handler({
minify: true,
config: "/stealconfig.js"
});
assert.deepEqual(buildArgs.system, {
config: "/stealconfig.js"
});
assert(buildArgs.options.minify);
});
it("bundles-path works", function(){
cmdBuild.handler({
config: "/stealconfig.js",
bundlesPath: "foo"
});
assert.deepEqual(buildArgs.system, {
config: "/stealconfig.js",
bundlesPath: "foo"
});
});
it("watch mode defaults minify to false", function() {
cmdBuild.handler({ config: "/stealconfig.js", watch: true });
assert.equal(buildArgs.options.minify, false);
});
it("watch mode should still minify if flag provided", function() {
cmdBuild.handler({
config: "/stealconfig.js",
watch: true,
minify: true
});
assert.equal(buildArgs.options.minify, true);
});
it("--no-tree-shaking flag", function() {
cmdBuild.handler({ config: "/stealconfig.js", noTreeShaking: true });
assert.equal(buildArgs.options.treeShaking, false);
});
});
|
var path = require("path");
var htmlWebpackPlugin = require("html-webpack-plugin")
var VueLoaserPlugin = require("vue-loader/lib/plugin")
module.exports = {
entry: path.join(__dirname, "./src/main.js"),
output: {
path:path.join(__dirname, "./dist"),
filename: "bundle.js"
},
plugins:[
new htmlWebpackPlugin({
template: path.join(__dirname, "./src/index.html"),
filename: "index.html"
}),
new VueLoaserPlugin()
],
module:{
rules:[
{test:/\.css$/, use:["style-loader", "css-loader"]},
{test:/\.less$/, use:["style-loader", "css-loader", "less-loader"]},
{test:/\.scss$/, use:["style-loader", "css-loader", "sass-loader"]},
// 处理图片的loader
{test:/\.(jpg|png|gif|bmp|jpeg)$/, use:"url-loader?limit=20433&name=[hash:8]-[name].[ext]"},
// limit 给定的值,是图片的大小,单位是byte,如果我们引用的图片大于或者等于给定的limit值,
// 则不会被转为base64格式的字符串,如果图片小于给定的limit值,则会被转为base64的字符串
// 处理字体文件的loader
{test:/\.(ttf|eot|svg|woff|woff2|otf)$/, use: 'url-loader'},
// 配置Babel来转换高级的ES语法
{test: /\.js$/, use: "babel-loader", exclude: /node_modules/},
// 处理.vue文件的loader
{test: /\.vue$/, use: "vue-loader"},
]
},
resolve:{
alias:{ // 修改Vue被导入时候的包的路径
// "vue$": "vue/dist/vue.js"
}
}
}; |
import { createStore, applyMiddleware } from 'redux'
import sagaMiddleware from '../../src'
import * as io from '../../src/effects'
test('should not interpret returned effect. fork(() => effectCreator())', () => {
const middleware = sagaMiddleware()
createStore(() => ({}), {}, applyMiddleware(middleware))
const fn = () => null
function* genFn() {
const task = yield io.fork(() => io.call(fn))
return task.toPromise()
}
return middleware
.run(genFn)
.toPromise()
.then(actual => {
expect(actual).toEqual(io.call(fn))
})
})
test("should not interpret returned effect. yield fork(takeEvery, 'pattern', fn)", () => {
const middleware = sagaMiddleware()
createStore(() => ({}), {}, applyMiddleware(middleware))
const fn = () => null
function* genFn() {
const task = yield io.fork(io.takeEvery, 'pattern', fn)
return task.toPromise()
}
return middleware
.run(genFn)
.toPromise()
.then(actual => {
expect(actual).toEqual(io.takeEvery('pattern', fn))
})
})
test('should interpret returned promise. fork(() => promise)', () => {
const middleware = sagaMiddleware()
createStore(() => ({}), {}, applyMiddleware(middleware))
function* genFn() {
const task = yield io.fork(() => Promise.resolve('a'))
return task.toPromise()
}
return middleware
.run(genFn)
.toPromise()
.then(actual => {
expect(actual).toEqual('a')
})
})
test('should handle promise that resolves undefined properly. fork(() => Promise.resolve(undefined))', () => {
const middleware = sagaMiddleware()
createStore(() => ({}), {}, applyMiddleware(middleware))
function* genFn() {
const task = yield io.fork(() => Promise.resolve(undefined))
return task.toPromise()
}
return middleware
.run(genFn)
.toPromise()
.then(actual => {
expect(actual).toEqual(undefined)
})
})
test('should interpret returned iterator. fork(() => iterator)', () => {
const middleware = sagaMiddleware()
createStore(() => ({}), {}, applyMiddleware(middleware))
function* genFn() {
const task = yield io.fork(function*() {
yield 1
return 'b'
})
return task.toPromise()
}
return middleware
.run(genFn)
.toPromise()
.then(actual => {
expect(actual).toEqual('b')
})
})
|
from .core import Model |
/**
* @author Richard Davey <[email protected]>
* @copyright 2019 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
var BlendModes = require('../../renderer/BlendModes');
var Class = require('../../utils/Class');
var Components = require('../components');
var DeathZone = require('./zones/DeathZone');
var EdgeZone = require('./zones/EdgeZone');
var EmitterOp = require('./EmitterOp');
var GetFastValue = require('../../utils/object/GetFastValue');
var GetRandom = require('../../utils/array/GetRandom');
var HasAny = require('../../utils/object/HasAny');
var HasValue = require('../../utils/object/HasValue');
var Particle = require('./Particle');
var RandomZone = require('./zones/RandomZone');
var Rectangle = require('../../geom/rectangle/Rectangle');
var StableSort = require('../../utils/array/StableSort');
var Vector2 = require('../../math/Vector2');
var Wrap = require('../../math/Wrap');
/**
* @classdesc
* A particle emitter represents a single particle stream.
* It controls a pool of {@link Phaser.GameObjects.Particles.Particle Particles} and is controlled by a {@link Phaser.GameObjects.Particles.ParticleEmitterManager Particle Emitter Manager}.
*
* @class ParticleEmitter
* @memberof Phaser.GameObjects.Particles
* @constructor
* @since 3.0.0
*
* @extends Phaser.GameObjects.Components.BlendMode
* @extends Phaser.GameObjects.Components.Mask
* @extends Phaser.GameObjects.Components.ScrollFactor
* @extends Phaser.GameObjects.Components.Visible
*
* @param {Phaser.GameObjects.Particles.ParticleEmitterManager} manager - The Emitter Manager this Emitter belongs to.
* @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} config - Settings for this emitter.
*/
var ParticleEmitter = new Class({
Mixins: [
Components.BlendMode,
Components.Mask,
Components.ScrollFactor,
Components.Visible
],
initialize:
function ParticleEmitter (manager, config)
{
/**
* The Emitter Manager this Emitter belongs to.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#manager
* @type {Phaser.GameObjects.Particles.ParticleEmitterManager}
* @since 3.0.0
*/
this.manager = manager;
/**
* The texture assigned to particles.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#texture
* @type {Phaser.Textures.Texture}
* @since 3.0.0
*/
this.texture = manager.texture;
/**
* The texture frames assigned to particles.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#frames
* @type {Phaser.Textures.Frame[]}
* @since 3.0.0
*/
this.frames = [ manager.defaultFrame ];
/**
* The default texture frame assigned to particles.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#defaultFrame
* @type {Phaser.Textures.Frame}
* @since 3.0.0
*/
this.defaultFrame = manager.defaultFrame;
/**
* Names of simple configuration properties.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#configFastMap
* @type {object}
* @since 3.0.0
*/
this.configFastMap = [
'active',
'blendMode',
'collideBottom',
'collideLeft',
'collideRight',
'collideTop',
'deathCallback',
'deathCallbackScope',
'emitCallback',
'emitCallbackScope',
'follow',
'frequency',
'gravityX',
'gravityY',
'maxParticles',
'name',
'on',
'particleBringToTop',
'particleClass',
'radial',
'timeScale',
'trackVisible',
'visible'
];
/**
* Names of complex configuration properties.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#configOpMap
* @type {object}
* @since 3.0.0
*/
this.configOpMap = [
'accelerationX',
'accelerationY',
'angle',
'alpha',
'bounce',
'delay',
'lifespan',
'maxVelocityX',
'maxVelocityY',
'moveToX',
'moveToY',
'quantity',
'rotate',
'scaleX',
'scaleY',
'speedX',
'speedY',
'tint',
'x',
'y'
];
/**
* The name of this Particle Emitter.
*
* Empty by default and never populated by Phaser, this is left for developers to use.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#name
* @type {string}
* @default ''
* @since 3.0.0
*/
this.name = '';
/**
* The Particle Class which will be emitted by this Emitter.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#particleClass
* @type {Phaser.GameObjects.Particles.Particle}
* @default Phaser.GameObjects.Particles.Particle
* @since 3.0.0
*/
this.particleClass = Particle;
/**
* The x-coordinate of the particle origin (where particles will be emitted).
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#x
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 0
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setPosition
*/
this.x = new EmitterOp(config, 'x', 0, true);
/**
* The y-coordinate of the particle origin (where particles will be emitted).
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#y
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 0
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setPosition
*/
this.y = new EmitterOp(config, 'y', 0, true);
/**
* A radial emitter will emit particles in all directions between angle min and max,
* using {@link Phaser.GameObjects.Particles.ParticleEmitter#speed} as the value. If set to false then this acts as a point Emitter.
* A point emitter will emit particles only in the direction derived from the speedX and speedY values.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#radial
* @type {boolean}
* @default true
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setRadial
*/
this.radial = true;
/**
* Horizontal acceleration applied to emitted particles, in pixels per second squared.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#gravityX
* @type {number}
* @default 0
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setGravity
*/
this.gravityX = 0;
/**
* Vertical acceleration applied to emitted particles, in pixels per second squared.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#gravityY
* @type {number}
* @default 0
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setGravity
*/
this.gravityY = 0;
/**
* Whether accelerationX and accelerationY are non-zero. Set automatically during configuration.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#acceleration
* @type {boolean}
* @default false
* @since 3.0.0
*/
this.acceleration = false;
/**
* Horizontal acceleration applied to emitted particles, in pixels per second squared.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#accelerationX
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 0
* @since 3.0.0
*/
this.accelerationX = new EmitterOp(config, 'accelerationX', 0, true);
/**
* Vertical acceleration applied to emitted particles, in pixels per second squared.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#accelerationY
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 0
* @since 3.0.0
*/
this.accelerationY = new EmitterOp(config, 'accelerationY', 0, true);
/**
* The maximum horizontal velocity of emitted particles, in pixels per second squared.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#maxVelocityX
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 10000
* @since 3.0.0
*/
this.maxVelocityX = new EmitterOp(config, 'maxVelocityX', 10000, true);
/**
* The maximum vertical velocity of emitted particles, in pixels per second squared.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#maxVelocityY
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 10000
* @since 3.0.0
*/
this.maxVelocityY = new EmitterOp(config, 'maxVelocityY', 10000, true);
/**
* The initial horizontal speed of emitted particles, in pixels per second.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#speedX
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 0
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setSpeedX
*/
this.speedX = new EmitterOp(config, 'speedX', 0, true);
/**
* The initial vertical speed of emitted particles, in pixels per second.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#speedY
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 0
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setSpeedY
*/
this.speedY = new EmitterOp(config, 'speedY', 0, true);
/**
* Whether moveToX and moveToY are nonzero. Set automatically during configuration.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#moveTo
* @type {boolean}
* @default false
* @since 3.0.0
*/
this.moveTo = false;
/**
* The x-coordinate emitted particles move toward, when {@link Phaser.GameObjects.Particles.ParticleEmitter#moveTo} is true.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#moveToX
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 0
* @since 3.0.0
*/
this.moveToX = new EmitterOp(config, 'moveToX', 0, true);
/**
* The y-coordinate emitted particles move toward, when {@link Phaser.GameObjects.Particles.ParticleEmitter#moveTo} is true.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#moveToY
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 0
* @since 3.0.0
*/
this.moveToY = new EmitterOp(config, 'moveToY', 0, true);
/**
* Whether particles will rebound when they meet the emitter bounds.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#bounce
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 0
* @since 3.0.0
*/
this.bounce = new EmitterOp(config, 'bounce', 0, true);
/**
* The horizontal scale of emitted particles.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#scaleX
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 1
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setScale
* @see Phaser.GameObjects.Particles.ParticleEmitter#setScaleX
*/
this.scaleX = new EmitterOp(config, 'scaleX', 1);
/**
* The vertical scale of emitted particles.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#scaleY
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 1
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setScale
* @see Phaser.GameObjects.Particles.ParticleEmitter#setScaleY
*/
this.scaleY = new EmitterOp(config, 'scaleY', 1);
/**
* Color tint applied to emitted particles. Any alpha component (0xAA000000) is ignored.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#tint
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 0xffffffff
* @since 3.0.0
*/
this.tint = new EmitterOp(config, 'tint', 0xffffffff);
/**
* The alpha (transparency) of emitted particles.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#alpha
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 1
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setAlpha
*/
this.alpha = new EmitterOp(config, 'alpha', 1);
/**
* The lifespan of emitted particles, in ms.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#lifespan
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 1000
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setLifespan
*/
this.lifespan = new EmitterOp(config, 'lifespan', 1000, true);
/**
* The angle of the initial velocity of emitted particles, in degrees.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#angle
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default { min: 0, max: 360 }
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setAngle
*/
this.angle = new EmitterOp(config, 'angle', { min: 0, max: 360 }, true);
/**
* The rotation of emitted particles, in degrees.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#rotate
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 0
* @since 3.0.0
*/
this.rotate = new EmitterOp(config, 'rotate', 0);
/**
* A function to call when a particle is emitted.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#emitCallback
* @type {?Phaser.Types.GameObjects.Particles.ParticleEmitterCallback}
* @default null
* @since 3.0.0
*/
this.emitCallback = null;
/**
* The calling context for {@link Phaser.GameObjects.Particles.ParticleEmitter#emitCallback}.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#emitCallbackScope
* @type {?*}
* @default null
* @since 3.0.0
*/
this.emitCallbackScope = null;
/**
* A function to call when a particle dies.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#deathCallback
* @type {?Phaser.Types.GameObjects.Particles.ParticleDeathCallback}
* @default null
* @since 3.0.0
*/
this.deathCallback = null;
/**
* The calling context for {@link Phaser.GameObjects.Particles.ParticleEmitter#deathCallback}.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#deathCallbackScope
* @type {?*}
* @default null
* @since 3.0.0
*/
this.deathCallbackScope = null;
/**
* Set to hard limit the amount of particle objects this emitter is allowed to create.
* 0 means unlimited.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#maxParticles
* @type {integer}
* @default 0
* @since 3.0.0
*/
this.maxParticles = 0;
/**
* How many particles are emitted each time particles are emitted (one explosion or one flow cycle).
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#quantity
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 1
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setFrequency
* @see Phaser.GameObjects.Particles.ParticleEmitter#setQuantity
*/
this.quantity = new EmitterOp(config, 'quantity', 1, true);
/**
* How many ms to wait after emission before the particles start updating.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#delay
* @type {Phaser.GameObjects.Particles.EmitterOp}
* @default 0
* @since 3.0.0
*/
this.delay = new EmitterOp(config, 'delay', 0, true);
/**
* For a flow emitter, the time interval (>= 0) between particle flow cycles in ms.
* A value of 0 means there is one particle flow cycle for each logic update (the maximum flow frequency). This is the default setting.
* For an exploding emitter, this value will be -1.
* Calling {@link Phaser.GameObjects.Particles.ParticleEmitter#flow} also puts the emitter in flow mode (frequency >= 0).
* Calling {@link Phaser.GameObjects.Particles.ParticleEmitter#explode} also puts the emitter in explode mode (frequency = -1).
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#frequency
* @type {number}
* @default 0
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setFrequency
*/
this.frequency = 0;
/**
* Controls if the emitter is currently emitting a particle flow (when frequency >= 0).
* Already alive particles will continue to update until they expire.
* Controlled by {@link Phaser.GameObjects.Particles.ParticleEmitter#start} and {@link Phaser.GameObjects.Particles.ParticleEmitter#stop}.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#on
* @type {boolean}
* @default true
* @since 3.0.0
*/
this.on = true;
/**
* Newly emitted particles are added to the top of the particle list, i.e. rendered above those already alive.
* Set to false to send them to the back.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#particleBringToTop
* @type {boolean}
* @default true
* @since 3.0.0
*/
this.particleBringToTop = true;
/**
* The time rate applied to active particles, affecting lifespan, movement, and tweens. Values larger than 1 are faster than normal.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#timeScale
* @type {number}
* @default 1
* @since 3.0.0
*/
this.timeScale = 1;
/**
* An object describing a shape to emit particles from.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#emitZone
* @type {?Phaser.GameObjects.Particles.Zones.EdgeZone|Phaser.GameObjects.Particles.Zones.RandomZone}
* @default null
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setEmitZone
*/
this.emitZone = null;
/**
* An object describing a shape that deactivates particles when they interact with it.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#deathZone
* @type {?Phaser.GameObjects.Particles.Zones.DeathZone}
* @default null
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setDeathZone
*/
this.deathZone = null;
/**
* A rectangular boundary constraining particle movement.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#bounds
* @type {?Phaser.Geom.Rectangle}
* @default null
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setBounds
*/
this.bounds = null;
/**
* Whether particles interact with the left edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#collideLeft
* @type {boolean}
* @default true
* @since 3.0.0
*/
this.collideLeft = true;
/**
* Whether particles interact with the right edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#collideRight
* @type {boolean}
* @default true
* @since 3.0.0
*/
this.collideRight = true;
/**
* Whether particles interact with the top edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#collideTop
* @type {boolean}
* @default true
* @since 3.0.0
*/
this.collideTop = true;
/**
* Whether particles interact with the bottom edge of the emitter {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds}.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#collideBottom
* @type {boolean}
* @default true
* @since 3.0.0
*/
this.collideBottom = true;
/**
* Whether this emitter updates itself and its particles.
*
* Controlled by {@link Phaser.GameObjects.Particles.ParticleEmitter#pause}
* and {@link Phaser.GameObjects.Particles.ParticleEmitter#resume}.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#active
* @type {boolean}
* @default true
* @since 3.0.0
*/
this.active = true;
/**
* Set this to false to hide any active particles.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#visible
* @type {boolean}
* @default true
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setVisible
*/
this.visible = true;
/**
* The blend mode of this emitter's particles.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#blendMode
* @type {integer}
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setBlendMode
*/
this.blendMode = BlendModes.NORMAL;
/**
* A Game Object whose position is used as the particle origin.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#follow
* @type {?Phaser.GameObjects.GameObject}
* @default null
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#startFollow
* @see Phaser.GameObjects.Particles.ParticleEmitter#stopFollow
*/
this.follow = null;
/**
* The offset of the particle origin from the {@link Phaser.GameObjects.Particles.ParticleEmitter#follow} target.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#followOffset
* @type {Phaser.Math.Vector2}
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#startFollow
*/
this.followOffset = new Vector2();
/**
* Whether the emitter's {@link Phaser.GameObjects.Particles.ParticleEmitter#visible} state will track
* the {@link Phaser.GameObjects.Particles.ParticleEmitter#follow} target's visibility state.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#trackVisible
* @type {boolean}
* @default false
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#startFollow
*/
this.trackVisible = false;
/**
* The current texture frame, as an index of {@link Phaser.GameObjects.Particles.ParticleEmitter#frames}.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#currentFrame
* @type {integer}
* @default 0
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setFrame
*/
this.currentFrame = 0;
/**
* Whether texture {@link Phaser.GameObjects.Particles.ParticleEmitter#frames} are selected at random.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#randomFrame
* @type {boolean}
* @default true
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setFrame
*/
this.randomFrame = true;
/**
* The number of consecutive particles that receive a single texture frame (per frame cycle).
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#frameQuantity
* @type {integer}
* @default 1
* @since 3.0.0
* @see Phaser.GameObjects.Particles.ParticleEmitter#setFrame
*/
this.frameQuantity = 1;
/**
* Inactive particles.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#dead
* @type {Phaser.GameObjects.Particles.Particle[]}
* @private
* @since 3.0.0
*/
this.dead = [];
/**
* Active particles
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#alive
* @type {Phaser.GameObjects.Particles.Particle[]}
* @private
* @since 3.0.0
*/
this.alive = [];
/**
* The time until the next flow cycle.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#_counter
* @type {number}
* @private
* @default 0
* @since 3.0.0
*/
this._counter = 0;
/**
* Counts up to {@link Phaser.GameObjects.Particles.ParticleEmitter#frameQuantity}.
*
* @name Phaser.GameObjects.Particles.ParticleEmitter#_frameCounter
* @type {integer}
* @private
* @default 0
* @since 3.0.0
*/
this._frameCounter = 0;
if (config)
{
this.fromJSON(config);
}
},
/**
* Merges configuration settings into the emitter's current settings.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#fromJSON
* @since 3.0.0
*
* @param {Phaser.Types.GameObjects.Particles.ParticleEmitterConfig} config - Settings for this emitter.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
fromJSON: function (config)
{
if (!config)
{
return this;
}
// Only update properties from their current state if they exist in the given config
var i = 0;
var key = '';
for (i = 0; i < this.configFastMap.length; i++)
{
key = this.configFastMap[i];
if (HasValue(config, key))
{
this[key] = GetFastValue(config, key);
}
}
for (i = 0; i < this.configOpMap.length; i++)
{
key = this.configOpMap[i];
if (HasValue(config, key))
{
this[key].loadConfig(config);
}
}
this.acceleration = (this.accelerationX.propertyValue !== 0 || this.accelerationY.propertyValue !== 0);
this.moveTo = (this.moveToX.propertyValue !== 0 || this.moveToY.propertyValue !== 0);
// Special 'speed' override
if (HasValue(config, 'speed'))
{
this.speedX.loadConfig(config, 'speed');
this.speedY = null;
}
// If you specify speedX, speedY or moveTo then it changes the emitter from radial to a point emitter
if (HasAny(config, [ 'speedX', 'speedY' ]) || this.moveTo)
{
this.radial = false;
}
// Special 'scale' override
if (HasValue(config, 'scale'))
{
this.scaleX.loadConfig(config, 'scale');
this.scaleY = null;
}
if (HasValue(config, 'callbackScope'))
{
var callbackScope = GetFastValue(config, 'callbackScope', null);
this.emitCallbackScope = callbackScope;
this.deathCallbackScope = callbackScope;
}
if (HasValue(config, 'emitZone'))
{
this.setEmitZone(config.emitZone);
}
if (HasValue(config, 'deathZone'))
{
this.setDeathZone(config.deathZone);
}
if (HasValue(config, 'bounds'))
{
this.setBounds(config.bounds);
}
if (HasValue(config, 'followOffset'))
{
this.followOffset.setFromObject(GetFastValue(config, 'followOffset', 0));
}
if (HasValue(config, 'frame'))
{
this.setFrame(config.frame);
}
return this;
},
/**
* Creates a description of this emitter suitable for JSON serialization.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#toJSON
* @since 3.0.0
*
* @param {object} [output] - An object to copy output into.
*
* @return {object} - The output object.
*/
toJSON: function (output)
{
if (output === undefined) { output = {}; }
var i = 0;
var key = '';
for (i = 0; i < this.configFastMap.length; i++)
{
key = this.configFastMap[i];
output[key] = this[key];
}
for (i = 0; i < this.configOpMap.length; i++)
{
key = this.configOpMap[i];
if (this[key])
{
output[key] = this[key].toJSON();
}
}
// special handlers
if (!this.speedY)
{
delete output.speedX;
output.speed = this.speedX.toJSON();
}
if (!this.scaleY)
{
delete output.scaleX;
output.scale = this.scaleX.toJSON();
}
return output;
},
/**
* Continuously moves the particle origin to follow a Game Object's position.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#startFollow
* @since 3.0.0
*
* @param {Phaser.GameObjects.GameObject} target - The Game Object to follow.
* @param {number} [offsetX=0] - Horizontal offset of the particle origin from the Game Object.
* @param {number} [offsetY=0] - Vertical offset of the particle origin from the Game Object.
* @param {boolean} [trackVisible=false] - Whether the emitter's visible state will track the target's visible state.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
startFollow: function (target, offsetX, offsetY, trackVisible)
{
if (offsetX === undefined) { offsetX = 0; }
if (offsetY === undefined) { offsetY = 0; }
if (trackVisible === undefined) { trackVisible = false; }
this.follow = target;
this.followOffset.set(offsetX, offsetY);
this.trackVisible = trackVisible;
return this;
},
/**
* Stops following a Game Object.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#stopFollow
* @since 3.0.0
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
stopFollow: function ()
{
this.follow = null;
this.followOffset.set(0, 0);
this.trackVisible = false;
return this;
},
/**
* Chooses a texture frame from {@link Phaser.GameObjects.Particles.ParticleEmitter#frames}.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#getFrame
* @since 3.0.0
*
* @return {Phaser.Textures.Frame} The texture frame.
*/
getFrame: function ()
{
if (this.frames.length === 1)
{
return this.defaultFrame;
}
else if (this.randomFrame)
{
return GetRandom(this.frames);
}
else
{
var frame = this.frames[this.currentFrame];
this._frameCounter++;
if (this._frameCounter === this.frameQuantity)
{
this._frameCounter = 0;
this.currentFrame = Wrap(this.currentFrame + 1, 0, this._frameLength);
}
return frame;
}
},
// frame: 0
// frame: 'red'
// frame: [ 0, 1, 2, 3 ]
// frame: [ 'red', 'green', 'blue', 'pink', 'white' ]
// frame: { frames: [ 'red', 'green', 'blue', 'pink', 'white' ], [cycle: bool], [quantity: int] }
/**
* Sets a pattern for assigning texture frames to emitted particles.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setFrame
* @since 3.0.0
*
* @param {(array|string|integer|Phaser.Types.GameObjects.Particles.ParticleEmitterFrameConfig)} frames - One or more texture frames, or a configuration object.
* @param {boolean} [pickRandom=true] - Whether frames should be assigned at random from `frames`.
* @param {integer} [quantity=1] - The number of consecutive particles that will receive each frame.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setFrame: function (frames, pickRandom, quantity)
{
if (pickRandom === undefined) { pickRandom = true; }
if (quantity === undefined) { quantity = 1; }
this.randomFrame = pickRandom;
this.frameQuantity = quantity;
this.currentFrame = 0;
this._frameCounter = 0;
var t = typeof (frames);
if (Array.isArray(frames) || t === 'string' || t === 'number')
{
this.manager.setEmitterFrames(frames, this);
}
else if (t === 'object')
{
var frameConfig = frames;
frames = GetFastValue(frameConfig, 'frames', null);
if (frames)
{
this.manager.setEmitterFrames(frames, this);
}
var isCycle = GetFastValue(frameConfig, 'cycle', false);
this.randomFrame = (isCycle) ? false : true;
this.frameQuantity = GetFastValue(frameConfig, 'quantity', quantity);
}
this._frameLength = this.frames.length;
if (this._frameLength === 1)
{
this.frameQuantity = 1;
this.randomFrame = false;
}
return this;
},
/**
* Turns {@link Phaser.GameObjects.Particles.ParticleEmitter#radial} particle movement on or off.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setRadial
* @since 3.0.0
*
* @param {boolean} [value=true] - Radial mode (true) or point mode (true).
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setRadial: function (value)
{
if (value === undefined) { value = true; }
this.radial = value;
return this;
},
/**
* Sets the position of the emitter's particle origin.
* New particles will be emitted here.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setPosition
* @since 3.0.0
*
* @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} x - The x-coordinate of the particle origin.
* @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} y - The y-coordinate of the particle origin.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setPosition: function (x, y)
{
this.x.onChange(x);
this.y.onChange(y);
return this;
},
/**
* Sets or modifies a rectangular boundary constraining the particles.
*
* To remove the boundary, set {@link Phaser.GameObjects.Particles.ParticleEmitter#bounds} to null.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setBounds
* @since 3.0.0
*
* @param {(number|Phaser.Types.GameObjects.Particles.ParticleEmitterBounds|Phaser.Types.GameObjects.Particles.ParticleEmitterBoundsAlt)} x - The x-coordinate of the left edge of the boundary, or an object representing a rectangle.
* @param {number} y - The y-coordinate of the top edge of the boundary.
* @param {number} width - The width of the boundary.
* @param {number} height - The height of the boundary.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setBounds: function (x, y, width, height)
{
if (typeof x === 'object')
{
var obj = x;
x = obj.x;
y = obj.y;
width = (HasValue(obj, 'w')) ? obj.w : obj.width;
height = (HasValue(obj, 'h')) ? obj.h : obj.height;
}
if (this.bounds)
{
this.bounds.setTo(x, y, width, height);
}
else
{
this.bounds = new Rectangle(x, y, width, height);
}
return this;
},
/**
* Sets the initial horizontal speed of emitted particles.
* Changes the emitter to point mode.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setSpeedX
* @since 3.0.0
*
* @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The speed, in pixels per second.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setSpeedX: function (value)
{
this.speedX.onChange(value);
// If you specify speedX and Y then it changes the emitter from radial to a point emitter
this.radial = false;
return this;
},
/**
* Sets the initial vertical speed of emitted particles.
* Changes the emitter to point mode.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setSpeedY
* @since 3.0.0
*
* @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The speed, in pixels per second.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setSpeedY: function (value)
{
if (this.speedY)
{
this.speedY.onChange(value);
// If you specify speedX and Y then it changes the emitter from radial to a point emitter
this.radial = false;
}
return this;
},
/**
* Sets the initial radial speed of emitted particles.
* Changes the emitter to radial mode.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setSpeed
* @since 3.0.0
*
* @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The speed, in pixels per second.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setSpeed: function (value)
{
this.speedX.onChange(value);
this.speedY = null;
// If you specify speedX and Y then it changes the emitter from radial to a point emitter
this.radial = true;
return this;
},
/**
* Sets the horizontal scale of emitted particles.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setScaleX
* @since 3.0.0
*
* @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - The scale, relative to 1.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setScaleX: function (value)
{
this.scaleX.onChange(value);
return this;
},
/**
* Sets the vertical scale of emitted particles.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setScaleY
* @since 3.0.0
*
* @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - The scale, relative to 1.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setScaleY: function (value)
{
this.scaleY.onChange(value);
return this;
},
/**
* Sets the scale of emitted particles.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setScale
* @since 3.0.0
*
* @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - The scale, relative to 1.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setScale: function (value)
{
this.scaleX.onChange(value);
this.scaleY = null;
return this;
},
/**
* Sets the horizontal gravity applied to emitted particles.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setGravityX
* @since 3.0.0
*
* @param {number} value - Acceleration due to gravity, in pixels per second squared.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setGravityX: function (value)
{
this.gravityX = value;
return this;
},
/**
* Sets the vertical gravity applied to emitted particles.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setGravityY
* @since 3.0.0
*
* @param {number} value - Acceleration due to gravity, in pixels per second squared.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setGravityY: function (value)
{
this.gravityY = value;
return this;
},
/**
* Sets the gravity applied to emitted particles.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setGravity
* @since 3.0.0
*
* @param {number} x - Horizontal acceleration due to gravity, in pixels per second squared.
* @param {number} y - Vertical acceleration due to gravity, in pixels per second squared.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setGravity: function (x, y)
{
this.gravityX = x;
this.gravityY = y;
return this;
},
/**
* Sets the opacity of emitted particles.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setAlpha
* @since 3.0.0
*
* @param {(Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType|Phaser.Types.GameObjects.Particles.EmitterOpOnUpdateType)} value - A value between 0 (transparent) and 1 (opaque).
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setAlpha: function (value)
{
this.alpha.onChange(value);
return this;
},
/**
* Sets the angle of a {@link Phaser.GameObjects.Particles.ParticleEmitter#radial} particle stream.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setEmitterAngle
* @since 3.0.0
*
* @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The angle of the initial velocity of emitted particles.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setEmitterAngle: function (value)
{
this.angle.onChange(value);
return this;
},
/**
* Sets the angle of a {@link Phaser.GameObjects.Particles.ParticleEmitter#radial} particle stream.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setAngle
* @since 3.0.0
*
* @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The angle of the initial velocity of emitted particles.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setAngle: function (value)
{
this.angle.onChange(value);
return this;
},
/**
* Sets the lifespan of newly emitted particles.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setLifespan
* @since 3.0.0
*
* @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} value - The particle lifespan, in ms.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setLifespan: function (value)
{
this.lifespan.onChange(value);
return this;
},
/**
* Sets the number of particles released at each flow cycle or explosion.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setQuantity
* @since 3.0.0
*
* @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} quantity - The number of particles to release at each flow cycle or explosion.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setQuantity: function (quantity)
{
this.quantity.onChange(quantity);
return this;
},
/**
* Sets the emitter's {@link Phaser.GameObjects.Particles.ParticleEmitter#frequency}
* and {@link Phaser.GameObjects.Particles.ParticleEmitter#quantity}.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setFrequency
* @since 3.0.0
*
* @param {number} frequency - The time interval (>= 0) of each flow cycle, in ms; or -1 to put the emitter in explosion mode.
* @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} [quantity] - The number of particles to release at each flow cycle or explosion.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setFrequency: function (frequency, quantity)
{
this.frequency = frequency;
this._counter = 0;
if (quantity)
{
this.quantity.onChange(quantity);
}
return this;
},
/**
* Sets or removes the {@link Phaser.GameObjects.Particles.ParticleEmitter#emitZone}.
*
* An {@link Phaser.Types.GameObjects.Particles.ParticleEmitterEdgeZoneConfig EdgeZone} places particles on its edges. Its {@link Phaser.Types.GameObjects.Particles.EdgeZoneSource source} can be a Curve, Path, Circle, Ellipse, Line, Polygon, Rectangle, or Triangle; or any object with a suitable {@link Phaser.Types.GameObjects.Particles.EdgeZoneSourceCallback getPoints} method.
*
* A {@link Phaser.Types.GameObjects.Particles.ParticleEmitterRandomZoneConfig RandomZone} places randomly within its interior. Its {@link RandomZoneSource source} can be a Circle, Ellipse, Line, Polygon, Rectangle, or Triangle; or any object with a suitable {@link Phaser.Types.GameObjects.Particles.RandomZoneSourceCallback getRandomPoint} method.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setEmitZone
* @since 3.0.0
*
* @param {Phaser.Types.GameObjects.Particles.ParticleEmitterEdgeZoneConfig|Phaser.Types.GameObjects.Particles.ParticleEmitterRandomZoneConfig} [zoneConfig] - An object describing the zone, or `undefined` to remove any current emit zone.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setEmitZone: function (zoneConfig)
{
if (zoneConfig === undefined)
{
this.emitZone = null;
}
else
{
// Where source = Geom like Circle, or a Path or Curve
// emitZone: { type: 'random', source: X }
// emitZone: { type: 'edge', source: X, quantity: 32, [stepRate=0], [yoyo=false], [seamless=true] }
var type = GetFastValue(zoneConfig, 'type', 'random');
var source = GetFastValue(zoneConfig, 'source', null);
switch (type)
{
case 'random':
this.emitZone = new RandomZone(source);
break;
case 'edge':
var quantity = GetFastValue(zoneConfig, 'quantity', 1);
var stepRate = GetFastValue(zoneConfig, 'stepRate', 0);
var yoyo = GetFastValue(zoneConfig, 'yoyo', false);
var seamless = GetFastValue(zoneConfig, 'seamless', true);
this.emitZone = new EdgeZone(source, quantity, stepRate, yoyo, seamless);
break;
}
}
return this;
},
/**
* Sets or removes the {@link Phaser.GameObjects.Particles.ParticleEmitter#deathZone}.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#setDeathZone
* @since 3.0.0
*
* @param {Phaser.Types.GameObjects.Particles.ParticleEmitterDeathZoneConfig} [zoneConfig] - An object describing the zone, or `undefined` to remove any current death zone.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
setDeathZone: function (zoneConfig)
{
if (zoneConfig === undefined)
{
this.deathZone = null;
}
else
{
// Where source = Geom like Circle or Rect that supports a 'contains' function
// deathZone: { type: 'onEnter', source: X }
// deathZone: { type: 'onLeave', source: X }
var type = GetFastValue(zoneConfig, 'type', 'onEnter');
var source = GetFastValue(zoneConfig, 'source', null);
if (source && typeof source.contains === 'function')
{
var killOnEnter = (type === 'onEnter') ? true : false;
this.deathZone = new DeathZone(source, killOnEnter);
}
}
return this;
},
/**
* Creates inactive particles and adds them to this emitter's pool.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#reserve
* @since 3.0.0
*
* @param {integer} particleCount - The number of particles to create.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
reserve: function (particleCount)
{
var dead = this.dead;
for (var i = 0; i < particleCount; i++)
{
dead.push(new this.particleClass(this));
}
return this;
},
/**
* Gets the number of active (in-use) particles in this emitter.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#getAliveParticleCount
* @since 3.0.0
*
* @return {integer} The number of particles with `active=true`.
*/
getAliveParticleCount: function ()
{
return this.alive.length;
},
/**
* Gets the number of inactive (available) particles in this emitter.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#getDeadParticleCount
* @since 3.0.0
*
* @return {integer} The number of particles with `active=false`.
*/
getDeadParticleCount: function ()
{
return this.dead.length;
},
/**
* Gets the total number of particles in this emitter.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#getParticleCount
* @since 3.0.0
*
* @return {integer} The number of particles, including both alive and dead.
*/
getParticleCount: function ()
{
return this.getAliveParticleCount() + this.getDeadParticleCount();
},
/**
* Whether this emitter is at its limit (if set).
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#atLimit
* @since 3.0.0
*
* @return {boolean} Returns `true` if this Emitter is at its limit, or `false` if no limit, or below the `maxParticles` level.
*/
atLimit: function ()
{
return (this.maxParticles > 0 && this.getParticleCount() === this.maxParticles);
},
/**
* Sets a function to call for each newly emitted particle.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#onParticleEmit
* @since 3.0.0
*
* @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} callback - The function.
* @param {*} [context] - The calling context.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
onParticleEmit: function (callback, context)
{
if (callback === undefined)
{
// Clear any previously set callback
this.emitCallback = null;
this.emitCallbackScope = null;
}
else if (typeof callback === 'function')
{
this.emitCallback = callback;
if (context)
{
this.emitCallbackScope = context;
}
}
return this;
},
/**
* Sets a function to call for each particle death.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#onParticleDeath
* @since 3.0.0
*
* @param {Phaser.Types.GameObjects.Particles.ParticleDeathCallback} callback - The function.
* @param {*} [context] - The function's calling context.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
onParticleDeath: function (callback, context)
{
if (callback === undefined)
{
// Clear any previously set callback
this.deathCallback = null;
this.deathCallbackScope = null;
}
else if (typeof callback === 'function')
{
this.deathCallback = callback;
if (context)
{
this.deathCallbackScope = context;
}
}
return this;
},
/**
* Deactivates every particle in this emitter.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#killAll
* @since 3.0.0
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
killAll: function ()
{
var dead = this.dead;
var alive = this.alive;
while (alive.length > 0)
{
dead.push(alive.pop());
}
return this;
},
/**
* Calls a function for each active particle in this emitter.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#forEachAlive
* @since 3.0.0
*
* @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} callback - The function.
* @param {*} context - The function's calling context.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
forEachAlive: function (callback, context)
{
var alive = this.alive;
var length = alive.length;
for (var index = 0; index < length; ++index)
{
// Sends the Particle and the Emitter
callback.call(context, alive[index], this);
}
return this;
},
/**
* Calls a function for each inactive particle in this emitter.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#forEachDead
* @since 3.0.0
*
* @param {Phaser.Types.GameObjects.Particles.ParticleEmitterCallback} callback - The function.
* @param {*} context - The function's calling context.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
forEachDead: function (callback, context)
{
var dead = this.dead;
var length = dead.length;
for (var index = 0; index < length; ++index)
{
// Sends the Particle and the Emitter
callback.call(context, dead[index], this);
}
return this;
},
/**
* Turns {@link Phaser.GameObjects.Particles.ParticleEmitter#on} the emitter and resets the flow counter.
*
* If this emitter is in flow mode (frequency >= 0; the default), the particle flow will start (or restart).
*
* If this emitter is in explode mode (frequency = -1), nothing will happen.
* Use {@link Phaser.GameObjects.Particles.ParticleEmitter#explode} or {@link Phaser.GameObjects.Particles.ParticleEmitter#flow} instead.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#start
* @since 3.0.0
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
start: function ()
{
this.on = true;
this._counter = 0;
return this;
},
/**
* Turns {@link Phaser.GameObjects.Particles.ParticleEmitter#on off} the emitter.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#stop
* @since 3.11.0
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
stop: function ()
{
this.on = false;
return this;
},
/**
* {@link Phaser.GameObjects.Particles.ParticleEmitter#active Deactivates} the emitter.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#pause
* @since 3.0.0
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
pause: function ()
{
this.active = false;
return this;
},
/**
* {@link Phaser.GameObjects.Particles.ParticleEmitter#active Activates} the emitter.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#resume
* @since 3.0.0
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
resume: function ()
{
this.active = true;
return this;
},
/**
* Sorts active particles with {@link Phaser.GameObjects.Particles.ParticleEmitter#depthSortCallback}.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#depthSort
* @since 3.0.0
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
depthSort: function ()
{
StableSort.inplace(this.alive, this.depthSortCallback);
return this;
},
/**
* Puts the emitter in flow mode (frequency >= 0) and starts (or restarts) a particle flow.
*
* To resume a flow at the current frequency and quantity, use {@link Phaser.GameObjects.Particles.ParticleEmitter#start} instead.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#flow
* @since 3.0.0
*
* @param {number} frequency - The time interval (>= 0) of each flow cycle, in ms.
* @param {Phaser.Types.GameObjects.Particles.EmitterOpOnEmitType} [count=1] - The number of particles to emit at each flow cycle.
*
* @return {Phaser.GameObjects.Particles.ParticleEmitter} This Particle Emitter.
*/
flow: function (frequency, count)
{
if (count === undefined) { count = 1; }
this.frequency = frequency;
this.quantity.onChange(count);
return this.start();
},
/**
* Puts the emitter in explode mode (frequency = -1), stopping any current particle flow, and emits several particles all at once.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#explode
* @since 3.0.0
*
* @param {integer} count - The amount of Particles to emit.
* @param {number} x - The x coordinate to emit the Particles from.
* @param {number} y - The y coordinate to emit the Particles from.
*
* @return {Phaser.GameObjects.Particles.Particle} The most recently emitted Particle.
*/
explode: function (count, x, y)
{
this.frequency = -1;
return this.emitParticle(count, x, y);
},
/**
* Emits particles at a given position (or the emitter's current position).
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#emitParticleAt
* @since 3.0.0
*
* @param {number} [x=this.x] - The x coordinate to emit the Particles from.
* @param {number} [y=this.x] - The y coordinate to emit the Particles from.
* @param {integer} [count=this.quantity] - The number of Particles to emit.
*
* @return {Phaser.GameObjects.Particles.Particle} The most recently emitted Particle.
*/
emitParticleAt: function (x, y, count)
{
return this.emitParticle(count, x, y);
},
/**
* Emits particles at a given position (or the emitter's current position).
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#emitParticle
* @since 3.0.0
*
* @param {integer} [count=this.quantity] - The number of Particles to emit.
* @param {number} [x=this.x] - The x coordinate to emit the Particles from.
* @param {number} [y=this.x] - The y coordinate to emit the Particles from.
*
* @return {Phaser.GameObjects.Particles.Particle} The most recently emitted Particle.
*
* @see Phaser.GameObjects.Particles.Particle#fire
*/
emitParticle: function (count, x, y)
{
if (this.atLimit())
{
return;
}
if (count === undefined)
{
count = this.quantity.onEmit();
}
var dead = this.dead;
for (var i = 0; i < count; i++)
{
var particle = dead.pop();
if (!particle)
{
particle = new this.particleClass(this);
}
particle.fire(x, y);
if (this.particleBringToTop)
{
this.alive.push(particle);
}
else
{
this.alive.unshift(particle);
}
if (this.emitCallback)
{
this.emitCallback.call(this.emitCallbackScope, particle, this);
}
if (this.atLimit())
{
break;
}
}
return particle;
},
/**
* Updates this emitter and its particles.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#preUpdate
* @since 3.0.0
*
* @param {integer} time - The current timestamp as generated by the Request Animation Frame or SetTimeout.
* @param {number} delta - The delta time, in ms, elapsed since the last frame.
*/
preUpdate: function (time, delta)
{
// Scale the delta
delta *= this.timeScale;
var step = (delta / 1000);
if (this.trackVisible)
{
this.visible = this.follow.visible;
}
// Any particle processors?
var processors = this.manager.getProcessors();
var particles = this.alive;
var dead = this.dead;
var i = 0;
var rip = [];
var length = particles.length;
for (i = 0; i < length; i++)
{
var particle = particles[i];
// update returns `true` if the particle is now dead (lifeCurrent <= 0)
if (particle.update(delta, step, processors))
{
rip.push({ index: i, particle: particle });
}
}
// Move dead particles to the dead array
length = rip.length;
if (length > 0)
{
var deathCallback = this.deathCallback;
var deathCallbackScope = this.deathCallbackScope;
for (i = length - 1; i >= 0; i--)
{
var entry = rip[i];
// Remove from particles array
particles.splice(entry.index, 1);
// Add to dead array
dead.push(entry.particle);
// Callback
if (deathCallback)
{
deathCallback.call(deathCallbackScope, entry.particle);
}
entry.particle.resetPosition();
}
}
if (!this.on)
{
return;
}
if (this.frequency === 0)
{
this.emitParticle();
}
else if (this.frequency > 0)
{
this._counter -= delta;
if (this._counter <= 0)
{
this.emitParticle();
// counter = frequency - remained from previous delta
this._counter = (this.frequency - Math.abs(this._counter));
}
}
},
/**
* Calculates the difference of two particles, for sorting them by depth.
*
* @method Phaser.GameObjects.Particles.ParticleEmitter#depthSortCallback
* @since 3.0.0
*
* @param {object} a - The first particle.
* @param {object} b - The second particle.
*
* @return {integer} The difference of a and b's y coordinates.
*/
depthSortCallback: function (a, b)
{
return a.y - b.y;
}
});
module.exports = ParticleEmitter;
|
var VueAudioSoundcloud=function(t){"use strict";t=t&&t.hasOwnProperty("default")?t.default:t;const e=t=>{let e=new Date(t).toISOString().substr(11,8);return 0===e.indexOf("00:")?e.substr(3):e};const i={name:"vue-audio-soundcloud",props:{elements:{type:Object,default:{}},defaultVolume:{type:Number,default:100}},data:()=>({currentTrack:{},duration:{current:"00:00",total:"--:--"},els:{},list:[],listPosition:{},isDraggable:!1,isLoading:!1,isLoop:!1,isMuted:!1,isPlaying:!1,progression:0,seekToShortcutAvailable:!0,volume:100,widget:{}}),methods:{finished(){if("track"===this.isLoop)return this.widget.seekTo(0),this.play();this.next(),(this.list&&this.list.length<=0||this.list&&this.list.length>0&&!this.isLoop)&&this.pause()},load({track:t,list:e}){this.isLoading=!0,this.loadList(t,e),this.loadTrack(t)},loadList(t,e){if(!e)return this.list=[],this.listPosition=!1;this.list=e,this.setListPosition(e.findIndex(e=>e.id===t.id))},loadTrack(t){this.currentTrack=t,this.progression=0,this.duration.total=e(t.duration),this.loadWidget(t)},loadWidget(t){this.widget.load(t.uri,{show_artwork:!1,show_comments:!1,show_playcount:!1,show_user:!1,buying:!1,sharing:!1,auto_play:!0,callback:()=>{this.isLoading=!1,this.isPlaying=!0,this.isMuted?this.widget.setVolume(0):this.widget.setVolume(this.volume),this.$emit("load",this.currentTrack.id)}})},loop(){let t=[!1,"track","list"];this.list.length>0?(this.isLoop="list"===this.isLoop?t[0]:t[t.indexOf(this.isLoop)+1],this.setListPosition()):this.isLoop="track"===this.isLoop?t[0]:t[t.indexOf(this.isLoop)+1]},mute(){this.isMuted=!0,this.widget.setVolume(0)},next(){this.list&&this.list.length>0&&("list"===this.isLoop&&this.listPosition.current===this.list.length-1?(this.setListPosition(0),this.loadTrack(this.list[this.listPosition.current])):this.listPosition.current>=0&&this.listPosition.current<this.list.length-1&&(this.setListPosition(this.listPosition.current+1),this.loadTrack(this.list[this.listPosition.current])))},pause(){this.widget.pause(),this.isPlaying=!1,this.$emit("pause")},play(){this.widget&&Object.keys(this.currentTrack).length>0&&(this.widget.play(),this.isPlaying=!0,this.$emit("play"))},previous(){this.list&&this.list.length>0&&this.widget.getPosition(t=>{if(t/1e3>10)return this.widget.seekTo(0);"list"===this.isLoop&&0===this.listPosition.current?(this.setListPosition(this.list.length-1),this.loadTrack(this.list[this.listPosition.current])):this.listPosition.current>0&&(this.setListPosition(this.listPosition.current-1),this.loadTrack(this.list[this.listPosition.current]))})},fastBackward(){this.widget.getPosition(t=>{this.seekToShortcutAvailable&&(t>=5e3?this.widget.seekTo(t-5e3):this.widget.seekTo(0),this.seekToShortcutAvailable=!1,setTimeout(()=>{this.seekToShortcutAvailable=!0},200))})},fastForward(){this.widget.getPosition(t=>{this.seekToShortcutAvailable&&(this.widget.seekTo(t+5e3),this.seekToShortcutAvailable=!1,setTimeout(()=>{this.seekToShortcutAvailable=!0},200))})},setListPosition(t){this.listPosition||(this.listPosition={}),this.listPosition.current=void 0!==t?t:this.listPosition.current,this.listPosition.first=this.listPosition.current<=0&&"list"!==this.isLoop,this.listPosition.last=this.listPosition.current===this.list.length-1&&"list"!==this.isLoop},setTime(t,e){this.widget.getDuration(i=>{this.widget.seekTo(parseInt(t.offsetX/e.offsetWidth*i))})},setVolume(t,e){this.volume=parseInt(t.offsetX/e.offsetWidth*100),this.widget.setVolume(this.volume),this.isMuted&&(this.isMuted=!1),0===this.volume&&(this.isMuted=!0)},unmute(){0===this.volume&&(this.volume=10),this.isMuted=!1,this.widget.setVolume(this.volume)},_handleMouseUp(){this.isDraggable=!1},_handleTimelineClick(t){this.isDraggable=!0,this.setTime(t,this.els.timeline)},_handleTimelineMove(t){this.isDraggable&&this.setTime(t,this.els.timeline)},_handleVolumeClick(t){this.isDraggable=!0,this.setVolume(t,this.els.volume)},_handleVolumeMove(t){this.isDraggable&&this.setVolume(t,this.els.volume)},_shortcuts(t){let e=t.which||t.keyCode;32===e?(t.preventDefault(),this.isPlaying?this.pause():this.play()):77===e?this.isMuted?this.unmute():this.mute():37===e&&t.shiftKey?this.previous():39===e&&t.shiftKey?this.next():37===e?this.fastBackward():39===e?this.fastForward():38===e&&t.shiftKey?(this.volume<=95?this.volume+=5:this.volume=100,this.widget.setVolume(this.volume)):40===e&&t.shiftKey&&(this.volume>=5?this.volume-=5:this.volume=0,this.widget.setVolume(this.volume))}},created(){t.prototype.$AudioSoundcloud={load:t=>this.load(t),pause:()=>this.pause(),play:()=>this.play()}},mounted(){this.volume=this.defaultVolume,this.widget=SC.Widget("soundcloud-iframe"),this.els.timeline=document.getElementById(this.elements.timeline),this.els.volume=document.getElementById(this.elements.volume),this.widget.bind(SC.Widget.Events.READY,()=>{this.widget.bind(SC.Widget.Events.FINISH,()=>{this.finished()}),this.widget.bind(SC.Widget.Events.PAUSE,()=>{this.isPlaying=!1,this.$emit("pause")}),this.widget.bind(SC.Widget.Events.PLAY,()=>{this.isPlaying=!0,this.$emit("play")}),this.widget.bind(SC.Widget.Events.PLAY_PROGRESS,t=>{this.progression=100*t.relativePosition,this.duration.current=e(t.currentPosition)}),this.els.timeline&&(this.els.timeline.addEventListener("mousedown",this._handleTimelineClick),this.els.timeline.addEventListener("mousemove",this._handleTimelineMove)),this.els.volume&&(this.els.volume.addEventListener("mousedown",this._handleVolumeClick),this.els.volume.addEventListener("mousemove",this._handleVolumeMove)),document.addEventListener("mouseup",this._handleMouseUp),document.addEventListener("keydown",this._shortcuts)})},beforeDestoy(){this.widget.unbind(SC.Widget.Events.FINISH),this.widget.unbind(SC.Widget.Events.PAUSE),this.widget.unbind(SC.Widget.Events.PLAY),this.widget.unbind(SC.Widget.Events.PLAY_PROGRESS),this.widget.unbind(SC.Widget.Events.READY),this.els.timeline&&(this.els.timeline.removeEventListener("mousedown",this._handleTimelineClick),this.els.timeline.removeEventListener("mousemove",this._handleTimelineMove)),this.els.volume&&(this.els.volume.removeEventListener("mousedown",this._handleVolumeClick),this.els.volume.removeEventListener("mousemove",this._handleVolumeMove)),document.removeEventListener("mouseup",this._handleMouseUp),document.removeEventListener("keydown",this._shortcuts)}};var s=function(){var t=this,e=t.$createElement,i=t._self._c||e;return i("div",[i("iframe",{attrs:{id:"soundcloud-iframe",width:"100%",height:"166",scrolling:"no",frameborder:"no",allow:"autoplay",src:"https://w.soundcloud.com/player/?url="}}),t._v(" "),t._t("default",null,null,{currentTrack:t.currentTrack,duration:t.duration,listPosition:t.listPosition,loop:t.loop,isLoading:t.isLoading,isLoop:t.isLoop,isMuted:t.isMuted,isPlaying:t.isPlaying,mute:t.mute,next:t.next,play:t.play,pause:t.pause,previous:t.previous,progression:t.progression,fastBackward:t.fastBackward,fastForward:t.fastForward,unmute:t.unmute,volume:t.volume})],2)};s._withStripped=!0;var o=function(t,e,i,s,o,n,l,d){const u=("function"==typeof i?i.options:i)||{};u.__file="/Users/flavio/Desktop/Projects/vue-audio-soundcloud/src/Player.vue",u.render||(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0,o&&(u.functional=!0)),u._scopeId=s;{let t;if(e&&(t=function(t){e.call(this,l(t))}),void 0!==t)if(u.functional){const e=u.render;u.render=function(i,s){return t.call(s),e(i,s)}}else{const e=u.beforeCreate;u.beforeCreate=e?[].concat(e,t):[t]}}return u}({render:s,staticRenderFns:[]},function(t){t&&t("data-v-dfb1f676_0",{source:"\n#soundcloud-iframe[data-v-dfb1f676] {\n left: 99999px;\n position: fixed;\n top: 0;\n}\n",map:{version:3,sources:["/Users/flavio/Desktop/Projects/vue-audio-soundcloud/src/Player.vue"],names:[],mappings:";AA6BA;EACA,cAAA;EACA,gBAAA;EACA,OAAA;CACA",file:"Player.vue",sourcesContent:['<template>\n <div>\n <iframe id="soundcloud-iframe" width="100%" height="166" scrolling="no" frameborder="no" allow="autoplay" src="https://w.soundcloud.com/player/?url="></iframe>\n <slot v-bind="{ \n currentTrack,\n duration,\n listPosition,\n loop,\n isLoading,\n isLoop,\n isMuted,\n isPlaying,\n mute,\n next,\n play,\n pause,\n previous,\n progression,\n fastBackward,\n fastForward,\n unmute,\n volume,\n }"></slot>\n </div>\n</template>\n\n<script src="./plugin.js"><\/script>\n\n<style scoped>\n #soundcloud-iframe {\n left: 99999px;\n position: fixed;\n top: 0;\n }\n</style>']},media:void 0})},i,"data-v-dfb1f676",!1,0,function t(){const e=document.head||document.getElementsByTagName("head")[0],i=t.styles||(t.styles={}),s="undefined"!=typeof navigator&&/msie [6-9]\\b/.test(navigator.userAgent.toLowerCase());return function(t,o){if(document.querySelector('style[data-vue-ssr-id~="'+t+'"]'))return;const n=s?o.media||"default":t,l=i[n]||(i[n]={ids:[],parts:[],element:void 0});if(!l.ids.includes(t)){let i=o.source,d=l.ids.length;if(l.ids.push(t),s&&(l.element=l.element||document.querySelector("style[data-group="+n+"]")),!l.element){const t=l.element=document.createElement("style");t.type="text/css",o.media&&t.setAttribute("media",o.media),s&&(t.setAttribute("data-group",n),t.setAttribute("data-next-index","0")),e.appendChild(t)}if(s&&(d=parseInt(l.element.getAttribute("data-next-index")),l.element.setAttribute("data-next-index",d+1)),l.element.styleSheet)l.parts.push(i),l.element.styleSheet.cssText=l.parts.filter(Boolean).join("\n");else{const t=document.createTextNode(i),e=l.element.childNodes;e[d]&&l.element.removeChild(e[d]),e.length?l.element.insertBefore(t,e[d]):l.element.appendChild(t)}}}});const n={install:function(t){t.component("vue-audio-soundcloud",o)}};return"undefined"!=typeof window&&window.Vue&&window.Vue.use(n),n}(Vue);
|
from pathlib import Path
from typing import Union, Dict, Any, List, Tuple
from collections import OrderedDict
# fmt: off
FilePath = Union[str, Path]
# Superficial JSON input/output types
# https://github.com/python/typing/issues/182#issuecomment-186684288
JSONOutput = Union[str, int, float, bool, None, Dict[str, Any], List[Any]]
JSONOutputBin = Union[bytes, str, int, float, bool, None, Dict[str, Any], List[Any]]
# For input, we also accept tuples, ordered dicts etc.
JSONInput = Union[str, int, float, bool, None, Dict[str, Any], List[Any], Tuple[Any], OrderedDict]
JSONInputBin = Union[bytes, str, int, float, bool, None, Dict[str, Any], List[Any], Tuple[Any], OrderedDict]
YAMLInput = JSONInput
YAMLOutput = JSONOutput
# fmt: on
def force_path(location, require_exists=True):
if not isinstance(location, Path):
location = Path(location)
if require_exists and not location.exists():
raise ValueError(f"Can't read file: {location}")
return location
def force_string(location):
if isinstance(location, str):
return location
return str(location)
|
/*! Lawrence - v1.0.9 - 2015-12-26 */
(function(){$(function(){return $("a[rel=group]").fancybox({padding:"0",titleShow:!1,cyclic:!0,overlayOpacity:"0.8",overlayColor:"#000",centerOnScroll:"true"}),$(".jq-action-btn").mouseover(function(){return $(this).find(".action-buttons").css({visibility:"visible"})}),$(".jq-action-btn").mouseout(function(){return $(this).find(".action-buttons").css({visibility:"hidden"})}),$(".js-pubu").waterfall({debug:!1,itemCls:"waterfall-item",gutterWidth:20,gutterHeight:20,colWidth:212,maxPage:1,loadingMsg:"",callbacks:{loadingFinished:function(a,b){return b?a.hide():a.fadeOut()},renderData:function(){return $(".js-pubu").html()}}})})}).call(this);
//# sourceMappingURL=detail.js.map |
import clamp from 'clamp'
import colorMap from './big-color-map.js'
export default function vizVerticalBars (options={}) {
let { ctx, cv, bandCount, rotateAmount } = options
const dampen = true
let allRotate = 0
let centerRadius, heightMultiplier, gap, fade
let variant = 0
const variants = [[false, true], [true, false], [false, false]]
const vary = function () {
variant = (variant + 1) % variants.length
gap = variants[variant][0]
fade = variants[variant][1]
}
const resize = function () {
const shortestSide = Math.min(cv.width, cv.height)
centerRadius = 85.0 / 800 * shortestSide
heightMultiplier = 1.0 / 800 * shortestSide
}
const draw = function (spectrum) {
ctx.clearRect(0, 0, cv.width, cv.height)
let barWidth = cv.width / bandCount
for (let i = 0; i < bandCount; i++) {
let hue = Math.floor(360.0 / bandCount * i)
let brightness = fade ? clamp(Math.floor(spectrum[i] / 1.5), 25, 99) : 99
ctx.fillStyle = colorMap.bigColorMap[hue * 100 + brightness]
let barHeight = cv.height * (spectrum[i] / 255)
ctx.fillRect(i * barWidth, cv.height - barHeight, barWidth, barHeight)
}
}
vary()
return Object.freeze({ dampen, vary, resize, draw })
}
|
const express = require("express");
const path = require("path");
const fs = require("fs");
const axios = require("axios");
const router = express.Router();
/* GET home page. */
router.get("/", function(req, res, next) {
res.sendFile(path.join(__dirname + "/public/index.html"));
});
router.get("/update", function(req, res, next) {
const jsonPath = path.join(__dirname + "/../public/data.json");
//Update code goes here
//Year 2016-2019, Month 1-12
let obj = { year: 2019, month: 1 };
function sortFunction(a, b) {
//jobsCount jobsLength maxLength minLength jobsFinance jobsMass maxMass
return jobsByUser[b].jobsCount - jobsByUser[a].jobsCount;
}
const instance = axios.create({
baseURL: "https://api.vtlog.net/v1",
timeout: 10000,
headers: { "X-API-KEY": "A46A7953ED857401628A76246BF7C90EB5703FE5D4237EAB" }
});
obj.month = (obj.month - 1) % 13;
//const date = new Date();
// const obj = { year: date.getFullYear(), month: date.getMonth() };
let startTime = new Date(Date.UTC(obj.year, obj.month));
let endTime = new Date(Date.UTC(obj.year, obj.month + 1));
console.log("Start time: " + startTime.toUTCString());
console.log("End time: " + endTime.toUTCString());
const jobsByUser = {};
const jobsByTruck = {};
const company = {
companyId: 53,
jobsCount: 0,
jobsLength: 0,
jobsFinance: 0,
start: startTime.toUTCString(),
end: endTime.toUTCString()
};
startTime = startTime.valueOf() / 1000;
endTime = endTime.valueOf() / 1000;
console.log("Please wait, Pikachu is charging Thunder.");
//Flag set to true if any data is stored
let someDataFlag = false;
(async () => {
let page = 1;
while (true) {
const response = await instance.get(
"companies/" + company.companyId + "/jobs",
{
params: { page: page, limit: 99 }
}
);
page++;
//Flag set to false if no data is found in current call
let noDataFlag = true;
response.data.response.jobs.forEach(job => {
if (
job.realStartTime > startTime &&
job.realStartTime < endTime &&
job.canceled == "0"
) {
someDataFlag = true;
noDataFlag = false;
company.jobsCount++;
if (job.odometer < 0) return;
company.jobsLength += parseFloat(job.odometer);
company.jobsFinance += parseFloat(job.fin_result);
job.username = job.username.replace("[LKW Tr.] ", "");
const truckName = job.truck_make + " " + job.truck_model;
if (Object.keys(jobsByUser).includes(job.username)) {
const {
jobsCount,
jobsLength,
maxLength,
minLength,
avgLength,
jobsFinance,
jobsMass,
maxMass,
minMass,
fuel,
mileage,
lkwVisited,
trucksUsed,
peterVisited
} = jobsByUser[job.username];
const currentDist = parseFloat(job.odometer);
jobsByUser[job.username] = {
jobsCount: jobsCount + 1,
jobsLength: jobsLength + currentDist,
minLength: Math.min(minLength, currentDist),
maxLength: Math.max(maxLength, currentDist),
avgLength: avgLength,
jobsFinance: jobsFinance + parseFloat(job.fin_result),
jobsMass: jobsMass + parseFloat(job.cargo_mass / 1000),
maxMass: Math.max(maxMass, parseFloat(job.cargo_mass / 1000)),
minMass: Math.min(minMass, parseFloat(job.cargo_mass / 1000)),
fuel: fuel + parseFloat(job.fuel),
mileage: mileage,
lkwVisited: (function(lkwVisited) {
if (job.source_company.includes("Lkw")) lkwVisited++;
if (job.destination_company.includes("Lkw")) lkwVisited++;
return lkwVisited;
})(lkwVisited),
trucksUsed: (function(trucksUsed) {
if (trucksUsed.indexOf(truckName) === -1)
trucksUsed.push(truckName);
return trucksUsed;
})(trucksUsed),
peterVisited: (function(peterVisited) {
if (job.source_city.includes("Санкт")) peterVisited++;
if (job.destination_city.includes("Санкт")) peterVisited++;
return peterVisited;
})(peterVisited)
};
} else {
jobsByUser[job.username] = {
jobsCount: 1,
jobsLength: parseFloat(job.odometer),
minLength: parseFloat(job.odometer),
maxLength: parseFloat(job.odometer),
avgLength: 0,
jobsFinance: parseFloat(job.fin_result),
jobsMass: parseFloat(job.cargo_mass / 1000),
maxMass: parseFloat(job.cargo_mass / 1000),
minMass: parseFloat(job.cargo_mass / 1000),
fuel: parseFloat(job.fuel),
mileage: 0,
lkwVisited: (function() {
if (
job.source_company.includes("Lkw") ||
job.destination_company.includes("Lkw")
)
return 1;
return 0;
})(),
trucksUsed: new Array(truckName),
peterVisited: (function() {
if (
job.source_city.includes("Санкт") ||
job.destination_city.includes("Санкт")
)
return 1;
return 0;
})()
};
}
if (Object.keys(jobsByTruck).includes(truckName)) {
const { jobsCount, users } = jobsByTruck[truckName];
jobsByTruck[truckName] = {
jobsCount: jobsCount + 1,
users: (function(users) {
if (users.indexOf(job.username) === -1)
users.push(job.username);
return users;
})(users)
};
} else {
jobsByTruck[truckName] = {
jobsCount: 1,
users: new Array(job.username)
};
}
}
});
if (someDataFlag && noDataFlag) {
console.log("Gone till page: " + page);
break;
}
}
//Sorting final data by count and calculating avg distance
const jobsByUserOrdered = {};
Object.keys(jobsByUser)
.sort(sortFunction)
.forEach(function(key) {
jobsByUserOrdered[key] = jobsByUser[key];
const { jobsCount, jobsLength, fuel } = jobsByUserOrdered[key];
jobsByUserOrdered[key].avgLength = parseFloat(jobsLength / jobsCount);
jobsByUserOrdered[key].mileage = parseFloat((fuel * 100) / jobsLength);
jobsByUserOrdered[key].name = key;
});
const jobsByTruckOrdered = {};
Object.keys(jobsByTruck)
.sort(function(a, b) {
return jobsByTruck[b].users.length - jobsByTruck[a].users.length;
})
.forEach(function(key) {
jobsByTruckOrdered[key] = jobsByTruck[key];
});
const jobsArray = [];
Object.keys(jobsByUserOrdered).forEach(function(key) {
jobsArray.push(jobsByUserOrdered[key]);
});
company.usersActive = Object.keys(jobsByUser).length + " Truckers";
company.avgLength = parseFloat(company.jobsLength / company.jobsCount);
company.user = jobsArray;
//company.truck = jobsByTruckOrdered;
function replacer(key, value) {
if (Number(value) === value && value % 1 != 0) return parseInt(value);
return value;
}
let data = JSON.stringify(company, replacer, " ");
res.send(data);
fs.writeFile(jsonPath, data, function(err) {
if (err) {
return console.log(err);
}
console.log("Data dumped in data.json");
console.log("Pikachu used Thunder, it is super effective !!");
});
})();
});
module.exports = router;
|
const ages = require("../ages");
const ageCost = require("../ages-cost/IronAge");
module.exports = {
key: "Colosseum",
age: ages.IronAge.key,
levels: ageCost
};
|
import React from "react";
import ReactDOM from "react-dom";
import Amplify from "aws-amplify";
import { BrowserRouter as Router } from "react-router-dom";
import App from "./App";
import registerServiceWorker from "./registerServiceWorker";
import config from "./config";
import "./index.css";
Amplify.configure({
Auth: {
mandatorySignIn: true,
region: config.cognito.REGION,
userPoolId: config.cognito.USER_POOL_ID,
identityPoolId: config.cognito.IDENTITY_POOL_ID,
userPoolWebClientId: config.cognito.APP_CLIENT_ID
},
Storage: {
region: config.s3.REGION,
bucket: config.s3.BUCKET,
identityPoolId: config.cognito.IDENTITY_POOL_ID
},
API: {
endpoints: [
{
name: "notes",
endpoint: config.apiGateway.URL,
region: config.apiGateway.REGION
},
]
}
});
ReactDOM.render(
<Router>
<App />
</Router>,
document.getElementById("root")
);
registerServiceWorker(); |
/* eslint no-console: 0, import/no-extraneous-dependencies: 0, import/no-dynamic-require: 0 */
const fs = require('fs-extra')
const path = require('path')
const { execSync } = require('child_process')
const archiver = require('archiver')
// In the future, could consider crx-hotreload script for better
// development experience:
// https://github.com/xpl/crx-hotreload/blob/master/hot-reload.js
process.env.BROWSER = 'chrome'
const BASE_BUILD_DIR = path.join(__dirname, '../build/')
const BUILD_DIR = path.join(BASE_BUILD_DIR, 'chromium/')
const SHARED_CODE_BUILD_DIR = path.join(
__dirname,
'../intermediate-builds/shared/'
)
const SRC_DIR = path.join(__dirname, '../src/chromium/')
// Get the version number.
const manifest = require(path.join(SRC_DIR, 'manifest.json'))
const { version } = manifest
console.log(`Building extension version ${version}...`)
// Empty build target contents. This will also create the directory
// if it does not exist.
fs.emptyDirSync(BUILD_DIR)
// Create the build version of the src.
const stageDir = path.join(BUILD_DIR, 'chrome-search-for-a-cause')
// Filter copying source files to build. Return true if we should copy and
// false if we should not.
const filterCopiedFiles = src => {
if (path.basename(src) === '.DS_Store') {
return false
}
return true
}
fs.copySync(SRC_DIR, stageDir, { filter: filterCopiedFiles })
fs.removeSync(path.join(stageDir, '__tests__'))
// Build the shared code and add it to the built extension.
execSync('yarn run shared:build')
fs.copySync(SHARED_CODE_BUILD_DIR, stageDir)
// Create zip file.
const zipFileName = `chrome-search-for-a-cause-v${version}.zip`
const output = fs.createWriteStream(path.join(BUILD_DIR, zipFileName))
const archive = archiver('zip')
// Listen for all archive data to be written.
output.on('close', () => {
console.log(`${archive.pointer()} total bytes`)
console.log('Finished building.')
})
archive.on('error', err => {
throw err
})
// Pipe archive data to the file.
archive.pipe(output)
// Append all files in our src directory.
archive.directory(stageDir, '/')
// Finalize the archive (i.e. we are done appending files,
// but streams still have to finish).
archive.finalize()
|
import React, { Component } from "react";
import axios from "axios";
class Login extends Component {
state = {
email: "",
password: "",
loginErrors: "",
};
handleSubmit = (e) => {
e.preventDefault();
axios
.post(
"http://localhost:5000/sessions",
{
user: {
email: this.state.email,
password: this.state.password,
},
},
{ withCredentials: true }
)
.then((response) => {
if (response.data.logged_in) {
this.props.handleSuccessfulAuth(response.data);
}
})
.catch((error) => {
console.log("Login error:", error);
});
};
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
};
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input
type="email"
name="email"
placeholder="Email"
value={this.state.email}
onChange={this.handleChange}
required
/>
<input
type="password"
name="password"
placeholder="Password"
value={this.state.password}
onChange={this.handleChange}
required
/>
<button type="submit">Login</button>
</form>
</div>
);
}
}
export default Login;
|
const Collectable = {
options: { onCollection: null },
create(object, options) {
const body = object.body
if (!body.onOverlap)
body.onOverlap = new Phaser.Signal()
if (options.onCollection)
body.onOverlap.add(options.onCollection)
}
}
export default Collectable
|
$(document).ready(function(){
//Usuarios login
$("button[action='login']").on("click",function(){
$("#formLogin").validate({
rules:
{
email: {
required: true,
email: true,
minlength: 5,
maxlength: 191
},
password: {
required: true,
minlength: 8,
maxlength: 40
}
},
messages:
{
email: {
email: 'Introduce una dirección de correo valida.',
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
password: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
}
},
submitHandler: function(form) {
$("button[action='login']").attr('disabled', true);
form.submit();
}
});
});
//Usuarios register
$("button[action='register']").on("click",function(){
$("#formRegister").validate({
rules:
{
name: {
required: true,
minlength: 2,
maxlength: 191
},
lastname: {
required: true,
minlength: 2,
maxlength: 191
},
email: {
required: true,
email: true,
minlength: 5,
maxlength: 191,
remote: {
url: "/usuarios/email",
type: "get"
}
},
password: {
required: true,
minlength: 8,
maxlength: 40
},
terms: {
required: true
}
},
messages:
{
name: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
lastname: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
email: {
email: 'Introduce una dirección de correo valida.',
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.',
remote: "Este correo ya esta en uso."
},
password: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
}
},
submitHandler: function(form) {
$("button[action='register']").attr('disabled', true);
form.submit();
}
});
});
//Recuperar Contraseña
$("button[action='recovery']").on("click",function(){
$("#formRecovery").validate({
rules:
{
email: {
required: true,
email: true,
minlength: 5,
maxlength: 191
},
recovery: {
required: true,
email: true,
minlength: 5,
maxlength: 191
}
},
messages:
{
email: {
email: 'Introduce una dirección de correo valida.',
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
recovery: {
email: 'Introduce una dirección de correo valida.',
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
}
},
submitHandler: function(form) {
$("button[action='recovery']").attr('disabled', true);
form.submit();
}
});
});
//Restaurar Contraseña
$("button[action='reset']").on("click",function(){
$("#formReset").validate({
rules:
{
email: {
required: true,
email: true,
minlength: 5,
maxlength: 191
},
password: {
required: true,
minlength: 8,
maxlength: 40
},
password_confirmation: {
equalTo: "#password",
minlength: 8,
maxlength: 40
}
},
messages:
{
email: {
email: 'Introduce una dirección de correo valida.',
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
password: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
password_confirmation: {
equalTo: 'Los datos ingresados no coinciden.',
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
}
},
submitHandler: function(form) {
$("button[action='reset']").attr('disabled', true);
form.submit();
}
});
});
//Perfil
$("button[action='profile']").on("click",function(){
$("#formProfile").validate({
rules:
{
name: {
required: true,
minlength: 2,
maxlength: 191
},
lastname: {
required: true,
minlength: 2,
maxlength: 191
},
phone: {
required: false,
minlength: 5,
maxlength: 15
},
type: {
required: true
},
password: {
required: false,
minlength: 8,
maxlength: 40
},
password_confirmation: {
equalTo: "#password",
minlength: 8,
maxlength: 40
}
},
messages:
{
name: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
lastname: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
phone: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
type: {
required: 'Seleccione una opción.'
},
password: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
password_confirmation: {
equalTo: 'Los datos ingresados no coinciden.',
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
}
},
submitHandler: function(form) {
$("button[action='profile']").attr('disabled', true);
form.submit();
}
});
});
// Usuarios
$("button[action='user']").on("click",function(){
$("#formUser").validate({
rules:
{
name: {
required: true,
minlength: 2,
maxlength: 191
},
lastname: {
required: true,
minlength: 2,
maxlength: 191
},
email: {
required: true,
email: true,
minlength: 5,
maxlength: 191,
remote: {
url: "/usuarios/email",
type: "get"
}
},
phone: {
required: false,
minlength: 5,
maxlength: 15
},
type: {
required: true
},
password: {
required: true,
minlength: 8,
maxlength: 40
},
password_confirmation: {
equalTo: "#password",
minlength: 8,
maxlength: 40
}
},
messages:
{
name: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
lastname: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
email: {
email: 'Introduce una dirección de correo valida.',
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.',
remote: "Este correo ya esta en uso."
},
phone: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
type: {
required: 'Seleccione una opción.'
},
password: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
password_confirmation: {
equalTo: 'Los datos ingresados no coinciden.',
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
}
},
submitHandler: function(form) {
$("button[action='user']").attr('disabled', true);
form.submit();
}
});
});
// Banners Create
$("button[action='banner']").on("click",function(){
$("#formBanner").validate({
rules:
{
state: {
required: true
},
image: {
required: true
}
},
messages:
{
state: {
required: 'Seleccione una opción.'
},
image: {
required: 'Seleccione una imagen.'
}
},
submitHandler: function(form) {
$("button[action='banner']").attr('disabled', true);
form.submit();
}
});
});
// Banners Edit
$("button[action='banner']").on("click",function(){
$("#formBannerEdit").validate({
rules:
{
image: {
required: false
},
state: {
required: true
}
},
messages:
{
state: {
required: 'Seleccione una opción.'
}
},
submitHandler: function(form) {
$("button[action='banner']").attr('disabled', true);
form.submit();
}
});
});
//Categorias
$("button[action='category']").on("click",function(){
$("#formCategory").validate({
rules:
{
name: {
required: true,
minlength: 2,
maxlength: 191
}
},
messages:
{
name: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
}
},
submitHandler: function(form) {
$("button[action='category']").attr('disabled', true);
form.submit();
}
});
});
//Productos
$("button[action='product']").on("click",function(){
$("#formProduct").validate({
rules:
{
image: {
required: false
},
name: {
required: true,
minlength: 2,
maxlength: 191
},
category_id: {
required: true
},
qty: {
required: true,
min: 0
},
discount: {
required: true,
min: 0,
max: 100
},
description: {
required: true,
minlength: 2,
maxlength: 65000
},
price: {
required: true,
min: 0
}
},
messages:
{
name: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
category_id: {
required: 'Seleccione una opción.'
},
qty: {
min: 'Escribe un valor mayor o igual a {0}.'
},
discount: {
min: 'Escribe un valor mayor o igual a {0}.',
max: 'Escribe un valor menor o igual a {0}.'
},
description: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
price: {
min: 'Escribe un valor mayor o igual a {0}.'
}
},
submitHandler: function(form) {
$("button[action='product']").attr('disabled', true);
form.submit();
}
});
});
//Cupones
$("button[action='coupon']").on("click",function(){
$("#formCoupon").validate({
rules:
{
discount: {
required: true,
min: 0,
max: 100
},
limit: {
required: true,
min: 1
}
},
messages:
{
discount: {
min: 'Escribe un valor mayor o igual a {0}.',
max: 'Escribe un valor menor o igual a {0}.'
},
limit: {
min: 'Escribe un valor mayor o igual a {0}.'
}
},
submitHandler: function(form) {
$("button[action='coupon']").attr('disabled', true);
form.submit();
}
});
});
//Terminos y condiciones
$("button[action='term']").on("click",function(){
$("#formTerm").validate({
rules:
{
terms: {
required: false,
minlength: 1,
maxlength: 16770000
}
},
messages:
{
terms: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
}
},
submitHandler: function(form) {
$("button[action='term']").attr('disabled', true);
form.submit();
}
});
});
//Políticas
$("button[action='politic']").on("click",function(){
$("#formPolitic").validate({
rules:
{
privacity: {
required: false,
minlength: 1,
maxlength: 16770000
}
},
messages:
{
privacity: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
}
},
submitHandler: function(form) {
$("button[action='politic']").attr('disabled', true);
form.submit();
}
});
});
//Contactos
$("button[action='contact']").on("click",function(){
$("#formContact").validate({
rules:
{
phone: {
required: false,
minlength: 5,
maxlength: 20
},
email: {
required: false,
email: true,
minlength: 5,
maxlength: 191
},
address: {
required: false,
minlength: 2,
maxlength: 191
},
facebook: {
required: false,
minlength: 2,
maxlength: 191
},
twitter: {
required: false,
minlength: 2,
maxlength: 191
},
instagram: {
required: false,
minlength: 2,
maxlength: 191
}
},
messages:
{
phone: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
email: {
email: 'Introduce una dirección de correo valida.',
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
address: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
facebook: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
twitter: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
instagram: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
}
},
submitHandler: function(form) {
$("button[action='contact']").attr('disabled', true);
form.submit();
}
});
});
// Finalizar Compra
$("button[action='checkout']").on("click",function(){
$("#formCheckout").validate({
rules:
{
name: {
required: true,
minlength: 2,
maxlength: 191
},
lastname: {
required: true,
minlength: 2,
maxlength: 191
},
email: {
required: true,
email: true,
minlength: 5,
maxlength: 191
},
phone: {
required: true,
minlength: 5,
maxlength: 15
},
shipping: {
required: true
},
address: {
required: true,
minlength: 2,
maxlength: 191
},
payment: {
required: true
},
password: {
required: true,
minlength: 8,
maxlength: 40
},
password_confirmation: {
equalTo: "#password",
minlength: 8,
maxlength: 40
}
},
messages:
{
name: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
lastname: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
email: {
email: 'Introduce una dirección de correo valida.',
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
phone: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
shipping: {
required: 'Seleccione un opción.'
},
address: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
payment: {
required: 'Seleccione un opción.'
},
password: {
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
},
password_confirmation: {
equalTo: 'Los datos ingresados no coinciden.',
minlength: 'Escribe mínimo {0} caracteres.',
maxlength: 'Escribe máximo {0} caracteres.'
}
},
submitHandler: function(form) {
$("button[action='checkout']").attr('disabled', true);
form.submit();
}
});
});
}); |
const path = require('path');
const defaultProject = {
projectName: 'default',
workingDir: 'C:\\Users\\yaniv\\dev\\kb',
buildCommand: 'venv\\Scripts\\activate.bat & make.bat html',
contentDir: path.join(__dirname, '..', 'content'),
homePage: 'index.html',
};
exports.loadProject = () => defaultProject;
|
import React, {Component,Suspense, lazy} from "react";
import { Switch, Redirect } from 'react-router-dom';
import Spinner from '../shared/Spinner';
import Route from './Route';
import SignIn from '../signin';
const Dashboard = lazy(() => import('../dashboard/Dashboard'));
const Buttons = lazy(() => import('../basic-ui/Buttons'));
const Dropdowns = lazy(() => import('../basic-ui/Dropdowns'));
const Typography = lazy(() => import('../basic-ui/Typography'));
const BasicElements = lazy(() => import('../form-elements/BasicElements'));
const BasicTable = lazy(() => import('../tables/BasicTable'));
const FontAwesome = lazy(() => import('../icons/FontAwesome'));
const ChartJs = lazy(() => import('../charts/ChartJs'));
const Error404 = lazy(() => import('../user-pages/Error404'));
const Error500 = lazy(() => import('../user-pages/Error500'));
const Login = lazy(() => import('../user-pages/Login'));
const Register1 = lazy(() => import('../user-pages/Register'));
const BlankPage = lazy(() => import('../user-pages/BlankPage'));
const users = lazy(() => import('../users/index'));
const users_add = lazy(() => import('../users/add'));
const tvshows = lazy(() => import('../tvshows/index'));
const tvshows_add = lazy(() => import('../tvshows/add'));
const evaluations = lazy(() => import('../evaluations/index'));
const evaluations_add = lazy(() => import('../evaluations/add'));
const evaluation_view = lazy(() => import('../evaluations/view'));
export default function Routes() {
return (
<Suspense fallback={<Spinner/>}>
<Switch>
<Route exact path="/" component={ SignIn } />
<Route path="/user-pages/register-1" component={ Register1 } />
<Route path="/dashboard" component={ Dashboard } isPrivate />
<Route path="/basic-ui/buttons" component={ Buttons } isPrivate/>
<Route path="/basic-ui/dropdowns" component={ Dropdowns } isPrivate/>
<Route path="/basic-ui/typography" component={ Typography } isPrivate/>
<Route path="/form-Elements/basic-elements" component={ BasicElements } isPrivate/>
<Route path="/tables/basic-table" component={ BasicTable } isPrivate/>
<Route path="/icons/font-awesome" component={ FontAwesome } isPrivate/>
<Route path="/charts/chart-js" component={ ChartJs } isPrivate/>
<Route path="/usuarios/todos" component={ users } isPrivate/>
<Route path="/usuarios/novo" component={ users_add } isPrivate/>
<Route path="/tvshows/index" component={ tvshows } isPrivate/>
<Route path="/tvshows/novo" component={ tvshows_add } isPrivate/>
<Route path="/evaluations/index" component={ evaluations } isPrivate/>
<Route path="/evaluations/novo" component={ evaluations_add } isPrivate/>
<Route path="/evaluations/view/" component={ evaluation_view } isPrivate/>
<Route path="/user-pages/error-404" component={ Error404 }/>
<Route path="/user-pages/error-500" component={ Error500 }/>
<Route path="/user-pages/blank-page" component={ BlankPage }/>
</Switch>
</Suspense>
);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.