code stringlengths 2 1.05M |
|---|
export default `flf2a$ 7 5 20 -1 2
rozzo.flf font by Mike Rosulek [unar2@sfa.ope.ed.gov] 1/12/95
This was based on FujiyamaBlack TrueType Font.
$$#
$$#
$$#
$$#
$$#
$$#
$$##
888$#
888$#
"8"$#
e $#
"8"$#
$#
$##
8 8$#
8 8$#
$#
$#
$#
$#
$##
d8P d8"$#
88888888888$#
d8P d8P $#
88888888888$#
e8P d8P $#
$#
$##
8 $#
d8 8e $#
C88 $#
Y8 8b $#
88D$#
"8 8P $#
8 $##
,8, / $#
"8"/ $#
/ $#
/,8, $#
/ "8" $#
$#
$##
d8b,$#
,db YP'$#
e Y8b ,$#
d8b Y8b" $#
Y88b Y8b $#
$#
$##
d8b$#
Y8P$#
,P $#
P $#
$#
$#
$##
e88$#
d888$#
e8888$#
88888$#
"8888$#
Y888$#
"88$##
88e $#
888b $#
8888e$#
88888$#
8888"$#
888P $#
88" $##
Yb 8 dP$#
\`D8K' $#
dP 8 Yb$#
$#
$#
$#
$##
$#
8 $#
88888$#
8 $#
$#
$#
$##
$#
$#
$#
d8b$#
Y8P$#
,P $#
P $##
$#
$#
888$#
$#
$#
$#
$##
$#
$#
$#
d8b$#
Y8P$#
$#
$##
d8P$#
d8P $#
d8P $#
d8P $#
d8P $#
$#
$##
e88 88e $#
d888 888b $#
C8888 8888D$#
Y888 888P $#
"88 88" $#
$#
$##
d88$#
d888$#
d"888$#
888$#
888$#
$#
$##
,8,"88e $#
" 888D$#
88P $#
,*" $#
8888888$#
$#
$##
,8,"88b,$#
" ,88P'$#
C8K $#
e \`88b,$#
"8",88P'$#
$#
$##
d 888 $#
d8 888 $#
d88 888e$#
""" 888"$#
888 $#
$#
$##
8888888$#
88 $#
"""Y88b$#
e 888$#
"8",88P$#
$#
$##
e88",8, $#
d888 " $#
C8888 88e $#
Y888 888D$#
"88 88" $#
$#
$##
888888$#
,e$#
,eP $#
,e8P $#
88P $#
$#
$##
,d8 8b, $#
"Y8 8P" $#
,d8 8b, $#
C888 888D$#
"Y8 8P" $#
$#
$##
e88 88e $#
C888 888b $#
"88 8888D$#
e 888P $#
"8",88" $#
$#
$##
d8b$#
Y8P$#
$#
d8b$#
Y8P$#
$#
$##
d8b$#
Y8P$#
$#
d8b$#
Y8P$#
,P $#
P $##
d8P$#
d8P $#
C8K $#
Y8b $#
Y8b$#
$#
$##
$#
8888888$#
$#
8888888$#
$#
$#
$##
Y8b $#
Y8b $#
D8D$#
d8P $#
d8P $#
$#
$##
,8,'88b $#
" 888D$#
88P $#
,"' $#
"8" $#
$#
$##
,e""""e, $#
e" e"""e"e$#
8 C 8 8$#
"e "*ee"*"$#
\`"eeeee" $#
$#
$##
e Y8b $#
d8b Y8b $#
d888b Y8b $#
d888888888b $#
d8888888b Y8b$#
$#
$##
888 88b,$#
888 88P'$#
888 8K $#
888 88b,$#
888 88P'$#
$#
$##
e88'Y88$#
d888 'Y$#
C8888 $#
Y888 ,d$#
"88,d88$#
$#
$##
888 88e $#
888 888b $#
888 8888D$#
888 888P $#
888 88" $#
$#
$##
888'Y88$#
888 ,'Y$#
888C8 $#
888 ",d$#
888,d88$#
$#
$##
888'Y88$#
888 ,'Y$#
888C8 $#
888 " $#
888 $#
$#
$##
e88'Y88 $#
d888 'Y $#
C8888 eeee$#
Y888 888P$#
"88 88" $#
$#
$##
888 888$#
888 888$#
8888888$#
888 888$#
888 888$#
$#
$##
888$#
888$#
888$#
888$#
888$#
$#
$##
888$#
888$#
888$#
e 88P$#
"8",P' $#
$#
$##
888 88P$#
888 8P $#
888 K $#
888 8b $#
888 88b$#
$#
$##
888 $#
888 $#
888 $#
888 ,d$#
888,d88$#
$#
$##
e e $#
d8b d8b $#
e Y8b Y8b $#
d8b Y8b Y8b $#
d888b Y8b Y8b$#
$#
$##
Y88b Y88$#
Y88b Y8$#
b Y88b Y$#
8b Y88b $#
88b Y88b$#
$#
$##
e88 88e $#
d888 888b $#
C8888 8888D$#
Y888 888P $#
"88 88" $#
$#
$##
888 88e $#
888 888D$#
888 88" $#
888 $#
888 $#
$#
$##
e88 88e $#
d888 888b $#
C8888 8888D$#
Y888 888P $#
"88 88" $#
b $#
8b, $##
888 88e $#
888 888D$#
888 88" $#
888 b, $#
888 88b,$#
$#
$##
dP"8$#
C8b Y$#
Y8b $#
b Y8D$#
8edP $#
$#
$##
88P'888'Y88$#
P' 888 'Y$#
888 $#
888 $#
888 $#
$#
$##
8888 8888$#
8888 8888$#
8888 8888$#
8888 8888$#
'Y88 88P'$#
$#
$##
Y8b Y88888P$#
Y8b Y888P $#
Y8b Y8P $#
Y8b Y $#
Y8P $#
$#
$##
Y8b Y8b Y888P$#
Y8b Y8b Y8P $#
Y8b Y8b Y $#
Y8b Y8b $#
Y8P Y $#
$#
$##
Y8b Y8P$#
Y8b Y $#
Y8b $#
e Y8b $#
d8b Y8b$#
$#
$##
Y88b Y8P$#
Y88b Y $#
Y88b $#
888 $#
888 $#
$#
$##
8P d8P$#
P d8P $#
d8P d$#
d8P d8$#
d8P d88$#
$#
$##
8888$#
88 $#
88 $#
88 $#
88 $#
88 $#
8888$##
d8P$#
d8P $#
d8P $#
d8P $#
d8P $#
$#
$##
8888$#
88$#
88$#
88$#
88$#
88$#
8888$##
d8b $#
dP Yb$#
$#
$#
$#
$#
$##
$#
$#
$#
$#
$#
888$#
$##
Y88$#
Y8$#
Y$#
$#
$#
$#
$##
$#
,"Y88b$#
"8" 888$#
,ee 888$#
"88 888$#
$#
$##
888 $#
888 88e $#
888 888b$#
888 888P$#
888 88" $#
$#
$##
$#
e88'888$#
d888 '8$#
Y888 ,$#
"88,e8'$#
$#
$##
888$#
e88 888$#
d888 888$#
Y888 888$#
"88 888$#
$#
$##
$#
,e e, $#
d88 88b$#
888 ,$#
"YeeP"$#
$#
$##
dP,e,$#
8b " $#
888888$#
888 $#
888 $#
$#
$##
$#
e88 888$#
d888 888$#
Y888 888$#
"88 888$#
, 88P$#
"8",P" $##
888 $#
888 ee $#
888 88b$#
888 888$#
888 888$#
$#
$##
,e,$#
" $#
888$#
888$#
888$#
$#
$##
,e,$#
" $#
888$#
888$#
888$#
88P$#
8" $##
888 $#
888 ee$#
888 P $#
888 b $#
888 8b$#
$#
$##
888$#
888$#
888$#
888$#
888$#
$#
$##
$#
888 888 8e $#
888 888 88b$#
888 888 888$#
888 888 888$#
$#
$##
$#
888 8e $#
888 88b$#
888 888$#
888 888$#
$#
$##
$#
e88 88e $#
d888 888b$#
Y888 888P$#
"88 88" $#
$#
$##
$#
888 88e $#
888 888b$#
888 888P$#
888 88" $#
888 $#
888 $##
$#
e88 888$#
d888 888$#
Y888 888$#
"88 888$#
888$#
888$##
$#
888,8,$#
888 " $#
888 $#
888 $#
$#
$##
$#
dP"Y$#
C88b $#
Y88D$#
d,dP $#
$#
$##
d8 $#
d88 $#
d88888$#
888 $#
888 $#
$#
$##
$#
8888 8888$#
8888 8888$#
Y888 888P$#
"88 88" $#
$#
$##
$#
Y8b Y888P$#
Y8b Y8P $#
Y8b " $#
Y8P $#
$#
$##
$#
Y8b Y8b Y888P$#
Y8b Y8b Y8P $#
Y8b Y8b " $#
YP Y8P $#
$#
$##
$#
Y8b Y8Y$#
Y8b Y $#
e Y8b $#
d8b Y8b $#
$#
$##
$#
Y8b Y888P$#
Y8b Y8P $#
Y8b Y $#
888 $#
888 $#
888 $##
$#
8P d8P$#
P d8P $#
d8P d$#
d8P d8$#
$#
$##
,888$#
88 $#
e8P $#
C8K $#
"8b $#
88 $#
"888$##
88$#
88$#
88$#
88$#
88$#
88$#
88$##
888, $#
88 $#
Y8 $#
D8D$#
d8 $#
88 $#
888" $##
,d8b,d8$#
8P"Y8P"$#
$#
$#
$#
$#
$##
e e Y8b e $#
"8"d8b Y8b"8"$#
d888b Y8b $#
d888888888b $#
d8888888b Y8b$#
$#
$##
e e88 88e e $#
"8"d888 888b"8"$#
C8888 8888D $#
Y888 888P $#
"88 88" $#
$#
$##
e 8888 8888 e $#
"8" 8888 8888 "8"$#
8888 8888 $#
Y888 888P $#
"88 88" $#
$#
$##
e e $#
"8","Y88b"8"$#
"8" 888 $#
,ee 888 $#
"88 888 $#
$#
$##
$#
e e88 88e e $#
"8"d888 888b"8"$#
Y888 888P $#
"88 88" $#
$#
$##
e e $#
"8"8888 8888"8"$#
8888 8888 $#
Y888 888P $#
"88 88" $#
$#
$##
$#
dP"Y$#
C88b $#
Y88D$#
d,dP $#
$#
$##
` |
/* eslint no-multi-spaces: 0 */
const moment = require("moment-timezone");
const data = require("../../configs/data/weatherforecast_data.json");
describe("Functions module weatherforecast", function () {
beforeAll(function () {
Module = {};
config = {};
Module.definitions = {};
Module.register = function (name, moduleDefinition) {
Module.definitions[name] = moduleDefinition;
};
require("../../../modules/default/weatherforecast/weatherforecast.js");
Module.definitions.weatherforecast.config = {};
});
describe("roundValue", function () {
describe("this.config.roundTemp is true", function () {
beforeAll(function () {
Module.definitions.weatherforecast.config.roundTemp = true;
});
const values = [
// index 0 value
// index 1 expect
[1, "1"],
[1.0, "1"],
[1.02, "1"],
[10.12, "10"],
[2.0, "2"],
["2.12", "2"],
[10.1, "10"]
];
values.forEach((value) => {
it(`for ${value[0]} should be return ${value[1]}`, function () {
expect(Module.definitions.weatherforecast.roundValue(value[0])).toBe(value[1]);
});
});
});
describe("this.config.roundTemp is false", function () {
beforeAll(function () {
Module.definitions.weatherforecast.config.roundTemp = false;
});
const values = [
// index 0 value
// index 1 expect
[1, "1.0"],
[1.0, "1.0"],
[1.02, "1.0"],
[10.12, "10.1"],
[2.0, "2.0"],
["2.12", "2.1"],
[10.1, "10.1"],
[10.1, "10.1"]
];
values.forEach((value) => {
it(`for ${value[0]} should be return ${value[1]}`, function () {
expect(Module.definitions.weatherforecast.roundValue(value[0])).toBe(value[1]);
});
});
});
});
describe("forecastIcons", function () {
Log = {
error: function () {}
};
let originalLocale;
let originalTimeZone;
beforeAll(function () {
originalLocale = moment.locale();
originalTimeZone = moment.tz.guess();
moment.locale("hi");
moment.tz.setDefault("Europe/Warsaw");
});
describe("forecastIcons sunset specified", function () {
beforeAll(function () {
Module.definitions.weatherforecast.Log = {};
Module.definitions.weatherforecast.forecast = [];
Module.definitions.weatherforecast.show = Module.definitions.weatherforecast.updateDom = function () {};
Module.definitions.weatherforecast.config = Module.definitions.weatherforecast.defaults;
});
it(`returns correct icons with sunset time`, function () {
Module.definitions.weatherforecast.processWeather(data.withSunset, moment);
let forecastData = Module.definitions.weatherforecast.forecast;
expect(forecastData.length).toBe(4);
expect(forecastData[2].icon).toBe("wi-rain");
});
});
describe("forecastIcons sunset not specified", function () {
beforeAll(function () {
Module.definitions.weatherforecast.forecast = [];
});
it(`returns correct icons with out sunset time`, function () {
Module.definitions.weatherforecast.processWeather(data.withoutSunset, moment);
let forecastData = Module.definitions.weatherforecast.forecast;
expect(forecastData.length).toBe(4);
expect(forecastData[2].icon).toBe("wi-rain");
});
});
afterAll(function () {
moment.locale(originalLocale);
moment.tz.setDefault(originalTimeZone);
});
});
});
|
import RSVP from 'ember-runtime/ext/rsvp';
import Controller from 'ember-runtime/controllers/controller';
import Route from 'ember-routing/system/route';
import run from 'ember-metal/run_loop';
import { compile } from 'ember-template-compiler/tests/utils/helpers';
import Application from 'ember-application/system/application';
import Engine from 'ember-application/system/engine';
import jQuery from 'ember-views/system/jquery';
import NoneLocation from 'ember-routing/location/none_location';
import DefaultResolver from 'ember-application/system/resolver';
import { setTemplates, set as setTemplate } from 'ember-templates/template_registry';
import isEnabled from 'ember-metal/features';
let Router, App, templates, router, container, registry, counter;
function step(expectedValue, description) {
equal(counter, expectedValue, 'Step ' + expectedValue + ': ' + description);
counter++;
}
function bootApplication(startingURL) {
for (let name in templates) {
setTemplate(name, compile(templates[name]));
}
if (startingURL) {
NoneLocation.reopen({
path: startingURL
});
}
startingURL = startingURL || '';
router = container.lookup('router:main');
run(App, 'advanceReadiness');
}
QUnit.module('Loading/Error Substates', {
setup() {
counter = 1;
run(function() {
App = Application.create({
name: 'App',
rootElement: '#qunit-fixture',
// fake a modules resolver
Resolver: DefaultResolver.extend({ moduleBasedResolver: true })
});
App.deferReadiness();
App.Router.reopen({
location: 'none'
});
Router = App.Router;
container = App.__container__;
registry = App.__registry__;
templates = {
application: '<div id="app">{{outlet}}</div>',
index: 'INDEX',
loading: 'LOADING',
bro: 'BRO',
sis: 'SIS'
};
});
},
teardown() {
run(function() {
App.destroy();
App = null;
setTemplates({});
});
NoneLocation.reopen({
path: ''
});
}
});
QUnit.test('Slow promise from a child route of application enters nested loading state', function() {
let broModel = {};
let broDeferred = RSVP.defer();
Router.map(function() {
this.route('bro');
});
App.ApplicationRoute = Route.extend({
setupController() {
step(2, 'ApplicationRoute#setup');
}
});
App.BroRoute = Route.extend({
model() {
step(1, 'BroRoute#model');
return broDeferred.promise;
}
});
bootApplication('/bro');
equal(jQuery('#app', '#qunit-fixture').text(), 'LOADING', 'The Loading template is nested in application template\'s outlet');
run(broDeferred, 'resolve', broModel);
equal(jQuery('#app', '#qunit-fixture').text(), 'BRO', 'bro template has loaded and replaced loading template');
});
QUnit.test('Slow promises waterfall on startup', function() {
expect(7);
let grandmaDeferred = RSVP.defer();
let sallyDeferred = RSVP.defer();
Router.map(function() {
this.route('grandma', function() {
this.route('mom', { resetNamespace: true }, function() {
this.route('sally');
});
});
});
templates.grandma = 'GRANDMA {{outlet}}';
templates.mom = 'MOM {{outlet}}';
templates['mom/loading'] = 'MOMLOADING';
templates['mom/sally'] = 'SALLY';
App.GrandmaRoute = Route.extend({
model() {
step(1, 'GrandmaRoute#model');
return grandmaDeferred.promise;
}
});
App.MomRoute = Route.extend({
model() {
step(2, 'Mom#model');
return {};
}
});
App.MomSallyRoute = Route.extend({
model() {
step(3, 'SallyRoute#model');
return sallyDeferred.promise;
},
setupController() {
step(4, 'SallyRoute#setupController');
}
});
bootApplication('/grandma/mom/sally');
equal(jQuery('#app', '#qunit-fixture').text(), 'LOADING', 'The Loading template is nested in application template\'s outlet');
run(grandmaDeferred, 'resolve', {});
equal(jQuery('#app', '#qunit-fixture').text(), 'GRANDMA MOM MOMLOADING', 'Mom\'s child loading route is displayed due to sally\'s slow promise');
run(sallyDeferred, 'resolve', {});
equal(jQuery('#app', '#qunit-fixture').text(), 'GRANDMA MOM SALLY', 'Sally template displayed');
});
QUnit.test('ApplicationRoute#currentPath reflects loading state path', function() {
expect(4);
let momDeferred = RSVP.defer();
Router.map(function() {
this.route('grandma', function() {
this.route('mom');
});
});
templates.grandma = 'GRANDMA {{outlet}}';
templates['grandma/loading'] = 'GRANDMALOADING';
templates['grandma/mom'] = 'MOM';
App.GrandmaMomRoute = Route.extend({
model() {
return momDeferred.promise;
}
});
bootApplication('/grandma/mom');
equal(jQuery('#app', '#qunit-fixture').text(), 'GRANDMA GRANDMALOADING');
let appController = container.lookup('controller:application');
equal(appController.get('currentPath'), 'grandma.loading', 'currentPath reflects loading state');
run(momDeferred, 'resolve', {});
equal(jQuery('#app', '#qunit-fixture').text(), 'GRANDMA MOM');
equal(appController.get('currentPath'), 'grandma.mom', 'currentPath reflects final state');
});
QUnit.test('Slow promises returned from ApplicationRoute#model don\'t enter LoadingRoute', function() {
expect(2);
let appDeferred = RSVP.defer();
App.ApplicationRoute = Route.extend({
model() {
return appDeferred.promise;
}
});
App.LoadingRoute = Route.extend({
setupController() {
ok(false, 'shouldn\'t get here');
}
});
bootApplication();
equal(jQuery('#app', '#qunit-fixture').text(), '', 'nothing has been rendered yet');
run(appDeferred, 'resolve', {});
equal(jQuery('#app', '#qunit-fixture').text(), 'INDEX');
});
QUnit.test('Don\'t enter loading route unless either route or template defined', function() {
delete templates.loading;
expect(2);
let indexDeferred = RSVP.defer();
App.ApplicationController = Controller.extend();
App.IndexRoute = Route.extend({
model() {
return indexDeferred.promise;
}
});
bootApplication();
let appController = container.lookup('controller:application');
ok(appController.get('currentPath') !== 'loading', 'loading state not entered');
run(indexDeferred, 'resolve', {});
equal(jQuery('#app', '#qunit-fixture').text(), 'INDEX');
});
QUnit.test('Enter loading route if only LoadingRoute defined', function() {
delete templates.loading;
expect(4);
let indexDeferred = RSVP.defer();
App.IndexRoute = Route.extend({
model() {
step(1, 'IndexRoute#model');
return indexDeferred.promise;
}
});
App.LoadingRoute = Route.extend({
setupController() {
step(2, 'LoadingRoute#setupController');
}
});
bootApplication();
let appController = container.lookup('controller:application');
equal(appController.get('currentPath'), 'loading', 'loading state entered');
run(indexDeferred, 'resolve', {});
equal(jQuery('#app', '#qunit-fixture').text(), 'INDEX');
});
QUnit.test('Enter child loading state of pivot route', function() {
expect(4);
let deferred = RSVP.defer();
Router.map(function() {
this.route('grandma', function() {
this.route('mom', { resetNamespace: true }, function() {
this.route('sally');
});
this.route('smells');
});
});
templates['grandma/loading'] = 'GMONEYLOADING';
App.ApplicationController = Controller.extend();
App.MomSallyRoute = Route.extend({
setupController() {
step(1, 'SallyRoute#setupController');
}
});
App.GrandmaSmellsRoute = Route.extend({
model() {
return deferred.promise;
}
});
bootApplication('/grandma/mom/sally');
let appController = container.lookup('controller:application');
equal(appController.get('currentPath'), 'grandma.mom.sally', 'Initial route fully loaded');
run(router, 'transitionTo', 'grandma.smells');
equal(appController.get('currentPath'), 'grandma.loading', 'in pivot route\'s child loading state');
run(deferred, 'resolve', {});
equal(appController.get('currentPath'), 'grandma.smells', 'Finished transition');
});
QUnit.test('Loading actions bubble to root, but don\'t enter substates above pivot', function() {
expect(6);
delete templates.loading;
let sallyDeferred = RSVP.defer();
let smellsDeferred = RSVP.defer();
Router.map(function() {
this.route('grandma', function() {
this.route('mom', { resetNamespace: true }, function() {
this.route('sally');
});
this.route('smells');
});
});
App.ApplicationController = Controller.extend();
App.ApplicationRoute = Route.extend({
actions: {
loading(transition, route) {
ok(true, 'loading action received on ApplicationRoute');
}
}
});
App.MomSallyRoute = Route.extend({
model() {
return sallyDeferred.promise;
}
});
App.GrandmaSmellsRoute = Route.extend({
model() {
return smellsDeferred.promise;
}
});
bootApplication('/grandma/mom/sally');
let appController = container.lookup('controller:application');
ok(!appController.get('currentPath'), 'Initial route fully loaded');
run(sallyDeferred, 'resolve', {});
equal(appController.get('currentPath'), 'grandma.mom.sally', 'transition completed');
run(router, 'transitionTo', 'grandma.smells');
equal(appController.get('currentPath'), 'grandma.mom.sally', 'still in initial state because the only loading state is above the pivot route');
run(smellsDeferred, 'resolve', {});
equal(appController.get('currentPath'), 'grandma.smells', 'Finished transition');
});
QUnit.test('Default error event moves into nested route', function() {
expect(6);
templates['grandma'] = 'GRANDMA {{outlet}}';
templates['grandma/error'] = 'ERROR: {{model.msg}}';
Router.map(function() {
this.route('grandma', function() {
this.route('mom', { resetNamespace: true }, function() {
this.route('sally');
});
});
});
App.ApplicationController = Controller.extend();
App.MomSallyRoute = Route.extend({
model() {
step(1, 'MomSallyRoute#model');
return RSVP.reject({
msg: 'did it broke?'
});
},
actions: {
error() {
step(2, 'MomSallyRoute#actions.error');
return true;
}
}
});
throws(function() {
bootApplication('/grandma/mom/sally');
}, function(err) { return err.msg === 'did it broke?';});
step(3, 'App finished booting');
equal(jQuery('#app', '#qunit-fixture').text(), 'GRANDMA ERROR: did it broke?', 'error bubbles');
let appController = container.lookup('controller:application');
equal(appController.get('currentPath'), 'grandma.error', 'Initial route fully loaded');
});
QUnit.test('Error events that aren\'t bubbled don\t throw application assertions', function() {
expect(2);
templates['grandma'] = 'GRANDMA {{outlet}}';
Router.map(function() {
this.route('grandma', function() {
this.route('mom', { resetNamespace: true }, function() {
this.route('sally');
});
});
});
App.ApplicationController =
Controller.extend();
App.MomSallyRoute = Route.extend({
model() {
step(1, 'MomSallyRoute#model');
return RSVP.reject({
msg: 'did it broke?'
});
},
actions: {
error(err) {
equal(err.msg, 'did it broke?');
return false;
}
}
});
bootApplication('/grandma/mom/sally');
});
QUnit.test('Non-bubbled errors that re-throw aren\'t swallowed', function() {
expect(2);
templates['grandma'] = 'GRANDMA {{outlet}}';
Router.map(function() {
this.route('grandma', function() {
this.route('mom', { resetNamespace: true }, function() {
this.route('sally');
});
});
});
App.ApplicationController = Controller.extend();
App.MomSallyRoute = Route.extend({
model() {
step(1, 'MomSallyRoute#model');
return RSVP.reject({
msg: 'did it broke?'
});
},
actions: {
error(err) {
// returns undefined which is falsey
throw err;
}
}
});
throws(function() {
bootApplication('/grandma/mom/sally');
}, function(err) { return err.msg === 'did it broke?';});
});
QUnit.test('Handled errors that re-throw aren\'t swallowed', function() {
expect(4);
let handledError;
templates['grandma'] = 'GRANDMA {{outlet}}';
Router.map(function() {
this.route('grandma', function() {
this.route('mom', { resetNamespace: true }, function() {
this.route('sally');
this.route('this-route-throws');
});
});
});
App.ApplicationController = Controller.extend();
App.MomSallyRoute = Route.extend({
model() {
step(1, 'MomSallyRoute#model');
return RSVP.reject({
msg: 'did it broke?'
});
},
actions: {
error(err) {
step(2, 'MomSallyRoute#error');
handledError = err;
this.transitionTo('mom.this-route-throws');
// Marks error as handled
return false;
}
}
});
App.MomThisRouteThrowsRoute = Route.extend({
model() {
step(3, 'MomThisRouteThrows#model');
throw handledError;
}
});
throws(function() {
bootApplication('/grandma/mom/sally');
}, function(err) { return err.msg === 'did it broke?'; });
});
QUnit.test('Handled errors that bubble can be handled at a higher level', function() {
expect(4);
let handledError;
templates['grandma'] = 'GRANDMA {{outlet}}';
Router.map(function() {
this.route('grandma', function() {
this.route('mom', { resetNamespace: true }, function() {
this.route('sally');
});
});
});
App.ApplicationController = Controller.extend();
App.MomRoute = Route.extend({
actions: {
error(err) {
step(3, 'MomRoute#error');
equal(err, handledError, 'error handled and rebubbled is handleable at heigher route');
}
}
});
App.MomSallyRoute = Route.extend({
model() {
step(1, 'MomSallyRoute#model');
return RSVP.reject({
msg: 'did it broke?'
});
},
actions: {
error(err) {
step(2, 'MomSallyRoute#error');
handledError = err;
return true;
}
}
});
bootApplication('/grandma/mom/sally');
});
QUnit.test('errors that are bubbled are thrown at a higher level if not handled', function() {
expect(3);
let handledError;
templates['grandma'] = 'GRANDMA {{outlet}}';
Router.map(function() {
this.route('grandma', function() {
this.route('mom', { resetNamespace: true }, function() {
this.route('sally');
});
});
});
App.ApplicationController = Controller.extend();
App.MomSallyRoute = Route.extend({
model() {
step(1, 'MomSallyRoute#model');
return RSVP.reject({
msg: 'did it broke?'
});
},
actions: {
error(err) {
step(2, 'MomSallyRoute#error');
handledError = err;
return true;
}
}
});
throws(
function() {
bootApplication('/grandma/mom/sally');
},
function(err) {
return err.msg === 'did it broke?';
},
'Correct error was thrown'
);
});
QUnit.test('Handled errors that are thrown through rejection aren\'t swallowed', function() {
expect(4);
let handledError;
templates['grandma'] = 'GRANDMA {{outlet}}';
Router.map(function() {
this.route('grandma', function() {
this.route('mom', { resetNamespace: true }, function() {
this.route('sally');
this.route('this-route-throws');
});
});
});
App.ApplicationController = Controller.extend();
App.MomSallyRoute = Route.extend({
model() {
step(1, 'MomSallyRoute#model');
return RSVP.reject({
msg: 'did it broke?'
});
},
actions: {
error(err) {
step(2, 'MomSallyRoute#error');
handledError = err;
this.transitionTo('mom.this-route-throws');
// Marks error as handled
return false;
}
}
});
App.MomThisRouteThrowsRoute = Route.extend({
model() {
step(3, 'MomThisRouteThrows#model');
return RSVP.reject(handledError);
}
});
throws(function() {
bootApplication('/grandma/mom/sally');
}, function(err) { return err.msg === 'did it broke?'; });
});
QUnit.test('Setting a query param during a slow transition should work', function() {
let deferred = RSVP.defer();
Router.map(function() {
this.route('grandma', { path: '/grandma/:seg' }, function() { });
});
templates['grandma/loading'] = 'GMONEYLOADING';
App.ApplicationController = Controller.extend();
App.IndexRoute = Route.extend({
beforeModel: function() {
this.transitionTo('grandma', 1);
}
});
App.GrandmaRoute = Route.extend({
queryParams: {
test: { defaultValue: 1 }
}
});
App.GrandmaIndexRoute = Route.extend({
model() {
return deferred.promise;
}
});
bootApplication('/');
let appController = container.lookup('controller:application');
let grandmaController = container.lookup('controller:grandma');
equal(appController.get('currentPath'), 'grandma.loading', 'Initial route should be loading');
run(function() {
grandmaController.set('test', 3);
});
equal(appController.get('currentPath'), 'grandma.loading', 'Route should still be loading');
equal(grandmaController.get('test'), 3, 'Controller query param value should have changed');
run(deferred, 'resolve', {});
equal(appController.get('currentPath'), 'grandma.index', 'Transition should be complete');
});
QUnit.test('Slow promises returned from ApplicationRoute#model enter ApplicationLoadingRoute if present', function() {
expect(2);
let appDeferred = RSVP.defer();
App.ApplicationRoute = Route.extend({
model() {
return appDeferred.promise;
}
});
let loadingRouteEntered = false;
App.ApplicationLoadingRoute = Route.extend({
setupController() {
loadingRouteEntered = true;
}
});
bootApplication();
ok(loadingRouteEntered, 'ApplicationLoadingRoute was entered');
run(appDeferred, 'resolve', {});
equal(jQuery('#app', '#qunit-fixture').text(), 'INDEX');
});
QUnit.test('Slow promises returned from ApplicationRoute#model enter application_loading if template present', function() {
expect(3);
templates['application_loading'] = '<div id="toplevel-loading">TOPLEVEL LOADING</div>';
let appDeferred = RSVP.defer();
App.ApplicationRoute = Route.extend({
model() {
return appDeferred.promise;
}
});
bootApplication();
equal(jQuery('#qunit-fixture #toplevel-loading').text(), 'TOPLEVEL LOADING');
run(appDeferred, 'resolve', {});
equal(jQuery('#toplevel-loading', '#qunit-fixture').length, 0, 'top-level loading View has been entirely removed from DOM');
equal(jQuery('#app', '#qunit-fixture').text(), 'INDEX');
});
QUnit.test('Default error event moves into nested route, prioritizing more specifically named error route', function() {
expect(6);
templates['grandma'] = 'GRANDMA {{outlet}}';
templates['grandma/error'] = 'ERROR: {{model.msg}}';
templates['grandma/mom_error'] = 'MOM ERROR: {{model.msg}}';
Router.map(function() {
this.route('grandma', function() {
this.route('mom', { resetNamespace: true }, function() {
this.route('sally');
});
});
});
App.ApplicationController = Controller.extend();
App.MomSallyRoute = Route.extend({
model() {
step(1, 'MomSallyRoute#model');
return RSVP.reject({
msg: 'did it broke?'
});
},
actions: {
error() {
step(2, 'MomSallyRoute#actions.error');
return true;
}
}
});
throws(function() {
bootApplication('/grandma/mom/sally');
}, function(err) { return err.msg === 'did it broke?'; });
step(3, 'App finished booting');
equal(jQuery('#app', '#qunit-fixture').text(), 'GRANDMA MOM ERROR: did it broke?', 'the more specifically-named mom error substate was entered over the other error route');
let appController = container.lookup('controller:application');
equal(appController.get('currentPath'), 'grandma.mom_error', 'Initial route fully loaded');
});
QUnit.test('Prioritized substate entry works with preserved-namespace nested routes', function() {
expect(2);
templates['foo/bar_loading'] = 'FOOBAR LOADING';
templates['foo/bar/index'] = 'YAY';
Router.map(function() {
this.route('foo', function() {
this.route('foo.bar', { path: '/bar', resetNamespace: true }, function() {
});
});
});
App.ApplicationController = Controller.extend();
let deferred = RSVP.defer();
App.FooBarRoute = Route.extend({
model() {
return deferred.promise;
}
});
bootApplication('/foo/bar');
equal(jQuery('#app', '#qunit-fixture').text(), 'FOOBAR LOADING', 'foo.bar_loading was entered (as opposed to something like foo/foo/bar_loading)');
run(deferred, 'resolve');
equal(jQuery('#app', '#qunit-fixture').text(), 'YAY');
});
QUnit.test('Prioritized loading substate entry works with preserved-namespace nested routes', function() {
expect(2);
templates['foo/bar_loading'] = 'FOOBAR LOADING';
templates['foo/bar'] = 'YAY';
Router.map(function() {
this.route('foo', function() {
this.route('bar');
});
});
App.ApplicationController = Controller.extend();
let deferred = RSVP.defer();
App.FooBarRoute = Route.extend({
model() {
return deferred.promise;
}
});
bootApplication('/foo/bar');
equal(jQuery('#app', '#qunit-fixture').text(), 'FOOBAR LOADING', 'foo.bar_loading was entered (as opposed to something like foo/foo/bar_loading)');
run(deferred, 'resolve');
equal(jQuery('#app', '#qunit-fixture').text(), 'YAY');
});
QUnit.test('Prioritized error substate entry works with preserved-namespace nested routes', function() {
expect(2);
templates['foo/bar_error'] = 'FOOBAR ERROR: {{model.msg}}';
templates['foo/bar'] = 'YAY';
Router.map(function() {
this.route('foo', function() {
this.route('bar');
});
});
App.ApplicationController = Controller.extend();
App.FooBarRoute = Route.extend({
model() {
return RSVP.reject({
msg: 'did it broke?'
});
}
});
throws(function() {
bootApplication('/foo/bar');
}, function(err) { return err.msg === 'did it broke?'; });
equal(jQuery('#app', '#qunit-fixture').text(), 'FOOBAR ERROR: did it broke?', 'foo.bar_error was entered (as opposed to something like foo/foo/bar_error)');
});
QUnit.test('Prioritized loading substate entry works with auto-generated index routes', function() {
expect(2);
templates['foo/index_loading'] = 'FOO LOADING';
templates['foo/index'] = 'YAY';
templates['foo'] = '{{outlet}}';
Router.map(function() {
this.route('foo', function() {
this.route('bar');
});
});
App.ApplicationController = Controller.extend();
let deferred = RSVP.defer();
App.FooIndexRoute = Route.extend({
model() {
return deferred.promise;
}
});
App.FooRoute = Route.extend({
model() {
return true;
}
});
bootApplication('/foo');
equal(jQuery('#app', '#qunit-fixture').text(), 'FOO LOADING', 'foo.index_loading was entered');
run(deferred, 'resolve');
equal(jQuery('#app', '#qunit-fixture').text(), 'YAY');
});
QUnit.test('Prioritized error substate entry works with auto-generated index routes', function() {
expect(2);
templates['foo/index_error'] = 'FOO ERROR: {{model.msg}}';
templates['foo/index'] = 'YAY';
templates['foo'] = '{{outlet}}';
Router.map(function() {
this.route('foo', function() {
this.route('bar');
});
});
App.ApplicationController = Controller.extend();
App.FooIndexRoute = Route.extend({
model() {
return RSVP.reject({
msg: 'did it broke?'
});
}
});
App.FooRoute = Route.extend({
model() {
return true;
}
});
throws(() => bootApplication('/foo'),
err => err.msg === 'did it broke?');
equal(jQuery('#app', '#qunit-fixture').text(), 'FOO ERROR: did it broke?', 'foo.index_error was entered');
});
QUnit.test('Rejected promises returned from ApplicationRoute transition into top-level application_error', function() {
expect(3);
templates['application_error'] = '<p id="toplevel-error">TOPLEVEL ERROR: {{model.msg}}</p>';
let reject = true;
App.ApplicationRoute = Route.extend({
model() {
if (reject) {
return RSVP.reject({ msg: 'BAD NEWS BEARS' });
} else {
return {};
}
}
});
throws(() => bootApplication(),
err => err.msg === 'BAD NEWS BEARS');
equal(jQuery('#toplevel-error', '#qunit-fixture').text(), 'TOPLEVEL ERROR: BAD NEWS BEARS');
reject = false;
run(router, 'transitionTo', 'index');
equal(jQuery('#app', '#qunit-fixture').text(), 'INDEX');
});
if (isEnabled('ember-application-engines')) {
QUnit.test('Slow Promise from an Engine application route enters the mounts loading state', function() {
expect(1);
templates['news/blog_loading'] = 'BLOG LOADING';
// Register engine
let BlogEngine = Engine.extend();
registry.register('engine:blog', BlogEngine);
// Register engine route map
let BlogMap = function() {};
registry.register('route-map:blog', BlogMap);
Router.map(function() {
this.route('news', function() {
this.mount('blog');
});
});
let deferred = RSVP.defer();
let BlogRoute = Route.extend({
model() {
return deferred.promise;
}
});
var blog = container.lookup('engine:blog');
blog.register('route:application', BlogRoute);
bootApplication('/news/blog');
equal(jQuery('#app', '#qunit-fixture').text(), 'BLOG LOADING', 'news/blog_loading was entered');
run(deferred, 'resolve');
});
QUnit.test('Rejected Promise from an Engine application route enters the mounts error state', function() {
expect(1);
templates['news/blog_error'] = 'BLOG ERROR';
// Register engine
let BlogEngine = Engine.extend();
registry.register('engine:blog', BlogEngine);
// Register engine route map
let BlogMap = function() {};
registry.register('route-map:blog', BlogMap);
Router.map(function() {
this.route('news', function() {
this.mount('blog');
});
});
let BlogRoute = Route.extend({
model() {
return RSVP.Promise.reject();
}
});
var blog = container.lookup('engine:blog');
blog.register('route:application', BlogRoute);
bootApplication('/news/blog');
equal(jQuery('#app', '#qunit-fixture').text(), 'BLOG ERROR', 'news/blog_loading was entered');
});
}
|
import './shim';
import { AppRegistry } from 'react-native';
import App from './App';
AppRegistry.registerComponent('Lumino', () => App);
|
(function(window) {
})(window);
|
'use strict';
var getClassName = Y.ClassNameManager.getClassName;
Y.App.CLASS_NAMES = {
app : getClassName('rocket'),
views: getClassName('rocket', 'views')
};
Y.Rocket = Y.App;
|
/*
* grunt-contrib-handlebars
* http://gruntjs.com/
*
* Copyright (c) 2015 Tim Branyen, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>'
],
options: {
jshintrc: '.jshintrc'
}
},
jscs: {
src: ['tasks/**/*.js', 'test/*.js', 'Gruntfile.js'],
options: {
config: '.jscsrc'
}
},
// Before generating any new files, remove any previously-created files.
clean: {
tests: ['tmp']
},
// Configuration to be run (and then tested).
handlebars: {
compile: {
options: {
namespace: 'JST'
},
files: {
'tmp/handlebars.js': ['test/fixtures/_partial.hbs', 'test/fixtures/one.hbs']
}
},
compileNode: {
options: {
namespace: 'JST',
node: true
},
files: {
'tmp/handlebars-node.js': ['test/fixtures/_partial.hbs', 'test/fixtures/one.hbs']
}
},
nowrap: {
options: {
namespace: 'JST',
wrapped: false
},
files: {
'tmp/handlebarsnowrap.js': ['test/fixtures/_partial.hbs', 'test/fixtures/one.hbs']
}
},
uglyfile: {
files: {
'tmp/uglyfile.js': ['test/fixtures/*bad-filename*']
}
},
ns_nested: {
options: {
namespace: 'MyApp.JST.Main'
},
files: {
'tmp/ns_nested.js': ['test/fixtures/basic.hbs']
}
},
ns_nested_this: {
options: {
namespace: 'this.MyApp.JST.Main'
},
files: {
'tmp/ns_nested_this.js': ['test/fixtures/basic.hbs']
}
},
no_namespace: {
options: {
namespace: false
},
files: {
'tmp/no_namespace.js': ['test/fixtures/basic.hbs']
}
},
processcontent: {
options: {
processContent: function(content) {
content = content.replace(/^[\x20\t]+/mg, '').replace(/[\x20\t]+$/mg, '');
content = content.replace(/^[\r\n]+/, '').replace(/[\r\n]+$/, '');
return content;
}
},
files: {
'tmp/processcontent.js': ['test/fixtures/has-spaces.hbs']
}
},
process_ast: {
options: {
processAST: function(ast) {
ast.body.forEach(function(statement, i) {
if (statement.type === 'PartialStatement') {
ast.body[i] = {type: 'ContentStatement', value: 'Fooville'};
}
});
return ast;
}
},
files: {
'tmp/process_ast.js': ['test/fixtures/one.hbs']
}
},
amd_compile: {
options: {
amd: true
},
files: {
'tmp/amd_compile.js': ['test/fixtures/amd.html']
}
},
amd_compile_direct: {
options: {
amd: true,
namespace: false
},
files: {
'tmp/amd_compile_direct.js': ['test/fixtures/amd.html']
}
},
amd_compile_string_path: {
options: {
amd: 'lib/handlebars',
namespace: false
},
files: {
'tmp/amd_compile_string_path.js': ['test/fixtures/amd.html']
}
},
amd_compile_string_deps: {
options: {
amd: 'handlebars\', \'handlebars.helpers',
namespace: false
},
files: {
'tmp/amd_compile_string_deps.js': ['test/fixtures/amd.html']
}
},
amd_compile_array: {
options: {
amd: ['handlebars', 'handlebars.helpers'],
namespace: false
},
files: {
'tmp/amd_compile_array.js': ['test/fixtures/amd.html']
}
},
amd_namespace: {
options: {
amd: ['handlebars', 'handlebars.helpers'],
namespace: 'foo'
},
files: {
'tmp/amd_namespace.js': ['test/fixtures/amd.html']
}
},
amd_partials_use_namespace: {
options: {
amd: ['handlebars'],
partialsUseNamespace: true
},
files: {
'tmp/amd_partials_use_namespace.js': ['test/fixtures/_partial.hbs', 'test/fixtures/one.hbs']
}
},
amd_partials_no_namespace: {
options: {
amd: ['handlebars'],
partialsUseNamespace: false
},
files: {
'tmp/amd_partials_no_namespace.js': ['test/fixtures/_partial.hbs', 'test/fixtures/one.hbs']
}
},
amd_namespace_as_function: {
options: {
amd: ['handlebars', 'handlebars.helpers'],
processName: function(filename) {
return filename.replace(/.*\/(\w+)\.hbs/, '$1');
},
namespace: function(filename) {
var names = filename.replace(/.*modules\/(.*)(\/\w+\.hbs)/, '$1');
return 'JST.' + names.split('/').join('.');
}
},
files: {
'tmp/amd_namespace_as_function.js': ['test/fixtures/modules/**/*.hbs']
}
},
amd_compile_function: {
options: {
amd: function() { return ['handlebars', 'custom dependency'].join("', '"); },
namespace: false
},
files: {
'tmp/amd_compile_function.js': ['test/fixtures/amd.html']
}
},
commonjs_compile: {
options: {
commonjs: true
},
files: {
'tmp/commonjs_compile.js': ['test/fixtures/commonjs.html']
}
},
commonjs_compile_direct: {
options: {
commonjs: true,
namespace: false
},
files: {
'tmp/commonjs_compile_direct.js': ['test/fixtures/commonjs.html']
}
},
custom_separator: {
options: {
separator: ';;;;;'
},
files: {
'tmp/custom_separator.js': ['test/fixtures/basic.hbs']
}
},
processname: {
options: {
processName: function(filename) {
return filename.toUpperCase();
}
},
files: {
'tmp/processname.js': ['test/fixtures/basic.hbs']
}
},
process_partial_name: {
options: {
processPartialName: function(filepath) {
return filepath.replace('test/fixtures/_weird_prefix_', '').replace('.hbs', '');
}
},
files: {
'tmp/process_partial_name.js': ['test/fixtures/_weird_prefix_partial.hbs', 'test/fixtures/one.hbs']
}
},
partial_regex: {
options: {
partialRegex: /^par_/,
processPartialName: function(filepath) {
return filepath.replace('test/fixtures/par_', '').replace('.hbs', '');
}
},
files: {
'tmp/partial_regex.js': ['test/fixtures/par_partial.hbs', 'test/fixtures/one.hbs']
}
},
partials_use_namespace: {
options: {
partialsUseNamespace: true
},
files: {
'tmp/partials_use_namespace.js': ['test/fixtures/_partial.hbs', 'test/fixtures/one.hbs']
}
},
partials_use_namespace_multiple_templates: {
options: {
partialsUseNamespace: true
},
files: {
'tmp/partials_use_namespace_multiple_templates.js': ['test/fixtures/has-spaces.hbs',
'test/fixtures/_partial.hbs', 'test/fixtures/one.hbs']
}
},
partials_path_regex: {
options: {
partialRegex: /.*/,
partialsPathRegex: /\/partials\//
},
files: {
'tmp/partials_path_regex.js': ['test/fixtures/partials/partial.hbs', 'test/fixtures/one.hbs']
}
},
unknown_helpers: {
files: {
'tmp/unknown_helpers.js': ['test/fixtures/uses_helpers.hbs']
}
},
known_helpers: {
options: {
compilerOptions: {
knownHelpers: {
'my-helper': true
}
}
},
files: {
'tmp/known_helpers.js': ['test/fixtures/uses_helpers.hbs']
}
},
only_known_helpers: {
options: {
compilerOptions: {
knownHelpers: {
'my-helper': true,
'another-helper': true
},
knownHelpersOnly: true
}
},
files: {
'tmp/only_known_helpers.js': ['test/fixtures/uses_helpers.hbs']
}
},
namespace_as_function: {
options: {
processName: function(filename) {
return filename.replace(/.*\/(\w+)\.hbs/, '$1');
},
namespace: function(filename) {
var names = filename.replace(/.*modules\/(.*)(\/\w+\.hbs)/, '$1');
return 'JST.' + names.split('/').join('.');
}
},
files: {
'tmp/namespace_as_function.js': ['test/fixtures/modules/**/*.hbs']
}
}
},
// Unit tests.
nodeunit: {
tests: ['test/*_test.js']
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-internal');
grunt.loadNpmTasks('grunt-jscs');
// Whenever the "test" task is run, first clean the "tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['jshint', 'jscs', 'clean', 'handlebars', 'nodeunit']);
// By default, lint and run all tests.
grunt.registerTask('default', ['test', 'build-contrib']);
};
|
import React from 'react'
import Icon from 'react-icon-base'
const MdCenterFocusWeak = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m20 23.4q1.3 0 2.3-1.1t1.1-2.3-1.1-2.3-2.3-1.1-2.3 1.1-1.1 2.3 1.1 2.3 2.3 1.1z m0-10q2.7 0 4.7 1.9t1.9 4.7-1.9 4.7-4.7 1.9-4.7-1.9-1.9-4.7 1.9-4.7 4.7-1.9z m11.6 18.2v-6.6h3.4v6.6q0 1.4-1 2.4t-2.4 1h-6.6v-3.4h6.6z m0-26.6q1.4 0 2.4 1t1 2.4v6.6h-3.4v-6.6h-6.6v-3.4h6.6z m-23.2 3.4v6.6h-3.4v-6.6q0-1.4 1-2.4t2.4-1h6.6v3.4h-6.6z m0 16.6v6.6h6.6v3.4h-6.6q-1.4 0-2.4-1t-1-2.4v-6.6h3.4z"/></g>
</Icon>
)
export default MdCenterFocusWeak
|
import React from 'react'
import ReactDOM from 'react-dom'
import { Panel } from 'react-bootstrap'
import TestUtils from 'react-addons-test-utils'
import { expect } from 'chai'
import CandidateMatchCategory
from '../../../../assets/js/components/organisms/CandidateMatchCategory'
import CandidateMatchRating
from '../../../../assets/js/components/atoms/CandidateMatchRating'
describe('The candidate match category component', () => {
let category
beforeEach(() => {
category = TestUtils.renderIntoDocument(
<CandidateMatchCategory
categoryName="Test Category"
categoryMatch="94"
questions={[]} />
)
})
it('will exist', () => {
expect(category).to.be.ok
})
it('will have a categoryName property', () => {
expect(category).to.have.property('props')
.that.have.property('categoryName')
.that.is.a('string')
.that.not.empty
})
it('will have a categoryMatch property', () => {
expect(category).to.have.property('props')
.that.have.property('categoryMatch')
.that.is.a('string')
.that.not.empty
})
context('panel', () => {
let panel
beforeEach(() => {
panel = TestUtils.scryRenderedComponentsWithType(category, Panel)[0]
})
it('will exist', () => {
expect(panel).to.be.ok
})
context('div', () => {
let div
beforeEach(() => {
// why is this the third one in?
div = TestUtils.scryRenderedDOMComponentsWithTag(panel, 'div')[2]
})
it('will exist', () => {
expect(div).to.be.ok
})
it('will have a flex display style', () => {
expect(div).to.have.property('style')
.that.have.property('display')
.that.equal('flex')
})
it('will align its items in the center', () => {
expect(div).to.have.property('style')
.that.have.property('alignItems')
.that.equal('center')
})
})
context('header', () => {
let header
beforeEach(() => {
header = TestUtils.scryRenderedDOMComponentsWithTag(panel, 'h4')[0]
})
it('will exist', () => {
expect(header).to.be.ok
})
it('will include the category name in its text', () => {
expect(header).to.have.property('textContent')
.that.include(category.props.categoryName)
})
it('will have a flex-grow of 1', () => {
expect(header).to.have.property('style')
.that.have.property('flexGrow')
.that.equal('1')
})
})
context('match rating', () => {
let rating
beforeEach(() => {
rating = TestUtils.scryRenderedComponentsWithType(panel,
CandidateMatchRating)[0]
})
it('will exist', () => {
expect(rating).to.exist
})
it('will have the match as a percentage for its text content', () => {
expect(ReactDOM.findDOMNode(rating).textContent)
.to.contain(`${category.props.categoryMatch}%`)
})
})
})
})
|
(function() {
'use strict';
angular
.module('macchiato')
.config(routerConfig);
/** @ngInject */
function routerConfig($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('home', {
url: '/',
templateUrl: 'app/controllers/main/main.html',
controller: 'MainController',
controllerAs: 'main'
})
.state('publish',{
url: '/publish',
templateUrl: 'app/controllers/publish/publish.html',
controller: 'PublishController',
controllerAs: 'publish'
})
.state('post',{
url: '/post/:id',
templateUrl: 'app/controllers/post/post.html',
controller: 'PostController',
controllerAs: 'post'
})
.state('edit',{
url: '/edit/post/:id',
templateUrl: 'app/controllers/edit/edit.html',
controller: 'EditController',
controllerAs: 'edit'
});
$urlRouterProvider.otherwise('/');
$locationProvider.html5Mode(true);
}
})();
|
"use strict";
var assert = require("assert");
var testUtils = require("./helpers/util.js");
var noop = testUtils.noop;
var isStrictModeSupported = testUtils.isStrictModeSupported;
var onUnhandledFail = testUtils.onUnhandledFail;
var onUnhandledSucceed = testUtils.onUnhandledSucceed;
function yesE() {
return new Error();
}
function notE() {
var rets = [{}, []];
return rets[Math.random()*rets.length|0];
}
function cleanUp() {
Promise.onPossiblyUnhandledRejection(null);
Promise.onUnhandledRejectionHandled(null);
}
function setupCleanUps() {
beforeEach(cleanUp);
afterEach(cleanUp);
}
describe("Will report rejections that are not handled in time", function() {
setupCleanUps();
specify("Immediately rejected not handled at all", function testFunction() {
var promise = Promise.defer();
promise.reject(yesE());
return onUnhandledSucceed();
});
specify("Eventually rejected not handled at all", function testFunction() {
var promise = Promise.defer();
setTimeout(function(){
promise.reject(yesE());
}, 1);
return onUnhandledSucceed();
});
specify("Immediately rejected handled too late", function testFunction() {
var promise = Promise.defer();
promise.reject(yesE());
setTimeout(function() {
promise.promise.then(assert.fail, function(){});
}, 150);
return onUnhandledSucceed();
});
specify("Eventually rejected handled too late", function testFunction() {
var promise = Promise.defer();
setTimeout(function(){
promise.reject(yesE());
setTimeout(function() {
promise.promise.then(assert.fail, function(){});
}, 150);
}, 1);
return onUnhandledSucceed();
});
});
describe("Will report rejections that are code errors", function() {
setupCleanUps();
specify("Immediately fulfilled handled with erroneous code", function testFunction() {
var deferred = Promise.defer();
var promise = deferred.promise;
deferred.fulfill(null);
promise.then(function(itsNull){
itsNull.will.fail.four.sure();
});
return onUnhandledSucceed();
});
specify("Eventually fulfilled handled with erroneous code", function testFunction() {
var deferred = Promise.defer();
var promise = deferred.promise;
setTimeout(function(){
deferred.fulfill(null);
}, 1);
promise.then(function(itsNull){
itsNull.will.fail.four.sure();
});
return onUnhandledSucceed();
});
specify("Already fulfilled handled with erroneous code but then recovered and failDeferred again", function testFunction() {
var err = yesE();
var promise = Promise.resolve(null);
promise.then(function(itsNull){
itsNull.will.fail.four.sure();
}).then(assert.fail, function(e){
assert.ok(e instanceof Promise.TypeError);
}).then(function(){
//then assert.failing again
//this error should be reported
throw err;
});
return onUnhandledSucceed(err);
});
specify("Immediately fulfilled handled with erroneous code but then recovered and failDeferred again", function testFunction() {
var err = yesE();
var deferred = Promise.defer();
var promise = deferred.promise;
deferred.fulfill(null);
promise.then(function(itsNull){
itsNull.will.fail.four.sure();
}).then(assert.fail, function(e){
assert.ok(e instanceof Promise.TypeError)
//Handling the type error here
}).then(function(){
//then assert.failing again
//this error should be reported
throw err;
});
return onUnhandledSucceed(err);
});
specify("Eventually fulfilled handled with erroneous code but then recovered and failDeferred again", function testFunction() {
var err = yesE();
var deferred = Promise.defer();
var promise = deferred.promise;
promise.then(function(itsNull){
itsNull.will.fail.four.sure();
}).then(assert.fail, function(e){
assert.ok(e instanceof Promise.TypeError)
//Handling the type error here
}).then(function(){
//then assert.failing again
//this error should be reported
throw err;
});
setTimeout(function(){
deferred.fulfill(null);
}, 1);
return onUnhandledSucceed(err);
});
specify("Already fulfilled handled with erroneous code but then recovered in a parallel handler and failDeferred again", function testFunction() {
var err = yesE();
var promise = Promise.resolve(null);
promise.then(function(itsNull){
itsNull.will.fail.four.sure();
}).then(assert.fail, function(e){
assert.ok(e instanceof Promise.TypeError)
});
promise.then(function(){
//then assert.failing again
//this error should be reported
throw err;
});
return onUnhandledSucceed(err);
});
});
describe("Will report rejections that are not instanceof Error", function() {
setupCleanUps();
specify("Immediately rejected with non instanceof Error", function testFunction() {
var failDeferred = Promise.defer();
failDeferred.reject(notE());
return onUnhandledSucceed();
});
specify("Eventually rejected with non instanceof Error", function testFunction() {
var failDeferred = Promise.defer();
setTimeout(function(){
failDeferred.reject(notE());
}, 1);
return onUnhandledSucceed();
});
});
describe("Will handle hostile rejection reasons like frozen objects", function() {
setupCleanUps();
specify("Immediately rejected with non instanceof Error", function testFunction() {
var failDeferred = Promise.defer();
failDeferred.reject(Object.freeze({}));
return onUnhandledSucceed(function(e) {
return true;
});
});
specify("Eventually rejected with non instanceof Error", function testFunction() {
var failDeferred = Promise.defer();
var obj = {};
setTimeout(function(){
failDeferred.reject(Object.freeze(obj));
}, 1);
return onUnhandledSucceed(function(e) {
return e === obj;
});
});
});
describe("Will not report rejections that are handled in time", function() {
setupCleanUps();
specify("Already rejected handled", function testFunction() {
var failDeferred = Promise.reject(yesE()).caught(noop);
return onUnhandledFail(isStrictModeSupported ? testFunction : arguments.callee);
});
specify("Immediately rejected handled", function testFunction() {
var failDeferred = Promise.defer();
failDeferred.promise.caught(noop);
failDeferred.reject(yesE());
return onUnhandledFail(isStrictModeSupported ? testFunction : arguments.callee);
});
specify("Eventually rejected handled", function testFunction() {
var failDeferred = Promise.defer();
setTimeout(function() {
failDeferred.reject(yesE());
}, 1);
failDeferred.promise.caught(noop);
return onUnhandledFail(isStrictModeSupported ? testFunction : arguments.callee);
});
specify("Already rejected handled in a deep sequence", function testFunction() {
var failDeferred = Promise.reject(yesE());
failDeferred
.then(function(){})
.then(function(){}, null, function(){})
.then()
.then(function(){})
.caught(noop);
return onUnhandledFail(isStrictModeSupported ? testFunction : arguments.callee);
});
specify("Immediately rejected handled in a deep sequence", function testFunction() {
var failDeferred = Promise.defer();
failDeferred.promise.then(function(){})
.then(function(){}, null, function(){})
.then()
.then(function(){})
.caught(noop);
failDeferred.reject(yesE());
return onUnhandledFail(isStrictModeSupported ? testFunction : arguments.callee);
});
specify("Eventually handled in a deep sequence", function testFunction() {
var failDeferred = Promise.defer();
setTimeout(function() {
failDeferred.reject(yesE());
}, 1);
failDeferred.promise.then(function(){})
.then(function(){}, null, function(){})
.then()
.then(function(){})
.caught(noop);
return onUnhandledFail(isStrictModeSupported ? testFunction : arguments.callee);
});
specify("Already rejected handled in a middle parallel deep sequence", function testFunction() {
var failDeferred = Promise.reject(yesE());
failDeferred
.then(function(){})
.then(function(){}, null, function(){})
.then()
.then(function(){});
failDeferred
.then(function(){})
.then(function(){}, null, function(){})
.then(assert.fail, function(){
});
failDeferred
.then(function(){})
.then(function(){}, null, function(){})
.then()
.then(function(){});
return onUnhandledSucceed(undefined, 2);
});
specify("Immediately rejected handled in a middle parallel deep sequence", function testFunction() {
var failDeferred = Promise.defer();
failDeferred.promise
.then(function(){})
.then(function(){}, null, function(){})
.then()
.then(function(){});
failDeferred.promise
.then(function(){})
.then(function(){}, null, function(){})
.then(assert.fail, function(){
});
failDeferred.promise
.then(function(){})
.then(function(){}, null, function(){})
.then()
.then(function(){});
failDeferred.reject(yesE());
return onUnhandledSucceed(undefined, 2);
});
specify("Eventually handled in a middle parallel deep sequence", function testFunction() {
var failDeferred = Promise.defer();
failDeferred.promise
.then(function(){})
.then(function(){}, null, function(){})
.then()
.then(function(){});
failDeferred.promise
.then(function(){})
.then(function(){}, null, function(){})
.then(assert.fail, function(){
});
failDeferred.promise
.then(function(){})
.then(function(){}, null, function(){})
.then()
.then(function(){});
setTimeout(function(){
failDeferred.reject(yesE());
}, 1);
return onUnhandledSucceed(undefined, 2);
});
});
describe("immediate assert.failures without .then", function testFunction() {
setupCleanUps();
var err = new Error('');
specify("Promise.reject", function testFunction() {
Promise.reject(err);
return onUnhandledSucceed(function(e) {
return e === err;
});
});
specify("new Promise throw", function testFunction() {
new Promise(function() {
throw err;
});
return onUnhandledSucceed(function(e) {
return e === err;
});
});
specify("new Promise reject", function testFunction() {
new Promise(function(_, r) {
r(err);
});
return onUnhandledSucceed(function(e) {
return e === err;
});
});
specify("Promise.method", function testFunction() {
Promise.method(function() {
throw err;
})();
return onUnhandledSucceed(function(e) {
return e === err;
});
});
specify("Promise.all", function testFunction() {
Promise.all([Promise.reject(err)]);
return onUnhandledSucceed(function(e) {
return e === err;
});
});
});
describe("immediate assert.failures with .then", function testFunction() {
setupCleanUps();
var err = new Error('');
specify("Promise.reject", function testFunction() {
Promise.reject(err).caught(noop);
return onUnhandledFail(isStrictModeSupported ? testFunction : arguments.callee);
});
specify("new Promise throw", function testFunction() {
new Promise(function() {
throw err;
}).caught(noop);
return onUnhandledFail(isStrictModeSupported ? testFunction : arguments.callee);
});
specify("new Promise reject", function testFunction() {
new Promise(function(_, r) {
r(err);
}).caught(noop);
return onUnhandledFail(isStrictModeSupported ? testFunction : arguments.callee);
});
specify("Promise.method", function testFunction() {
Promise.method(function() {
throw err;
})().caught(noop);
return onUnhandledFail(isStrictModeSupported ? testFunction : arguments.callee);
});
specify("Promise.all", function testFunction() {
Promise.all([Promise.reject("err")])
.caught(noop);
return onUnhandledFail(isStrictModeSupported ? testFunction : arguments.callee);
});
specify("Promise.all many", function testFunction() {
Promise.all([Promise.reject("err"), Promise.reject("err2")])
.caught(noop);
return onUnhandledFail(isStrictModeSupported ? testFunction : arguments.callee);
});
specify("Promise.all many, latter async", function testFunction() {
Promise.all([Promise.reject("err"), Promise.delay(1).thenThrow(new Error())])
.caught(noop);
return onUnhandledFail(isStrictModeSupported ? testFunction : arguments.callee);
});
specify("Promise.all many pending", function testFunction() {
var a = new Promise(function(v, w){
setTimeout(function(){w("err");}, 1);
});
var b = new Promise(function(v, w){
setTimeout(function(){w("err2");}, 1);
});
Promise.all([a, b])
.caught(noop);
return onUnhandledFail(isStrictModeSupported ? testFunction : arguments.callee);
});
specify("Already rejected promise for a collection", function testFunction(){
Promise.settle(Promise.reject(err))
.caught(noop);
return onUnhandledFail(isStrictModeSupported ? testFunction : arguments.callee);
});
});
describe("gh-118", function() {
setupCleanUps();
specify("eventually rejected promise", function testFunction() {
Promise.resolve().then(function() {
return new Promise(function(_, reject) {
setTimeout(function() {
reject(13);
}, 1);
});
}).caught(noop);
return onUnhandledFail(isStrictModeSupported ? testFunction : arguments.callee);
});
specify("already rejected promise", function testFunction() {
Promise.resolve().then(function() {
return Promise.reject(13);
}).caught(noop);
return onUnhandledFail(isStrictModeSupported ? testFunction : arguments.callee);
});
specify("immediately rejected promise", function testFunction() {
Promise.resolve().then(function() {
return new Promise(function(_, reject) {
reject(13);
});
}).caught(noop);
return onUnhandledFail(isStrictModeSupported ? testFunction : arguments.callee);
});
});
describe("Promise.onUnhandledRejectionHandled", function() {
specify("should be called when unhandled promise is later handled", function() {
var unhandledPromises = [];
var spy1 = testUtils.getSpy();
var spy2 = testUtils.getSpy();
Promise.onPossiblyUnhandledRejection(spy1(function(reason, promise) {
unhandledPromises.push({
reason: reason,
promise: promise
});
}));
Promise.onUnhandledRejectionHandled(spy2(function(promise) {
assert.equal(unhandledPromises.length, 1);
assert(unhandledPromises[0].promise === promise);
assert(promise === a);
assert(unhandledPromises[0].reason === reason);
}));
var reason = new Error("error");
var a = new Promise(function(){
throw reason;
});
setTimeout(function(){
a.then(assert.fail, function(){});
}, 200);
return Promise.all([spy1.promise, spy2.promise]);
});
});
describe("global events", function() {
var attachGlobalHandler, detachGlobalHandlers;
if (typeof process !== "undefined" &&
typeof process.version === "string" &&
typeof window === "undefined") {
attachGlobalHandler = function(name, fn) {
process.on(name, fn);
};
detachGlobalHandlers = function() {
process.removeAllListeners("unhandledRejection");
process.removeAllListeners("rejectionHandled");
};
} else {
attachGlobalHandler = function(name, fn) {
window[("on" + name).toLowerCase()] = fn;
};
detachGlobalHandlers = function() {
window.onunhandledrejection = null;
window.onrejectionhandled = null;
};
}
setupCleanUps();
beforeEach(detachGlobalHandlers);
afterEach(detachGlobalHandlers);
specify("are fired", function() {
return new Promise(function(resolve, reject) {
var err = new Error();
var receivedPromise;
attachGlobalHandler("unhandledRejection", function(reason, promise) {
assert.strictEqual(reason, err);
receivedPromise = promise;
});
attachGlobalHandler("rejectionHandled", function(promise) {
assert.strictEqual(receivedPromise, promise);
resolve();
});
var promise = new Promise(function() {throw err;});
setTimeout(function() {
promise.then(assert.fail, function(){});
}, 150);
}).timeout(500);
});
specify("are fired with local events", function() {
return new Promise(function(resolve, reject) {
var expectedOrder = [1, 2, 3, 4];
var order = [];
var err = new Error();
var receivedPromises = [];
Promise.onPossiblyUnhandledRejection(function(reason, promise) {
assert.strictEqual(reason, err);
receivedPromises.push(promise);
order.push(1);
});
Promise.onUnhandledRejectionHandled(function(promise) {
assert.strictEqual(receivedPromises[0], promise);
order.push(3);
});
attachGlobalHandler("unhandledRejection", function(reason, promise) {
assert.strictEqual(reason, err);
receivedPromises.push(promise);
order.push(2);
});
attachGlobalHandler("rejectionHandled", function(promise) {
assert.strictEqual(receivedPromises[1], promise);
order.push(4);
assert.deepEqual(expectedOrder, order);
assert.strictEqual(receivedPromises.length, 2);
resolve();
});
var promise = new Promise(function() {throw err;});
setTimeout(function() {
promise.then(assert.fail, function(){});
}, 150);
}).timeout(500);
});
});
var windowDomEventSupported = true;
try {
var event = document.createEvent("CustomEvent");
event.initCustomEvent("testingtheevent", false, true, {});
self.dispatchEvent(event);
} catch (e) {
windowDomEventSupported = false;
}
if (windowDomEventSupported) {
describe("dom events", function() {
var events = [];
beforeEach(detachEvents);
afterEach(detachEvents);
function detachEvents() {
events.forEach(function(e) {
self.removeEventListener(e.type, e.fn, false);
});
events = [];
}
function attachEvent(type, fn) {
events.push({type: type, fn: fn});
self.addEventListener(type, fn, false);
}
specify("are fired", function() {
return new Promise(function(resolve, reject) {
var order = [];
var err = new Error();
var promise = Promise.reject(err);
attachEvent("unhandledrejection", function(e) {
e.preventDefault();
assert.strictEqual(e.detail.promise, promise);
assert.strictEqual(e.detail.reason, err);
order.push(1);
});
attachEvent("unhandledrejection", function(e) {
assert.strictEqual(e.detail.promise, promise);
assert.strictEqual(e.detail.reason, err);
assert.strictEqual(e.defaultPrevented, true);
order.push(2);
});
attachEvent("rejectionhandled", function(e) {
e.preventDefault();
assert.strictEqual(e.detail.promise, promise);
assert.strictEqual(e.detail.reason, undefined);
order.push(3);
});
attachEvent("rejectionhandled", function(e) {
assert.strictEqual(e.detail.promise, promise);
assert.strictEqual(e.detail.reason, undefined);
assert.strictEqual(e.defaultPrevented, true);
order.push(4);
resolve();
});
setTimeout(function() {
promise.then(assert.fail, function(r) {
order.push(5);
assert.strictEqual(r, err);
assert.deepEqual(order, [1,2,3,4,5]);
});
}, 150);
}).timeout(500);
})
});
}
describe("Unhandled rejection when joining chains with common rejected parent", function testFunction() {
specify("GH 645", function() {
var aError = new Error('Something went wrong');
var a = Promise.try(function(){
throw aError;
});
var b = Promise.try(function(){
throw new Error('Something went wrong here as well');
});
var c = Promise
.join(a, b)
.spread(function( a, b ){
return a+b;
});
var test1 = Promise
.join(a, c)
.spread(function( a, product ){
// ...
})
.caught(Error, function(e) {
assert.strictEqual(aError, e);
});
var test2 = onUnhandledFail(testFunction);
return Promise.all([test1, test2]);
});
});
|
const webpack = require('webpack')
const plugins = [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
__DEV__: process.env.NODE_ENV === 'development',
__TEST__: process.env.NODE_ENV === 'test'
})
]
if (process.env.NODE_ENV === 'production') {
plugins.push(new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}))
}
module.exports = {
output: {
library: 'jssExtend',
libraryTarget: 'umd'
},
plugins,
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}
]
},
devtool: 'source-map'
}
|
'use strict';
import { assert } from 'chai';
// import fs from 'fs';
import FormData from 'form-data';
import streamToPromise from 'stream-to-promise';
import initServer from '../app/services/server';
import db from '../app/db';
import { setupStructure as setupDdStructure } from '../app/db/structure';
import { setupStructure as setupStorageStructure } from '../app/s3/structure';
import { fixMeUp } from './utils/data';
import { getOSRMProfileDefaultSpeedSettings, toLua, getOSRMProfileDefaultSpeedMeta } from '../app/utils/osrm-profile';
var options = {
connection: {port: 2000, host: '0.0.0.0'}
};
var instance;
before(function (done) {
initServer(options, function (_, server) {
instance = server.hapi;
instance.register(require('inject-then'), function (err) {
if (err) throw err;
done();
});
});
});
describe('Projects source data', function () {
before('Before - Project files', function () {
this.timeout(5000);
return setupDdStructure()
.then(() => setupStorageStructure())
.then(() => fixMeUp());
});
describe('POST /projects/{projId}/source-data', function () {
it('should error when data format is not multipart/form-data', function () {
return instance.injectThen({
method: 'POST',
url: '/projects/300/source-data'
}).then(res => {
assert.equal(res.statusCode, 415, 'Status code is 415');
assert.equal(res.result.error, 'Unsupported Media Type');
});
});
it('should return 404 for a project not found', function () {
let form = new FormData();
form.append('', '');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/300/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 404, 'Status code is 404');
assert.equal(res.result.message, 'Project not found');
});
});
it('should return 400 when project is not pending', function () {
let form = new FormData();
form.append('', '');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/2000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
assert.equal(res.result.message, 'Project no longer in the setup phase. Source data can not be uploaded');
});
});
it('should error when source-type is not provided', function () {
let form = new FormData();
form.append('', '');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
assert.match(res.result.message, /"source-type" is required/);
});
});
it('should error when source-name is not provided', function () {
let form = new FormData();
form.append('source-type', 'file');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
assert.match(res.result.message, /"source-name" is required/);
});
});
it('should error when invalid source-name is provided', function () {
let form = new FormData();
form.append('source-type', 'file');
form.append('source-name', 'invalid');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
assert.equal(res.result.message, '"source-name" must be one of [profile, origins, admin-bounds]');
});
});
it('should error when invalid source-type is provided', function () {
let form = new FormData();
form.append('source-type', 'invalid');
form.append('source-name', 'profile');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
assert.equal(res.result.message, '"source-type" for "profile" must be one of [file, default, wbcatalog]');
});
});
});
describe('POST /projects/{projId}/source-data -- file', function () {
it('should error when file is missing', function () {
let form = new FormData();
form.append('source-type', 'file');
form.append('source-name', 'profile');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
assert.equal(res.result.message, '"file" is required');
});
});
});
describe('POST /projects/{projId}/source-data -- origins', function () {
it('should error when available-ind is missing', function () {
let form = new FormData();
form.append('source-type', 'file');
form.append('source-name', 'origins');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
assert.equal(res.result.message, '"available-ind" is required');
});
});
it('should error when available-ind is empty', function () {
let form = new FormData();
form.append('source-type', 'file');
form.append('source-name', 'origins');
form.append('available-ind', '');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
assert.equal(res.result.message, '"available-ind" must not be empty');
});
});
it('should error when indicators[key] is missing', function () {
let form = new FormData();
form.append('source-type', 'file');
form.append('source-name', 'origins');
form.append('available-ind', 'value-1');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
assert.equal(res.result.message, '"indicators[key]" is required');
});
});
it('should error when indicators[key] is empty', function () {
let form = new FormData();
form.append('source-type', 'file');
form.append('source-name', 'origins');
form.append('available-ind', 'value-1');
form.append('indicators[key]', '');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
assert.equal(res.result.message, '"indicators[key]" must not be empty');
});
});
it('should error when indicators[label] is missing', function () {
let form = new FormData();
form.append('source-type', 'file');
form.append('source-name', 'origins');
form.append('available-ind', 'value-1');
form.append('indicators[key]', 'key-1');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
assert.equal(res.result.message, '"indicators[label]" is required');
});
});
it('should error when indicators[label] is empty', function () {
let form = new FormData();
form.append('source-type', 'file');
form.append('source-name', 'origins');
form.append('available-ind', 'value-1');
form.append('indicators[key]', 'key-1');
form.append('indicators[label]', '');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
assert.equal(res.result.message, '"indicators[label]" must not be empty');
});
});
it('should error when indicators[key] and indicators[label] have different lengths', function () {
let form = new FormData();
form.append('source-type', 'file');
form.append('source-name', 'origins');
form.append('available-ind', 'value-1');
form.append('indicators[key]', 'key-1');
form.append('indicators[label]', 'label-1');
form.append('indicators[label]', 'label-2');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
assert.equal(res.result.message, '"indicators[key]" and "indicators[label]" must have the same number of values');
});
});
it('should error when indicators[key] values are not in available-ind', function () {
let form = new FormData();
form.append('source-type', 'file');
form.append('source-name', 'origins');
form.append('available-ind', 'value-1');
form.append('indicators[key]', 'key-1');
form.append('indicators[label]', 'label-1');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
assert.equal(res.result.message, 'Submitted indicator keys are not listed as available');
});
});
it('should error on missing file when indicator info is correct', function () {
let form = new FormData();
form.append('source-type', 'file');
form.append('source-name', 'origins');
form.append('available-ind', 'ind-1');
form.append('available-ind', 'ind-2');
form.append('indicators[key]', 'ind-1');
form.append('indicators[label]', 'label-1');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 404, 'Status code is 404');
assert.equal(res.result.message, 'File not found');
});
});
});
describe('POST /projects/{projId}/source-data -- wbcatalog', function () {
it('should error when wbcatalog-options[key] is missing', function () {
let form = new FormData();
form.append('source-type', 'wbcatalog');
form.append('source-name', 'profile');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
assert.equal(res.result.message, '"wbcatalog-options[key]" is required');
});
});
it('should error when wbcatalog-options[key] is empty', function () {
let form = new FormData();
form.append('source-type', 'wbcatalog');
form.append('source-name', 'profile');
form.append('wbcatalog-options[key]', '');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
assert.equal(res.result.message, '"wbcatalog-options[key]" must not be empty');
});
});
it('should save key to the database for source-name profile', function () {
let form = new FormData();
form.append('source-type', 'wbcatalog');
form.append('source-name', 'profile');
form.append('wbcatalog-options[key]', 'key 1');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 200, 'Status code is 200');
assert.equal(res.result.sourceType, 'wbcatalog');
assert.equal(res.result.sourceName, 'profile');
})
.then(() => db('projects_source_data')
.select('data')
.where('project_id', 1000)
.where('name', 'profile')
.first()
)
.then(({data}) => {
assert.deepEqual(data, {resources: [ {key: 'key 1'} ]});
});
});
it('should save key to the database for source-name origins', function () {
let form = new FormData();
form.append('source-type', 'wbcatalog');
form.append('source-name', 'origins');
form.append('wbcatalog-options[key]', 'key origins');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 200, 'Status code is 200');
assert.equal(res.result.sourceType, 'wbcatalog');
assert.equal(res.result.sourceName, 'origins');
})
.then(() => db('projects_source_data')
.select('data')
.where('project_id', 1000)
.where('name', 'origins')
.first()
)
.then(({data}) => {
assert.deepEqual(data, {resources: [ {key: 'key origins'} ]});
});
});
it('should save key to the database for source-name admin-bounds', function () {
let form = new FormData();
form.append('source-type', 'wbcatalog');
form.append('source-name', 'admin-bounds');
form.append('wbcatalog-options[key]', 'key admin-bounds');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 200, 'Status code is 200');
assert.equal(res.result.sourceType, 'wbcatalog');
assert.equal(res.result.sourceName, 'admin-bounds');
})
.then(() => db('projects_source_data')
.select('data')
.where('project_id', 1000)
.where('name', 'admin-bounds')
.first()
)
.then(({data}) => {
assert.deepEqual(data, {resources: [ {key: 'key admin-bounds'} ]});
});
});
it('should save first key to the database if multiple submitted', function () {
let form = new FormData();
form.append('source-type', 'wbcatalog');
form.append('source-name', 'profile');
form.append('wbcatalog-options[key]', 'key 1');
form.append('wbcatalog-options[key]', 'key 2');
return streamToPromise(form)
.then(payload => instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data',
payload,
headers: form.getHeaders()
}))
.then(res => {
assert.equal(res.statusCode, 200, 'Status code is 200');
assert.equal(res.result.sourceType, 'wbcatalog');
assert.equal(res.result.sourceName, 'profile');
})
.then(() => db('projects_source_data')
.select('data')
.where('project_id', 1000)
.where('name', 'profile')
.first()
)
.then(({data}) => {
assert.deepEqual(data, {resources: [ {key: 'key 1'} ]});
});
});
});
describe('GET /projects/{projId}/source-data/editor -- profile', function () {
it('should fail without a type', function () {
return instance.injectThen({
method: 'GET',
url: '/projects/1000/source-data/editor'
}).then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
var result = res.result;
assert.match(result.message, /"type" is required/);
});
});
it('should fail without a type different than profile', function () {
return instance.injectThen({
method: 'GET',
url: '/projects/1000/source-data/editor?type=invalid'
}).then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
var result = res.result;
assert.match(result.message, /"type" must be one of \[profile\]/);
});
});
it('should fail if project is not found', function () {
return instance.injectThen({
method: 'GET',
url: '/projects/0000/source-data/editor?type=profile'
}).then(res => {
assert.equal(res.statusCode, 404, 'Status code is 404');
var result = res.result;
assert.equal(result.message, 'Project not found');
});
});
it('should fail if project setup is not completed', function () {
return instance.injectThen({
method: 'GET',
url: '/projects/1000/source-data/editor?type=profile'
}).then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
var result = res.result;
assert.equal(result.message, 'Project setup not completed');
});
});
it('should return the profile settings', function () {
return instance.injectThen({
method: 'GET',
url: '/projects/2000/source-data/editor?type=profile'
}).then(res => {
assert.equal(res.statusCode, 200, 'Status code is 200');
var result = res.result;
assert.deepEqual(result, {
sections: getOSRMProfileDefaultSpeedMeta(),
settings: getOSRMProfileDefaultSpeedSettings()
});
});
});
});
describe('POST /projects/{projId}/source-data/editor -- profile', function () {
it('should fail without a type', function () {
return instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data/editor'
}).then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
var result = res.result;
assert.match(result.message, /"type" is required/);
});
});
it('should fail without a type different than profile', function () {
return instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data/editor?type=invalid'
}).then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
var result = res.result;
assert.match(result.message, /"type" must be one of \[profile\]/);
});
});
it('should fail with missing keys', function () {
return instance.injectThen({
method: 'POST',
url: '/projects/2000/source-data/editor?type=profile',
payload: {
}
}).then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
var result = res.result;
assert.match(result.message, /"speed_profile" is required/);
});
});
const emptySettings = {
speed_profile: {},
surface_speeds: {},
tracktype_speeds: {},
smoothness_speeds: {},
maxspeed_table_default: {},
maxspeed_table: {}
};
it('should fail with invalid section keys', function () {
return instance.injectThen({
method: 'POST',
url: '/projects/2000/source-data/editor?type=profile',
payload: Object.assign({}, emptySettings, {
invalid: {}
})
}).then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
var result = res.result;
assert.equal(result.message, '"invalid" is not allowed');
});
});
it('should fail with invalid speed keys', function () {
return instance.injectThen({
method: 'POST',
url: '/projects/2000/source-data/editor?type=profile',
payload: Object.assign({}, emptySettings, {
speed_profile: {
'invalid key': 10
}
})
}).then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
var result = res.result;
assert.match(result.message, /"invalid key" is not allowed/);
});
});
it('should fail with invalid speed values', function () {
return instance.injectThen({
method: 'POST',
url: '/projects/2000/source-data/editor?type=profile',
payload: Object.assign({}, emptySettings, {
speed_profile: {
'valid_key': 'invalid'
}
})
}).then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
var result = res.result;
assert.match(result.message, /"valid_key" must be a number/);
});
});
it('should fail if project is not found', function () {
return instance.injectThen({
method: 'POST',
url: '/projects/0000/source-data/editor?type=profile',
payload: emptySettings
}).then(res => {
assert.equal(res.statusCode, 404, 'Status code is 404');
var result = res.result;
assert.equal(result.message, 'Project not found');
});
});
it('should fail if project setup is not completed', function () {
return instance.injectThen({
method: 'POST',
url: '/projects/1000/source-data/editor?type=profile',
payload: emptySettings
}).then(res => {
assert.equal(res.statusCode, 400, 'Status code is 400');
var result = res.result;
assert.equal(result.message, 'Project setup not completed');
});
});
it('should render the object to lua', function () {
const data = {
foo: 'bar',
another: 'baz'
};
assert.equal(toLua(data), `{
["foo"] = "bar",
["another"] = "baz"
}`);
});
it('should render the nested object to lua', function () {
const data = {
foo: 'bar',
another: {
baz: 10,
more: 20,
double: {
nesting: 'all the way'
}
},
bax: 10
};
assert.equal(toLua(data), `{
["foo"] = "bar",
["another"] = {
["baz"] = 10,
["more"] = 20,
["double"] = {
["nesting"] = "all the way"
}
},
["bax"] = 10
}`);
});
it('should update the profile settings', function () {
return instance.injectThen({
method: 'POST',
url: '/projects/2000/source-data/editor?type=profile',
payload: Object.assign({}, emptySettings, {
speed_profile: {
highway: '100',
secondary: 20
}
})
}).then(res => {
assert.equal(res.statusCode, 200, 'Status code is 200');
var result = res.result;
assert.equal(result.message, 'Profile settings uploaded');
})
.then(() => {
return db('projects_source_data')
.select('*')
.where('project_id', 2000)
.where('name', 'profile')
.first();
})
.then(({data}) => {
assert.deepEqual(data.settings, Object.assign({}, emptySettings, {
speed_profile: {
highway: 100,
secondary: 20
}
}));
});
});
});
});
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2019 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
// bitmask flag for GameObject.renderMask
var _FLAG = 1; // 0001
/**
* Provides methods used for setting the visibility of a Game Object.
* Should be applied as a mixin and not used directly.
*
* @namespace Phaser.GameObjects.Components.Visible
* @since 3.0.0
*/
var Visible = {
/**
* Private internal value. Holds the visible value.
*
* @name Phaser.GameObjects.Components.Visible#_visible
* @type {boolean}
* @private
* @default true
* @since 3.0.0
*/
_visible: true,
/**
* The visible state of the Game Object.
*
* An invisible Game Object will skip rendering, but will still process update logic.
*
* @name Phaser.GameObjects.Components.Visible#visible
* @type {boolean}
* @since 3.0.0
*/
visible: {
get: function ()
{
return this._visible;
},
set: function (value)
{
if (value)
{
this._visible = true;
this.renderFlags |= _FLAG;
}
else
{
this._visible = false;
this.renderFlags &= ~_FLAG;
}
}
},
/**
* Sets the visibility of this Game Object.
*
* An invisible Game Object will skip rendering, but will still process update logic.
*
* @method Phaser.GameObjects.Components.Visible#setVisible
* @since 3.0.0
*
* @param {boolean} value - The visible state of the Game Object.
*
* @return {this} This Game Object instance.
*/
setVisible: function (value)
{
this.visible = value;
return this;
}
};
module.exports = Visible;
|
/**
* Author: Ido Green @greenido
* date: Sep 2013
*/
// TODO - move to their own object.
var map;
var markersArray = [];
var bounds = new google.maps.LatLngBounds();
var gotTheData = false;
/**
* Initialize our map obj.
* @returns {undefined}
*/
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(31.7, 35.1),
zoom: 10,
streetViewControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
/**
* Fetching the stations geo points and other data from our google sheet in JSON baby!
* @returns {undefined}
*/
function fetchPoints() {
$.ajax({
type: 'GET',
dataType: 'json',
url: 'https://spreadsheets.google.com/feeds/list/0Ass6q5sTeDKidDlKY3BUU0NoSnk4UUZIQ2NuUDYtTHc/od7/public/basic?alt=json',
success: function(response, status, xhr) {
if (gotTheData) {
return;
}
if (response !== "") {
gotTheData = true;
for (var i = 0; i < response.feed.entry.length; i++) {
//console.log("data: " + response.feed.entry[i].content.$t);
//console.log("waze link: " + response.feed.entry[i].title.$t);
var tmpData = response.feed.entry[i].content.$t.split(":");
tmpData[4] = tmpData[4].replace("city", "");
tmpData[5] = tmpData[5].replace(", hours", "");
tmpData[3] = tmpData[3].replace(", address", "");
var address = tmpData[4] + " " + tmpData[5];
$("#maintable").append(
'<div class="ui-block-a righttext"><div class="ui-bar ui-bar-b" style="height:75px">' +
'<a target="_blank" href="https://maps.google.com/?q=' + encodeURI(tmpData[3]) + '">' +
address +
'</a></div></div>' +
'<div class="ui-block-b"><div class="ui-bar ui-bar-b" style="height:75px">' +
'<a href="' + response.feed.entry[i].title.$t +
'" data-role="button" class="wazeButton"><img src="img/waze48.png" alt="waze logo"><span class="butText">לחץ לניווט </span></a></div></div>' +
'<div class="ui-block-c righttext"><div class="ui-bar ui-bar-d" style="height:75px">' +
tmpData[6] + '</div></div>'
);
addStation(tmpData);
}
map.fitBounds(bounds);
$(".wazeButton").buttonMarkup("refresh");
}
else {
console.error("ERR: blagan... we didn't get any response from our google sheet JSON obj. Status" + status + " XHR:" + xhr);
}
}
});
}
/**
* Adding the station to our map
* @param {type} tmpData
* @returns {undefined}
*/
function addStation(tmpData) {
var station = new Object;
var stationText = tmpData[4] + " <br>" + tmpData[6];
station.long = tmpData[1].replace(", geolong", "");
station.lang = tmpData[2].replace(", geopoint", "");
station.title = tmpData[5]; // TODO - change it
station.contentString = "<div class='textright darkback'>" + station.title +
"<br>" + stationText + "</div>";
var infowindow = new google.maps.InfoWindow();
var tmpPos = new google.maps.LatLng(station.long, station.lang);
var marker = new google.maps.Marker({
position: tmpPos,
map: map
});
bounds.extend(tmpPos);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(station.contentString); //"תחנת חלוקה <br>" + tmpData[4]
infowindow.open(map, marker);
}
})(marker));
}
/**
* Clear all the markers
* @returns {undefined}
*/
function clearOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
}
/**
* Start the party
*/
$(document).on('pageinit', '[data-role=page]', function() {
console.log("--start the map party--");
initialize();
$.mobile.touchOverflowEnabled = true;
fetchPoints();
$("#reload").click(function() {
clearOverlays();
});
}); |
import isArray from '@f/is-array'
import Analyse from 'js-analyse'
import filter from '@f/filter'
let lastLoc = 0
export default (code = '') => {
try {
if (isArray(code)) {
return filter(
({ type }) =>
['block_end', 'comment', 'lineBreak'].indexOf(type) === -1,
code
).length
}
const analysis = new Analyse(code)
lastLoc = analysis.lloc()
return lastLoc
} catch (e) {
return lastLoc
}
}
|
// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
var MembershipIterator = require('../lib/membership-iterator.js');
var testRingpop = require('./lib/test-ringpop.js');
testRingpop('iterates over two members correctly', function t(deps, assert) {
var ringpop = deps.ringpop;
var membership = deps.membership;
var iterator = deps.iterator;
membership.makeAlive('127.0.0.1:3001', Date.now());
membership.makeAlive('127.0.0.1:3002', Date.now());
var iterated = {};
iterated[iterator.next().address] = true;
iterated[iterator.next().address] = true;
assert.equals(Object.keys(iterated).length, 2, '2 members iterated over');
});
testRingpop('iterates over three members correctly', function t(deps, assert) {
var ringpop = deps.ringpop;
var membership = deps.membership;
var iterator = deps.iterator;
membership.makeAlive('127.0.0.1:3001', Date.now());
membership.makeAlive('127.0.0.1:3002', Date.now());
membership.makeAlive('127.0.0.1:3003', Date.now());
var iterated = {};
iterated[iterator.next().address] = true;
iterated[iterator.next().address] = true;
iterated[iterator.next().address] = true;
assert.equals(Object.keys(iterated).length, 3, '3 members iterated over');
});
testRingpop('skips over faulty member and 1 local member', function t(deps, assert) {
var ringpop = deps.ringpop;
var membership = deps.membership;
var iterator = deps.iterator;
membership.makeAlive('127.0.0.1:3001', Date.now());
membership.makeFaulty('127.0.0.1:3002', Date.now());
membership.makeAlive('127.0.0.1:3003', Date.now());
var iterated = {};
iterated[iterator.next().address] = true;
iterated[iterator.next().address] = true;
iterated[iterator.next().address] = true;
assert.equals(Object.keys(iterated).length, 2, '2 members iterated over');
assert.notok(iterated['127.0.0.1:3002'], 'faulty member not iterated over');
});
|
/**
* Created by bryangill on 10/24/15.
*/
var http;
var q;
var config;
class SummaryService {
constructor($http, $q, siwBlogConfig) {
http = $http;
q = $q;
config = siwBlogConfig;
}
getPosts(params) {
var request = {
method: 'get',
url: config.api_url + ':' + config.api_port + '/post',
params: params
};
return http(request).then(function (response) {
if (response) {
return response;
} else {
return q.reject(response);
}
}, function (response) {
return q.reject(response);
});
}
getPost(id, params) {
var request = {
method: 'get',
url: config.api_url + ':' + config.api_port + '/post' + '/' + id,
params: params
};
return http(request).then(function (response) {
if (response) {
return response;
} else {
return q.reject(response);
}
}, function (response) {
return q.reject(response);
});
}
}
SummaryService.$inject = ['$http', '$q', 'siwBlog.config'];
export default SummaryService;
|
/* globals $ */
/*
Create a function that takes an id or DOM element and:
*/
function solve() {
return function (selector) {
var buttons,
div,
content,
button,
element;
if (typeof selector !== 'string') {
throw new Error('Selector must be a string');
}
element = document.getElementById(selector);
if (element === null) {
throw new Error('There is no such element');
}
buttons = document.getElementsByClassName('button');
div = document.getElementById('root');
for (var item in buttons) {
buttons[item].innerHTML = 'hide';
}
div.addEventListener('click', function (ev) {
if (ev.target.className === 'button') {
button = ev.target;
content = ev.target;
while (content) {
if (content.className === 'content') {
break;
}
content = content.nextElementSibling;
}
if (content.style.display === '') {
button.innerHTML = 'show';
content.style.display = 'none';
} else if (content.style.display === 'none') {
button.innerHTML = 'hide';
content.style.display = '';
}
}
}, false);
};
}
module.exports = solve; |
/**
* Copyright 2015 Telerik AD
*
* 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.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["dsb-DE"] = {
name: "dsb-DE",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ".",
".": ",",
groupSize: [3],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ".",
".": ",",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["-n $","n $"],
decimals: 2,
",": ".",
".": ",",
groupSize: [3],
symbol: "€"
}
},
calendars: {
standard: {
days: {
names: ["njeźela","ponjeźele","wałtora","srjoda","stwortk","pětk","sobota"],
namesAbbr: ["nje","pon","wał","srj","stw","pět","sob"],
namesShort: ["n","p","w","s","s","p","s"]
},
months: {
names: ["januar","februar","měrc","apryl","maj","junij","julij","awgust","september","oktober","nowember","december",""],
namesAbbr: ["jan","feb","měr","apr","maj","jun","jul","awg","sep","okt","now","dec",""]
},
AM: [""],
PM: [""],
patterns: {
d: "d. M. yyyy",
D: "dddd, 'dnja' d. MMMM yyyy",
F: "dddd, 'dnja' d. MMMM yyyy H:mm:ss",
g: "d. M. yyyy H.mm 'goź.'",
G: "d. M. yyyy H:mm:ss",
m: "d. MMMM",
M: "d. MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "H.mm 'goź.'",
T: "H:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": ". ",
":": ":",
firstDay: 1
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); |
'use strict';
const assert = require('assert');
const acl = require('../../');
const httpMocks = require('node-mocks-http');
let response = {
success: {
status: 200,
success: true,
message: 'ACCESS GRANTED'
},
restricted: {
status: 'Access denied',
success: false,
message: 'Unauthorized access'
}
};
describe('Testing for resource scenarios', function() {
let req, res, next, data;
context('When action deny', function() {
beforeEach(function(done) {
acl.config({
baseUrl: 'api',
filename: 'resource-glob-deny.json',
path: './tests/config'
});
res = httpMocks.createResponse();
next = function() {
res.send(response.success);
};
done();
});
it('Should deny access to resource /api/mangoes/42', function(done) {
req = httpMocks.createRequest({
method: 'POST',
url: '/api/mangoes/42'
});
req.decoded = {};
req.session = {};
req.decoded.role = 'user';
acl.authorize(req, res, next);
data = JSON.parse(res._getData());
assert(data, true);
assert(typeof data, 'object');
assert.deepEqual(data, response.restricted);
done();
});
it('Should deny access to resource /api/mangoes/42', function(done) {
req = httpMocks.createRequest({
method: 'PUT',
url: '/api/mangoes/42'
});
req.decoded = {};
req.session = {};
req.decoded.role = 'user';
acl.authorize(req, res, next);
data = JSON.parse(res._getData());
assert(data, true);
assert(typeof data, 'object');
assert.deepEqual(data, response.restricted);
done();
});
it('Should allow access to resource /api/user/42', function(done) {
req = httpMocks.createRequest({
method: 'DElETE',
url: '/api/mangoes/42'
});
req.decoded = {};
req.session = {};
req.decoded.role = 'user';
acl.authorize(req, res, next);
data = res._getData();
assert(data, true);
assert.deepEqual(data, response.success);
done();
});
});
context('When action allow', function() {
beforeEach(function(done) {
acl.config({
baseUrl: 'api',
filename: 'resource-glob-allow.json',
path: './tests/config'
});
res = httpMocks.createResponse();
done();
});
it('Should allow access to resource /api/mangoes/42', function(done) {
req = httpMocks.createRequest({
method: 'POST',
url: '/api/mangoes/42'
});
req.decoded = {};
req.session = {};
req.decoded.role = 'user';
acl.authorize(req, res, next);
data = res._getData();
assert(data, true);
assert.deepEqual(data, response.success);
done();
});
it('Should allow access to resource /api/mangoes/42', function(done) {
req = httpMocks.createRequest({
method: 'PUT',
url: '/api/mangoes/42'
});
req.decoded = {};
req.session = {};
req.decoded.role = 'user';
acl.authorize(req, res, next);
data = res._getData();
assert(data, true);
assert.deepEqual(data, response.success);
done();
});
it('Should deny access to resource /api/user/42', function(done) {
req = httpMocks.createRequest({
method: 'DElETE',
url: '/api/mangoes/42',
params: {
id: 42
}
});
req.decoded = {};
req.decoded.role = 'user';
acl.authorize(req, res, next);
data = JSON.parse(res._getData());
assert(data, true);
assert.deepEqual(data, response.restricted);
done();
});
});
});
|
import { expect } from 'chai'
import beforeDate from './beforeDate';
describe('The before date validator', () => {
const parentVm = {
date: '01/11/2001'
};
const formatParentVm = {
date: '01/17'
}
it('should determine if a date is before another date', () => {
expect(beforeDate('date')('01/10/2001', parentVm)).to.be.true;
expect(beforeDate('date')('01/11/2000', parentVm)).to.be.true;
});
it('should accept a format string', () => {
expect(beforeDate('date', 'MM/YY')('01/16', formatParentVm)).to.be.true;
});
it('should return false if a date is not before', () => {
expect(beforeDate('date')('01/13/2001', parentVm)).to.be.false;
});
it('should return false for a date with a format string', () => {
expect(beforeDate('date', 'MM/YY')('01/18', formatParentVm)).to.be.false;
});
it('should fail for invalid dates', () => {
expect(beforeDate('date')('01/32/2001', parentVm)).to.be.false;
})
});
|
'use strict';
exports.BattleFormats = {
pokemon: {
effectType: 'Banlist',
onValidateSet: function (set, format) {
if (set.moves) {
for (let i = 0; i < set.moves.length; i++) {
let move = this.getMove(set.moves[i]);
if (move.gen > this.gen && move.id !== 'trickroom'){
problems.push(move.name + ' does not exist in gen ' + this.gen + '.');
} else if (move.isNonstandard) {
problems.push(move.name + ' is not a real move.');
}
}
}
}
},
};
|
define([
'jquery'
], function(
$
){
var sim = function( world, Physics ){
var $win = $(window)
,viewWidth = $win.width()
,viewHeight = $win.height()
,viewportBounds = Physics.aabb(0, 0, viewWidth, viewHeight)
,edgeBounce = Physics.behavior('edge-collision-detection', {
aabb: viewportBounds,
restitution: 0.99,
cof: 0.99
})
;
$(window).on('resize', function(){
viewWidth = $win.width();
viewHeight = $win.height();
viewportBounds = Physics.aabb(0, 0, viewWidth, viewHeight);
edgeBounce.setAABB( viewportBounds );
}).trigger('resize');
// begin
var circles = [];
circles.push(
Physics.body('circle', {
x: 400,
y: 100,
vx: 0,
radius: 30
})
);
circles.push(
Physics.body('circle', {
x: 160,
y: 300,
radius: 45,
mass: 2,
vx: 0.05,
vy: -0.15,
angularVelocity: 0.01
})
);
circles.push(
Physics.body('circle', {
x: Physics.util.random(60, 400),
y: Physics.util.random(500),
radius: 60,
mass: 1.5,
vx: 0.25,
vy: .1
})
);
// add things to world
world.add( circles );
world.add( edgeBounce );
world.add( Physics.behavior('body-impulse-response') );
// add gravity
world.add( Physics.behavior('constant-acceleration') );
};
sim.title = "Simple bouncing balls";
sim.sourceUrl = "https://github.com/wellcaffeinated/PhysicsJS/blob/master/examples/sims/simple.js";
return sim;
}); |
var gulp = require('gulp');
var glob = require('glob');
var path = require('path');
var fs = require('fs');
var gutil = require('gulp-util');
var config = require('../config');
var chalk = require('chalk');
/**
* Collect extensions styles looking in modules with name matching mozaik-ext-*
*/
gulp.task('collect:styles', function (done) {
gutil.log(chalk.green('Collecting extensions styles'));
var files = glob.sync(config.root + 'node_modules/mozaik-ext-*/styl/index.styl');
var lines = [
'/**',
' * This file is generated by gulp collect:styl task, do not edit',
' */'
];
files.forEach(function (file) {
lines.push('@require "' + path.relative(config.mozaikSrc + 'ext', file) + '";');
});
fs.writeFile(config.mozaikSrc + 'ext/collected.styl', lines.join('\n'), function (err) {
if (err) {
throw err;
}
});
done();
}); |
"use strict";
var nonCapturing = function(pattern) {
return ('(?:' + pattern + ')');
};
var oneOf = function(choices) {
return (nonCapturing(choices.join('|')));
};
var atBeginning = function(pattern) {
return ('^' + pattern);
};
var atEnd = function(pattern) {
return (pattern + '$');
};
module.exports = {
nonCapturing: nonCapturing,
oneOf: oneOf,
atBeginning: atBeginning,
atEnd: atEnd
};
|
// DATA_TEMPLATE: dom_data
oTest.fnStart("Cookie callback");
$(document).ready(function () {
var mPass;
/* Note that in order to be fully effective here for saving state, there would need to be a
* stringify function to serialise the data array
*/
oTest.fnTest(
"null by default",
function () {
$('#example').dataTable();
},
function () {
return $('#example').dataTable().fnSettings().fnCookieCallback == null;
}
);
oTest.fnTest(
"Number of arguments",
function () {
$('#example').dataTable({
"bDestroy": true,
"bStateSave": true,
"fnCookieCallback": function (sName, oData, sExpires, sPath) {
mPass = arguments.length;
return sName + "=; expires=" + sExpires + "; path=" + sPath;
}
});
},
function () {
return mPass == 4;
}
);
oTest.fnTest(
"Name",
function () {
$('#example').dataTable({
"bDestroy": true,
"bStateSave": true,
"fnCookieCallback": function (sName, oData, sExpires, sPath) {
mPass = sName == "SpryMedia_DataTables_example_dom_data.php";
return sName + "=; expires=" + sExpires + "; path=" + sPath;
}
});
},
function () {
return mPass;
}
);
oTest.fnTest(
"Data",
function () {
$('#example').dataTable({
"bDestroy": true,
"bStateSave": true,
"fnCookieCallback": function (sName, oData, sExpires, sPath) {
mPass = typeof oData.iStart != 'undefined';
return sName + "=; expires=" + sExpires + "; path=" + sPath;
}
});
},
function () {
return mPass;
}
);
oTest.fnTest(
"Expires",
function () {
$('#example').dataTable({
"bDestroy": true,
"bStateSave": true,
"fnCookieCallback": function (sName, oData, sExpires, sPath) {
mPass = typeof sExpires == 'string';
return sName + "=; expires=" + sExpires + "; path=" + sPath;
}
});
},
function () {
return mPass;
}
);
oTest.fnTest(
"Path",
function () {
$('#example').dataTable({
"bDestroy": true,
"bStateSave": true,
"fnCookieCallback": function (sName, oData, sExpires, sPath) {
mPass = sPath.match(/media\/unit_testing\/templates/);
return sName + "=; expires=" + sExpires + "; path=" + sPath;
}
});
},
function () {
return mPass;
}
);
oTest.fnCookieDestroy($('#example').dataTable());
oTest.fnComplete();
});
|
import { MMOMDatabase, MMOMStatement } from './mmom';
const { AXIOM, PROVABLE, OPEN, CLOSE, CONSTANT, VARIABLE, FLOATING, ESSENTIAL, DV, MAX_TYPE } = MMOMStatement;
const ALL_FILTER = new Int32Array(MAX_TYPE+1); [ AXIOM, PROVABLE, OPEN, CLOSE, CONSTANT, VARIABLE, FLOATING, ESSENTIAL, DV ].forEach( type => ALL_FILTER[type] = 1 );
const PINK_FILTER = new Int32Array(MAX_TYPE+1); [ AXIOM, PROVABLE ].forEach( type => PINK_FILTER[type] = 1 );
// This is an extremely simple example of an analyzer, as it has no error conditions
class MMOMNumberer {
constructor(db) {
this._db = db;
this._dirty = true;
this._counts = new Int32Array();
this._pink = new Int32Array();
this._all = new Int32Array();
this._db._observer.push(this);
}
notifyChanged(rec) {
this._dirty = true;
}
_scan() {
this._dirty = false;
let counts = this._counts = new Int32Array(MAX_TYPE + 1);
for (let i = 0; i < this._db.statements.length; i++)
counts[this._db.statements[i].type]++;
let pinkCount = 0, allCount = 0;
for (let i = 0; i <= MAX_TYPE; i++) {
if (ALL_FILTER[i]) allCount += counts[i];
if (PINK_FILTER[i]) pinkCount += counts[i];
}
let pink = this._pink = new Int32Array(pinkCount);
let all = this._all = new Int32Array(allCount);
let j = 0, k = 0;
for (let i = 0; i < this._db.statements.length; i++) {
let type = this._db.statements[i].type;
if (ALL_FILTER[type]) all[k++] = i;
if (PINK_FILTER[type]) pink[j++] = i;
}
}
_update() {
if (this._dirty) this._scan();
return this;
}
get counts() { return this._update()._counts; }
}
MMOMDatabase.prototype.statementByPinkNumber = function (nr) {
nr |= 0;
let array = this.numberer._update()._pink;
if (nr <= 0 || nr > array.length) throw new RangeError('pinkNumber out of range');
return this.statement(array[nr - 1]);
};
MMOMDatabase.prototype.statementByMetamathNumber = function (nr) {
nr |= 0;
let array = this.numberer._update()._all;
if (nr <= 0 || nr > array.length) throw new RangeError('metamathNumber out of range');
return this.statement(array[nr - 1]);
};
Object.defineProperty(MMOMDatabase.prototype, 'assertionCount', { get: function () {
return this.numberer._update()._pink.length;
}});
function search(ary, val) {
let j = 0, k = ary.length, l;
if (k === 0) return -1;
while (k - j > 1) {
l = (j + k) >>> 1;
if (val >= ary[l]) {
j = l;
}
else {
k = l;
}
}
return (ary[j] === val) ? j : -1;
}
Object.defineProperty(MMOMStatement.prototype, 'pinkNumber', { get: function () {
let db = this.database;
let array = db && db.numberer._update()._pink;
let index = array ? search(array, this.index) : -1;
if (index < 0) throw new TypeError('statement does not have a pinkNumber');
return index + 1;
}});
Object.defineProperty(MMOMStatement.prototype, 'metamathNumber', { get: function () {
let db = this.database;
let array = db && db.numberer._update()._all;
let index = array ? search(array, this.index) : -1;
if (index < 0) throw new TypeError('statement does not have a metamathNumber');
return index + 1;
}});
MMOMDatabase.registerAnalyzer('numberer', MMOMNumberer);
|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var Template = require("./Template");
function HotUpdateChunkTemplate(outputOptions) {
Template.call(this, outputOptions);
}
module.exports = HotUpdateChunkTemplate;
HotUpdateChunkTemplate.prototype = Object.create(Template.prototype);
HotUpdateChunkTemplate.prototype.constructor = HotUpdateChunkTemplate;
HotUpdateChunkTemplate.prototype.render = function(id, modules, hash, moduleTemplate, dependencyTemplates) {
var modulesSource = this.renderChunkModules({
id: id,
modules: modules
}, moduleTemplate, dependencyTemplates);
var core = this.applyPluginsWaterfall("modules", modulesSource, modules, moduleTemplate, dependencyTemplates);
var source = this.applyPluginsWaterfall("render", core, modules, hash, id, moduleTemplate, dependencyTemplates);
return source;
};
HotUpdateChunkTemplate.prototype.updateHash = function(hash) {
hash.update("HotUpdateChunkTemplate");
hash.update("1");
this.applyPlugins("hash", hash);
};
|
var searchData=
[
['fetchdata',['FetchData',['../class_u_e4_a_m___d_b_handler.html#a3858bee81ad39a80260c2fc0989ba358',1,'UE4AM_DBHandler']]],
['fixsc',['FixSC',['../class_u_e4_a_m___d_b_handler.html#a15e31611d6efcedddeeafd7d25a7e583',1,'UE4AM_DBHandler']]]
];
|
/*!
* jQuery UI Core 1.11.0
* http://jqueryui.com
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/category/ui-core/
*/
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define( [ "jquery" ], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
// $.ui might exist from components with no dependencies, e.g., $.ui.position
$.ui = $.ui || {};
$.extend( $.ui, {
version: "1.11.0",
keyCode: {
BACKSPACE: 8,
COMMA: 188,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
LEFT: 37,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SPACE: 32,
TAB: 9,
UP: 38
}
});
// plugins
$.fn.extend({
scrollParent: function() {
var position = this.css( "position" ),
excludeStaticParent = position === "absolute",
scrollParent = this.parents().filter( function() {
var parent = $( this );
if ( excludeStaticParent && parent.css( "position" ) === "static" ) {
return false;
}
return (/(auto|scroll)/).test( parent.css( "overflow" ) + parent.css( "overflow-y" ) + parent.css( "overflow-x" ) );
}).eq( 0 );
return position === "fixed" || !scrollParent.length ? $( this[ 0 ].ownerDocument || document ) : scrollParent;
},
uniqueId: (function() {
var uuid = 0;
return function() {
return this.each(function() {
if ( !this.id ) {
this.id = "ui-id-" + ( ++uuid );
}
});
};
})(),
removeUniqueId: function() {
return this.each(function() {
if ( /^ui-id-\d+$/.test( this.id ) ) {
$( this ).removeAttr( "id" );
}
});
}
});
// selectors
function focusable( element, isTabIndexNotNaN ) {
var map, mapName, img,
nodeName = element.nodeName.toLowerCase();
if ( "area" === nodeName ) {
map = element.parentNode;
mapName = map.name;
if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
return false;
}
img = $( "img[usemap=#" + mapName + "]" )[0];
return !!img && visible( img );
}
return ( /input|select|textarea|button|object/.test( nodeName ) ?
!element.disabled :
"a" === nodeName ?
element.href || isTabIndexNotNaN :
isTabIndexNotNaN) &&
// the element and all of its ancestors must be visible
visible( element );
}
function visible( element ) {
return $.expr.filters.visible( element ) &&
!$( element ).parents().addBack().filter(function() {
return $.css( this, "visibility" ) === "hidden";
}).length;
}
$.extend( $.expr[ ":" ], {
data: $.expr.createPseudo ?
$.expr.createPseudo(function( dataName ) {
return function( elem ) {
return !!$.data( elem, dataName );
};
}) :
// support: jQuery <1.8
function( elem, i, match ) {
return !!$.data( elem, match[ 3 ] );
},
focusable: function( element ) {
return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
},
tabbable: function( element ) {
var tabIndex = $.attr( element, "tabindex" ),
isTabIndexNaN = isNaN( tabIndex );
return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
}
});
// support: jQuery <1.8
if ( !$( "<a>" ).outerWidth( 1 ).jquery ) {
$.each( [ "Width", "Height" ], function( i, name ) {
var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
type = name.toLowerCase(),
orig = {
innerWidth: $.fn.innerWidth,
innerHeight: $.fn.innerHeight,
outerWidth: $.fn.outerWidth,
outerHeight: $.fn.outerHeight
};
function reduce( elem, size, border, margin ) {
$.each( side, function() {
size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
if ( border ) {
size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
}
if ( margin ) {
size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
}
});
return size;
}
$.fn[ "inner" + name ] = function( size ) {
if ( size === undefined ) {
return orig[ "inner" + name ].call( this );
}
return this.each(function() {
$( this ).css( type, reduce( this, size ) + "px" );
});
};
$.fn[ "outer" + name] = function( size, margin ) {
if ( typeof size !== "number" ) {
return orig[ "outer" + name ].call( this, size );
}
return this.each(function() {
$( this).css( type, reduce( this, size, true, margin ) + "px" );
});
};
});
}
// support: jQuery <1.8
if ( !$.fn.addBack ) {
$.fn.addBack = function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
};
}
// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
$.fn.removeData = (function( removeData ) {
return function( key ) {
if ( arguments.length ) {
return removeData.call( this, $.camelCase( key ) );
} else {
return removeData.call( this );
}
};
})( $.fn.removeData );
}
// deprecated
$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() );
$.fn.extend({
focus: (function( orig ) {
return function( delay, fn ) {
return typeof delay === "number" ?
this.each(function() {
var elem = this;
setTimeout(function() {
$( elem ).focus();
if ( fn ) {
fn.call( elem );
}
}, delay );
}) :
orig.apply( this, arguments );
};
})( $.fn.focus ),
disableSelection: (function() {
var eventType = "onselectstart" in document.createElement( "div" ) ?
"selectstart" :
"mousedown";
return function() {
return this.bind( eventType + ".ui-disableSelection", function( event ) {
event.preventDefault();
});
};
})(),
enableSelection: function() {
return this.unbind( ".ui-disableSelection" );
},
zIndex: function( zIndex ) {
if ( zIndex !== undefined ) {
return this.css( "zIndex", zIndex );
}
if ( this.length ) {
var elem = $( this[ 0 ] ), position, value;
while ( elem.length && elem[ 0 ] !== document ) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css( "position" );
if ( position === "absolute" || position === "relative" || position === "fixed" ) {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt( elem.css( "zIndex" ), 10 );
if ( !isNaN( value ) && value !== 0 ) {
return value;
}
}
elem = elem.parent();
}
}
return 0;
}
});
// $.ui.plugin is deprecated. Use $.widget() extensions instead.
$.ui.plugin = {
add: function( module, option, set ) {
var i,
proto = $.ui[ module ].prototype;
for ( i in set ) {
proto.plugins[ i ] = proto.plugins[ i ] || [];
proto.plugins[ i ].push( [ option, set[ i ] ] );
}
},
call: function( instance, name, args, allowDisconnected ) {
var i,
set = instance.plugins[ name ];
if ( !set ) {
return;
}
if ( !allowDisconnected && ( !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) ) {
return;
}
for ( i = 0; i < set.length; i++ ) {
if ( instance.options[ set[ i ][ 0 ] ] ) {
set[ i ][ 1 ].apply( instance.element, args );
}
}
}
};
}));
/*!
* jQuery UI Datepicker 1.11.0
* http://jqueryui.com
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/datepicker/
*/
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([
"jquery",
"./core"
], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
$.extend($.ui, { datepicker: { version: "1.11.0" } });
var datepicker_instActive;
function datepicker_getZindex( elem ) {
var position, value;
while ( elem.length && elem[ 0 ] !== document ) {
// Ignore z-index if position is set to a value where z-index is ignored by the browser
// This makes behavior of this function consistent across browsers
// WebKit always returns auto if the element is positioned
position = elem.css( "position" );
if ( position === "absolute" || position === "relative" || position === "fixed" ) {
// IE returns 0 when zIndex is not specified
// other browsers return a string
// we ignore the case of nested elements with an explicit value of 0
// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
value = parseInt( elem.css( "zIndex" ), 10 );
if ( !isNaN( value ) && value !== 0 ) {
return value;
}
}
elem = elem.parent();
}
return 0;
}
/* Date picker manager.
Use the singleton instance of this class, $.datepicker, to interact with the date picker.
Settings for (groups of) date pickers are maintained in an instance object,
allowing multiple different settings on the same page. */
function Datepicker() {
this._curInst = null; // The current instance in use
this._keyEvent = false; // If the last event was a key event
this._disabledInputs = []; // List of date picker inputs that have been disabled
this._datepickerShowing = false; // True if the popup picker is showing , false if not
this._inDialog = false; // True if showing within a "dialog", false if not
this._mainDivId = "ui-datepicker-div"; // The ID of the main datepicker division
this._inlineClass = "ui-datepicker-inline"; // The name of the inline marker class
this._appendClass = "ui-datepicker-append"; // The name of the append marker class
this._triggerClass = "ui-datepicker-trigger"; // The name of the trigger marker class
this._dialogClass = "ui-datepicker-dialog"; // The name of the dialog marker class
this._disableClass = "ui-datepicker-disabled"; // The name of the disabled covering marker class
this._unselectableClass = "ui-datepicker-unselectable"; // The name of the unselectable cell marker class
this._currentClass = "ui-datepicker-current-day"; // The name of the current day marker class
this._dayOverClass = "ui-datepicker-days-cell-over"; // The name of the day hover marker class
this.regional = []; // Available regional settings, indexed by language code
this.regional[""] = { // Default regional settings
closeText: "Done", // Display text for close link
prevText: "Prev", // Display text for previous month link
nextText: "Next", // Display text for next month link
currentText: "Today", // Display text for current month link
monthNames: ["January","February","March","April","May","June",
"July","August","September","October","November","December"], // Names of months for drop-down and formatting
monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // For formatting
dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], // For formatting
dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], // For formatting
dayNamesMin: ["Su","Mo","Tu","We","Th","Fr","Sa"], // Column headings for days starting at Sunday
weekHeader: "Wk", // Column header for week of the year
dateFormat: "mm/dd/yy", // See format options on parseDate
firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
isRTL: false, // True if right-to-left language, false if left-to-right
showMonthAfterYear: false, // True if the year select precedes month, false for month then year
yearSuffix: "" // Additional text to append to the year in the month headers
};
this._defaults = { // Global defaults for all the date picker instances
showOn: "focus", // "focus" for popup on focus,
// "button" for trigger button, or "both" for either
showAnim: "fadeIn", // Name of jQuery animation for popup
showOptions: {}, // Options for enhanced animations
defaultDate: null, // Used when field is blank: actual date,
// +/-number for offset from today, null for today
appendText: "", // Display text following the input box, e.g. showing the format
buttonText: "...", // Text for trigger button
buttonImage: "", // URL for trigger button image
buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
hideIfNoPrevNext: false, // True to hide next/previous month links
// if not applicable, false to just disable them
navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
gotoCurrent: false, // True if today link goes back to current selection instead
changeMonth: false, // True if month can be selected directly, false if only prev/next
changeYear: false, // True if year can be selected directly, false if only prev/next
yearRange: "c-10:c+10", // Range of years to display in drop-down,
// either relative to today's year (-nn:+nn), relative to currently displayed year
// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
showOtherMonths: false, // True to show dates in other months, false to leave blank
selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
showWeek: false, // True to show week of the year, false to not show it
calculateWeek: this.iso8601Week, // How to calculate the week of the year,
// takes a Date and returns the number of the week for it
shortYearCutoff: "+10", // Short year values < this are in the current century,
// > this are in the previous century,
// string value starting with "+" for current year + value
minDate: null, // The earliest selectable date, or null for no limit
maxDate: null, // The latest selectable date, or null for no limit
duration: "fast", // Duration of display/closure
beforeShowDay: null, // Function that takes a date and returns an array with
// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or "",
// [2] = cell title (optional), e.g. $.datepicker.noWeekends
beforeShow: null, // Function that takes an input field and
// returns a set of custom settings for the date picker
onSelect: null, // Define a callback function when a date is selected
onChangeMonthYear: null, // Define a callback function when the month or year is changed
onClose: null, // Define a callback function when the datepicker is closed
numberOfMonths: 1, // Number of months to show at a time
showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
stepMonths: 1, // Number of months to step back/forward
stepBigMonths: 12, // Number of months to step back/forward for the big links
altField: "", // Selector for an alternate field to store selected dates into
altFormat: "", // The date format to use for the alternate field
constrainInput: true, // The input is constrained by the current date format
showButtonPanel: false, // True to show button panel, false to not show it
autoSize: false, // True to size the input for the date format, false to leave as is
disabled: false // The initial disabled state
};
$.extend(this._defaults, this.regional[""]);
this.regional.en = $.extend( true, {}, this.regional[ "" ]);
this.regional[ "en-US" ] = $.extend( true, {}, this.regional.en );
this.dpDiv = datepicker_bindHover($("<div id='" + this._mainDivId + "' class='ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>"));
}
$.extend(Datepicker.prototype, {
/* Class name added to elements to indicate already configured with a date picker. */
markerClassName: "hasDatepicker",
//Keep track of the maximum number of rows displayed (see #7043)
maxRows: 4,
// TODO rename to "widget" when switching to widget factory
_widgetDatepicker: function() {
return this.dpDiv;
},
/* Override the default settings for all instances of the date picker.
* @param settings object - the new settings to use as defaults (anonymous object)
* @return the manager object
*/
setDefaults: function(settings) {
datepicker_extendRemove(this._defaults, settings || {});
return this;
},
/* Attach the date picker to a jQuery selection.
* @param target element - the target input field or division or span
* @param settings object - the new settings to use for this date picker instance (anonymous)
*/
_attachDatepicker: function(target, settings) {
var nodeName, inline, inst;
nodeName = target.nodeName.toLowerCase();
inline = (nodeName === "div" || nodeName === "span");
if (!target.id) {
this.uuid += 1;
target.id = "dp" + this.uuid;
}
inst = this._newInst($(target), inline);
inst.settings = $.extend({}, settings || {});
if (nodeName === "input") {
this._connectDatepicker(target, inst);
} else if (inline) {
this._inlineDatepicker(target, inst);
}
},
/* Create a new instance object. */
_newInst: function(target, inline) {
var id = target[0].id.replace(/([^A-Za-z0-9_\-])/g, "\\\\$1"); // escape jQuery meta chars
return {id: id, input: target, // associated target
selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
drawMonth: 0, drawYear: 0, // month being drawn
inline: inline, // is datepicker inline or not
dpDiv: (!inline ? this.dpDiv : // presentation div
datepicker_bindHover($("<div class='" + this._inlineClass + " ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all'></div>")))};
},
/* Attach the date picker to an input field. */
_connectDatepicker: function(target, inst) {
var input = $(target);
inst.append = $([]);
inst.trigger = $([]);
if (input.hasClass(this.markerClassName)) {
return;
}
this._attachments(input, inst);
input.addClass(this.markerClassName).keydown(this._doKeyDown).
keypress(this._doKeyPress).keyup(this._doKeyUp);
this._autoSize(inst);
$.data(target, "datepicker", inst);
//If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
if( inst.settings.disabled ) {
this._disableDatepicker( target );
}
},
/* Make attachments based on settings. */
_attachments: function(input, inst) {
var showOn, buttonText, buttonImage,
appendText = this._get(inst, "appendText"),
isRTL = this._get(inst, "isRTL");
if (inst.append) {
inst.append.remove();
}
if (appendText) {
inst.append = $("<span class='" + this._appendClass + "'>" + appendText + "</span>");
input[isRTL ? "before" : "after"](inst.append);
}
input.unbind("focus", this._showDatepicker);
if (inst.trigger) {
inst.trigger.remove();
}
showOn = this._get(inst, "showOn");
if (showOn === "focus" || showOn === "both") { // pop-up date picker when in the marked field
input.focus(this._showDatepicker);
}
if (showOn === "button" || showOn === "both") { // pop-up date picker when button clicked
buttonText = this._get(inst, "buttonText");
buttonImage = this._get(inst, "buttonImage");
inst.trigger = $(this._get(inst, "buttonImageOnly") ?
$("<img/>").addClass(this._triggerClass).
attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
$("<button type='button'></button>").addClass(this._triggerClass).
html(!buttonImage ? buttonText : $("<img/>").attr(
{ src:buttonImage, alt:buttonText, title:buttonText })));
input[isRTL ? "before" : "after"](inst.trigger);
inst.trigger.click(function() {
if ($.datepicker._datepickerShowing && $.datepicker._lastInput === input[0]) {
$.datepicker._hideDatepicker();
} else if ($.datepicker._datepickerShowing && $.datepicker._lastInput !== input[0]) {
$.datepicker._hideDatepicker();
$.datepicker._showDatepicker(input[0]);
} else {
$.datepicker._showDatepicker(input[0]);
}
return false;
});
}
},
/* Apply the maximum length for the date format. */
_autoSize: function(inst) {
if (this._get(inst, "autoSize") && !inst.inline) {
var findMax, max, maxI, i,
date = new Date(2009, 12 - 1, 20), // Ensure double digits
dateFormat = this._get(inst, "dateFormat");
if (dateFormat.match(/[DM]/)) {
findMax = function(names) {
max = 0;
maxI = 0;
for (i = 0; i < names.length; i++) {
if (names[i].length > max) {
max = names[i].length;
maxI = i;
}
}
return maxI;
};
date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
"monthNames" : "monthNamesShort"))));
date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
"dayNames" : "dayNamesShort"))) + 20 - date.getDay());
}
inst.input.attr("size", this._formatDate(inst, date).length);
}
},
/* Attach an inline date picker to a div. */
_inlineDatepicker: function(target, inst) {
var divSpan = $(target);
if (divSpan.hasClass(this.markerClassName)) {
return;
}
divSpan.addClass(this.markerClassName).append(inst.dpDiv);
$.data(target, "datepicker", inst);
this._setDate(inst, this._getDefaultDate(inst), true);
this._updateDatepicker(inst);
this._updateAlternate(inst);
//If disabled option is true, disable the datepicker before showing it (see ticket #5665)
if( inst.settings.disabled ) {
this._disableDatepicker( target );
}
// Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
// http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
inst.dpDiv.css( "display", "block" );
},
/* Pop-up the date picker in a "dialog" box.
* @param input element - ignored
* @param date string or Date - the initial date to display
* @param onSelect function - the function to call when a date is selected
* @param settings object - update the dialog date picker instance's settings (anonymous object)
* @param pos int[2] - coordinates for the dialog's position within the screen or
* event - with x/y coordinates or
* leave empty for default (screen centre)
* @return the manager object
*/
_dialogDatepicker: function(input, date, onSelect, settings, pos) {
var id, browserWidth, browserHeight, scrollX, scrollY,
inst = this._dialogInst; // internal instance
if (!inst) {
this.uuid += 1;
id = "dp" + this.uuid;
this._dialogInput = $("<input type='text' id='" + id +
"' style='position: absolute; top: -100px; width: 0px;'/>");
this._dialogInput.keydown(this._doKeyDown);
$("body").append(this._dialogInput);
inst = this._dialogInst = this._newInst(this._dialogInput, false);
inst.settings = {};
$.data(this._dialogInput[0], "datepicker", inst);
}
datepicker_extendRemove(inst.settings, settings || {});
date = (date && date.constructor === Date ? this._formatDate(inst, date) : date);
this._dialogInput.val(date);
this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
if (!this._pos) {
browserWidth = document.documentElement.clientWidth;
browserHeight = document.documentElement.clientHeight;
scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
scrollY = document.documentElement.scrollTop || document.body.scrollTop;
this._pos = // should use actual width/height below
[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
}
// move input on screen for focus, but hidden behind dialog
this._dialogInput.css("left", (this._pos[0] + 20) + "px").css("top", this._pos[1] + "px");
inst.settings.onSelect = onSelect;
this._inDialog = true;
this.dpDiv.addClass(this._dialogClass);
this._showDatepicker(this._dialogInput[0]);
if ($.blockUI) {
$.blockUI(this.dpDiv);
}
$.data(this._dialogInput[0], "datepicker", inst);
return this;
},
/* Detach a datepicker from its control.
* @param target element - the target input field or division or span
*/
_destroyDatepicker: function(target) {
var nodeName,
$target = $(target),
inst = $.data(target, "datepicker");
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
$.removeData(target, "datepicker");
if (nodeName === "input") {
inst.append.remove();
inst.trigger.remove();
$target.removeClass(this.markerClassName).
unbind("focus", this._showDatepicker).
unbind("keydown", this._doKeyDown).
unbind("keypress", this._doKeyPress).
unbind("keyup", this._doKeyUp);
} else if (nodeName === "div" || nodeName === "span") {
$target.removeClass(this.markerClassName).empty();
}
},
/* Enable the date picker to a jQuery selection.
* @param target element - the target input field or division or span
*/
_enableDatepicker: function(target) {
var nodeName, inline,
$target = $(target),
inst = $.data(target, "datepicker");
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
if (nodeName === "input") {
target.disabled = false;
inst.trigger.filter("button").
each(function() { this.disabled = false; }).end().
filter("img").css({opacity: "1.0", cursor: ""});
} else if (nodeName === "div" || nodeName === "span") {
inline = $target.children("." + this._inlineClass);
inline.children().removeClass("ui-state-disabled");
inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
prop("disabled", false);
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value === target ? null : value); }); // delete entry
},
/* Disable the date picker to a jQuery selection.
* @param target element - the target input field or division or span
*/
_disableDatepicker: function(target) {
var nodeName, inline,
$target = $(target),
inst = $.data(target, "datepicker");
if (!$target.hasClass(this.markerClassName)) {
return;
}
nodeName = target.nodeName.toLowerCase();
if (nodeName === "input") {
target.disabled = true;
inst.trigger.filter("button").
each(function() { this.disabled = true; }).end().
filter("img").css({opacity: "0.5", cursor: "default"});
} else if (nodeName === "div" || nodeName === "span") {
inline = $target.children("." + this._inlineClass);
inline.children().addClass("ui-state-disabled");
inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
prop("disabled", true);
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value === target ? null : value); }); // delete entry
this._disabledInputs[this._disabledInputs.length] = target;
},
/* Is the first field in a jQuery collection disabled as a datepicker?
* @param target element - the target input field or division or span
* @return boolean - true if disabled, false if enabled
*/
_isDisabledDatepicker: function(target) {
if (!target) {
return false;
}
for (var i = 0; i < this._disabledInputs.length; i++) {
if (this._disabledInputs[i] === target) {
return true;
}
}
return false;
},
/* Retrieve the instance data for the target control.
* @param target element - the target input field or division or span
* @return object - the associated instance data
* @throws error if a jQuery problem getting data
*/
_getInst: function(target) {
try {
return $.data(target, "datepicker");
}
catch (err) {
throw "Missing instance data for this datepicker";
}
},
/* Update or retrieve the settings for a date picker attached to an input field or division.
* @param target element - the target input field or division or span
* @param name object - the new settings to update or
* string - the name of the setting to change or retrieve,
* when retrieving also "all" for all instance settings or
* "defaults" for all global defaults
* @param value any - the new value for the setting
* (omit if above is an object or to retrieve a value)
*/
_optionDatepicker: function(target, name, value) {
var settings, date, minDate, maxDate,
inst = this._getInst(target);
if (arguments.length === 2 && typeof name === "string") {
return (name === "defaults" ? $.extend({}, $.datepicker._defaults) :
(inst ? (name === "all" ? $.extend({}, inst.settings) :
this._get(inst, name)) : null));
}
settings = name || {};
if (typeof name === "string") {
settings = {};
settings[name] = value;
}
if (inst) {
if (this._curInst === inst) {
this._hideDatepicker();
}
date = this._getDateDatepicker(target, true);
minDate = this._getMinMaxDate(inst, "min");
maxDate = this._getMinMaxDate(inst, "max");
datepicker_extendRemove(inst.settings, settings);
// reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
if (minDate !== null && settings.dateFormat !== undefined && settings.minDate === undefined) {
inst.settings.minDate = this._formatDate(inst, minDate);
}
if (maxDate !== null && settings.dateFormat !== undefined && settings.maxDate === undefined) {
inst.settings.maxDate = this._formatDate(inst, maxDate);
}
if ( "disabled" in settings ) {
if ( settings.disabled ) {
this._disableDatepicker(target);
} else {
this._enableDatepicker(target);
}
}
this._attachments($(target), inst);
this._autoSize(inst);
this._setDate(inst, date);
this._updateAlternate(inst);
this._updateDatepicker(inst);
}
},
// change method deprecated
_changeDatepicker: function(target, name, value) {
this._optionDatepicker(target, name, value);
},
/* Redraw the date picker attached to an input field or division.
* @param target element - the target input field or division or span
*/
_refreshDatepicker: function(target) {
var inst = this._getInst(target);
if (inst) {
this._updateDatepicker(inst);
}
},
/* Set the dates for a jQuery selection.
* @param target element - the target input field or division or span
* @param date Date - the new date
*/
_setDateDatepicker: function(target, date) {
var inst = this._getInst(target);
if (inst) {
this._setDate(inst, date);
this._updateDatepicker(inst);
this._updateAlternate(inst);
}
},
/* Get the date(s) for the first entry in a jQuery selection.
* @param target element - the target input field or division or span
* @param noDefault boolean - true if no default date is to be used
* @return Date - the current date
*/
_getDateDatepicker: function(target, noDefault) {
var inst = this._getInst(target);
if (inst && !inst.inline) {
this._setDateFromField(inst, noDefault);
}
return (inst ? this._getDate(inst) : null);
},
/* Handle keystrokes. */
_doKeyDown: function(event) {
var onSelect, dateStr, sel,
inst = $.datepicker._getInst(event.target),
handled = true,
isRTL = inst.dpDiv.is(".ui-datepicker-rtl");
inst._keyEvent = true;
if ($.datepicker._datepickerShowing) {
switch (event.keyCode) {
case 9: $.datepicker._hideDatepicker();
handled = false;
break; // hide on tab out
case 13: sel = $("td." + $.datepicker._dayOverClass + ":not(." +
$.datepicker._currentClass + ")", inst.dpDiv);
if (sel[0]) {
$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
}
onSelect = $.datepicker._get(inst, "onSelect");
if (onSelect) {
dateStr = $.datepicker._formatDate(inst);
// trigger custom callback
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
} else {
$.datepicker._hideDatepicker();
}
return false; // don't submit the form
case 27: $.datepicker._hideDatepicker();
break; // hide on escape
case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
-$.datepicker._get(inst, "stepBigMonths") :
-$.datepicker._get(inst, "stepMonths")), "M");
break; // previous month/year on page up/+ ctrl
case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+$.datepicker._get(inst, "stepBigMonths") :
+$.datepicker._get(inst, "stepMonths")), "M");
break; // next month/year on page down/+ ctrl
case 35: if (event.ctrlKey || event.metaKey) {
$.datepicker._clearDate(event.target);
}
handled = event.ctrlKey || event.metaKey;
break; // clear on ctrl or command +end
case 36: if (event.ctrlKey || event.metaKey) {
$.datepicker._gotoToday(event.target);
}
handled = event.ctrlKey || event.metaKey;
break; // current on ctrl or command +home
case 37: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), "D");
}
handled = event.ctrlKey || event.metaKey;
// -1 day on ctrl or command +left
if (event.originalEvent.altKey) {
$.datepicker._adjustDate(event.target, (event.ctrlKey ?
-$.datepicker._get(inst, "stepBigMonths") :
-$.datepicker._get(inst, "stepMonths")), "M");
}
// next month/year on alt +left on Mac
break;
case 38: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, -7, "D");
}
handled = event.ctrlKey || event.metaKey;
break; // -1 week on ctrl or command +up
case 39: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), "D");
}
handled = event.ctrlKey || event.metaKey;
// +1 day on ctrl or command +right
if (event.originalEvent.altKey) {
$.datepicker._adjustDate(event.target, (event.ctrlKey ?
+$.datepicker._get(inst, "stepBigMonths") :
+$.datepicker._get(inst, "stepMonths")), "M");
}
// next month/year on alt +right
break;
case 40: if (event.ctrlKey || event.metaKey) {
$.datepicker._adjustDate(event.target, +7, "D");
}
handled = event.ctrlKey || event.metaKey;
break; // +1 week on ctrl or command +down
default: handled = false;
}
} else if (event.keyCode === 36 && event.ctrlKey) { // display the date picker on ctrl+home
$.datepicker._showDatepicker(this);
} else {
handled = false;
}
if (handled) {
event.preventDefault();
event.stopPropagation();
}
},
/* Filter entered characters - based on date format. */
_doKeyPress: function(event) {
var chars, chr,
inst = $.datepicker._getInst(event.target);
if ($.datepicker._get(inst, "constrainInput")) {
chars = $.datepicker._possibleChars($.datepicker._get(inst, "dateFormat"));
chr = String.fromCharCode(event.charCode == null ? event.keyCode : event.charCode);
return event.ctrlKey || event.metaKey || (chr < " " || !chars || chars.indexOf(chr) > -1);
}
},
/* Synchronise manual entry and field/alternate field. */
_doKeyUp: function(event) {
var date,
inst = $.datepicker._getInst(event.target);
if (inst.input.val() !== inst.lastVal) {
try {
date = $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
(inst.input ? inst.input.val() : null),
$.datepicker._getFormatConfig(inst));
if (date) { // only if valid
$.datepicker._setDateFromField(inst);
$.datepicker._updateAlternate(inst);
$.datepicker._updateDatepicker(inst);
}
}
catch (err) {
}
}
return true;
},
/* Pop-up the date picker for a given input field.
* If false returned from beforeShow event handler do not show.
* @param input element - the input field attached to the date picker or
* event - if triggered by focus
*/
_showDatepicker: function(input) {
input = input.target || input;
if (input.nodeName.toLowerCase() !== "input") { // find from button/image trigger
input = $("input", input.parentNode)[0];
}
if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput === input) { // already here
return;
}
var inst, beforeShow, beforeShowSettings, isFixed,
offset, showAnim, duration;
inst = $.datepicker._getInst(input);
if ($.datepicker._curInst && $.datepicker._curInst !== inst) {
$.datepicker._curInst.dpDiv.stop(true, true);
if ( inst && $.datepicker._datepickerShowing ) {
$.datepicker._hideDatepicker( $.datepicker._curInst.input[0] );
}
}
beforeShow = $.datepicker._get(inst, "beforeShow");
beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {};
if(beforeShowSettings === false){
return;
}
datepicker_extendRemove(inst.settings, beforeShowSettings);
inst.lastVal = null;
$.datepicker._lastInput = input;
$.datepicker._setDateFromField(inst);
if ($.datepicker._inDialog) { // hide cursor
input.value = "";
}
if (!$.datepicker._pos) { // position below input
$.datepicker._pos = $.datepicker._findPos(input);
$.datepicker._pos[1] += input.offsetHeight; // add the height
}
isFixed = false;
$(input).parents().each(function() {
isFixed |= $(this).css("position") === "fixed";
return !isFixed;
});
offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
$.datepicker._pos = null;
//to avoid flashes on Firefox
inst.dpDiv.empty();
// determine sizing offscreen
inst.dpDiv.css({position: "absolute", display: "block", top: "-1000px"});
$.datepicker._updateDatepicker(inst);
// fix width for dynamic number of date pickers
// and adjust position before showing
offset = $.datepicker._checkOffset(inst, offset, isFixed);
inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
"static" : (isFixed ? "fixed" : "absolute")), display: "none",
left: offset.left + "px", top: offset.top + "px"});
if (!inst.inline) {
showAnim = $.datepicker._get(inst, "showAnim");
duration = $.datepicker._get(inst, "duration");
inst.dpDiv.css( "z-index", datepicker_getZindex( $( input ) ) + 1 );
$.datepicker._datepickerShowing = true;
if ( $.effects && $.effects.effect[ showAnim ] ) {
inst.dpDiv.show(showAnim, $.datepicker._get(inst, "showOptions"), duration);
} else {
inst.dpDiv[showAnim || "show"](showAnim ? duration : null);
}
if ( $.datepicker._shouldFocusInput( inst ) ) {
inst.input.focus();
}
$.datepicker._curInst = inst;
}
},
/* Generate the date picker content. */
_updateDatepicker: function(inst) {
this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
datepicker_instActive = inst; // for delegate hover events
inst.dpDiv.empty().append(this._generateHTML(inst));
this._attachHandlers(inst);
inst.dpDiv.find("." + this._dayOverClass + " a");
var origyearshtml,
numMonths = this._getNumberOfMonths(inst),
cols = numMonths[1],
width = 17;
inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");
if (cols > 1) {
inst.dpDiv.addClass("ui-datepicker-multi-" + cols).css("width", (width * cols) + "em");
}
inst.dpDiv[(numMonths[0] !== 1 || numMonths[1] !== 1 ? "add" : "remove") +
"Class"]("ui-datepicker-multi");
inst.dpDiv[(this._get(inst, "isRTL") ? "add" : "remove") +
"Class"]("ui-datepicker-rtl");
if (inst === $.datepicker._curInst && $.datepicker._datepickerShowing && $.datepicker._shouldFocusInput( inst ) ) {
inst.input.focus();
}
// deffered render of the years select (to avoid flashes on Firefox)
if( inst.yearshtml ){
origyearshtml = inst.yearshtml;
setTimeout(function(){
//assure that inst.yearshtml didn't change.
if( origyearshtml === inst.yearshtml && inst.yearshtml ){
inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml);
}
origyearshtml = inst.yearshtml = null;
}, 0);
}
},
// #6694 - don't focus the input if it's already focused
// this breaks the change event in IE
// Support: IE and jQuery <1.9
_shouldFocusInput: function( inst ) {
return inst.input && inst.input.is( ":visible" ) && !inst.input.is( ":disabled" ) && !inst.input.is( ":focus" );
},
/* Check positioning to remain on screen. */
_checkOffset: function(inst, offset, isFixed) {
var dpWidth = inst.dpDiv.outerWidth(),
dpHeight = inst.dpDiv.outerHeight(),
inputWidth = inst.input ? inst.input.outerWidth() : 0,
inputHeight = inst.input ? inst.input.outerHeight() : 0,
viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft()),
viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop());
offset.left -= (this._get(inst, "isRTL") ? (dpWidth - inputWidth) : 0);
offset.left -= (isFixed && offset.left === inst.input.offset().left) ? $(document).scrollLeft() : 0;
offset.top -= (isFixed && offset.top === (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
// now check if datepicker is showing outside window viewport - move to a better place if so.
offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
Math.abs(offset.left + dpWidth - viewWidth) : 0);
offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
Math.abs(dpHeight + inputHeight) : 0);
return offset;
},
/* Find an object's position on the screen. */
_findPos: function(obj) {
var position,
inst = this._getInst(obj),
isRTL = this._get(inst, "isRTL");
while (obj && (obj.type === "hidden" || obj.nodeType !== 1 || $.expr.filters.hidden(obj))) {
obj = obj[isRTL ? "previousSibling" : "nextSibling"];
}
position = $(obj).offset();
return [position.left, position.top];
},
/* Hide the date picker from view.
* @param input element - the input field attached to the date picker
*/
_hideDatepicker: function(input) {
var showAnim, duration, postProcess, onClose,
inst = this._curInst;
if (!inst || (input && inst !== $.data(input, "datepicker"))) {
return;
}
if (this._datepickerShowing) {
showAnim = this._get(inst, "showAnim");
duration = this._get(inst, "duration");
postProcess = function() {
$.datepicker._tidyDialog(inst);
};
// DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) ) {
inst.dpDiv.hide(showAnim, $.datepicker._get(inst, "showOptions"), duration, postProcess);
} else {
inst.dpDiv[(showAnim === "slideDown" ? "slideUp" :
(showAnim === "fadeIn" ? "fadeOut" : "hide"))]((showAnim ? duration : null), postProcess);
}
if (!showAnim) {
postProcess();
}
this._datepickerShowing = false;
onClose = this._get(inst, "onClose");
if (onClose) {
onClose.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ""), inst]);
}
this._lastInput = null;
if (this._inDialog) {
this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" });
if ($.blockUI) {
$.unblockUI();
$("body").append(this.dpDiv);
}
}
this._inDialog = false;
}
},
/* Tidy up after a dialog display. */
_tidyDialog: function(inst) {
inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar");
},
/* Close date picker if clicked elsewhere. */
_checkExternalClick: function(event) {
if (!$.datepicker._curInst) {
return;
}
var $target = $(event.target),
inst = $.datepicker._getInst($target[0]);
if ( ( ( $target[0].id !== $.datepicker._mainDivId &&
$target.parents("#" + $.datepicker._mainDivId).length === 0 &&
!$target.hasClass($.datepicker.markerClassName) &&
!$target.closest("." + $.datepicker._triggerClass).length &&
$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) ||
( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst !== inst ) ) {
$.datepicker._hideDatepicker();
}
},
/* Adjust one of the date sub-fields. */
_adjustDate: function(id, offset, period) {
var target = $(id),
inst = this._getInst(target[0]);
if (this._isDisabledDatepicker(target[0])) {
return;
}
this._adjustInstDate(inst, offset +
(period === "M" ? this._get(inst, "showCurrentAtPos") : 0), // undo positioning
period);
this._updateDatepicker(inst);
},
/* Action for current link. */
_gotoToday: function(id) {
var date,
target = $(id),
inst = this._getInst(target[0]);
if (this._get(inst, "gotoCurrent") && inst.currentDay) {
inst.selectedDay = inst.currentDay;
inst.drawMonth = inst.selectedMonth = inst.currentMonth;
inst.drawYear = inst.selectedYear = inst.currentYear;
} else {
date = new Date();
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
}
this._notifyChange(inst);
this._adjustDate(target);
},
/* Action for selecting a new month/year. */
_selectMonthYear: function(id, select, period) {
var target = $(id),
inst = this._getInst(target[0]);
inst["selected" + (period === "M" ? "Month" : "Year")] =
inst["draw" + (period === "M" ? "Month" : "Year")] =
parseInt(select.options[select.selectedIndex].value,10);
this._notifyChange(inst);
this._adjustDate(target);
},
/* Action for selecting a day. */
_selectDay: function(id, month, year, td) {
var inst,
target = $(id);
if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
return;
}
inst = this._getInst(target[0]);
inst.selectedDay = inst.currentDay = $("a", td).html();
inst.selectedMonth = inst.currentMonth = month;
inst.selectedYear = inst.currentYear = year;
this._selectDate(id, this._formatDate(inst,
inst.currentDay, inst.currentMonth, inst.currentYear));
},
/* Erase the input field and hide the date picker. */
_clearDate: function(id) {
var target = $(id);
this._selectDate(target, "");
},
/* Update the input field with the selected date. */
_selectDate: function(id, dateStr) {
var onSelect,
target = $(id),
inst = this._getInst(target[0]);
dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
if (inst.input) {
inst.input.val(dateStr);
}
this._updateAlternate(inst);
onSelect = this._get(inst, "onSelect");
if (onSelect) {
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback
} else if (inst.input) {
inst.input.trigger("change"); // fire the change event
}
if (inst.inline){
this._updateDatepicker(inst);
} else {
this._hideDatepicker();
this._lastInput = inst.input[0];
if (typeof(inst.input[0]) !== "object") {
inst.input.focus(); // restore focus
}
this._lastInput = null;
}
},
/* Update any alternate field to synchronise with the main field. */
_updateAlternate: function(inst) {
var altFormat, date, dateStr,
altField = this._get(inst, "altField");
if (altField) { // update alternate field too
altFormat = this._get(inst, "altFormat") || this._get(inst, "dateFormat");
date = this._getDate(inst);
dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
$(altField).each(function() { $(this).val(dateStr); });
}
},
/* Set as beforeShowDay function to prevent selection of weekends.
* @param date Date - the date to customise
* @return [boolean, string] - is this date selectable?, what is its CSS class?
*/
noWeekends: function(date) {
var day = date.getDay();
return [(day > 0 && day < 6), ""];
},
/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
* @param date Date - the date to get the week for
* @return number - the number of the week within the year that contains this date
*/
iso8601Week: function(date) {
var time,
checkDate = new Date(date.getTime());
// Find Thursday of this week starting on Monday
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
},
/* Parse a string value into a date object.
* See formatDate below for the possible formats.
*
* @param format string - the expected format of the date
* @param value string - the date in the above format
* @param settings Object - attributes include:
* shortYearCutoff number - the cutoff year for determining the century (optional)
* dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
* dayNames string[7] - names of the days from Sunday (optional)
* monthNamesShort string[12] - abbreviated names of the months (optional)
* monthNames string[12] - names of the months (optional)
* @return Date - the extracted date value or null if value is blank
*/
parseDate: function (format, value, settings) {
if (format == null || value == null) {
throw "Invalid arguments";
}
value = (typeof value === "object" ? value.toString() : value + "");
if (value === "") {
return null;
}
var iFormat, dim, extra,
iValue = 0,
shortYearCutoffTemp = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff,
shortYearCutoff = (typeof shortYearCutoffTemp !== "string" ? shortYearCutoffTemp :
new Date().getFullYear() % 100 + parseInt(shortYearCutoffTemp, 10)),
dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
year = -1,
month = -1,
day = -1,
doy = -1,
literal = false,
date,
// Check whether a format character is doubled
lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
if (matches) {
iFormat++;
}
return matches;
},
// Extract a number from the string value
getNumber = function(match) {
var isDoubled = lookAhead(match),
size = (match === "@" ? 14 : (match === "!" ? 20 :
(match === "y" && isDoubled ? 4 : (match === "o" ? 3 : 2)))),
digits = new RegExp("^\\d{1," + size + "}"),
num = value.substring(iValue).match(digits);
if (!num) {
throw "Missing number at position " + iValue;
}
iValue += num[0].length;
return parseInt(num[0], 10);
},
// Extract a name from the string value and convert to an index
getName = function(match, shortNames, longNames) {
var index = -1,
names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) {
return [ [k, v] ];
}).sort(function (a, b) {
return -(a[1].length - b[1].length);
});
$.each(names, function (i, pair) {
var name = pair[1];
if (value.substr(iValue, name.length).toLowerCase() === name.toLowerCase()) {
index = pair[0];
iValue += name.length;
return false;
}
});
if (index !== -1) {
return index + 1;
} else {
throw "Unknown name at position " + iValue;
}
},
// Confirm that a literal character matches the string value
checkLiteral = function() {
if (value.charAt(iValue) !== format.charAt(iFormat)) {
throw "Unexpected literal at position " + iValue;
}
iValue++;
};
for (iFormat = 0; iFormat < format.length; iFormat++) {
if (literal) {
if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
literal = false;
} else {
checkLiteral();
}
} else {
switch (format.charAt(iFormat)) {
case "d":
day = getNumber("d");
break;
case "D":
getName("D", dayNamesShort, dayNames);
break;
case "o":
doy = getNumber("o");
break;
case "m":
month = getNumber("m");
break;
case "M":
month = getName("M", monthNamesShort, monthNames);
break;
case "y":
year = getNumber("y");
break;
case "@":
date = new Date(getNumber("@"));
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case "!":
date = new Date((getNumber("!") - this._ticksTo1970) / 10000);
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case "'":
if (lookAhead("'")){
checkLiteral();
} else {
literal = true;
}
break;
default:
checkLiteral();
}
}
}
if (iValue < value.length){
extra = value.substr(iValue);
if (!/^\s+/.test(extra)) {
throw "Extra/unparsed characters found in date: " + extra;
}
}
if (year === -1) {
year = new Date().getFullYear();
} else if (year < 100) {
year += new Date().getFullYear() - new Date().getFullYear() % 100 +
(year <= shortYearCutoff ? 0 : -100);
}
if (doy > -1) {
month = 1;
day = doy;
do {
dim = this._getDaysInMonth(year, month - 1);
if (day <= dim) {
break;
}
month++;
day -= dim;
} while (true);
}
date = this._daylightSavingAdjust(new Date(year, month - 1, day));
if (date.getFullYear() !== year || date.getMonth() + 1 !== month || date.getDate() !== day) {
throw "Invalid date"; // E.g. 31/02/00
}
return date;
},
/* Standard date formats. */
ATOM: "yy-mm-dd", // RFC 3339 (ISO 8601)
COOKIE: "D, dd M yy",
ISO_8601: "yy-mm-dd",
RFC_822: "D, d M y",
RFC_850: "DD, dd-M-y",
RFC_1036: "D, d M y",
RFC_1123: "D, d M yy",
RFC_2822: "D, d M yy",
RSS: "D, d M y", // RFC 822
TICKS: "!",
TIMESTAMP: "@",
W3C: "yy-mm-dd", // ISO 8601
_ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),
/* Format a date object into a string value.
* The format can be combinations of the following:
* d - day of month (no leading zero)
* dd - day of month (two digit)
* o - day of year (no leading zeros)
* oo - day of year (three digit)
* D - day name short
* DD - day name long
* m - month of year (no leading zero)
* mm - month of year (two digit)
* M - month name short
* MM - month name long
* y - year (two digit)
* yy - year (four digit)
* @ - Unix timestamp (ms since 01/01/1970)
* ! - Windows ticks (100ns since 01/01/0001)
* "..." - literal text
* '' - single quote
*
* @param format string - the desired format of the date
* @param date Date - the date value to format
* @param settings Object - attributes include:
* dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
* dayNames string[7] - names of the days from Sunday (optional)
* monthNamesShort string[12] - abbreviated names of the months (optional)
* monthNames string[12] - names of the months (optional)
* @return string - the date in the above format
*/
formatDate: function (format, date, settings) {
if (!date) {
return "";
}
var iFormat,
dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort,
dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames,
monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort,
monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames,
// Check whether a format character is doubled
lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
if (matches) {
iFormat++;
}
return matches;
},
// Format a number, with leading zero if necessary
formatNumber = function(match, value, len) {
var num = "" + value;
if (lookAhead(match)) {
while (num.length < len) {
num = "0" + num;
}
}
return num;
},
// Format a name, short or long as requested
formatName = function(match, value, shortNames, longNames) {
return (lookAhead(match) ? longNames[value] : shortNames[value]);
},
output = "",
literal = false;
if (date) {
for (iFormat = 0; iFormat < format.length; iFormat++) {
if (literal) {
if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
literal = false;
} else {
output += format.charAt(iFormat);
}
} else {
switch (format.charAt(iFormat)) {
case "d":
output += formatNumber("d", date.getDate(), 2);
break;
case "D":
output += formatName("D", date.getDay(), dayNamesShort, dayNames);
break;
case "o":
output += formatNumber("o",
Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
break;
case "m":
output += formatNumber("m", date.getMonth() + 1, 2);
break;
case "M":
output += formatName("M", date.getMonth(), monthNamesShort, monthNames);
break;
case "y":
output += (lookAhead("y") ? date.getFullYear() :
(date.getYear() % 100 < 10 ? "0" : "") + date.getYear() % 100);
break;
case "@":
output += date.getTime();
break;
case "!":
output += date.getTime() * 10000 + this._ticksTo1970;
break;
case "'":
if (lookAhead("'")) {
output += "'";
} else {
literal = true;
}
break;
default:
output += format.charAt(iFormat);
}
}
}
}
return output;
},
/* Extract all possible characters from the date format. */
_possibleChars: function (format) {
var iFormat,
chars = "",
literal = false,
// Check whether a format character is doubled
lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) === match);
if (matches) {
iFormat++;
}
return matches;
};
for (iFormat = 0; iFormat < format.length; iFormat++) {
if (literal) {
if (format.charAt(iFormat) === "'" && !lookAhead("'")) {
literal = false;
} else {
chars += format.charAt(iFormat);
}
} else {
switch (format.charAt(iFormat)) {
case "d": case "m": case "y": case "@":
chars += "0123456789";
break;
case "D": case "M":
return null; // Accept anything
case "'":
if (lookAhead("'")) {
chars += "'";
} else {
literal = true;
}
break;
default:
chars += format.charAt(iFormat);
}
}
}
return chars;
},
/* Get a setting value, defaulting if necessary. */
_get: function(inst, name) {
return inst.settings[name] !== undefined ?
inst.settings[name] : this._defaults[name];
},
/* Parse existing date and initialise date picker. */
_setDateFromField: function(inst, noDefault) {
if (inst.input.val() === inst.lastVal) {
return;
}
var dateFormat = this._get(inst, "dateFormat"),
dates = inst.lastVal = inst.input ? inst.input.val() : null,
defaultDate = this._getDefaultDate(inst),
date = defaultDate,
settings = this._getFormatConfig(inst);
try {
date = this.parseDate(dateFormat, dates, settings) || defaultDate;
} catch (event) {
dates = (noDefault ? "" : dates);
}
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
inst.currentDay = (dates ? date.getDate() : 0);
inst.currentMonth = (dates ? date.getMonth() : 0);
inst.currentYear = (dates ? date.getFullYear() : 0);
this._adjustInstDate(inst);
},
/* Retrieve the default date shown on opening. */
_getDefaultDate: function(inst) {
return this._restrictMinMax(inst,
this._determineDate(inst, this._get(inst, "defaultDate"), new Date()));
},
/* A date may be specified as an exact value or a relative one. */
_determineDate: function(inst, date, defaultDate) {
var offsetNumeric = function(offset) {
var date = new Date();
date.setDate(date.getDate() + offset);
return date;
},
offsetString = function(offset) {
try {
return $.datepicker.parseDate($.datepicker._get(inst, "dateFormat"),
offset, $.datepicker._getFormatConfig(inst));
}
catch (e) {
// Ignore
}
var date = (offset.toLowerCase().match(/^c/) ?
$.datepicker._getDate(inst) : null) || new Date(),
year = date.getFullYear(),
month = date.getMonth(),
day = date.getDate(),
pattern = /([+\-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,
matches = pattern.exec(offset);
while (matches) {
switch (matches[2] || "d") {
case "d" : case "D" :
day += parseInt(matches[1],10); break;
case "w" : case "W" :
day += parseInt(matches[1],10) * 7; break;
case "m" : case "M" :
month += parseInt(matches[1],10);
day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
break;
case "y": case "Y" :
year += parseInt(matches[1],10);
day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
break;
}
matches = pattern.exec(offset);
}
return new Date(year, month, day);
},
newDate = (date == null || date === "" ? defaultDate : (typeof date === "string" ? offsetString(date) :
(typeof date === "number" ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));
newDate = (newDate && newDate.toString() === "Invalid Date" ? defaultDate : newDate);
if (newDate) {
newDate.setHours(0);
newDate.setMinutes(0);
newDate.setSeconds(0);
newDate.setMilliseconds(0);
}
return this._daylightSavingAdjust(newDate);
},
/* Handle switch to/from daylight saving.
* Hours may be non-zero on daylight saving cut-over:
* > 12 when midnight changeover, but then cannot generate
* midnight datetime, so jump to 1AM, otherwise reset.
* @param date (Date) the date to check
* @return (Date) the corrected date
*/
_daylightSavingAdjust: function(date) {
if (!date) {
return null;
}
date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
return date;
},
/* Set the date(s) directly. */
_setDate: function(inst, date, noChange) {
var clear = !date,
origMonth = inst.selectedMonth,
origYear = inst.selectedYear,
newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));
inst.selectedDay = inst.currentDay = newDate.getDate();
inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
if ((origMonth !== inst.selectedMonth || origYear !== inst.selectedYear) && !noChange) {
this._notifyChange(inst);
}
this._adjustInstDate(inst);
if (inst.input) {
inst.input.val(clear ? "" : this._formatDate(inst));
}
},
/* Retrieve the date(s) directly. */
_getDate: function(inst) {
var startDate = (!inst.currentYear || (inst.input && inst.input.val() === "") ? null :
this._daylightSavingAdjust(new Date(
inst.currentYear, inst.currentMonth, inst.currentDay)));
return startDate;
},
/* Attach the onxxx handlers. These are declared statically so
* they work with static code transformers like Caja.
*/
_attachHandlers: function(inst) {
var stepMonths = this._get(inst, "stepMonths"),
id = "#" + inst.id.replace( /\\\\/g, "\\" );
inst.dpDiv.find("[data-handler]").map(function () {
var handler = {
prev: function () {
$.datepicker._adjustDate(id, -stepMonths, "M");
},
next: function () {
$.datepicker._adjustDate(id, +stepMonths, "M");
},
hide: function () {
$.datepicker._hideDatepicker();
},
today: function () {
$.datepicker._gotoToday(id);
},
selectDay: function () {
$.datepicker._selectDay(id, +this.getAttribute("data-month"), +this.getAttribute("data-year"), this);
return false;
},
selectMonth: function () {
$.datepicker._selectMonthYear(id, this, "M");
return false;
},
selectYear: function () {
$.datepicker._selectMonthYear(id, this, "Y");
return false;
}
};
$(this).bind(this.getAttribute("data-event"), handler[this.getAttribute("data-handler")]);
});
},
/* Generate the HTML for the current state of the date picker. */
_generateHTML: function(inst) {
var maxDraw, prevText, prev, nextText, next, currentText, gotoDate,
controls, buttonPanel, firstDay, showWeek, dayNames, dayNamesMin,
monthNames, monthNamesShort, beforeShowDay, showOtherMonths,
selectOtherMonths, defaultDate, html, dow, row, group, col, selectedDate,
cornerClass, calender, thead, day, daysInMonth, leadDays, curRows, numRows,
printDate, dRow, tbody, daySettings, otherMonth, unselectable,
tempDate = new Date(),
today = this._daylightSavingAdjust(
new Date(tempDate.getFullYear(), tempDate.getMonth(), tempDate.getDate())), // clear time
isRTL = this._get(inst, "isRTL"),
showButtonPanel = this._get(inst, "showButtonPanel"),
hideIfNoPrevNext = this._get(inst, "hideIfNoPrevNext"),
navigationAsDateFormat = this._get(inst, "navigationAsDateFormat"),
numMonths = this._getNumberOfMonths(inst),
showCurrentAtPos = this._get(inst, "showCurrentAtPos"),
stepMonths = this._get(inst, "stepMonths"),
isMultiMonth = (numMonths[0] !== 1 || numMonths[1] !== 1),
currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
new Date(inst.currentYear, inst.currentMonth, inst.currentDay))),
minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
drawMonth = inst.drawMonth - showCurrentAtPos,
drawYear = inst.drawYear;
if (drawMonth < 0) {
drawMonth += 12;
drawYear--;
}
if (maxDate) {
maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
drawMonth--;
if (drawMonth < 0) {
drawMonth = 11;
drawYear--;
}
}
}
inst.drawMonth = drawMonth;
inst.drawYear = drawYear;
prevText = this._get(inst, "prevText");
prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
this._getFormatConfig(inst)));
prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
"<a class='ui-datepicker-prev ui-corner-all' data-handler='prev' data-event='click'" +
" title='" + prevText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>" :
(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-prev ui-corner-all ui-state-disabled' title='"+ prevText +"'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "e" : "w") + "'>" + prevText + "</span></a>"));
nextText = this._get(inst, "nextText");
nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
this._getFormatConfig(inst)));
next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
"<a class='ui-datepicker-next ui-corner-all' data-handler='next' data-event='click'" +
" title='" + nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>" :
(hideIfNoPrevNext ? "" : "<a class='ui-datepicker-next ui-corner-all ui-state-disabled' title='"+ nextText + "'><span class='ui-icon ui-icon-circle-triangle-" + ( isRTL ? "w" : "e") + "'>" + nextText + "</span></a>"));
currentText = this._get(inst, "currentText");
gotoDate = (this._get(inst, "gotoCurrent") && inst.currentDay ? currentDate : today);
currentText = (!navigationAsDateFormat ? currentText :
this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
controls = (!inst.inline ? "<button type='button' class='ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all' data-handler='hide' data-event='click'>" +
this._get(inst, "closeText") + "</button>" : "");
buttonPanel = (showButtonPanel) ? "<div class='ui-datepicker-buttonpane ui-widget-content'>" + (isRTL ? controls : "") +
(this._isInRange(inst, gotoDate) ? "<button type='button' class='ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all' data-handler='today' data-event='click'" +
">" + currentText + "</button>" : "") + (isRTL ? "" : controls) + "</div>" : "";
firstDay = parseInt(this._get(inst, "firstDay"),10);
firstDay = (isNaN(firstDay) ? 0 : firstDay);
showWeek = this._get(inst, "showWeek");
dayNames = this._get(inst, "dayNames");
dayNamesMin = this._get(inst, "dayNamesMin");
monthNames = this._get(inst, "monthNames");
monthNamesShort = this._get(inst, "monthNamesShort");
beforeShowDay = this._get(inst, "beforeShowDay");
showOtherMonths = this._get(inst, "showOtherMonths");
selectOtherMonths = this._get(inst, "selectOtherMonths");
defaultDate = this._getDefaultDate(inst);
html = "";
dow;
for (row = 0; row < numMonths[0]; row++) {
group = "";
this.maxRows = 4;
for (col = 0; col < numMonths[1]; col++) {
selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
cornerClass = " ui-corner-all";
calender = "";
if (isMultiMonth) {
calender += "<div class='ui-datepicker-group";
if (numMonths[1] > 1) {
switch (col) {
case 0: calender += " ui-datepicker-group-first";
cornerClass = " ui-corner-" + (isRTL ? "right" : "left"); break;
case numMonths[1]-1: calender += " ui-datepicker-group-last";
cornerClass = " ui-corner-" + (isRTL ? "left" : "right"); break;
default: calender += " ui-datepicker-group-middle"; cornerClass = ""; break;
}
}
calender += "'>";
}
calender += "<div class='ui-datepicker-header ui-widget-header ui-helper-clearfix" + cornerClass + "'>" +
(/all|left/.test(cornerClass) && row === 0 ? (isRTL ? next : prev) : "") +
(/all|right/.test(cornerClass) && row === 0 ? (isRTL ? prev : next) : "") +
this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
"</div><table class='ui-datepicker-calendar'><thead>" +
"<tr>";
thead = (showWeek ? "<th class='ui-datepicker-week-col'>" + this._get(inst, "weekHeader") + "</th>" : "");
for (dow = 0; dow < 7; dow++) { // days of the week
day = (dow + firstDay) % 7;
thead += "<th scope='col'" + ((dow + firstDay + 6) % 7 >= 5 ? " class='ui-datepicker-week-end'" : "") + ">" +
"<span title='" + dayNames[day] + "'>" + dayNamesMin[day] + "</span></th>";
}
calender += thead + "</tr></thead><tbody>";
daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
if (drawYear === inst.selectedYear && drawMonth === inst.selectedMonth) {
inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
}
leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate
numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043)
this.maxRows = numRows;
printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
for (dRow = 0; dRow < numRows; dRow++) { // create date picker rows
calender += "<tr>";
tbody = (!showWeek ? "" : "<td class='ui-datepicker-week-col'>" +
this._get(inst, "calculateWeek")(printDate) + "</td>");
for (dow = 0; dow < 7; dow++) { // create date picker days
daySettings = (beforeShowDay ?
beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, ""]);
otherMonth = (printDate.getMonth() !== drawMonth);
unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
tbody += "<td class='" +
((dow + firstDay + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + // highlight weekends
(otherMonth ? " ui-datepicker-other-month" : "") + // highlight days from other months
((printDate.getTime() === selectedDate.getTime() && drawMonth === inst.selectedMonth && inst._keyEvent) || // user pressed key
(defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ?
// or defaultDate is current printedDate and defaultDate is selectedDate
" " + this._dayOverClass : "") + // highlight selected day
(unselectable ? " " + this._unselectableClass + " ui-state-disabled": "") + // highlight unselectable days
(otherMonth && !showOtherMonths ? "" : " " + daySettings[1] + // highlight custom dates
(printDate.getTime() === currentDate.getTime() ? " " + this._currentClass : "") + // highlight selected day
(printDate.getTime() === today.getTime() ? " ui-datepicker-today" : "")) + "'" + // highlight today (if different)
((!otherMonth || showOtherMonths) && daySettings[2] ? " title='" + daySettings[2].replace(/'/g, "'") + "'" : "") + // cell title
(unselectable ? "" : " data-handler='selectDay' data-event='click' data-month='" + printDate.getMonth() + "' data-year='" + printDate.getFullYear() + "'") + ">" + // actions
(otherMonth && !showOtherMonths ? " " : // display for other months
(unselectable ? "<span class='ui-state-default'>" + printDate.getDate() + "</span>" : "<a class='ui-state-default" +
(printDate.getTime() === today.getTime() ? " ui-state-highlight" : "") +
(printDate.getTime() === currentDate.getTime() ? " ui-state-active" : "") + // highlight selected day
(otherMonth ? " ui-priority-secondary" : "") + // distinguish dates from other months
"' href='#'>" + printDate.getDate() + "</a>")) + "</td>"; // display selectable date
printDate.setDate(printDate.getDate() + 1);
printDate = this._daylightSavingAdjust(printDate);
}
calender += tbody + "</tr>";
}
drawMonth++;
if (drawMonth > 11) {
drawMonth = 0;
drawYear++;
}
calender += "</tbody></table>" + (isMultiMonth ? "</div>" +
((numMonths[0] > 0 && col === numMonths[1]-1) ? "<div class='ui-datepicker-row-break'></div>" : "") : "");
group += calender;
}
html += group;
}
html += buttonPanel;
inst._keyEvent = false;
return html;
},
/* Generate the month and year header. */
_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
secondary, monthNames, monthNamesShort) {
var inMinYear, inMaxYear, month, years, thisYear, determineYear, year, endYear,
changeMonth = this._get(inst, "changeMonth"),
changeYear = this._get(inst, "changeYear"),
showMonthAfterYear = this._get(inst, "showMonthAfterYear"),
html = "<div class='ui-datepicker-title'>",
monthHtml = "";
// month selection
if (secondary || !changeMonth) {
monthHtml += "<span class='ui-datepicker-month'>" + monthNames[drawMonth] + "</span>";
} else {
inMinYear = (minDate && minDate.getFullYear() === drawYear);
inMaxYear = (maxDate && maxDate.getFullYear() === drawYear);
monthHtml += "<select class='ui-datepicker-month' data-handler='selectMonth' data-event='change'>";
for ( month = 0; month < 12; month++) {
if ((!inMinYear || month >= minDate.getMonth()) && (!inMaxYear || month <= maxDate.getMonth())) {
monthHtml += "<option value='" + month + "'" +
(month === drawMonth ? " selected='selected'" : "") +
">" + monthNamesShort[month] + "</option>";
}
}
monthHtml += "</select>";
}
if (!showMonthAfterYear) {
html += monthHtml + (secondary || !(changeMonth && changeYear) ? " " : "");
}
// year selection
if ( !inst.yearshtml ) {
inst.yearshtml = "";
if (secondary || !changeYear) {
html += "<span class='ui-datepicker-year'>" + drawYear + "</span>";
} else {
// determine range of years to display
years = this._get(inst, "yearRange").split(":");
thisYear = new Date().getFullYear();
determineYear = function(value) {
var year = (value.match(/c[+\-].*/) ? drawYear + parseInt(value.substring(1), 10) :
(value.match(/[+\-].*/) ? thisYear + parseInt(value, 10) :
parseInt(value, 10)));
return (isNaN(year) ? thisYear : year);
};
year = determineYear(years[0]);
endYear = Math.max(year, determineYear(years[1] || ""));
year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
inst.yearshtml += "<select class='ui-datepicker-year' data-handler='selectYear' data-event='change'>";
for (; year <= endYear; year++) {
inst.yearshtml += "<option value='" + year + "'" +
(year === drawYear ? " selected='selected'" : "") +
">" + year + "</option>";
}
inst.yearshtml += "</select>";
html += inst.yearshtml;
inst.yearshtml = null;
}
}
html += this._get(inst, "yearSuffix");
if (showMonthAfterYear) {
html += (secondary || !(changeMonth && changeYear) ? " " : "") + monthHtml;
}
html += "</div>"; // Close datepicker_header
return html;
},
/* Adjust one of the date sub-fields. */
_adjustInstDate: function(inst, offset, period) {
var year = inst.drawYear + (period === "Y" ? offset : 0),
month = inst.drawMonth + (period === "M" ? offset : 0),
day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) + (period === "D" ? offset : 0),
date = this._restrictMinMax(inst, this._daylightSavingAdjust(new Date(year, month, day)));
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
if (period === "M" || period === "Y") {
this._notifyChange(inst);
}
},
/* Ensure a date is within any min/max bounds. */
_restrictMinMax: function(inst, date) {
var minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
newDate = (minDate && date < minDate ? minDate : date);
return (maxDate && newDate > maxDate ? maxDate : newDate);
},
/* Notify change of month/year. */
_notifyChange: function(inst) {
var onChange = this._get(inst, "onChangeMonthYear");
if (onChange) {
onChange.apply((inst.input ? inst.input[0] : null),
[inst.selectedYear, inst.selectedMonth + 1, inst]);
}
},
/* Determine the number of months to show. */
_getNumberOfMonths: function(inst) {
var numMonths = this._get(inst, "numberOfMonths");
return (numMonths == null ? [1, 1] : (typeof numMonths === "number" ? [1, numMonths] : numMonths));
},
/* Determine the current maximum date - ensure no time components are set. */
_getMinMaxDate: function(inst, minMax) {
return this._determineDate(inst, this._get(inst, minMax + "Date"), null);
},
/* Find the number of days in a given month. */
_getDaysInMonth: function(year, month) {
return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate();
},
/* Find the day of the week of the first of a month. */
_getFirstDayOfMonth: function(year, month) {
return new Date(year, month, 1).getDay();
},
/* Determines if we should allow a "next/prev" month display change. */
_canAdjustMonth: function(inst, offset, curYear, curMonth) {
var numMonths = this._getNumberOfMonths(inst),
date = this._daylightSavingAdjust(new Date(curYear,
curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));
if (offset < 0) {
date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
}
return this._isInRange(inst, date);
},
/* Is the given date in the accepted range? */
_isInRange: function(inst, date) {
var yearSplit, currentYear,
minDate = this._getMinMaxDate(inst, "min"),
maxDate = this._getMinMaxDate(inst, "max"),
minYear = null,
maxYear = null,
years = this._get(inst, "yearRange");
if (years){
yearSplit = years.split(":");
currentYear = new Date().getFullYear();
minYear = parseInt(yearSplit[0], 10);
maxYear = parseInt(yearSplit[1], 10);
if ( yearSplit[0].match(/[+\-].*/) ) {
minYear += currentYear;
}
if ( yearSplit[1].match(/[+\-].*/) ) {
maxYear += currentYear;
}
}
return ((!minDate || date.getTime() >= minDate.getTime()) &&
(!maxDate || date.getTime() <= maxDate.getTime()) &&
(!minYear || date.getFullYear() >= minYear) &&
(!maxYear || date.getFullYear() <= maxYear));
},
/* Provide the configuration settings for formatting/parsing. */
_getFormatConfig: function(inst) {
var shortYearCutoff = this._get(inst, "shortYearCutoff");
shortYearCutoff = (typeof shortYearCutoff !== "string" ? shortYearCutoff :
new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
return {shortYearCutoff: shortYearCutoff,
dayNamesShort: this._get(inst, "dayNamesShort"), dayNames: this._get(inst, "dayNames"),
monthNamesShort: this._get(inst, "monthNamesShort"), monthNames: this._get(inst, "monthNames")};
},
/* Format the given date for display. */
_formatDate: function(inst, day, month, year) {
if (!day) {
inst.currentDay = inst.selectedDay;
inst.currentMonth = inst.selectedMonth;
inst.currentYear = inst.selectedYear;
}
var date = (day ? (typeof day === "object" ? day :
this._daylightSavingAdjust(new Date(year, month, day))) :
this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
return this.formatDate(this._get(inst, "dateFormat"), date, this._getFormatConfig(inst));
}
});
/*
* Bind hover events for datepicker elements.
* Done via delegate so the binding only occurs once in the lifetime of the parent div.
* Global datepicker_instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
*/
function datepicker_bindHover(dpDiv) {
var selector = "button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";
return dpDiv.delegate(selector, "mouseout", function() {
$(this).removeClass("ui-state-hover");
if (this.className.indexOf("ui-datepicker-prev") !== -1) {
$(this).removeClass("ui-datepicker-prev-hover");
}
if (this.className.indexOf("ui-datepicker-next") !== -1) {
$(this).removeClass("ui-datepicker-next-hover");
}
})
.delegate(selector, "mouseover", function(){
if (!$.datepicker._isDisabledDatepicker( datepicker_instActive.inline ? dpDiv.parent()[0] : datepicker_instActive.input[0])) {
$(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");
$(this).addClass("ui-state-hover");
if (this.className.indexOf("ui-datepicker-prev") !== -1) {
$(this).addClass("ui-datepicker-prev-hover");
}
if (this.className.indexOf("ui-datepicker-next") !== -1) {
$(this).addClass("ui-datepicker-next-hover");
}
}
});
}
/* jQuery extend now ignores nulls! */
function datepicker_extendRemove(target, props) {
$.extend(target, props);
for (var name in props) {
if (props[name] == null) {
target[name] = props[name];
}
}
return target;
}
/* Invoke the datepicker functionality.
@param options string - a command, optionally followed by additional parameters or
Object - settings for attaching new datepicker functionality
@return jQuery object */
$.fn.datepicker = function(options){
/* Verify an empty collection wasn't passed - Fixes #6976 */
if ( !this.length ) {
return this;
}
/* Initialise the date picker. */
if (!$.datepicker.initialized) {
$(document).mousedown($.datepicker._checkExternalClick);
$.datepicker.initialized = true;
}
/* Append datepicker main container to body if not exist. */
if ($("#"+$.datepicker._mainDivId).length === 0) {
$("body").append($.datepicker.dpDiv);
}
var otherArgs = Array.prototype.slice.call(arguments, 1);
if (typeof options === "string" && (options === "isDisabled" || options === "getDate" || options === "widget")) {
return $.datepicker["_" + options + "Datepicker"].
apply($.datepicker, [this[0]].concat(otherArgs));
}
if (options === "option" && arguments.length === 2 && typeof arguments[1] === "string") {
return $.datepicker["_" + options + "Datepicker"].
apply($.datepicker, [this[0]].concat(otherArgs));
}
return this.each(function() {
typeof options === "string" ?
$.datepicker["_" + options + "Datepicker"].
apply($.datepicker, [this].concat(otherArgs)) :
$.datepicker._attachDatepicker(this, options);
});
};
$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.11.0";
return $.datepicker;
}));
|
var Travis = require('travis-ci');
var repo = 'marionettejs/marionettejs.com';
var travis = new Travis({
version: '2.0.0',
headers: {
'User-Agent': 'Travis/1.0'
}
});
var getLastMainBuildId = function(builds) {
var id;
for (var i = 0; i < builds.length; i++) {
if (!builds[i].pull_request) {
id = builds[i].id;
break;
}
}
if (!id) {
throw new Error('Build id was not found');
}
return id;
};
travis.authenticate({
github_token: process.env.GH_TOKEN
}, function (err, res) {
if (err) {
return console.error(err);
}
//get repo builds
travis.repos(repo.split('/')[0], repo.split('/')[1]).builds.get(function (err, res) {
if (err) {
return console.error(err);
}
//rebuild latest build
travis.requests.post({
build_id: getLastMainBuildId(res.builds)
}, function (err, res) {
if (err) {
return console.error(err);
}
console.log(res.flash[0].notice);
});
});
});
|
$(function () {
$('.demo1').colorpicker();
$('.demo2').colorpicker();
// Horizontal mode
$('#demo_forceformat').colorpicker({
format: 'rgba', // force this format
horizontal: true
});
// Horizontal mode
$('#demo_forceformat3').colorpicker({
format: 'rgba', // force this format
});
$('.demo-auto').colorpicker();
});
|
import React, { Component } from 'react';
import { ModeCommentIconWithText } from 'components/utils/Icons';
import Paper from 'material-ui/Paper';
import DisplayAreaHOC from 'components/hoc/DisplayAreaHOC';
import '../../../../style/display/display.scss';
export class EmptyArea extends Component {
render() {
return (
<Paper className={'fff-display'}>
<ModeCommentIconWithText text={'Select a namespace and a key to edit.'} />
</Paper>
);
}
}
export default DisplayAreaHOC(EmptyArea);
|
(function() {
'use strict';
angular
.module('app')
.directive('upload', upload);
upload.$inject = ['$window'];
function upload ($window) {
// Usage:
// <upload></upload>
// Creates:
// <upload>
// <button>$label</button>
// <input type="file" id="$id" name="$name" style="display:none;" />
// </upload>
var directive = {
link: link,
restrict: 'EA'
};
return directive;
function link($scope, $element, $attrs) {
var $input = $('<input />', {
'accept':$attrs.accept,
'type': 'file',
'style': 'display:none;',
'id': $attrs.id,
'name':$attrs.name
});
var $button = $($attrs.target);
$button.on('click', function () {
$input.click();
});
$element.append($input);
$element.append($button);
// TODO: preview image
//$input.on('change', function () {
// if (x.files.length == 0) {
// $button.text("Select one or more files.");
// } else {
// for (var i = 0; i < x.files.length; i++) {
// txt += "<br><strong>" + (i + 1) + ". file</strong><br>";
// var file = x.files[i];
// if ('name' in file) {
// txt += "name: " + file.name + "<br>";
// }
// if ('size' in file) {
// txt += "size: " + file.size + " bytes <br>";
// }
// }
// }
//});
};
}
})(); |
/**
* @author Swagatam Mitra
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, document, console, brackets, $, Mustache */
define(function (require, exports, module) {
"use strict";
var DocumentManager = brackets.getModule("document/DocumentManager");
var CSSNodeFormatter = require('stylemodule/CSSNodeFormatter');
var currentApplication = null;
function _findAndUpdateLinkedSelectors(styleSheet, oldelementID, newElementID){
var setCount,mediaCount, ruleSets, ruleSet,mediacount,mediaRule;
var ref;
ruleSets = styleSheet.rules;
for (setCount = 0; setCount < ruleSets.length; setCount++) {
ruleSet = ruleSets[setCount];
if(ruleSet.cssRules && ruleSet.cssRules.length > 0 && ruleSet.cssText.indexOf(oldelementID)>=0){
styleSheet.insertRule(ruleSet.cssText.split(oldelementID).join(newElementID), setCount);
styleSheet.deleteRule(setCount+1);
_witeStyleSheetFromDOMToDoc(styleSheet);
} else if (ruleSet.selectorText && ruleSet.selectorText.indexOf(oldelementID)>=0) {
styleSheet.insertRule(ruleSet.cssText.split(oldelementID).join(newElementID), setCount);
styleSheet.deleteRule(setCount+1);
_witeStyleSheetFromDOMToDoc(styleSheet);
}
}
}
function _cascadeUpdateInAllStyleSheets(oldelementID,newElementID){
var styleSheets = document.getElementById('htmldesignerIframe').contentWindow.document.styleSheets;
var sheetCount, styleSheet;
var ref;
for (sheetCount = 0; sheetCount < styleSheets.length ;sheetCount++) {
styleSheet = document.getElementById('htmldesignerIframe').contentWindow.document.styleSheets[sheetCount];
_findAndUpdateLinkedSelectors(styleSheet,oldelementID,newElementID);
}
}
function _witeStyleSheetFromDOMToDoc(styleSheet){
var styleText;
if(styleSheet.href){
DocumentManager.getDocumentForPath(styleSheet.href.replace(brackets.platform === 'mac' ? 'file://' : 'file:///' ,'').split('?')[0])
.done(function (doc) {
styleText = CSSNodeFormatter.formatCSSAsText(styleSheet,false);
doc.setText(styleText);
$("#html-design-editor").trigger("cssdoc.changed",[currentApplication,doc]);
});
} else {
styleText = CSSNodeFormatter.formatCSSAsText(styleSheet,true);
styleSheet.ownerNode.innerText = styleText;
$("#html-design-editor").trigger('html.element.updated');
}
}
$(document).on("id-attribute-update","#html-design-editor", function(event,oldelementID,newElementID){
_cascadeUpdateInAllStyleSheets(oldelementID,newElementID);
});
$(document).on("application.context","#html-design-editor", function(event,applicationKey){
currentApplication = applicationKey;
});
}); |
import React from 'react'
import Icon from 'react-icon-base'
const FaEyedropper = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m37.9 2.1q2.1 2.1 2.1 5.1t-2.1 5l-5 5 2.3 2.3q0.2 0.2 0.2 0.5t-0.2 0.5l-4.7 4.7q-0.2 0.2-0.5 0.2t-0.5-0.2l-2.4-2.3-13.4 13.4q-0.8 0.8-2 0.8h-4.6l-5.7 2.9-1.4-1.4 2.9-5.7v-4.6q0-1.2 0.8-2l13.4-13.4-2.3-2.4q-0.2-0.2-0.2-0.5t0.2-0.5l4.7-4.7q0.2-0.2 0.5-0.2t0.5 0.2l2.3 2.3 5-5q2.1-2.1 5-2.1t5.1 2.1z m-26.5 30.8l12.9-12.9-4.3-4.3-12.9 12.9v4.3h4.3z"/></g>
</Icon>
)
export default FaEyedropper
|
/**
* @jest-environment node
*/
const Vue = require('vue');
const renderer = require('vue-server-renderer').createRenderer();
const draggable = require("@/vuedraggable").default;
Vue.component('draggable', draggable);
const app = new Vue({
name: "test-app",
template: `<draggable :list="items"><div v-for="item in items" :key="item">{{item}}</div></draggable>`,
data:{
items:["a","b","c"]
}
});
let html;
describe("vuedraggable in a SSR context", () => {
beforeEach(async () => {
html = await renderer.renderToString(app);
});
it("can be rendered", () => {
const expected = '<div data-server-rendered="true"><div>a</div><div>b</div><div>c</div></div>';
expect(html).toEqual(expected);
})
}) |
/**
* Theme Customizer enhancements for a better user experience.
*
* Contains handlers to make Theme Customizer preview reload changes asynchronously.
*/
( function( $, less ) {
// Site title and description.
wp.customize( 'blogname', function( value ) {
value.bind( function( to ) {
$( 'a.site-title' ).text( to );
} );
} );
wp.customize( 'blogdescription', function( value ) {
value.bind( function( to ) {
$( '.featured-hero__title' ).text( to );
} );
} );
function handle_header() {
$( '.header__logo' ).hide();
if ( wp.customize( 'briar_header' ).get() == 'logo' )
$( '.header__logo .site-logo' ).closest( '.header__logo' ).show();
else
$( '.header__logo .site-title' ).closest( '.header__logo' ).show();
}
// Header
wp.customize( 'briar_header', function( value ) {
handle_header();
value.bind( handle_header );
} );
// Header logo.
wp.customize( 'briar_header_logo', function( value ) {
value.bind( function( to ) {
$( '.header__logo .site-logo img' ).hide();
if ( to ) {
$( '.header__logo .site-logo img:not(.default)' ).attr( 'src', to ).show();
}
else {
$( '.header__logo .site-logo img.default' ).show();
}
} );
} );
// Social buttons.
wp.customize( 'briar_footer_social_buttons', function( value ) {
value.bind( function( to ) {
var social_buttons = '';
$.each( to, function( i, social_button ) {
social_buttons += '<li class="' + social_button.css_class + '-ico social-nav__item btn--transition"><a class="social-nav__link" href="' + social_button.url + '" title="' + social_button.social + '" target="_blank"><i class="fa fa-' + social_button.css_class + '"></i></a></li>\n';
} );
$( '#footer ul.social-nav' ).html( social_buttons );
} );
} );
// Layout
var get_page_layout = function() {
var classes = $( 'body' ).attr( 'class' ).split( /\s+/ );
var name = 'global';
if ( $.inArray( 'archive', classes ) > -1 )
name = 'archive';
if ( $.inArray( 'category', classes ) > -1 )
name = 'category_archive';
if ( $.inArray( 'search', classes ) > -1 )
name = 'search';
if ( $.inArray( 'error404', classes ) > -1 )
name = '404';
if ( $.inArray( 'single', classes ) > -1 )
name = 'single';
if ( $.inArray( 'page', classes ) > -1 )
name = 'page';
if ( $.inArray( 'home', classes ) > -1 )
name = 'home';
if ( $.inArray( 'blog', classes ) > -1 && 'page' == wp.customize( 'show_on_front' ).get() )
name = 'blog';
return wp.customize( 'briar_' + name + '_layout' ).get();
};
var $main = $( '.briar-main-class' ),
$sidebar = $( '.briar-sidebar-class' );
var handle_layout = function() {
if ( ! $main.length || !$sidebar.length )
return;
var page_layout = get_page_layout();
if ( page_layout == 'disabled' )
page_layout = wp.customize( 'briar_global_layout' ).get();
$main.removeClass( 'col-md-12 col-md-8 col-md-push-4 col-lg-8 col-md-10 col-lg-offset-2 col-md-offset-1' );
$sidebar.removeClass( 'col-md-pull-8' ).show();
if ( page_layout == 'none' ) {
if ( $( 'body' ).hasClass( 'single' ) )
$main.addClass( 'col-lg-8 col-md-10 col-lg-offset-2 col-md-offset-1' );
else
$main.addClass( 'col-md-12' );
$sidebar.hide();
}
else {
$main.addClass( 'col-md-8' );
if ( page_layout == 'left' ) {
$main.addClass( 'col-md-push-4' );
$sidebar.addClass( 'col-md-pull-8' );
}
}
$( window ).trigger( 'resize' );
};
var handle_layout_change = function( value ) {
value.bind( handle_layout );
};
wp.customize( 'briar_global_layout', handle_layout_change );
wp.customize( 'briar_home_layout', handle_layout_change );
wp.customize( 'briar_blog_layout', handle_layout_change );
wp.customize( 'briar_archive_layout', handle_layout_change );
wp.customize( 'briar_category_archive_layout', handle_layout_change );
wp.customize( 'briar_search_layout', handle_layout_change );
wp.customize( 'briar_404_layout', handle_layout_change );
wp.customize( 'briar_single_layout', handle_layout_change );
wp.customize( 'briar_page_layout', handle_layout_change );
wp.customize( 'show_on_front', handle_layout_change );
$( document ).on( 'ready', handle_layout );
$( document ).on( 'click', 'a', handle_layout );
/* Colors */
function lighten( color, amount ) {
var color = new less.tree.Color( color.replace( '#', '' ) );
var amount = new(less.tree.Dimension)( amount, '%' );
return less.functions.functionRegistry._data.lighten( color, amount ).toRGB();
}
function darken( color, amount ) {
var color = new less.tree.Color( color.replace( '#', '' ) );
var amount = new(less.tree.Dimension)( amount, '%' );
return less.functions.functionRegistry._data.darken( color, amount ).toRGB();
}
var schemes = {
'#f15156': 'red',
'#e8813d': 'orange',
'#f5d13d': 'yellow',
'#2980b9': 'blue',
'#b365d3': 'violet',
'#27ae60': 'green'
};
var colors_timeout = null;
function update_style() {
var current_scheme = 'custom';
var one_color = false;
var style_output;
var styles = [];
var anchor_color = wp.customize( 'briar_anchor_color' ).get();
var anchor_top = 'a:hover, a:focus{color: ' + anchor_color + ';}';
var anchor_post_item = '.post-item a{color: ' + anchor_color + ';} .post-item a:hover, .post-item a:focus{border-bottom-color: ' + anchor_color + ';}';
var anchor_bottom = '.error-message a{color: ' + anchor_color + ';}.error-message a:hover, .error-message a:focus{border-bottom-color: ' + anchor_color + ';}.widget a:hover, .widget a:focus{color: ' + anchor_color + ';}';
var header_color = wp.customize( 'briar_header_color' ).get();
var header = '.header{border-top-color: ' + header_color + ';}.header--borders:before, .header--borders:after{background-color: ' + header_color + ';}.header--transparent .header__logo-link{background-color: ' + header_color + ';} .header--transparent .header__logo-link:hover, .header--transparent .header__logo-link:focus{color: ' + header_color + ';}';
var menu_color = wp.customize( 'briar_menu_color' ).get();
var menu = '.main-nav .menu-item-has-children > .dropdown-nav__link{border-bottom-color: ' + menu_color + ';}.main-nav .menu-item-has-children > .dropdown-nav__link:focus{border-color: ' + menu_color + ';}.dropdown-nav{background-color: ' + menu_color + ';}.dropdown-nav__toggle{background-color: ' + menu_color + ';border-color: ' + menu_color + ';}.dropdown-nav__toggle:hover{border-color: ' + menu_color + ';}.dropdown-nav__toggle:hover span{background: ' + menu_color + ';}.dropdown-nav__toggle:hover span:after, .dropdown-nav__toggle:hover span:before{background: ' + menu_color + ';}.dropdown-nav__toggle:focus span, .dropdown-nav__toggle:hover span{background: ' + menu_color + ';}.dropdown-nav__toggle:focus span:after, .dropdown-nav__toggle:hover span:after, .dropdown-nav__toggle:focus span:before, .dropdown-nav__toggle:hover span:before{background: ' + menu_color + ';}';
var footer_color = wp.customize( 'briar_footer_color' ).get();
var footer = '.footer:after{background-color: ' + footer_color + ';}.footer__copyright a:hover, .footer__copyright a:focus{color: ' + footer_color + ';}';
var logo_color = wp.customize( 'briar_logo_color' ).get();
var logo = '.btn--logo{border-color: ' + logo_color + ';color: ' + logo_color + ';}.btn--logo:hover, .btn--logo:focus{background-color: ' + logo_color + ';}';
var readmore_color = wp.customize( 'briar_readmore_color' ).get();
var readmore = '.btn--more-posts{border-color: ' + readmore_color + ';color: ' + readmore_color + ';}.btn--more-posts:hover, .btn--more-posts:focus{background-color: ' + readmore_color + ';}';
var comments_button_color = wp.customize( 'briar_comments_button_color' ).get();
var comments_button = '.fixed-footer__btn--red{background: ' + comments_button_color + ';}.fixed-footer__btn--red:hover, .fixed-footer__btn--red:focus{background: ' + lighten( comments_button_color, 5 ) + ';}';
var comments_submit_button_color = wp.customize( 'briar_comments_submit_button_color' ).get();
var comments_submit_button = '.form-submit .submit{background-color: ' + comments_submit_button_color + ';}';
var title_hover_color = wp.customize( 'briar_title_hover_color' ).get();
var title_hover = '.post-list .post-item__title a:hover, .post-list .post-item__title a:focus{color: ' + title_hover_color + ';}';
var prev_next_posts_color = wp.customize( 'briar_prev_next_posts_color' ).get();
var prev_next_posts = '.post-list-nav__prev a, .post-list-nav__next a{ background-color: ' + prev_next_posts_color + '; }.post-list-nav__prev a:hover, .post-list-nav__next a:hover, .post-list-nav__prev a:focus, .post-list-nav__next a:focus{background-color: ' + darken( prev_next_posts_color, 7 ) + ';}';
var search_button_color = wp.customize( 'briar_search_button_color' ).get();
var search_button = '.search-form__button{background: ' + search_button_color + ';}.search-form__button:hover, .search-form__button:focus{background-color: ' + darken( search_button_color, 7 ) + ';}';
var audio_color = wp.customize( 'briar_audio_color' ).get();
var audio = '.mejs-controls .mejs-time-rail .mejs-time-loaded, .mejs-controls .mejs-horizontal-volume-slider .mejs-horizontal-volume-current{background-color: ' + audio_color + ' !important;}';
var gallery_arrows_color = wp.customize( 'briar_gallery_arrows_color' ).get();
var gallery_arrows = '.gallery-slider .slick-arrow:before{background-color: ' + gallery_arrows_color + ';}';
var blog_post_pagination_color = wp.customize( 'briar_blog_post_pagination_color' ).get();
var blog_post_pagination = '.pagination li a{background-color: ' + blog_post_pagination_color + ';}.pagination li:hover, .pagination li:focus{background-color: ' + lighten( blog_post_pagination_color, 5 ) + ';}.pagination .current{background-color: ' + darken( blog_post_pagination_color, 4 ) + ';}';
var password_protected_button_color = wp.customize( 'briar_password_protected_button_color' ).get();
var password_protected_button = '.post-password-form input[type="submit"]{background-color: ' + password_protected_button_color + ';}.post-password-form input[type="submit"]:hover, .post-password-form input[type="submit"]:focus{background-color: ' + darken( password_protected_button_color, 7 ) + ';}';
if (
schemes[ anchor_color ] !== undefined &&
anchor_color == header_color &&
header_color == menu_color &&
menu_color == footer_color &&
footer_color == logo_color &&
logo_color == readmore_color &&
readmore_color == comments_button_color &&
comments_button_color == comments_submit_button_color &&
comments_submit_button_color == prev_next_posts_color &&
prev_next_posts_color == search_button_color &&
search_button_color == audio_color &&
audio_color == gallery_arrows_color &&
gallery_arrows_color == blog_post_pagination_color &&
blog_post_pagination_color == password_protected_button_color
) one_color = true;
styles.push( anchor_top );
styles.push( header );
styles.push( menu );
styles.push( footer );
styles.push( logo );
styles.push( readmore );
styles.push( anchor_post_item );
styles.push( comments_button );
styles.push( comments_submit_button );
styles.push( title_hover );
styles.push( prev_next_posts );
styles.push( anchor_bottom );
styles.push( search_button );
styles.push( audio );
styles.push( gallery_arrows );
styles.push( blog_post_pagination );
styles.push( password_protected_button );
style_output = styles.join( '\n' );
if ( one_color == false ) {
if ( wp.customize.preview.window[0].parent.wp.customize( 'briar_custom_style' ).get() !== style_output )
wp.customize.preview.window[0].parent.wp.customize( 'briar_custom_style' ).set( style_output );
}
else {
if ( wp.customize.preview.window[0].parent.wp.customize( 'briar_custom_style' ).get() !== '' )
wp.customize.preview.window[0].parent.wp.customize( 'briar_custom_style' ).set( '' );
}
$( 'style#customize-preview-style' ).html( style_output );
}
function handle_color( value ) {
value.bind( update_style );
}
wp.customize( 'briar_anchor_color', handle_color );
wp.customize( 'briar_header_color', handle_color );
wp.customize( 'briar_menu_color', handle_color );
wp.customize( 'briar_footer_color', handle_color );
wp.customize( 'briar_logo_color', handle_color );
wp.customize( 'briar_readmore_color', handle_color );
wp.customize( 'briar_comments_button_color', handle_color );
wp.customize( 'briar_comments_submit_button_color', handle_color );
wp.customize( 'briar_title_hover_color', handle_color );
wp.customize( 'briar_prev_next_posts_color', handle_color );
wp.customize( 'briar_search_button_color', handle_color );
wp.customize( 'briar_audio_color', handle_color );
wp.customize( 'briar_gallery_arrows_color', handle_color );
wp.customize( 'briar_blog_post_pagination_color', handle_color );
wp.customize( 'briar_password_protected_button_color', handle_color );
$( document ).on( 'ready', update_style );
} )( jQuery, less );
|
const prettier = require('prettier');
const prettierOptions = {} // optional
// filename serializer that removes the basedir
module.exports = {
test: function(val) {
try {
return (
typeof val === 'string' &&
/function /.test(val) &&
val !== prettier.format(val, prettierOptions)
);
} catch (ex) {
return false;
}
},
print: function(val, serialize, indent) {
return serialize(prettier.format(val, prettierOptions));
}
};
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S11.13.2_A4.3_T1.2;
* @section: 11.13.2, 11.5.3;
* @assertion: The production x %= y is the same as x = x % y;
* @description: Type(x) and Type(y) vary between primitive number and Number object;
*/
//CHECK#1
x = 1;
x %= 1;
if (x !== 0) {
$ERROR('#1: x = 1; x %= 1; x === 0. Actual: ' + (x));
}
//CHECK#2
x = new Number(1);
x %= 1;
if (x !== 0) {
$ERROR('#2: x = new Number(1); x %= 1; x === 0. Actual: ' + (x));
}
//CHECK#3
x = 1;
x %= new Number(1);
if (x !== 0) {
$ERROR('#3: x = 1; x %= new Number(1); x === 0. Actual: ' + (x));
}
//CHECK#4
x = new Number(1);
x %= new Number(1);
if (x !== 0) {
$ERROR('#4: x = new Number(1); x %= new Number(1); x === 0. Actual: ' + (x));
}
|
'use strict';
var fs = require('fs');
var path = require('path');
var http = require('http');
var url = require('url');
var css = require('css');
var ignore = require('ignore');
var cheerio = require('cheerio');
var Promise = require('promise');
var ColorConsole = require('./color-console.js');
// http://font-spider.org/css/style.css
//var RE_SERVER = /^(\/|http\:|https\:)/i;
var RE_SERVER = /^(http\:|https\:)/i;
var Spider = function (htmlFiles, options) {
options = this._getOptions(options);
if (typeof htmlFiles === 'string') {
htmlFiles = [htmlFiles];
}
new ColorConsole(options).mix(this);
var that = this;
this.fontsCache = {};
this.charsCache = {};
this.fileCache = {};
this.cssParserCache = {};
this.options = options;
this.ignore = ignore({
ignore: options.ignore
});
htmlFiles = this.filter(htmlFiles)
.map(function (htmlFile) {
return that.htmlParser(htmlFile);
});
return Promise.all(htmlFiles)
.then(function (contents) {
var list = [];
var files = that.fontsCache;
var chars = that.charsCache;
function sort (a, b) {
return a.charCodeAt() - b.charCodeAt();
}
// 数组除重复
function unique (array) {
var ret = [];
array.forEach(function (val) {
if (ret.indexOf(val) === -1) {
ret.push(val);
}
});
return ret;
};
Object.keys(chars).forEach(function (familyName) {
var strings = chars[familyName].split('');
// 对字符进行除重操作
if (options.unique) {
strings = unique(strings);
}
// 对字符按照编码进行排序
if (options.sort) {
strings.sort(sort);
}
strings = strings.join('');
// 删除无效字符
strings = strings.replace(/[\n\r\t]/g, '');
chars[familyName] = strings;
});
Object.keys(files).forEach(function (familyName) {
if (chars[familyName]) {
list.push({
name: familyName,
chars: chars[familyName],
files: files[familyName]
});
}
});
return list;
})
.then(null, function (errors) {
console.error(errors && errors.stack || errors);
return errors;
});
};
Spider.defaults = {
sort: true, // 是否将查询到的文本按字体中字符的顺序排列
unique: true, // 是否去除重复字符
ignore: [], // 忽略的文件配置
map: [], // 文件映射配置
log: false, // 是否显示调试日志
info: true, // 是否显示提示
error: true, // 是否显示错误
warn: true // 是否显示警告
};
Spider.prototype = {
constructor: Spider,
/*
* 解析 HTML
* @param {String} 文件绝对路径
* @return {Promise}
*/
htmlParser: function (htmlFile) {
var $;
var pme;
var that = this;
var isBuffer = typeof htmlFile === 'object' && htmlFile.isBuffer();
var options = {
from : 'Node',
cache : false
};
if( isBuffer ){
options.file = htmlFile.path;
options.content = htmlFile.contents.toString();
options.base = path.dirname( htmlFile.path );
pme = Promise.resolve( options );
}
else{
options.file = htmlFile;
options.base = path.dirname( htmlFile );
pme = this.resource( options );
}
// 查找页面中的样式内容
// 如 link 标签与页面内联 style 标签
return pme.then(function (resource) {
var htmlContent = resource.content;
var resources = [];
$ = cheerio.load(htmlContent);
// TODO <base /> 标签顺序会影响解析
var base = $('base[href]').attr('href') || resource.base;
// 外部样式
$('link[rel=stylesheet]').each(function (index) {
var line = index + 1;
var $this = $(this);
var cssFile;
var href = $this.attr('href');
// 忽略含有有 disabled 属性的
if ($this.attr('disabled') && $this.attr('disabled') !== 'false') {
return;
}
if (!that.filter([href]).length) {
return;
}
cssFile = that._resolve(base, href);
cssFile = that.map(cssFile);
cssFile = that._normalize(cssFile);
resources.push(that.resource({
file: cssFile,
from: htmlFile + '#<link:nth-of-type(' + line + ')>',
base: path.dirname(cssFile),
cache: true
}));
});
// 页面内联样式
$('style').each(function (index) {
var line = index + 1;
var $this = $(this);
// 忽略含有有 disabled 属性的
if ($this.attr('disabled') && $this.attr('disabled') !== 'false') {
return;
}
resources.push(that.resource({
file: htmlFile + '#<style:nth-of-type(' + line + ')>',
from: htmlFile,
base: base,
cache: false,
content: $this.text()
}));
});
return Promise.all(resources);
})
// 解析样式表
.then(function (resources) {
var cssInfos = [];
resources.forEach(function (resource) {
var cssInfo = that.cssParser(resource);
cssInfos.push(cssInfo);
});
return Promise.all(cssInfos);
})
// 根据选择器查询 HTML 节点,提取 WebFont 使用的字符
.then(function (cssInfos) {
var RE_SPURIOUS = /\:(link|visited|hover|active|focus)\b/ig;
var eachSelectors = function (selectors) {
var rules = selectors.rules.join(', ');
selectors.familys.forEach(function (family) {
if (!that.fontsCache[family]) { // TODO 这一句可能因为顺序问题产生BUG
return;
}
that.charsCache[family] = that.charsCache[family] || '';
// 使用 CSS content 属性存放的字符(不支持继承)
that.charsCache[family] += selectors.contents;
// 使用选择器查找节点
try {
// 剔除状态伪类
rules = rules.replace(RE_SPURIOUS, '');
var elements = $(rules);
} catch (e) {
// 1. 包含 :before 等不支持的伪类
// 2. 非法语句
return;
}
that.log('[%s]', family, rules);
elements.each(function (index, element) {
// 找到使用了字体的文本
that.charsCache[family] += $(element).text();
});
});
};
cssInfos.forEach(function (cssInfo) {
cssInfo.fonts.forEach(function (item) {
that.fontsCache[item.name] = item.files;
});
// 提取 HTML 的文本
cssInfo.selectors.forEach(eachSelectors);
that.log(JSON.stringify(cssInfo, null, 4));
});
});
},
// 提取 css 中要用到的信息
cssParser: function (resource) {
var string = resource.content;
var file = resource.file;
var from = resource.from;
var base = resource.base;
// url(../font/font.ttf)
// url("../font/font.ttf")
// url('../font/font.ttf')
var RE_FONT_URL = /url\((.*?)\)/ig;
var RE_CSS_URL = /url\((.*?)\)/i;
// "../font/font.ttf"
// '../font/font.ttf'
var RE_QUOTATION = /^['"]|['"]/g;
// !important
var RE_IMPORTANT = /!important[\s\t]*$/i;
// art, lanting, heiti
var RE_SPLIT_COMMA = /\s*,\s*/;
var that = this;
var cache = this.cssParserCache[file];
var imports = [];
if (cache) {
return cache;
}
var getCssError = function (error) {
return error.reason + ', line: ' + error.line + ', column: ' + error.column;
};
// 字体文件信息
var fonts = [];
// 选择器信息
var selectors = [];
try {
var ast = css.parse(string, {
silent: false,
source: file
});
} catch (e) {
if (e.line !== undefined) {
that.error('[ERROR]', getCssError(e),
'\n ', 'file:', file);
} else if (e.stack) {
that.error('[ERROR]',
'\n ', 'file:', file, e.stack);
}
return {
fonts: [],
selectors: [],
from: from
};
}
var parser = function (rule) {
var position = rule.position;
switch (rule.type) {
case 'import':
var src = rule['import'];
// @import url("./g.css?t=2009");
// @import "./g.css?t=2009";
if (RE_CSS_URL.test(src)) {
RE_CSS_URL.lastIndex = 0;
src = RE_CSS_URL.exec(src)[1];
}
src = src.trim().replace(RE_QUOTATION, '')
if (!that.filter([src]).length) {
break;
}
var target = that._resolve(base, src);
var line = position ? position.start.line : null;
target = that.map(target);
target = that._normalize(target);
// TODO 超过一层嵌套后,from 不准确
imports.push(
that.resource({
file: target,
base: path.dirname(target),
from: file,
line: line,
cache: true
})
.then(function (resource) {
return that.cssParser(resource);
})
);
break;
case 'font-face':
var family = {
name: '',
files: []
};
rule.declarations.forEach(function (declaration) {
var property = declaration.property;
var value = declaration.value;
if (property) {
property = property.toLocaleLowerCase();
}
switch (property) {
case 'font-family':
value = value
.replace(RE_IMPORTANT, '')
.replace(RE_QUOTATION, '')
.trim();
family.name = value;
break;
case 'src':
var src;
RE_FONT_URL.lastIndex = 0;
while ((src = RE_FONT_URL.exec(value)) !== null) {
src = src[1];
src = src.trim().replace(RE_QUOTATION, '');
src = that._resolve(base, src);
src = that.map(src);
src = that._normalize(src);
if (family.files.indexOf(src) === -1) {
family.files.push(src);
}
}
break;
}
});
if (family.name) {
family.files = that.filter(family.files);
fonts.push(family);
}
break;
case 'media':
rule.rules.forEach(parser);
break;
case 'rule':
var selector = {
rules: rule.selectors,// 注意:包含伪类选择器
familys: [],
contents: ''
};
rule.declarations.forEach(function (declaration) {
var property = declaration.property;
var value = declaration.value;
if (property) {
property = property.toLocaleLowerCase()
}
switch (property) {
case 'font-family':
value.split(RE_SPLIT_COMMA).forEach(function (val) {
// 去掉空格与前后引号
val = val
.replace(RE_IMPORTANT, '')
.replace(RE_QUOTATION, '')
.trim();
selector.familys.push(val);
});
break;
case 'content':
selector.contents += value;
break;
}
});
if (selector.familys.length) {
selectors.push(selector);
}
break;
}
};
ast.stylesheet.rules.forEach(parser);
imports.unshift({
fonts: fonts,
selectors: selectors,
from: from
});
return this.cssParserCache[file] = Promise.all(imports)
.then(function (res) {
var cssInfo = {
fonts: [],
selectors: [],
from: from
};
res.forEach(function (item) {
cssInfo.fonts = cssInfo.fonts.concat(item.fonts);
cssInfo.selectors = cssInfo.selectors.concat(item.selectors);
});
return cssInfo;
});
},
/*
* 资源。注意:读取错误的文件会返回空字符串,不会进入错误流程
* @param {Object options} <options.file>, ...
* @param {Promise, options} <options.file>, <options.content>, ...
*/
resource: function (options) {
var file = options.file;
var content = options.content;
var isCache = options.cache !== undefined;
if (content !== undefined) {
return options;
} else {
options.content = '';
}
var from = options.from;
var that = this;
var cache = this.fileCache[file];
var ret;
if (cache) {
return cache;
}
var error = function (errors) {
var fromCode = from;
if (typeof options.line !== undefined) {
fromCode == from + ':' + options.line;
}
that.error('[ERROR]', 'load "' + file + '" failed',
'\n ', 'from:', fromCode);
};
ret = new Promise(function (resolve, reject) {
// 远程文件
if (RE_SERVER.test(file)) {
that.info('Load', '(' + file + ')');
http.get(file, function (res) {
var size = 0;
var chunks = [];
res.on('data', function (chunk) {
size += chunk.length;
chunks.push(chunk);
});
res.on('end', function () {
var buffer = Buffer.concat(chunks, size);
options.content = buffer.toString();
resolve(options);
});
})
.on('error', function (errors) {
error(errors);
resolve(options);
});
// 本地文件
} else {
that.log('Read', '(' + file + ')');
fs.readFile(file, 'utf8', function (errors, content) {
if (errors) {
error(errors);
resolve(options);
} else {
options.content = content;
resolve(options);
}
});
}
});
if (isCache) {
this.fileCache[file] = ret;
}
return ret;
},
/*
* 转换到绝对路径,支持 HTTP 形式
* @param {String} 来源路径
* @param {String} 子路径
* @return {String} 绝对路径
*/
_resolve: function (from, to) {
if (RE_SERVER.test(from)) {
return url.resolve(from, to);
} else if (RE_SERVER.test(to)) {
return to;
} else {
return path.resolve(from, to);
}
},
/*
* 标准化路径
* @param {String} 路径
* @return {String} 标准化路径
*/
_normalize: function (src) {
// ../font/font.eot?#font-spider
var RE_QUERY = /[#?].*$/g;
if (RE_SERVER.test(src)) {
return src;
} else {
src = src.replace(RE_QUERY, '');
return path.normalize(src);
}
},
_getOptions: function (options) {
var ret = {};
options = options || {};
Object.keys(Spider.defaults).forEach(function (key) {
ret[key] = Spider.defaults[key];
if (options[key] !== undefined) {
ret[key] = options[key];
}
});
ret.map = ret.map.map(function (params) {
if (typeof params[0] === 'string') {
params[0] = new RegExp(params[0]);
}
return params;
});
return ret;
},
// 根据正则替换 URL
map: function (src) {
var regs = this.options.map;
if (!regs || !regs.length) {
return src;
}
if (!Array.isArray(regs[0])) {
regs = [regs];
}
regs.forEach(function (reg) {
src = src.replace.apply(src, reg);
});
return src;
},
// 筛选路径
filter: function (srcs) {
if( Array.isArray(srcs) ){
return this.ignore.filter(srcs);
}
else{
return [ srcs ];
}
}
};
module.exports = Spider;
|
import svg from 'config/svg';
import namespaces from 'config/namespaces';
var createElement;
// Test for SVG support
if ( !svg ) {
createElement = function ( type, ns ) {
if ( ns && ns !== namespaces.html ) {
throw 'This browser does not support namespaces other than http://www.w3.org/1999/xhtml. The most likely cause of this error is that you\'re trying to render SVG in an older browser. See http://docs.ractivejs.org/latest/svg-and-older-browsers for more information';
}
return document.createElement( type );
};
} else {
createElement = function ( type, ns ) {
if ( !ns || ns === namespaces.html ) {
return document.createElement( type );
}
return document.createElementNS( ns, type );
};
}
export default createElement;
|
/**
* @license The MIT License (MIT)
*
* Copyright (c) 2014 Felipe O. Carvalho
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
define(['JSXTransformer', 'text'], function (JSXTransformer, text) {
'use strict';
var buildMap = {};
var jsx = {
version: '0.5.1',
load: function (name, req, onLoadNative, config) {
var fileExtension = config.jsx && config.jsx.fileExtension || '.js';
var transformOptions = (config.jsx && config.jsx.harmony) ? {harmony: true} : null;
var onLoad = function(content) {
try {
content = JSXTransformer.transform(content, transformOptions).code;
} catch (err) {
onLoadNative.error(err);
}
if (config.isBuild) {
buildMap[name] = content;
} else if (typeof location !== 'undefined') { // Do not create sourcemap when loaded in Node
content += '\n//# sourceURL=' + location.protocol + '//' + location.hostname +
config.baseUrl + name + fileExtension;
}
onLoadNative.fromText(content);
};
text.load(name + fileExtension, req, onLoad, config);
},
write: function (pluginName, moduleName, write) {
if (buildMap.hasOwnProperty(moduleName)) {
var content = buildMap[moduleName];
write.asModule(pluginName + '!' + moduleName, content);
}
}
};
return jsx;
});
|
import Enum from '../../lib/Enum';
export default new Enum([
'invalidMeetingInfo',
'emptyTopic',
'noPassword',
'durationIncorrect',
'scheduledSuccess',
], 'meetingStatus');
|
/**
* Single radio field. Similar to checkbox, but automatically handles making sure only one radio is checked
* at a time within a group of radios with the same name.
*
* # Labeling
*
* In addition to the {@link Ext.form.Labelable standard field labeling options}, radio buttons
* may be given an optional {@link #boxLabel} which will be displayed immediately to the right of the input. Also
* see {@link Ext.form.RadioGroup} for a convenient method of grouping related radio buttons.
*
* # Values
*
* The main value of a Radio field is a boolean, indicating whether or not the radio is checked.
*
* The following values will check the radio:
*
* - `true`
* - `'true'`
* - `'1'`
* - `'on'`
*
* Any other value will uncheck it.
*
* In addition to the main boolean value, you may also specify a separate {@link #inputValue}. This will be sent
* as the parameter value when the form is {@link Ext.form.Basic#submit submitted}. You will want to set this
* value if you have multiple radio buttons with the same {@link #name}, as is almost always the case.
*
* # Example usage
*
* @example
* Ext.create('Ext.form.Panel', {
* title : 'Order Form',
* width : 300,
* bodyPadding: 10,
* renderTo : Ext.getBody(),
* items: [
* {
* xtype : 'fieldcontainer',
* fieldLabel : 'Size',
* defaultType: 'radiofield',
* defaults: {
* flex: 1
* },
* layout: 'hbox',
* items: [
* {
* boxLabel : 'M',
* name : 'size',
* inputValue: 'm',
* id : 'radio1'
* }, {
* boxLabel : 'L',
* name : 'size',
* inputValue: 'l',
* id : 'radio2'
* }, {
* boxLabel : 'XL',
* name : 'size',
* inputValue: 'xl',
* id : 'radio3'
* }
* ]
* },
* {
* xtype : 'fieldcontainer',
* fieldLabel : 'Color',
* defaultType: 'radiofield',
* defaults: {
* flex: 1
* },
* layout: 'hbox',
* items: [
* {
* boxLabel : 'Blue',
* name : 'color',
* inputValue: 'blue',
* id : 'radio4'
* }, {
* boxLabel : 'Grey',
* name : 'color',
* inputValue: 'grey',
* id : 'radio5'
* }, {
* boxLabel : 'Black',
* name : 'color',
* inputValue: 'black',
* id : 'radio6'
* }
* ]
* }
* ],
* bbar: [
* {
* text: 'Smaller Size',
* handler: function() {
* var radio1 = Ext.getCmp('radio1'),
* radio2 = Ext.getCmp('radio2'),
* radio3 = Ext.getCmp('radio3');
*
* //if L is selected, change to M
* if (radio2.getValue()) {
* radio1.setValue(true);
* return;
* }
*
* //if XL is selected, change to L
* if (radio3.getValue()) {
* radio2.setValue(true);
* return;
* }
*
* //if nothing is set, set size to S
* radio1.setValue(true);
* }
* },
* {
* text: 'Larger Size',
* handler: function() {
* var radio1 = Ext.getCmp('radio1'),
* radio2 = Ext.getCmp('radio2'),
* radio3 = Ext.getCmp('radio3');
*
* //if M is selected, change to L
* if (radio1.getValue()) {
* radio2.setValue(true);
* return;
* }
*
* //if L is selected, change to XL
* if (radio2.getValue()) {
* radio3.setValue(true);
* return;
* }
*
* //if nothing is set, set size to XL
* radio3.setValue(true);
* }
* },
* '-',
* {
* text: 'Select color',
* menu: {
* indent: false,
* items: [
* {
* text: 'Blue',
* handler: function() {
* var radio = Ext.getCmp('radio4');
* radio.setValue(true);
* }
* },
* {
* text: 'Grey',
* handler: function() {
* var radio = Ext.getCmp('radio5');
* radio.setValue(true);
* }
* },
* {
* text: 'Black',
* handler: function() {
* var radio = Ext.getCmp('radio6');
* radio.setValue(true);
* }
* }
* ]
* }
* }
* ]
* });
*/
Ext.define('Ext.form.field.Radio', {
extend:'Ext.form.field.Checkbox',
alias: ['widget.radiofield', 'widget.radio'],
alternateClassName: 'Ext.form.Radio',
requires: ['Ext.form.RadioManager'],
/**
* @property {Boolean} isRadio
* `true` in this class to identify an object as an instantiated Radio, or subclass thereof.
*/
isRadio: true,
/**
* @cfg {String} uncheckedValue
* @private
*/
// private
inputType: 'radio',
ariaRole: 'radio',
// Radios are naturally focusable but they need to participate in RadioGroups
// which are focusable containers; we set tabIndex to >= 0 here to make that work
tabIndex: 0,
formId: null,
/**
* If this radio is part of a group, it will return the selected value
* @return {String}
*/
getGroupValue: function() {
var selected = this.getManager().getChecked(this.name, this.getFormId());
return selected ? selected.inputValue : null;
},
/**
* @private Handle click on the radio button
*/
onBoxClick: function() {
var me = this;
if (!me.disabled && !me.readOnly) {
this.setValue(true);
}
},
onRemoved: function(){
this.callParent(arguments);
this.formId = null;
},
/**
* Sets either the checked/unchecked status of this Radio, or, if a string value is passed, checks a sibling Radio
* of the same name whose value is the value specified.
* @param {String/Boolean} value Checked value, or the value of the sibling radio button to check.
* @return {Ext.form.field.Radio} this
*/
setValue: function(value) {
var me = this,
active;
if (Ext.isBoolean(value)) {
me.callParent(arguments);
} else {
active = me.getManager().getWithValue(me.name, value, me.getFormId()).getAt(0);
if (active) {
active.setValue(true);
}
}
return me;
},
/**
* Returns the submit value for the checkbox which can be used when submitting forms.
* @return {Boolean/Object} True if checked, null if not.
*/
getSubmitValue: function() {
return this.checked ? this.inputValue : null;
},
onChange: function(newVal, oldVal) {
var me = this,
r, rLen, radio, radios;
me.callParent(arguments);
if (newVal) {
radios = me.getManager().getByName(me.name, me.getFormId()).items;
rLen = radios.length;
for (r = 0; r < rLen; r++) {
radio = radios[r];
if (radio !== me) {
radio.setValue(false);
}
}
}
},
getManager: function() {
return Ext.form.RadioManager;
}
});
|
import React from 'react'
import Icon from 'react-icon-base'
const FaLevelDown = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m9.2 5.7h15.7q0.3 0 0.5 0.2t0.2 0.6v19.2h4.3q0.9 0 1.3 0.8t-0.2 1.6l-7.1 8.6q-0.4 0.4-1.1 0.4t-1.1-0.4l-7.1-8.6q-0.6-0.7-0.2-1.6 0.4-0.8 1.2-0.8h4.3v-14.3h-7.1q-0.3 0-0.6-0.2l-3.5-4.3q-0.3-0.3-0.1-0.8 0.2-0.4 0.6-0.4z"/></g>
</Icon>
)
export default FaLevelDown
|
/**
* Draw routes.
*
* Route handlers are created using Electrolyte, which automatically wires
* together any necessary components, including database connections, logging
* facilities, configuration settings, etc.
*/
exports = module.exports = function routes(express, listHandler, createHandler) {
var router = express();
router.get('/', listHandler);
router.post('/todo', createHandler);
return router;
}
exports['@async'] = true;
exports['@singleton'] = true;
exports['@require'] = ['express', 'handlers/list', 'handlers/create']
|
'use strict';
/* Filters */
angular.module('myApp.filters', []).
filter('n', [ function() {
return function(i) {
return i == 0 ? "" : i;
};
}]
)
.filter('pos', [ function() {
return function(i) {
if (i == 1) return "GK";
if (i == 2) return "DEF";
if (i == 3) return "MID";
if (i == 4) return "FWD";
return i;
};
}]
)
.filter('movement', [ function() {
return function(i) {
if (i > 0) return "positive";
if (i < 0) return "negative";
return "";
};
}]
)
.filter('status', [ function() {
return function(i, chance, news) {
if (i == 'd') {
if (chance == 25 || chance == 50 || chance == 75) return "doubt" + chance;
return "doubt";
}
if (i == 'u' || news) return "warn";
return i;
};
}]
)
.filter('statusText', [ function() {
return function(i, chance, news) {
if (i == 'd') {
if (chance == 25 || chance == 50 || chance == 75) return chance + "%";
return "d" // doubt;
}
if (i == 'i') return "i";
if (i == 'u' || i == 'n') return "x";
return i;
};
}]
).filter('maskBool', [ function() {
return function(i, trueText, falseText) {
if (i == true) return trueText;
if (i == false) return falseText;
return "";
};
}]
);
|
import React from "react";
import ReactDOM from "react-dom";
import VictoryScatter from "src/components/victory-scatter/victory-scatter";
import VictoryChart from "src/components/victory-chart/victory-chart";
import VictoryGroup from "src/components/victory-group/victory-group";
import VictoryStack from "src/components/victory-stack/victory-stack";
import { element, suiteOpts } from "../../helpers/bench-helpers.js";
import { dataSamples, dataAccessorSamples } from "./sample-data";
suite("<VictoryScatter> data", () => {
benchmark("identity fn", () => ReactDOM.render(<VictoryScatter />, element));
benchmark("10 pts", () => ReactDOM.render(
<VictoryScatter
data={dataSamples[10]}
/>, element)
);
benchmark("50 pts", () => ReactDOM.render(
<VictoryScatter
data={dataSamples[50]}
/>, element)
);
benchmark("100 pts", () => ReactDOM.render(
<VictoryScatter
data={dataSamples[100]}
/>, element)
);
}, suiteOpts);
suite("<VictoryScatter> data accessor", () => {
benchmark("10 pts", () => ReactDOM.render(
<VictoryScatter
data={dataAccessorSamples[10]}
x={"count"}
/>, element)
);
benchmark("50 pts", () => ReactDOM.render(
<VictoryScatter
data={dataAccessorSamples[50]}
x={"count"}
/>, element)
);
benchmark("100 pts", () => ReactDOM.render(
<VictoryScatter
data={dataAccessorSamples[100]}
x={"count"}
/>, element)
);
}, suiteOpts);
suite("<VictoryScatter> wrapped in <VictoryChart>", () => {
benchmark("unwrapped <VictoryScatter>",
() => ReactDOM.render(<VictoryScatter />, element));
benchmark("wrapped by <VictoryChart>", () => ReactDOM.render(
<VictoryChart>
<VictoryScatter />
</VictoryChart>, element));
}, suiteOpts);
suite("<VictoryScatter> wrapped in <VictoryGroup>", () => {
benchmark("unwrapped <VictoryScatter>",
() => ReactDOM.render(<VictoryScatter />, element));
benchmark("wrapped by <VictoryGroup>", () => ReactDOM.render(
<VictoryGroup>
<VictoryScatter />
</VictoryGroup>, element));
}, suiteOpts);
suite("<VictoryScatter> wrapped in <VictoryStack>", () => {
benchmark("unwrapped <VictoryScatter>",
() => ReactDOM.render(<VictoryScatter />, element));
benchmark("wrapped by <VictoryStack>", () => ReactDOM.render(
<VictoryStack>
<VictoryScatter />
</VictoryStack>, element));
}, suiteOpts);
|
'use strict';
const { isString, isPlainObject } = require('lodash');
const regex = /\$\{[^()]*\}/g;
const excludeConfigPaths = ['info.scripts'];
/**
* Allow dynamic config values through the native ES6 template string function.
*/
const templateConfiguration = (obj, configPath = '') => {
// Allow values which looks like such as an ES6 literal string without parenthesis inside (aka function call).
// Exclude config with conflicting syntax (e.g. npm scripts).
return Object.keys(obj).reduce((acc, key) => {
if (isPlainObject(obj[key]) && !isString(obj[key])) {
acc[key] = templateConfiguration(obj[key], `${configPath}.${key}`);
} else if (
isString(obj[key]) &&
!excludeConfigPaths.includes(configPath.substr(1)) &&
obj[key].match(regex) !== null
) {
// eslint-disable-next-line prefer-template
acc[key] = eval('`' + obj[key] + '`');
} else {
acc[key] = obj[key];
}
return acc;
}, {});
};
module.exports = templateConfiguration;
|
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next){
res.render('index', { title: 'Express' });
console.log(req);
});
router.post('/',function(req,res,next){
res.render('login',{title:'hum'});
console.log(req);
});
module.exports = router;
|
"use strict";
var fs = require('fs');
var path = require('path');
var dns = require('dns');
var net = require('net');
var util = require("util");
var events = require("events");
var utils = require('./utils');
var sock = require('./line_socket');
var server = require('./server');
var logger = require('./logger');
var config = require('./config');
var constants = require('./constants');
var trans = require('./transaction');
var plugins = require('./plugins');
var async = require('async');
var Address = require('./address').Address;
var TimerQueue = require('./timer_queue');
var date_to_str = utils.date_to_str;
var existsSync = utils.existsSync;
var FsyncWriteStream = require('./fsync_writestream');
var core_consts = require('constants');
var WRITE_EXCL = core_consts.O_CREAT | core_consts.O_TRUNC | core_consts.O_WRONLY | core_consts.O_EXCL;
var DENY = constants.deny;
var OK = constants.ok;
var MAX_UNIQ = 10000;
var host = require('os').hostname().replace(/\\/, '\\057').replace(/:/, '\\072');
var fn_re = /^(\d+)_(\d+)_/; // I like how this looks like a person
var queue_dir = path.resolve(config.get('queue_dir') || (process.env.HARAKA + '/queue'));
var uniq = Math.round(Math.random() * MAX_UNIQ);
var MAX_CONCURRENCY = config.get('outbound.concurrency_max') || 100;
var load_queue = async.queue(function (file, cb) {
var hmail = new HMailItem(file, path.join(queue_dir, file));
exports._add_file(hmail);
hmail.once('ready', cb);
}, MAX_CONCURRENCY);
var in_progress = 0;
var delivery_queue = async.queue(function (hmail, cb) {
in_progress++;
hmail.next_cb = function () {
in_progress--;
cb();
}
hmail.send()
}, MAX_CONCURRENCY);
var temp_fail_queue = new TimerQueue();
var queue_count = 0;
exports.get_stats = function () {
return in_progress + '/' + delivery_queue.length() + '/' + temp_fail_queue.length();
}
exports.list_queue = function (cb) {
this._load_cur_queue(null, "_list_file", cb);
}
exports.stat_queue = function (cb) {
var self = this;
this._load_cur_queue(null, "_stat_file", function () {
return cb(self.stats());
});
}
exports.scan_queue_pids = function (cb) {
var self = this;
fs.readdir(queue_dir, function (err, files) {
if (err) {
self.logerror("Failed to load queue directory (" + queue_dir + "): " + err);
return cb(err);
}
var pids = {};
files.forEach(function (file) {
if (/^\./.test(file)) {
// dot-file...
self.logwarn("Removing left over dot-file: " + file);
return fs.unlink(file, function () {});
}
// Format: $time_$attempts_$pid_$uniq.$host
var match = /^\d+_\d+_(\d+)_\d+\./.exec(file);
if (!match) {
self.logerror("Unrecognised file in queue directory: " + queue_dir + '/' + file);
return;
}
pids[match[1]] = true;
});
return cb(null, Object.keys(pids));
});
}
process.on('message', function (msg) {
if (msg.event && msg.event === 'outbound.load_pid_queue') {
exports.load_pid_queue(msg.data);
}
else if (msg.event && msg.event === 'outbound.flush_queue') {
exports.flush_queue();
}
// otherwise ignore the message
});
exports.flush_queue = function () {
temp_fail_queue.drain();
}
exports.load_pid_queue = function (pid) {
this.loginfo("Loading queue for pid: " + pid);
this.load_queue(pid);
}
exports.load_queue = function (pid) {
// Initialise and load queue
// we create the dir here because this is used when Haraka is running
// properly.
// no reason not to do this stuff syncronously - we're just loading here
if (!existsSync(queue_dir)) {
this.logdebug("Creating queue directory " + queue_dir);
try {
fs.mkdirSync(queue_dir, 493); // 493 == 0755
}
catch (err) {
if (err.code != 'EEXIST') {
logger.logerror("Error creating queue directory: " + err);
throw err;
}
}
}
this._load_cur_queue(pid, "_add_file");
}
exports._load_cur_queue = function (pid, cb_name, cb) {
var self = this;
self.loginfo("Loading outbound queue from ", queue_dir);
fs.readdir(queue_dir, function (err, files) {
if (err) {
return self.logerror("Failed to load queue directory (" + queue_dir + "): " + err);
}
self.cur_time = new Date(); // set this once so we're not calling it a lot
self.load_queue_files(pid, cb_name, files);
if (cb) cb();
});
}
exports.load_queue_files = function (pid, cb_name, files) {
var self = this;
if (files.length === 0) return;
if (config.get('outbound.disabled') && cb_name === '_add_file') {
// try again in 1 second if delivery is disabled
setTimeout(function () {self.load_queue_files(pid, cb_name, files)}, 1000);
return;
}
if (pid) {
// Pre-scan to rename PID files to my PID:
this.loginfo("Grabbing queue files for pid: " + pid);
async.eachLimit(files, 200, function (file, cb) {
var match = /^(\d+)(_\d+_)(\d+)(_\d+\..*)$/.exec(file);
if (match && match[3] == pid) {
var next_process = match[1];
var new_filename = match[1] + match[2] + process.pid + match[4];
// self.loginfo("Renaming: " + file + " to " + new_filename);
fs.rename(queue_dir + '/' + file, queue_dir + '/' + new_filename, function (err) {
if (err) {
self.logerror("Unable to rename queue file: " + file + " to " + new_filename + " : " + err);
return cb();
}
if (next_process <= self.cur_time) {
load_queue.push(new_filename);
}
else {
temp_fail_queue.add(next_process - self.cur_time, function () { load_queue.push(new_filename) });
}
// self.loginfo("Done");
cb();
});
}
else if (/^\./.test(file)) {
// dot-file...
self.logwarn("Removing left over dot-file: " + file);
return fs.unlink(queue_dir + "/" + file, function (err) {
if (err) {
self.logerror("Error removing dot-file: " + file + ": " + err);
}
cb();
});
}
else {
// Do this because otherwise we blow the stack
async.setImmediate(cb);
}
}, function (err) {
if (err) {
// no error cases yet, but log anyway
self.logerror("Error fixing up queue files: " + err);
}
self.loginfo("Done fixing up old PID queue files");
self.loginfo(delivery_queue.length() + " files in my delivery queue");
self.loginfo(load_queue.length() + " files in my load queue");
self.loginfo(temp_fail_queue.length() + " files in my temp fail queue");
});
}
else {
self.loginfo("Loading the queue...");
files.forEach(function (file) {
if (/^\./.test(file)) {
// dot-file...
self.logwarn("Removing left over dot-file: " + file);
return fs.unlink(queue_dir + "/" + file, function () {});
}
var matches = file.match(fn_re);
if (!matches) {
self.logerror("Unrecognised file in queue folder: " + file);
return;
}
var next_process = matches[1];
if (cb_name === '_add_file') {
if (next_process <= self.cur_time) {
load_queue.push(file);
}
else {
temp_fail_queue.add(next_process - self.cur_time, function () { load_queue.push(file) });
}
}
else {
self[cb_name](file);
}
});
}
}
exports._add_file = function (hmail) {
var self = this;
// this.loginfo("Adding file: " + hmail.filename);
if (hmail.next_process < this.cur_time) {
delivery_queue.push(hmail);
}
else {
temp_fail_queue.add(hmail.next_process - this.cur_time, function () { delivery_queue.push(hmail) });
}
}
exports._list_file = function (file) {
// TODO: output more data here?
console.log("Q: " + file);
}
exports._stat_file = function () {
queue_count++;
}
exports.stats = function () {
// TODO: output more data here
var results = {
queue_dir: queue_dir,
queue_count: queue_count,
};
return results;
}
function _next_uniq () {
var result = uniq++;
if (uniq >= MAX_UNIQ) {
uniq = 1;
}
return result;
}
function _fname () {
var time = new Date().getTime();
return time + '_0_' + process.pid + "_" + _next_uniq() + '.' + host;
}
exports.send_email = function () {
if (arguments.length === 2) {
this.loginfo("Sending email as with a transaction");
return this.send_trans_email(arguments[0], arguments[1]);
}
var self = this;
var from = arguments[0],
to = arguments[1],
contents = arguments[2];
var next = arguments[3];
this.loginfo("Sending email via params");
var transaction = trans.createTransaction();
this.loginfo("Created transaction: " + transaction.uuid);
// set MAIL FROM address, and parse if it's not an Address object
if (from instanceof Address) {
transaction.mail_from = from;
}
else {
try {
from = new Address(from);
}
catch (err) {
return next(DENY, "Malformed from: " + err);
}
transaction.mail_from = from;
}
// Make sure to is an array
if (!(Array.isArray(to))) {
// turn into an array
to = [ to ];
}
if (to.length === 0) {
return next(DENY, "No recipients for email");
}
// Set RCPT TO's, and parse each if it's not an Address object.
for (var i=0,l=to.length; i < l; i++) {
if (!(to[i] instanceof Address)) {
try {
to[i] = new Address(to[i]);
}
catch (err) {
return next(DENY, "Malformed to address (" + to[i] + "): " + err);
}
}
}
transaction.rcpt_to = to;
// Set data_lines to lines in contents
var match;
var re = /^([^\n]*\n?)/;
while (match = re.exec(contents)) {
var line = match[1];
line = line.replace(/\n?$/, '\r\n'); // make sure it ends in \r\n
transaction.add_data(line);
contents = contents.substr(match[1].length);
if (contents.length === 0) {
break;
}
}
transaction.message_stream.add_line_end();
this.send_trans_email(transaction, next);
}
exports.send_trans_email = function (transaction, next) {
var self = this;
// add in potentially missing headers
if (!transaction.header.get_all('Message-Id').length) {
this.loginfo("Adding missing Message-Id header");
transaction.add_header('Message-Id', '<' + transaction.uuid + '@' + config.get('me') + '>');
}
if (!transaction.header.get_all('Date').length) {
this.loginfo("Adding missing Date header");
transaction.add_header('Date', date_to_str(new Date()));
}
transaction.add_leading_header('Received', 'via haraka outbound.js at ' + date_to_str(new Date()));
// First get each domain
var recips = {};
var num_domains = 0;
transaction.rcpt_to.forEach(function (item) {
var domain = item.host;
if (!recips[domain]) {
recips[domain] = [];
num_domains++;
}
recips[domain].push(item);
});
var hmails = [];
var ok_paths = [];
async.forEachSeries(Object.keys(recips), function (domain, cb) {
var todo = new TODOItem(domain, recips[domain], transaction);
self.process_domain(ok_paths, todo, hmails, cb);
},
function (err) {
if (err) {
for (var i=0,l=ok_paths.length; i<l; i++) {
fs.unlink(ok_paths[i], function () {});
}
if (next) next(DENY, err);
return;
}
for (var i = 0; i < hmails.length; i++) {
var hmail = hmails[i];
delivery_queue.push(hmail);
}
if (next) next(OK, "Mail Queued");
})
}
exports.process_domain = function (ok_paths, todo, hmails, cb) {
var self = this;
this.loginfo("Processing domain: " + todo.domain);
var fname = _fname();
var tmp_path = path.join(queue_dir, '.' + fname);
var ws = new FsyncWriteStream(tmp_path, { flags: WRITE_EXCL });
// var ws = fs.createWriteStream(tmp_path, { flags: WRITE_EXCL });
ws.on('close', function () {
var dest_path = path.join(queue_dir, fname);
fs.rename(tmp_path, dest_path, function (err) {
if (err) {
self.logerror("Unable to rename tmp file!: " + err);
fs.unlink(tmp_path, function () {});
cb("Queue error");
}
else {
hmails.push(new HMailItem (fname, dest_path, todo.notes));
ok_paths.push(dest_path);
cb();
}
});
});
ws.on('error', function (err) {
self.logerror("Unable to write queue file (" + fname + "): " + err);
ws.destroy();
fs.unlink(tmp_path, function () {});
cb("Queueing failed");
});
self.build_todo(todo, ws);
todo.message_stream.pipe(ws, { line_endings: '\r\n', dot_stuffing: true, ending_dot: false });
}
exports.build_todo = function (todo, ws) {
// Replacer function to exclude items from the queue file header
function exclude_from_json(key, value) {
switch (key) {
case 'message_stream':
return undefined;
default:
return value;
}
}
var todo_str = new Buffer(JSON.stringify(todo, exclude_from_json));
// since JS has no pack() we have to manually write the bytes of a long
var todo_length = new Buffer(4);
var todo_l = todo_str.length;
todo_length[3] = todo_l & 0xff;
todo_length[2] = (todo_l >> 8) & 0xff;
todo_length[1] = (todo_l >> 16) & 0xff;
todo_length[0] = (todo_l >> 24) & 0xff;
var buf = Buffer.concat([todo_length, todo_str], todo_str.length + 4);
ws.write(buf);
}
exports.split_to_new_recipients = function (hmail, recipients, response, cb) {
if (recipients.length === hmail.todo.rcpt_to.length) {
// Split to new for no reason - increase refcount and return self
hmail.refcount++;
return cb(hmail);
}
var self = this;
var fname = _fname();
var tmp_path = path.join(queue_dir, '.' + fname);
var ws = new FsyncWriteStream(tmp_path, { flags: WRITE_EXCL });
// var ws = fs.createWriteStream(tmp_path, { flags: WRITE_EXCL });
var err_handler = function (err, location) {
self.logerror("Error while splitting to new recipients (" + location + "): " + err);
hmail.bounce("Error splitting to new recipients", err);
}
ws.on('error', function (err) { err_handler(err, "tmp file writer") });
var writing = false;
var write_more = function () {
if (writing) return;
writing = true;
var rs = hmail.data_stream();
rs.pipe(ws, {end: false});
rs.on('error', function (err) {
err_handler(err, "hmail.data_stream reader");
})
rs.on('end', function () {
ws.on('close', function () {
var dest_path = path.join(queue_dir, fname);
fs.rename(tmp_path, dest_path, function (err) {
if (err) {
err_handler(err, "tmp file rename");
}
else {
var split_mail = new HMailItem (fname, dest_path);
split_mail.once('ready', function () {
cb(split_mail);
});
}
});
});
ws.destroySoon();
return;
});
}
ws.on('error', function (err) {
self.logerror("Unable to write queue file (" + fname + "): " + err);
ws.destroy();
hmail.bounce("Error re-queueing some recipients", err);
});
ws.on('drain', write_more);
var new_todo = JSON.parse(JSON.stringify(hmail.todo));
new_todo.rcpt_to = recipients;
new_todo.uuid = utils.uuid();
self.build_todo(new_todo, ws, write_more);
}
// TODOItem - queue file header data
function TODOItem (domain, recipients, transaction) {
this.queue_time = Date.now();
this.domain = domain;
this.rcpt_to = recipients;
this.mail_from = transaction.mail_from;
this.message_stream = transaction.message_stream;
this.notes = transaction.notes;
this.uuid = transaction.uuid;
return this;
}
/////////////////////////////////////////////////////////////////////////////
// HMailItem - encapsulates an individual outbound mail item
var dummy_func = function () {}
function HMailItem (filename, path, notes) {
events.EventEmitter.call(this);
var matches = filename.match(fn_re);
if (!matches) {
throw new Error("Bad filename: " + filename);
}
this.path = path;
this.filename = filename;
this.next_process = matches[1];
this.num_failures = matches[2];
this.notes = notes || {};
this.refcount = 1;
this.todo = null;
this.file_size = 0;
this.next_cb = dummy_func;
this.bounce_error = null;
this.bounce_extra = null;
this.size_file();
}
util.inherits(HMailItem, events.EventEmitter);
exports.HMailItem = HMailItem;
// populate log functions - so we can use hooks
for (var key in logger) {
if (key.match(/^log\w/)) {
exports[key] = (function (key) {
return function () {
var args = ["[outbound] "];
for (var i=0, l=arguments.length; i<l; i++) {
args.push(arguments[i]);
}
logger[key].apply(logger, args);
}
})(key);
HMailItem.prototype[key] = (function (key) {
return function () {
var args = [ this ];
for (var i=0, l=arguments.length; i<l; i++) {
args.push(arguments[i]);
}
logger[key].apply(logger, args);
}
})(key);
}
}
HMailItem.prototype.data_stream = function () {
return fs.createReadStream(this.path, {start: this.data_start, end: this.file_size});
}
HMailItem.prototype.size_file = function () {
var self = this;
fs.stat(self.path, function (err, stats) {
if (err) {
// we are fucked... guess I need somewhere for this to go
self.logerror("Error obtaining file size: " + err);
self.temp_fail("Error obtaining file size");
}
else {
self.file_size = stats.size;
self.read_todo();
}
});
}
HMailItem.prototype.read_todo = function () {
var self = this;
var tl_reader = fs.createReadStream(self.path, {start: 0, end: 3});
tl_reader.on('error', function (err) {
self.logerror("Error reading queue file: " + self.path + ": " + err);
return self.temp_fail("Error reading queue file");
});
tl_reader.on('data', function (buf) {
// I'm making the assumption here we won't ever read less than 4 bytes
// as no filesystem on the planet should be that dumb...
tl_reader.destroy();
var todo_len = (buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3];
var td_reader = fs.createReadStream(self.path, {encoding: 'utf8', start: 4, end: todo_len + 3});
self.data_start = todo_len + 4;
var todo = '';
td_reader.on('data', function (str) {
todo += str;
if (Buffer.byteLength(todo) === todo_len) {
// we read everything
self.todo = JSON.parse(todo);
self.emit('ready');
}
});
td_reader.on('end', function () {
if (Buffer.byteLength(todo) !== todo_len) {
self.logcrit("Didn't find right amount of data in todo!");
fs.rename(self.path, path.join(queue_dir, "error." + self.filename), function (err) {
if (err) {
self.logerror("Error creating error file after todo read failure (" + self.filename + "): " + err);
}
});
self.emit('error', "Didn't find right amount of data in todo!"); // Note nothing picks this up yet
}
})
});
}
HMailItem.prototype.send = function () {
if (config.get('outbound.disabled')) {
// try again in 1 second if delivery is disabled
this.logdebug("delivery disabled temporarily. Retrying in 1s.");
var hmail = this;
setTimeout(function () {hmail.send()}, 1000);
return;
}
if (!this.todo) {
var self = this;
this.once('ready', function () { self._send() });
}
else {
this._send();
}
}
HMailItem.prototype._send = function () {
plugins.run_hooks('send_email', this);
}
HMailItem.prototype.send_email_respond = function (retval, delay_seconds) {
if (retval === constants.delay) {
// Try again in 'delay' seconds.
this.logdebug("Delivery of this email delayed for " + delay_seconds + " seconds");
var hmail = this;
hmail.next_cb();
temp_fail_queue.add(delay_seconds * 1000, function () { delivery_queue.push(hmail) });
}
else {
this.logdebug("Sending mail: " + this.filename);
this.get_mx();
}
}
HMailItem.prototype.get_mx = function () {
var domain = this.todo.domain;
plugins.run_hooks('get_mx', this, domain);
}
HMailItem.prototype.get_mx_respond = function (retval, mx) {
switch(retval) {
case constants.ok:
var mx_list;
if (Array.isArray(mx)) {
mx_list = mx;
}
else if (typeof mx === "object") {
mx_list = [mx];
}
else {
// assume string
var matches = /^(.*?)(:(\d+))?$/.exec(mx);
if (!matches) {
throw("get_mx returned something that doesn't match hostname or hostname:port");
}
mx_list = [{priority: 0, exchange: matches[1], port: matches[3]}];
}
this.logdebug("Got an MX from Plugin: " + this.todo.domain + " => 0 " + mx);
return this.found_mx(null, mx_list);
case constants.deny:
this.logwarn("get_mx plugin returned DENY: " + mx);
return this.bounce("No MX for " + this.domain);
case constants.denysoft:
this.logwarn("get_mx plugin returned DENYSOFT: " + mx);
return this.temp_fail("Temporary MX lookup error for " + this.domain);
}
var hmail = this;
// if none of the above return codes, drop through to this...
exports.lookup_mx(this.todo.domain, function (err, mxs) {
hmail.found_mx(err, mxs);
});
}
exports.lookup_mx = function lookup_mx (domain, cb) {
var mxs = [];
// Possible DNS errors
// NODATA
// FORMERR
// BADRESP
// NOTFOUND
// BADNAME
// TIMEOUT
// CONNREFUSED
// NOMEM
// DESTRUCTION
// NOTIMP
// EREFUSED
// SERVFAIL
// default wrap_mx just returns our object with "priority" and "exchange" keys
var wrap_mx = function (a) { return a };
var process_dns = function (err, addresses) {
if (err) {
if (err.code === 'ENODATA') {
// Most likely this is a hostname with no MX record
// Drop through and we'll get the A record instead.
return 0;
}
cb(err);
}
else if (addresses && addresses.length) {
for (var i=0,l=addresses.length; i < l; i++) {
var mx = wrap_mx(addresses[i]);
// hmail.logdebug("Got an MX from DNS: " + hmail.todo.domain + " => " + mx.priority + " " + mx.exchange);
mxs.push(mx);
}
cb(null, mxs);
}
else {
// return zero if we need to keep trying next option
return 0;
}
return 1;
};
dns.resolveMx(domain, function(err, addresses) {
if (process_dns(err, addresses)) {
return;
}
// if MX lookup failed, we lookup an A record. To do that we change
// wrap_mx() to return same thing as resolveMx() does.
wrap_mx = function (a) { return {priority:0,exchange:a} };
dns.resolve(domain, function(err, addresses) {
if (process_dns(err, addresses)) {
return;
}
var err = new Error("Found nowhere to deliver to");
err.code = 'NOMX';
cb(err);
});
});
}
HMailItem.prototype.found_mx = function (err, mxs) {
if (err) {
this.logerror("MX Lookup for " + this.todo.domain + " failed: " + err);
if (err.code === dns.NXDOMAIN || err.code === 'ENOTFOUND') {
this.bounce("No Such Domain: " + this.todo.domain);
}
else if (err.code === 'NOMX') {
this.bounce("Nowhere to deliver mail to for domain: " + this.todo.domain);
}
else {
// every other error is transient
this.temp_fail("DNS lookup failure: " + err);
}
}
else {
// got MXs
var mxlist = sort_mx(mxs);
this.mxlist = mxlist;
this.try_deliver();
}
}
// MXs must be sorted by priority order, but matched priorities must be
// randomly shuffled in that list, so this is a bit complex.
function sort_mx (mx_list) {
var sorted = mx_list.sort(function (a,b) {
return a.priority - b.priority;
});
// This isn't a very good shuffle but it'll do for now.
for (var i=0,l=sorted.length-1; i<l; i++) {
if (sorted[i].priority === sorted[i+1].priority) {
if (Math.round(Math.random())) { // 0 or 1
var j = sorted[i];
sorted[i] = sorted[i+1];
sorted[i+1] = j;
}
}
}
return sorted;
}
HMailItem.prototype.try_deliver = function () {
var self = this;
// check if there are any MXs left
if (this.mxlist.length === 0) {
return this.temp_fail("Tried all MXs");
}
var mx = this.mxlist.shift();
var host = mx.exchange;
// IP or IP:port
if (net.isIP(host)) {
self.hostlist = [ host ];
return self.try_deliver_host(mx);
}
this.loginfo("Looking up A records for: " + host);
// now we have a host, we have to lookup the addresses for that host
// and try each one in order they appear
dns.resolve(host, function (err, addresses) {
if (err) {
self.logerror("DNS lookup of " + host + " failed: " + err);
return self.try_deliver(); // try next MX
}
if (addresses.length === 0) {
// NODATA or empty host list
self.logerror("DNS lookup of " + host + " resulted in no data");
return self.try_deliver(); // try next MX
}
self.hostlist = addresses;
self.try_deliver_host(mx);
});
}
var smtp_regexp = /^([0-9]{3})([ -])(.*)/;
HMailItem.prototype.try_deliver_host = function (mx) {
if (this.hostlist.length === 0) {
return this.try_deliver(); // try next MX
}
var host = this.hostlist.shift();
var port = mx.port || 25;
var socket = sock.connect({port: port, host: host, localAddress: mx.bind});
var self = this;
var processing_mail = true;
this.loginfo("Attempting to deliver to: " + host + ":" + port + " (" + delivery_queue.length() + ") (" + temp_fail_queue.length() + ")");
socket.on('error', function (err) {
if (processing_mail) {
self.logerror("Ongoing connection failed to " + host + ":" + port + " : " + err);
processing_mail = false;
// try the next MX
self.try_deliver_host(mx);
}
});
socket.on('close', function () {
if (processing_mail) {
return self.try_deliver_host(mx);
}
});
socket.setTimeout(300 * 1000); // TODO: make this configurable
var command = 'connect';
var response = [];
var recipients = this.todo.rcpt_to.map(function (a) { return new Address (a.original) });
var mail_from = new Address (this.todo.mail_from.original);
var data_marker = 0;
var last_recip = null;
var ok_recips = 0;
var fail_recips = [];
var bounce_recips = [];
var smtp_properties = {
"tls": false,
"max_size": 0,
"eightbitmime": false,
"enh_status_codes": false,
};
socket.send_command = function (cmd, data) {
if (!this.writable) {
self.logerror("Socket writability went away");
return self.try_deliver_host(mx);
}
var line = cmd + (data ? (' ' + data) : '');
if (cmd === 'dot') {
line = '.';
}
self.logprotocol("C: " + line);
this.write(line + "\r\n");
command = cmd.toLowerCase();
response = [];
};
socket.process_ehlo_data = function () {
for (var i=0,l=response.length; i < l; i++) {
var r = response[i];
if (r.toUpperCase() === '8BITMIME') {
smtp_properties.eightbitmime = true;
}
else if (r.toUpperCase() === 'STARTTLS') {
smtp_properties.tls = true;
}
else if (r.toUpperCase() === 'ENHANCEDSTATUSCODES') {
smtp_properties.enh_status_codes = true;
}
else {
var matches;
matches = r.match(/^SIZE\s+(\d+)$/);
if (matches) {
smtp_properties.max_size = matches[1];
}
}
}
if (smtp_properties.tls && config.get('outbound.enable_tls')) {
this.on('secure', function () {
socket.send_command('EHLO', config.get('me'));
});
this.send_command('STARTTLS');
}
else {
this.send_command('MAIL', 'FROM:' + mail_from);
}
}
socket.on('timeout', function () {
self.logerror("Outbound connection timed out to " + host + ":" + port);
processing_mail = false;
socket.end();
self.try_deliver_host(mx);
});
socket.on('connect', function () {
});
socket.on('line', function (line) {
var matches;
self.logprotocol("S: " + line);
if (matches = smtp_regexp.exec(line)) {
var code = matches[1],
cont = matches[2],
rest = matches[3];
response.push(rest);
if (cont === ' ') {
if (code.match(/^4/)) {
if (/^rcpt/.test(command)) {
// this recipient was rejected
fail_recips.push(last_recip);
}
else {
var reason = response.join(' ');
socket.send_command('QUIT');
processing_mail = false;
return self.temp_fail("Upstream error: " + code + " " + reason);
}
}
else if (code.match(/^5/)) {
if (command === 'ehlo') {
// EHLO command was rejected; fall-back to HELO
return socket.send_command('HELO', config.get('me'));
}
if (/^rcpt/.test(command)) {
bounce_recips.push(last_recip);
}
else {
var reason = response.join(' ');
socket.send_command('QUIT');
processing_mail = false;
return self.bounce(reason);
}
}
switch (command) {
case 'connect':
socket.send_command('EHLO', config.get('me'));
break;
case 'ehlo':
socket.process_ehlo_data();
break;
case 'starttls':
var key = config.get('tls_key.pem', 'binary');
var cert = config.get('tls_cert.pem', 'binary');
var tls_options = { key: key, cert: cert };
smtp_properties = {};
socket.upgrade(tls_options);
break;
case 'helo':
socket.send_command('MAIL', 'FROM:' + mail_from);
break;
case 'mail':
last_recip = recipients.shift();
socket.send_command('RCPT', 'TO:' + last_recip.format());
break;
case 'rcpt':
if (last_recip && code.match(/^250/)) ok_recips++;
if (!recipients.length) {
if (fail_recips.length) {
self.refcount++;
exports.split_to_new_recipients(self, fail_recips, "Some recipients temporarily failed", function (hmail) {
self.discard();
hmail.temp_fail("Some recipients temp failed: " + fail_recips.join(', '));
});
}
if (bounce_recips.length) {
self.refcount++;
exports.split_to_new_recipients(self, bounce_recips, "Some recipients rejected", function (hmail) {
self.discard();
hmail.bounce("Some recipients failed: " + bounce_recips.join(', '));
});
}
if (ok_recips) {
socket.send_command('DATA');
}
else {
processing_mail = false;
socket.send_command('QUIT');
self.discard();
}
}
else {
last_recip = recipients.shift();
socket.send_command('RCPT', 'TO:' + last_recip.format());
}
break;
case 'data':
var data_stream = self.data_stream();
data_stream.on('data', function (data) {
self.logdata("C: " + data);
});
data_stream.on('error', function (err) {
self.logerror("Reading from the data stream failed: " + err);
});
data_stream.on('end', function () {
socket.send_command('dot');
});
data_stream.pipe(socket, {end: false});
break;
case 'dot':
processing_mail = false;
var reason = response.join(' ');
socket.send_command('QUIT');
self.delivered(host, mx.exchange, reason);
break;
case 'quit':
socket.end();
break;
default:
// should never get here - means we did something
// wrong.
throw new Error("Unknown command: " + command);
}
}
}
else {
// Unrecognised response.
self.logerror("Unrecognised response from upstream server: " + line);
processing_mail = false;
socket.end();
return self.bounce("Unrecognised response from upstream server: " + line);
}
});
}
function populate_bounce_message (from, to, reason, hmail, cb) {
var values = {
date: new Date().toString(),
me: config.get('me'),
from: from,
to: to,
reason: reason,
pid: process.pid,
msgid: '<' + utils.uuid() + '@' + config.get('me') + '>',
};
var bounce_msg_ = config.get('outbound.bounce_message', 'data');
var bounce_msg = bounce_msg_.map(function (item) {
return item.replace(/\{(\w+)\}/g, function (i, word) { return values[word] || '?' }) + '\n';
});
var data_stream = hmail.data_stream();
data_stream.on('data', function (data) {
bounce_msg.push(data.toString());
});
data_stream.on('end', function () {
cb(null, bounce_msg);
});
data_stream.on('error', function (err) {
cb(err);
})
}
HMailItem.prototype.bounce = function (err, extra) {
this.loginfo("bouncing mail: " + err);
if (!this.todo) {
// haven't finished reading the todo, delay here...
var self = this;
self.once('ready', function () { self._bounce(err, extra) });
return;
}
this._bounce(err, extra);
}
HMailItem.prototype._bounce = function (err, extra) {
this.bounce_error = err;
if (extra) {
this.bounce_extra = extra;
}
plugins.run_hooks("bounce", this, err);
}
HMailItem.prototype.bounce_respond = function (retval, msg) {
if (retval != constants.cont) {
this.loginfo("plugin responded with: " + retval + ". Not sending bounce.");
if (retval === constants.stop) {
this.discard(); // calls next_cb
}
else {
return this.next_cb();
}
}
var self = this;
var err = this.bounce_error;
if (!this.todo.mail_from.user) {
// double bounce - mail was already a bounce
return this.double_bounce("Mail was already a bounce");
}
var from = new Address ('<>');
var recip = new Address (this.todo.mail_from.user, this.todo.mail_from.host);
populate_bounce_message(from, recip, err, this, function (err, data_lines) {
if (err) {
return self.double_bounce("Error populating bounce message: " + err);
}
exports.send_email(from, recip, data_lines.join(''), function (code, msg) {
if (code === DENY) {
// failed to even queue the mail
return self.double_bounce("Unable to queue the bounce message. Not sending bounce!");
}
self.discard();
});
});
}
HMailItem.prototype.double_bounce = function (err) {
this.logerror("Double bounce: " + err);
fs.unlink(this.path, function () {});
this.next_cb();
// TODO: fill this in... ?
// One strategy is perhaps log to an mbox file. What do other servers do?
// Another strategy might be delivery "plugins" to cope with this.
}
HMailItem.prototype.delivered = function (ip, host, response) {
var delay = (Date.now() - this.todo.queue_time)/1000;
this.lognotice("delivered file=" + this.filename +
' domain="' + this.todo.domain + '"' +
' host="' + host + '"' +
' ip=' + ip +
' response="' + response + '"' +
' delay=' + delay +
' fails=' + this.num_failures);
plugins.run_hooks("delivered", this, [host, ip, response, delay]);
}
HMailItem.prototype.discard = function () {
this.refcount--;
if (this.refcount === 0) {
// Remove the file.
fs.unlink(this.path, function () {});
this.next_cb();
}
}
HMailItem.prototype.temp_fail = function (err, extra) {
this.num_failures++;
// Test for max failures which is configurable.
if (this.num_failures >= (config.get('outbound.maxTempFailures') || 13)) {
return this.bounce("Too many failures (" + err + ")", extra);
}
// basic strategy is we exponentially grow the delay to the power
// two each time, starting at 2 ** 6 seconds
// Note: More advanced options should be explored in the future as the
// last delay is 2**17 secs (1.5 days), which is a bit long... Exim has a max delay of
// 6 hours (configurable) and the expire time is also configurable... But
// this is good enough for now.
var delay = (Math.pow(2, (this.num_failures + 5)) * 1000);
var until = Date.now() + delay;
this.loginfo("Temp failing " + this.filename + " for " + (delay/1000) + " seconds: " + err);
var new_filename = this.filename.replace(/^(\d+)_(\d+)_/, until + '_' + this.num_failures + '_');
var hmail = this;
fs.rename(this.path, path.join(queue_dir, new_filename), function (err) {
if (err) {
return hmail.bounce("Error re-queueing email", err);
}
hmail.path = path.join(queue_dir, new_filename);
hmail.filename = new_filename;
hmail.next_cb();
temp_fail_queue.add(delay, function () { delivery_queue.push(hmail) });
});
}
// The following handler has an impact on outgoing mail. It does remove the queue file.
HMailItem.prototype.delivered_respond = function (retval, msg) {
if (retval != constants.cont && retval != constants.ok) {
this.logwarn("delivered plugin responded with: " + retval + " msg=" + msg + ".");
}
this.discard();
};
|
define(function(require) {
function fatalError(err) {
var container = document.getElementById('container');
container.classList.add('error');
var elm = splash.querySelector('.contents');
html = [
"<h1>Fatal Error!</h1>",
"<p>",
err.filename || err.fileName,
" (",
err.lineno || err.lineNumber,
"):",
"</p>",
"<p>",
err.message,
"</p>",
"<p>Press F5 to attempt a rejoin</p>",
].join("\n");
elm.innerHTML = html;
exitPointerLock();
fatalError.fatalErrorTriggered = true;
function exitPointerLock() {
(document.exitPointerLock ||
document.mozExitPointerLock ||
document.webkitExitPointerLock).call(document);
}
}
fatalError.fatalErrorTriggered = false;
return fatalError;
}); |
'use strict';
var Sequelize = require('sequelize');
var orm = new Sequelize('test', 'root', 'victor');
var WorkerThread = orm.define('WorkerThread', {
name: Sequelize.STRING,
coreAffinity: Sequelize.BOOLEAN,
options: Sequelize.STRING
});
WorkerThread.sync();
exports.WorkerThread = WorkerThread; |
angular.module('polliwogApp')
.controller('SpeakerCtrl', function ($scope, $state, socket, lodash, $stateParams, Lecture) {
'use strict';
$scope.lectures = Lecture.query();
$scope.showCreateSessionDialog = function () {};
socket.socket.on('lecture:save', function (lecture) {
var index = lodash.findIndex($scope.lectures, {_id: lecture._id});
if(index < 0){
$scope.lectures.push(lecture);
} else {
$scope.lectures[index] = lecture;
}
});
});
|
import Component from '@ember/component';
import { computed } from '@ember/object';
import ParentComponentSupport from 'ember-composability/mixins/parent-component-support';
import layout from '../templates/components/mdl-menu';
export default Component.extend(ParentComponentSupport, {
layout,
_primaryClassNameString: 'mdl-menu',
icon: 'more_vert',
didInsertElement() {
this._super(...arguments);
let mdlmenu = new window.MaterialMenu(this.$('ul')[0]);
this.set('_mdlComponent', mdlmenu);
},
_buttonId: computed('elementId', {
get() {
return `${this.get('elementId')}-button`;
}
}),
align: 'top-left',
_alignClass: computed('align', {
get() {
return `mdl-menu--${this.get('align')}`;
}
})
});
|
export { default } from './getImageRender';
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require foundation
//= require turbolinks
//= require slick/slick
//= require_tree .
function initialize(noteWidget) {
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// MAP STUFFFFFFFFF ============================
function placeInMarkers(inNotes, imageUrls, noteUsernames) {
for (var i = 0; i < inNotes.length; i++) {
current_marker = setExistingMarker(inNotes[i], inIcon); //global icon
// addInfoWindow(current_marker, inNotes[i], imageUrls[i], noteUsernames[i]);
}
}
function setExistingMarker(note, icon) {
return new google.maps.Marker({
position: new google.maps.LatLng(note.longitude, note.latitude),
icon: icon, //extract into a model att?
animation: google.maps.Animation.DROP, //extract into a model attr
map: map //global map object
});
}
function placeOutMarkers(outNotes) {
for (var j = 0; j < outNotes.length; j++) {
setExistingMarker(outNotes[j], outIcon); //global icon
}
}
// function addInfoWindow(marker, note, imageUrl, username) {
// var info = infoWindowTemplate(note.comment, imageUrl, username);
// // var infoWindow = newInfoWindow(info);
// // google.maps.event.addListener(marker, 'click', function () {
// // infoWindow.open(map, marker); //global map object
// // });
// var buttonSelector = "#"+ note.id;
// if ($(buttonSelector).length > 0) {
// $(buttonSelector).on("click", function(){
// note = $(this).parent()[0];
// $('#currentNote').empty();
// $(note).clone().appendTo('#currentNote').show();
// });
// }
// };
// function newInfoWindow(info) {
// return new google.maps.InfoWindow({
// content: info
// });
// }
// function infoWindowTemplate(comment, imageUrl, username) {
// if(imageUrl === "/images/original/missing.png") {
// return "<h5>"+ username +"</h6>" + comment + "</h5>";
// } else {
// return "<h5>"+ username +"</h6>" + comment + "<br><img src=" + imageUrl + "></h5>";
// }
// }
// take this comment out after
function setUserMarker(pos) {
return new google.maps.Marker({
position: pos,
animation: google.maps.Animation.DROP,
map: map //global map object
});
}
function setCircleRadius(pos) {
return new google.maps.Circle({
center: pos,
radius: 9,
fillColor: "#00EEEE",
fillOpacity: 0.5,
strokeOpacity: 0.0,
strokeWeight: 0,
map: map //global map object
});
}
// GEO NAV PARTY ==============
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var currentLocation = setUserMarker(pos);
var circle = setCircleRadius(pos);
var longitudeMax = currentLocation.position.k + 0.000090;
var longitudeMin = currentLocation.position.k - 0.000090;
var latitudeMax = currentLocation.position.B + 0.000090;
var latitudeMin = currentLocation.position.B - 0.000090;
$.ajax({
url: '/notes/1',
type: 'get',
data: {longitudeMax: longitudeMax, longitudeMin: longitudeMin, latitudeMax: latitudeMax, latitudeMin: latitudeMin },
})
.success(function(data) {
console.log("success");
noteWidget.addReadableNotes(data[0], data[1], data[2], data[5]);
placeInMarkers(data[0], data[1], data[2]);
placeOutMarkers(data[3]);
})
.fail(function() {
console.log("error");
});
$("#leaveANote").on('click', function() { //controller binding event
$("#myModalNote").foundation('reveal', 'open'); //view thingy
$('#noteSubmit').click(function() { // controller binding event
$("#noteForm").ajaxForm({
success: setNewMarker
}).submit(function(){
});
});
function updateNoteLocation(note, marker) {
var userLongitude = marker.position.k;
var userLatitude = marker.position.B;
$.ajax({
url: "/notes/" + note[0].id,
type: 'PUT',
data: {longitude: userLongitude, latitude: userLatitude}
})
.success(function(data) {
$("#noteForm")[0].reset();
$("#myModalNote").foundation('reveal', 'close');
noteWidget.addReadableNotes([note[0]], [note[1]], [note[2]], data.id);
// addInfoWindow(marker, note[0], note[1], note[2]);
$("#noCommentError").text("");
console.log("success");
})
.fail(function() {
console.log("error");
$("#noCommentError").text("Note field can't be empty.");
}); //end ajax request
} //end updateNoteLocation function
var setNewMarker = function(note) {
var noteMarker = new google.maps.Marker({
position: pos,
icon: inIcon,
animation: google.maps.Animation.DROP,
map: map
});
updateNoteLocation(note, noteMarker);
}; //end createNewMarker
}); // leave note on click function
map.setCenter(pos);
}, function() { // end get current position
handleNoGeolocation(true);
});
} else { //end of if nav geo
handleNoGeolocation(false);
} //end else
} // end initalize function
|
import React, {Component, PropTypes} from 'react'
import { Link } from 'react-router'
import CSSModules from 'react-css-modules'
import styles from './post_excerpt.scss'
import { browserHistory } from 'react-router'
import {TweenMax, Power4} from 'gsap'
@CSSModules(styles, {allowMultiple: true})
class PostExcerpt extends Component {
componentDidMount() {
const excerpt = this._excerpt
const { index } = this.props
TweenMax.fromTo(excerpt, 1, {
opacity: 0,
x: 20
}, {
opacity: 1,
x: 0,
ease: Power4.easeOut,
delay: index * 0.1
})
}
_handleClick(e) {
e.preventDefault()
const target = e.currentTarget.href
const posts = document.getElementsByClassName(styles.base)
TweenMax.staggerTo(posts, 0.5, {
opacity: 0,
x: -20,
ease: Power4.easeOut
}, -0.1)
window.setTimeout( ()=> {
browserHistory.push(target)
}, 500)
}
_renderExcerpt() {
const { post_excerpt } = this.props.post
return {
__html: post_excerpt
}
}
render() {
const { post_title: title, post_name: name, thumbnail } = this.props.post
const bg = {
backgroundImage: `url('${thumbnail}')`
}
return (
<div ref={(c) => this._excerpt = c}>
<Link to={'post/' + encodeURIComponent(name)} styleName="base" onClick={this._handleClick.bind(this)}>
<div styleName="info">
<h2 styleName="title">{title}</h2>
<p styleName="text" dangerouslySetInnerHTML = {this._renderExcerpt()}/>
</div>
<div styleName="thumbnail" style={bg}>
</div>
</Link>
</div>
)
}
}
PostExcerpt.propTypes = {
index: PropTypes.number,
styles: PropTypes.object,
post: PropTypes.object,
settings: PropTypes.object
}
export default PostExcerpt
|
import Device from '../../../utils/device';
export default function () {
const swiper = this;
const {
classNames, params, rtl, $el,
} = swiper;
const suffixes = [];
suffixes.push('initialized');
suffixes.push(params.direction);
if (params.freeMode) {
suffixes.push('free-mode');
}
if (params.autoHeight) {
suffixes.push('autoheight');
}
if (rtl) {
suffixes.push('rtl');
}
if (params.slidesPerColumn > 1) {
suffixes.push('multirow');
if (params.slidesPerColumnFill === 'column') {
suffixes.push('multirow-column');
}
}
if (Device.android) {
suffixes.push('android');
}
if (Device.ios) {
suffixes.push('ios');
}
if (params.cssMode) {
suffixes.push('css-mode');
}
suffixes.forEach((suffix) => {
classNames.push(params.containerModifierClass + suffix);
});
$el.addClass(classNames.join(' '));
}
|
// Last commit: 49acd4b (2013-07-05 09:03:40 -0400)
(function() {
var get = Ember.get, set = Ember.set;
function samePosition(a, b) {
return a && b && a.x === b.x && a.y === b.y;
}
function positionElement() {
var element, position, _position;
Ember.instrument('view.updateContext.positionElement', this, function() {
element = get(this, 'element');
position = get(this, 'position');
_position = this._position;
if (!position || !element) { return; }
// TODO: avoid needing this by avoiding unnecessary
// calls to this method in the first place
if (samePosition(position, _position)) { return; }
this._parentView.applyTransform(element, position);
this._position = position;
}, this);
}
Ember.ListItemViewMixin = Ember.Mixin.create({
init: function(){
this._super();
this.one('didInsertElement', positionElement);
},
classNames: ['ember-list-item-view'],
_position: null,
_positionDidChange: Ember.observer(positionElement, 'position'),
_positionElement: positionElement
});
})();
(function() {
var get = Ember.get, set = Ember.set;
var backportedInnerString = function(buffer) {
var content = [], childBuffers = buffer.childBuffers;
Ember.ArrayPolyfills.forEach.call(childBuffers, function(buffer) {
var stringy = typeof buffer === 'string';
if (stringy) {
content.push(buffer);
} else {
buffer.array(content);
}
});
return content.join('');
};
function willInsertElementIfNeeded(view) {
if (view.willInsertElement) {
view.willInsertElement();
}
}
function didInsertElementIfNeeded(view) {
if (view.didInsertElement) {
view.didInsertElement();
}
}
function rerender() {
var element, buffer, context, hasChildViews;
element = get(this, 'element');
if (!element) { return; }
context = get(this, 'context');
// releases action helpers in contents
// this means though that the ListViewItem itself can't use classBindings or attributeBindings
// need support for rerender contents in ember
this.triggerRecursively('willClearRender');
if (this.lengthAfterRender > this.lengthBeforeRender) {
this.clearRenderedChildren();
this._childViews.length = this.lengthBeforeRender; // triage bug in ember
}
if (context) {
buffer = Ember.RenderBuffer();
buffer = this.renderToBuffer(buffer);
// check again for childViews, since rendering may have added some
hasChildViews = this._childViews.length > 0;
if (hasChildViews) {
this.invokeRecursively(willInsertElementIfNeeded, false);
}
element.innerHTML = buffer.innerString ? buffer.innerString() : backportedInnerString(buffer);
set(this, 'element', element);
this.transitionTo('inDOM');
if (hasChildViews) {
this.invokeRecursively(didInsertElementIfNeeded, false);
}
} else {
element.innerHTML = ''; // when there is no context, this view should be completely empty
}
}
/**
The `Ember.ListViewItem` view class renders a
[div](https://developer.mozilla.org/en/HTML/Element/div) HTML element
with `ember-list-item-view` class. It allows you to specify a custom item
handlebars template for `Ember.ListView`.
Example:
```handlebars
<script type="text/x-handlebars" data-template-name="row_item">
{{name}}
</script>
```
```javascript
App.ListView = Ember.ListView.extend({
height: 500,
rowHeight: 20,
itemViewClass: Ember.ListItemView.extend({templateName: "row_item"})
});
```
@extends Ember.View
@class ListItemView
@namespace Ember
*/
Ember.ListItemView = Ember.View.extend(Ember.ListItemViewMixin, {
updateContext: function(newContext){
var context = get(this, 'context');
Ember.instrument('view.updateContext.render', this, function() {
if (context !== newContext) {
this.set('context', newContext);
if (newContext instanceof Ember.ObjectController) {
this.set('controller', newContext);
}
}
}, this);
},
rerender: function () { Ember.run.scheduleOnce('render', this, rerender); },
_contextDidChange: Ember.observer(rerender, 'context', 'controller')
});
})();
(function() {
var get = Ember.get, set = Ember.set;
Ember.ReusableListItemView = Ember.View.extend(Ember.ListItemViewMixin, {
init: function(){
this._super();
this.set('context', Ember.ObjectProxy.create());
},
isVisible: Ember.computed('context.content', function(){
return !!this.get('context.content');
}),
updateContext: function(newContext){
var context = get(this, 'context.content');
if (context !== newContext) {
if (this.state === 'inDOM') {
this.prepareForReuse(newContext);
}
set(this, 'context.content', newContext);
}
},
prepareForReuse: Ember.K
});
})();
(function() {
Ember.ListViewHelper = {
applyTransform: (function(){
var element = document.createElement('div');
if ('webkitTransform' in element.style){
return function(element, position){
var x = position.x,
y = position.y;
element.style.webkitTransform = 'translate3d(' + x + 'px, ' + y + 'px, 0)';
};
}else{
return function(element, position){
var x = position.x,
y = position.y;
element.style.top = y + 'px';
element.style.left = x + 'px';
};
}
})()
};
})();
(function() {
var get = Ember.get, set = Ember.set,
min = Math.min, max = Math.max, floor = Math.floor,
ceil = Math.ceil,
forEach = Ember.ArrayPolyfills.forEach;
function addContentArrayObserver() {
var content = get(this, 'content');
if (content) {
content.addArrayObserver(this);
}
}
function removeAndDestroy(object){
this.removeObject(object);
object.destroy();
}
function syncChildViews(){
Ember.run.once(this, '_syncChildViews');
}
function sortByContentIndex (viewOne, viewTwo){
return get(viewOne, 'contentIndex') - get(viewTwo, 'contentIndex');
}
function detectListItemViews(childView) {
return Ember.ListItemViewMixin.detect(childView);
}
function notifyMutationListeners() {
if (Ember.View.notifyMutationListeners) {
Ember.run.once(Ember.View, 'notifyMutationListeners');
}
}
var domManager = Ember.create(Ember.ContainerView.proto().domManager);
domManager.prepend = function(view, html) {
view.$('.ember-list-container').prepend(html);
notifyMutationListeners();
};
function syncListContainerWidth(){
var elementWidth, columnCount, containerWidth, element;
elementWidth = get(this, 'elementWidth');
columnCount = get(this, 'columnCount');
containerWidth = elementWidth * columnCount;
element = this.$('.ember-list-container');
if (containerWidth && element) {
element.css('width', containerWidth);
}
}
function enableProfilingOutput() {
function before(name, time, payload) {
console.time(name);
}
function after (name, time, payload) {
console.timeEnd(name);
}
if (Ember.ENABLE_PROFILING) {
Ember.subscribe('view._scrollContentTo', {
before: before,
after: after
});
Ember.subscribe('view.updateContext', {
before: before,
after: after
});
}
}
/**
@class Ember.ListViewMixin
@namespace Ember
*/
Ember.ListViewMixin = Ember.Mixin.create({
itemViewClass: Ember.ListItemView,
classNames: ['ember-list-view'],
attributeBindings: ['style'],
domManager: domManager,
scrollTop: 0,
bottomPadding: 0,
_lastEndingIndex: 0,
paddingCount: 1,
/**
@private
Setup a mixin.
- adding observer to content array
- creating child views based on height and length of the content array
@method init
*/
init: function() {
this._super();
enableProfilingOutput();
addContentArrayObserver.call(this);
this._syncChildViews();
this.columnCountDidChange();
this.on('didInsertElement', syncListContainerWidth);
},
/**
Called on your view when it should push strings of HTML into a
`Ember.RenderBuffer`.
Adds a [div](https://developer.mozilla.org/en-US/docs/HTML/Element/div)
with a required `ember-list-container` class.
@method render
@param {Ember.RenderBuffer} buffer The render buffer
*/
render: function(buffer) {
buffer.push('<div class="ember-list-container">');
this._super(buffer);
buffer.push('</div>');
},
willInsertElement: function() {
if (!this.get("height") || !this.get("rowHeight")) {
throw "A ListView must be created with a height and a rowHeight.";
}
this._super();
},
/**
@private
Sets inline styles of the view:
- height
- width
- position
- overflow
- -webkit-overflow
- overflow-scrolling
Called while attributes binding.
@property {Ember.ComputedProperty} style
*/
style: Ember.computed('height', 'width', function() {
var height, width, style, css;
height = get(this, 'height');
width = get(this, 'width');
css = get(this, 'css');
style = '';
if (height) { style += 'height:' + height + 'px;'; }
if (width) { style += 'width:' + width + 'px;'; }
for ( var rule in css ){
if (css.hasOwnProperty(rule)) {
style += rule + ':' + css[rule] + ';';
}
}
return style;
}),
/**
@private
Performs visual scrolling. Is overridden in Ember.ListView.
@method scrollTo
*/
scrollTo: function(y) {
throw 'must override to perform the visual scroll and effectively delegate to _scrollContentTo';
},
/**
@private
Internal method used to force scroll position
@method scrollTo
*/
_scrollTo: Ember.K,
/**
@private
@method _scrollContentTo
*/
_scrollContentTo: function(y) {
var startingIndex, endingIndex,
contentIndex, visibleEndingIndex, maxContentIndex,
contentIndexEnd, contentLength, scrollTop;
scrollTop = max(0, y);
Ember.instrument('view._scrollContentTo', {
scrollTop: scrollTop,
content: get(this, 'content'),
startingIndex: this._startingIndex(),
endingIndex: min(max(get(this, 'content.length') - 1, 0), this._startingIndex() + this._numChildViewsForViewport())
}, function () {
contentLength = get(this, 'content.length');
set(this, 'scrollTop', scrollTop);
maxContentIndex = max(contentLength - 1, 0);
startingIndex = this._startingIndex();
visibleEndingIndex = startingIndex + this._numChildViewsForViewport();
endingIndex = min(maxContentIndex, visibleEndingIndex);
this.trigger('scrollYChanged', y);
if (startingIndex === this._lastStartingIndex &&
endingIndex === this._lastEndingIndex) {
return;
}
this._reuseChildren();
this._lastStartingIndex = startingIndex;
this._lastEndingIndex = endingIndex;
}, this);
},
/**
@private
Computes the height for a `Ember.ListView` scrollable container div.
You must specify `rowHeight` parameter for the height to be computed properly.
@property {Ember.ComputedProperty} totalHeight
*/
totalHeight: Ember.computed('content.length', 'rowHeight', 'columnCount', 'bottomPadding', function() {
var contentLength, rowHeight, columnCount, bottomPadding;
contentLength = get(this, 'content.length');
rowHeight = get(this, 'rowHeight');
columnCount = get(this, 'columnCount');
bottomPadding = get(this, 'bottomPadding');
return ((ceil(contentLength / columnCount)) * rowHeight) + bottomPadding;
}),
/**
@private
@method _prepareChildForReuse
*/
_prepareChildForReuse: function(childView) {
childView.prepareForReuse();
},
/**
@private
@method _reuseChildForContentIndex
*/
_reuseChildForContentIndex: function(childView, contentIndex) {
var content, context, newContext, childsCurrentContentIndex, position, enableProfiling;
content = get(this, 'content');
enableProfiling = get(this, 'enableProfiling');
position = this.positionForIndex(contentIndex);
set(childView, 'position', position);
set(childView, 'contentIndex', contentIndex);
if (enableProfiling) {
Ember.instrument('view._reuseChildForContentIndex', position, function(){}, this);
}
newContext = content.objectAt(contentIndex);
childView.updateContext(newContext);
},
/**
@private
@method positionForIndex
*/
positionForIndex: function(index){
var elementWidth, width, columnCount, rowHeight, y, x;
elementWidth = get(this, 'elementWidth') || 1;
width = get(this, 'width') || 1;
columnCount = get(this, 'columnCount');
rowHeight = get(this, 'rowHeight');
y = (rowHeight * floor(index/columnCount));
x = (index % columnCount) * elementWidth;
return {
y: y,
x: x
};
},
/**
@private
@method _childViewCount
*/
_childViewCount: function() {
var contentLength, childViewCountForHeight;
contentLength = get(this, 'content.length');
childViewCountForHeight = this._numChildViewsForViewport();
return min(contentLength, childViewCountForHeight);
},
/**
@private
Returns a number of columns in the Ember.ListView (for grid layout).
If you want to have a multi column layout, you need to specify both
`width` and `elementWidth`.
If no `elementWidth` is specified, it returns `1`. Otherwise, it will
try to fit as many columns as possible for a given `width`.
@property {Ember.ComputedProperty} columnCount
*/
columnCount: Ember.computed('width', 'elementWidth', function() {
var elementWidth, width, count;
elementWidth = get(this, 'elementWidth');
width = get(this, 'width');
if (elementWidth) {
count = floor(width / elementWidth);
} else {
count = 1;
}
return count;
}),
/**
@private
Fires every time column count is changed.
@event columnCountDidChange
*/
columnCountDidChange: Ember.observer(function(){
var ratio, currentScrollTop, proposedScrollTop, maxScrollTop,
scrollTop, lastColumnCount, newColumnCount, element;
lastColumnCount = this._lastColumnCount;
currentScrollTop = get(this, 'scrollTop');
newColumnCount = get(this, 'columnCount');
maxScrollTop = get(this, 'maxScrollTop');
element = get(this, 'element');
this._lastColumnCount = newColumnCount;
if (lastColumnCount) {
ratio = (lastColumnCount / newColumnCount);
proposedScrollTop = currentScrollTop * ratio;
scrollTop = min(maxScrollTop, proposedScrollTop);
this._scrollTo(scrollTop);
set(this, 'scrollTop', scrollTop);
}
if (arguments.length > 0) {
// invoked by observer
Ember.run.schedule('afterRender', this, syncListContainerWidth);
}
}, 'columnCount'),
/**
@private
Computes max possible scrollTop value given the visible viewport
and scrollable container div height.
@property {Ember.ComputedProperty} maxScrollTop
*/
maxScrollTop: Ember.computed('height', 'totalHeight', function(){
var totalHeight, viewportHeight;
totalHeight = get(this, 'totalHeight'),
viewportHeight = get(this, 'height');
return max(0, totalHeight - viewportHeight);
}),
/**
@private
Computes the number of views that would fit in the viewport area.
You must specify `height` and `rowHeight` parameters for the number of
views to be computed properly.
@method _numChildViewsForViewport
*/
_numChildViewsForViewport: function() {
var height, rowHeight, paddingCount, columnCount;
height = get(this, 'height');
rowHeight = get(this, 'rowHeight');
paddingCount = get(this, 'paddingCount');
columnCount = get(this, 'columnCount');
return (ceil(height / rowHeight) * columnCount) + (paddingCount * columnCount);
},
/**
@private
Computes the starting index of the item views array.
Takes `scrollTop` property of the element into account.
Is used in `_syncChildViews`.
@method _startingIndex
*/
_startingIndex: function() {
var scrollTop, rowHeight, columnCount, calculatedStartingIndex,
contentLength, largestStartingIndex;
contentLength = get(this, 'content.length');
scrollTop = get(this, 'scrollTop');
rowHeight = get(this, 'rowHeight');
columnCount = get(this, 'columnCount');
calculatedStartingIndex = floor(scrollTop / rowHeight) * columnCount;
largestStartingIndex = max(contentLength - 1, 0);
return min(calculatedStartingIndex, largestStartingIndex);
},
/**
@private
@event contentWillChange
*/
contentWillChange: Ember.beforeObserver(function() {
var content;
content = get(this, 'content');
if (content) {
content.removeArrayObserver(this);
}
}, 'content'),
/**
@private
@event contentDidChange
*/
contentDidChange: Ember.observer(function() {
addContentArrayObserver.call(this);
syncChildViews.call(this);
}, 'content'),
/**
@private
@property {Function} needsSyncChildViews
*/
needsSyncChildViews: Ember.observer(syncChildViews, 'height', 'width', 'columnCount'),
/**
@private
Returns a new item view. Takes `contentIndex` to set the context
of the returned view properly.
@param {Number} contentIndex item index in the content array
@method _addItemView
*/
_addItemView: function(contentIndex){
var itemViewClass, childView;
itemViewClass = get(this, 'itemViewClass');
childView = this.createChildView(itemViewClass);
this.pushObject(childView);
},
/**
@private
Intelligently manages the number of childviews.
@method _syncChildViews
**/
_syncChildViews: function(){
var itemViewClass, startingIndex, childViewCount,
endingIndex, numberOfChildViews, numberOfChildViewsNeeded,
childViews, count, delta, index, childViewsLength, contentIndex;
if (get(this, 'isDestroyed') || get(this, 'isDestroying')) {
return;
}
childViewCount = this._childViewCount();
childViews = this.positionOrderedChildViews();
startingIndex = this._startingIndex();
endingIndex = startingIndex + childViewCount;
numberOfChildViewsNeeded = childViewCount;
numberOfChildViews = childViews.length;
delta = numberOfChildViewsNeeded - numberOfChildViews;
if (delta === 0) {
// no change
} else if (delta > 0) {
// more views are needed
contentIndex = this._lastEndingIndex;
for (count = 0; count < delta; count++, contentIndex++) {
this._addItemView(contentIndex);
}
} else {
// less views are needed
forEach.call(
childViews.splice(numberOfChildViewsNeeded, numberOfChildViews),
removeAndDestroy,
this
);
}
this._scrollContentTo(get(this, 'scrollTop'));
// if _scrollContentTo short-circuits, we still need
// to call _reuseChildren to get new views positioned
// and rendered correctly
this._reuseChildren();
this._lastStartingIndex = startingIndex;
this._lastEndingIndex = this._lastEndingIndex + delta;
},
/**
@private
@method _reuseChildren
*/
_reuseChildren: function(){
var contentLength, childViews, childViewsLength,
startingIndex, endingIndex, childView, attrs,
contentIndex, visibleEndingIndex, maxContentIndex,
contentIndexEnd, scrollTop;
scrollTop = get(this, 'scrollTop');
contentLength = get(this, 'content.length');
maxContentIndex = max(contentLength - 1, 0);
childViews = get(this, 'listItemViews');
childViewsLength = childViews.length;
startingIndex = this._startingIndex();
visibleEndingIndex = startingIndex + this._numChildViewsForViewport();
endingIndex = min(maxContentIndex, visibleEndingIndex);
this.trigger('scrollContentTo', scrollTop);
contentIndexEnd = min(visibleEndingIndex, startingIndex + childViewsLength);
for (contentIndex = startingIndex; contentIndex < contentIndexEnd; contentIndex++) {
childView = childViews[contentIndex % childViewsLength];
this._reuseChildForContentIndex(childView, contentIndex);
}
},
/**
@private
Returns an array of current ListItemView views in the visible area
when you start to scroll.
@property {Ember.ComputedProperty} listItemViews
*/
listItemViews: Ember.computed('[]', function(){
return this.filter(detectListItemViews);
}),
/**
@private
@method positionOrderedChildViews
*/
positionOrderedChildViews: function() {
return get(this, 'listItemViews').sort(sortByContentIndex);
},
arrayWillChange: Ember.K,
/**
@private
@event arrayDidChange
*/
// TODO: refactor
arrayDidChange: function(content, start, removedCount, addedCount) {
var index, contentIndex;
if (this.state === 'inDOM') {
// ignore if all changes are out of the visible change
if( start >= this._lastStartingIndex || start < this._lastEndingIndex) {
index = 0;
// ignore all changes not in the visible range
// this can re-position many, rather then causing a cascade of re-renders
forEach.call(
this.positionOrderedChildViews(),
function(childView) {
contentIndex = this._lastStartingIndex + index;
this._reuseChildForContentIndex(childView, contentIndex);
index++;
},
this
);
}
syncChildViews.call(this);
}
}
});
})();
(function() {
var get = Ember.get, set = Ember.set;
/**
The `Ember.ListView` view class renders a
[div](https://developer.mozilla.org/en/HTML/Element/div) HTML element,
with `ember-list-view` class.
The context of each item element within the `Ember.ListView` are populated
from the objects in the `Element.ListView`'s `content` property.
### `content` as an Array of Objects
The simplest version of an `Ember.ListView` takes an array of object as its
`content` property. The object will be used as the `context` each item element
inside the rendered `div`.
Example:
```javascript
App.contributors = [{ name: 'Stefan Penner' }, { name: 'Alex Navasardyan' }, { name: 'Rey Cohen'}];
```
```handlebars
{{#collection Ember.ListView contentBinding="App.contributors" height=500 rowHeight=50}}
{{name}}
{{/collection}}
```
Would result in the following HTML:
```html
<div id="ember181" class="ember-view ember-list-view" style="height:500px;width:500px;position:relative;overflow:scroll;-webkit-overflow-scrolling:touch;overflow-scrolling:touch;">
<div class="ember-list-container">
<div id="ember186" class="ember-view ember-list-item-view" style="-webkit-transform: translate3d(0px, 0px, 0);">
<script id="metamorph-0-start" type="text/x-placeholder"></script>Stefan Penner<script id="metamorph-0-end" type="text/x-placeholder"></script>
</div>
<div id="ember187" class="ember-view ember-list-item-view" style="-webkit-transform: translate3d(0px, 50px, 0);">
<script id="metamorph-1-start" type="text/x-placeholder"></script>Alex Navasardyan<script id="metamorph-1-end" type="text/x-placeholder"></script>
</div>
<div id="ember188" class="ember-view ember-list-item-view" style="-webkit-transform: translate3d(0px, 100px, 0);">
<script id="metamorph-2-start" type="text/x-placeholder"></script>Rey Cohen<script id="metamorph-2-end" type="text/x-placeholder"></script>
</div>
<div id="ember189" class="ember-view ember-list-scrolling-view" style="height: 150px"></div>
</div>
</div>
```
By default `Ember.ListView` provides support for `height`,
`rowHeight`, `width`, `elementWidth`, `scrollTop` parameters.
Note, that `height` and `rowHeight` are required parameters.
```handlebars
{{#collection Ember.ListView contentBinding="App.contributors" height=500 rowHeight=50}}
{{name}}
{{/collection}}
```
If you would like to have multiple columns in your view layout, you can
set `width` and `elementWidth` parameters respectively.
```handlebars
{{#collection Ember.ListView contentBinding="App.contributors" height=500 rowHeight=50 width=500 elementWidth=80}}
{{name}}
{{/collection}}
```
### extending `Ember.ListView`
Example:
```handlebars
{{view App.ListView contentBinding="content"}}
<script type="text/x-handlebars" data-template-name="row_item">
{{name}}
</script>
```
```javascript
App.ListView = Ember.ListView.extend({
height: 500,
width: 500,
elementWidth: 80,
rowHeight: 20,
itemViewClass: Ember.ListItemView.extend({templateName: "row_item"})
});
```
@extends Ember.ContainerView
@class ListView
@namespace Ember
*/
Ember.ListView = Ember.ContainerView.extend(Ember.ListViewMixin, {
css: {
position: 'relative',
overflow: 'scroll',
'-webkit-overflow-scrolling': 'touch',
'overflow-scrolling': 'touch'
},
applyTransform: function(element, position){
var x = position.x,
y = position.y;
element.style.top = y + 'px';
element.style.left = x + 'px';
},
_scrollTo: function(scrollTop) {
var element = get(this, 'element');
if (element) { element.scrollTop = scrollTop; }
},
didInsertElement: function() {
var that, element;
that = this,
element = get(this, 'element');
this._updateScrollableHeight();
this._scroll = function(e) { that.scroll(e); };
Ember.$(element).on('scroll', this._scroll);
},
willDestroyElement: function() {
var element;
element = get(this, 'element');
Ember.$(element).off('scroll', this._scroll);
},
scroll: function(e) {
Ember.run(this, this.scrollTo, e.target.scrollTop);
},
scrollTo: function(y){
var element = get(this, 'element');
this._scrollTo(y);
this._scrollContentTo(y);
},
totalHeightDidChange: Ember.observer(function () {
Ember.run.scheduleOnce('afterRender', this, this._updateScrollableHeight);
}, 'totalHeight'),
_updateScrollableHeight: function () {
if (this.state === 'inDOM') {
this.$('.ember-list-container').css({
height: get(this, 'totalHeight')
});
}
}
});
})();
(function() {
/*global Scroller*/
var max = Math.max, get = Ember.get, set = Ember.set;
function updateScrollerDimensions(target) {
var width, height, totalHeight;
target = target || this;
width = get(target, 'width');
height = get(target, 'height');
totalHeight = get(target, 'totalHeight');
target.scroller.setDimensions(width, height, width, totalHeight);
target.trigger('scrollerDimensionsDidChange');
}
/**
VirtualListView
@class VirtualListView
@namespace Ember
*/
Ember.VirtualListView = Ember.ContainerView.extend(Ember.ListViewMixin, {
_isScrolling: false,
css: {
position: 'relative',
overflow: 'hidden'
},
init: function(){
this._super();
this.setupScroller();
},
_scrollerTop: 0,
applyTransform: Ember.ListViewHelper.applyTransform,
setupScroller: function(){
var view, y;
view = this;
view.scroller = new Scroller(function(left, top, zoom) {
if (view.state !== 'inDOM') { return; }
if (view.listContainerElement) {
view.applyTransform(view.listContainerElement, {x: 0, y: -top});
view._scrollerTop = top;
view._scrollContentTo(top);
}
}, {
scrollingX: false,
scrollingComplete: function(){
view.trigger('scrollingDidComplete');
}
});
view.trigger('didInitializeScroller');
updateScrollerDimensions(view);
},
scrollerDimensionsNeedToChange: Ember.observer(function() {
Ember.run.once(this, updateScrollerDimensions);
}, 'width', 'height', 'totalHeight'),
didInsertElement: function() {
var that, listContainerElement;
that = this;
this.listContainerElement = this.$('> .ember-list-container')[0];
this._mouseWheel = function(e) { that.mouseWheel(e); };
this.$().on('mousewheel', this._mouseWheel);
},
willDestroyElement: function() {
this.$().off('mousewheel', this._mouseWheel);
},
willBeginScroll: function(touches, timeStamp) {
this._isScrolling = false;
this.trigger('scrollingDidStart');
this.scroller.doTouchStart(touches, timeStamp);
},
continueScroll: function(touches, timeStamp) {
var startingScrollTop, endingScrollTop, event;
if (this._isScrolling) {
this.scroller.doTouchMove(touches, timeStamp);
} else {
startingScrollTop = this._scrollerTop;
this.scroller.doTouchMove(touches, timeStamp);
endingScrollTop = this._scrollerTop;
if (startingScrollTop !== endingScrollTop) {
event = Ember.$.Event("scrollerstart");
Ember.$(touches[0].target).trigger(event);
this._isScrolling = true;
}
}
},
// api
scrollTo: function(y, animate) {
if (animate === undefined) {
animate = true;
}
this.scroller.scrollTo(0, y, animate, 1);
},
// events
mouseWheel: function(e){
var inverted, delta, candidatePosition;
inverted = e.webkitDirectionInvertedFromDevice;
delta = e.wheelDeltaY * (inverted ? 0.8 : -0.8);
candidatePosition = this.scroller.__scrollTop + delta;
if ((candidatePosition >= 0) && (candidatePosition <= this.scroller.__maxScrollTop)) {
this.scroller.scrollBy(0, delta, true);
}
return false;
},
endScroll: function(timeStamp) {
this.scroller.doTouchEnd(timeStamp);
},
touchStart: function(e){
e = e.originalEvent || e;
this.willBeginScroll(e.touches, e.timeStamp);
return false;
},
touchMove: function(e){
e = e.originalEvent || e;
this.continueScroll(e.touches, e.timeStamp);
return false;
},
touchEnd: function(e){
e = e.originalEvent || e;
this.endScroll(e.timeStamp);
return false;
},
mouseDown: function(e){
this.willBeginScroll([e], e.timeStamp);
return false;
},
mouseMove: function(e){
this.continueScroll([e], e.timeStamp);
return false;
},
mouseUp: function(e){
this.endScroll(e.timeStamp);
return false;
},
mouseLeave: function(e){
this.endScroll(e.timeStamp);
return false;
}
});
})();
(function() {
})();
|
/*
* There is currently (Duktape 1.0) no way to prevent user code from
* accessing built-in prototype objects through plain values. For
* example, a plain string implicitly inherites from the original
* String.prototype.
*/
/*===
FOO
false
undefined
undefined
===*/
function test() {
var proto;
// Implicit inheritance example
print("foo".toUpperCase());
// This is not possible because String.prototype is not configurable
proto = {};
String.prototype = proto;
print(String.prototype === proto);
// Even if a sandboxing environment were to provide an empty String.prototype
// or not even expose 'String' at all, "foo".toUpperCase would still resolve
// to the built-in function. This is not demonstrated here.
// This is sufficient to prevent access to toUpperCase.
delete String.prototype.toUpperCase;
print(typeof String.prototype.toUpperCase);
print(typeof "foo".toUpperCase);
}
try {
test();
} catch (e) {
print(e.stack || e);
}
|
/*
* Version 0.2.6
* Made By Robin Kuiper
* Changes in Version 0.2.1, 0.2.6 by The Aaron
* Skype: RobinKuiper.eu
* Discord: Atheos#1095
* My Discord Server: https://discord.gg/AcC9VME
* Roll20: https://app.roll20.net/users/1226016/robin
* Roll20 Thread: https://app.roll20.net/forum/post/6349145/script-combattracker
* Github: https://github.com/RobinKuiper/Roll20APIScripts
* Reddit: https://www.reddit.com/user/robinkuiper/
* Patreon: https://patreon.com/robinkuiper
* Paypal.me: https://www.paypal.me/robinkuiper
*/
/* TODO
*
* Styling
* More chat message options
* Show menu with B shows always
* Add icon if not StatusInfo (?) (IF YES, remove conditions on statusmarker remove)
* Edit Conditions
*/
/* globals StatusInfo, TokenMod */
var CombatTracker = CombatTracker || (function() {
'use strict';
let round = 1,
timerObj,
intervalHandle,
rotationInterval,
paused = false,
observers = {
tokenChange: []
},
extensions = {
StatusInfo: false // This will be set to true automatically if you have StatusInfo
};
// Styling for the chat responses.
const styles = {
reset: 'padding: 0; margin: 0;',
menu: 'background-color: #fff; border: 1px solid #000; padding: 5px; border-radius: 5px;',
button: 'background-color: #000; border: 1px solid #292929; border-radius: 3px; padding: 5px; color: #fff; text-align: center;',
textButton: 'background-color: transparent; border: none; padding: 0; color: #000; text-decoration: underline',
list: 'list-style: none;',
float: {
right: 'float: right;',
left: 'float: left;'
},
overflow: 'overflow: hidden;',
fullWidth: 'width: 100%;',
underline: 'text-decoration: underline;',
strikethrough: 'text-decoration: strikethrough'
},
script_name = 'CombatTracker',
state_name = 'COMBATTRACKER',
handleInput = (msg) => {
if (msg.type != 'api') return;
let args = msg.content.split(' ');
let command = args.shift().substring(1);
let extracommand = args.shift();
if(command !== state[state_name].config.command) return;
if(extracommand === 'next'){
if(!getTurnorder().length) return;
if(playerIsGM(msg.playerid) || msg.playerid === 'api'){
NextTurn();
return;
}
let turn = getCurrentTurn(),
token = getObj('graphic', turn.id);
if(token){
let character = getObj('character', token.get('represents'));
if((token.get('controlledby').split(',').includes(msg.playerid) || token.get('controlledby').split(',').includes('all')) ||
(character && (character.get('controlledby').split(',').includes(msg.playerid) || character.get('controlledby').split(',').includes(msg.playerid)))){
NextTurn();
// SHOW MENU
}
}
}
// Below commands are only for GM's
if(!playerIsGM(msg.playerid)) return;
let name, duration, direction, message, condition;
switch(extracommand){
case 'help':
sendHelpMenu();
break;
case 'reset':
switch(args.shift()){
case 'conditions':
state[state_name].conditions = {};
break;
default:
state[state_name] = {};
setDefaults(true);
sendConfigMenu();
break;
}
break;
case 'config':
if(args[0] === 'timer'){
if(args[1]){
let setting = args[1].split('|');
let key = setting.shift();
let value = (setting[0] === 'true') ? true : (setting[0] === 'false') ? false : setting[0];
state[state_name].config.timer[key] = value;
}
sendConfigTimerMenu();
}else if (args[0] === 'turnorder'){
if(args[1]){
let setting = args[1].split('|');
let key = setting.shift();
let value = (setting[0] === 'true') ? true : (setting[0] === 'false') ? false : setting[0];
state[state_name].config.turnorder[key] = value;
}
sendConfigTurnorderMenu();
}else if (args[0] === 'announcements'){
if(args[1]){
let setting = args[1].split('|');
let key = setting.shift();
let value = (setting[0] === 'true') ? true : (setting[0] === 'false') ? false : setting[0];
state[state_name].config.announcements[key] = value;
}
sendConfigAnnounceMenu();
}else if (args[0] === 'macro'){
if(args[1]){
let setting = args[1].split('|');
let key = setting.shift();
let value = (setting[0] === 'true') ? true : (setting[0] === 'false') ? false : setting[0];
state[state_name].config.macro[key] = value;
}
sendConfigMacroMenu();
}else{
if(args[0]){
let setting = args.shift().split('|');
let key = setting.shift();
let value = (setting[0] === 'true') ? true : (setting[0] === 'false') ? false : setting[0];
state[state_name].config[key] = value;
}
sendConfigMenu();
}
break;
case 'prev':
PrevTurn();
break;
case 'start':
startCombat(msg.selected);
if(args.shift() === 'b') sendMenu();
break;
case 'stop':
stopCombat();
if(args.shift() === 'b') sendMenu();
break;
case 'st':
stopTimer();
if(args.shift() === 'b') sendMenu();
break;
case 'pt':
pauseTimer();
if(args.shift() === 'b') sendMenu();
break;
case 'conditions':
sendConditionsMenu();
break;
case 'show': {
if(!msg.selected || !msg.selected.length){
makeAndSendMenu('No tokens are selected.', '', 'gm');
return;
}
let tokens = msg.selected.map(s => getObj('graphic', s._id));
sendTokenConditionMenu(tokens);
}
break;
case 'add':
name = args.shift();
if(!name){
makeAndSendMenu('No condition name was given.', '', 'gm');
return;
}
duration = args.shift();
duration = (!duration || duration === 0) ? 'none' : duration;
direction = args.shift() || -1;
message = args.join(' ');
condition = { name, duration, direction, message };
if(!msg.selected || !msg.selected.length){
let tokenid = args.shift();
let token = getObj('graphic', tokenid);
if(!tokenid || !token){
makeAndSendMenu('No tokens were selected.', '', 'gm');
return;
}
addCondition(token, condition, true);
return;
}
msg.selected.forEach(s => {
let token = getObj(s._type, s._id);
if(!token) return;
addCondition(token, condition, true);
});
break;
case 'addfav':
name= args.shift();
duration = args.shift();
direction = args.shift() || -1;
message = args.join(' ');
condition = { name, duration, direction, message };
addOrEditFavoriteCondition(condition);
sendFavoritesMenu();
break;
case 'editfav':
name = args.shift();
if(!name){
makeAndSendMenu('No condition name was given.', '', 'gm');
return;
}
name = strip(name).toLowerCase();
condition = state[state_name].favorites[name];
if(!condition){
makeAndSendMenu('Condition does not exists.', '', 'gm');
return;
}
if(args[0]){
let setting = args.shift().split('|');
let key = setting.shift();
let value = (setting[0] === 'true') ? true : (setting[0] === 'false') ? false : setting[0];
state[state_name].favorites[name][key] = value;
if(key === 'name'){
state[state_name].favorites[strip(value).toLowerCase()] = state[state_name].favorites[name];
delete state[state_name].favorites[name];
}
}
sendEditFavoriteConditionMenu(condition);
break;
case 'removefav':
removeFavoriteCondition(args.shift());
sendFavoritesMenu();
break;
case 'favorites':
sendFavoritesMenu();
break;
case 'remove': {
let cname = args.shift();
let tokenid = args.shift();
let token;
if(!cname){
makeAndSendMenu('No condition was given.', '', 'gm');
return;
}
if(tokenid){
token = getObj('graphic', tokenid);
if(token){
removeCondition(token, cname);
sendTokenConditionMenu([token]);
return;
}
}
if(!msg.selected || !msg.selected.length){
makeAndSendMenu('No tokens were selected.', '', 'gm');
return;
}
msg.selected.forEach(s => {
token = getObj(s._type, s._id);
if(!token) return;
removeCondition(token, cname);
});
}
break;
case 'showcondition': {
let cname = args.shift();
let tokenid = args.shift();
let token;
if(!cname){
makeAndSendMenu('No condition was given.', '', 'gm');
return;
}
if(tokenid){
token = getObj('graphic', tokenid);
if(token){
showCondition(token, cname);
}
}
}
break;
default:
sendMenu();
break;
}
},
addOrEditFavoriteCondition = (condition) => {
if(condition.duration === 0 || condition.duration === '') condition.duration = undefined;
let strippedName = strip(condition.name).toLowerCase();
state[state_name].favorites[strippedName] = condition;
},
removeFavoriteCondition = (name) => {
name = strip(name).toLowerCase();
delete state[state_name].favorites[name];
},
addCondition = (token, condition, announce=false) => {
if(extensions.StatusInfo){
/*const duration = condition.duration;
const direction = condition.direction;
const message = condition.message;*/
let si_condition = StatusInfo.getConditionByName(condition.name) || condition;
condition.name = si_condition.name;
condition.icon = si_condition.icon;
}
if(!condition.duration || condition.duration === 0 || condition.duration === '0' || condition.duration === '' || condition.duration === 'none') condition.duration = undefined;
if(state[state_name].conditions[strip(token.get('id')).toLowerCase()]){
let hasCondition = false;
state[state_name].conditions[strip(token.get('id')).toLowerCase()].forEach(c => {
if(c.name.toLowerCase() === condition.name.toLowerCase()) hasCondition = true;
});
if(hasCondition) return;
state[state_name].conditions[strip(token.get('id')).toLowerCase()].push(condition);
}else{
state[state_name].conditions[strip(token.get('id')).toLowerCase()] = [condition];
}
if(condition.icon){
// let prevSM = token.get('statusmarkers');
token.set('status_'+condition.icon, true);
if(announce && extensions.StatusInfo){
StatusInfo.sendConditionToChat(condition);
}
}else makeAndSendMenu('Condition ' + condition.name + ' added to ' + token.get('name'));
},
removeCondition = (token, condition_name, auto=false) => {
if(!state[state_name].conditions[strip(token.get('id')).toLowerCase()]) return;
let si_condition = false;
if(extensions.StatusInfo){
si_condition = StatusInfo.getConditionByName(condition_name) || false;
}
state[state_name].conditions[strip(token.get('id')).toLowerCase()].forEach((condition, i) => {
if(condition.name.toLowerCase() !== condition_name.toLowerCase()) return;
state[state_name].conditions[strip(token.get('id')).toLowerCase()].splice(i, 1);
if(si_condition){
token.set('status_'+condition.icon, false);
}else if(!auto){
makeAndSendMenu('Condition ' + condition.name + ' removed from ' + token.get('name'));
}
});
},
showCondition = (token, condition_name) => {
if(!state[state_name].conditions[strip(token.get('id')).toLowerCase()]) return;
let si_condition = false;
if(extensions.StatusInfo){
si_condition = StatusInfo.getConditionByName(condition_name) || false;
}
state[state_name].conditions[strip(token.get('id')).toLowerCase()].forEach((condition, i) => {
if(condition.name.toLowerCase() !== condition_name.toLowerCase()) return;
if(si_condition){
StatusInfo.sendConditionToChat(si_condition);
}
if(condition.message) makeAndSendMenu(condition.message, condition.name, '');
});
},
strip = (str) => {
return str.replace(/[^a-zA-Z0-9]+/g, '_');
},
handleTurnorderChange = (obj, prev) => {
if(obj.get('turnorder') === prev.turnorder) return;
let turnorder = (obj.get('turnorder') === "") ? [] : JSON.parse(obj.get('turnorder'));
let prevTurnorder = (prev.turnorder === "") ? [] : JSON.parse(prev.turnorder);
if(obj.get('turnorder') === "[]"){
resetMarker();
stopTimer();
return;
}
if(turnorder.length && prevTurnorder.length && turnorder[0].id !== prevTurnorder[0].id){
doTurnorderChange();
}
},
handleStatusMarkerChange = (obj, prev) => {
if(extensions.StatusInfo){
prev.statusmarkers = (typeof prev.get === 'function') ? prev.get('statusmarkers') : prev.statusmarkers;
if(obj.get('statusmarkers') !== prev.statusmarkers){
let nS = obj.get('statusmarkers').split(','),
oS = prev.statusmarkers.split(',');
// Marker added?
array_diff(oS, nS).forEach(icon => {
if(icon === '') return;
getObjects(StatusInfo.getConditions(), 'icon', icon).forEach(condition => {
addCondition(obj, { name: condition.name });
});
});
// Marker Removed?
array_diff(nS, oS).forEach(icon => {
if(icon === '') return;
getObjects(StatusInfo.getConditions(), 'icon', icon).forEach(condition => {
removeCondition(obj, condition.name);
});
});
}
}
},
handleGraphicMovement = (obj /*, prev */) => {
if(!inFight()) return;
if(getCurrentTurn().id === obj.get('id')){
changeMarker(obj);
}
},
array_diff = (a, b) => {
return b.filter(function(i) {return a.indexOf(i) < 0;});
},
//return an array of objects according to key, value, or key and value matching
getObjects = (obj, key, val) => {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else
//if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
if (i == key && obj[i] == val || i == key && val == '') { //
objects.push(obj);
} else if (obj[i] == val && key == ''){
//only add if the object is not already in the array
if (objects.lastIndexOf(obj) == -1){
objects.push(obj);
}
}
}
return objects;
},
startCombat = (selected) => {
paused = false;
resetMarker();
Campaign().set('initiativepage', Campaign().get('playerpageid'));
if(selected && state[state_name].config.turnorder.throw_initiative){
rollInitiative(selected, state[state_name].config.turnorder.auto_sort);
}
doTurnorderChange();
},
inFight = () => {
return (Campaign().get('initiativepage') !== false);
},
rollInitiative = (selected, sort) => {
selected.forEach(s => {
if(s._type !== 'graphic') return;
let token = getObj('graphic', s._id),
whisper = (token.get('layer') === 'gmlayer') ? 'gm ' : '',
bonus = parseFloat(getAttrByName(token.get('represents'), state[state_name].config.initiative_attribute_name, 'current')) || 0;
let roll = randomInteger(20);
//pr = (Math.round(pr) !== pr) ? pr.toFixed(2) : pr;
if(state[state_name].config.turnorder.show_initiative_roll){
let contents = ' \
<table style="width: 100%; text-align: left;"> \
<tr> \
<th>Modifier</th> \
<td>'+bonus+'</td> \
</tr> \
</table> \
<div style="text-align: center"> \
<b style="font-size: 16pt;"> \
<span style="border: 1px solid green; padding-bottom: 2px; padding-top: 4px;">[['+roll+'+'+bonus+']]</span><br><br> \
</b> \
</div>'
makeAndSendMenu(contents, token.get('name') + ' Initiative', whisper);
}
addToTurnorder({ id: token.get('id'), pr: roll+bonus, custom: '', _pageid: token.get('pageid') });
});
if(sort){
sortTurnorder();
}
},
stopCombat = () => {
if(timerObj) timerObj.remove();
removeMarker();
stopTimer();
paused = false;
Campaign().set({
initiativepage: false,
turnorder: ''
});
state[state_name].turnorder = {};
round = 1;
},
clearTurnorder = () => {
Campaign().set({ turnorder: '' });
state[state_name].turnorder = {};
},
removeMarker = () => {
stopRotate();
getOrCreateMarker().remove();
},
resetMarker = () => {
let marker = getOrCreateMarker();
marker.set({
name: 'Round ' + round,
imgsrc: state[state_name].config.marker_img,
pageid: Campaign().get('playerpageid'),
layer: 'gmlayer',
left: 35, top: 35,
width: 70, height: 70
});
return marker;
},
doTurnorderChange = (prev=false) => {
if(!Campaign().get('initiativepage') || getTurnorder().length <= 1) return;
let turn = getCurrentTurn();
if(turn.id === '-1'){
if(!state[state_name].config.turnorder.skip_custom) resetMarker();
else NextTurn();
return;
}
if(turn.id === getOrCreateMarker().get('id')){
if(prev) PrevRound();
else NextRound();
return;
}
let token = getObj('graphic', turn.id);
if(!token){
resetMarker();
return;
}
toFront(token);
if(state[state_name].config.timer.use_timer){
startTimer(token);
}
changeMarker(token || false);
if(state[state_name].config.macro.run_macro){
let ability = findObjs({ _characterid: token.get('represents'), _type: 'ability', name: state[state_name].config.macro.macro_name })
if(ability && ability.length){
sendChat(token.get('name'), ability[0].get('action'), null, {noarchive:true} );
}
}
if(state[state_name].config.announcements.announce_turn){
announceTurn(token || turn.custom, (token.get('layer') === 'objects') ? '' : 'gm');
}else if(state[state_name].config.announcements.announce_conditions){
let name = token.get('name') || turn.custom;
let conditions = getConditionString(token);
if(conditions && conditions !== '') makeAndSendMenu(conditions, 'Conditions - ' + name, (token.get('layer') === 'objects') ? '' : 'gm');
}
Pull(token);
doFX(token);
},
doFX = (token) => {
if(!state[state_name].config.announcements.use_fx || token.get('layer') === 'gmlayer') return;
let pos = {x: token.get('left'), y: token.get('top')};
spawnFxBetweenPoints(pos, pos, state[state_name].config.announcements.fx_type, token.get('pageid'));
},
Pull = (token) => {
if(!state[state_name].config.pull) return;
sendPing(token.get('left'), token.get('top'), token.get('pageid'), null, true);
},
startTimer = (token) => {
paused = false;
clearInterval(intervalHandle);
if(timerObj) timerObj.remove();
let config_time = parseInt(state[state_name].config.timer.time);
let time = config_time;
if(token && state[state_name].config.timer.token_timer){
timerObj = createObj('text', {
text: 'Timer: ' + time,
font_size: state[state_name].config.timer.token_font_size,
font_family: state[state_name].config.timer.token_font,
color: state[state_name].config.timer.token_font_color,
pageid: token.get('pageid'),
layer: 'gmlayer'
});
}
intervalHandle = setInterval(() => {
if(paused) return;
if(timerObj) timerObj.set({
top: token.get('top')+token.get('width')/2+40,
left: token.get('left'),
text: 'Timer: ' + time,
layer: token.get('layer')
});
if(state[state_name].config.timer.chat_timer && (time === config_time || config_time/2 === time || config_time/4 === time || time === 10 || time === 5)){
makeAndSendMenu('', 'Time Remaining: ' + time);
}
if(time <= 0){
if(timerObj) timerObj.remove();
clearInterval(intervalHandle);
if(state[state_name].config.timer.auto_skip) NextTurn();
else makeAndSendMenu(token.get('name') + "'s time ran out!", '');
}
time--;
}, 1000);
},
stopTimer = () => {
clearInterval(intervalHandle);
if(timerObj) timerObj.remove();
},
pauseTimer = () => {
paused = !paused;
},
announceTurn = (token, target) => {
target = (state[state_name].config.announcements.whisper_turn_gm) ? 'gm' : target;
let name, imgurl;
if(typeof token === 'object'){
name = token.get('name');
imgurl = token.get('imgsrc');
}else{
name = token;
}
let conditions = getConditionString(token);
let image = (imgurl) ? '<img src="'+imgurl+'" width="50px" height="50px" />' : '';
name = (state[state_name].config.announcements.handleLongName) ? handleLongString(name) : name;
let contents = '\
<table> \
<tr> \
<td>'+image+'</td> \
<td style="padding-left: 5px;"><span style="font-size: 16pt;">'+name+'\'s Turn</span></td> \
</tr> \
</table> \
<div style="overflow: hidden"> \
<div style="float: left">'+conditions+'</div> \
' + makeButton('Done', '!'+state[state_name].config.command+' next', styles.button + styles.float.right) +' \
</div>';
makeAndSendMenu(contents, '', target);
},
getConditionString = (token) => {
let name = strip(token.get('id')).toLowerCase();
let conditionsSTR = '';
if(state[state_name].conditions[name] && state[state_name].conditions[name].length){
for(let i = 0; i < state[state_name].conditions[name].length; i++){
let condition = state[state_name].conditions[name][i];
if(typeof condition.duration === 'undefined' || condition.duration === false){
conditionsSTR += '<strong>'+condition.name+'</strong><br>';
}else if(condition.duration <= 1){
conditionsSTR += '<strong>'+condition.name+'</strong> removed.<br>';
removeCondition(token, condition.name, true);
i--;
} else {
state[state_name].conditions[name][i].duration = parseInt(state[state_name].conditions[name][i].duration)+parseInt(condition.direction);
conditionsSTR += '<strong>'+condition.name+'</strong>: ' + condition.duration + '<br>';
}
conditionsSTR += (condition.message) ? '<em style="font-size: 10pt">'+condition.message+'</em><br>' : '';
}
}
return conditionsSTR;
},
handleLongString = (str, max=8) => {
str = str.split(' ')[0];
return (str.length > max) ? str.slice(0, max) + '...' : str;
},
NextTurn = () => {
let turnorder = getTurnorder(),
current_turn = turnorder.shift();
turnorder.push(current_turn);
setTurnorder(turnorder);
doTurnorderChange();
},
PrevTurn = () => {
let turnorder = getTurnorder(),
last_turn = turnorder.pop();
turnorder.unshift(last_turn);
setTurnorder(turnorder);
doTurnorderChange(true);
},
NextRound = () => {
let marker = getOrCreateMarker();
round++;
marker.set({ name: 'Round ' + round});
if(state[state_name].config.announcements.announce_round){
let text = '<span style="font-size: 16pt; font-weight: bold;">'+marker.get('name')+'</span>';
makeAndSendMenu(text);
}
if(state[state_name].config.turnorder.reroll_ini_round){
let turnorder = getTurnorder();
clearTurnorder();
rollInitiative(turnorder.map(t => { return (t.id !== -1 && t.id !== marker.get('id')) ? { _type: 'graphic', _id: t.id } : false }), state[state_name].config.turnorder.auto_sort);
sortTurnorder();
}else{
NextTurn();
}
},
PrevRound = () => {
let marker = getOrCreateMarker();
round--;
marker.set({ name: 'Round ' + round});
if(state[state_name].config.announcements.announce_round){
let text = '<span style="font-size: 16pt; font-weight: bold;">'+marker.get('name')+'</span>';
makeAndSendMenu(text);
}
PrevTurn();
},
changeMarker = (token) => {
let marker = getOrCreateMarker();
if(!token){
resetMarker();
return;
}
let settings = {
layer: token.get('layer'),
top: token.get('top'),
left: token.get('left'),
width: token.get('width')+(token.get('width')*0.35),
height: token.get('height')+(token.get('height')*0.35)
};
marker.set(settings);
toBack(marker);
},
getOrCreateMarker = () => {
let marker,
img = state[state_name].config.marker_img,
playerpageid = Campaign().get('playerpageid'),
markers = findObjs({
pageid: playerpageid,
imgsrc: img
});
markers.forEach((marker, i) => {
if(i > 0) marker.remove();
});
marker = markers.shift();
if(!marker) {
marker = createObj('graphic', {
name: 'Round 0',
imgsrc: img,
pageid: playerpageid,
layer: 'gmlayer',
showplayers_name: true,
left: 35, top: 35,
width: 70, height: 70
});
}
checkMarkerturn(marker);
toBack(marker);
//startRotate(marker);
return marker;
},
/*
startRotate = (token) => {
clearInterval(rotationInterval);
let i = 0;
rotationInterval = setInterval(() => {
i += 2;
log(i);
if(i >= 360) i = 0;
token.set('rotation', i);
}, 50);
},
*/
stopRotate = () => {
clearInterval(rotationInterval);
},
checkMarkerturn = (marker) => {
let turnorder = getTurnorder(),
hasTurn = false;
turnorder.forEach(turn => {
if(turn.id === marker.get('id')) hasTurn = true;
});
if(!hasTurn){
turnorder.push({ id: marker.get('id'), pr: -1, custom: '', _pageid: marker.get('pageid') });
Campaign().set('turnorder', JSON.stringify(turnorder));
}
},
sortTurnorder = (order='DESC') => {
let turnorder = getTurnorder();
turnorder.sort((a,b) => {
return (order === 'ASC') ? a.pr - b.pr : b.pr - a.pr;
});
setTurnorder(turnorder);
doTurnorderChange();
},
getTurnorder = () => {
return (Campaign().get('turnorder') === '') ? [] : Array.from(JSON.parse(Campaign().get('turnorder')));
},
getCurrentTurn = () => {
return getTurnorder().shift();
},
addToTurnorder = (turn) => {
if(!turn){
return;
}
let turnorder = getTurnorder(),
justDoIt = true;
turnorder.forEach(t => {
if(t.id === turn.id) justDoIt = false;
});
if(justDoIt){
turnorder.push(turn);
setTurnorder(turnorder);
}
},
setTurnorder = (turnorder) => {
Campaign().set('turnorder', JSON.stringify(turnorder));
},
randomBetween = (min, max) => {
return Math.floor(Math.random()*(max-min+1)+min);
},
sendTokenConditionMenu = (tokens) => {
let contents = '<table style="width: 100%;">';
let i = 0;
tokens.forEach(token => {
if(!token) return;
let conditions = state[state_name].conditions[strip(token.get('id')).toLowerCase()];
if(i) contents += '<tr><td colspan="2"><hr></td></tr>';
i++;
contents += ' \
<tr> \
<td colspan="2" style="font-size: 12pt; font-weight: bold;"> \
<img src='+token.get('imgsrc')+' style="width: 32px; height: 32px; vertical-align: middle;" /> \
<span style="vertical-align: middle;">'+token.get('name')+'</span> \
</td> \
</tr>';
if(!conditions || !conditions.length){
contents += '<tr><td colspan="2" style="text-align: center;"><i>None</i></td></tr>';
}else{
conditions.forEach(condition => {
let si_condition = false;
if(extensions.StatusInfo){
si_condition = StatusInfo.getConditionByName(condition.name) || false;
}
let removeButton = makeButton('<img src="https://s3.amazonaws.com/files.d20.io/images/11381509/YcG-o2Q1-CrwKD_nXh5yAA/thumb.png?1439051579" />', '!'+state[state_name].config.command + ' remove ' + condition.name + ' ' + token.get('id'), styles.button + styles.float.right + 'width: 16px; height: 16px;');
let showButton = (condition.message || si_condition) ? makeButton('<img src="https://cdn1.iconfinder.com/data/icons/hawcons/32/699008-icon-22-eye-128.png" />', '!'+state[state_name].config.command + ' showcondition ' + condition.name + ' ' + token.get('id'), styles.button + styles.float.right + 'width: 16px; height: 16px;') : '';
let name = condition.name;
name += (condition.duration) ? ' (' + condition.duration + ')' : '';
contents += ' \
<tr> \
<td style="text-align: center">'+name+'</td> \
<td>'+removeButton+showButton+'</td> \
</tr>';
});
}
});
contents += '</table>';
makeAndSendMenu(contents, '', 'gm');
},
sendConditionsMenu = () => {
let addButton;
let SI_listItems = [];
if(extensions.StatusInfo){
Object.keys(StatusInfo.getConditions()).map(key => StatusInfo.getConditions()[key]).forEach(condition => {
let conditionSTR = condition.name + ' ?{Duration} ?{Direction|-1} ?{Message}';
addButton = makeButton(StatusInfo.getIcon(condition.icon, 'margin-right: 5px; margin-top: 5px; display: inline-block;') + condition.name, '!'+state[state_name].config.command + ' add ' + conditionSTR, styles.textButton);
SI_listItems.push('<span style="'+styles.float.left+'">'+addButton+'</span>');
});
}
let F_listItems = [];
Object.keys(state[state_name].favorites).map(key => state[state_name].favorites[key]).forEach(condition => {
let conditionSTR = (!condition.duration) ? condition.name : condition.name + ' ' + condition.duration + ' ' + condition.direction + ' ' + condition.message;
addButton = makeButton(condition.name, '!'+state[state_name].config.command + ' add ' + conditionSTR, styles.textButton);
F_listItems.push('<span style="'+styles.float.left+'">'+addButton+' - <span style="font-size: 8pt">'+condition.duration+':'+condition.direction+':'+condition.message+'</span></span>');
});
let contents = '';
contents += '<h4>StatusInfo Conditions</h4>';
if(SI_listItems.length){
contents += makeList(SI_listItems, styles.reset + styles.list + styles.overflow, styles.overflow);
}else{
contents += (extensions.StatusInfo) ? 'Your StatusInfo doesn\'t have any conditions.' : makeButton('StatusInfo', 'https://github.com/RobinKuiper/Roll20APIScripts/tree/master/StatusInfo', styles.textButton) + ' is not installed.';
}
contents += '<hr>';
contents += '<h4>Favorite Conditions</h4>';
if(F_listItems.length){
contents += makeList(F_listItems, styles.reset + styles.list + styles.overflow, styles.overflow);
}else{
contents += 'You don\'t have any favorite conditions yet.';
}
contents += '<br><br>' + makeButton('Edit Favorites', '!'+state[state_name].config.command + ' favorites', styles.button + styles.fullWidth);
makeAndSendMenu(contents, 'Conditions', 'gm');
},
sendFavoritesMenu = () => {
let addButton, editButton, list;
let listItems = [];
Object.keys(state[state_name].favorites).map(key => state[state_name].favorites[key]).forEach(condition => {
let conditionSTR = (!condition.duration) ? condition.name : condition.name + ' ' + condition.duration + ' ' + condition.direction + ' ' + condition.message;
addButton = makeButton(condition.name, '!'+state[state_name].config.command + ' add ' + conditionSTR, styles.textButton);
editButton = makeButton('Edit', '!'+state[state_name].config.command + ' editfav ' + condition.name, styles.button + styles.float.right);
listItems.push('<span style="'+styles.float.left+'">'+addButton+'</span> '+editButton);
});
let newButton = makeButton('Add New', '!'+state[state_name].config.command + ' addfav ?{Name} ?{Duration} ?{Direction} ?{Message}', styles.button + styles.fullWidth);
list = (listItems.length) ? makeList(listItems, styles.reset + styles.list + styles.overflow, styles.overflow) : 'No favorites yet.';
makeAndSendMenu(list + '<hr>' + newButton, 'Favorite Conditions', 'gm');
},
sendEditFavoriteConditionMenu = (condition) => {
if(!state[state_name].favorites[strip(condition.name).toLowerCase()]){
makeAndSendMenu('Condition does not exist.', '', 'gm');
return;
}
let nameButton = makeButton(condition.name, '!'+state[state_name].config.command + ' editfav ' + condition.name + ' name|?{Name|'+condition.name+'}', styles.button + styles.float.right);
let durationButton = makeButton(condition.duration, '!'+state[state_name].config.command + ' editfav ' + condition.name + ' duration|?{Duration|'+condition.duration+'}', styles.button + styles.float.right);
let directionButton = makeButton(condition.direction, '!'+state[state_name].config.command + ' editfav ' + condition.name + ' direction|?{Direction|'+condition.direction+'}', styles.button + styles.float.right);
let listItems = [
'<span style="'+styles.float.left+'">Name</span> '+nameButton,
'<span style="'+styles.float.left+'">Duration</span> '+durationButton
];
if(condition.duration && condition.duration !== 0 && condition.duration !== '0'){
listItems.push('<span style="'+styles.float.left+'">Direction</span> '+directionButton);
}
let removeButton = makeButton('Remove', '!'+state[state_name].config.command + ' removefav ' + condition.name, styles.button + styles.fullWidth);
let backButton = makeButton('Back', '!'+state[state_name].config.command + ' favorites', styles.button + styles.fullWidth);
let messageButton = makeButton((condition.message) ? 'Change Message' : 'Set Message', '!'+state[state_name].config.command + ' editfav ' + condition.name + ' message|?{Message|'+condition.message+'}', styles.button);
let message = (condition.message) ? condition.message : '<i>None</i>';
makeAndSendMenu(makeList(listItems, styles.reset + styles.list + styles.overflow, styles.overflow) + '<hr><b>Message</b><p>' + message + '</p>' + messageButton + '<hr>' + removeButton + '<hr>' + backButton, 'Edit - ' + condition.name, 'gm');
},
sendConfigMenu = (first, message) => {
let commandButton = makeButton('!'+state[state_name].config.command, '!' + state[state_name].config.command + ' config command|?{Command (without !)}', styles.button + styles.float.right),
markerImgButton = makeButton('<img src="'+state[state_name].config.marker_img+'" width="30px" height="30px" />', '!' + state[state_name].config.command + ' config marker_img|?{Image Url}', styles.button + styles.float.right),
iniAttrButton = makeButton(state[state_name].config.initiative_attribute_name, '!' + state[state_name].config.command + ' config initiative_attribute_name|?{Attribute|'+state[state_name].config.initiative_attribute_name+'}', styles.button + styles.float.right),
closeStopButton = makeButton(state[state_name].config.close_stop, '!' + state[state_name].config.command + ' config close_stop|'+!state[state_name].config.close_stop, styles.button + styles.float.right),
pullButton = makeButton(state[state_name].config.pull, '!' + state[state_name].config.command + ' config pull|'+!state[state_name].config.pull, styles.button + styles.float.right),
listItems = [
'<span style="'+styles.float.left+'">Command:</span> ' + commandButton,
'<span style="'+styles.float.left+'">Ini. Attribute:</span> ' + iniAttrButton,
'<span style="'+styles.float.left+'">Marker Img:</span> ' + markerImgButton,
'<span style="'+styles.float.left+'">Stop on close:</span> ' + closeStopButton,
'<span style="'+styles.float.left+'">Auto Pull Map:</span> ' + pullButton,
],
configTurnorderButton = makeButton('Turnorder Config', '!'+state[state_name].config.command + ' config turnorder', styles.button),
configTimerButton = makeButton('Timer Config', '!'+state[state_name].config.command + ' config timer', styles.button),
configAnnouncementsButton = makeButton('Announcement Config', '!'+state[state_name].config.command + ' config announcements', styles.button),
configMacroButton = makeButton('Macro Config', '!'+state[state_name].config.command + ' config macro', styles.button),
resetButton = makeButton('Reset', '!' + state[state_name].config.command + ' reset', styles.button + styles.fullWidth),
title_text = (first) ? script_name + ' First Time Setup' : script_name + ' Config';
message = (message) ? '<p>'+message+'</p>' : '';
let contents = message+makeList(listItems, styles.reset + styles.list + styles.overflow, styles.overflow)+configTurnorderButton+'<br>'+configTimerButton+'<br>'+configAnnouncementsButton+'<br>'+configMacroButton+'<hr><p style="font-size: 80%">You can always come back to this config by typing `!'+state[state_name].config.command+' config`.</p><hr>'+resetButton;
makeAndSendMenu(contents, title_text, 'gm');
},
sendConfigTurnorderMenu = () => {
let throwIniButton = makeButton(state[state_name].config.turnorder.throw_initiative, '!' + state[state_name].config.command + ' config turnorder throw_initiative|'+!state[state_name].config.turnorder.throw_initiative, styles.button + styles.float.right),
showRollButton = makeButton(state[state_name].config.turnorder.show_initiative_roll, '!' + state[state_name].config.command + ' config turnorder show_initiative_roll|'+!state[state_name].config.turnorder.show_initiative_roll, styles.button + styles.float.right),
autoSortButton = makeButton(state[state_name].config.turnorder.auto_sort, '!' + state[state_name].config.command + ' config turnorder auto_sort|'+!state[state_name].config.turnorder.auto_sort, styles.button + styles.float.right),
rerollIniButton = makeButton(state[state_name].config.turnorder.reroll_ini_round, '!' + state[state_name].config.command + ' config turnorder reroll_ini_round|'+!state[state_name].config.turnorder.reroll_ini_round, styles.button + styles.float.right),
skipCustomButton = makeButton(state[state_name].config.turnorder.skip_custom, '!' + state[state_name].config.command + ' config turnorder skip_custom|'+!state[state_name].config.turnorder.skip_custom, styles.button + styles.float.right),
backButton = makeButton('< Back', '!'+state[state_name].config.command + ' config', styles.button + styles.fullWidth),
listItems = [
'<span style="'+styles.float.left+'">Auto Roll Ini.:</span> ' + throwIniButton,
'<span style="'+styles.float.left+'">Reroll Ini. p. Round:</span> ' + rerollIniButton,
'<span style="'+styles.float.left+'">Auto Sort:</span> ' + autoSortButton,
'<span style="'+styles.float.left+'">Skip Custom Item:</span> ' + skipCustomButton
];
if(state[state_name].config.turnorder.throw_initiative){
listItems.push('<span style="'+styles.float.left+'">Show Initiative:</span> ' + showRollButton)
}
let contents = makeList(listItems, styles.reset + styles.list + styles.overflow, styles.overflow)+'<hr>'+backButton;
makeAndSendMenu(contents, script_name + ' Turnorder Config', 'gm');
},
sendConfigAnnounceMenu = () =>{
let announceTurnButton = makeButton(state[state_name].config.announcements.announce_turn, '!' + state[state_name].config.command + ' config announcements announce_turn|'+!state[state_name].config.announcements.announce_turn, styles.button + styles.float.right),
announceRoundButton = makeButton(state[state_name].config.announcements.announce_round, '!' + state[state_name].config.command + ' config announcements announce_round|'+!state[state_name].config.announcements.announce_round, styles.button + styles.float.right),
announceConditionsButton = makeButton(state[state_name].config.announcements.announce_conditions, '!' + state[state_name].config.command + ' config announcements announce_conditions|'+!state[state_name].config.announcements.announce_conditions, styles.button + styles.float.right),
handleLongNameButton = makeButton(state[state_name].config.announcements.handleLongName, '!' + state[state_name].config.command + ' config announcements handleLongName|'+!state[state_name].config.announcements.handleLongName, styles.button + styles.float.right),
useFXButton = makeButton(state[state_name].config.announcements.use_fx, '!' + state[state_name].config.command + ' config announcements use_fx|'+!state[state_name].config.announcements.use_fx, styles.button + styles.float.right),
FXTypeButton = makeButton(state[state_name].config.announcements.fx_type, '!' + state[state_name].config.command + ' config announcements fx_type|?{Type|'+state[state_name].config.announcements.fx_type+'}', styles.button + styles.float.right),
whisperTurnGMButton = makeButton(state[state_name].config.announcements.whisper_turn_gm, '!' + state[state_name].config.command + ' config announcements whisper_turn_gm|'+!state[state_name].config.announcements.whisper_turn_gm, styles.button + styles.float.right),
backButton = makeButton('< Back', '!'+state[state_name].config.command + ' config', styles.button + styles.fullWidth),
listItems = [];
listItems.push('<span style="'+styles.float.left+'">Announce Round:</span> ' + announceRoundButton);
listItems.push('<span style="'+styles.float.left+'">Announce Turn:</span> ' + announceTurnButton);
if(!state[state_name].config.announcements.announce_turn){
listItems.push('<span style="'+styles.float.left+'">Announce Conditions:</span> ' + announceConditionsButton);
}
if(state[state_name].config.announcements.announce_turn){
listItems.push('<span style="'+styles.float.left+'">Whisper GM Only:</span> ' + whisperTurnGMButton);
listItems.push('<span style="'+styles.float.left+'">Shorten Long Name:</span> ' + handleLongNameButton);
}
listItems.push('<span style="'+styles.float.left+'">Use FX:</span> ' + useFXButton);
if(state[state_name].config.announcements.use_fx){
listItems.push('<span style="'+styles.float.left+'">FX Type:</span> ' + FXTypeButton);
}
let contents = makeList(listItems, styles.reset + styles.list + styles.overflow, styles.overflow)+'<hr>'+backButton;
makeAndSendMenu(contents, script_name + ' Announcements Config', 'gm');
},
sendConfigTimerMenu = () => {
let turnTimerButton = makeButton(state[state_name].config.timer.use_timer, '!' + state[state_name].config.command + ' config timer use_timer|'+!state[state_name].config.timer.use_timer, styles.button + styles.float.right),
timeButton = makeButton(state[state_name].config.timer.time, '!' + state[state_name].config.command + ' config timer time|?{Time|'+state[state_name].config.timer.time+'}', styles.button + styles.float.right),
autoSkipButton = makeButton(state[state_name].config.timer.auto_skip, '!' + state[state_name].config.command + ' config timer auto_skip|'+!state[state_name].config.timer.auto_skip, styles.button + styles.float.right),
chatTimerButton = makeButton(state[state_name].config.timer.chat_timer, '!' + state[state_name].config.command + ' config timer chat_timer|'+!state[state_name].config.timer.chat_timer, styles.button + styles.float.right),
tokenTimerButton = makeButton(state[state_name].config.timer.token_timer, '!' + state[state_name].config.command + ' config timer token_timer|'+!state[state_name].config.timer.token_timer, styles.button + styles.float.right),
tokenFontButton = makeButton(state[state_name].config.timer.token_font, '!' + state[state_name].config.command + ' config timer token_font|?{Font|Arial|Patrick Hand|Contrail|Light|Candal}', styles.button + styles.float.right),
tokenFontSizeButton = makeButton(state[state_name].config.timer.token_font_size, '!' + state[state_name].config.command + ' config timer token_font_size|?{Font Size|'+state[state_name].config.timer.token_font_size+'}', styles.button + styles.float.right),
backButton = makeButton('< Back', '!'+state[state_name].config.command + ' config', styles.button + styles.fullWidth),
listItems = [
'<span style="'+styles.float.left+'">Turn Timer:</span> ' + turnTimerButton,
'<span style="'+styles.float.left+'">Time:</span> ' + timeButton,
'<span style="'+styles.float.left+'">Auto Skip:</span> ' + autoSkipButton,
'<span style="'+styles.float.left+'">Show in Chat:</span> ' + chatTimerButton,
'<span style="'+styles.float.left+'">Show on Token:</span> ' + tokenTimerButton,
'<span style="'+styles.float.left+'">Token Font:</span> ' + tokenFontButton,
'<span style="'+styles.float.left+'">Token Font Size:</span> ' + tokenFontSizeButton
];
let contents = makeList(listItems, styles.reset + styles.list + styles.overflow, styles.overflow)+'<hr>'+backButton;
makeAndSendMenu(contents, script_name + ' Timer Config', 'gm');
},
sendConfigMacroMenu = () => {
let runMacroButton = makeButton(state[state_name].config.macro.run_macro, '!' + state[state_name].config.command + ' config macro run_macro|'+!state[state_name].config.macro.run_macro, styles.button + styles.float.right),
macroNameButton = makeButton(state[state_name].config.macro.macro_name, '!' + state[state_name].config.command + ' config macro macro_name|?{Macro Name|'+state[state_name].config.macro.macro_name+'}', styles.button + styles.float.right),
backButton = makeButton('< Back', '!'+state[state_name].config.command + ' config', styles.button + styles.fullWidth),
listItems = [
'<span style="'+styles.float.left+'">Run Macro:</span> ' + runMacroButton,
'<span style="'+styles.float.left+'">Macro Name:</span> ' + macroNameButton,
];
let contents = '<p>A macro with the right name should be in the characters ability list.</p>'+makeList(listItems, styles.reset + styles.list + styles.overflow, styles.overflow)+'<hr>'+backButton;
makeAndSendMenu(contents, script_name + ' Macro Config', 'gm');
},
sendMenu = () => {
let nextButton = makeButton('Next Turn', '!' + state[state_name].config.command + ' next b', styles.button),
prevButton = makeButton('Prev. Turn', '!' + state[state_name].config.command + ' prev b', styles.button),
startCombatButton = makeButton('Start Combat', '!' + state[state_name].config.command + ' start b', styles.button),
stopCombatButton = makeButton('Stop Combat', '!' + state[state_name].config.command + ' stop b', styles.button),
pauseTimerTitle = (paused) ? 'Start Timer' : 'Pause Timer',
pauseTimerButton = makeButton(pauseTimerTitle, '!' + state[state_name].config.command + ' pt b', styles.button),
stopTimerButton = makeButton('Stop Timer', '!' + state[state_name].config.command + ' st b', styles.button),
addConditionButton = makeButton('Add Condition', '!' + state[state_name].config.command + ' add ?{Condition} ?{Duration}', styles.button),
removeConditionButton = makeButton('Remove Condition', '!' + state[state_name].config.command + ' remove ?{Condition}', styles.button),
resetConditionsButton = makeButton('Reset Conditions', '!'+state[state_name].config.command + ' reset conditions', styles.button),
favoritesButton = makeButton('Favorite Conditions', '!'+state[state_name].config.command + ' favorites', styles.button),
contents;
if(inFight()){
contents = ' \
'+nextButton+prevButton+'<br> \
'+pauseTimerButton+stopTimerButton+' \
<hr> \
<b>With Selected:</b><br> \
'+addConditionButton+'<br> \
'+removeConditionButton+' \
<hr> \
'+favoritesButton+' \
<hr> \
'+stopCombatButton+'<br> \
'+resetConditionsButton;
}else{
contents = ' \
'+startCombatButton+' \
<hr> \
'+favoritesButton;
}
makeAndSendMenu(contents, script_name + ' Menu', 'gm');
},
sendHelpMenu = () => {
let configButton = makeButton('Config', '!' + state[state_name].config.command + ' config', styles.button + styles.fullWidth);
let listItems = [
'<span style="'+styles.underline+'">!'+state[state_name].config.command+' help</span> - Shows this menu.',
'<span style="'+styles.underline+'">!'+state[state_name].config.command+' config</span> - Shows the configuration menu.'
];
let contents = '<b>Commands:</b>'+makeList(listItems, styles.reset + styles.list)+'<hr>'+configButton;
makeAndSendMenu(contents, script_name + ' Help', 'gm');
},
makeAndSendMenu = (contents, title, whisper) => {
title = (title && title != '') ? makeTitle(title) : '';
whisper = (whisper && whisper !== '') ? '/w ' + whisper + ' ' : '';
sendChat(script_name, whisper + '<div style="'+styles.menu+styles.overflow+'">'+title+contents+'</div>', null, {noarchive:true});
},
makeTitle = (title) => {
return '<h3 style="margin-bottom: 10px;">'+title+'</h3>';
},
makeButton = (title, href, style) => {
return '<a style="'+style+'" href="'+href+'">'+title+'</a>';
},
makeList = (items, listStyle, itemStyle) => {
let list = '<ul style="'+listStyle+'">';
items.forEach((item) => {
list += '<li style="'+itemStyle+'">'+item+'</li>';
});
list += '</ul>';
return list;
},
checkStatusInfo = () => {
if(typeof StatusInfo === 'undefined'){
makeAndSendMenu('Consider installing '+makeButton('StatusInfo', 'https://github.com/RobinKuiper/Roll20APIScripts/tree/master/StatusInfo', styles.textButton)+' it works great with this script.', '', 'gm');
return;
}
if(!StatusInfo.version || StatusInfo.version !== "0.3.8"){
makeAndSendMenu('Please update '+makeButton('StatusInfo', 'https://github.com/RobinKuiper/Roll20APIScripts/tree/master/StatusInfo', styles.textButton)+' to the latest version.', '', 'gm');
return;
}
extensions.StatusInfo = true;
},
checkInstall = () => {
if(!_.has(state, state_name)){
state[state_name] = state[state_name] || {};
}
setDefaults();
checkStatusInfo();
log(script_name + ' Ready! Command: !'+state[state_name].config.command);
if(state[state_name].config.debug){
makeAndSendMenu(script_name + ' Ready! Debug On.', '', 'gm');
}
},
handeIniativePageChange = (obj,prev) => {
if(state[state_name].config.close_stop && (obj.get('initiativepage') !== prev.initiativepage && !obj.get('initiativepage'))){
stopCombat();
}
},
observeTokenChange = function(handler){
if(handler && _.isFunction(handler)){
observers.tokenChange.push(handler);
}
},
notifyObservers = function(event,obj,prev){
_.each(observers[event],function(handler){
handler(obj,prev);
});
},
registerEventHandlers = () => {
on('chat:message', handleInput);
on('change:campaign:turnorder', handleTurnorderChange);
on('change:campaign:initiativepage', handeIniativePageChange);
on('change:graphic:top', handleGraphicMovement);
on('change:graphic:left', handleGraphicMovement);
on('change:graphic:layer', handleGraphicMovement);
on('change:graphic:statusmarkers', handleStatusMarkerChange);
if('undefined' !== typeof TokenMod && TokenMod.ObserveTokenChange){
TokenMod.ObserveTokenChange(function(obj,prev){
handleStatusMarkerChange(obj,prev);
});
}
},
setDefaults = (reset) => {
const defaults = {
config: {
command: 'ct',
marker_img: 'https://s3.amazonaws.com/files.d20.io/images/52550079/U-3U950B3wk_KRtspSPyuw/thumb.png?1524507826',
initiative_attribute_name: 'initiative_bonus',
close_stop: true,
pull: true,
turnorder: {
throw_initiative: true,
show_initiative_roll: false,
auto_sort: true,
reroll_ini_round: false,
skip_custom: true,
},
timer: {
use_timer: true,
time: 120,
auto_skip: true,
chat_timer: true,
token_timer: true,
token_font: 'Candal',
token_font_size: 16,
token_font_color: 'rgb(255, 0, 0)'
},
announcements: {
announce_conditions: false,
announce_turn: true,
whisper_turn_gm: false,
announce_round: true,
handleLongName: true,
use_fx: false,
fx_type: 'nova-holy'
},
macro: {
run_macro: true,
macro_name: 'CT_TURN'
}
},
conditions: {},
favorites: {}
};
if(!state[state_name].config){
state[state_name].config = defaults.config;
}else{
if(!state[state_name].config.hasOwnProperty('command')){
state[state_name].config.command = defaults.config.command;
}
if(!state[state_name].config.hasOwnProperty('marker_img')){
state[state_name].config.marker_img = defaults.config.marker_img;
}
if(!state[state_name].config.hasOwnProperty('initiative_attribute_name')){
state[state_name].config.initiative_attribute_name = defaults.config.initiative_attribute_name;
}
if(!state[state_name].config.hasOwnProperty('close_stop')){
state[state_name].config.close_stop = defaults.config.close_stop;
}
if(!state[state_name].config.hasOwnProperty('pull')){
state[state_name].config.pull = defaults.config.pull;
}
if(!state[state_name].config.hasOwnProperty('turnorder')){
state[state_name].config.turnorder = defaults.config.turnorder;
}else{
if(!state[state_name].config.turnorder.hasOwnProperty('skip_custom')){
state[state_name].config.turnorder.skip_custom = defaults.config.turnorder.skip_custom;
}
if(!state[state_name].config.turnorder.hasOwnProperty('throw_initiative')){
state[state_name].config.turnorder.throw_initiative = defaults.config.turnorder.throw_initiative;
}
if(!state[state_name].config.turnorder.hasOwnProperty('auto_sort')){
state[state_name].config.turnorder.auto_sort = defaults.config.turnorder.auto_sort;
}
if(!state[state_name].config.hasOwnProperty('reroll_ini_round')){
state[state_name].config.turnorder.reroll_ini_round = defaults.config.turnorder.reroll_ini_round;
}
}
if(!state[state_name].config.hasOwnProperty('timer')){
state[state_name].config.timer = defaults.config.timer;
}else{
if(!state[state_name].config.timer.hasOwnProperty('use_timer')){
state[state_name].config.timer.use_timer = defaults.config.timer.use_timer;
}
if(!state[state_name].config.timer.hasOwnProperty('time')){
state[state_name].config.timer.time = defaults.config.timer.time;
}
if(!state[state_name].config.timer.hasOwnProperty('auto_skip')){
state[state_name].config.timer.auto_skip = defaults.config.timer.auto_skip;
}
if(!state[state_name].config.timer.hasOwnProperty('chat_timer')){
state[state_name].config.timer.chat_timer = defaults.config.timer.chat_timer;
}
if(!state[state_name].config.timer.hasOwnProperty('token_timer')){
state[state_name].config.timer.token_timer = defaults.config.timer.token_timer;
}
if(!state[state_name].config.timer.hasOwnProperty('token_font')){
state[state_name].config.timer.token_font = defaults.config.timer.token_font;
}
if(!state[state_name].config.timer.hasOwnProperty('token_font_size')){
state[state_name].config.timer.token_font_size = defaults.config.timer.token_font_size;
}
if(!state[state_name].config.timer.hasOwnProperty('token_font_color')){
state[state_name].config.timer.token_font_color = defaults.config.timer.token_font_color;
}
}
if(!state[state_name].config.hasOwnProperty('announcements')){
state[state_name].config.announcements = defaults.config.announcements;
}else{
if(!state[state_name].config.announcements.hasOwnProperty('announce_turn')){
state[state_name].config.announcements.announce_turn = defaults.config.announcements.announce_turn;
}
if(!state[state_name].config.announcements.hasOwnProperty('whisper_turn_gm')){
state[state_name].config.announcements.whisper_turn_gm = defaults.config.announcements.whisper_turn_gm;
}
if(!state[state_name].config.announcements.hasOwnProperty('announce_round')){
state[state_name].config.announcements.announce_round = defaults.config.announcements.announce_round;
}
if(!state[state_name].config.announcements.hasOwnProperty('announce_conditions')){
state[state_name].config.announcements.announce_conditions = defaults.config.announcements.announce_conditions;
}
if(!state[state_name].config.announcements.hasOwnProperty('handleLongName')){
state[state_name].config.announcements.handleLongName = defaults.config.announcements.handleLongName;
}
if(!state[state_name].config.announcements.hasOwnProperty('use_fx')){
state[state_name].config.announcements.use_fx = defaults.config.announcements.use_fx;
}
if(!state[state_name].config.announcements.hasOwnProperty('fx_type')){
state[state_name].config.announcements.fx_type = defaults.config.announcements.fx_type;
}
}
if(!state[state_name].config.hasOwnProperty('macro')){
state[state_name].config.macro = defaults.config.macro;
}else{
if(!state[state_name].config.macro.hasOwnProperty('run_macro')){
state[state_name].config.macro.run_macro = defaults.config.macro.run_macro;
}
if(!state[state_name].config.macro.hasOwnProperty('macro_name')){
state[state_name].config.macro.macro_name = defaults.config.macro.macro_name;
}
}
}
if(!state[state_name].hasOwnProperty('conditions')){
state[state_name].conditions = defaults.conditions;
}
if(!state[state_name].hasOwnProperty('favorites')){
state[state_name].favorites = defaults.favorites;
}
if(!state[state_name].config.hasOwnProperty('firsttime') && !reset){
sendConfigMenu(true);
state[state_name].config.firsttime = false;
}
};
return {
CheckInstall: checkInstall,
RegisterEventHandlers: registerEventHandlers,
ObserveTokenChange: observeTokenChange
};
})();
on('ready',function() {
'use strict';
CombatTracker.CheckInstall();
CombatTracker.RegisterEventHandlers();
});
/*
conditions = {
54235346534564: [
{ name: 'prone', duration: '1' }
]
}
*/
|
angular.module('profile.controller', [])
.controller('ProfileController', function(ProfileServices, AuthServices, GoalServices, $location){
var profile = this;
profile.loadProfile = function() { //Loads the user's profile data via ProfileServices
ProfileServices.getProfileData()
.then(function(resp){
profile.limitClicked = false;
profile.savingsClicked = false;
profile.allocateClicked = false;
profile.newGoalClicked = false;
profile.showTotalSavings = false;
profile.total_savings = resp.total_savings;
profile.email = resp.email;
profile.full_name = resp.full_name;
profile.monthly_limit = resp.monthly_limit;
profile.savings_goal = resp.savings_goal;
GoalServices.getGoals()
.then(function(resp){
profile.goals = resp.data;
});
}, function(error){
throw error;
});
};
profile.changeLimit = function() {
profile.limitClicked = !profile.limitClicked;
};
profile.submitNewLimit = function(newLimit){ //Allows the user to update their monthly spending limit via ProfileServices
newLimit = newLimit || profile.monthly_limit;
ProfileServices.updateLimit(newLimit)
.then(function(resp){
profile.loadProfile();
}, function(error){
throw error;
});
};
profile.changeTarget = function() {
profile.targetClicked = !profile.targetClicked;
};
profile.submitNewSavingsTarget = function(newSavings){ //Allows the user to update their savings target via ProfileServices
newSavings = newSavings || profile.savings_goal;
ProfileServices.updateSavingsTarget(newSavings)
.then(function(resp){
profile.changeTarget();
profile.loadProfile();
}, function(error){
throw error;
});
};
profile.toggleNewGoal = function(){
profile.newGoalClicked = !profile.newGoalClicked;
};
profile.submitNewGoal = function(goal){ //Allows the user to input a new goal via GoalServices
profile.toggleNewGoal();
var newGoal = {
name: goal.name,
amount: goal.amount,
category: goal.category,
notes: goal.notes
};
GoalServices.addNewGoal(newGoal)
.then(function(resp){
profile.goals.push(resp.data);
goal.name = '';
goal.amount = '';
goal.category = '';
goal.notes = '';
});
};
profile.toggleTotalSavings = function(){
profile.showTotalSavings = !profile.showTotalSavings;
};
profile.submitNewTotalSavings = function(amount){ //Allows the user to update their total savings via ProfileServices
amount = amount || profile.total_savings;
ProfileServices.updateTotalSavings(amount)
.then(function(resp){
profile.total_savings = amount;
profile.toggleTotalSavings();
});
};
profile.completeGoal = function(idx, id){ //Allows the user to acquire a current goal via GoalServices
profile.goals.splice(idx, 1);
//TODO call service for complete goal
GoalServices.completeGoal(id)
.then(function(){
$location.path('main/expenses');
});
};
profile.deleteGoal = function(idx, id){ //Allows the user to delete a current goal via GoalServices
profile.goals.splice(idx, 1);
//TODO call service for complete goal
GoalServices.deleteGoal(id);
};
profile.showNotes = function(notes){
profile.currentNote = notes;
};
profile.goalUpdateAmount = null;
profile.goalUpdateId = null;
profile.addMoneyToGoal = function(){ //Allows the user to add money towards one of their goals via GoalServices
GoalServices.addMoneyToGoal(profile.goalUpdateAmount, profile.goalUpdateId)
.then(function(){
profile.loadProfile();
});
};
profile.subtractMoneyFromGoal = function(){ //Allows the user to subtract money from one of their goals via GoalServices
GoalServices.subtractMoneyFromGoal(profile.goalUpdateAmount, profile.goalUpdateId)
.then(function(){
profile.loadProfile();
});
};
profile.makeActiveId = function(id){
profile.goalUpdateId = id;
};
profile.loadProfile(); //Renders all the profile data for the user
});
|
//
for (let aaa = 5; aaa < 10; aaa += 1) {
//
|
'use strict';
import config from '../config';
import changed from 'gulp-changed';
import gulp from 'gulp';
import browserSync from 'browser-sync';
gulp.task('fonts', function() {
return gulp.src(config.fonts.src)
.pipe(changed(config.fonts.dest)) // Ignore unchanged files
.pipe(gulp.dest(config.fonts.dest))
.pipe(browserSync.stream({once: true}));
});
|
'use strict';
var controllersModule = require('./_index');
/**
* @ngInject
*/
function MainController($scope, $http, $cookieStore) {
$scope.isAuthenticated = function () {
return (angular.isDefined($cookieStore.get('user')));
};
}
controllersModule.controller('MainController', MainController);
|
/**
A sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive elements is the same.
For example, these are arithmetic sequence:
1, 3, 5, 7, 9
7, 7, 7, 7
3, -1, -5, -9
The following sequence is not arithmetic.
1, 1, 2, 5, 7
A zero-indexed array A consisting of N numbers is given. A slice of that array is any pair of integers (P, Q) such that 0 <= P < Q < N.
A slice (P, Q) of array A is called arithmetic if the sequence:
A[P], A[p + 1], ..., A[Q - 1], A[Q] is arithmetic. In particular, this means that P + 1 < Q.
The function should return the number of arithmetic slices in the array A.
Example:
A = [1, 2, 3, 4]
return: 3, for 3 arithmetic slices in A: [1, 2, 3], [2, 3, 4] and [1, 2, 3, 4] itself.
*/
/**
* @param {number[]} A
* @return {number}
*/
var numberOfArithmeticSlices = function(A) {
var len = A.length;
if(len < 3) {
return 0;
}
// dp[i] means the number of arithmetic slices ending with A[i]
var dp = new Array(len).fill(0);
var res = 0;
for(let i = 2; i < len; i++){
/**
if A[i-2], A[i-1], A[i] are arithmetic, then the number of arithmetic slices
ending with A[i] (dp[i]) equals to:
the number of arithmetic slices ending with A[i-1] (dp[i-1], all these arithmetic
slices appending A[i] are also arithmetic) + A[i-2], A[i-1], A[i] (a brand new arithmetic slice)
it is how dp[i] = dp[i-1] + 1 comes
*/
if(A[i] - A[i-1] === A[i-1] - A[i-2]){
dp[i] = dp[i-1]+1;
}
res += dp[i];
}
return res;
};
|
describe('Magnificent Triumph', function() {
integration(function() {
describe('Magnificent Triumph\'s ability', function() {
beforeEach(function() {
this.setupTest({
phase: 'conflict',
player1: {
inPlay: ['mirumoto-raitsugu','doomed-shugenja'],
hand: ['magnificent-triumph']
},
player2: {
inPlay: ['doji-whisperer', 'doji-challenger'],
hand: ['banzai']
}
});
this.mirumotoRaitsugu = this.player1.findCardByName('mirumoto-raitsugu');
this.doomedShugenja = this.player1.findCardByName('doomed-shugenja');
this.magnificentTriumph = this.player1.findCardByName('magnificent-triumph');
this.dojiWhisperer = this.player2.findCardByName('doji-whisperer');
this.dojiChallenger = this.player2.findCardByName('doji-challenger');
this.banzai = this.player2.findCardByName('banzai');
this.noMoreActions();
this.initiateConflict({
attackers: [this.mirumotoRaitsugu, this.doomedShugenja],
defenders: [this.dojiWhisperer, this.dojiChallenger]
});
this.player2.pass();
this.player1.clickCard(this.mirumotoRaitsugu);
this.player1.clickCard(this.dojiWhisperer);
this.player1.clickPrompt('5');
this.player2.clickPrompt('1');
});
it('should allow you to select characters that have won a duel', function() {
this.player2.pass();
this.player1.clickCard(this.magnificentTriumph);
expect(this.player1).toHavePrompt('Magnificent Triumph');
expect(this.player1).toBeAbleToSelect(this.mirumotoRaitsugu);
expect(this.player1).not.toBeAbleToSelect(this.doomedShugenja);
expect(this.player1).not.toBeAbleToSelect(this.dojiChallenger);
});
it('should give the target +2/+2', function() {
let militarySkill = this.mirumotoRaitsugu.getMilitarySkill();
let politicalSkill = this.mirumotoRaitsugu.getPoliticalSkill();
this.player2.pass();
this.player1.clickCard(this.magnificentTriumph);
this.player1.clickCard(this.mirumotoRaitsugu);
expect(this.mirumotoRaitsugu.getMilitarySkill()).toBe(militarySkill + 2);
expect(this.mirumotoRaitsugu.getPoliticalSkill()).toBe(politicalSkill + 2);
});
it('should make the target immune to opponent\'s events', function() {
this.player2.pass();
this.player1.clickCard(this.magnificentTriumph);
this.player1.clickCard(this.mirumotoRaitsugu);
this.player2.clickCard(this.banzai);
expect(this.player2).not.toBeAbleToSelect(this.mirumotoRaitsugu);
expect(this.player2).toBeAbleToSelect(this.doomedShugenja);
expect(this.player2).toBeAbleToSelect(this.dojiChallenger);
});
it('should only last to the end of the conflict', function() {
let militarySkill = this.mirumotoRaitsugu.getMilitarySkill();
let politicalSkill = this.mirumotoRaitsugu.getPoliticalSkill();
this.player2.pass();
this.player1.clickCard(this.magnificentTriumph);
this.player1.clickCard(this.mirumotoRaitsugu);
this.player2.pass();
this.player1.pass();
this.player1.clickPrompt('Yes');
this.player1.clickPrompt('Don\'t Resolve');
expect(this.mirumotoRaitsugu.getMilitarySkill()).toBe(militarySkill);
expect(this.mirumotoRaitsugu.getPoliticalSkill()).toBe(politicalSkill);
});
});
});
});
|
define([
'app/models/repos_bundle/repo',
'app/collections/base'
], function(Repo, Base)
{
var exports = Base.extend({
model: Repo,
url: function() {
if (this.params.user != null) {
return '/users/:user/repos';
} else {
return '/repositories';
}
}
});
exports.id = 'repos_bundle/repos';
return exports;
});
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 8.12.1-1_4
description: >
Properties - [[HasOwnProperty]] (non-writable, non-configurable,
non-enumerable own value property)
includes: [runTestCase.js]
---*/
function testcase() {
var o = {};
Object.defineProperty(o, "foo", {value: 42});
return o.hasOwnProperty("foo");
}
runTestCase(testcase);
|
/*******************************************************************************
# ____ __ __ _ _____ _ _ #
# / __ \ \ \ / / | | / ____| | | | #
# | | | |_ __ ___ _ __ \ /\ / /__| |__ | | __| | ___ | |__ ___ #
# | | | | '_ \ / _ \ '_ \ \/ \/ / _ \ '_ \| | |_ | |/ _ \| '_ \ / _ \ #
# | |__| | |_) | __/ | | \ /\ / __/ |_) | |__| | | (_) | |_) | __/ #
# \____/| .__/ \___|_| |_|\/ \/ \___|_.__/ \_____|_|\___/|_.__/ \___| #
# | | #
# |_| _____ _____ _ __ #
# / ____| __ \| |/ / #
# | (___ | | | | ' / #
# \___ \| | | | < #
# ____) | |__| | . \ #
# |_____/|_____/|_|\_\ #
# #
# (c) 2010-2011 by #
# University of Applied Sciences Northwestern Switzerland #
# Institute of Geomatics Engineering #
# martin.christen@fhnw.ch #
********************************************************************************
* Licensed under MIT License. Read the file LICENSE for more information *
*******************************************************************************/
goog.provide('owg.GoogleImageLayer');
goog.require('owg.GlobeUtils');
goog.require('owg.OSMImageLayer');
goog.require('owg.MercatorQuadtree');
goog.require('owg.Texture');
//------------------------------------------------------------------------------
/**
* @constructor
* @description Image Layer for Google Maps
* @author Feng Lei, fenglgis@gmail.com
*/
function GoogleImageLayer()
{
this.servers = null;
this.layer = null;
this.quadtree = new MercatorQuadtree();
this.curserver = 0;
this.sub = 0;
this.subs = ["Galile", "Galil", "Gali", "Gal", "Ga", "G"];
//---------------------------------------------------------------------------
this.Ready = function()
{
return true;
}
//---------------------------------------------------------------------------
this.Failed = function()
{
return false;
}
//---------------------------------------------------------------------------
this.RequestTile = function(engine, quadcode, layer, cbfReady, cbfFailed, caller)
{
var coords = new Array(4);
var res = {};
this.quadtree.QuadKeyToTileCoord(quadcode, res);
//http://khm1.google.com/kh/v=89&x=3&y=5&z=4&s=Galile
var sFilename = this.servers[this.curserver] + "/kh/v=101&x=" +
res.x + "&y=" +
res.y + "&z=" +
res.lod + "&s=" + this.subs[this.sub];
this.sub++;
if (this.sub == 5) this.sub = 0;
var ImageTexture = new Texture(engine);
ImageTexture.quadcode = quadcode; // store quadcode in texture object
ImageTexture.layer = layer;
ImageTexture.cbfReady = cbfReady; // store the ready callback in texture object
ImageTexture.cbfFailed = cbfFailed; // store the failure callback in texture object
ImageTexture.caller = caller;
ImageTexture.loadTexture(sFilename, _cbOSMTileReady, _cbOSMTileFailed, true);
this.curserver++;
if (this.curserver>=this.servers.length)
{
this.curserver = 0;
}
};
//---------------------------------------------------------------------------
this.GetMinLod = function()
{
return 0;
}
//---------------------------------------------------------------------------
this.GetMaxLod = function()
{
return 19;
}
//---------------------------------------------------------------------------
this.Contains = function(quadcode)
{
if (quadcode.length<20)
{
return true;
}
return false;
}
//---------------------------------------------------------------------------
this.Setup = function(serverlist)
{
// Please respect: http://wiki.openstreetmap.org/wiki/Tile_Usage_Policy
// serverlist:
// ["http://a.tile.openstreetmap.org", "http://b.tile.openstreetmap.org", "http://c.tile.openstreetmap.org" ]
// or your own tileserver(s).
//
this.servers = serverlist;
}
}
GoogleImageLayer.prototype = new OSMImageLayer();
//------------------------------------------------------------------------------
|
import Helper from '@ember/component/helper';
import md5 from 'blueimp-md5';
import {isEmpty} from '@ember/utils';
import {inject as service} from '@ember/service';
export default Helper.extend({
config: service(),
compute([email], {size = 180, d = 'blank'}/*, hash*/) {
if (!this.get('config.useGravatar')) {
return;
}
if (!email || isEmpty(email)) {
return;
}
return `https://www.gravatar.com/avatar/${md5(email)}?s=${size}&d=${d}`;
}
});
|
(function() {
var program = chinachu.getProgramById(request.param.id, data.recording);
if (program === null) return response.error(404);
if (!data.status.feature.streamer) return response.error(403);
if (!program.pid) return response.error(503);
if (program.tuner && program.tuner.isScrambling) return response.error(409);
if (!fs.existsSync(program.recorded)) return response.error(410);
if (request.query.debug) {
util.log(JSON.stringify(request.headers, null, ' '));
}
switch (request.type) {
case 'xspf':
response.setHeader('content-disposition', 'attachment; filename="' + program.id + '.xspf"');
response.head(200);
var ext = request.query.ext || 'm2ts';
var prefix = request.query.prefix || '';
var target = prefix + 'watch.' + ext + url.parse(request.url).search;
response.write('<?xml version="1.0" encoding="UTF-8"?>\n');
response.write('<playlist version="1" xmlns="http://xspf.org/ns/0/">\n');
response.write('<trackList>\n');
response.write('<track>\n<location>' + target.replace(/&/g, '&') + '</location>\n');
response.write('<title>' + program.title + '</title>\n</track>\n');
response.write('</trackList>\n');
response.write('</playlist>\n');
response.end();
return;
case 'm2ts':
case 'webm':
case 'mp4':
response.head(200);
util.log('[streamer] streaming: ' + program.recorded);
var d = {
ss : request.query.ss || null, //start(seconds)
t : request.query.t || null,//duration(seconds)
s : request.query.s || null,//size(WxH)
f : request.query.f || null,//format
'c:v': request.query['c:v'] || null,//vcodec
'c:a': request.query['c:a'] || null,//acodec
'b:v': request.query['b:v'] || null,//bitrate
'b:a': request.query['b:a'] || null,//ab
ar : request.query.ar || null,//ar(Hz)
r : request.query.r || null//rate(fps)
};
switch (request.type) {
case 'm2ts':
d.f = 'mpegts';
break;
case 'mp4':
d.f = 'mp4';
d['c:v'] = d['c:v'] || 'libx264';
d['c:a'] = d['c:a'] || 'libfdk_aac';
break;
case 'webm':
d.f = 'webm';
d['c:v'] = d['c:v'] || 'libvpx';
d['c:a'] = d['c:a'] || 'libvorbis';
break;
}
var args = [];
if (!request.query.debug) args.push('-v', '0');
if (d.ss) args.push('-ss', (parseInt(d.ss, 10) - 1) + '');
args.push('-re', '-i', (!d.ss) ? 'pipe:0' : program.recorded);
args.push('-ss', '1');
if (d.t) { args.push('-t', d.t); }
args.push('-threads', 'auto');
if (d['c:v']) args.push('-c:v', d['c:v']);
if (d['c:a']) args.push('-c:a', d['c:a']);
if (d.s) args.push('-s', d.s);
if (d.r) args.push('-r', d.r);
if (d.ar) args.push('-ar', d.ar);
if (!d.s || d.s === '1920x1080') {
args.push('-filter:v', 'yadif');
}
if (d['b:v']) args.push('-b:v', d['b:v']);
if (d['b:a']) args.push('-b:a', d['b:a']);
if (d['c:v'] === 'libx264') {
args.push('-vsync', '1');
args.push('-profile:v', 'baseline');
args.push('-level', '31');
args.push('-preset', 'ultrafast');
}
if (d['c:v'] === 'libvpx') {
args.push('-deadline', 'realtime');
}
if (d.f === 'mp4') {
args.push('-movflags', 'frag_keyframe+empty_moov+faststart');
}
args.push('-y', '-f', d.f, 'pipe:1');
if ((!d.ss) && (d['c:v'] === 'copy') && (d['c:a'] === 'copy') && (d.f === 'mpegts')) {
var tailf = child_process.spawn('tail', ['-f', '-c', '61440', program.recorded]);// 1KB
children.push(tailf.pid);
tailf.stdout.pipe(response);
tailf.on('exit', function(code) {
response.end();
tailf = null;
});
request.on('close', function() {
if (tailf) {
tailf.stdout.removeAllListeners('data');
tailf.stderr.removeAllListeners('data');
tailf.kill('SIGKILL');
}
});
} else {
var ffmpeg = child_process.spawn('ffmpeg', args);
children.push(ffmpeg.pid);
util.log('SPAWN: ffmpeg ' + args.join(' ') + ' (pid=' + ffmpeg.pid + ')');
if (!d.ss) {
var tailf = child_process.spawn('tail', ['-f', program.recorded]);
children.push(tailf.pid);
tailf.stdout.pipe(ffmpeg.stdin);
tailf.on('exit', function(code) {
if (ffmpeg) ffmpeg.kill('SIGKILL');
tailf = null;
});
}
ffmpeg.stdout.pipe(response);
ffmpeg.stderr.on('data', function(d) {
util.log(d);
});
ffmpeg.on('exit', function(code) {
if (tailf) {
tailf.stdout.removeAllListeners('data');
tailf.stderr.removeAllListeners('data');
tailf.kill('SIGKILL');
tailf = null;
} else {
ffmpeg = null;
}
response.end();
});
request.on('close', function() {
if (tailf) {
tailf.stdout.removeAllListeners('data');
tailf.stderr.removeAllListeners('data');
tailf.kill('SIGKILL');
} else {
ffmpeg.stdout.removeAllListeners('data');
ffmpeg.stderr.removeAllListeners('data');
ffmpeg.kill('SIGKILL');
ffmpeg = null;
}
});
}
return;
}//<--switch
})();
|
'use strict';
/**
* @ngdoc function
* @name beetlApp.controller:UserListCtrl
* @description
* # UserListCtrl
* Controller of the beetlApp
*/
angular.module('beetlApp').controller('UserListCtrl', ['$scope', '$state', '$stateParams', 'apiHandler', function($scope, $state, $stateParams, apiHandler) {
// Prequisites
$scope.users = {};
/**
* The function will initialize the user list
*/
var initializeUserList = function() {
$scope.users = [];
apiHandler.getUserList()
.success(function(res) {
$scope.users = res;
})
.error(function(err) {
$state.go('errorPage', { errorId: 1, msg: err });
});
};
// Initialize on controller loading
initializeUserList();
/**
* The function will delete the given user
*/
$scope.deleteUser = function(id) {
apiHandler.deleteUser(id)
.success(function() {
initializeUserList();
})
.error(function(err) {
$state.go('errorPage', { errorId: 4, msg: err });
});
};
/**
* The function will create a new user object
*/
$scope.createUser = function() {
apiHandler.setUser()
.success(function(res) {
$state.go('userDetail', { id: res.id });
})
.error(function(err) {
$state.go('errorPage', { errorId: 3, msg: err });
});
};
}]); |
/* eslint-disable */
(function () {
'use strict'
var root = this
if (typeof root.GOVUK === 'undefined') { root.GOVUK = {} }
/*
Cookie methods
==============
Usage:
Setting a cookie:
GOVUK.cookie('hobnob', 'tasty', { days: 30 });
Reading a cookie:
GOVUK.cookie('hobnob');
Deleting a cookie:
GOVUK.cookie('hobnob', null);
*/
GOVUK.cookie = function (name, value, options) {
if (typeof value !== 'undefined') {
if (value === false || value === null) {
return GOVUK.setCookie(name, '', { days: -1 })
} else {
return GOVUK.setCookie(name, value, options)
}
} else {
return GOVUK.getCookie(name)
}
}
GOVUK.setCookie = function (name, value, options) {
if (typeof options === 'undefined') {
options = {}
}
var cookieString = name + '=' + value + '; path=/'
if (options.days) {
var date = new Date()
date.setTime(date.getTime() + (options.days * 24 * 60 * 60 * 1000))
cookieString = cookieString + '; expires=' + date.toGMTString()
}
if (document.location.protocol === 'https:') {
cookieString = cookieString + '; Secure'
}
document.cookie = cookieString
}
GOVUK.getCookie = function (name) {
var nameEQ = name + '='
var cookies = document.cookie.split(';')
for (var i = 0, len = cookies.length; i < len; i++) {
var cookie = cookies[i]
while (cookie.charAt(0) === ' ') {
cookie = cookie.substring(1, cookie.length)
}
if (cookie.indexOf(nameEQ) === 0) {
return decodeURIComponent(cookie.substring(nameEQ.length))
}
}
return null
}
}).call(this);
(function () {
'use strict'
var root = this
if (typeof root.GOVUK === 'undefined') { root.GOVUK = {} }
GOVUK.addCookieMessage = function () {
var message = document.getElementById('global-cookie-message')
var hasCookieMessage = (message && GOVUK.cookie('seen_cookie_message') === null)
if (hasCookieMessage) {
message.style.display = 'block'
GOVUK.cookie('seen_cookie_message', 'yes', { days: 28 })
}
}
}).call(this);
(function () {
'use strict'
// add cookie message
if (window.GOVUK && GOVUK.addCookieMessage) {
GOVUK.addCookieMessage()
}
// header navigation toggle
if (document.querySelectorAll && document.addEventListener) {
var els = document.querySelectorAll('.js-header-toggle')
var i
var _i
for (i = 0, _i = els.length; i < _i; i++) {
els[i].addEventListener('click', function (e) {
e.preventDefault()
var target = document.getElementById(this.getAttribute('href').substr(1))
var targetClass = target.getAttribute('class') || ''
var sourceClass = this.getAttribute('class') || ''
if (targetClass.indexOf('js-visible') !== -1) {
target.setAttribute('class', targetClass.replace(/(^|\s)js-visible(\s|$)/, ''))
} else {
target.setAttribute('class', targetClass + ' js-visible')
}
if (sourceClass.indexOf('js-hidden') !== -1) {
this.setAttribute('class', sourceClass.replace(/(^|\s)js-hidden(\s|$)/, ''))
} else {
this.setAttribute('class', sourceClass + ' js-hidden')
}
})
}
}
}).call(this)
|
function countOccurances(str, key) {
let matches = str
.match(new RegExp(`\\b${key}\\b`, 'gi'));
return matches === null ? 0 : matches.length
}
console.log(countOccurances('The waterfall was so high, that the child couldn’t see its peak.', 'the'));
console.log(countOccurances('How do you plan on achieving that? How? How can you even think of that?', 'how'));
console.log(countOccurances('There was one. Therefore I bought it. I wouldn’t buy it otherwise.', 'there'));
console.log(countOccurances('The waterfall was so high, that the child couldn’t see its peak.', 'them'));
|
'use strict';
module.exports = {
write: true,
prefix: '^',
test: [
'test',
'benchmark',
],
devdep: [
'egg',
'egg-ci',
'egg-bin',
'autod',
'eslint',
'eslint-config-egg',
'supertest',
'webstorm-disable-index',
],
exclude: [
'./test/fixtures',
'./docs',
'./coverage',
],
registry: 'https://r.cnpmjs.org',
};
|
import { AppRegistry } from 'react-native';
import TravelgramApp from './js';
AppRegistry.registerComponent('TravelgramApp', () => TravelgramApp);
|
import Utils from './Utils';
import testIDs from '../playground/src/testIDs';
const { elementById } = Utils;
describe(':ios: custom transition', () => {
beforeEach(async () => {
await device.launchApp({ newInstance: true });
});
test('sanity', async () => {
await elementById(testIDs.PUSH_OPTIONS_BUTTON).tap();
await elementById(testIDs.CUSTOM_TRANSITION_BUTTON).tap();
await expect(element(by.id('shared_image1'))).toExist();
await element(by.id('shared_image1')).tap();
await expect(element(by.id('shared_image2'))).toExist();
await element(by.id('shared_image2')).tap();
await expect(element(by.id('shared_image1'))).toExist();
});
});
|
var fs = require('fs'),
util = require('util');
function Logger(filename) {
this.filename = filename;
}
Logger.prototype.init = function init() {
try {
fs.mkdirSync('logs');
}
catch (e) {
if (e['code'] != 'EEXIST') {
throw e;
}
}
var filename = 'logs/' + this.filename;
try {
this.stream = fs.createWriteStream(filename, {flags: 'a'});
}
catch (e) {
console.log('LOGGER: Could not open file %s for writing! %s', filename, e);
return false;
}
return this;
};
Logger.prototype.write = function write(data) {
if (!this.stream) {
console.log('LOGGER: Attempted write when stream does not exist.');
return false;
}
//This is an async call without a callback - assumes that all writes will eventually make it, if there is for
// some reason a backlog of writes (there shouldn't be)
this.stream.write(data + "\n");
return this;
};
/**
* Write to steam with a timestamp prepending the message
*
* @param data
*/
Logger.prototype.writeWithStamp = function writeWithStamp(data) {
var now = new Date();
var timeString = util.format('[%s/%s/%s %s:%s:%s +0000] ',
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours() < 10 ? '0'+now.getUTCHours() : now.getUTCHours(),
now.getUTCMinutes() < 10 ? '0'+now.getUTCMinutes() : now.getUTCMinutes(),
now.getUTCSeconds() < 10 ? '0'+now.getUTCSeconds() : now.getUTCSeconds()
);
this.write(timeString + data);
};
module.exports = Logger; |
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
const {difference, prettyPrint} = require('../../flowResult');
const {default: simpleDiffAssertion} = require('./simpleDiffAssertion');
import type {AssertionLocation, ErrorAssertion} from './assertionTypes';
function newErrors(
expected: string,
assertLoc: ?AssertionLocation,
): ErrorAssertion {
return (reason: ?string, env) => {
const diff = difference(env.getNewErrors(), env.getOldErrors());
const actual = prettyPrint(diff);
let suggestion = {method: 'noNewErrors', args: []};
if (!diff.passed) {
suggestion = {
method: 'newErrors',
args: [prettyPrint(diff)],
};
}
return simpleDiffAssertion(
expected,
actual,
assertLoc,
reason,
'new errors',
suggestion,
);
};
}
module.exports = {
default: newErrors,
};
|
'use strict';
var path = require('path');
var Address = require('address-rfc2821').Address;
var fixtures = require('haraka-test-fixtures');
var Connection = fixtures.connection;
function _setup (done) {
this.plugin = new fixtures.plugin('queue/smtp_forward');
// switch config directory to 'tests/config'
this.plugin.config = this.plugin.config.module_config(path.resolve('tests'));
this.plugin.register();
this.connection = Connection.createConnection();
this.connection.transaction = fixtures.transaction.createTransaction();
done();
}
exports.register = {
setUp : _setup,
'register': function (test) {
test.expect(1);
this.plugin.register();
test.ok(this.plugin.cfg.main);
test.done();
},
};
exports.get_config = {
setUp : _setup,
'no recipient': function (test) {
test.expect(2);
var cfg = this.plugin.get_config(this.connection);
test.equal(cfg.host, 'localhost');
test.equal(cfg.enable_tls, true);
test.done();
},
'null recipient': function (test) {
test.expect(2);
this.connection.transaction.rcpt_to.push(new Address('<>'));
var cfg = this.plugin.get_config(this.connection);
test.equal(cfg.host, 'localhost');
test.equal(cfg.enable_tls, true);
test.done();
},
'valid recipient': function (test) {
test.expect(2);
this.connection.transaction.rcpt_to.push(
new Address('<matt@example.com>')
);
var cfg = this.plugin.get_config(this.connection);
test.equal(cfg.enable_tls, true);
test.equal(cfg.host, 'localhost');
test.done();
},
'valid recipient with route': function (test) {
test.expect(1);
this.connection.transaction.rcpt_to.push(
new Address('<matt@test.com>')
);
test.deepEqual(this.plugin.get_config(this.connection), {
host: '1.2.3.4',
enable_tls: true,
auth_user: 'postmaster@test.com',
auth_pass: 'superDuperSecret',
});
test.done();
},
'valid recipient with route & diff config': function (test) {
test.expect(1);
this.connection.transaction.rcpt_to.push(
new Address('<matt@test1.com>')
);
var cfg = this.plugin.get_config(this.connection);
test.deepEqual(cfg, {
host: '1.2.3.4',
enable_tls: false,
});
test.done();
},
'valid 2 recipients with same route': function (test) {
test.expect(1);
this.connection.transaction.rcpt_to.push(
new Address('<matt@test.com>'),
new Address('<matt@test.com>')
);
var cfg = this.plugin.get_config(this.connection);
test.deepEqual(cfg.host, '1.2.3.4' );
test.done();
},
'valid 2 recipients with different routes': function (test) {
test.expect(1);
this.connection.transaction.rcpt_to.push(
new Address('<matt@test1.com>'),
new Address('<matt@test2.com>')
);
var cfg = this.plugin.get_config(this.connection);
test.equal(cfg.host, 'localhost' );
test.done();
},
};
|
import Ember from "ember-metal/core";
import {get} from "ember-metal/property_get";
import {set} from "ember-metal/property_set";
import run from "ember-metal/run_loop";
import {addObserver, removeObserver} from "ember-metal/observer";
import EmberObject from "ember-runtime/system/object";
import {Controller as EmberController} from "ember-runtime/controllers/controller";
import EmberDataAdapter from "ember-extension-support/data_adapter";
import EmberApplication from "ember-application/system/application";
import {DefaultResolver} from "ember-application/system/resolver";
var adapter, App, Model = EmberObject.extend();
var DataAdapter = EmberDataAdapter.extend({
detect: function(klass) {
return klass !== Model && Model.detect(klass);
}
});
module("Data Adapter", {
setup:function() {
run(function() {
App = EmberApplication.create();
App.toString = function() { return 'App'; };
App.deferReadiness();
App.__container__.register('data-adapter:main', DataAdapter);
});
},
teardown: function() {
run(function() {
adapter.destroy();
App.destroy();
});
}
});
test("Model types added with DefaultResolver", function() {
App.Post = Model.extend();
adapter = App.__container__.lookup('data-adapter:main');
adapter.reopen({
getRecords: function() {
return Ember.A([1,2,3]);
},
columnsForType: function() {
return [ { name: 'title', desc: 'Title'} ];
}
});
run(App, 'advanceReadiness');
var modelTypesAdded = function(types) {
equal(types.length, 1);
var postType = types[0];
equal(postType.name, 'post', 'Correctly sets the name');
equal(postType.count, 3, 'Correctly sets the record count');
strictEqual(postType.object, App.Post, 'Correctly sets the object');
deepEqual(postType.columns, [ {name: 'title', desc: 'Title'} ], 'Correctly sets the columns');
};
adapter.watchModelTypes(modelTypesAdded);
});
test("Model types added with custom container-debug-adapter", function() {
var PostClass = Model.extend() ,
StubContainerDebugAdapter = DefaultResolver.extend({
canCatalogEntriesByType: function(type){
return true;
},
catalogEntriesByType: function(type){
return [PostClass];
}
});
App.__container__.register('container-debug-adapter:main', StubContainerDebugAdapter);
adapter = App.__container__.lookup('data-adapter:main');
adapter.reopen({
getRecords: function() {
return Ember.A([1,2,3]);
},
columnsForType: function() {
return [ { name: 'title', desc: 'Title'} ];
}
});
run(App, 'advanceReadiness');
var modelTypesAdded = function(types) {
equal(types.length, 1);
var postType = types[0];
equal(postType.name, PostClass.toString(), 'Correctly sets the name');
equal(postType.count, 3, 'Correctly sets the record count');
strictEqual(postType.object, PostClass, 'Correctly sets the object');
deepEqual(postType.columns, [ {name: 'title', desc: 'Title'} ], 'Correctly sets the columns');
};
adapter.watchModelTypes(modelTypesAdded);
});
test("Model Types Updated", function() {
App.Post = Model.extend();
adapter = App.__container__.lookup('data-adapter:main');
var records = Ember.A([1,2,3]);
adapter.reopen({
getRecords: function() {
return records;
}
});
run(App, 'advanceReadiness');
var modelTypesAdded = function() {
run(function() {
records.pushObject(4);
});
};
var modelTypesUpdated = function(types) {
var postType = types[0];
equal(postType.count, 4, 'Correctly updates the count');
};
adapter.watchModelTypes(modelTypesAdded, modelTypesUpdated);
});
test("Records Added", function() {
expect(8);
var countAdded = 1;
App.Post = Model.extend();
var post = App.Post.create();
var recordList = Ember.A([post]);
adapter = App.__container__.lookup('data-adapter:main');
adapter.reopen({
getRecords: function() {
return recordList;
},
getRecordColor: function() {
return 'blue';
},
getRecordColumnValues: function() {
return { title: 'Post ' + countAdded };
},
getRecordKeywords: function() {
return ['Post ' + countAdded];
}
});
var recordsAdded = function(records) {
var record = records[0];
equal(record.color, 'blue', 'Sets the color correctly');
deepEqual(record.columnValues, { title: 'Post ' + countAdded }, 'Sets the column values correctly');
deepEqual(record.searchKeywords, ['Post ' + countAdded], 'Sets search keywords correctly');
strictEqual(record.object, post, 'Sets the object to the record instance');
};
adapter.watchRecords(App.Post, recordsAdded);
countAdded++;
post = App.Post.create();
recordList.pushObject(post);
});
test("Observes and releases a record correctly", function() {
var updatesCalled = 0;
App.Post = Model.extend();
var post = App.Post.create({ title: 'Post' });
var recordList = Ember.A([post]);
adapter = App.__container__.lookup('data-adapter:main');
adapter.reopen({
getRecords: function() {
return recordList;
},
observeRecord: function(record, recordUpdated) {
var self = this;
var callback = function() {
recordUpdated(self.wrapRecord(record));
};
addObserver(record, 'title', callback);
return function() {
removeObserver(record, 'title', callback);
};
},
getRecordColumnValues: function(record) {
return { title: get(record, 'title') };
}
});
var recordsAdded = function() {
set(post, 'title', 'Post Modified');
};
var recordsUpdated = function(records) {
updatesCalled++;
equal(records[0].columnValues.title, 'Post Modified');
};
var release = adapter.watchRecords(App.Post, recordsAdded, recordsUpdated);
release();
set(post, 'title', 'New Title');
equal(updatesCalled, 1, 'Release function removes observers');
});
|
import AnimationMixin from 'pui-react-animation';
export default ParentClass => {
return class Animation extends ParentClass {
componentWillUnmount() {
if (super.componentWillUnmount) super.componentWillUnmount();
this::AnimationMixin.componentWillUnmount();
}
shouldAnimate = AnimationMixin.shouldAnimate
animate = AnimationMixin.animate
};
};
|
'use strict';
const pipe = (...fns) => fns.length === 1 ? fns[0].constructor === Function ? fns[0]() : fns[0] : fns.reduce((v, f, i) => {
if (i === 1 && v && v.constructor === Function) {
let exec = v();
if (exec && exec.then) {
return exec.then(v => f(v));
} else {
return f(exec);
}
} else if (v && v.then) {
return v.then(v => f(v));
} else {
return f(v);
}
});
module.exports = pipe; |
import React, { Component } from 'react';
import sinon from 'sinon';
import Autosuggest from '../../src/Autosuggest';
import languages from '../plain-list/languages';
import { escapeRegexCharacters } from '../../demo/src/components/utils/utils.js';
const getMatchingLanguages = value => {
const escapedValue = escapeRegexCharacters(value.trim());
const regex = new RegExp('^' + escapedValue, 'i');
return languages.filter(language => regex.test(language.name));
};
let app = null;
const onChange = (event, { newValue }) => {
app.setState({
value: newValue
});
};
const onSuggestionsFetchRequested = ({ value }) => {
app.setState({
suggestions: getMatchingLanguages(value)
});
};
const onSuggestionsClearRequested = () => {
app.setState({
suggestions: []
});
};
const getSuggestionValue = suggestion => suggestion.name;
const renderSuggestion = suggestion => suggestion.name;
export const renderSuggestionsContainer = sinon.spy(
({ containerProps, children, query }) => (
<div {...containerProps}>
{children}
<div className="my-suggestions-container-footer">
Press Enter to search <strong className="my-query">{query}</strong>
</div>
</div>
)
);
export default class AutosuggestApp extends Component {
constructor() {
super();
app = this;
this.state = {
value: '',
suggestions: []
};
}
storeAutosuggestReference = autosuggest => {
if (autosuggest !== null) {
this.input = autosuggest.input;
}
};
render() {
const { value, suggestions } = this.state;
const inputProps = {
value,
onChange
};
return (
<Autosuggest
suggestions={suggestions}
onSuggestionsFetchRequested={onSuggestionsFetchRequested}
onSuggestionsClearRequested={onSuggestionsClearRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
renderSuggestionsContainer={renderSuggestionsContainer}
inputProps={inputProps}
ref={this.storeAutosuggestReference}
/>
);
}
}
|
Template.trending.created = function () {
this.autorun(function () {
this.subscription = Meteor.subscribe('products');
this.subscription = Meteor.subscribe('shares');//
}.bind(this));
};
Template.trending.rendered = function () {
this.autorun(function () {
if (!this.subscription.ready()) {
IonLoading.show();
} else {
IonLoading.hide();
}
}.bind(this));
};
Template.trending.helpers({
// products: function () {
// return Products.find({}, {sort: {numberOfVotes: -1, name: -1}});
// }
shares:function(){
return Shares.find({},{sort:{createdAt:-1}});
}
});
|
const addStudent = require('./add-student/add-student.module'),
editSection = require('./edit-section/edit-section.module'),
confirmSectionDelete = require('./confirm-section-delete/confirm-section-delete.module');
const moduleName = 'section-dialogs.component',
dependencies = [ addStudent, editSection, confirmSectionDelete ];
angular.module(moduleName, dependencies);
module.exports = moduleName; |
"function"!=typeof Object.create&&function(){var a=function(){};Object.create=function(b){if(1<arguments.length)throw Error("Second argument not supported");if(null===b)throw Error("Cannot set a null [[Prototype]]");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;return new a}}();
CKEDITOR.plugins.add("toolbarconfiguratorarea",{afterInit:function(a){a.addMode("wysiwyg",function(b){var c=CKEDITOR.dom.element.createFromHtml('\x3cdiv class\x3d"cke_wysiwyg_div cke_reset" hidefocus\x3d"true"\x3e\x3c/div\x3e');a.ui.space("contents").append(c);c=a.editable(c);c.detach=CKEDITOR.tools.override(c.detach,function(b){return function(){b.apply(this,arguments);this.remove()}});a.setData(a.getData(1),b);a.fire("contentDom")});a.dataProcessor.toHtml=function(b){return b};a.dataProcessor.toDataFormat=
function(b){return b}}});Object.keys||(Object.keys=function(){var a=Object.prototype.hasOwnProperty,b=!{toString:null}.propertyIsEnumerable("toString"),c="toString toLocaleString valueOf hasOwnProperty isPrototypeOf propertyIsEnumerable constructor".split(" "),e=c.length;return function(d){if("object"!==typeof d&&("function"!==typeof d||null===d))throw new TypeError("Object.keys called on non-object");var g=[],f;for(f in d)a.call(d,f)&&g.push(f);if(b)for(f=0;f<e;f++)a.call(d,c[f])&&g.push(c[f]);return g}}());
(function(){function a(b,c){this.cfg=c||{};this.hidden=!1;this.editorId=b;this.fullToolbarEditor=new ToolbarConfigurator.FullToolbarEditor;this.actualConfig=this.originalConfig=this.mainContainer=null;this.isEditableVisible=this.waitForReady=!1;this.toolbarContainer=null;this.toolbarButtons=[]}ToolbarConfigurator.AbstractToolbarModifier=a;a.prototype.setConfig=function(b){this._onInit(void 0,b,!0)};a.prototype.init=function(b){var c=this;this.mainContainer=new CKEDITOR.dom.element("div");if(null!==
this.fullToolbarEditor.editorInstance)throw"Only one instance of ToolbarModifier is allowed";this.editorInstance||this._createEditor(!1);this.editorInstance.once("loaded",function(){c.fullToolbarEditor.init(function(){c._onInit(b);if("function"==typeof c.onRefresh)c.onRefresh()},c.editorInstance.config)});return this.mainContainer};a.prototype._onInit=function(b,c){this.originalConfig=this.editorInstance.config;this.actualConfig=c?JSON.parse(c):JSON.parse(JSON.stringify(this.originalConfig));if(!this.actualConfig.toolbarGroups&&
!this.actualConfig.toolbar){for(var a=this.actualConfig,d=this.editorInstance.toolbar,g=[],f=d.length,k=0;k<f;k++){var h=d[k];"string"==typeof h?g.push(h):g.push({name:h.name,groups:h.groups?h.groups.slice():[]})}a.toolbarGroups=g}"function"===typeof b&&b(this.mainContainer)};a.prototype._createModifier=function(){this.mainContainer.addClass("unselectable");this.modifyContainer&&this.modifyContainer.remove();this.modifyContainer=new CKEDITOR.dom.element("div");this.modifyContainer.addClass("toolbarModifier");
this.mainContainer.append(this.modifyContainer);return this.mainContainer};a.prototype.getEditableArea=function(){return this.editorInstance.container.findOne("#"+this.editorInstance.id+"_contents")};a.prototype._hideEditable=function(){var b=this.getEditableArea();this.isEditableVisible=!1;this.lastEditableAreaHeight=b.getStyle("height");b.setStyle("height","0")};a.prototype._showEditable=function(){this.isEditableVisible=!0;this.getEditableArea().setStyle("height",this.lastEditableAreaHeight||"auto")};
a.prototype._toggleEditable=function(){this.isEditableVisible?this._hideEditable():this._showEditable()};a.prototype._refreshEditor=function(){function b(){c.editorInstance.destroy();c._createEditor(!0,c.getActualConfig());c.waitForReady=!1}var c=this,a=this.editorInstance.status;this.waitForReady||("unloaded"==a||"loaded"==a?(this.waitForReady=!0,this.editorInstance.once("instanceReady",function(){b()},this)):b())};a.prototype._createEditor=function(b,c){function e(){}var d=this;this.editorInstance=
CKEDITOR.replace(this.editorId);this.editorInstance.on("configLoaded",function(){var b=d.editorInstance.config;c&&CKEDITOR.tools.extend(b,c,!0);a.extendPluginsConfig(b)});this.editorInstance.on("uiSpace",function(b){"top"!=b.data.space&&b.stop()},null,null,-999);this.editorInstance.once("loaded",function(){var c=d.editorInstance.ui.instances,a;for(a in c)c[a]&&(c[a].click=e,c[a].onClick=e);d.isEditableVisible||d._hideEditable();d.currentActive&&d.currentActive.name&&d._highlightGroup(d.currentActive.name);
d.hidden?d.hideUI():d.showUI();if(b&&"function"===typeof d.onRefresh)d.onRefresh()})};a.prototype.getActualConfig=function(){return JSON.parse(JSON.stringify(this.actualConfig))};a.prototype._createToolbar=function(){if(this.toolbarButtons.length){this.toolbarContainer=new CKEDITOR.dom.element("div");this.toolbarContainer.addClass("toolbar");for(var b=this.toolbarButtons.length,c=0;c<b;c+=1)this._createToolbarBtn(this.toolbarButtons[c])}};a.prototype._createToolbarBtn=function(b){var c=ToolbarConfigurator.FullToolbarEditor.createButton("string"===
typeof b.text?b.text:b.text.inactive,b.cssClass);this.toolbarContainer.append(c);c.data("group",b.group);c.addClass(b.position);c.on("click",function(){b.clickCallback.call(this,c,b)},this);return c};a.prototype._fixGroups=function(b){b=b.toolbarGroups||[];for(var c=b.length,a=0;a<c;a+=1){var d=b[a];"/"==d?(d=b[a]={},d.type="separator",d.name="separator"+CKEDITOR.tools.getNextNumber()):(d.groups=d.groups||[],-1==CKEDITOR.tools.indexOf(d.groups,d.name)&&(this.editorInstance.ui.addToolbarGroup(d.name,
d.groups[d.groups.length-1],d.name),d.groups.push(d.name)),this._fixSubgroups(d))}};a.prototype._fixSubgroups=function(b){b=b.groups;for(var c=b.length,a=0;a<c;a+=1){var d=b[a];b[a]={name:d,totalBtns:ToolbarConfigurator.ToolbarModifier.getTotalSubGroupButtonsNumber(d,this.fullToolbarEditor)}}};a.stringifyJSONintoOneLine=function(b,a){a=a||{};var e=JSON.stringify(b,null,""),e=e.replace(/\n/g,"");a.addSpaces&&(e=e.replace(/(\{|:|,|\[|\])/g,function(a){return a+" "}),e=e.replace(/(\])/g,function(a){return" "+
a}));a.noQuotesOnKey&&(e=e.replace(/"(\w*)":/g,function(a,b){return b+":"}));a.singleQuotes&&(e=e.replace(/\"/g,"'"));return e};a.prototype.hideUI=function(){this.hidden=!0;this.mainContainer.hide();this.editorInstance.container&&this.editorInstance.container.hide()};a.prototype.showUI=function(){this.hidden=!1;this.mainContainer.show();this.editorInstance.container&&this.editorInstance.container.show()};a.extendPluginsConfig=function(a){var c=a.extraPlugins;a.extraPlugins=(c?c+",":"")+"toolbarconfiguratorarea"}})();
|
'use strict';
var crypto = require('crypto');
/**
* Derives 512 bit key from a string secret
*
* @param {string} secret The secret
* @param {string} type The type of key to generate. Can be any string.
* @return {Buffer} 512 bit key
*/
var deriveKey = function (secret, type) {
var hmac = crypto.createHmac('sha512', secret);
hmac.update(type);
return new Buffer(hmac.digest());
};
/**
* Utility function: Zeros a buffer for security
*
* @param {Buffer} buf The buffer
*/
var clearBuffer = function (buf) {
for (var i = 0; i < buf.length; i++) {
buf[i] = 0;
}
};
/**
* Drops 256 bits from a 512 bit buffer
*
* @param {Buffer} buf A 512 bit buffer
* @return {Buffer} A 256 bit buffer
*/
var drop256 = function (buf) {
var buf256 = new Buffer(32);
buf.copy(buf256, 0, 0, 32);
clearBuffer(buf);
return buf256;
};
module.exports = {
deriveKey: deriveKey,
clearBuffer: clearBuffer,
drop256: drop256
};
|
import FileSaver from 'file-saver';
import jsonexport from 'jsonexport';
import Visualizer from './visualizer';
/**
* JSON raw data visualizer.
*
* @type {Object}
*/
export default class CsvVisualizer extends Visualizer {
/**
* Visualizes the given
* story part as JSON.
* @return {[type]} [description]
*/
visualize(part) {
// get the part's output section
const output = part.output;
// export the data as a flat CSV
jsonexport(output.data, (err, csv) => {
if (err) {
console.error(err);
} else {
const blob = new Blob([csv], {type: 'text/csv'});
FileSaver.saveAs(blob, 'data.csv');
}
});
// emit an event
this.emit('rendered');
}
}
|
import { defineMessages } from 'react-intl';
const translations = defineMessages({
lessonPlanItemSettings: {
id: 'course.admin.lessonPlanSettings.lessonPlanItemSettings',
defaultMessage: 'Lesson Plan Item Settings',
},
lessonPlanAssessmentItemSettings: {
id: 'course.admin.lessonPlanSettings.lessonPlanAssessmentItemSettings',
defaultMessage: 'Assessment Item Settings',
},
lessonPlanComponentItemSettings: {
id: 'course.admin.lessonPlanSettings.lessonPlanComponentItemSettings',
defaultMessage: 'Component Item Settings',
},
assessmentCategory: {
id: 'course.admin.LessonPlanItemSettings.assessmentCategory',
defaultMessage: 'Assessment Category',
},
assessmentTab: {
id: 'course.admin.LessonPlanItemSettings.assessmentTab',
defaultMessage: 'Assessment Tab',
},
enabled: {
id: 'course.admin.LessonPlanItemSettings.enabled',
defaultMessage: 'Show on Lesson Plan',
},
visible: {
id: 'course.admin.LessonPlanItemSettings.visible',
defaultMessage: 'Visible by Default',
},
component: {
id: 'course.admin.LessonPlanItemSettings.component',
defaultMessage: 'Component',
},
updateSuccess: {
id: 'course.admin.LessonPlanItemSettings.updateSuccess',
defaultMessage: 'Setting for "{setting}" updated.',
},
updateFailure: {
id: 'course.admin.LessonPlanItemSettings.updateFailure',
defaultMessage: 'Failed to update setting for "{setting}".',
},
noLessonPlanItems: {
id: 'course.admin.LessonPlanItemSettings.noLessonPlanItems',
defaultMessage: 'There are no lesson plan items to configure for lesson plan display.',
},
});
export default translations;
|
'use strict';Object.defineProperty(exports,"__esModule",{value:true});var _jsxFileName='src/xAxis.js';var _createClass=function(){function defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value" in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}return function(Constructor,protoProps,staticProps){if(protoProps)defineProperties(Constructor.prototype,protoProps);if(staticProps)defineProperties(Constructor,staticProps);return Constructor;};}();
var _react=require('react');var _react2=_interopRequireDefault(_react);
var _reactNative=require('react-native');function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&(typeof call==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}
var styles=_reactNative.StyleSheet.create({
xAxisContainer:{
flexDirection:'row',
flex:0,
backgroundColor:'transparent',
justifyContent:'space-between'},
axisText:{
flex:1,
backgroundColor:'transparent'}});var
XAxis=function(_Component){_inherits(XAxis,_Component);function XAxis(){_classCallCheck(this,XAxis);return _possibleConstructorReturn(this,Object.getPrototypeOf(XAxis).apply(this,arguments));}_createClass(XAxis,[{key:'render',value:function render()
{var _this2=this;
var data=this.props.data||[[]];
var transform=function transform(d){return d;};
if(this.props.xAxisTransform&&typeof this.props.xAxisTransform==='function'){
transform=this.props.xAxisTransform;}
return (
_react2.default.createElement(_reactNative.View,{
style:[
styles.xAxisContainer,
{
borderTopColor:this.props.axisColor,
borderTopWidth:this.props.axisLineWidth},
this.props.style],__source:{fileName:_jsxFileName,lineNumber:45}},
function(){
if(!_this2.props.showXAxisLabels)return null;
return data.map(function(d,i){
var stepsBetweenVerticalLines=_this2.props.horizontalGridStep?Math.round(data.length/_this2.props.horizontalGridStep+1):1;
if(stepsBetweenVerticalLines<1)stepsBetweenVerticalLines=1;
if(i%stepsBetweenVerticalLines!==0)return null;
var item=transform(d[0]);
if(typeof item!=='number'&&!item)return null;
return (
_react2.default.createElement(_reactNative.Text,{
key:i,
style:[
styles.axisText,
{
textAlign:_this2.props.align,
color:_this2.props.axisLabelColor,
fontSize:_this2.props.labelFontSize}],__source:{fileName:_jsxFileName,lineNumber:64}},
item));});}()));}}]);return XAxis;}(_react.Component);XAxis.propTypes={axisColor:_react.PropTypes.any.isRequired,axisLabelColor:_react.PropTypes.any.isRequired,axisLineWidth:_react.PropTypes.number.isRequired,data:_react.PropTypes.arrayOf(_react.PropTypes.arrayOf(_react.PropTypes.array)).isRequired,showXAxisLabels:_react.PropTypes.bool.isRequired,style:_react.PropTypes.any,width:_react.PropTypes.number.isRequired,align:_react.PropTypes.string,labelFontSize:_react.PropTypes.number.isRequired,xAxisTransform:_react.PropTypes.func,horizontalGridStep:_react.PropTypes.number};XAxis.defaultProps={align:'center'};exports.default=XAxis; |
/**
* A view which explains the currently-shown revision of the diff.
*/
RB.DiffRevisionLabelView = Backbone.View.extend({
events: {
'click .select-latest': '_onSelectLatest',
'click .select-changed': '_onSelectChanged',
},
/**
* Templates for various strings.
*
* We use _.template instead of interpolate to make sure that revision
* strings are HTML-escaped.
*/
template: _.template(dedent`
<h1><%- header %></h1>
<% if (detail) { %><p><%= detail %><% } %>
`),
_interdiffTemplate: _.template(gettext(
'Changes between revision <%- revision %> and <%- interdiffRevision %>')),
_latestTemplate: _.template(gettext(
'Diff Revision <%- revision %> (Latest)')),
_oldHeaderTemplate: _.template(gettext('Diff Revision <%- revision %>')),
_oldDetailTemplate: _.template(
/* Translators: This string should be valid HTML (including any necessary escaping for entities). */
gettext('This is not the most recent revision of the diff. The <a href="#" class="select-latest">latest diff</a> is revision <%- latestRevision %>. <a href="#" class="select-changed">See what\'s changed.</a>')),
/**
* Initialize the view.
*/
initialize() {
this.listenTo(this.model, 'change', this.render);
},
/**
* Render the view.
*
* Returns:
* RB.DiffRevisionLabelView:
* This object, for chaining.
*/
render() {
const revision = this.model.get('revision');
const latestRevision = this.model.get('latestRevision');
let header = '';
let detail = null;
if (this.model.get('isInterdiff')) {
const interdiffRevision = this.model.get('interdiffRevision');
header = this._interdiffTemplate({
revision: revision,
interdiffRevision: interdiffRevision,
});
} else if (revision === latestRevision) {
header = this._latestTemplate({
revision: revision,
});
} else if (this.model.get('isDraftDiff')) {
header = gettext('Draft diff');
/* Translators: This string should be valid HTML (including any necessary escaping for entities). */
detail = gettext('This diff is part of your current draft. Other users will not see this diff until you publish your draft.');
} else {
header = this._oldHeaderTemplate({
revision: revision,
});
detail = this._oldDetailTemplate({
revision: revision,
latestRevision: latestRevision,
});
}
this.$el.html(this.template({
header: header,
detail: detail,
}));
return this;
},
/**
* Callback when the "latest diff" link is clicked.
*
* This is shown in the "This is not the most recent revision"
* explanation.
*
* Args:
* ev (Event):
* The click event.
*/
_onSelectLatest(ev) {
ev.preventDefault();
ev.stopPropagation();
this.trigger('revisionSelected',
[0, this.model.get('latestRevision')]);
},
/*
* Callback for when "See what's changed" is clicked.
*
* This is shown in the "This is not the most recent revision"
* explanation.
*
* Args:
* ev (Event):
* The click event.
*/
_onSelectChanged(ev) {
ev.preventDefault();
ev.stopPropagation();
this.trigger('revisionSelected',
[this.model.get('revision'),
this.model.get('latestRevision')]);
},
});
|
/// <reference path="Scripts/angular.min.js" />
/// <reference path="~/Scripts/underscore.js" />
var app = angular.module("OfferWorld", []);
app.config(function ($routeProvider) {
$routeProvider
.when('/home',
{
templateUrl: 'AdminClient/partials/home.html',
controller: HomeController
})
.when('/user/login',
{
templateUrl: 'AdminClient/partials/login-form.html',
controller: LoginController
})
.when('/tasks',
{
templateUrl: 'AdminClient/partials/tasks.html',
controller: LogoutController
})
.when('/category/create',
{
templateUrl: 'AdminClient/partials/create-category.html',
controller: CategoriesController
})
.when('/category/delete',
{
templateUrl: 'AdminClient/partials/delete-category.html',
controller: CategoriesController
})
.when('/user/register',
{
templateUrl: 'AdminClient/partials/register-form.html',
controller: RegisterController
})
.when('/tasks',
{
templateUrl: 'AdminClient/partials/tasks.html',
controller: TasksController
})
.otherwise({ redirectTo: "/home" });;
});
app.factory("SessionService", function () {
var get = function (key) {
return sessionStorage.getItem(key);
};
var set = function (key, value) {
return sessionStorage.setItem(key, value);
};
var unset = function (key) {
return sessionStorage.removeItem(key);
};
return {
get: get,
set: set,
unset: unset
};
});
app.factory("AuthenticationService", function ($http, $location, SessionService) {
var login = function (username, password) {
var newUser = {
Username: username,
AuthCode: CryptoJS.SHA1(password).toString()
};
var result = $http.post("http://localhost:37755/api/users/login", newUser);
result.success(function (data) {
SessionService.set("SessionKey", data.SessionKey);
});
return result;
};
var logout = function () {
var sessionKey = SessionService.get("SessionKey");
var headers = {
"X-sessionKey": sessionKey
};
var result = $http.put("http://localhost:37755/api/users/logout", headers);
//result.success(function () {
// SessionService.set("SessionKey", "");
//});
return result;
};
var register = function (username, email, password) {
var newUser = {
Username: username,
AuthCode: CryptoJS.SHA1(password).toString(),
Email: email
};
var result = $http.post("http://localhost:37755/api/users/register", newUser);
result.success(function (data) {
SessionService.set("SessionKey", data.SessionKey);
});
return result;
};
var isUserLoggedIn = function () {
return SessionService.get("SessionKey");
};
return {
login: login,
logout: logout,
register: register,
isUserLoggedIn: isUserLoggedIn
};
}); |
'use strict';
angular.module('eehNavigation').directive('eehNavigationSidebar', SidebarDirective);
/**
* @ngInject
* @ngdoc directive
* @name eeh-navigation-sidebar
* @restrict AE
*
* @description
* This directive adds a sidebar, based on the Twitter Bootstrap navbar component, to the template.
* If Angular UI Router is used (which is recommended), then the sidebar directive should wrap a __ui-view__ element.
* It should also be in a template that is at or near the top of the state hierarchy.
*
* @param {string=} menuName Sets the name of the menu that the directive will render.
* @param {string=} [navClass=navbar-default] Sets the ng-class attribute of the top-level nav element.
* @param {number=} [topOffset=51]
* This attribute offsets the top position of the sidebar.
* It should equal the height of the navbar, or 0 if there is no navbar.
* This attribute should be used if the navbar's height is something different or if the navbar is not used.
* @param {string=} [menuItemCollapsedIconClass="glyphicon-chevron-left"]
* This attribute sets the icon used to indicate that a parent of a nested menu item is collapsed.
* @param {string=} [menuItemExpandedIconClass="glyphicon-chevron-down"]
* This attribute sets the icon used to indicate that a parent of a nested menu item is expanded.
* @param {string=} [sidebarCollapsedIconClass="glyphicon-arrow-right"]
* This attribute sets the icon used to indicate that the sidebar is collapsed.
* @param {string=} [sidebarExpandedIconClass="glyphicon-arrow-left"]
* This attribute sets the icon used to indicate that the search input is use for searching.
* @param {string=} [searchInputIconClass="glyphicon-search"]
* This attribute sets the icon used to indicate that the sidebar is collapsed.
* @param {boolean=} [searchInputIsVisible=true]
* This attribute causes the search input to be shown or hidden.
* @param {boolean=} [sidebarCollapsedButtonIsVisible=true]
* This attribute causes the text collapse toggle button to be shown or hidden.
* @param {boolean=} [sidebarIsCollapsed=false]
* This attribute sets the state of the text collapse button.
* @param {function=} refresh
* This attribute provides a function for refreshing the directive.
*/
function SidebarDirective($window, eehNavigation) {
return {
restrict: 'AE',
transclude: true,
templateUrl: 'template/eeh-navigation/sidebar/eeh-navigation-sidebar.html',
scope: {
menuName: '=',
navClass: '=?',
topOffset: '=?',
menuItemCollapsedIconClass: '=?',
menuItemExpandedIconClass: '=?',
sidebarCollapsedIconClass: '=?',
sidebarExpandedIconClass: '=?',
searchInputIconClass: '=?',
searchInputIsVisible: '=?',
searchInputSubmit: '=',
sidebarCollapsedButtonIsVisible: '=?',
sidebarIsCollapsed: '=?',
refresh: '=?'
},
link: function (scope) {
scope.iconBaseClass = function () {
return eehNavigation.iconBaseClass();
};
scope.defaultIconClassPrefix = function () {
return eehNavigation.defaultIconClassPrefix();
};
scope.topOffset = scope.topOffset || 51; // 51 is the default height of the navbar component
scope.navClass = scope.navClass || 'navbar-default';
scope.menuItemCollapsedIconClass = scope.menuItemCollapsedIconClass || scope.defaultIconClassPrefix() + '-chevron-left';
scope.menuItemExpandedIconClass = scope.menuItemExpandedIconClass || scope.defaultIconClassPrefix() + '-chevron-down';
scope.sidebarCollapsedIconClass = scope.sidebarCollapsedIconClass || scope.defaultIconClassPrefix() + '-arrow-right';
scope.sidebarExpandedIconClass = scope.sidebarExpandedIconClass || scope.defaultIconClassPrefix() + '-arrow-left';
scope.searchInputIconClass = scope.searchInputIconClass || scope.defaultIconClassPrefix() + '-search';
if (scope.sidebarCollapsedButtonIsVisible !== false) {
scope.sidebarCollapsedButtonIsVisible = true;
}
scope.sidebarIsCollapsed = scope.sidebarIsCollapsed || false;
if (scope.searchInputIsVisible !== false) {
scope.searchInputIsVisible = true;
}
var menuItems = function () {
return eehNavigation.menuItems();
};
scope.refresh = function () {
if (angular.isUndefined(scope.menuName)) {
return;
}
scope.sidebarMenuItems = eehNavigation.menuItemTree(scope.menuName);
};
scope.$watch(menuItems, scope.refresh, true);
var windowElement = angular.element($window);
windowElement.bind('resize', function () {
scope.$apply();
});
var getWindowDimensions = function () {
return {
innerHeight: windowElement[0].innerHeight,
innerWidth: windowElement[0].innerWidth
};
};
var transcludedWrapper = angular.element(document.querySelectorAll('#eeh-navigation-page-wrapper'));
scope.$watch(getWindowDimensions, function (newValue) {
if (angular.isUndefined(newValue)) {
return;
}
var height = (newValue.innerHeight > 0) ? newValue.innerHeight : $window.screen.height;
height = height - scope.topOffset;
if (height < 1) {
height = 1;
}
if (height > scope.topOffset) {
transcludedWrapper.css('min-height', (height) + 'px');
}
}, true);
scope.toggleSidebarTextCollapse = function () {
scope.sidebarIsCollapsed = !scope.sidebarIsCollapsed;
setTextCollapseState();
};
function setTextCollapseState() {
var sidebarMenuItems = angular.element(document.querySelectorAll('ul.sidebar-nav:not(.sidebar-nav-nested) > li > a > span'));
var sidebarMenuItemText = sidebarMenuItems.find('span');
var allMenuItemTextElements = Array.prototype.filter.call(sidebarMenuItemText, function (item) {
return item.matches('.menu-item-text');
});
var arrowIconElements = Array.prototype.filter.call(sidebarMenuItems, function (item) {
return item.matches('.sidebar-arrow');
});
var sidebarElement = angular.element(document.querySelectorAll('.eeh-navigation-sidebar'));
if (scope.sidebarIsCollapsed) {
transcludedWrapper.addClass('sidebar-text-collapsed');
sidebarElement.addClass('sidebar-text-collapsed');
allMenuItemTextElements.forEach(function (menuItem) {
angular.element(menuItem).addClass('hidden');
});
arrowIconElements.forEach(function (menuItem) {
angular.element(menuItem).addClass('hidden');
});
angular.forEach(menuItems(), function (menuItem) {
menuItem.isCollapsed = true;
});
} else {
transcludedWrapper.removeClass('sidebar-text-collapsed');
sidebarElement.removeClass('sidebar-text-collapsed');
allMenuItemTextElements.forEach(function (menuItem) {
angular.element(menuItem).removeClass('hidden');
});
arrowIconElements.forEach(function (menuItem) {
angular.element(menuItem).removeClass('hidden');
});
}
}
/**
* $includeContentLoaded is emitted when ng-include templates are finished loading.
* The text collapse state needs to be evaluated after the sidebar menu templates (which are loaded via
* ng-include) are loaded. If not, the sidebar menu item will not be hidden if the initial state of the
* sidebar text is collapsed as the menu items will not exist when the state is initially evaluated.
*/
scope.$on('$includeContentLoaded', function () {
setTextCollapseState();
});
scope.isSidebarVisible = function () {
return scope.searchInputIsVisible || (angular.isArray(scope.sidebarMenuItems) && scope.sidebarMenuItems
.filter(function (item) {
return item._isVisible();
})
.length > 0);
};
scope.topLevelMenuItemClickHandler = function (clickedMenuItem) {
if (!scope.sidebarIsCollapsed || !clickedMenuItem.hasChildren()) {
return;
}
scope.sidebarMenuItems
.filter(function (menuItem) {
return menuItem.hasChildren() && clickedMenuItem !== menuItem;
})
.forEach(function (menuItem) {
menuItem.isCollapsed = true;
});
};
}
};
}
|
/**
* Copyright 2015 Telerik AD
*
* 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.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["tg-Cyrl-TJ"] = {
name: "tg-Cyrl-TJ",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
percent: {
pattern: ["-n%","n%"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["-n $","n $"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
symbol: "смн"
}
},
calendars: {
standard: {
days: {
names: ["якшанбе","душанбе","сешанбе","чоршанбе","панҷшанбе","ҷумъа","шанбе"],
namesAbbr: ["пкш","дшб","сшб","чшб","пшб","ҷум","шнб"],
namesShort: ["яш","дш","сш","чш","пш","ҷм","шб"]
},
months: {
names: ["январ","феврал","март","апрел","май","июн","июл","август","сентябр","октябр","ноябр","декабр",""],
namesAbbr: ["янв","фев","мар","апр","май","июн","июл","авг","сен","окт","ноя","дек",""]
},
AM: [""],
PM: [""],
patterns: {
d: "dd.MM.yyyy",
D: "d MMMM yyyy' с.'",
F: "d MMMM yyyy' с.' HH:mm:ss",
g: "dd.MM.yyyy HH:mm",
G: "dd.MM.yyyy HH:mm:ss",
m: "dd MMMM",
M: "dd MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "HH:mm",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": ".",
":": ":",
firstDay: 1
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); |
var vows = require('vows'),
traverse = require('traverse'),
commands = require('./jsmin.sourcemap.commands.js');
// Theoretical setup for TestDriver class
// var engines = {};
// function addEngine(name, engine) {
// engines[name] = engine;
// }
// function TestDriver(engineName) {
// // Grab and localize the engine
// var engine = engines[engineName];
// this.engine = engine;
// // TODO: We might want to create SuiteDriver
// this.suite = engine.createSuite();
// this.batches = [];
// }
// TestDriver.prototype = {
// 'addBatch': function (inBatch) {
// var outBatch = addCommands(inBatch);
// this.suite.addBatch(outBatch);
// }
// };
function addCommands(batch) {
// Traverse over the batch
traverse(batch).forEach(function traverseBatch (node) {
var key = this.key;
// If there is a key
if (key) {
// Look up the command for it
var command = commands[key];
// If there is a command
if (command) {
// If the node is an object
if (typeof node === 'object') {
// Add it as a topic
var topic = node.topic || command;
// DEV: Wrap the topic inside of a try/catch for debugging
node.topic = function () {
var retVal;
try {
retVal = topic.apply(this, arguments);
} catch (e) {
console.error(e);
}
return retVal;
};
} else {
// Otherwise, save it over the node itself
node = command;
}
}
}
// Return the node
return node;
});
// Return the batch
return batch;
}
// Set up the vows suite
var suite = vows.describe('jsmin-sourcemap'),
// batches = eval(require('fs').readFileSync(__dirname + '/jsmin.sourcemap.tests.json', 'utf8'));
batches = require('./jsmin.sourcemap.tests.json');
// Generate each batch and add it to the suite
batches.forEach(function (_batch) {
var batch = addCommands(_batch);
suite.addBatch(batch);
});
// TODO: Multi-nested
// Export the batch as a suite
suite['export'](module); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.