code
stringlengths 2
1.05M
|
---|
"use strict";
import superagent from "superagent";
import FeedParser from "feedparser";
export default class FeedService {
constructor() {
}
parse(url) {
return new Promise((resolve, reject) => {
let items = [];
superagent
.get(url)
.pipe(new FeedParser([]))
.on("error", function(error) {
reject(error);
})
.on("meta", function(meta) {
//console.log(meta);
})
.on("readable", function() {
let stream = this;
let item;
while(item = stream.read()) {
items.push(item);
}
stream.end = () => {
resolve(items);
};
});
});
}
static activate() {
FeedService.instance = new FeedService();
return FeedService.instance;
}
}
FeedService.activate.$inject = [];
|
for (var i = 0; i < 16; i++) {
var wool = "minecraft:wool:" + i;
var carpet = "chisel:carpet_block:" + i;
// removeRecipes(carpet);
addShapedRecipe(carpet + "@8", [
[wool, wool, wool],
[wool, "itemString", wool],
[wool, wool, wool]
]);
}
|
bg.ecard.DomTargets = function( params ) {
if (params) {
this.params = params;
if (params.parent) this.parent = params.parent;
} else {
this.params = {};
}
this.params.type = 'bg.ecard.DomTargets';
/*
if ( typeof(selector) === 'string' ) {
this.params.id = selector;
this.params.selector = selector;
} else {
this.target = selector;
this.params.selector = selector;
}
*/
this.init();
}
bg.ecard.DomTargets.prototype.init = function() {
app.log(this, 'init()');
//ANTON UGLY PATCH
if ( !this.params || !this.params.parentEl ) {
app.log(this, 'UNDEFINED PARENT EL');
return;
}
this.targets = this.params.parentEl.querySelectorAll( this.params.query );
this.targetDOMs = [];
for (var i=0; i <this.targets.length; i++) {
this.targetDOMs.push( new bg.ecard.DomTarget(this.targets[i]) );
}
}
bg.ecard.DomTargets.prototype.button = function(domEl) {
app.log( this, 'button() not yet implemented !' );
}
bg.ecard.DomTargets.prototype.html = function( htmlStr ) {
app.log( this, 'html()' );
//ANTON PATCH
if ( !this.targetDOMs ) {
return;
}
//console.log('!!!!!!!!!');
for (var i=0; i<this.targetDOMs.length; i++) {
this.targetDOMs[i].html( htmlStr );
}
}
bg.ecard.DomTargets.prototype.getValues = function() {
app.log( this, 'getValues() not yet implemented !' );
}
bg.ecard.DomTargets.prototype.getValue = function() {
app.log( this, 'getValue() not yet implemented !' );
}
bg.ecard.DomTargets.prototype.serialize = function() {
app.log( this, 'serialize() not yet implemented !' );
}
bg.ecard.DomTargets.prototype.select = function() {
app.log( this, 'select()' );
for (var i=0; i<this.targetDOMs.length; i++) {
this.targetDOMs[i].select();
}
}
bg.ecard.DomTargets.prototype.deselect = function() {
app.log( this, 'select()' );
for (var i=0; i<this.targetDOMs.length; i++) {
this.targetDOMs[i].deselect();
}
}
bg.ecard.DomTargets.prototype.setState = function(stateId) {
app.log( this, 'setState()', stateId );
for (var i=0; i<this.targetDOMs.length; i++) {
this.targetDOMs[i].setState(stateId);
}
}
bg.ecard.DomTargets.prototype.removeState = function(stateId) {
app.log( this, 'removeState()', stateId);
for (var i=0; i<this.targetDOMs.length; i++) {
this.targetDOMs[i].removeState(stateId);
}
}
bg.ecard.DomTargets.prototype.setValue = function( newValue ) {
for (var i=0; i<this.targetDOMs.length; i++) {
this.targetDOMs[i].setValue(newValue);
}
}
bg.ecard.DomTargets.prototype.show = function() {
app.log( this, 'show() not yet implemented !' );
}
bg.ecard.DomTargets.prototype.hide = function() {
app.log( this, 'hide() not yet implemented !' );
}
bg.ecard.DomTargets.prototype.focus = function() {
app.log( this, 'focus() not yet implemented !' );
}
bg.ecard.DomTargets.prototype.blur = function() {
app.log( this, 'blur() not yet implemented !' );
}
bg.ecard.DomTargets.prototype.find = function(selector, returnDomTarget) {
app.log( this, 'find() not yet implemented !' );
}
bg.ecard.DomTargets.prototype.findAll = function(selector) {
app.log( this, 'findAll() not yet implemented !' );
}
bg.ecard.DomTargets.prototype.removeClass = function(className) {
app.log( this, 'removeClass() not yet implemented !' );
}
bg.ecard.DomTargets.prototype.addClass = function(className) {
app.log( this, 'addClass() not yet implemented !' );
}
bg.ecard.DomTargets.prototype.setData = function(dataObj) {
app.log( this, 'setData()' );
for (var i=0; i<this.targetDOMs.length; i++) {
this.targetDOMs[i].setData(dataObj);
}
}
bg.ecard.DomTargets.prototype.removeData = function(dataId) {
app.log( this, 'removeData()' );
console.log( this, 'removeData()' );
for (var i=0; i<this.targetDOMs.length; i++) {
console.log(i);
this.targetDOMs[i].removeData(dataId);
}
}
bg.ecard.DomTargets.prototype.remove = function() {
app.log( this, 'remove() not yet implemented !' );
}
bg.ecard.utils.registerJS('bg.ecard.DomTargets.js');
|
const path = require('path');
const merge = require('webpack-merge');
const autoprefixer = require('autoprefixer');
const postcssFixes = require('postcss-fixes');
const cssnano = require('cssnano');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const baseConfig = require('./webpack.base');
const postcssOptions = {
plugins: [
postcssFixes(),
autoprefixer({
browsers: ['last 2 version', 'IE >= 9'],
}),
cssnano({
safe: true,
calc: false,
}),
],
};
module.exports = merge(baseConfig, {
mode: 'production',
stats: {
assets: true,
cached: false,
cachedAssets: false,
children: false,
chunks: false,
chunkModules: false,
chunkOrigins: false,
modules: false,
reasons: false,
source: false,
},
devtool: 'source-map',
entry: ['./src/index'],
output: {
path: path.join(__dirname, '../dist'),
filename: 'bundle.[hash].js',
},
plugins: [
new MiniCssExtractPlugin({
filename: 'styles.[hash].css',
allChunks: true,
}),
new HtmlWebpackPlugin({
template: './src/html/index.prod.html',
}),
// new BundleAnalyzerPlugin(),
],
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { importLoaders: true } },
{ loader: 'postcss-loader', options: postcssOptions },
],
},
{
test: /\.less$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
modules: true,
importLoaders: true,
localIdentName: '[name]__[local]___[hash:base64:5]',
},
},
{ loader: 'postcss-loader', options: postcssOptions },
{ loader: 'less-loader' },
],
},
{
test: /\.woff(2)?(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/font-woff',
},
},
],
},
{
test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: 'url-loader',
options: {
limit: 10000,
mimetype: 'application/octet-stream',
},
},
],
},
],
},
resolve: {
alias: {
'lodash-es': 'lodash',
},
},
});
|
var R = require('../source/index.js');
var eq = require('./shared/eq.js');
var testObj = {
a: [{
b: 1
}, {
b: 2
}],
d: 3
};
describe('lensPath', function() {
describe('view', function() {
it('focuses the specified object property', function() {
eq(R.view(R.lensPath(['d']), testObj), 3);
eq(R.view(R.lensPath(['a', 1, 'b']), testObj), 2);
eq(R.view(R.lensPath([]), testObj), testObj);
});
});
describe('set', function() {
it('sets the value of the object property specified', function() {
eq(R.set(R.lensPath(['d']), 0, testObj), {a: [{b: 1}, {b: 2}], d: 0});
eq(R.set(R.lensPath(['a', 0, 'b']), 0, testObj), {a: [{b: 0}, {b: 2}], d: 3});
eq(R.set(R.lensPath([]), 0, testObj), 0);
});
it('adds the property to the object if it doesn\'t exist', function() {
eq(R.set(R.lensPath(['X']), 0, testObj), {a: [{b: 1}, {b: 2}], d: 3, X: 0});
eq(R.set(R.lensPath(['a', 0, 'X']), 0, testObj), {a: [{b: 1, X: 0}, {b: 2}], d: 3});
});
});
describe('over', function() {
it('applies function to the value of the specified object property', function() {
eq(R.over(R.lensPath(['d']), R.inc, testObj), {a: [{b: 1}, {b: 2}], d: 4});
eq(R.over(R.lensPath(['a', 1, 'b']), R.inc, testObj), {a: [{b: 1}, {b: 3}], d: 3});
eq(R.over(R.lensPath([]), R.toPairs, testObj), [['a', [{b: 1}, {b: 2}]], ['d', 3]]);
});
it('applies function to undefined and adds the property if it doesn\'t exist', function() {
eq(R.over(R.lensPath(['X']), R.identity, testObj), {a: [{b: 1}, {b: 2}], d: 3, X: undefined});
eq(R.over(R.lensPath(['a', 0, 'X']), R.identity, testObj), {a: [{b: 1, X: undefined}, {b: 2}], d: 3});
});
});
describe('composability', function() {
it('can be composed', function() {
var composedLens = R.compose(R.lensPath(['a']), R.lensPath([1, 'b']));
eq(R.view(composedLens, testObj), 2);
});
});
describe('well behaved lens', function() {
it('set s (get s) === s', function() {
eq(R.set(R.lensPath(['d']), R.view(R.lensPath(['d']), testObj), testObj), testObj);
eq(R.set(R.lensPath(['a', 0, 'b']), R.view(R.lensPath(['a', 0, 'b']), testObj), testObj), testObj);
});
it('get (set s v) === v', function() {
eq(R.view(R.lensPath(['d']), R.set(R.lensPath(['d']), 0, testObj)), 0);
eq(R.view(R.lensPath(['a', 0, 'b']), R.set(R.lensPath(['a', 0, 'b']), 0, testObj)), 0);
});
it('get (set(set s v1) v2) === v2', function() {
var p = ['d'];
var q = ['a', 0, 'b'];
eq(R.view(R.lensPath(p), R.set(R.lensPath(p), 11, R.set(R.lensPath(p), 10, testObj))), 11);
eq(R.view(R.lensPath(q), R.set(R.lensPath(q), 11, R.set(R.lensPath(q), 10, testObj))), 11);
});
});
});
|
import axios from 'axios';
import { selected } from './selectedHackathon';
import { reducer as notifReducer, actions as notifActions, Notifs } from 're-notif';
const { notifSend } = notifActions;
import notification from './notification';
export const HACKATHONS = 'HACKATHONS';
export const SELECT = 'SELECT';
// ------------------------------------
// Actions
// ------------------------------------
export function hackathons (value: Array): Action {
return {
type: HACKATHONS,
payload: {hackathons: value}
};
}
export const listFromServer = () => (dispatch) => {
axios.get('/api/hackathons')
.then((res) => {
var response = res.data;
dispatch(hackathons(response));
});
};
export const selectToServer = (hackathon) => (dispatch) => {
dispatch(selected(hackathon));
};
export const actions = {
listFromServer,
selectToServer
};
// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
[HACKATHONS]: (state: array, action: {payload: array}): array => action.payload
};
// ------------------------------------
// Reducer
// ------------------------------------
const initialState = new Object();
export default function hackathonsReducers (state: Object = initialState, action: Action): Object {
const handler = ACTION_HANDLERS[action.type];
return handler ? handler(state, action) : state;
}
|
PhotoAlbums.LoginRoute = PhotoAlbums.Route.extend({
title: "Login",
setupController: function(controller, model) {
this._super(controller, model);
this.setApplicationContext(controller);
},
setApplicationContext: function(controller) {
var applicationController = this.controllerFor('application');
Ember.run(function() {
applicationController.set('album', undefined);
applicationController.set('header', 'Login');
applicationController.set('parentHeader', undefined);
});
}
});
|
// https://leetcode-cn.com/problems/generate-parentheses/
/**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function(n) {
let len = n * 2;
let arr = [[]];
for (let i = 0; i < len; i++) {
arr = generateBracket(arr);
}
const result = {};
for (let i = 0; i < arr.length; i++) {
let item = arr[i];
if (isValidBracket(item)) {
result[transformToChars(item)] = 1;
}
}
return Object.keys(result);
};
const generateBracket = (arr) => {
return [...arr.map(item => [...item, 1]), ...arr.map(item => [...item, -1])];
};
const isValidBracket = (arrParams) => {
let res = 0;
const arr = [...arrParams];
while (arr.length) {
res += arr.splice(0, 1)[0];
if (res < 0) {
return false;
}
}
return res === 0;
};
const transformToChars = (arr) => {
return arr.reduce((acc, cur) => acc + (cur === 1 ? '(' : ')'),'');
};
console.log(generateParenthesis(3));
|
var Service = function(){
this.data = {};
};
Service.prototype.getService = function(url,data){
var promise = $.ajax({
url: url,
async: false,
crossDomain: true,
method:'POST',
data:data
});
return promise;
};
|
/***********************************************************************
* app-src/js/yopcontext.js
* YeAPF 0.8.52-107 built on 2016-12-01 07:30 (-2 DST)
* Copyright (C) 2004-2016 Esteban Daniel Dortta - dortta@yahoo.com
* 2016-06-23 12:11:10 (-2 DST)
* First Version (C) 2014 - esteban daniel dortta - dortta@yahoo.com
*
* This is a set of function that helps to recognize operational context
**********************************************************************/
//# sourceURL=app-src/js/yopcontext.js
function getInternetExplorerVersion() {
/* http://msdn.microsoft.com/en-us/library/ms537509(v=vs.85).aspx
* Returns the version of Internet Explorer or a -1
* (indicating the use of another browser).
*/
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
function isInternetExplorer() {
return (getInternetExplorerVersion() >= 0);
};
function getAndroidVersion(ua) {
ua = (ua || navigator.userAgent).toLowerCase();
var match = ua.match(/android\s([0-9\.]*)/);
return match ? match[1] : false;
};
function isOnMobile() {
var ret=false;
_dump(navigator.userAgent);
if (typeof mosync != 'undefined') {
ret = mosync.isAndroid || mosync.isIOS || mosync.isWindowsPhone;
} else
ret=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
return ret;
};
|
const assert = require('assert');
const uint32 = 0xffffffff;
const fourbytes = 0xffffffff + 1;
const Poly1305 = require('seccamp2016-tls-poly1305');
function LeftRotate(x, n) {
assert(n > 0);
assert(32 > n);
var lowmask = uint32 >>> n;
var himask = (~lowmask & uint32) >>> 0;
var xhi = (x & himask) >>> 32 - n;
var xlow = ((x & lowmask) << n) >>> 0;
var ret = Plus(xhi, xlow);
return ret;
}
function Plus(a, b) {
a += b;
a %= fourbytes;
return a;
}
function RoundOperation(array) {
var a = array[0].readUInt32BE(0);
var b = array[1].readUInt32BE(0);
var c = array[2].readUInt32BE(0);
var d = array[3].readUInt32BE(0);
// 1.
a = Plus(a, b);
d ^= a;
d = LeftRotate(d, 16);
// 2.
c = Plus(c, d);
b ^= c;
b = LeftRotate(b, 12);
// 3.
a = Plus(a, b);
d ^= a;
d = LeftRotate(d, 8);
// 4.
c = Plus(c, d);
b ^= c;
b = LeftRotate(b, 7);
array[0].writeUInt32BE(a, 0);
array[1].writeUInt32BE(b, 0);
array[2].writeUInt32BE(c, 0);
array[3].writeUInt32BE(d, 0);
}
function QuarterRound(state, x, y, z, w) {
var data = [];
data[0] = state[x];
data[1] = state[y];
data[2] = state[z];
data[3] = state[w];
RoundOperation(data);
state[x] = data[0];
state[y] = data[1];
state[z] = data[2];
state[w] = data[3];
}
function ChaCha20InitState(key, nonce, count) {
var i;
var key_list = [];
for(i = 0; i < key.length; i += 4) {
var k = key.slice(i, i + 4);
var b = new Buffer(4);
b.writeUInt32BE(key.readUInt32LE(i), 0);
key_list.push(b);
}
var nonce_list = [];
for(i = 0; i < nonce.length; i += 4) {
var b = new Buffer(4);
b.writeUInt32BE(nonce.readUInt32LE(i), 0);
nonce_list.push(b);
}
var state = [
new Buffer('61707865', 'hex'),
new Buffer('3320646e', 'hex'),
new Buffer('79622d32', 'hex'),
new Buffer('6b206574', 'hex'),
key_list[0],
key_list[1],
key_list[2],
key_list[3],
key_list[4],
key_list[5],
key_list[6],
key_list[7],
count,
nonce_list[0],
nonce_list[1],
nonce_list[2]
];
return state;
}
function StateDup(a) {
var b = [];
for(var i = 0; i < a.length; i++) {
var buf = new Buffer(4);
a[i].copy(buf);
b.push(buf);
}
return b;
}
function StatePlus(a, b) {
var c = [];
for(var i = 0; i < 16; i++) {
var buf = new Buffer(4);
buf.writeUInt32BE(Plus(a[i].readUInt32BE(0), b[i].readUInt32BE(0)), 0);
c.push(buf);
}
return c;
}
function ChaCha20Block(key, nonce, count) {
var init_state = ChaCha20InitState(key, nonce, count);
var state = StateDup(init_state);
for(var i = 0; i < 10; i++) {
QuarterRound(state, 0, 4, 8, 12);
QuarterRound(state, 1, 5, 9, 13);
QuarterRound(state, 2, 6, 10, 14);
QuarterRound(state, 3, 7, 11, 15);
QuarterRound(state, 0, 5, 10, 15);
QuarterRound(state, 1, 6, 11, 12);
QuarterRound(state, 2, 7, 8, 13);
QuarterRound(state, 3, 4, 9, 14);
}
return StatePlus(init_state, state);
}
function ChaCha20KeyStream(key, nonce, count_buf) {
var key_stream = new Buffer(64);
var state = ChaCha20Block(key, nonce, count_buf);
for(var i = 0; i < state.length; i++) {
key_stream.writeUInt32BE(state[i].readUInt32LE(0), 4*i);
}
return key_stream;
}
function BufferXOR(a, b) {
var c = new Buffer(a.length);
for(var i = 0; i < a.length; i++) {
c[i] = a[i] ^ b[i];
}
return c;
}
function ChaCha20Encrypt(key, nonce, count, plain) {
var encrypted_list = [];
var count_buf;
for(var j = 0; j < Math.floor(plain.length/64); j++) {
count_buf = new Buffer(4);
count_buf.writeUInt32BE(count+j);
var key_stream = ChaCha20KeyStream(key, nonce, count_buf);
var block = plain.slice(j*64, (j + 1)*64);
var encrypted = BufferXOR(block, key_stream);
encrypted_list.push(encrypted);
}
if (plain.length % 64 !== 0) {
var j = Math.floor(plain.length/64);
count_buf = new Buffer(4);
count_buf.writeUInt32BE(count+j);
var key_stream = ChaCha20KeyStream(key, nonce, count_buf);
var block = plain.slice(j*64);
var encrypted = BufferXOR(block, key_stream.slice(0, block.length));
encrypted_list.push(encrypted);
}
return Buffer.concat(encrypted_list);
}
function Poly1305KeyGeneration(key, nonce) {
var counter = (new Buffer(4)).fill(0);
var block = ChaCha20KeyStream(key, nonce, counter);
return block.slice(0, 32);
}
function Pad16(x) {
assert(Buffer.isBuffer(x));
if (x.length % 16 === 0) {
return new Buffer(0);
} else {
var buf = (new Buffer(16 - x.length % 16)).fill(0x00);
return buf;
}
}
function ChaCha20Poly1305Code(aad, key, nonce, data) {
var otk = Poly1305KeyGeneration(key, nonce);
var counter = 1;
var coded_data = ChaCha20Encrypt(key, nonce, counter, data);
return {data: coded_data, otk: otk};
}
function ChaCha20Poly1305Encrypt(aad, key, nonce, plaintext) {
var coded = ChaCha20Poly1305Code(aad, key, nonce, plaintext);
var ciphertext = coded.data;
var otk = coded.otk;
var aad_length = (new Buffer(8)).fill(0x00);
aad_length.writeUInt32LE(aad.length);
var ciphertext_length = (new Buffer(8)).fill(0x00);
ciphertext_length.writeUInt32LE(ciphertext.length);
var mac_data = Buffer.concat([aad, Pad16(aad), ciphertext, Pad16(ciphertext), aad_length, ciphertext_length]);
var tag = Poly1305.Poly1305Mac(mac_data, otk);
return {ciphertext: ciphertext, tag: tag};
}
var aad = new Buffer('50515253c0c1c2c3c4c5c6c7', 'hex');
var key = new Buffer('808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f', 'hex');
var iv = new Buffer('070000004041424344454647', 'hex');
var plain = new Buffer("Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it.", 'utf8');
var encrypted = ChaCha20Poly1305Encrypt(aad, key, iv, plain);
console.log(Buffer.concat([encrypted.ciphertext, encrypted.tag]).toString('hex'));
|
this.workbox=this.workbox||{},this.workbox.navigationPreload=function(t){"use strict";try{self.workbox.v["workbox:navigation-preload:3.4.1"]=1}catch(t){}function e(){return Boolean(self.registration&&self.registration.navigationPreload)}return t.enable=function(t){e()&&self.addEventListener("activate",e=>{e.waitUntil(self.registration.navigationPreload.enable().then(()=>{t&&self.registration.navigationPreload.setHeaderValue(t)}))})},t.isSupported=e,t}({});
//# sourceMappingURL=workbox-navigation-preload.prod.js.map
|
// ****************************************
// Execute model changes
// ****************************************
function modelChanges(changes) {
//console.log("changes = "+JSON.stringify(changes, null, 2));
var tasklist = _.pluck(changes, 'name');
//console.log("tasklist = "+tasklist);
// Just got the geometry yo. Let's make a map.
if (_.contains(tasklist, "targetLayer")) {
//console.log("tasklist targetLayer");
if(activeLayer == "census"){
// neighborhoods = censusFeatures;
// metricConfig = censusMetricConfig;
// metricConfig = neighborhoodMetricConfig;
// var modelTargetLayer = model.targetLayer;
// console.log('model.targetLayer = '+modelTargetLayer);
// metricConfig = censusMetricConfig;
// map.removeLayer(d3NeighborhoodLayer);
// getMetricValues();
// model.metricId = $("#metric").val();
// d3Layer = undefined;
// // fetchMetricData(model.metricId, changeTargetLayer);
// fetchMetricData(model.metricId);
}
else if(activeLayer == "neighborhood"){
// neighborhoods = neighborhoodFeatures;
// metricConfig = neighborhoodMetricConfig;
// var modelTargetLayer = model.targetLayer;
// console.log('model.targetLayer = '+modelTargetLayer);
// map.removeLayer(d3CensusLayer);
// getMetricValues();
// model.metricId = $("#metric").val();
// d3Layer = undefined;
// // fetchMetricData(model.metricId, changeTargetLayer);
// fetchMetricData(model.metricId);
}
// switchMap(modelTargetLayer);
}
if (_.contains(tasklist, "geom")) {
//console.log("tasklist geom activeLayer = " + activeLayer + " map.hasLayer(d3NeighborhoodLayer) = " + map.hasLayer(d3NeighborhoodLayer) + " map.hasLayer(d3CensusLayer) = " + map.hasLayer(d3CensusLayer)+" blInitMap = " + blInitMap);
if (blInitMap== true){
//console.log("tasklist geom initMap");
initMap();
initTypeahead();
}
}
// the metric id changed, get some data
if (_.contains(tasklist, "metricId")) {
// Make sure a year has been set before
//console.log("metricId fired");
var metricChange = _.filter(changes, function(el) { return el.name === "metricId"; });
if (metricChange[0].hasOwnProperty('oldValue')) {
// change chosen if not samsies
if (model.metricId !== undefined && $(".chosen-select").chosen().val() !== model.metricId) {
$('.chosen-select').val(model.metricId);
$('.chosen-select').trigger("chosen:updated");
}
//console.log("observer model.metricId = "+model.metricId);
fetchMetricData(model.metricId);
verticalBarChart();
}
}
// Metrics in the house
if (_.contains(tasklist, "metric")) {
processMetric();
drawMap();
drawBarChart();
//*****Remove the line chart functions
// lineChartCreate();
updateMeta();
updateStats();
drawTable();
if (recordHistory) { recordMetricHistory(); }
recordHistory = true;
verticalBarChart();
}
// the selected set changed
if (_.contains(tasklist, "selected")) {
//console.log("tasklist selected model.selected.length = "+model.selected.length);
d3.selectAll(".geom").classed("d3-select", false);
d3.selectAll(".geom").classed("d3-select", function(d) { return _.contains(model.selected, $(this).attr("data-id")); });
$(".report-launch").removeClass("disabled");
// valueChart.selectedPointer(".value-select");
//*****Remove the line chart functions
// lineChartCreate();
updateStats();
drawTable();
if (recordHistory) { recordMetricHistory(); }
recordHistory = true;
if (model.selected.length === 0) {
//console.log("tasklist selected model.selected.length === 0");
// disable report links and remove map marker
$(".report-launch").addClass("disabled");
try {
map.removeLayer(marker);
if (model.selected.length == 0){
//console.log("drawTable model.selected.length == 0");
if (blTargetLayerChange == true){
//console.log("blTargetLayerChange == true");
var evt = document.createEvent("Event");
evt.initEvent("drawTable targetLayerChanged",true,true);
document.dispatchEvent(evt);
verticalBarChart();
}
}
}
catch (err) {}
}
}
}
function changeYear() {
// change year slider if not samsies
if ($('.slider').slider('value') !== model.year) {
$('.slider').slider('value', model.year);
verticalBarChart();
}
var keys = Object.keys(model.metric[0]);
$('.time-year').text(keys[model.year + 1].replace("y_", ""));
// set up data quantile from extent
//console.log("changeYearFail");
quantize = d3.scale.quantile()
.domain(x_extent)
.range(d3.range(colorbreaks).map(function (i) {
return "q" + i;
}));
drawMap();
drawBarChart();
drawTable();
updateStats();
}
function getMetricValues(){
//console.log("getMetrticValues Fired");
$("#metric").empty();
//console.log("selectLength = " + $('#metric option').length);
// _.each(metricConfig, function(el, key) {
// console.log("genericMetric = "+el.title);
// });
// load metrics
console.log("metricConfig: " + JSON.stringify(metricConfig));
var selectVals = '',
selectGroup = '';
_.each(metricConfig, function(el, key) {
// console.log("el.title = " + el.title);
if (el.category === selectGroup) {
selectVals += '<option value="' + key + '">' + el.title + '</option>';
} else {
if (selectVals.length > 0) { selectVals += '</optgroup>'; }
selectVals += '<optgroup label="' + el.category + '">';
selectVals += '<option value="' + key + '">' + el.title + '</option>';
selectGroup = el.category;
}
});
// console.log("selectVals = " + selectVals);
selectVals += '</optgroup>';
$("#metric").html(selectVals);
$("#metric").trigger("chosen:updated");
//console.log("selectLength = " + $('#metric option').length);
//console.log("selected Metric = " + $("#metric option:selected").text());
}
function changeTargetLayer() {
processMetric();
drawMap();
drawBarChart();//
//*****Remove the line chart functions
lineChartCreate();//
updateMeta();
updateStats();
drawTable();
// createVerticalBarChart();
}
|
/**
* Pure JavaScript implementation of zoom.js.
*
* Original preamble:
* zoom.js - It's the best way to zoom an image
* @version v0.0.2
* @link https://github.com/fat/zoom.js
* @license MIT
*
*/
class ZoomJS extends HTMLElement {
constructor() {
super();
this.zoom = this.firstElementChild; // Img node
this.offset = 80; // Offset to margin-left
this.initialTouchPos = 0;
this.initialScroll = 0;
if (this.zoom) this.zoom.preservedTransform = this.zoom.style.transform; // Preserve styles
this.zoomEvents = {
handler: this.zoomOut.bind(this.zoom),
scroll: e => {
if (this.initialScroll) this.initialScroll = window.pageYOffset;
const pos = window.pageYOffset;
if (Math.abs(this.initialScroll - pos) >= 60) {
this.zoomEvents.handler();
}
},
escapeKey: e => {
if (e.keyCode == 27) this.zoomEvents.handler();
},
touchMove: e => {
const pos = e.touches[0].pageY;
if (Math.abs(this.initialTouchPos - pos) > 10) {
this.zoomEvents.handler();
}
},
firstTouch: e => this.initialTouchPos = e.touches[0].pageY
};
}
connectedCallback() {
// Initialize after DOM insertion
if (this.zoom) {
this.zoom.style.cursor = "zoom-in";
this.addEventListener("click", e => {
if (e.metaKey || e.ctrlKey) {
window.open(e.target.src);
return this.connectedCallback();
}
if (e.target.width >= document.documentElement.clientWidth - this.offset) {
return Error("Image exceeds screen width");
}
this.zoomIn.call(this.zoom);
this.zoomListeners();
return "zoomed";
}, { once: true });
}
}
zoomIn() {
// this is bound to the child image node
const scale = (() => {
const maxScaleFactor = this.naturalWidth / this.width,
viewportWidth = document.documentElement.clientWidth - this.parentElement.offset,
viewportHeight = document.documentElement.clientHeight - this.parentElement.offset,
imageAspectRatio = this.naturalWidth / this.naturalHeight,
viewportAspectRatio = viewportWidth / viewportHeight;
if (this.naturalWidth < viewportWidth && this.naturalHeight < viewportHeight) {
return maxScaleFactor;
} else if (imageAspectRatio < viewportAspectRatio) {
return (viewportHeight / this.naturalHeight) * maxScaleFactor;
} else {
return (viewportWidth / this.naturalWidth) * maxScaleFactor;
}
})();
const imageOffset = (() => {
const rect = this.getBoundingClientRect();
return {
top: rect.top + window.pageYOffset - document.documentElement.clientTop,
left: rect.left + window.pageXOffset - document.documentElement.clientLeft
};
})();
Object.assign(this.parentElement.style, {
display: "block",
transition: "all 300ms"
});
Object.assign(this.style, {
outline: "100vw solid transparent",
transition: "all 300ms",
pointerEvents: "auto",
cursor: "zoom-out"
});
Object.assign(document.body.style, {
pointerEvents: "none"
});
(function animate() {
const scrollTop = window.pageYOffset,
viewportX = (document.documentElement.clientWidth / 2),
viewportY = scrollTop + (document.documentElement.clientHeight / 2),
imageCenterX = imageOffset.left + (this.width / 2),
imageCenterY = imageOffset.top + (this.height / 2),
tx = viewportX - imageCenterX,
ty = viewportY - imageCenterY,
tz = 0;
Object.assign(this.parentElement.style, {
transform: `translate3d(${tx}px, ${ty}px, ${tz}px)`
});
Object.assign(this.style, {
outlineColor: "#fff",
transform: `scale(${scale})`
});
}).call(this);
}
zoomOut() {
// this is bound to the child image node
const sleep = ms => new Promise(resolve => window.setTimeout(resolve, ms));
(async function cleanup() {
this.parentElement.zoomListeners("remove");
Object.assign(this.parentElement.style, {
transform: `none`
});
Object.assign(this.style, {
outlineColor: "transparent",
transform: this.preservedTransform
});
await sleep(300);
Object.assign(this.parentElement.style, {
display: "",
transition: ""
});
Object.assign(this.style, {
outline: "",
outlineColor: "",
transition: "",
cursor: "zoom-in"
});
Object.assign(document.body.style, {
pointerEvents: "auto"
});
// Restart the Zoom Cycle
this.parentElement.connectedCallback();
}).call(this);
}
zoomListeners(remove) {
if (remove) {
document.removeEventListener("scroll", this.zoomEvents.scroll);
document.removeEventListener("keyup", this.zoomEvents.escapeKey);
document.removeEventListener("touchstart", this.zoomEvents.firstTouch);
document.removeEventListener("touchmove", this.zoomEvents.touchMove);
document.removeEventListener("click", this.zoomEvents.handler, true);
} else {
document.addEventListener("scroll", this.zoomEvents.scroll);
document.addEventListener("keyup", this.zoomEvents.escapeKey, { once: true });
document.addEventListener("touchstart", this.zoomEvents.firstTouch, {once: true});
document.addEventListener("touchmove", this.zoomEvents.touchMove);
document.addEventListener("click", this.zoomEvents.handler, { capture: true, once: true });
}
}
}
customElements.define('zoom-js', ZoomJS);
|
$Behavior.datePicker = function()
{
$('.js_date_picker').datepicker({
onSelect: function(dateText, inst)
{
var aParts = explode('/', dateText);
var sMonth = ltrim(aParts[0], '0');
var sDay = ltrim(aParts[1], '0');
$(this).parents('.js_datepicker_holder:first').find('.js_datepicker_month').val(sMonth);
$(this).parents('.js_datepicker_holder:first').find('.js_datepicker_day').val(sDay);
$(this).parents('.js_datepicker_holder:first').find('.js_datepicker_year').val(aParts[2]);
}
});
}
|
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
/**
* @license Angular v4.1.0
* (c) 2010-2017 Google, Inc. https://angular.io/
* License: MIT
*/
import { AUTO_STYLE, NoopAnimationPlayer, sequence, style, ɵAnimationGroupPlayer } from '@angular/animations';
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @experimental
*/
var NoopAnimationDriver = (function () {
function NoopAnimationDriver() {
}
NoopAnimationDriver.prototype.animate = function (element, keyframes, duration, delay, easing, previousPlayers) {
if (previousPlayers === void 0) { previousPlayers = []; }
return new NoopAnimationPlayer();
};
return NoopAnimationDriver;
}());
/**
* @experimental
*/
var AnimationDriver = (function () {
function AnimationDriver() {
}
return AnimationDriver;
}());
AnimationDriver.NOOP = new NoopAnimationDriver();
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @abstract
*/
var AnimationEngine = (function () {
function AnimationEngine() {
}
/**
* @abstract
* @param {?} trigger
* @param {?=} name
* @return {?}
*/
AnimationEngine.prototype.registerTrigger = function (trigger, name) { };
/**
* @abstract
* @param {?} element
* @param {?} domFn
* @return {?}
*/
AnimationEngine.prototype.onInsert = function (element, domFn) { };
/**
* @abstract
* @param {?} element
* @param {?} domFn
* @return {?}
*/
AnimationEngine.prototype.onRemove = function (element, domFn) { };
/**
* @abstract
* @param {?} element
* @param {?} property
* @param {?} value
* @return {?}
*/
AnimationEngine.prototype.setProperty = function (element, property, value) { };
/**
* @abstract
* @param {?} element
* @param {?} eventName
* @param {?} eventPhase
* @param {?} callback
* @return {?}
*/
AnimationEngine.prototype.listen = function (element, eventName, eventPhase, callback) { };
/**
* @abstract
* @return {?}
*/
AnimationEngine.prototype.flush = function () { };
Object.defineProperty(AnimationEngine.prototype, "activePlayers", {
/**
* @return {?}
*/
get: function () { throw new Error('...'); },
enumerable: true,
configurable: true
});
Object.defineProperty(AnimationEngine.prototype, "queuedPlayers", {
/**
* @return {?}
*/
get: function () { throw new Error('...'); },
enumerable: true,
configurable: true
});
return AnimationEngine;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var ONE_SECOND = 1000;
/**
* @param {?} exp
* @param {?} errors
* @return {?}
*/
function parseTimeExpression(exp, errors) {
var /** @type {?} */ regex = /^([\.\d]+)(m?s)(?:\s+([\.\d]+)(m?s))?(?:\s+([-a-z]+(?:\(.+?\))?))?$/i;
var /** @type {?} */ duration;
var /** @type {?} */ delay = 0;
var /** @type {?} */ easing = null;
if (typeof exp === 'string') {
var /** @type {?} */ matches = exp.match(regex);
if (matches === null) {
errors.push("The provided timing value \"" + exp + "\" is invalid.");
return { duration: 0, delay: 0, easing: null };
}
var /** @type {?} */ durationMatch = parseFloat(matches[1]);
var /** @type {?} */ durationUnit = matches[2];
if (durationUnit == 's') {
durationMatch *= ONE_SECOND;
}
duration = Math.floor(durationMatch);
var /** @type {?} */ delayMatch = matches[3];
var /** @type {?} */ delayUnit = matches[4];
if (delayMatch != null) {
var /** @type {?} */ delayVal = parseFloat(delayMatch);
if (delayUnit != null && delayUnit == 's') {
delayVal *= ONE_SECOND;
}
delay = Math.floor(delayVal);
}
var /** @type {?} */ easingVal = matches[5];
if (easingVal) {
easing = easingVal;
}
}
else {
duration = (exp);
}
return { duration: duration, delay: delay, easing: easing };
}
/**
* @param {?} styles
* @return {?}
*/
function normalizeStyles(styles) {
var /** @type {?} */ normalizedStyles = {};
if (Array.isArray(styles)) {
styles.forEach(function (data) { return copyStyles(data, false, normalizedStyles); });
}
else {
copyStyles(styles, false, normalizedStyles);
}
return normalizedStyles;
}
/**
* @param {?} styles
* @param {?} readPrototype
* @param {?=} destination
* @return {?}
*/
function copyStyles(styles, readPrototype, destination) {
if (destination === void 0) { destination = {}; }
if (readPrototype) {
// we make use of a for-in loop so that the
// prototypically inherited properties are
// revealed from the backFill map
for (var /** @type {?} */ prop in styles) {
destination[prop] = styles[prop];
}
}
else {
Object.keys(styles).forEach(function (prop) { return destination[prop] = styles[prop]; });
}
return destination;
}
/**
* @param {?} element
* @param {?} styles
* @return {?}
*/
function setStyles(element, styles) {
if (element['style']) {
Object.keys(styles).forEach(function (prop) { return element.style[prop] = styles[prop]; });
}
}
/**
* @param {?} element
* @param {?} styles
* @return {?}
*/
function eraseStyles(element, styles) {
if (element['style']) {
Object.keys(styles).forEach(function (prop) {
// IE requires '' instead of null
// see https://github.com/angular/angular/issues/7916
element.style[prop] = '';
});
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @param {?} visitor
* @param {?} node
* @param {?} context
* @return {?}
*/
function visitAnimationNode(visitor, node, context) {
switch (node.type) {
case 0 /* State */:
return visitor.visitState(/** @type {?} */ (node), context);
case 1 /* Transition */:
return visitor.visitTransition(/** @type {?} */ (node), context);
case 2 /* Sequence */:
return visitor.visitSequence(/** @type {?} */ (node), context);
case 3 /* Group */:
return visitor.visitGroup(/** @type {?} */ (node), context);
case 4 /* Animate */:
return visitor.visitAnimate(/** @type {?} */ (node), context);
case 5 /* KeyframeSequence */:
return visitor.visitKeyframeSequence(/** @type {?} */ (node), context);
case 6 /* Style */:
return visitor.visitStyle(/** @type {?} */ (node), context);
default:
throw new Error("Unable to resolve animation metadata node #" + node.type);
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var ANY_STATE = '*';
/**
* @param {?} transitionValue
* @param {?} errors
* @return {?}
*/
function parseTransitionExpr(transitionValue, errors) {
var /** @type {?} */ expressions = [];
if (typeof transitionValue == 'string') {
((transitionValue))
.split(/\s*,\s*/)
.forEach(function (str) { return parseInnerTransitionStr(str, expressions, errors); });
}
else {
expressions.push(/** @type {?} */ (transitionValue));
}
return expressions;
}
/**
* @param {?} eventStr
* @param {?} expressions
* @param {?} errors
* @return {?}
*/
function parseInnerTransitionStr(eventStr, expressions, errors) {
if (eventStr[0] == ':') {
eventStr = parseAnimationAlias(eventStr, errors);
}
var /** @type {?} */ match = eventStr.match(/^(\*|[-\w]+)\s*(<?[=-]>)\s*(\*|[-\w]+)$/);
if (match == null || match.length < 4) {
errors.push("The provided transition expression \"" + eventStr + "\" is not supported");
return expressions;
}
var /** @type {?} */ fromState = match[1];
var /** @type {?} */ separator = match[2];
var /** @type {?} */ toState = match[3];
expressions.push(makeLambdaFromStates(fromState, toState));
var /** @type {?} */ isFullAnyStateExpr = fromState == ANY_STATE && toState == ANY_STATE;
if (separator[0] == '<' && !isFullAnyStateExpr) {
expressions.push(makeLambdaFromStates(toState, fromState));
}
}
/**
* @param {?} alias
* @param {?} errors
* @return {?}
*/
function parseAnimationAlias(alias, errors) {
switch (alias) {
case ':enter':
return 'void => *';
case ':leave':
return '* => void';
default:
errors.push("The transition alias value \"" + alias + "\" is not supported");
return '* => *';
}
}
/**
* @param {?} lhs
* @param {?} rhs
* @return {?}
*/
function makeLambdaFromStates(lhs, rhs) {
return function (fromState, toState) {
var /** @type {?} */ lhsMatch = lhs == ANY_STATE || lhs == fromState;
var /** @type {?} */ rhsMatch = rhs == ANY_STATE || rhs == toState;
return lhsMatch && rhsMatch;
};
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @param {?} keyframes
* @param {?} duration
* @param {?} delay
* @param {?} easing
* @return {?}
*/
function createTimelineInstruction(keyframes, duration, delay, easing) {
return {
type: 1 /* TimelineAnimation */,
keyframes: keyframes,
duration: duration,
delay: delay,
totalTime: duration + delay, easing: easing
};
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @param {?} ast
* @param {?=} startingStyles
* @param {?=} finalStyles
* @return {?}
*/
function buildAnimationKeyframes(ast, startingStyles, finalStyles) {
if (startingStyles === void 0) { startingStyles = {}; }
if (finalStyles === void 0) { finalStyles = {}; }
var /** @type {?} */ normalizedAst = Array.isArray(ast) ? sequence(/** @type {?} */ (ast)) : (ast);
return new AnimationTimelineVisitor().buildKeyframes(normalizedAst, startingStyles, finalStyles);
}
var AnimationTimelineContext = (function () {
/**
* @param {?} errors
* @param {?} timelines
* @param {?=} initialTimeline
*/
function AnimationTimelineContext(errors, timelines, initialTimeline) {
this.errors = errors;
this.timelines = timelines;
this.previousNode = ({});
this.subContextCount = 0;
this.currentTimeline = initialTimeline || new TimelineBuilder(0);
timelines.push(this.currentTimeline);
}
/**
* @return {?}
*/
AnimationTimelineContext.prototype.createSubContext = function () {
var /** @type {?} */ context = new AnimationTimelineContext(this.errors, this.timelines, this.currentTimeline.fork());
context.previousNode = this.previousNode;
context.currentAnimateTimings = this.currentAnimateTimings;
this.subContextCount++;
return context;
};
/**
* @param {?=} newTime
* @return {?}
*/
AnimationTimelineContext.prototype.transformIntoNewTimeline = function (newTime) {
if (newTime === void 0) { newTime = 0; }
this.currentTimeline = this.currentTimeline.fork(newTime);
this.timelines.push(this.currentTimeline);
return this.currentTimeline;
};
/**
* @param {?} time
* @return {?}
*/
AnimationTimelineContext.prototype.incrementTime = function (time) {
this.currentTimeline.forwardTime(this.currentTimeline.duration + time);
};
return AnimationTimelineContext;
}());
var AnimationTimelineVisitor = (function () {
function AnimationTimelineVisitor() {
}
/**
* @param {?} ast
* @param {?} startingStyles
* @param {?} finalStyles
* @return {?}
*/
AnimationTimelineVisitor.prototype.buildKeyframes = function (ast, startingStyles, finalStyles) {
var /** @type {?} */ context = new AnimationTimelineContext([], []);
context.currentTimeline.setStyles(startingStyles);
visitAnimationNode(this, ast, context);
// this checks to see if an actual animation happened
var /** @type {?} */ timelines = context.timelines.filter(function (timeline) { return timeline.hasStyling(); });
if (timelines.length && Object.keys(finalStyles).length) {
var /** @type {?} */ tl = timelines[timelines.length - 1];
if (!tl.allowOnlyTimelineStyles()) {
tl.setStyles(finalStyles);
}
}
return timelines.length ? timelines.map(function (timeline) { return timeline.buildKeyframes(); }) :
[createTimelineInstruction([], 0, 0, '')];
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationTimelineVisitor.prototype.visitState = function (ast, context) {
// these values are not visited in this AST
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationTimelineVisitor.prototype.visitTransition = function (ast, context) {
// these values are not visited in this AST
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationTimelineVisitor.prototype.visitSequence = function (ast, context) {
var _this = this;
var /** @type {?} */ subContextCount = context.subContextCount;
if (context.previousNode.type == 6 /* Style */) {
context.currentTimeline.forwardFrame();
context.currentTimeline.snapshotCurrentStyles();
}
ast.steps.forEach(function (s) { return visitAnimationNode(_this, s, context); });
// this means that some animation function within the sequence
// ended up creating a sub timeline (which means the current
// timeline cannot overlap with the contents of the sequence)
if (context.subContextCount > subContextCount) {
context.transformIntoNewTimeline();
}
context.previousNode = ast;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationTimelineVisitor.prototype.visitGroup = function (ast, context) {
var _this = this;
var /** @type {?} */ innerTimelines = [];
var /** @type {?} */ furthestTime = context.currentTimeline.currentTime;
ast.steps.forEach(function (s) {
var /** @type {?} */ innerContext = context.createSubContext();
visitAnimationNode(_this, s, innerContext);
furthestTime = Math.max(furthestTime, innerContext.currentTimeline.currentTime);
innerTimelines.push(innerContext.currentTimeline);
});
// this operation is run after the AST loop because otherwise
// if the parent timeline's collected styles were updated then
// it would pass in invalid data into the new-to-be forked items
innerTimelines.forEach(function (timeline) { return context.currentTimeline.mergeTimelineCollectedStyles(timeline); });
context.transformIntoNewTimeline(furthestTime);
context.previousNode = ast;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationTimelineVisitor.prototype.visitAnimate = function (ast, context) {
var /** @type {?} */ timings = ast.timings.hasOwnProperty('duration') ? (ast.timings) :
parseTimeExpression(/** @type {?} */ (ast.timings), context.errors);
context.currentAnimateTimings = timings;
if (timings.delay) {
context.incrementTime(timings.delay);
context.currentTimeline.snapshotCurrentStyles();
}
var /** @type {?} */ astType = ast.styles ? ast.styles.type : -1;
if (astType == 5 /* KeyframeSequence */) {
this.visitKeyframeSequence(/** @type {?} */ (ast.styles), context);
}
else {
var /** @type {?} */ styleAst = (ast.styles);
if (!styleAst) {
var /** @type {?} */ newStyleData = {};
if (timings.easing) {
newStyleData['easing'] = timings.easing;
}
styleAst = style(newStyleData);
((styleAst))['treatAsEmptyStep'] = true;
}
context.incrementTime(timings.duration);
if (styleAst) {
this.visitStyle(styleAst, context);
}
}
context.currentAnimateTimings = null;
context.previousNode = ast;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationTimelineVisitor.prototype.visitStyle = function (ast, context) {
// this is a special case when a style() call is issued directly after
// a call to animate(). If the clock is not forwarded by one frame then
// the style() calls will be merged into the previous animate() call
// which is incorrect.
if (!context.currentAnimateTimings &&
context.previousNode.type == 4 /* Animate */) {
context.currentTimeline.forwardFrame();
}
var /** @type {?} */ normalizedStyles = normalizeStyles(ast.styles);
var /** @type {?} */ easing = context.currentAnimateTimings && context.currentAnimateTimings.easing;
this._applyStyles(normalizedStyles, easing, ((ast))['treatAsEmptyStep'] ? true : false, context);
context.previousNode = ast;
};
/**
* @param {?} styles
* @param {?} easing
* @param {?} treatAsEmptyStep
* @param {?} context
* @return {?}
*/
AnimationTimelineVisitor.prototype._applyStyles = function (styles, easing, treatAsEmptyStep, context) {
if (styles.hasOwnProperty('easing')) {
easing = easing || (styles['easing']);
delete styles['easing'];
}
context.currentTimeline.setStyles(styles, easing, treatAsEmptyStep);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationTimelineVisitor.prototype.visitKeyframeSequence = function (ast, context) {
var _this = this;
var /** @type {?} */ MAX_KEYFRAME_OFFSET = 1;
var /** @type {?} */ limit = ast.steps.length - 1;
var /** @type {?} */ firstKeyframe = ast.steps[0];
var /** @type {?} */ offsetGap = 0;
var /** @type {?} */ containsOffsets = getOffset(firstKeyframe) != null;
if (!containsOffsets) {
offsetGap = MAX_KEYFRAME_OFFSET / limit;
}
var /** @type {?} */ startTime = context.currentTimeline.duration;
var /** @type {?} */ duration = ((context.currentAnimateTimings)).duration;
var /** @type {?} */ innerContext = context.createSubContext();
var /** @type {?} */ innerTimeline = innerContext.currentTimeline;
innerTimeline.easing = ((context.currentAnimateTimings)).easing;
ast.steps.forEach(function (step, i) {
var /** @type {?} */ normalizedStyles = normalizeStyles(step.styles);
var /** @type {?} */ offset = containsOffsets ?
(step.offset != null ? step.offset : parseFloat(/** @type {?} */ (normalizedStyles['offset']))) :
(i == limit ? MAX_KEYFRAME_OFFSET : i * offsetGap);
innerTimeline.forwardTime(offset * duration);
_this._applyStyles(normalizedStyles, null, false, innerContext);
});
// this will ensure that the parent timeline gets all the styles from
// the child even if the new timeline below is not used
context.currentTimeline.mergeTimelineCollectedStyles(innerTimeline);
// we do this because the window between this timeline and the sub timeline
// should ensure that the styles within are exactly the same as they were before
context.transformIntoNewTimeline(startTime + duration);
context.previousNode = ast;
};
return AnimationTimelineVisitor;
}());
var TimelineBuilder = (function () {
/**
* @param {?} startTime
* @param {?=} globalTimelineStyles
*/
function TimelineBuilder(startTime, globalTimelineStyles) {
this.startTime = startTime;
this.duration = 0;
this.easing = '';
this._previousKeyframe = {};
this._keyframes = new Map();
this._styleSummary = {};
this._backFill = {};
this._currentEmptyStepKeyframe = null;
this._localTimelineStyles = Object.create(this._backFill, {});
this._globalTimelineStyles =
globalTimelineStyles ? globalTimelineStyles : this._localTimelineStyles;
this._loadKeyframe();
}
/**
* @return {?}
*/
TimelineBuilder.prototype.hasStyling = function () { return this._keyframes.size > 1; };
Object.defineProperty(TimelineBuilder.prototype, "currentTime", {
/**
* @return {?}
*/
get: function () { return this.startTime + this.duration; },
enumerable: true,
configurable: true
});
/**
* @param {?=} currentTime
* @return {?}
*/
TimelineBuilder.prototype.fork = function (currentTime) {
if (currentTime === void 0) { currentTime = 0; }
return new TimelineBuilder(currentTime || this.currentTime, this._globalTimelineStyles);
};
/**
* @return {?}
*/
TimelineBuilder.prototype._loadKeyframe = function () {
if (this._currentKeyframe) {
this._previousKeyframe = this._currentKeyframe;
}
this._currentKeyframe = ((this._keyframes.get(this.duration)));
if (!this._currentKeyframe) {
this._currentKeyframe = Object.create(this._backFill, {});
this._keyframes.set(this.duration, this._currentKeyframe);
}
};
/**
* @return {?}
*/
TimelineBuilder.prototype.forwardFrame = function () {
this.duration++;
this._loadKeyframe();
};
/**
* @param {?} time
* @return {?}
*/
TimelineBuilder.prototype.forwardTime = function (time) {
this.duration = time;
this._loadKeyframe();
};
/**
* @param {?} prop
* @param {?} value
* @return {?}
*/
TimelineBuilder.prototype._updateStyle = function (prop, value) {
this._localTimelineStyles[prop] = value; /** @type {?} */
((this._globalTimelineStyles))[prop] = value;
this._styleSummary[prop] = { time: this.currentTime, value: value };
};
/**
* @return {?}
*/
TimelineBuilder.prototype.allowOnlyTimelineStyles = function () { return this._currentEmptyStepKeyframe !== this._currentKeyframe; };
/**
* @param {?} styles
* @param {?=} easing
* @param {?=} treatAsEmptyStep
* @return {?}
*/
TimelineBuilder.prototype.setStyles = function (styles, easing, treatAsEmptyStep) {
var _this = this;
if (easing === void 0) { easing = null; }
if (treatAsEmptyStep === void 0) { treatAsEmptyStep = false; }
if (easing) {
((this._previousKeyframe))['easing'] = easing;
}
if (treatAsEmptyStep) {
// special case for animate(duration):
// all missing styles are filled with a `*` value then
// if any destination styles are filled in later on the same
// keyframe then they will override the overridden styles
// We use `_globalTimelineStyles` here because there may be
// styles in previous keyframes that are not present in this timeline
Object.keys(this._globalTimelineStyles).forEach(function (prop) {
_this._backFill[prop] = _this._globalTimelineStyles[prop] || AUTO_STYLE;
_this._currentKeyframe[prop] = AUTO_STYLE;
});
this._currentEmptyStepKeyframe = this._currentKeyframe;
}
else {
Object.keys(styles).forEach(function (prop) {
if (prop !== 'offset') {
var /** @type {?} */ val = styles[prop];
_this._currentKeyframe[prop] = val;
if (!_this._localTimelineStyles[prop]) {
_this._backFill[prop] = _this._globalTimelineStyles[prop] || AUTO_STYLE;
}
_this._updateStyle(prop, val);
}
});
Object.keys(this._localTimelineStyles).forEach(function (prop) {
if (!_this._currentKeyframe.hasOwnProperty(prop)) {
_this._currentKeyframe[prop] = _this._localTimelineStyles[prop];
}
});
}
};
/**
* @return {?}
*/
TimelineBuilder.prototype.snapshotCurrentStyles = function () { copyStyles(this._localTimelineStyles, false, this._currentKeyframe); };
/**
* @return {?}
*/
TimelineBuilder.prototype.getFinalKeyframe = function () { return ((this._keyframes.get(this.duration))); };
Object.defineProperty(TimelineBuilder.prototype, "properties", {
/**
* @return {?}
*/
get: function () {
var /** @type {?} */ properties = [];
for (var /** @type {?} */ prop in this._currentKeyframe) {
properties.push(prop);
}
return properties;
},
enumerable: true,
configurable: true
});
/**
* @param {?} timeline
* @return {?}
*/
TimelineBuilder.prototype.mergeTimelineCollectedStyles = function (timeline) {
var _this = this;
Object.keys(timeline._styleSummary).forEach(function (prop) {
var /** @type {?} */ details0 = _this._styleSummary[prop];
var /** @type {?} */ details1 = timeline._styleSummary[prop];
if (!details0 || details1.time > details0.time) {
_this._updateStyle(prop, details1.value);
}
});
};
/**
* @return {?}
*/
TimelineBuilder.prototype.buildKeyframes = function () {
var _this = this;
var /** @type {?} */ finalKeyframes = [];
// special case for when there are only start/destination
// styles but no actual animation animate steps...
if (this.duration == 0) {
var /** @type {?} */ targetKeyframe = this.getFinalKeyframe();
var /** @type {?} */ firstKeyframe = copyStyles(targetKeyframe, true);
firstKeyframe['offset'] = 0;
finalKeyframes.push(firstKeyframe);
var /** @type {?} */ lastKeyframe = copyStyles(targetKeyframe, true);
lastKeyframe['offset'] = 1;
finalKeyframes.push(lastKeyframe);
}
else {
this._keyframes.forEach(function (keyframe, time) {
var /** @type {?} */ finalKeyframe = copyStyles(keyframe, true);
finalKeyframe['offset'] = time / _this.duration;
finalKeyframes.push(finalKeyframe);
});
}
return createTimelineInstruction(finalKeyframes, this.duration, this.startTime, this.easing);
};
return TimelineBuilder;
}());
/**
* @param {?} ast
* @return {?}
*/
function getOffset(ast) {
var /** @type {?} */ offset = ast.offset;
if (offset == null) {
var /** @type {?} */ styles = ast.styles;
if (Array.isArray(styles)) {
for (var /** @type {?} */ i = 0; i < styles.length; i++) {
var /** @type {?} */ o = (styles[i]['offset']);
if (o != null) {
offset = o;
break;
}
}
}
else {
offset = (styles['offset']);
}
}
return ((offset));
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @param {?} triggerName
* @param {?} fromState
* @param {?} toState
* @param {?} isRemovalTransition
* @param {?} fromStyles
* @param {?} toStyles
* @param {?} timelines
* @return {?}
*/
function createTransitionInstruction(triggerName, fromState, toState, isRemovalTransition, fromStyles, toStyles, timelines) {
return {
type: 0 /* TransitionAnimation */,
triggerName: triggerName,
isRemovalTransition: isRemovalTransition,
fromState: fromState,
fromStyles: fromStyles,
toState: toState,
toStyles: toStyles,
timelines: timelines
};
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var AnimationTransitionFactory = (function () {
/**
* @param {?} _triggerName
* @param {?} ast
* @param {?} matchFns
* @param {?} _stateStyles
*/
function AnimationTransitionFactory(_triggerName, ast, matchFns, _stateStyles) {
this._triggerName = _triggerName;
this.matchFns = matchFns;
this._stateStyles = _stateStyles;
var normalizedAst = Array.isArray(ast.animation) ?
sequence(ast.animation) :
ast.animation;
this._animationAst = normalizedAst;
}
/**
* @param {?} currentState
* @param {?} nextState
* @return {?}
*/
AnimationTransitionFactory.prototype.match = function (currentState, nextState) {
if (!oneOrMoreTransitionsMatch(this.matchFns, currentState, nextState))
return;
var /** @type {?} */ backupStateStyles = this._stateStyles['*'] || {};
var /** @type {?} */ currentStateStyles = this._stateStyles[currentState] || backupStateStyles;
var /** @type {?} */ nextStateStyles = this._stateStyles[nextState] || backupStateStyles;
var /** @type {?} */ timelines = buildAnimationKeyframes(this._animationAst, currentStateStyles, nextStateStyles);
return createTransitionInstruction(this._triggerName, currentState, nextState, nextState === 'void', currentStateStyles, nextStateStyles, timelines);
};
return AnimationTransitionFactory;
}());
/**
* @param {?} matchFns
* @param {?} currentState
* @param {?} nextState
* @return {?}
*/
function oneOrMoreTransitionsMatch(matchFns, currentState, nextState) {
return matchFns.some(function (fn) { return fn(currentState, nextState); });
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @param {?} ast
* @return {?}
*/
function validateAnimationSequence(ast) {
var /** @type {?} */ normalizedAst = Array.isArray(ast) ? sequence(/** @type {?} */ (ast)) : (ast);
return new AnimationValidatorVisitor().validate(normalizedAst);
}
var AnimationValidatorVisitor = (function () {
function AnimationValidatorVisitor() {
}
/**
* @param {?} ast
* @return {?}
*/
AnimationValidatorVisitor.prototype.validate = function (ast) {
var /** @type {?} */ context = new AnimationValidatorContext();
visitAnimationNode(this, ast, context);
return context.errors;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationValidatorVisitor.prototype.visitState = function (ast, context) {
// these values are not visited in this AST
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationValidatorVisitor.prototype.visitTransition = function (ast, context) {
// these values are not visited in this AST
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationValidatorVisitor.prototype.visitSequence = function (ast, context) {
var _this = this;
ast.steps.forEach(function (step) { return visitAnimationNode(_this, step, context); });
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationValidatorVisitor.prototype.visitGroup = function (ast, context) {
var _this = this;
var /** @type {?} */ currentTime = context.currentTime;
var /** @type {?} */ furthestTime = 0;
ast.steps.forEach(function (step) {
context.currentTime = currentTime;
visitAnimationNode(_this, step, context);
furthestTime = Math.max(furthestTime, context.currentTime);
});
context.currentTime = furthestTime;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationValidatorVisitor.prototype.visitAnimate = function (ast, context) {
// we reassign the timings here so that they are not reparsed each
// time an animation occurs
context.currentAnimateTimings = ast.timings =
parseTimeExpression(/** @type {?} */ (ast.timings), context.errors);
var /** @type {?} */ astType = ast.styles && ast.styles.type;
if (astType == 5 /* KeyframeSequence */) {
this.visitKeyframeSequence(/** @type {?} */ (ast.styles), context);
}
else {
context.currentTime +=
context.currentAnimateTimings.duration + context.currentAnimateTimings.delay;
if (astType == 6 /* Style */) {
this.visitStyle(/** @type {?} */ (ast.styles), context);
}
}
context.currentAnimateTimings = null;
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationValidatorVisitor.prototype.visitStyle = function (ast, context) {
var /** @type {?} */ styleData = normalizeStyles(ast.styles);
var /** @type {?} */ timings = context.currentAnimateTimings;
var /** @type {?} */ endTime = context.currentTime;
var /** @type {?} */ startTime = context.currentTime;
if (timings && startTime > 0) {
startTime -= timings.duration + timings.delay;
}
Object.keys(styleData).forEach(function (prop) {
var /** @type {?} */ collectedEntry = context.collectedStyles[prop];
var /** @type {?} */ updateCollectedStyle = true;
if (collectedEntry) {
if (startTime != endTime && startTime >= collectedEntry.startTime &&
endTime <= collectedEntry.endTime) {
context.errors.push("The CSS property \"" + prop + "\" that exists between the times of \"" + collectedEntry.startTime + "ms\" and \"" + collectedEntry.endTime + "ms\" is also being animated in a parallel animation between the times of \"" + startTime + "ms\" and \"" + endTime + "ms\"");
updateCollectedStyle = false;
}
// we always choose the smaller start time value since we
// want to have a record of the entire animation window where
// the style property is being animated in between
startTime = collectedEntry.startTime;
}
if (updateCollectedStyle) {
context.collectedStyles[prop] = { startTime: startTime, endTime: endTime };
}
});
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationValidatorVisitor.prototype.visitKeyframeSequence = function (ast, context) {
var _this = this;
var /** @type {?} */ totalKeyframesWithOffsets = 0;
var /** @type {?} */ offsets = [];
var /** @type {?} */ offsetsOutOfOrder = false;
var /** @type {?} */ keyframesOutOfRange = false;
var /** @type {?} */ previousOffset = 0;
ast.steps.forEach(function (step) {
var /** @type {?} */ styleData = normalizeStyles(step.styles);
var /** @type {?} */ offset = 0;
if (styleData.hasOwnProperty('offset')) {
totalKeyframesWithOffsets++;
offset = (styleData['offset']);
}
keyframesOutOfRange = keyframesOutOfRange || offset < 0 || offset > 1;
offsetsOutOfOrder = offsetsOutOfOrder || offset < previousOffset;
previousOffset = offset;
offsets.push(offset);
});
if (keyframesOutOfRange) {
context.errors.push("Please ensure that all keyframe offsets are between 0 and 1");
}
if (offsetsOutOfOrder) {
context.errors.push("Please ensure that all keyframe offsets are in order");
}
var /** @type {?} */ length = ast.steps.length;
var /** @type {?} */ generatedOffset = 0;
if (totalKeyframesWithOffsets > 0 && totalKeyframesWithOffsets < length) {
context.errors.push("Not all style() steps within the declared keyframes() contain offsets");
}
else if (totalKeyframesWithOffsets == 0) {
generatedOffset = 1 / length;
}
var /** @type {?} */ limit = length - 1;
var /** @type {?} */ currentTime = context.currentTime;
var /** @type {?} */ animateDuration = ((context.currentAnimateTimings)).duration;
ast.steps.forEach(function (step, i) {
var /** @type {?} */ offset = generatedOffset > 0 ? (i == limit ? 1 : (generatedOffset * i)) : offsets[i];
var /** @type {?} */ durationUpToThisFrame = offset * animateDuration;
context.currentTime =
currentTime + ((context.currentAnimateTimings)).delay + durationUpToThisFrame; /** @type {?} */
((context.currentAnimateTimings)).duration = durationUpToThisFrame;
_this.visitStyle(step, context);
});
};
return AnimationValidatorVisitor;
}());
var AnimationValidatorContext = (function () {
function AnimationValidatorContext() {
this.errors = [];
this.currentTime = 0;
this.collectedStyles = {};
}
return AnimationValidatorContext;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* \@experimental Animation support is experimental.
* @param {?} name
* @param {?} definitions
* @return {?}
*/
function buildTrigger(name, definitions) {
return new AnimationTriggerVisitor().buildTrigger(name, definitions);
}
/**
* \@experimental Animation support is experimental.
*/
var AnimationTrigger = (function () {
/**
* @param {?} name
* @param {?} states
* @param {?} _transitionAsts
*/
function AnimationTrigger(name, states, _transitionAsts) {
var _this = this;
this.name = name;
this._transitionAsts = _transitionAsts;
this.transitionFactories = [];
this.states = {};
Object.keys(states).forEach(function (stateName) { _this.states[stateName] = copyStyles(states[stateName], false); });
var errors = [];
_transitionAsts.forEach(function (ast) {
var exprs = parseTransitionExpr(ast.expr, errors);
var sequenceErrors = validateAnimationSequence(ast);
if (sequenceErrors.length) {
errors.push.apply(errors, sequenceErrors);
}
else {
_this.transitionFactories.push(new AnimationTransitionFactory(_this.name, ast, exprs, states));
}
});
if (errors.length) {
var LINE_START = '\n - ';
throw new Error("Animation parsing for the " + name + " trigger have failed:" + LINE_START + errors.join(LINE_START));
}
}
/**
* @param {?} currentState
* @param {?} nextState
* @return {?}
*/
AnimationTrigger.prototype.createFallbackInstruction = function (currentState, nextState) {
var /** @type {?} */ backupStateStyles = this.states['*'] || {};
var /** @type {?} */ currentStateStyles = this.states[currentState] || backupStateStyles;
var /** @type {?} */ nextStateStyles = this.states[nextState] || backupStateStyles;
return createTransitionInstruction(this.name, currentState, nextState, nextState == 'void', currentStateStyles, nextStateStyles, []);
};
/**
* @param {?} currentState
* @param {?} nextState
* @return {?}
*/
AnimationTrigger.prototype.matchTransition = function (currentState, nextState) {
for (var /** @type {?} */ i = 0; i < this.transitionFactories.length; i++) {
var /** @type {?} */ result = this.transitionFactories[i].match(currentState, nextState);
if (result)
return result;
}
return null;
};
return AnimationTrigger;
}());
var AnimationTriggerContext = (function () {
function AnimationTriggerContext() {
this.errors = [];
this.states = {};
this.transitions = [];
}
return AnimationTriggerContext;
}());
var AnimationTriggerVisitor = (function () {
function AnimationTriggerVisitor() {
}
/**
* @param {?} name
* @param {?} definitions
* @return {?}
*/
AnimationTriggerVisitor.prototype.buildTrigger = function (name, definitions) {
var _this = this;
var /** @type {?} */ context = new AnimationTriggerContext();
definitions.forEach(function (def) { return visitAnimationNode(_this, def, context); });
return new AnimationTrigger(name, context.states, context.transitions);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationTriggerVisitor.prototype.visitState = function (ast, context) {
var /** @type {?} */ styles = normalizeStyles(ast.styles.styles);
ast.name.split(/\s*,\s*/).forEach(function (name) { context.states[name] = styles; });
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationTriggerVisitor.prototype.visitTransition = function (ast, context) {
context.transitions.push(ast);
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationTriggerVisitor.prototype.visitSequence = function (ast, context) {
// these values are not visited in this AST
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationTriggerVisitor.prototype.visitGroup = function (ast, context) {
// these values are not visited in this AST
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationTriggerVisitor.prototype.visitAnimate = function (ast, context) {
// these values are not visited in this AST
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationTriggerVisitor.prototype.visitStyle = function (ast, context) {
// these values are not visited in this AST
};
/**
* @param {?} ast
* @param {?} context
* @return {?}
*/
AnimationTriggerVisitor.prototype.visitKeyframeSequence = function (ast, context) {
// these values are not visited in this AST
};
return AnimationTriggerVisitor;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var MARKED_FOR_ANIMATION_CLASSNAME = 'ng-animating';
var MARKED_FOR_ANIMATION_SELECTOR = '.ng-animating';
var MARKED_FOR_REMOVAL = '$$ngRemove';
var VOID_STATE = 'void';
var DomAnimationEngine = (function () {
/**
* @param {?} _driver
* @param {?} _normalizer
*/
function DomAnimationEngine(_driver, _normalizer) {
this._driver = _driver;
this._normalizer = _normalizer;
this._flaggedInserts = new Set();
this._queuedRemovals = new Map();
this._queuedTransitionAnimations = [];
this._activeTransitionAnimations = new Map();
this._activeElementAnimations = new Map();
this._elementTriggerStates = new Map();
this._triggers = Object.create(null);
this._triggerListeners = new Map();
this._pendingListenerRemovals = new Map();
}
Object.defineProperty(DomAnimationEngine.prototype, "queuedPlayers", {
/**
* @return {?}
*/
get: function () {
return this._queuedTransitionAnimations.map(function (q) { return q.player; });
},
enumerable: true,
configurable: true
});
Object.defineProperty(DomAnimationEngine.prototype, "activePlayers", {
/**
* @return {?}
*/
get: function () {
var /** @type {?} */ players = [];
this._activeElementAnimations.forEach(function (activePlayers) { return players.push.apply(players, activePlayers); });
return players;
},
enumerable: true,
configurable: true
});
/**
* @param {?} trigger
* @param {?=} name
* @return {?}
*/
DomAnimationEngine.prototype.registerTrigger = function (trigger, name) {
name = name || trigger.name;
if (this._triggers[name]) {
return;
}
this._triggers[name] = buildTrigger(name, trigger.definitions);
};
/**
* @param {?} element
* @param {?} domFn
* @return {?}
*/
DomAnimationEngine.prototype.onInsert = function (element, domFn) {
if (element['nodeType'] == 1) {
this._flaggedInserts.add(element);
}
domFn();
};
/**
* @param {?} element
* @param {?} domFn
* @return {?}
*/
DomAnimationEngine.prototype.onRemove = function (element, domFn) {
var _this = this;
if (element['nodeType'] != 1) {
domFn();
return;
}
var /** @type {?} */ lookupRef = this._elementTriggerStates.get(element);
if (lookupRef) {
var /** @type {?} */ possibleTriggers = Object.keys(lookupRef);
var /** @type {?} */ hasRemoval = possibleTriggers.some(function (triggerName) {
var /** @type {?} */ oldValue = ((lookupRef))[triggerName];
var /** @type {?} */ instruction = _this._triggers[triggerName].matchTransition(oldValue, VOID_STATE);
return !!instruction;
});
if (hasRemoval) {
element[MARKED_FOR_REMOVAL] = true;
this._queuedRemovals.set(element, domFn);
return;
}
}
// this means that there are no animations to take on this
// leave operation therefore we should fire the done|start callbacks
if (this._triggerListeners.has(element)) {
element[MARKED_FOR_REMOVAL] = true;
this._queuedRemovals.set(element, function () { });
}
this._onRemovalTransition(element).forEach(function (player) { return player.destroy(); });
domFn();
};
/**
* @param {?} element
* @param {?} property
* @param {?} value
* @return {?}
*/
DomAnimationEngine.prototype.setProperty = function (element, property, value) {
var /** @type {?} */ trigger = this._triggers[property];
if (!trigger) {
throw new Error("The provided animation trigger \"" + property + "\" has not been registered!");
}
var /** @type {?} */ lookupRef = this._elementTriggerStates.get(element);
if (!lookupRef) {
this._elementTriggerStates.set(element, lookupRef = {});
}
var /** @type {?} */ oldValue = lookupRef.hasOwnProperty(property) ? lookupRef[property] : VOID_STATE;
if (oldValue !== value) {
value = normalizeTriggerValue(value);
var /** @type {?} */ instruction = trigger.matchTransition(oldValue, value);
if (!instruction) {
// we do this to make sure we always have an animation player so
// that callback operations are properly called
instruction = trigger.createFallbackInstruction(oldValue, value);
}
this.animateTransition(element, instruction);
lookupRef[property] = value;
}
};
/**
* @param {?} element
* @param {?} eventName
* @param {?} eventPhase
* @param {?} callback
* @return {?}
*/
DomAnimationEngine.prototype.listen = function (element, eventName, eventPhase, callback) {
var _this = this;
if (!eventPhase) {
throw new Error("Unable to listen on the animation trigger \"" + eventName + "\" because the provided event is undefined!");
}
if (!this._triggers[eventName]) {
throw new Error("Unable to listen on the animation trigger event \"" + eventPhase + "\" because the animation trigger \"" + eventName + "\" doesn't exist!");
}
var /** @type {?} */ elementListeners = this._triggerListeners.get(element);
if (!elementListeners) {
this._triggerListeners.set(element, elementListeners = []);
}
validatePlayerEvent(eventName, eventPhase);
var /** @type {?} */ tuple = ({ triggerName: eventName, phase: eventPhase, callback: callback });
elementListeners.push(tuple);
return function () {
// this is queued up in the event that a removal animation is set
// to fire on the element (the listeners need to be set during flush)
getOrSetAsInMap(_this._pendingListenerRemovals, element, []).push(tuple);
};
};
/**
* @return {?}
*/
DomAnimationEngine.prototype._clearPendingListenerRemovals = function () {
var _this = this;
this._pendingListenerRemovals.forEach(function (tuples, element) {
var /** @type {?} */ elementListeners = _this._triggerListeners.get(element);
if (elementListeners) {
tuples.forEach(function (tuple) {
var /** @type {?} */ index = elementListeners.indexOf(tuple);
if (index >= 0) {
elementListeners.splice(index, 1);
}
});
}
});
this._pendingListenerRemovals.clear();
};
/**
* @param {?} element
* @return {?}
*/
DomAnimationEngine.prototype._onRemovalTransition = function (element) {
// when a parent animation is set to trigger a removal we want to
// find all of the children that are currently animating and clear
// them out by destroying each of them.
var /** @type {?} */ elms = element.querySelectorAll(MARKED_FOR_ANIMATION_SELECTOR);
var _loop_1 = function (i) {
var /** @type {?} */ elm = elms[i];
var /** @type {?} */ activePlayers = this_1._activeElementAnimations.get(elm);
if (activePlayers) {
activePlayers.forEach(function (player) { return player.destroy(); });
}
var /** @type {?} */ activeTransitions = this_1._activeTransitionAnimations.get(elm);
if (activeTransitions) {
Object.keys(activeTransitions).forEach(function (triggerName) {
var /** @type {?} */ player = activeTransitions[triggerName];
if (player) {
player.destroy();
}
});
}
};
var this_1 = this;
for (var /** @type {?} */ i = 0; i < elms.length; i++) {
_loop_1(/** @type {?} */ i);
}
// we make a copy of the array because the actual source array is modified
// each time a player is finished/destroyed (the forEach loop would fail otherwise)
return copyArray(/** @type {?} */ ((this._activeElementAnimations.get(element))));
};
/**
* @param {?} element
* @param {?} instruction
* @return {?}
*/
DomAnimationEngine.prototype.animateTransition = function (element, instruction) {
var _this = this;
var /** @type {?} */ triggerName = instruction.triggerName;
var /** @type {?} */ previousPlayers;
if (instruction.isRemovalTransition) {
previousPlayers = this._onRemovalTransition(element);
}
else {
previousPlayers = [];
var /** @type {?} */ existingTransitions = this._activeTransitionAnimations.get(element);
var /** @type {?} */ existingPlayer = existingTransitions ? existingTransitions[triggerName] : null;
if (existingPlayer) {
previousPlayers.push(existingPlayer);
}
}
// it's important to do this step before destroying the players
// so that the onDone callback below won't fire before this
eraseStyles(element, instruction.fromStyles);
// we first run this so that the previous animation player
// data can be passed into the successive animation players
var /** @type {?} */ totalTime = 0;
var /** @type {?} */ players = instruction.timelines.map(function (timelineInstruction, i) {
totalTime = Math.max(totalTime, timelineInstruction.totalTime);
return _this._buildPlayer(element, timelineInstruction, previousPlayers, i);
});
previousPlayers.forEach(function (previousPlayer) { return previousPlayer.destroy(); });
var /** @type {?} */ player = optimizeGroupPlayer(players);
player.onDone(function () {
player.destroy();
var /** @type {?} */ elmTransitionMap = _this._activeTransitionAnimations.get(element);
if (elmTransitionMap) {
delete elmTransitionMap[triggerName];
if (Object.keys(elmTransitionMap).length == 0) {
_this._activeTransitionAnimations.delete(element);
}
}
deleteFromArrayMap(_this._activeElementAnimations, element, player);
setStyles(element, instruction.toStyles);
});
var /** @type {?} */ elmTransitionMap = getOrSetAsInMap(this._activeTransitionAnimations, element, {});
elmTransitionMap[triggerName] = player;
this._queuePlayer(element, triggerName, player, makeAnimationEvent(element, triggerName, instruction.fromState, instruction.toState, null, // this will be filled in during event creation
totalTime));
return player;
};
/**
* @param {?} element
* @param {?} instructions
* @param {?=} previousPlayers
* @return {?}
*/
DomAnimationEngine.prototype.animateTimeline = function (element, instructions, previousPlayers) {
var _this = this;
if (previousPlayers === void 0) { previousPlayers = []; }
var /** @type {?} */ players = instructions.map(function (instruction, i) {
var /** @type {?} */ player = _this._buildPlayer(element, instruction, previousPlayers, i);
player.onDestroy(function () { deleteFromArrayMap(_this._activeElementAnimations, element, player); });
_this._markPlayerAsActive(element, player);
return player;
});
return optimizeGroupPlayer(players);
};
/**
* @param {?} element
* @param {?} instruction
* @param {?} previousPlayers
* @param {?=} index
* @return {?}
*/
DomAnimationEngine.prototype._buildPlayer = function (element, instruction, previousPlayers, index) {
if (index === void 0) { index = 0; }
// only the very first animation can absorb the previous styles. This
// is here to prevent the an overlap situation where a group animation
// absorbs previous styles multiple times for the same element.
if (index && previousPlayers.length) {
previousPlayers = [];
}
return this._driver.animate(element, this._normalizeKeyframes(instruction.keyframes), instruction.duration, instruction.delay, instruction.easing, previousPlayers);
};
/**
* @param {?} keyframes
* @return {?}
*/
DomAnimationEngine.prototype._normalizeKeyframes = function (keyframes) {
var _this = this;
var /** @type {?} */ errors = [];
var /** @type {?} */ normalizedKeyframes = [];
keyframes.forEach(function (kf) {
var /** @type {?} */ normalizedKeyframe = {};
Object.keys(kf).forEach(function (prop) {
var /** @type {?} */ normalizedProp = prop;
var /** @type {?} */ normalizedValue = kf[prop];
if (prop != 'offset') {
normalizedProp = _this._normalizer.normalizePropertyName(prop, errors);
normalizedValue =
_this._normalizer.normalizeStyleValue(prop, normalizedProp, kf[prop], errors);
}
normalizedKeyframe[normalizedProp] = normalizedValue;
});
normalizedKeyframes.push(normalizedKeyframe);
});
if (errors.length) {
var /** @type {?} */ LINE_START = '\n - ';
throw new Error("Unable to animate due to the following errors:" + LINE_START + errors.join(LINE_START));
}
return normalizedKeyframes;
};
/**
* @param {?} element
* @param {?} player
* @return {?}
*/
DomAnimationEngine.prototype._markPlayerAsActive = function (element, player) {
var /** @type {?} */ elementAnimations = getOrSetAsInMap(this._activeElementAnimations, element, []);
elementAnimations.push(player);
};
/**
* @param {?} element
* @param {?} triggerName
* @param {?} player
* @param {?} event
* @return {?}
*/
DomAnimationEngine.prototype._queuePlayer = function (element, triggerName, player, event) {
var /** @type {?} */ tuple = ({ element: element, player: player, triggerName: triggerName, event: event });
this._queuedTransitionAnimations.push(tuple);
player.init();
element.classList.add(MARKED_FOR_ANIMATION_CLASSNAME);
player.onDone(function () { element.classList.remove(MARKED_FOR_ANIMATION_CLASSNAME); });
};
/**
* @return {?}
*/
DomAnimationEngine.prototype._flushQueuedAnimations = function () {
var _loop_2 = function () {
var _a = ((this_2._queuedTransitionAnimations.shift())), player = _a.player, element = _a.element, triggerName = _a.triggerName, event = _a.event;
var /** @type {?} */ parent = element;
while (parent = parent.parentNode) {
// this means that a parent element will or will not
// have its own animation operation which in this case
// there's no point in even trying to do an animation
if (parent[MARKED_FOR_REMOVAL])
return "continue-parentLoop";
}
var /** @type {?} */ listeners = this_2._triggerListeners.get(element);
if (listeners) {
listeners.forEach(function (tuple) {
if (tuple.triggerName == triggerName) {
listenOnPlayer(player, tuple.phase, event, tuple.callback);
}
});
}
// if a removal exists for the given element then we need cancel
// all the queued players so that a proper removal animation can go
if (this_2._queuedRemovals.has(element)) {
player.destroy();
return "continue";
}
this_2._markPlayerAsActive(element, player);
// in the event that an animation throws an error then we do
// not want to re-run animations on any previous animations
// if they have already been kicked off beforehand
player.init();
if (!player.hasStarted()) {
player.play();
}
};
var this_2 = this;
parentLoop: while (this._queuedTransitionAnimations.length) {
var state_1 = _loop_2();
switch (state_1) {
case "continue-parentLoop": continue parentLoop;
}
}
};
/**
* @return {?}
*/
DomAnimationEngine.prototype.flush = function () {
var _this = this;
var /** @type {?} */ leaveListeners = new Map();
this._queuedRemovals.forEach(function (callback, element) {
var /** @type {?} */ tuple = _this._pendingListenerRemovals.get(element);
if (tuple) {
leaveListeners.set(element, tuple);
_this._pendingListenerRemovals.delete(element);
}
});
this._clearPendingListenerRemovals();
this._pendingListenerRemovals = leaveListeners;
this._flushQueuedAnimations();
var /** @type {?} */ flushAgain = false;
this._queuedRemovals.forEach(function (callback, element) {
// an item that was inserted/removed in the same flush means
// that an animation should not happen anyway
if (_this._flaggedInserts.has(element))
return;
var /** @type {?} */ parent = element;
var /** @type {?} */ players = [];
while (parent = parent.parentNode) {
// there is no reason to even try to
if (parent[MARKED_FOR_REMOVAL]) {
callback();
return;
}
var /** @type {?} */ match = _this._activeElementAnimations.get(parent);
if (match) {
players.push.apply(players, match);
break;
}
}
// the loop was unable to find an parent that is animating even
// though this element has set to be removed, so the algorithm
// should check to see if there are any triggers on the element
// that are present to handle a leave animation and then setup
// those players to facilitate the callback after done
if (players.length == 0) {
// this means that the element has valid state triggers
var /** @type {?} */ stateDetails_1 = _this._elementTriggerStates.get(element);
if (stateDetails_1) {
Object.keys(stateDetails_1).forEach(function (triggerName) {
flushAgain = true;
var /** @type {?} */ oldValue = stateDetails_1[triggerName];
var /** @type {?} */ instruction = _this._triggers[triggerName].matchTransition(oldValue, VOID_STATE);
if (instruction) {
players.push(_this.animateTransition(element, instruction));
}
else {
var /** @type {?} */ event = makeAnimationEvent(element, triggerName, oldValue, VOID_STATE, '', 0);
var /** @type {?} */ player = new NoopAnimationPlayer();
_this._queuePlayer(element, triggerName, player, event);
}
});
}
}
if (players.length) {
optimizeGroupPlayer(players).onDone(callback);
}
else {
callback();
}
});
this._queuedRemovals.clear();
this._flaggedInserts.clear();
// this means that one or more leave animations were detected
if (flushAgain) {
this._flushQueuedAnimations();
this._clearPendingListenerRemovals();
}
};
return DomAnimationEngine;
}());
/**
* @param {?} map
* @param {?} key
* @param {?} defaultValue
* @return {?}
*/
function getOrSetAsInMap(map, key, defaultValue) {
var /** @type {?} */ value = map.get(key);
if (!value) {
map.set(key, value = defaultValue);
}
return value;
}
/**
* @param {?} map
* @param {?} key
* @param {?} value
* @return {?}
*/
function deleteFromArrayMap(map, key, value) {
var /** @type {?} */ arr = map.get(key);
if (arr) {
var /** @type {?} */ index = arr.indexOf(value);
if (index >= 0) {
arr.splice(index, 1);
if (arr.length == 0) {
map.delete(key);
}
}
}
}
/**
* @param {?} players
* @return {?}
*/
function optimizeGroupPlayer(players) {
switch (players.length) {
case 0:
return new NoopAnimationPlayer();
case 1:
return players[0];
default:
return new ɵAnimationGroupPlayer(players);
}
}
/**
* @param {?} source
* @return {?}
*/
function copyArray(source) {
return source ? source.splice(0) : [];
}
/**
* @param {?} triggerName
* @param {?} eventName
* @return {?}
*/
function validatePlayerEvent(triggerName, eventName) {
switch (eventName) {
case 'start':
case 'done':
return;
default:
throw new Error("The provided animation trigger event \"" + eventName + "\" for the animation trigger \"" + triggerName + "\" is not supported!");
}
}
/**
* @param {?} player
* @param {?} eventName
* @param {?} baseEvent
* @param {?} callback
* @return {?}
*/
function listenOnPlayer(player, eventName, baseEvent, callback) {
switch (eventName) {
case 'start':
player.onStart(function () {
var /** @type {?} */ event = copyAnimationEvent(baseEvent);
event.phaseName = 'start';
callback(event);
});
break;
case 'done':
player.onDone(function () {
var /** @type {?} */ event = copyAnimationEvent(baseEvent);
event.phaseName = 'done';
callback(event);
});
break;
}
}
/**
* @param {?} e
* @return {?}
*/
function copyAnimationEvent(e) {
return makeAnimationEvent(e.element, e.triggerName, e.fromState, e.toState, e.phaseName, e.totalTime);
}
/**
* @param {?} element
* @param {?} triggerName
* @param {?} fromState
* @param {?} toState
* @param {?} phaseName
* @param {?} totalTime
* @return {?}
*/
function makeAnimationEvent(element, triggerName, fromState, toState, phaseName, totalTime) {
return ({ element: element, triggerName: triggerName, fromState: fromState, toState: toState, phaseName: phaseName, totalTime: totalTime });
}
/**
* @param {?} value
* @return {?}
*/
function normalizeTriggerValue(value) {
switch (typeof value) {
case 'boolean':
return value ? '1' : '0';
default:
return value ? value.toString() : null;
}
}
/**
* \@experimental Animation support is experimental.
* @abstract
*/
var AnimationStyleNormalizer = (function () {
function AnimationStyleNormalizer() {
}
/**
* @abstract
* @param {?} propertyName
* @param {?} errors
* @return {?}
*/
AnimationStyleNormalizer.prototype.normalizePropertyName = function (propertyName, errors) { };
/**
* @abstract
* @param {?} userProvidedProperty
* @param {?} normalizedProperty
* @param {?} value
* @param {?} errors
* @return {?}
*/
AnimationStyleNormalizer.prototype.normalizeStyleValue = function (userProvidedProperty, normalizedProperty, value, errors) { };
return AnimationStyleNormalizer;
}());
/**
* \@experimental Animation support is experimental.
*/
var NoopAnimationStyleNormalizer = (function () {
function NoopAnimationStyleNormalizer() {
}
/**
* @param {?} propertyName
* @param {?} errors
* @return {?}
*/
NoopAnimationStyleNormalizer.prototype.normalizePropertyName = function (propertyName, errors) { return propertyName; };
/**
* @param {?} userProvidedProperty
* @param {?} normalizedProperty
* @param {?} value
* @param {?} errors
* @return {?}
*/
NoopAnimationStyleNormalizer.prototype.normalizeStyleValue = function (userProvidedProperty, normalizedProperty, value, errors) {
return (value);
};
return NoopAnimationStyleNormalizer;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var Animation = (function () {
/**
* @param {?} input
*/
function Animation(input) {
var ast = Array.isArray(input) ? sequence(input) : input;
var errors = validateAnimationSequence(ast);
if (errors.length) {
var errorMessage = "animation validation failed:\n" + errors.join("\n");
throw new Error(errorMessage);
}
this._animationAst = ast;
}
/**
* @param {?} startingStyles
* @param {?} destinationStyles
* @return {?}
*/
Animation.prototype.buildTimelines = function (startingStyles, destinationStyles) {
var /** @type {?} */ start = Array.isArray(startingStyles) ? normalizeStyles(startingStyles) : (startingStyles);
var /** @type {?} */ dest = Array.isArray(destinationStyles) ? normalizeStyles(destinationStyles) : (destinationStyles);
return buildAnimationKeyframes(this._animationAst, start, dest);
};
/**
* @param {?} injector
* @param {?} element
* @param {?=} startingStyles
* @param {?=} destinationStyles
* @return {?}
*/
Animation.prototype.create = function (injector, element, startingStyles, destinationStyles) {
if (startingStyles === void 0) { startingStyles = {}; }
if (destinationStyles === void 0) { destinationStyles = {}; }
var /** @type {?} */ instructions = this.buildTimelines(startingStyles, destinationStyles);
// note the code below is only here to make the tests happy (once the new renderer is
// within core then the code below will interact with Renderer.transition(...))
var /** @type {?} */ driver = injector.get(AnimationDriver);
var /** @type {?} */ normalizer = injector.get(AnimationStyleNormalizer);
var /** @type {?} */ engine = new DomAnimationEngine(driver, normalizer);
return engine.animateTimeline(element, instructions);
};
return Animation;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var WebAnimationsStyleNormalizer = (function (_super) {
__extends(WebAnimationsStyleNormalizer, _super);
function WebAnimationsStyleNormalizer() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* @param {?} propertyName
* @param {?} errors
* @return {?}
*/
WebAnimationsStyleNormalizer.prototype.normalizePropertyName = function (propertyName, errors) {
return dashCaseToCamelCase(propertyName);
};
/**
* @param {?} userProvidedProperty
* @param {?} normalizedProperty
* @param {?} value
* @param {?} errors
* @return {?}
*/
WebAnimationsStyleNormalizer.prototype.normalizeStyleValue = function (userProvidedProperty, normalizedProperty, value, errors) {
var /** @type {?} */ unit = '';
var /** @type {?} */ strVal = value.toString().trim();
if (DIMENSIONAL_PROP_MAP[normalizedProperty] && value !== 0 && value !== '0') {
if (typeof value === 'number') {
unit = 'px';
}
else {
var /** @type {?} */ valAndSuffixMatch = value.match(/^[+-]?[\d\.]+([a-z]*)$/);
if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) {
errors.push("Please provide a CSS unit value for " + userProvidedProperty + ":" + value);
}
}
}
return strVal + unit;
};
return WebAnimationsStyleNormalizer;
}(AnimationStyleNormalizer));
var DIMENSIONAL_PROP_MAP = makeBooleanMap('width,height,minWidth,minHeight,maxWidth,maxHeight,left,top,bottom,right,fontSize,outlineWidth,outlineOffset,paddingTop,paddingLeft,paddingBottom,paddingRight,marginTop,marginLeft,marginBottom,marginRight,borderRadius,borderWidth,borderTopWidth,borderLeftWidth,borderRightWidth,borderBottomWidth,textIndent'
.split(','));
/**
* @param {?} keys
* @return {?}
*/
function makeBooleanMap(keys) {
var /** @type {?} */ map = {};
keys.forEach(function (key) { return map[key] = true; });
return map;
}
var DASH_CASE_REGEXP = /-+([a-z0-9])/g;
/**
* @param {?} input
* @return {?}
*/
function dashCaseToCamelCase(input) {
return input.replace(DASH_CASE_REGEXP, function () {
var m = [];
for (var _i = 0; _i < arguments.length; _i++) {
m[_i] = arguments[_i];
}
return m[1].toUpperCase();
});
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var DEFAULT_STATE_VALUE = 'void';
var DEFAULT_STATE_STYLES = '*';
var NoopAnimationEngine = (function (_super) {
__extends(NoopAnimationEngine, _super);
function NoopAnimationEngine() {
var _this = _super.apply(this, arguments) || this;
_this._listeners = new Map();
_this._changes = [];
_this._flaggedRemovals = new Set();
_this._onDoneFns = [];
_this._triggerStyles = Object.create(null);
return _this;
}
/**
* @param {?} trigger
* @param {?=} name
* @return {?}
*/
NoopAnimationEngine.prototype.registerTrigger = function (trigger, name) {
name = name || trigger.name;
if (this._triggerStyles[name]) {
return;
}
var /** @type {?} */ stateMap = {};
trigger.definitions.forEach(function (def) {
if (def.type === 0 /* State */) {
var /** @type {?} */ stateDef = (def);
stateMap[stateDef.name] = normalizeStyles(stateDef.styles.styles);
}
});
this._triggerStyles[name] = stateMap;
};
/**
* @param {?} element
* @param {?} domFn
* @return {?}
*/
NoopAnimationEngine.prototype.onInsert = function (element, domFn) { domFn(); };
/**
* @param {?} element
* @param {?} domFn
* @return {?}
*/
NoopAnimationEngine.prototype.onRemove = function (element, domFn) {
domFn();
if (element['nodeType'] == 1) {
this._flaggedRemovals.add(element);
}
};
/**
* @param {?} element
* @param {?} property
* @param {?} value
* @return {?}
*/
NoopAnimationEngine.prototype.setProperty = function (element, property, value) {
var /** @type {?} */ storageProp = makeStorageProp(property);
var /** @type {?} */ oldValue = element[storageProp] || DEFAULT_STATE_VALUE;
this._changes.push(/** @type {?} */ ({ element: element, oldValue: oldValue, newValue: value, triggerName: property }));
var /** @type {?} */ triggerStateStyles = this._triggerStyles[property] || {};
var /** @type {?} */ fromStateStyles = triggerStateStyles[oldValue] || triggerStateStyles[DEFAULT_STATE_STYLES];
if (fromStateStyles) {
eraseStyles(element, fromStateStyles);
}
element[storageProp] = value;
this._onDoneFns.push(function () {
var /** @type {?} */ toStateStyles = triggerStateStyles[value] || triggerStateStyles[DEFAULT_STATE_STYLES];
if (toStateStyles) {
setStyles(element, toStateStyles);
}
});
};
/**
* @param {?} element
* @param {?} eventName
* @param {?} eventPhase
* @param {?} callback
* @return {?}
*/
NoopAnimationEngine.prototype.listen = function (element, eventName, eventPhase, callback) {
var /** @type {?} */ listeners = this._listeners.get(element);
if (!listeners) {
this._listeners.set(element, listeners = []);
}
var /** @type {?} */ tuple = ({ triggerName: eventName, eventPhase: eventPhase, callback: callback });
listeners.push(tuple);
return function () { return tuple.doRemove = true; };
};
/**
* @return {?}
*/
NoopAnimationEngine.prototype.flush = function () {
var _this = this;
var /** @type {?} */ onStartCallbacks = [];
var /** @type {?} */ onDoneCallbacks = [];
/**
* @param {?} listener
* @param {?} data
* @return {?}
*/
function handleListener(listener, data) {
var /** @type {?} */ phase = listener.eventPhase;
var /** @type {?} */ event = makeAnimationEvent$1(data.element, data.triggerName, data.oldValue, data.newValue, phase, 0);
if (phase == 'start') {
onStartCallbacks.push(function () { return listener.callback(event); });
}
else if (phase == 'done') {
onDoneCallbacks.push(function () { return listener.callback(event); });
}
}
this._changes.forEach(function (change) {
var /** @type {?} */ element = change.element;
var /** @type {?} */ listeners = _this._listeners.get(element);
if (listeners) {
listeners.forEach(function (listener) {
if (listener.triggerName == change.triggerName) {
handleListener(listener, change);
}
});
}
});
// upon removal ALL the animation triggers need to get fired
this._flaggedRemovals.forEach(function (element) {
var /** @type {?} */ listeners = _this._listeners.get(element);
if (listeners) {
listeners.forEach(function (listener) {
var /** @type {?} */ triggerName = listener.triggerName;
var /** @type {?} */ storageProp = makeStorageProp(triggerName);
handleListener(listener, /** @type {?} */ ({
element: element,
triggerName: triggerName,
oldValue: element[storageProp] || DEFAULT_STATE_VALUE,
newValue: DEFAULT_STATE_VALUE
}));
});
}
});
// remove all the listeners after everything is complete
Array.from(this._listeners.keys()).forEach(function (element) {
var /** @type {?} */ listenersToKeep = ((_this._listeners.get(element))).filter(function (l) { return !l.doRemove; });
if (listenersToKeep.length) {
_this._listeners.set(element, listenersToKeep);
}
else {
_this._listeners.delete(element);
}
});
onStartCallbacks.forEach(function (fn) { return fn(); });
onDoneCallbacks.forEach(function (fn) { return fn(); });
this._flaggedRemovals.clear();
this._changes = [];
this._onDoneFns.forEach(function (doneFn) { return doneFn(); });
this._onDoneFns = [];
};
Object.defineProperty(NoopAnimationEngine.prototype, "activePlayers", {
/**
* @return {?}
*/
get: function () { return []; },
enumerable: true,
configurable: true
});
Object.defineProperty(NoopAnimationEngine.prototype, "queuedPlayers", {
/**
* @return {?}
*/
get: function () { return []; },
enumerable: true,
configurable: true
});
return NoopAnimationEngine;
}(AnimationEngine));
/**
* @param {?} element
* @param {?} triggerName
* @param {?} fromState
* @param {?} toState
* @param {?} phaseName
* @param {?} totalTime
* @return {?}
*/
function makeAnimationEvent$1(element, triggerName, fromState, toState, phaseName, totalTime) {
return ({ element: element, triggerName: triggerName, fromState: fromState, toState: toState, phaseName: phaseName, totalTime: totalTime });
}
/**
* @param {?} property
* @return {?}
*/
function makeStorageProp(property) {
return '_@_' + property;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var WebAnimationsPlayer = (function () {
/**
* @param {?} element
* @param {?} keyframes
* @param {?} options
* @param {?=} previousPlayers
*/
function WebAnimationsPlayer(element, keyframes, options, previousPlayers) {
if (previousPlayers === void 0) { previousPlayers = []; }
var _this = this;
this.element = element;
this.keyframes = keyframes;
this.options = options;
this._onDoneFns = [];
this._onStartFns = [];
this._onDestroyFns = [];
this._initialized = false;
this._finished = false;
this._started = false;
this._destroyed = false;
this.time = 0;
this.parentPlayer = null;
this._duration = options['duration'];
this._delay = options['delay'] || 0;
this.time = this._duration + this._delay;
this.previousStyles = {};
previousPlayers.forEach(function (player) {
var styles = player._captureStyles();
Object.keys(styles).forEach(function (prop) { return _this.previousStyles[prop] = styles[prop]; });
});
}
/**
* @return {?}
*/
WebAnimationsPlayer.prototype._onFinish = function () {
if (!this._finished) {
this._finished = true;
this._onDoneFns.forEach(function (fn) { return fn(); });
this._onDoneFns = [];
}
};
/**
* @return {?}
*/
WebAnimationsPlayer.prototype.init = function () {
var _this = this;
if (this._initialized)
return;
this._initialized = true;
var /** @type {?} */ keyframes = this.keyframes.map(function (styles) {
var /** @type {?} */ formattedKeyframe = {};
Object.keys(styles).forEach(function (prop, index) {
var /** @type {?} */ value = styles[prop];
if (value == AUTO_STYLE) {
value = _computeStyle(_this.element, prop);
}
if (value != undefined) {
formattedKeyframe[prop] = value;
}
});
return formattedKeyframe;
});
var /** @type {?} */ previousStyleProps = Object.keys(this.previousStyles);
if (previousStyleProps.length) {
var /** @type {?} */ startingKeyframe_1 = keyframes[0];
var /** @type {?} */ missingStyleProps_1 = [];
previousStyleProps.forEach(function (prop) {
if (!startingKeyframe_1.hasOwnProperty(prop)) {
missingStyleProps_1.push(prop);
}
startingKeyframe_1[prop] = _this.previousStyles[prop];
});
if (missingStyleProps_1.length) {
var /** @type {?} */ self_1 = this;
var _loop_3 = function () {
var /** @type {?} */ kf = keyframes[i];
missingStyleProps_1.forEach(function (prop) {
kf[prop] = _computeStyle(self_1.element, prop);
});
};
// tslint:disable-next-line
for (var /** @type {?} */ i = 1; i < keyframes.length; i++) {
_loop_3();
}
}
}
this._player = this._triggerWebAnimation(this.element, keyframes, this.options);
this._finalKeyframe =
keyframes.length ? _copyKeyframeStyles(keyframes[keyframes.length - 1]) : {};
// this is required so that the player doesn't start to animate right away
this._resetDomPlayerState();
this._player.addEventListener('finish', function () { return _this._onFinish(); });
};
/**
* \@internal
* @param {?} element
* @param {?} keyframes
* @param {?} options
* @return {?}
*/
WebAnimationsPlayer.prototype._triggerWebAnimation = function (element, keyframes, options) {
// jscompiler doesn't seem to know animate is a native property because it's not fully
// supported yet across common browsers (we polyfill it for Edge/Safari) [CL #143630929]
return (element['animate'](keyframes, options));
};
Object.defineProperty(WebAnimationsPlayer.prototype, "domPlayer", {
/**
* @return {?}
*/
get: function () { return this._player; },
enumerable: true,
configurable: true
});
/**
* @param {?} fn
* @return {?}
*/
WebAnimationsPlayer.prototype.onStart = function (fn) { this._onStartFns.push(fn); };
/**
* @param {?} fn
* @return {?}
*/
WebAnimationsPlayer.prototype.onDone = function (fn) { this._onDoneFns.push(fn); };
/**
* @param {?} fn
* @return {?}
*/
WebAnimationsPlayer.prototype.onDestroy = function (fn) { this._onDestroyFns.push(fn); };
/**
* @return {?}
*/
WebAnimationsPlayer.prototype.play = function () {
this.init();
if (!this.hasStarted()) {
this._onStartFns.forEach(function (fn) { return fn(); });
this._onStartFns = [];
this._started = true;
}
this._player.play();
};
/**
* @return {?}
*/
WebAnimationsPlayer.prototype.pause = function () {
this.init();
this._player.pause();
};
/**
* @return {?}
*/
WebAnimationsPlayer.prototype.finish = function () {
this.init();
this._onFinish();
this._player.finish();
};
/**
* @return {?}
*/
WebAnimationsPlayer.prototype.reset = function () {
this._resetDomPlayerState();
this._destroyed = false;
this._finished = false;
this._started = false;
};
/**
* @return {?}
*/
WebAnimationsPlayer.prototype._resetDomPlayerState = function () {
if (this._player) {
this._player.cancel();
}
};
/**
* @return {?}
*/
WebAnimationsPlayer.prototype.restart = function () {
this.reset();
this.play();
};
/**
* @return {?}
*/
WebAnimationsPlayer.prototype.hasStarted = function () { return this._started; };
/**
* @return {?}
*/
WebAnimationsPlayer.prototype.destroy = function () {
if (!this._destroyed) {
this._resetDomPlayerState();
this._onFinish();
this._destroyed = true;
this._onDestroyFns.forEach(function (fn) { return fn(); });
this._onDestroyFns = [];
}
};
/**
* @param {?} p
* @return {?}
*/
WebAnimationsPlayer.prototype.setPosition = function (p) { this._player.currentTime = p * this.time; };
/**
* @return {?}
*/
WebAnimationsPlayer.prototype.getPosition = function () { return this._player.currentTime / this.time; };
/**
* @return {?}
*/
WebAnimationsPlayer.prototype._captureStyles = function () {
var _this = this;
var /** @type {?} */ styles = {};
if (this.hasStarted()) {
Object.keys(this._finalKeyframe).forEach(function (prop) {
if (prop != 'offset') {
styles[prop] =
_this._finished ? _this._finalKeyframe[prop] : _computeStyle(_this.element, prop);
}
});
}
return styles;
};
return WebAnimationsPlayer;
}());
/**
* @param {?} element
* @param {?} prop
* @return {?}
*/
function _computeStyle(element, prop) {
return ((window.getComputedStyle(element)))[prop];
}
/**
* @param {?} styles
* @return {?}
*/
function _copyKeyframeStyles(styles) {
var /** @type {?} */ newStyles = {};
Object.keys(styles).forEach(function (prop) {
if (prop != 'offset') {
newStyles[prop] = styles[prop];
}
});
return newStyles;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var WebAnimationsDriver = (function () {
function WebAnimationsDriver() {
}
/**
* @param {?} element
* @param {?} keyframes
* @param {?} duration
* @param {?} delay
* @param {?} easing
* @param {?=} previousPlayers
* @return {?}
*/
WebAnimationsDriver.prototype.animate = function (element, keyframes, duration, delay, easing, previousPlayers) {
if (previousPlayers === void 0) { previousPlayers = []; }
var /** @type {?} */ playerOptions = { 'duration': duration, 'delay': delay, 'fill': 'forwards' };
// we check for this to avoid having a null|undefined value be present
// for the easing (which results in an error for certain browsers #9752)
if (easing) {
playerOptions['easing'] = easing;
}
var /** @type {?} */ previousWebAnimationPlayers = (previousPlayers.filter(function (player) { return player instanceof WebAnimationsPlayer; }));
return new WebAnimationsPlayer(element, keyframes, playerOptions, previousWebAnimationPlayers);
};
return WebAnimationsDriver;
}());
/**
* @return {?}
*/
function supportsWebAnimations() {
return typeof Element !== 'undefined' && typeof ((Element)).prototype['animate'] === 'function';
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @module
* @description
* Entry point for all animation APIs of the animation browser package.
*/
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @module
* @description
* Entry point for all public APIs of the animation package.
*/
/**
* Generated bundle index. Do not edit.
*/
export { AnimationDriver, AnimationEngine as ɵAnimationEngine, Animation as ɵAnimation, AnimationStyleNormalizer as ɵAnimationStyleNormalizer, NoopAnimationStyleNormalizer as ɵNoopAnimationStyleNormalizer, WebAnimationsStyleNormalizer as ɵWebAnimationsStyleNormalizer, NoopAnimationDriver as ɵNoopAnimationDriver, DomAnimationEngine as ɵDomAnimationEngine, NoopAnimationEngine as ɵNoopAnimationEngine, WebAnimationsDriver as ɵWebAnimationsDriver, supportsWebAnimations as ɵsupportsWebAnimations, WebAnimationsPlayer as ɵWebAnimationsPlayer };
//# sourceMappingURL=browser.es5.js.map
|
import devip from 'dev-ip';
import { getSettings, initLog } from 'roc';
import config from '../config/roc.config.js';
let onceDevPort = true;
const devIp = devip();
const log = initLog();
/**
* Returns the current dev host.
*
* @returns {string} The host that should be used.
*/
export function getDevHost() {
const { host } = getSettings('dev');
if (host) {
return host;
}
return devIp.length ? devIp[0] : 'localhost';
}
/**
* Returns the current dev port.
*
*It will first default to the environment variable `DEV_PORT` and after that `roc.config.js`.
*
* Will give a warning if `DEV_PORT` is defined and the value in the configuration is something other than default.
*
* @returns {number} The final port for the dev server.
*/
export function getDevPort() {
const settings = getSettings('dev');
if (settings.port !== config.settings.dev.port && process.env.DEV_PORT && onceDevPort) {
onceDevPort = false;
log.small.warn('You have configured a dev port but the environment variable DEV_PORT ' +
`is set and that will be used instead. The port that will be used is ${process.env.DEV_PORT}`
);
}
return process.env.DEV_PORT || settings.port;
}
/**
* Returns the current dev path.
*
* Will use {@link getDevPort} for getting the port.
*
* @param {string} [relativeBuildPath] - Relative path to where the build is saved.
* @returns {string} The complete dev path on the server including the port.
*/
export function getDevPath(relativeBuildPath = '') {
const buildPath = relativeBuildPath && relativeBuildPath.slice(-1) !== '/' ?
`${relativeBuildPath}/` :
relativeBuildPath;
return `http://${getDevHost()}:${getDevPort()}/${buildPath}`;
}
/**
* Removes possible trailing slashes from a path.
*
* @param {string} path - Path to remove possible trailing slashes.
*
* @returns {string} - Path without trailing slashes.
*/
export function removeTrailingSlash(path) {
const newPath = path.replace(/\/+$/, '');
if (!newPath) {
return '/';
}
return newPath;
}
/**
* Adds a trailing slashes to a path.
*
* Runs {@link removeTrailingSlash} internally first.
*
* @param {string} path - Path to add a trailing slashes to.
*
* @returns {string} - Path with trailing slash.
*/
export function addTrailingSlash(path) {
const newPath = removeTrailingSlash(path);
if (newPath !== '/') {
return `${newPath}/`;
}
return newPath;
}
|
/**
* Created by liuff on 2016/12/13 21:27
*/
var querystring = require('querystring');
var http = require('http');
var process = require('process');
var URL = process.argv[2];
var PATTERN = process.argv[3];
// console.log("Elasticsearch url = " + URL);
console.log("Index pattern = " + PATTERN);
if (URL == null || PATTERN == null) {
console.log("Invalid parameters.");
console.log("Usage: node detecter.js <ELASTIC_URL> <INDEX_PATTERNS>");
console.log("Example: node detecter.js http://192.168.1.1:9200 index*");
return;
}
var pos = URL.lastIndexOf(":");
if (pos == -1) {
console.log("PORT is not set");
return;
}
var protocol = URL.indexOf(":");
var HOST = URL.substr(protocol + 3, (pos - protocol - 3));
var PORT = URL.substr(pos + 1);
console.log("Elasticsearch Host = " + HOST + ", PORT = " + PORT);
var PATTERN = "sharpview-*";
// An object of options to indicate where to post to
var indices = {
host: HOST ,
port: PORT,
path: "/_cat/indices",
method: 'GET'
};
var http = require("http");
var https = require("https");
var s = "";
for (var i=0; i<PATTERN.length; i++) {
if (PATTERN[i] == "*") {
s += ".*";
continue;
}
if (PATTERN[i] == "?") {
s += ".?";
continue;
}
s += PATTERN[i];
}
var compiledPattern = new RegExp(s, "g");
get = function(options, onResult)
{
var prot = options.port == 443 ? https : http;
var req = prot.request(options, function(res)
{
var output = '';
// console.log(options.host + ':' + res.statusCode);
res.setEncoding('utf8');
res.on('data', function (chunk) {
output += chunk;
});
res.on('end', function() {
onResult(res.statusCode, output);
});
});
req.on('error', function(err) {
//res.send('error: ' + err.message);
console.error("Failed to send request", err.message);
});
req.end();
};
function getIndexName(line) {
var items = line.split(" ");
return items[2];
}
function processIndex(index) {
if (index.search(compiledPattern) == -1) {
return;
}
get( {
host: HOST ,
port: PORT,
path: "/" + index + "/_mappings",
method: "GET"
}, function(code, result) {
if (code == 200) {
console.log("Checking index", index);
var obj = JSON.parse(result);
for (var key in obj) {
var m = obj[key];
if (m == null) {
continue;
}
var mappings = m["mappings"];
if (mappings == null) {
continue;
}
for (var type in mappings) {
// console.log("Get a type ", type);
if (mappings[type] == null) {
continue;
}
var properties = mappings[type].properties;
for (var field in properties) {
var f = properties[field];
// console.log(f);
if (f == null) {
continue;
}
var fieldType = f.type;
// console.log("-> ", type, field, "-", fieldType);
audit(index, type, field, fieldType);
}
}
// console.log(mappings);
}
}
});
}
var allData = {};
function audit(index, type, field, fieldType) {
var list = allData[field];
if (list == null) {
list = [];
}
list.push( {
"index" : index,
"type" : type,
"field" : field,
"fieldType" : fieldType
})
allData[field] = list;
if (list.length > 1) {
check(list);
}
}
function check(list) {
for (var i=0; i<list.length; i++) {
for (var j=0; j<i; j++) {
if (i == j) {
continue;
}
var type0 = list[i].fieldType;
var type1 = list[j].fieldType;
var level = isOK(type0, type1);
if (level == null) {
console.warn("No data found for ", key)
return 0;
}
if (level == 9) {
console.log("ERR ", list[i].index + "/" + list[i].type + "/" + list[i].field
+ " is " + type0, " conflict with ",
list[j].index + "/" + list[j].type + "/" + list[j].field
)
}
if (level == 1) {
console.log("WARN ", list[i].index + "/" + list[i].type + "/" + list[i].field
+ " is " + type0, " is not same. May cause performance/precision problems ",
list[j].index + "/" + list[j].type + "/" + list[j].field
)
}
}
}
}
var matrix = {};
matrix["string,string"] = 0;
matrix["string,float"] = 9;
matrix["string,double"] = 9;
matrix["string,integer"] = 9;
matrix["string,date"] = 9;
matrix["string,long"] = 9;
matrix["string,number"] = 9;
matrix["string,byte"] = 9;
matrix["float,float"] = 0;
matrix["float,string"] = 9;
matrix["float,double"] = 1;
matrix["float,integer"] = 1;
matrix["float,date"] = 9;
matrix["float,long"] = 1;
matrix["float,number"] = 0;
matrix["float,byte"] = 1;
matrix["double,float"] = 1;
matrix["double,string"] = 9;
matrix["double,double"] = 0;
matrix["double,integer"] = 1;
matrix["double,date"] = 9;
matrix["double,long"] = 1;
matrix["double,number"] = 0;
matrix["double,byte"] = 1;
matrix["integer,float"] = 1;
matrix["integer,string"] = 9;
matrix["integer,double"] = 1;
matrix["integer,integer"] = 0;
matrix["integer,date"] = 9;
matrix["integer,long"] = 1;
matrix["integer,number"] = 0;
matrix["integer,byte"] = 1;
matrix["date,float"] = 9;
matrix["date,string"] = 9;
matrix["date,double"] = 9;
matrix["date,integer"] = 9;
matrix["date,date"] = 0;
matrix["date,long"] = 9;
matrix["date,number"] = 9;
matrix["date,byte"] = 9;
matrix["long,float"] = 1;
matrix["long,string"] = 9;
matrix["long,double"] = 1;
matrix["long,integer"] = 1;
matrix["long,date"] = 9;
matrix["long,long"] = 0;
matrix["long,number"] = 0;
matrix["long,byte"] = 1;
matrix["number,float"] = 0;
matrix["number,string"] = 9;
matrix["number,double"] = 0;
matrix["number,integer"] = 0;
matrix["number,date"] = 9;
matrix["number,long"] = 1;
matrix["number,number"] = 0;
matrix["number,byte"] = 1;
matrix["byte,float"] = 1;
matrix["byte,string"] = 9;
matrix["byte,double"] = 1;
matrix["byte,integer"] = 1;
matrix["byte,date"] = 9;
matrix["byte,long"] = 1;
matrix["byte,number"] = 0;
matrix["byte,byte"] = 0;
function isOK(type0, type1) {
var key = type0 +"," + type1;
var level = matrix[key];
return level;
}
get(indices, function(code, obj) {
if (code == 200) {
var lines = obj.split("\n");
console.log("Get " + lines.length + " indices.");
for (var i=0; i<lines.length; i++) {
var name = getIndexName(lines[i]);
if (name != undefined) {
processIndex(name);
}
}
}
});
|
// TEST DATA
// Keyed by mocha test ID
// Python code for generating test data can be found in the matching jupyter notebook in folder `notebooks/`.
;(function() {
var DATA = {
'convolutional.Conv2D.0': {
input: {
shape: [5, 5, 2],
data: [
-0.990562,
-0.756862,
0.341498,
0.651706,
-0.726587,
0.150187,
0.782644,
-0.581596,
-0.629344,
-0.783246,
-0.560605,
0.957248,
0.623366,
-0.656118,
0.632449,
-0.451853,
-0.136592,
0.88006,
0.635299,
-0.327776,
-0.649179,
-0.254336,
-0.988623,
-0.495147,
0.591325,
-0.96949,
0.197687,
0.207609,
-0.789705,
-0.236113,
-0.927048,
0.780823,
0.961842,
-0.880116,
0.781092,
0.153803,
0.484959,
0.260368,
0.163684,
-0.959122,
-0.579947,
0.08937,
0.53823,
-0.49861,
-0.428209,
0.70479,
0.950013,
0.769707,
-0.280984,
0.197718
]
},
expected: {
shape: [3, 3, 4],
data: [
1.881069,
1.507598,
-0.42648,
0.981946,
-1.295304,
-2.802102,
-3.379112,
1.371861,
-0.618295,
-0.672642,
0.74116,
-0.092844,
1.342198,
-0.536709,
-0.195162,
-1.44153,
-1.020649,
3.006844,
0.951307,
0.750237,
-0.934043,
-0.375223,
-1.075853,
2.961484,
0.996102,
-2.28647,
-2.774244,
0.264827,
-0.138134,
2.738469,
0.662859,
-2.902777,
-0.663609,
-1.414437,
-4.081861,
0.236701
]
},
weights: [
{
shape: [3, 3, 2, 4],
data: [
0.08681,
-0.443261,
-0.150965,
0.689552,
-0.990562,
-0.756862,
0.341498,
0.651706,
-0.726587,
0.150187,
0.782644,
-0.581596,
-0.629344,
-0.783246,
-0.560605,
0.957248,
0.623366,
-0.656118,
0.632449,
-0.451853,
-0.136592,
0.88006,
0.635299,
-0.327776,
-0.649179,
-0.254336,
-0.988623,
-0.495147,
0.591325,
-0.96949,
0.197687,
0.207609,
-0.789705,
-0.236113,
-0.927048,
0.780823,
0.961842,
-0.880116,
0.781092,
0.153803,
0.484959,
0.260368,
0.163684,
-0.959122,
-0.579947,
0.08937,
0.53823,
-0.49861,
-0.428209,
0.70479,
0.950013,
0.769707,
-0.280984,
0.197718,
-0.290409,
-0.31962,
-0.643838,
-0.524612,
-0.910275,
0.010863,
-0.247495,
0.185611,
0.259884,
-0.714799,
0.867683,
0.89276,
0.204593,
-0.224467,
-0.273624,
-0.591309,
-0.44647,
-0.506928
]
},
{ shape: [4], data: [0.08681, -0.443261, -0.150965, 0.689552] }
]
},
'convolutional.Conv2D.1': {
input: {
shape: [5, 5, 2],
data: [
0.303535,
-0.150862,
0.313191,
-0.581677,
0.319849,
0.059247,
0.497041,
-0.812486,
0.569044,
0.374484,
0.390157,
-0.006267,
0.950722,
-0.592945,
-0.401959,
-0.544688,
-0.903662,
0.807943,
-0.839793,
0.214433,
0.261693,
-0.244116,
-0.973518,
0.684439,
-0.230125,
0.103332,
0.421076,
0.350558,
0.389129,
-0.315086,
-0.175219,
-0.520418,
0.937672,
-0.422886,
-0.705377,
-0.741319,
0.888112,
-0.297131,
0.467135,
0.827779,
0.401975,
-0.222937,
0.884519,
0.472983,
-0.523071,
0.647547,
0.521227,
-0.210582,
-0.599624,
0.425193
]
},
expected: {
shape: [3, 3, 4],
data: [
0.222896,
1.085101,
1.523122,
0.029914,
-3.208341,
0.668446,
0.159678,
-2.842651,
1.751455,
0.291728,
-3.055066,
-1.414293,
2.641148,
-0.979586,
-3.159913,
0.963647,
2.551851,
-1.421387,
-2.003495,
-0.273586,
-0.434787,
0.075452,
0.122831,
0.496359,
-0.500579,
0.818305,
0.353606,
-1.248895,
-1.872087,
1.321958,
0.976701,
0.640393,
-2.795104,
-2.835678,
1.354631,
-1.549929
]
},
weights: [
{
shape: [3, 3, 2, 4],
data: [
0.032797,
0.141335,
-0.943052,
-0.656957,
0.370554,
0.667794,
-0.386068,
0.787226,
0.443088,
-0.620122,
0.108455,
-0.295736,
-0.636215,
0.571204,
0.930966,
-0.535293,
-0.832877,
0.207097,
0.457986,
-0.447522,
0.370613,
0.035735,
-0.903031,
-0.724262,
-0.626065,
0.988636,
0.041331,
0.157579,
0.469638,
0.083924,
0.826307,
0.61584,
-0.194004,
-0.285551,
0.905753,
-0.312737,
0.7302,
0.660555,
0.076323,
0.844939,
-0.805707,
-0.794305,
0.403015,
0.78096,
-0.680879,
-0.448855,
0.344983,
-0.671394,
0.402742,
-0.02473,
0.361356,
0.043096,
-0.913207,
-0.552127,
0.15041,
-0.759133,
0.000233,
-0.723981,
-0.894383,
-0.643446,
-0.115264,
0.755175,
0.898528,
-0.043665,
-0.077761,
0.274578,
-0.350784,
-0.764844,
-0.897798,
0.275317,
0.624532,
0.340521
]
}
]
},
'convolutional.Conv2D.2': {
input: {
shape: [5, 5, 2],
data: [
0.157479,
0.618035,
-0.665503,
-0.37571,
-0.284137,
-0.016505,
-0.019604,
0.78882,
-0.635179,
-0.277676,
0.621183,
-0.333106,
0.037901,
-0.47676,
-0.738144,
-0.755166,
0.103315,
-0.941233,
0.20555,
0.501765,
-0.501859,
-0.604645,
0.147912,
0.803597,
0.032433,
-0.197603,
0.034979,
0.874782,
0.700816,
-0.648994,
0.039638,
0.011529,
-0.302879,
-0.858314,
0.151964,
-0.196575,
0.82283,
0.617771,
-0.735886,
0.429729,
-0.306674,
0.228823,
-0.425021,
0.971139,
-0.455574,
0.638783,
0.199032,
0.44091,
0.91975,
-0.814286
]
},
expected: {
shape: [2, 2, 4],
data: [
0.20599,
0.342823,
0.742175,
0.0,
0.815729,
2.184798,
1.251954,
0.0,
0.0,
0.0,
1.112864,
0.010656,
0.731076,
0.0,
0.855229,
0.0
]
},
weights: [
{
shape: [3, 3, 2, 4],
data: [
0.195363,
0.351974,
-0.401437,
0.461481,
0.157479,
0.618035,
-0.665503,
-0.37571,
-0.284137,
-0.016505,
-0.019604,
0.78882,
-0.635179,
-0.277676,
0.621183,
-0.333106,
0.037901,
-0.47676,
-0.738144,
-0.755166,
0.103315,
-0.941233,
0.20555,
0.501765,
-0.501859,
-0.604645,
0.147912,
0.803597,
0.032433,
-0.197603,
0.034979,
0.874782,
0.700816,
-0.648994,
0.039638,
0.011529,
-0.302879,
-0.858314,
0.151964,
-0.196575,
0.82283,
0.617771,
-0.735886,
0.429729,
-0.306674,
0.228823,
-0.425021,
0.971139,
-0.455574,
0.638783,
0.199032,
0.44091,
0.91975,
-0.814286,
-0.088979,
0.765096,
0.395408,
-0.357503,
-0.275416,
0.467275,
0.245085,
-0.563436,
0.96541,
-0.199388,
0.43292,
-0.389609,
0.298369,
-0.25199,
-0.266434,
-0.949491,
-0.303867,
-0.024641
]
},
{ shape: [4], data: [0.195363, 0.351974, -0.401437, 0.461481] }
]
},
'convolutional.Conv2D.3': {
input: {
shape: [7, 7, 3],
data: [
-0.081293,
0.64537,
0.643096,
-0.385759,
-0.598211,
-0.193535,
0.895779,
0.355089,
0.21795,
0.344727,
-0.984035,
-0.32688,
-0.285455,
-0.02788,
0.756565,
0.509817,
0.26093,
-0.247033,
0.180323,
0.474657,
0.192293,
-0.815041,
-0.195458,
0.179373,
-0.769174,
-0.223611,
-0.880477,
0.167916,
-0.666549,
-0.303809,
-0.156202,
-0.501052,
0.539906,
0.10262,
-0.947416,
0.541952,
-0.813565,
0.405592,
0.159078,
0.198436,
0.71454,
0.102339,
-0.835312,
0.466992,
0.067715,
-0.315822,
-0.056778,
-0.556856,
-0.647049,
-0.050928,
-0.277526,
0.64888,
-0.708,
0.639138,
-0.632262,
0.126027,
-0.751824,
0.387838,
-0.924068,
-0.411933,
0.793635,
-0.432359,
-0.568279,
-0.942986,
-0.929277,
0.746907,
0.954599,
-0.470971,
0.887461,
-0.919761,
-0.423457,
0.359481,
0.23833,
0.4367,
0.136035,
0.837921,
0.01252,
0.76166,
-0.067006,
-0.569453,
0.707085,
-0.685992,
-0.972653,
0.424172,
-0.023413,
-0.494544,
0.239537,
-0.357146,
-0.832116,
0.911805,
-0.493355,
0.799492,
0.907763,
0.590698,
-0.657319,
-0.899599,
0.66576,
-0.026552,
-0.808517,
0.761201,
0.060031,
0.911167,
-0.541875,
-0.052366,
-0.677874,
-0.540037,
0.858037,
0.841428,
0.664757,
0.159247,
-0.408513,
0.157763,
0.953228,
-0.419758,
0.13644,
0.857617,
0.935383,
-0.725736,
0.482768,
0.919937,
0.516163,
0.078243,
0.504286,
0.149417,
0.153285,
-0.686413,
-0.515197,
0.529735,
-0.671812,
0.737835,
0.760286,
-0.825563,
0.862511,
-0.185154,
0.436687,
-0.452091,
-0.048684,
0.142544,
0.590622,
-0.014887,
0.081443,
-0.873841,
-0.178904,
0.779569,
0.836992,
-0.238607,
0.944873
]
},
expected: {
shape: [2, 4, 5],
data: [
0.0,
0.0,
3.453939,
0.0,
1.228864,
0.0,
0.469417,
0.0,
0.0,
2.662399,
0.0526,
0.0,
0.0,
0.0,
4.369679,
0.0,
0.0,
0.0,
3.251074,
0.602914,
0.0,
4.518651,
0.0,
2.820123,
1.26282,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.960698,
1.478059,
0.0,
0.0,
1.973457,
0.620029,
0.0,
0.0,
3.609938
]
},
weights: [
{
shape: [4, 4, 3, 5],
data: [
-0.135778,
-0.651569,
-0.658113,
0.655264,
0.174343,
-0.081293,
0.64537,
0.643096,
-0.385759,
-0.598211,
-0.193535,
0.895779,
0.355089,
0.21795,
0.344727,
-0.984035,
-0.32688,
-0.285455,
-0.02788,
0.756565,
0.509817,
0.26093,
-0.247033,
0.180323,
0.474657,
0.192293,
-0.815041,
-0.195458,
0.179373,
-0.769174,
-0.223611,
-0.880477,
0.167916,
-0.666549,
-0.303809,
-0.156202,
-0.501052,
0.539906,
0.10262,
-0.947416,
0.541952,
-0.813565,
0.405592,
0.159078,
0.198436,
0.71454,
0.102339,
-0.835312,
0.466992,
0.067715,
-0.315822,
-0.056778,
-0.556856,
-0.647049,
-0.050928,
-0.277526,
0.64888,
-0.708,
0.639138,
-0.632262,
0.126027,
-0.751824,
0.387838,
-0.924068,
-0.411933,
0.793635,
-0.432359,
-0.568279,
-0.942986,
-0.929277,
0.746907,
0.954599,
-0.470971,
0.887461,
-0.919761,
-0.423457,
0.359481,
0.23833,
0.4367,
0.136035,
0.837921,
0.01252,
0.76166,
-0.067006,
-0.569453,
0.707085,
-0.685992,
-0.972653,
0.424172,
-0.023413,
-0.494544,
0.239537,
-0.357146,
-0.832116,
0.911805,
-0.493355,
0.799492,
0.907763,
0.590698,
-0.657319,
-0.899599,
0.66576,
-0.026552,
-0.808517,
0.761201,
0.060031,
0.911167,
-0.541875,
-0.052366,
-0.677874,
-0.540037,
0.858037,
0.841428,
0.664757,
0.159247,
-0.408513,
0.157763,
0.953228,
-0.419758,
0.13644,
0.857617,
0.935383,
-0.725736,
0.482768,
0.919937,
0.516163,
0.078243,
0.504286,
0.149417,
0.153285,
-0.686413,
-0.515197,
0.529735,
-0.671812,
0.737835,
0.760286,
-0.825563,
0.862511,
-0.185154,
0.436687,
-0.452091,
-0.048684,
0.142544,
0.590622,
-0.014887,
0.081443,
-0.873841,
-0.178904,
0.779569,
0.836992,
-0.238607,
0.944873,
-0.037027,
0.774056,
-0.735437,
-0.253303,
0.60782,
-0.992794,
-0.798253,
-0.273809,
-0.777994,
-0.466779,
0.512164,
0.312941,
0.447827,
-0.619183,
-0.679821,
0.28787,
0.256291,
-0.157439,
-0.23489,
0.178363,
0.477582,
-0.679932,
-0.698904,
-0.04713,
-0.596417,
0.683988,
0.128674,
0.14461,
-0.053412,
-0.598701,
-0.28704,
-0.083479,
0.252272,
-0.817686,
0.195913,
-0.564344,
-0.987454,
0.1461,
-0.206776,
0.336421,
0.457537,
-0.656402,
0.828352,
-0.410226,
0.319745,
-0.742681,
-0.203616,
0.331785,
0.514347,
-0.517425,
-0.796471,
0.25001,
-0.495738,
-0.667485,
0.156551,
0.958574,
-0.644056,
0.765525,
-0.200055,
-0.415118,
-0.292941,
-0.599639,
0.416564,
-0.366227,
0.181605,
0.062272,
-0.277941,
-0.991833,
0.459158,
0.237737,
-0.007369,
-0.433549,
0.091637,
-0.048628,
0.386804,
0.402629,
-0.215112,
-0.178129,
-0.974124,
0.785804,
-0.987586,
-0.342624,
0.042113,
-0.991281,
-0.011006,
-0.075192,
-0.375827,
-0.229347
]
},
{ shape: [5], data: [-0.135778, -0.651569, -0.658113, 0.655264, 0.174343] }
]
},
'convolutional.Conv2D.4': {
input: {
shape: [5, 5, 2],
data: [
-0.628587,
0.544275,
-0.189121,
0.991809,
-0.028349,
0.30284,
0.201092,
-0.953154,
-0.343083,
0.640537,
-0.117391,
-0.526633,
-0.163892,
0.861458,
-0.665795,
0.51919,
-0.753596,
0.337708,
0.402785,
0.315812,
0.541968,
0.870102,
-0.141283,
-0.469735,
-0.574406,
-0.571765,
0.046045,
-0.790043,
-0.953079,
-0.774733,
-0.58544,
-0.882147,
0.282331,
0.214534,
0.862629,
-0.446078,
0.230215,
0.308982,
-0.361978,
-0.850926,
0.409799,
0.710712,
-0.391058,
-0.542441,
-0.41638,
0.558765,
-0.149949,
-0.864061,
-0.759997,
-0.265417
]
},
expected: {
shape: [5, 5, 4],
data: [
0.0,
1.245448,
1.285421,
0.0,
0.0,
0.359707,
1.273985,
0.0,
0.0,
0.0,
0.361441,
0.0,
0.0,
0.0,
0.0,
0.0,
0.814408,
0.0,
1.297703,
0.455072,
0.0,
0.045489,
0.0,
0.324618,
0.0,
0.74526,
0.0,
0.661333,
0.0,
0.0,
0.778435,
1.99095,
0.0,
0.0,
1.025771,
2.929728,
0.0,
0.0,
1.189183,
0.0,
0.0,
0.0,
2.123506,
0.0,
0.526917,
0.0,
2.237532,
0.0,
0.0,
0.0,
1.200334,
1.153394,
0.0,
0.0,
0.0,
4.087014,
0.0,
1.205699,
0.0,
1.322063,
0.159978,
0.037334,
0.0,
0.0,
0.0,
0.0,
0.4114,
0.0,
0.558253,
0.0,
0.0,
0.245042,
0.063339,
0.0,
0.433151,
0.396075,
0.39434,
0.0,
0.433619,
1.579657,
0.0,
0.0,
1.226101,
0.782336,
0.542313,
0.515257,
0.0,
0.0,
0.0,
0.0,
2.093277,
0.652337,
0.0,
0.0,
0.944013,
0.0,
0.306167,
0.0,
0.922607,
2.145665
]
},
weights: [
{
shape: [3, 3, 2, 4],
data: [
-0.704159,
-0.543403,
0.614987,
-0.403051,
-0.628587,
0.544275,
-0.189121,
0.991809,
-0.028349,
0.30284,
0.201092,
-0.953154,
-0.343083,
0.640537,
-0.117391,
-0.526633,
-0.163892,
0.861458,
-0.665795,
0.51919,
-0.753596,
0.337708,
0.402785,
0.315812,
0.541968,
0.870102,
-0.141283,
-0.469735,
-0.574406,
-0.571765,
0.046045,
-0.790043,
-0.953079,
-0.774733,
-0.58544,
-0.882147,
0.282331,
0.214534,
0.862629,
-0.446078,
0.230215,
0.308982,
-0.361978,
-0.850926,
0.409799,
0.710712,
-0.391058,
-0.542441,
-0.41638,
0.558765,
-0.149949,
-0.864061,
-0.759997,
-0.265417,
-0.331629,
-0.845702,
0.426935,
-0.731659,
0.062865,
-0.255582,
0.396332,
0.639196,
-0.078254,
-0.253246,
0.792036,
0.044105,
0.879927,
-0.987868,
-0.35422,
0.924714,
0.304954,
-0.870234
]
},
{ shape: [4], data: [-0.704159, -0.543403, 0.614987, -0.403051] }
]
},
'convolutional.Conv2D.5': {
input: {
shape: [4, 4, 2],
data: [
0.07128,
-0.872621,
-0.406331,
-0.99551,
-0.097768,
0.767239,
0.154115,
-0.502245,
-0.316894,
-0.859603,
0.076951,
0.050967,
0.637593,
0.372661,
0.261934,
-0.259222,
0.072217,
-0.653676,
-0.668125,
-0.779061,
-0.348294,
0.794828,
0.096874,
-0.517259,
-0.343993,
0.177857,
0.590341,
-0.037656,
0.152372,
0.180228,
0.595796,
0.556247
]
},
expected: {
shape: [2, 2, 4],
data: [
0.0,
0.565042,
0.12593,
0.0,
0.0,
0.320489,
0.979856,
0.0,
0.0,
0.0,
0.799525,
0.0,
0.0,
0.0,
0.637126,
0.0
]
},
weights: [
{
shape: [3, 3, 2, 4],
data: [
-0.83252,
-0.332987,
0.718711,
-0.788626,
0.07128,
-0.872621,
-0.406331,
-0.99551,
-0.097768,
0.767239,
0.154115,
-0.502245,
-0.316894,
-0.859603,
0.076951,
0.050967,
0.637593,
0.372661,
0.261934,
-0.259222,
0.072217,
-0.653676,
-0.668125,
-0.779061,
-0.348294,
0.794828,
0.096874,
-0.517259,
-0.343993,
0.177857,
0.590341,
-0.037656,
0.152372,
0.180228,
0.595796,
0.556247,
0.333295,
0.022451,
0.07271,
-0.653556,
0.35149,
0.816316,
0.070974,
-0.631558,
-0.817281,
0.142117,
0.649301,
-0.685559,
0.317358,
-0.816128,
0.896987,
-0.808449,
-0.141181,
0.254,
0.540822,
-0.053505,
-0.440647,
-0.503204,
-0.804487,
0.509112,
0.050405,
0.601983,
-0.385832,
0.238291,
0.998461,
0.496045,
0.077139,
-0.153403,
-0.960801,
0.630448,
-0.808006,
-0.801654
]
},
{ shape: [4], data: [-0.83252, -0.332987, 0.718711, -0.788626] }
]
},
'convolutional.Conv2D.6': {
input: {
shape: [6, 3, 1],
data: [
0.70412,
0.47762,
0.948863,
0.714924,
0.710821,
0.719052,
-0.295442,
-0.575936,
0.560889,
0.798823,
-0.904521,
-0.725105,
-0.647339,
-0.926505,
0.020986,
0.534159,
-0.030523,
-0.580772
]
},
expected: {
shape: [2, 2, 4],
data: [
0.0,
0.474708,
0.960876,
1.317228,
0.0,
2.040575,
0.0,
0.060188,
0.0,
2.127169,
0.77897,
0.632372,
0.0,
0.0,
0.462447,
0.405417
]
},
weights: [
{
shape: [3, 3, 1, 4],
data: [
-0.98287,
0.908613,
-0.10087,
0.220438,
0.70412,
0.47762,
0.948863,
0.714924,
0.710821,
0.719052,
-0.295442,
-0.575936,
0.560889,
0.798823,
-0.904521,
-0.725105,
-0.647339,
-0.926505,
0.020986,
0.534159,
-0.030523,
-0.580772,
-0.162302,
0.128018,
-0.216971,
0.026925,
0.392296,
0.991634,
0.214941,
0.639493,
-0.574398,
-0.430476,
-0.117988,
-0.261311,
-0.808084,
-0.466051
]
},
{ shape: [4], data: [-0.98287, 0.908613, -0.10087, 0.220438] }
]
},
'convolutional.Conv2D.7': {
input: {
shape: [5, 5, 2],
data: [
-0.990562,
-0.756862,
0.341498,
0.651706,
-0.726587,
0.150187,
0.782644,
-0.581596,
-0.629344,
-0.783246,
-0.560605,
0.957248,
0.623366,
-0.656118,
0.632449,
-0.451853,
-0.136592,
0.88006,
0.635299,
-0.327776,
-0.649179,
-0.254336,
-0.988623,
-0.495147,
0.591325,
-0.96949,
0.197687,
0.207609,
-0.789705,
-0.236113,
-0.927048,
0.780823,
0.961842,
-0.880116,
0.781092,
0.153803,
0.484959,
0.260368,
0.163684,
-0.959122,
-0.579947,
0.08937,
0.53823,
-0.49861,
-0.428209,
0.70479,
0.950013,
0.769707,
-0.280984,
0.197718
]
},
expected: { shape: [1, 1, 4], data: [-0.449265, 0.56076, -2.92837, 1.056555] },
weights: [
{
shape: [3, 3, 2, 4],
data: [
0.08681,
-0.443261,
-0.150965,
0.689552,
-0.990562,
-0.756862,
0.341498,
0.651706,
-0.726587,
0.150187,
0.782644,
-0.581596,
-0.629344,
-0.783246,
-0.560605,
0.957248,
0.623366,
-0.656118,
0.632449,
-0.451853,
-0.136592,
0.88006,
0.635299,
-0.327776,
-0.649179,
-0.254336,
-0.988623,
-0.495147,
0.591325,
-0.96949,
0.197687,
0.207609,
-0.789705,
-0.236113,
-0.927048,
0.780823,
0.961842,
-0.880116,
0.781092,
0.153803,
0.484959,
0.260368,
0.163684,
-0.959122,
-0.579947,
0.08937,
0.53823,
-0.49861,
-0.428209,
0.70479,
0.950013,
0.769707,
-0.280984,
0.197718,
-0.290409,
-0.31962,
-0.643838,
-0.524612,
-0.910275,
0.010863,
-0.247495,
0.185611,
0.259884,
-0.714799,
0.867683,
0.89276,
0.204593,
-0.224467,
-0.273624,
-0.591309,
-0.44647,
-0.506928
]
},
{ shape: [4], data: [0.08681, -0.443261, -0.150965, 0.689552] }
]
},
'convolutional.Conv2D.8': {
input: {
shape: [5, 5, 2],
data: [
0.303535,
-0.150862,
0.313191,
-0.581677,
0.319849,
0.059247,
0.497041,
-0.812486,
0.569044,
0.374484,
0.390157,
-0.006267,
0.950722,
-0.592945,
-0.401959,
-0.544688,
-0.903662,
0.807943,
-0.839793,
0.214433,
0.261693,
-0.244116,
-0.973518,
0.684439,
-0.230125,
0.103332,
0.421076,
0.350558,
0.389129,
-0.315086,
-0.175219,
-0.520418,
0.937672,
-0.422886,
-0.705377,
-0.741319,
0.888112,
-0.297131,
0.467135,
0.827779,
0.401975,
-0.222937,
0.884519,
0.472983,
-0.523071,
0.647547,
0.521227,
-0.210582,
-0.599624,
0.425193
]
},
expected: { shape: [1, 1, 4], data: [-0.578839, 1.046696, 1.078234, 0.69352] },
weights: [
{
shape: [3, 3, 2, 4],
data: [
0.032797,
0.141335,
-0.943052,
-0.656957,
0.370554,
0.667794,
-0.386068,
0.787226,
0.443088,
-0.620122,
0.108455,
-0.295736,
-0.636215,
0.571204,
0.930966,
-0.535293,
-0.832877,
0.207097,
0.457986,
-0.447522,
0.370613,
0.035735,
-0.903031,
-0.724262,
-0.626065,
0.988636,
0.041331,
0.157579,
0.469638,
0.083924,
0.826307,
0.61584,
-0.194004,
-0.285551,
0.905753,
-0.312737,
0.7302,
0.660555,
0.076323,
0.844939,
-0.805707,
-0.794305,
0.403015,
0.78096,
-0.680879,
-0.448855,
0.344983,
-0.671394,
0.402742,
-0.02473,
0.361356,
0.043096,
-0.913207,
-0.552127,
0.15041,
-0.759133,
0.000233,
-0.723981,
-0.894383,
-0.643446,
-0.115264,
0.755175,
0.898528,
-0.043665,
-0.077761,
0.274578,
-0.350784,
-0.764844,
-0.897798,
0.275317,
0.624532,
0.340521
]
}
]
},
'convolutional.Conv2D.9': {
input: {
shape: [7, 7, 2],
data: [
0.157479,
0.618035,
-0.665503,
-0.37571,
-0.284137,
-0.016505,
-0.019604,
0.78882,
-0.635179,
-0.277676,
0.621183,
-0.333106,
0.037901,
-0.47676,
-0.738144,
-0.755166,
0.103315,
-0.941233,
0.20555,
0.501765,
-0.501859,
-0.604645,
0.147912,
0.803597,
0.032433,
-0.197603,
0.034979,
0.874782,
0.700816,
-0.648994,
0.039638,
0.011529,
-0.302879,
-0.858314,
0.151964,
-0.196575,
0.82283,
0.617771,
-0.735886,
0.429729,
-0.306674,
0.228823,
-0.425021,
0.971139,
-0.455574,
0.638783,
0.199032,
0.44091,
0.91975,
-0.814286,
-0.088979,
0.765096,
0.395408,
-0.357503,
-0.275416,
0.467275,
0.245085,
-0.563436,
0.96541,
-0.199388,
0.43292,
-0.389609,
0.298369,
-0.25199,
-0.266434,
-0.949491,
-0.303867,
-0.024641,
-0.221058,
-0.27166,
-0.014907,
-0.92768,
-0.54906,
-0.731149,
0.600323,
0.352064,
-0.730288,
0.065041,
0.53791,
-0.398966,
-0.180102,
-0.233353,
0.95265,
0.076114,
0.820989,
-0.637627,
-0.434933,
-0.836859,
-0.781756,
0.2022,
0.420213,
-0.359623,
0.460477,
0.643565,
-0.143274,
-0.63885,
-0.803257,
0.287415
]
},
expected: { shape: [1, 1, 4], data: [0.0, 2.241294, 0.0, 1.107507] },
weights: [
{
shape: [3, 3, 2, 4],
data: [
0.195363,
0.351974,
-0.401437,
0.461481,
0.157479,
0.618035,
-0.665503,
-0.37571,
-0.284137,
-0.016505,
-0.019604,
0.78882,
-0.635179,
-0.277676,
0.621183,
-0.333106,
0.037901,
-0.47676,
-0.738144,
-0.755166,
0.103315,
-0.941233,
0.20555,
0.501765,
-0.501859,
-0.604645,
0.147912,
0.803597,
0.032433,
-0.197603,
0.034979,
0.874782,
0.700816,
-0.648994,
0.039638,
0.011529,
-0.302879,
-0.858314,
0.151964,
-0.196575,
0.82283,
0.617771,
-0.735886,
0.429729,
-0.306674,
0.228823,
-0.425021,
0.971139,
-0.455574,
0.638783,
0.199032,
0.44091,
0.91975,
-0.814286,
-0.088979,
0.765096,
0.395408,
-0.357503,
-0.275416,
0.467275,
0.245085,
-0.563436,
0.96541,
-0.199388,
0.43292,
-0.389609,
0.298369,
-0.25199,
-0.266434,
-0.949491,
-0.303867,
-0.024641
]
},
{ shape: [4], data: [0.195363, 0.351974, -0.401437, 0.461481] }
]
},
'convolutional.Conv2D.10': {
input: {
shape: [4, 8, 3],
data: [
0.655264,
0.174343,
-0.081293,
0.64537,
0.643096,
-0.385759,
-0.598211,
-0.193535,
0.895779,
0.355089,
0.21795,
0.344727,
-0.984035,
-0.32688,
-0.285455,
-0.02788,
0.756565,
0.509817,
0.26093,
-0.247033,
0.180323,
0.474657,
0.192293,
-0.815041,
-0.195458,
0.179373,
-0.769174,
-0.223611,
-0.880477,
0.167916,
-0.666549,
-0.303809,
-0.156202,
-0.501052,
0.539906,
0.10262,
-0.947416,
0.541952,
-0.813565,
0.405592,
0.159078,
0.198436,
0.71454,
0.102339,
-0.835312,
0.466992,
0.067715,
-0.315822,
-0.056778,
-0.556856,
-0.647049,
-0.050928,
-0.277526,
0.64888,
-0.708,
0.639138,
-0.632262,
0.126027,
-0.751824,
0.387838,
-0.924068,
-0.411933,
0.793635,
-0.432359,
-0.568279,
-0.942986,
-0.929277,
0.746907,
0.954599,
-0.470971,
0.887461,
-0.919761,
-0.423457,
0.359481,
0.23833,
0.4367,
0.136035,
0.837921,
0.01252,
0.76166,
-0.067006,
-0.569453,
0.707085,
-0.685992,
-0.972653,
0.424172,
-0.023413,
-0.494544,
0.239537,
-0.357146,
-0.832116,
0.911805,
-0.493355,
0.799492,
0.907763,
0.590698
]
},
expected: {
shape: [4, 8, 3],
data: [
1.131317,
0.0,
0.0,
0.809904,
0.0,
0.0,
0.056086,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.251846,
0.0,
0.650556,
0.628197,
0.0,
0.0,
1.029379,
0.0,
2.939306,
0.23459,
0.0,
0.385831,
0.0,
0.0,
1.017464,
0.18825,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
2.247988,
0.083916,
0.0,
0.0,
0.202801,
0.0,
0.137876,
1.309465,
0.0,
0.0,
0.969843,
0.531891,
0.0,
0.0,
0.06576,
0.0,
0.0,
0.0,
0.0,
0.096874,
0.0,
1.147747,
0.0,
0.0,
0.155811,
0.0,
0.331866,
0.0,
0.319746,
0.0,
0.0,
0.0,
0.0,
1.384199,
0.0,
1.856335,
0.0,
1.686605,
0.0,
0.0,
0.0,
0.0,
0.0,
1.802758,
0.0,
0.0,
0.0,
0.102891,
0.0,
0.0,
1.089357,
0.617667,
0.0,
0.0,
0.543751
]
},
weights: [
{
shape: [4, 4, 3, 3],
data: [
-0.135778,
-0.651569,
-0.658113,
0.655264,
0.174343,
-0.081293,
0.64537,
0.643096,
-0.385759,
-0.598211,
-0.193535,
0.895779,
0.355089,
0.21795,
0.344727,
-0.984035,
-0.32688,
-0.285455,
-0.02788,
0.756565,
0.509817,
0.26093,
-0.247033,
0.180323,
0.474657,
0.192293,
-0.815041,
-0.195458,
0.179373,
-0.769174,
-0.223611,
-0.880477,
0.167916,
-0.666549,
-0.303809,
-0.156202,
-0.501052,
0.539906,
0.10262,
-0.947416,
0.541952,
-0.813565,
0.405592,
0.159078,
0.198436,
0.71454,
0.102339,
-0.835312,
0.466992,
0.067715,
-0.315822,
-0.056778,
-0.556856,
-0.647049,
-0.050928,
-0.277526,
0.64888,
-0.708,
0.639138,
-0.632262,
0.126027,
-0.751824,
0.387838,
-0.924068,
-0.411933,
0.793635,
-0.432359,
-0.568279,
-0.942986,
-0.929277,
0.746907,
0.954599,
-0.470971,
0.887461,
-0.919761,
-0.423457,
0.359481,
0.23833,
0.4367,
0.136035,
0.837921,
0.01252,
0.76166,
-0.067006,
-0.569453,
0.707085,
-0.685992,
-0.972653,
0.424172,
-0.023413,
-0.494544,
0.239537,
-0.357146,
-0.832116,
0.911805,
-0.493355,
0.799492,
0.907763,
0.590698,
-0.657319,
-0.899599,
0.66576,
-0.026552,
-0.808517,
0.761201,
0.060031,
0.911167,
-0.541875,
-0.052366,
-0.677874,
-0.540037,
0.858037,
0.841428,
0.664757,
0.159247,
-0.408513,
0.157763,
0.953228,
-0.419758,
0.13644,
0.857617,
0.935383,
-0.725736,
0.482768,
0.919937,
0.516163,
0.078243,
0.504286,
0.149417,
0.153285,
-0.686413,
-0.515197,
0.529735,
-0.671812,
0.737835,
0.760286,
-0.825563,
0.862511,
-0.185154,
0.436687,
-0.452091,
-0.048684,
0.142544,
0.590622
]
},
{ shape: [3], data: [-0.135778, -0.651569, -0.658113] }
]
},
'convolutional.Conv2D.11': {
input: {
shape: [8, 8, 2],
data: [
-0.628587,
0.544275,
-0.189121,
0.991809,
-0.028349,
0.30284,
0.201092,
-0.953154,
-0.343083,
0.640537,
-0.117391,
-0.526633,
-0.163892,
0.861458,
-0.665795,
0.51919,
-0.753596,
0.337708,
0.402785,
0.315812,
0.541968,
0.870102,
-0.141283,
-0.469735,
-0.574406,
-0.571765,
0.046045,
-0.790043,
-0.953079,
-0.774733,
-0.58544,
-0.882147,
0.282331,
0.214534,
0.862629,
-0.446078,
0.230215,
0.308982,
-0.361978,
-0.850926,
0.409799,
0.710712,
-0.391058,
-0.542441,
-0.41638,
0.558765,
-0.149949,
-0.864061,
-0.759997,
-0.265417,
-0.331629,
-0.845702,
0.426935,
-0.731659,
0.062865,
-0.255582,
0.396332,
0.639196,
-0.078254,
-0.253246,
0.792036,
0.044105,
0.879927,
-0.987868,
-0.35422,
0.924714,
0.304954,
-0.870234,
-0.611808,
0.138739,
0.526129,
-0.170329,
0.504868,
-0.454139,
0.245234,
0.479283,
0.651594,
-0.447885,
-0.78716,
-0.537367,
-0.578885,
-0.3999,
-0.981424,
0.584097,
-0.461375,
0.948907,
0.763872,
-0.720626,
-0.572361,
0.780094,
-0.385637,
0.90998,
-0.697513,
0.366373,
-0.427147,
0.423096,
-0.55829,
0.769474,
-0.484912,
-0.731131,
-0.794623,
0.19042,
0.537997,
-0.390004,
-0.697993,
-0.710914,
-0.222541,
-0.375822,
0.236956,
-0.978421,
-0.834872,
0.29127,
0.125375,
0.82053,
0.953645,
0.931806,
0.170904,
-0.474968,
-0.266042,
-0.021253,
0.449315,
0.266589,
0.405989,
0.663497,
0.762836,
-0.421562,
0.664906,
0.130767
]
},
expected: {
shape: [8, 8, 4],
data: [
1.008111,
0.862141,
1.53732,
0.0,
0.0,
0.0,
2.278924,
0.0,
0.192175,
0.256028,
1.00272,
0.0,
0.0,
0.0,
0.0,
1.28356,
0.0,
0.0,
1.295987,
0.0,
0.0,
0.0,
0.522589,
0.0,
0.0,
0.0,
1.593745,
0.0,
0.094799,
1.375385,
1.350499,
0.637961,
0.0,
0.393093,
1.508163,
1.045792,
0.0,
0.580916,
0.774659,
0.0,
0.0,
0.0,
1.090937,
0.2098,
0.0,
0.0,
0.706958,
0.948835,
0.0,
0.0,
0.70246,
1.233015,
0.0,
0.0,
0.0,
0.0,
0.0,
0.237716,
0.150121,
0.0,
0.012937,
1.067614,
0.259571,
0.895802,
0.0,
0.127769,
0.0,
0.0,
0.0,
0.0,
0.0,
0.517957,
0.0,
0.0,
0.524233,
0.079491,
0.0,
0.0,
0.0,
1.424679,
0.0,
0.0,
0.798433,
0.0,
0.752754,
0.49452,
0.564184,
1.320468,
0.0,
0.0,
1.469927,
0.075539,
0.0,
0.760117,
0.0,
0.961547,
0.938599,
1.264279,
0.857871,
0.0,
0.114331,
0.0,
0.753579,
0.0,
0.0,
0.0,
0.020539,
0.0,
0.0,
0.0,
1.035394,
0.0,
0.0,
0.0,
0.745973,
0.0,
0.0,
0.070491,
0.0,
0.0,
0.0,
0.0,
0.308166,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
1.911015,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.178493,
1.44698,
0.0,
0.0,
0.0,
1.45985,
0.298695,
0.0,
0.0,
0.0,
0.0,
0.0,
0.402046,
0.536043,
1.160239,
0.0,
0.0,
0.0,
0.0,
0.575623,
0.009206,
0.639194,
0.0,
0.353097,
0.0,
0.471996,
0.411527,
1.148312,
0.966958,
1.172197,
0.0,
0.419191,
0.0,
2.142206,
0.0,
0.0,
0.0,
0.0,
0.0,
0.508378,
0.0,
1.110668,
1.82902,
0.0,
0.0,
2.081267,
0.05382,
0.0,
0.0,
1.5163,
1.476838,
1.364327,
0.033732,
1.076706,
0.609169,
0.0,
0.149234,
2.181282,
0.780896,
0.0,
0.0,
0.763411,
0.0,
0.0,
0.0,
2.053607,
0.12022,
0.0,
0.0,
0.0,
0.29116,
0.0,
0.0,
0.656705,
0.0,
0.0,
0.0,
1.055828,
0.634612,
0.0,
0.0,
0.0,
0.363467,
1.779839,
0.0,
1.270641,
0.15881,
0.0,
0.020913,
0.854418,
0.0,
0.0,
0.0,
0.436751,
0.0,
0.0,
0.0,
0.0,
0.0,
0.436203,
0.236268,
0.0,
0.0,
0.0,
0.0,
0.189446,
0.0,
0.0,
0.0,
0.827813,
0.0,
0.0,
0.0,
0.31375,
0.0,
0.0,
0.0,
0.755046,
0.0
]
},
weights: [
{
shape: [3, 3, 2, 4],
data: [
-0.704159,
-0.543403,
0.614987,
-0.403051,
-0.628587,
0.544275,
-0.189121,
0.991809,
-0.028349,
0.30284,
0.201092,
-0.953154,
-0.343083,
0.640537,
-0.117391,
-0.526633,
-0.163892,
0.861458,
-0.665795,
0.51919,
-0.753596,
0.337708,
0.402785,
0.315812,
0.541968,
0.870102,
-0.141283,
-0.469735,
-0.574406,
-0.571765,
0.046045,
-0.790043,
-0.953079,
-0.774733,
-0.58544,
-0.882147,
0.282331,
0.214534,
0.862629,
-0.446078,
0.230215,
0.308982,
-0.361978,
-0.850926,
0.409799,
0.710712,
-0.391058,
-0.542441,
-0.41638,
0.558765,
-0.149949,
-0.864061,
-0.759997,
-0.265417,
-0.331629,
-0.845702,
0.426935,
-0.731659,
0.062865,
-0.255582,
0.396332,
0.639196,
-0.078254,
-0.253246,
0.792036,
0.044105,
0.879927,
-0.987868,
-0.35422,
0.924714,
0.304954,
-0.870234
]
},
{ shape: [4], data: [-0.704159, -0.543403, 0.614987, -0.403051] }
]
}
}
window.TEST_DATA = Object.assign({}, window.TEST_DATA, DATA)
})()
|
/*
* Binary Ajax 0.1.5
* Copyright (c) 2008 Jacob Seidelin, cupboy@gmail.com, http://blog.nihilogic.dk/
* MIT License [http://www.opensource.org/licenses/mit-license.php]
*
* Extended by António Afonso <antonio.afonso gmail.com>
*/
var BinaryFile = function(strData, iDataOffset, iDataLength) {
var data = strData;
var dataOffset = iDataOffset || 0;
var dataLength = 0;
this.getRawData = function() {
return data;
}
if (typeof strData == "string") {
dataLength = iDataLength || data.length;
this.getByteAt = function(iOffset) {
return data.charCodeAt(iOffset + dataOffset) & 0xFF;
}
} else if (typeof strData == "unknown") {
dataLength = iDataLength || IEBinary_getLength(data);
this.getByteAt = function(iOffset) {
return IEBinary_getByteAt(data, iOffset + dataOffset);
}
}
// @aadsm
this.getBytesAt = function(iOffset, iLength) {
var bytes = new Array(iLength);
for( var i = 0; i < iLength; i++ ) {
bytes[i] = this.getByteAt(iOffset+i);
}
return bytes;
}
this.getLength = function() {
return dataLength;
}
// @aadsm
this.isBitSetAt = function(iOffset, iBit) {
var iByte = this.getByteAt(iOffset);
return (iByte & (1 << iBit)) != 0;
}
this.getSByteAt = function(iOffset) {
var iByte = this.getByteAt(iOffset);
if (iByte > 127)
return iByte - 256;
else
return iByte;
}
this.getShortAt = function(iOffset, bBigEndian) {
var iShort = bBigEndian ?
(this.getByteAt(iOffset) << 8) + this.getByteAt(iOffset + 1)
: (this.getByteAt(iOffset + 1) << 8) + this.getByteAt(iOffset)
if (iShort < 0) iShort += 65536;
return iShort;
}
this.getSShortAt = function(iOffset, bBigEndian) {
var iUShort = this.getShortAt(iOffset, bBigEndian);
if (iUShort > 32767)
return iUShort - 65536;
else
return iUShort;
}
this.getLongAt = function(iOffset, bBigEndian) {
var iByte1 = this.getByteAt(iOffset),
iByte2 = this.getByteAt(iOffset + 1),
iByte3 = this.getByteAt(iOffset + 2),
iByte4 = this.getByteAt(iOffset + 3);
var iLong = bBigEndian ?
(((((iByte1 << 8) + iByte2) << 8) + iByte3) << 8) + iByte4
: (((((iByte4 << 8) + iByte3) << 8) + iByte2) << 8) + iByte1;
if (iLong < 0) iLong += 4294967296;
return iLong;
}
this.getSLongAt = function(iOffset, bBigEndian) {
var iULong = this.getLongAt(iOffset, bBigEndian);
if (iULong > 2147483647)
return iULong - 4294967296;
else
return iULong;
}
// @aadsm
this.getInteger24At = function(iOffset, bBigEndian) {
var iByte1 = this.getByteAt(iOffset),
iByte2 = this.getByteAt(iOffset + 1),
iByte3 = this.getByteAt(iOffset + 2);
var iInteger = bBigEndian ?
((((iByte1 << 8) + iByte2) << 8) + iByte3)
: ((((iByte3 << 8) + iByte2) << 8) + iByte1);
if (iInteger < 0) iInteger += 16777216;
return iInteger;
}
this.getStringAt = function(iOffset, iLength) {
var aStr = [];
for (var i=iOffset,j=0;i<iOffset+iLength;i++,j++) {
aStr[j] = String.fromCharCode(this.getByteAt(i));
}
return aStr.join("");
}
// @aadsm
this.getStringWithCharsetAt = function(iOffset, iLength, iCharset) {
var bytes = this.getBytesAt(iOffset, iLength);
var sString;
switch( iCharset.toLowerCase() ) {
case 'utf-16':
case 'utf-16le':
case 'utf-16be':
sString = StringUtils.readUTF16String(bytes, iCharset);
break;
case 'utf-8':
sString = StringUtils.readUTF8String(bytes);
break;
default:
sString = StringUtils.readNullTerminatedString(bytes);
break;
}
return sString;
}
this.getCharAt = function(iOffset) {
return String.fromCharCode(this.getByteAt(iOffset));
}
this.toBase64 = function() {
return window.btoa(data);
}
this.fromBase64 = function(strBase64) {
data = window.atob(strBase64);
}
}
var BinaryAjax = (function() {
function createRequest() {
var oHTTP = null;
if (window.XMLHttpRequest) {
oHTTP = new XMLHttpRequest();
} else if (window.ActiveXObject) {
oHTTP = new ActiveXObject("Microsoft.XMLHTTP");
}
return oHTTP;
}
function getHead(strURL, fncCallback, fncError) {
var oHTTP = createRequest();
if (oHTTP) {
if (fncCallback) {
if (typeof(oHTTP.onload) != "undefined") {
oHTTP.onload = function() {
if (oHTTP.status == "200") {
fncCallback(this);
} else {
if (fncError) fncError();
}
oHTTP = null;
};
} else {
oHTTP.onreadystatechange = function() {
if (oHTTP.readyState == 4) {
if (oHTTP.status == "200") {
fncCallback(this);
} else {
if (fncError) fncError();
}
oHTTP = null;
}
};
}
}
oHTTP.open("HEAD", strURL, true);
oHTTP.send(null);
} else {
if (fncError) fncError();
}
}
function sendRequest(strURL, fncCallback, fncError, aRange, bAcceptRanges, iFileSize) {
var oHTTP = createRequest();
if (oHTTP) {
var iDataOffset = 0;
if (aRange && !bAcceptRanges) {
iDataOffset = aRange[0];
}
var iDataLen = 0;
if (aRange) {
iDataLen = aRange[1]-aRange[0]+1;
}
if (fncCallback) {
if (typeof(oHTTP.onload) != "undefined") {
oHTTP.onload = function() {
if (oHTTP.status == "200" || oHTTP.status == "206") {
this.binaryResponse = new BinaryFile(this.responseText, iDataOffset, iDataLen);
this.fileSize = iFileSize || this.getResponseHeader("Content-Length");
fncCallback(this);
} else {
if (fncError) fncError();
}
oHTTP = null;
};
} else {
oHTTP.onreadystatechange = function() {
if (oHTTP.readyState == 4) {
if (oHTTP.status == "200" || oHTTP.status == "206") {
this.binaryResponse = new BinaryFile(oHTTP.responseBody, iDataOffset, iDataLen);
this.fileSize = iFileSize || this.getResponseHeader("Content-Length");
fncCallback(this);
} else {
if (fncError) fncError();
}
oHTTP = null;
}
};
}
}
oHTTP.open("GET", strURL, true);
if (oHTTP.overrideMimeType) oHTTP.overrideMimeType('text/plain; charset=x-user-defined');
if (aRange && bAcceptRanges) {
oHTTP.setRequestHeader("Range", "bytes=" + aRange[0] + "-" + aRange[1]);
}
oHTTP.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 1970 00:00:00 GMT");
oHTTP.send(null);
} else {
if (fncError) fncError();
}
}
return function(strURL, fncCallback, fncError, aRange) {
if (aRange) {
getHead(
strURL,
function(oHTTP) {
var iLength = parseInt(oHTTP.getResponseHeader("Content-Length"),10) || -1;
var strAcceptRanges = oHTTP.getResponseHeader("Accept-Ranges");
var iStart, iEnd;
iStart = aRange[0];
if (aRange[0] < 0 )
iStart += iLength;
iEnd = iStart + aRange[1] - 1;
if( iStart >= 0 ) {
sendRequest(strURL, fncCallback, fncError, [iStart, iEnd], (strAcceptRanges == "bytes"), iLength);
} else {
sendRequest(strURL, fncCallback, fncError);
}
}
);
} else {
sendRequest(strURL, fncCallback, fncError);
}
}
}());
document.write(
"<script type='text/vbscript'>\r\n"
+ "Function IEBinary_getByteAt(strBinary, iOffset)\r\n"
+ " IEBinary_getByteAt = AscB(MidB(strBinary,iOffset+1,1))\r\n"
+ "End Function\r\n"
+ "Function IEBinary_getLength(strBinary)\r\n"
+ " IEBinary_getLength = LenB(strBinary)\r\n"
+ "End Function\r\n"
+ "</script>\r\n"
);
|
context('Runtime state saving', function () {
let materialUrl
beforeEach(() => {
cy.login()
cy.importMaterial("sequences/simple-sequence.json").then(url =>
materialUrl = url
)
})
afterEach(() => {
cy.deleteMaterial(materialUrl)
})
it('marks activity as completed once user responds to all the questions', () => {
cy.visit(materialUrl)
cy.get(".activities .activity-bg .banner").should("not.exist")
cy.get(".activities .activity").first().click()
cy.get("[value='Begin activity']").click()
cy.get("[name='embeddable_open_response_answer[answer_text]']").type("test answer").blur()
cy.wait(300)
cy.get(".sequence_title").click()
cy.get(".activities .activity-bg .banner .text").should("have.text", "Completed")
})
})
|
'use strict';
var Printer = require('../');
console.log(String.fromCharCode('0x2a'));
|
var path = require("path");
var fs = require("fs");
var _ = require("lodash");
var mkdirp = require("mkdirp");
var config = require("node-prefix");
var nodePrefix = config.prefix();
var globalModulePath = config.global("genesis");
module.exports = function (html, options) {
var size = options.size;
var height = "1189mm";
var width = "841mm";
if (size === "A1" || size === "a1") {
height = "841mm";
width = "594mm";
} else if (size === "A2" || size === "a2") {
height = "594mm";
width = "420mm";
} else if (size === "A3" || size === "a3") {
height = "420mm";
width = "297mm";
} else if (size === "A4" || size === "a4") {
height = "297mm";
width = "210mm";
}
if (options.direction === 'lateral') {
var tmp = height;
height = width;
width = tmp;
}
var templatePath = globalModulePath + "/template";
var poster = _.template(fs.readFileSync(templatePath + "/default.html").toString());
poster = poster({
"yield": html,
"height": height,
"width": width
});
var res = {};
res.poster = poster;
return res;
}
|
function ITER$0(v,f){if(v){if(Array.isArray(v))return f?v.slice():v;if(typeof v==='object'&&typeof v['iterator']==='function')return Array['from'](v);}throw new Error(v+' is not iterable')};function GET_ITER$0(v){if(v){if(Array.isArray(v))return 0;if(typeof v==='object'&&typeof v['iterator']==='function')return v['iterator']();}throw new Error(v+' is not iterable')};var $D$0;var $D$1;var $D$2;var $D$3;
{
var test;
}
{// destructuring & function expression
var output = [];
var test$0;$D$3 = (( function(x) {return [{test: x + 1}, {test: x + 2}, {test: x + 3}]})(2));$D$0 = GET_ITER$0($D$3);$D$1 = $D$0 === 0;$D$2 = ($D$1 ? $D$3.length : void 0);for( ; $D$1 ? ($D$0 < $D$2) : !($D$2 = $D$0["next"]())["done"]; ){;test$0 = ($D$1 ? $D$3[$D$0++] : $D$2["value"]).test;
output.push(test$0)
};$D$0 = $D$1 = $D$2 = $D$3 = void 0;
console.log(output.join("|") === [3, 4, 5].join("|"))
}
{
var a, b, c;
}
{// function expression & shorthand property & destructuring & spread
function retArr(a, b, c){return [
{test: a + 1, a: a} //{test: 3, a: 2}
, {test: b + 2, b: b} //{test: 3, b: 1}
, {test: c + 3, c: c} //{test: 3, c: 0}
]}
var output$0 = [];
var arr = [].concat([2], [1, 0])
var test$1, a$0, b$0, c$0;$D$3 = (retArr.apply(null, ITER$0(arr)));$D$0 = GET_ITER$0($D$3);$D$1 = $D$0 === 0;$D$2 = ($D$1 ? $D$3.length : void 0);for( ; $D$1 ? ($D$0 < $D$2) : !($D$2 = $D$0["next"]())["done"]; ){;test$1 = (c$0 = ($D$1 ? $D$3[$D$0++] : $D$2["value"])).test, a$0 = ((a$0 = c$0.a) === void 0 ? 1 : a$0), b$0 = ((b$0 = c$0.b) === void 0 ? 2 : b$0), c$0 = ((c$0 = c$0.c) === void 0 ? 3 : c$0);
output$0.push(test$1 + (a$0 + b$0 + c$0))
};$D$0 = $D$1 = $D$2 = $D$3 = void 0;
console.log(output$0.join("|") === [10, 8, 6].join("|"))
{
var output$1 = [];
var arr$0 = [].concat([2], [1, 0]);
var test$2, a$1, b$1, c$1;$D$3 = ((function(a, b, c) {return [
{test: a + 1, a: a} //{test: 3, a: 2}
, {test: b + 2, b: b} //{test: 3, b: 1}
, {test: c + 3, c: c} //{test: 3, c: 0}
]}).apply(null, ITER$0(arr$0)));$D$0 = GET_ITER$0($D$3);$D$1 = $D$0 === 0;$D$2 = ($D$1 ? $D$3.length : void 0);for( ; $D$1 ? ($D$0 < $D$2) : !($D$2 = $D$0["next"]())["done"]; ){;test$2 = (c$1 = ($D$1 ? $D$3[$D$0++] : $D$2["value"])).test, a$1 = ((a$1 = c$1.a) === void 0 ? 1 : a$1), b$1 = ((b$1 = c$1.b) === void 0 ? 2 : b$1), c$1 = ((c$1 = c$1.c) === void 0 ? 3 : c$1);
output$1.push(test$2 + (a$1 + b$1 + c$1))
};$D$0 = $D$1 = $D$2 = $D$3 = void 0;
console.log(output$1.join("|") === [10, 8, 6].join("|"))
}
}
{
var a$2, b$2, c$2;
}
//TODO::
//{// destructuring & arrow function
// let output = [];let arr = [8, 9];
// for(let [value, index] of ( arr.push(10), arr.map((value, index)=>[value, index]) ) ) {
// output.push(value)
// }
// console.log(output.join("|") === [8, 9, 10].join("|"))
//}
//
//{// destructuring & arrow function & rest
// let output = [];let arr = [8, 9];
// for(let [value, index] of ( arr.push(10), arr.map((...r)=>r) ) ) {
// output.push(value)
// }
// console.log(output.join("|") === [8, 9, 10].join("|"))
//}
|
'use strict';
const path = require('path');
const fastText = require('fasttext');
module.exports = fastText.Classifier;
|
// Preferences, stored in chrome.storage
var M = module.exports = {};
var keyboard = require('./keyboard'),
number = require('./number'),
util = require('./util');
var firstMod = keyboard.modifiers.ALT,
secondMod = keyboard.mac ? keyboard.modifiers.META : keyboard.modifiers.CTRL;
var defaults = {
'modifier.cell': firstMod,
'modifier.column': firstMod | secondMod,
'modifier.row': 0,
'modifier.table': 0,
'modifier.extend': keyboard.modifiers.SHIFT,
'capture.enabled': true,
'capture.reset': false,
'scroll.amount': 30,
'scroll.acceleration': 5,
'copy.format.enabled.richHTML': true,
'copy.format.enabled.richHTMLCSS': true,
'copy.format.enabled.textCSV': true,
'copy.format.enabled.textCSVSwap': true,
'copy.format.enabled.textHTML': true,
'copy.format.enabled.textHTMLCSS': true,
'copy.format.enabled.textTabs': true,
'copy.format.enabled.textTabsSwap': true,
'copy.format.enabled.textTextile': true,
'copy.format.default.richHTMLCSS': true,
'infobox.enabled': true,
'infobox.position': '0'
};
var captureModes = [
{
id: 'zzz',
name: 'Off'
},
{
id: 'cell',
name: 'Cells'
},
{
id: 'column',
name: 'Columns'
},
{
id: 'row',
name: 'Rows'
},
{
id: 'table',
name: 'Tables'
}
];
var copyFormats = [
{
"id": "richHTMLCSS",
"name": "As is",
"desc": "Copy the table as seen on the screen"
},
{
"id": "richHTML",
"name": "Plain Table",
"desc": "Copy the table without formatting"
},
{
"id": "textTabs",
"name": "Text",
"desc": "Copy as tab-delimited text"
},
{
"id": "textTabsSwap",
"name": "Text+Swap",
"desc": "Copy as tab-delimited text, swap columns and rows"
},
{
"id": "textCSV",
"name": "CSV",
"desc": "Copy as comma-separated text"
},
{
"id": "textCSVSwap",
"name": "CSV+Swap",
"desc": "Copy as comma-separated text, swap columns and rows"
},
{
"id": "textHTMLCSS",
"name": "HTML+CSS",
"desc": "Copy as HTML source, retain formatting"
},
{
"id": "textHTML",
"name": "HTML",
"desc": "Copy as HTML source, without formatting"
},
{
"id": "textTextile",
"name": "Textile",
"desc": "Copy as Textile (Text content)"
},
{
"id": "textTextileHTML",
"name": "Textile+HTML",
"desc": "Copy as Textile (HTML content)"
},
];
function sum(vs) {
return vs.reduce(function (x, y) {
return x + (Number(y) || 0)
}, 0);
}
function getNumbers(values) {
var vs = [];
values.forEach(function (v) {
if (v.isNumber)
vs.push(v.number);
});
return vs.length ? vs : null;
}
var infoFunctions = [
{
name: 'count',
fn: function (values) {
return values.length;
}
},
{
name: 'sum',
fn: function (values) {
var vs = getNumbers(values);
return vs ? number.format(sum(vs)) : null;
}
},
{
name: 'average',
fn: function (values) {
var vs = getNumbers(values);
return vs ? number.format(sum(vs) / vs.length, 2) : null;
}
},
{
name: 'min',
fn: function (values) {
var vs = getNumbers(values);
return vs ? number.format(Math.min.apply(Math, vs)) : null;
}
},
{
name: 'max',
fn: function (values) {
var vs = getNumbers(values);
return vs ? number.format(Math.max.apply(Math, vs)) : null;
}
}
];
var prefs = {};
function _constrain(min, val, max) {
val = Number(val) || min;
return Math.max(min, Math.min(val, max));
}
M.load = function () {
return util.callChromeAsync('storage.local.get', null)
.then(function (obj) {
obj = obj || {};
// from the previous version
if ('modKey' in obj && String(obj.modKey) === '1') {
console.log('FOUND ALTERNATE MODKEY SETTING');
obj['modifier.cell'] = secondMod;
delete obj.modKey;
}
prefs = Object.assign({}, defaults, prefs, obj);
prefs['scroll.amount'] = _constrain(1, prefs['scroll.amount'], 100);
prefs['scroll.acceleration'] = _constrain(0, prefs['scroll.acceleration'], 100);
if (!prefs['number.group']) {
prefs['number.group'] = number.defaultFormat().group;
}
if (!prefs['number.decimal']) {
prefs['number.decimal'] = number.defaultFormat().decimal;
}
console.log('PREFS LOAD', prefs);
return prefs;
});
};
M.save = function () {
return util.callChromeAsync('storage.local.clear')
.then(function () {
return util.callChromeAsync('storage.local.set', prefs);
}).then(function () {
console.log('PREFS SET', prefs);
return prefs;
});
};
M.setAll = function (obj) {
prefs = Object.assign({}, prefs, obj);
return M.save();
};
M.set = function (key, val) {
prefs[key] = val;
return M.save();
};
M.val = function (key) {
return prefs[key];
};
M.int = function (key) {
return Number(M.val(key)) || 0;
};
M.copyFormats = function () {
return copyFormats.map(function (f) {
f.enabled = !!M.val('copy.format.enabled.' + f.id);
f.default = !!M.val('copy.format.default.' + f.id);
return f;
});
};
M.numberFormat = function () {
var g = M.val('number.group');
var d = M.val('number.decimal');
if (!g && !d) {
return number.defaultFormat();
}
return {
group: g || '',
decimal: d || '',
};
}
M.infoFunctions = function () {
return infoFunctions;
};
M.captureModes = function () {
return captureModes;
};
|
var webpack = require('webpack');
var banner = require('./banner');
module.exports = {
output: {
library: 'ReactVimeo',
libraryTarget: 'umd'
},
externals: [
{
'react': {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react'
}
}
],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader'
}
]
},
node: {
Buffer: false
},
resolve: {
extensions: [
'',
'.js',
'.jsx'
]
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}),
new webpack.BannerPlugin(banner, { raw: true, entryOnly: true })
]
};
|
import TestStats from '../src/stats/test'
describe('TestStats', () => {
let stat
beforeAll(() => {
stat = new TestStats({ type: 'test:start',
title: 'should can do something',
parent: 'My awesome feature',
fullTitle: 'My awesome feature should can do something',
pending: false,
cid: '0-0',
specs: [ '/path/to/test/specs/sync.spec.js' ],
uid: 'should can do something3'
})
stat.complete = jest.fn()
})
it('should be initialised with correct values', () => {
expect(stat.type).toBe('test')
expect(stat.cid).toBe('0-0')
expect(stat.uid).toBe('should can do something3')
expect(stat.state).toBe('pending')
})
it('can get skipped', () => {
stat.skip()
expect(stat.state).toBe('skipped')
expect(stat.complete.mock.calls).toHaveLength(0)
})
it('can pass', () => {
stat.pass()
expect(stat.state).toBe('passed')
expect(stat.complete.mock.calls).toHaveLength(1)
stat.complete.mockReset()
})
it('can fail', () => {
stat.fail(new Error('oh oh'))
expect(stat.state).toBe('failed')
expect(stat.error.message).toBe('oh oh')
expect(stat.complete.mock.calls).toHaveLength(1)
stat.complete.mockReset()
})
})
|
/**
* @fileoverview Used for creating a suggested configuration based on project code.
* @author Ian VanSchooten
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const lodash = require("lodash"),
recConfig = require("../../conf/eslint-recommended"),
ConfigOps = require("../shared/config-ops"),
{ Linter } = require("../linter"),
configRule = require("./config-rule");
const debug = require("debug")("eslint:autoconfig");
const linter = new Linter();
//------------------------------------------------------------------------------
// Data
//------------------------------------------------------------------------------
const MAX_CONFIG_COMBINATIONS = 17, // 16 combinations + 1 for severity only
RECOMMENDED_CONFIG_NAME = "eslint:recommended";
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
/**
* Information about a rule configuration, in the context of a Registry.
* @typedef {Object} registryItem
* @param {ruleConfig} config A valid configuration for the rule
* @param {number} specificity The number of elements in the ruleConfig array
* @param {number} errorCount The number of errors encountered when linting with the config
*/
/**
* This callback is used to measure execution status in a progress bar
* @callback progressCallback
* @param {number} The total number of times the callback will be called.
*/
/**
* Create registryItems for rules
* @param {rulesConfig} rulesConfig Hash of rule names and arrays of ruleConfig items
* @returns {Object} registryItems for each rule in provided rulesConfig
*/
function makeRegistryItems(rulesConfig) {
return Object.keys(rulesConfig).reduce((accumulator, ruleId) => {
accumulator[ruleId] = rulesConfig[ruleId].map(config => ({
config,
specificity: config.length || 1,
errorCount: void 0
}));
return accumulator;
}, {});
}
/**
* Creates an object in which to store rule configs and error counts
*
* Unless a rulesConfig is provided at construction, the registry will not contain
* any rules, only methods. This will be useful for building up registries manually.
*
* Registry class
*/
class Registry {
// eslint-disable-next-line jsdoc/require-description
/**
* @param {rulesConfig} [rulesConfig] Hash of rule names and arrays of possible configurations
*/
constructor(rulesConfig) {
this.rules = (rulesConfig) ? makeRegistryItems(rulesConfig) : {};
}
/**
* Populate the registry with core rule configs.
*
* It will set the registry's `rule` property to an object having rule names
* as keys and an array of registryItems as values.
* @returns {void}
*/
populateFromCoreRules() {
const rulesConfig = configRule.createCoreRuleConfigs();
this.rules = makeRegistryItems(rulesConfig);
}
/**
* Creates sets of rule configurations which can be used for linting
* and initializes registry errors to zero for those configurations (side effect).
*
* This combines as many rules together as possible, such that the first sets
* in the array will have the highest number of rules configured, and later sets
* will have fewer and fewer, as not all rules have the same number of possible
* configurations.
*
* The length of the returned array will be <= MAX_CONFIG_COMBINATIONS.
* @returns {Object[]} "rules" configurations to use for linting
*/
buildRuleSets() {
let idx = 0;
const ruleIds = Object.keys(this.rules),
ruleSets = [];
/**
* Add a rule configuration from the registry to the ruleSets
*
* This is broken out into its own function so that it doesn't need to be
* created inside of the while loop.
* @param {string} rule The ruleId to add.
* @returns {void}
*/
const addRuleToRuleSet = function(rule) {
/*
* This check ensures that there is a rule configuration and that
* it has fewer than the max combinations allowed.
* If it has too many configs, we will only use the most basic of
* the possible configurations.
*/
const hasFewCombos = (this.rules[rule].length <= MAX_CONFIG_COMBINATIONS);
if (this.rules[rule][idx] && (hasFewCombos || this.rules[rule][idx].specificity <= 2)) {
/*
* If the rule has too many possible combinations, only take
* simple ones, avoiding objects.
*/
if (!hasFewCombos && typeof this.rules[rule][idx].config[1] === "object") {
return;
}
ruleSets[idx] = ruleSets[idx] || {};
ruleSets[idx][rule] = this.rules[rule][idx].config;
/*
* Initialize errorCount to zero, since this is a config which
* will be linted.
*/
this.rules[rule][idx].errorCount = 0;
}
}.bind(this);
while (ruleSets.length === idx) {
ruleIds.forEach(addRuleToRuleSet);
idx += 1;
}
return ruleSets;
}
/**
* Remove all items from the registry with a non-zero number of errors
*
* Note: this also removes rule configurations which were not linted
* (meaning, they have an undefined errorCount).
* @returns {void}
*/
stripFailingConfigs() {
const ruleIds = Object.keys(this.rules),
newRegistry = new Registry();
newRegistry.rules = Object.assign({}, this.rules);
ruleIds.forEach(ruleId => {
const errorFreeItems = newRegistry.rules[ruleId].filter(registryItem => (registryItem.errorCount === 0));
if (errorFreeItems.length > 0) {
newRegistry.rules[ruleId] = errorFreeItems;
} else {
delete newRegistry.rules[ruleId];
}
});
return newRegistry;
}
/**
* Removes rule configurations which were not included in a ruleSet
* @returns {void}
*/
stripExtraConfigs() {
const ruleIds = Object.keys(this.rules),
newRegistry = new Registry();
newRegistry.rules = Object.assign({}, this.rules);
ruleIds.forEach(ruleId => {
newRegistry.rules[ruleId] = newRegistry.rules[ruleId].filter(registryItem => (typeof registryItem.errorCount !== "undefined"));
});
return newRegistry;
}
/**
* Creates a registry of rules which had no error-free configs.
* The new registry is intended to be analyzed to determine whether its rules
* should be disabled or set to warning.
* @returns {Registry} A registry of failing rules.
*/
getFailingRulesRegistry() {
const ruleIds = Object.keys(this.rules),
failingRegistry = new Registry();
ruleIds.forEach(ruleId => {
const failingConfigs = this.rules[ruleId].filter(registryItem => (registryItem.errorCount > 0));
if (failingConfigs && failingConfigs.length === this.rules[ruleId].length) {
failingRegistry.rules[ruleId] = failingConfigs;
}
});
return failingRegistry;
}
/**
* Create an eslint config for any rules which only have one configuration
* in the registry.
* @returns {Object} An eslint config with rules section populated
*/
createConfig() {
const ruleIds = Object.keys(this.rules),
config = { rules: {} };
ruleIds.forEach(ruleId => {
if (this.rules[ruleId].length === 1) {
config.rules[ruleId] = this.rules[ruleId][0].config;
}
});
return config;
}
/**
* Return a cloned registry containing only configs with a desired specificity
* @param {number} specificity Only keep configs with this specificity
* @returns {Registry} A registry of rules
*/
filterBySpecificity(specificity) {
const ruleIds = Object.keys(this.rules),
newRegistry = new Registry();
newRegistry.rules = Object.assign({}, this.rules);
ruleIds.forEach(ruleId => {
newRegistry.rules[ruleId] = this.rules[ruleId].filter(registryItem => (registryItem.specificity === specificity));
});
return newRegistry;
}
/**
* Lint SourceCodes against all configurations in the registry, and record results
* @param {Object[]} sourceCodes SourceCode objects for each filename
* @param {Object} config ESLint config object
* @param {progressCallback} [cb] Optional callback for reporting execution status
* @returns {Registry} New registry with errorCount populated
*/
lintSourceCode(sourceCodes, config, cb) {
let lintedRegistry = new Registry();
lintedRegistry.rules = Object.assign({}, this.rules);
const ruleSets = lintedRegistry.buildRuleSets();
lintedRegistry = lintedRegistry.stripExtraConfigs();
debug("Linting with all possible rule combinations");
const filenames = Object.keys(sourceCodes);
const totalFilesLinting = filenames.length * ruleSets.length;
filenames.forEach(filename => {
debug(`Linting file: ${filename}`);
let ruleSetIdx = 0;
ruleSets.forEach(ruleSet => {
const lintConfig = Object.assign({}, config, { rules: ruleSet });
const lintResults = linter.verify(sourceCodes[filename], lintConfig);
lintResults.forEach(result => {
/*
* It is possible that the error is from a configuration comment
* in a linted file, in which case there may not be a config
* set in this ruleSetIdx.
* (https://github.com/eslint/eslint/issues/5992)
* (https://github.com/eslint/eslint/issues/7860)
*/
if (
lintedRegistry.rules[result.ruleId] &&
lintedRegistry.rules[result.ruleId][ruleSetIdx]
) {
lintedRegistry.rules[result.ruleId][ruleSetIdx].errorCount += 1;
}
});
ruleSetIdx += 1;
if (cb) {
cb(totalFilesLinting); // eslint-disable-line node/callback-return
}
});
// Deallocate for GC
sourceCodes[filename] = null;
});
return lintedRegistry;
}
}
/**
* Extract rule configuration into eslint:recommended where possible.
*
* This will return a new config with `["extends": [ ..., "eslint:recommended"]` and
* only the rules which have configurations different from the recommended config.
* @param {Object} config config object
* @returns {Object} config object using `"extends": ["eslint:recommended"]`
*/
function extendFromRecommended(config) {
const newConfig = Object.assign({}, config);
ConfigOps.normalizeToStrings(newConfig);
const recRules = Object.keys(recConfig.rules).filter(ruleId => ConfigOps.isErrorSeverity(recConfig.rules[ruleId]));
recRules.forEach(ruleId => {
if (lodash.isEqual(recConfig.rules[ruleId], newConfig.rules[ruleId])) {
delete newConfig.rules[ruleId];
}
});
newConfig.extends.unshift(RECOMMENDED_CONFIG_NAME);
return newConfig;
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = {
Registry,
extendFromRecommended
};
|
//~ name c102
alert(c102);
//~ component c103.js
|
/**
* HTTP Server Settings
* (sails.config.http)
*
* Configuration for the underlying HTTP server in Sails.
* Only applies to HTTP requests (not WebSockets)
*
* For more information on configuration, check out:
* http://sailsjs.org/#/documentation/reference/sails.config/sails.config.http.html
*/
module.exports.http = {
/****************************************************************************
* *
* Express middleware to use for every Sails request. To add custom *
* middleware to the mix, add a function to the middleware config object and *
* add its key to the "order" array. The $custom key is reserved for *
* backwards-compatibility with Sails v0.9.x apps that use the *
* `customMiddleware` config option. *
* *
****************************************************************************/
// middleware: {
/***************************************************************************
* *
* The order in which middleware should be run for HTTP request. (the Sails *
* router is invoked by the "router" middleware below.) *
* *
***************************************************************************/
// order: [
// 'startRequestTimer',
// 'cookieParser',
// 'session',
// 'myRequestLogger',
// 'bodyParser',
// 'handleBodyParserError',
// 'compress',
// 'methodOverride',
// 'poweredBy',
// '$custom',
// 'router',
// 'www',
// 'favicon',
// '404',
// '500'
// ],
/****************************************************************************
* *
* Example custom middleware; logs each request to the console. *
* *
****************************************************************************/
myRequestLogger: function (req, res, next) {
console.log("Requested :: ", req.method, req.url);
return next();
},
/***************************************************************************
* *
* The body parser that will handle incoming multipart HTTP requests. By *
* default as of v0.10, Sails uses *
* [skipper](http://github.com/balderdashy/skipper). See *
* http://www.senchalabs.org/connect/multipart.html for other options. *
* *
***************************************************************************/
bodyParser: require('formidable')
// },
/***************************************************************************
* *
* The number of seconds to cache flat files on disk being served by *
* Express static middleware (by default, these files are in `.tmp/public`) *
* *
* The HTTP static cache is only active in a 'production' environment, *
* since that's the only time Express will cache flat-files. *
* *
***************************************************************************/
// cache: 31557600000
};
|
/**
* THIS FILE IS AUTO-GENERATED
* DON'T MAKE CHANGES HERE
*/
import { createFalse } from '../../factoriesNumber.js';
export var falseDependencies = {
createFalse: createFalse
};
|
const STATES = {
SUCCESS: 1,
WARNING: 0,
FAIL: 2,
UNAUTHENTICATED: 4001,
INTERNAL_ERR: 500,
}
module.exports = {
SUCCESS: (_data) => { return { type: STATES.SUCCESS, data: _data } },
FAIL: (_data) => { return { type: STATES.FAIL, data: _data } },
WARNING: (_data) => { return { type: STATES.WARNING, data: _data } },
UNAUTHENTICATED: (_data) => { return { type: STATES.UNAUTHENTICATED, data: _data } },
INTERNAL_ERR: (_data) => { return { type: STATES.INTERNAL_ERR, data: _data } },
}
|
#!/usr/bin/env node
var simpleget = require('simple-get')
var map = require('tar-map-stream')
var tar = require('tar-fs')
var zlib = require('zlib')
var fs = require('fs')
var path = require('path')
var pump = require('pump')
var after = require('after-all')
var multi = require('multi-write-stream')
var semver = require('semver')
module.exports = install
function _get (url, callback) {
return simpleget({
url: url,
headers: {
'accept-encoding': ''
}
}, callback)
}
function install (opts, cb) {
if (typeof opts === 'function') return install(null, opts)
if (!opts) opts = {}
if (!cb) cb = noop
var log = opts.log
var version = opts.version || process.version
if (version[0] !== 'v') version = 'v' + version
var nightly = opts.nightly !== undefined ? opts.nightly : version.indexOf('nightly') > -1
var io = opts.iojs !== undefined ? opts.iojs : iojsVersion(version)
var platform = opts.platform || process.platform
var defaultIojsUrl = nightly ? 'https://iojs.org/download/nightly/' : 'https://iojs.org/dist/'
var iojsDistUrl = pad(process.env.NVM_IOJS_ORG_MIRROR || defaultIojsUrl)
var nodeDistUrl = pad(process.env.NVM_NODEJS_ORG_MIRROR || 'https://nodejs.org/dist/')
var url = io ?
iojsDistUrl + version + '/iojs-' + version + '.tar.gz' :
nodeDistUrl + version + '/node-' + version + '.tar.gz'
var target = path.join(process.env.HOME || process.env.USERPROFILE, '.node-gyp', version.slice(1))
exists(function (err) {
if (!err && !opts.force) {
if (log) log.info('install', 'Header files already fetched')
if (log) log.info('install', 'node-gyp should now work for ' + version)
return cb(null)
}
if (log) log.http('request', url)
_get(url, function (err, res) {
if (err) return cb(err)
if (log) log.http(res.statusCode, url)
pump(res, zlib.createGunzip(), map(mapEntry), tar.extract(target, {strip: 1}), function (err) {
if (err) return cb(err)
fetchWindows(function (err) {
if (err) return cb(err)
fs.writeFile(path.join(target, 'installVersion'), '9', function (err) {
if (err) return cb(err)
if (log) log.info('install', 'node-gyp should now work for ' + version)
cb()
})
})
})
})
})
function exists (cb) {
fs.exists(path.join(target, 'installVersion'), function (exists) {
if (!exists) return cb(new Error('missing installVersion'))
fs.exists(path.join(target, 'common.gypi'), function (exists) {
cb(exists ? null : new Error('missing common.gypi'))
})
})
}
function mapEntry (entry) {
return /(\.gypi$)|(\.h$)/.test(entry.name) ? entry : null
}
function fetchWindows (cb) {
if (platform !== 'win32') return cb()
var urls
if (io) {
urls = [
iojsDistUrl + version + '/win-x86/iojs.lib',
iojsDistUrl + version + '/win-x64/iojs.lib'
]
} else if (semver.satisfies(version, '>=4.0.0')) {
urls = [
nodeDistUrl + version + '/win-x86/node.lib',
nodeDistUrl + version + '/win-x64/node.lib'
]
} else {
urls = [
nodeDistUrl + version + '/node.lib',
nodeDistUrl + version + '/x64/node.lib'
]
}
var next = after(cb)
urls.forEach(function (url, index) {
var arch = index === 0 ? 'ia32' : 'x64'
var nodeLib = path.join(target, arch, 'node.lib')
var ioLib = path.join(target, arch, 'iojs.lib')
var parentDir = path.dirname(nodeLib)
var done = next()
if (log) log.http('request', url)
fs.mkdir(parentDir, function () {
_get(url, function (err, res) {
if (err) return done(err)
log.http(res.statusCode, url)
pump(res, multi([fs.createWriteStream(nodeLib), fs.createWriteStream(ioLib)]), done)
})
})
})
}
}
function iojsVersion (v) {
return semver.satisfies(v, '>=1.0.0 <4.0.0')
}
function pad (url) {
return url[url.length - 1] === '/' ? url : url + '/'
}
function noop () {}
|
'use strict'
var points = [ [1, 0, 0], [0, 1, 0] ]
var copoints = require('../acomp')(3, points)
console.log(copoints)
|
// helpers
var _ = require('lodash');
var log = require('../../core/log.js');
// let's create our own method
var method = {};
method.init = function() {
this.age = 0;
this.currentTrend;
this.requiredHistory = 16;
this.persistence=0;
//ADD_INDICATORS;
this.addindicator('inda', '..INDA..', this.settings['..INDA..'])
}
// what happens on every new candle?
method.update = function(candle) {
}
method.log = function() {
}
method.validation = function(ConditionList)
{
var validNB = ConditionList.filter(function(s) { return s; }).length;
return validNB/ ConditionList.length;
}
method.checkPersistence = function(candidateAdvice)
{
if (this.persistence >= this.settings.persistence)
this.advice(candidateAdvice);
else
this.advice();
}
method.check = function(candle) {
var price = candle.close;
//SIMPLIFY_INDICATORS;
//BUYCONDITIONS;
//SELLCONDITIONS;
this.age++;
if (this.validation(BuyConditions) > 0.6)
{
if(this.currentTrend !== 'up') {
this.currentTrend = 'up';
this.advice();
this.persistence=0;
} else{
this.persistence++;
this.checkPersistence('long');
}
}
else if (this.validation(SellConditions) > 0.6)
{
if (this.currentTrend !== 'down') {
this.currentTrend = 'down';
this.advice();
this.persistence=0;
} else{
this.persistence++;
this.checkPersistence('short');
}
} else {
this.advice();
}
}
module.exports = method;
|
'use strict';
app.controller('DashboardCtrl', function($scope , $route, $mdDialog, $pageVisibility, dataService, timerService, addressService, minerService) {
$scope.minerStats = {};
$scope.updateCharts = function (){
minerService.updateStats($scope.addrStats, function(minerStats){
$scope.minerStats = minerStats;
});
}
// Update miners everyime addrStats
$scope.$parent.$watch('addrStats', function(newValue, oldValue) {
$scope.updateCharts();
});
$scope.addAddress = function (){
if ($scope.paymentAddress){
addressService.trackAddress($scope.paymentAddress);
$scope.paymentAddress = "";
}
};
$scope.deleteAddress = function (key, ev){
var confirm = $mdDialog.confirm()
.title('Hide live stats?')
.textContent('You can add it back by entering your wallet address again')
.ariaLabel('Stop tracking payment address')
.targetEvent(ev)
.ok("Remove")
.cancel("Cancel");
$mdDialog.show(confirm).then(function() {
addressService.deleteAddress(key);
}, function() {
// cancel do nothing
});
}
$scope.setAlarm = function(addr, bool){
addressService.setAlarm(addr, bool);
};
$scope.viewPayments = function(ev, miner, addr){
$mdDialog.show({
locals: {
miner: miner,
addr: addr
},
controller: "MinerPaymentsCtrl",
templateUrl: 'user/dashboard/minerpayments.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true,
fullscreen: !$scope.menuOpen
})
.then(function(answer) {
$scope.status = 'You said the information was "' + answer + '".';
}, function() {
$scope.status = 'You cancelled the dialog.';
});
}
// Recurring API calls and timer
var loadData = function () {
_.each($scope.poolList, function(pool_type) {
dataService.getData("/pool/stats/"+pool_type, function(data){
$scope.poolStats[pool_type] = data;
});
dataService.getData("/pool/blocks/"+pool_type, function(data){
if (data.length > 0){
$scope.lastBlock[pool_type] = data[0];
} else {
$scope.lastBlock[pool_type] = {
ts: 0,
hash: "",
diff: 0,
shares: 0,
height: 0,
valid: false,
unlocked: false,
pool_type: pool_type,
value: 0
}
}
});
});
// Call minerservice update
$scope.updateCharts();
};
// No spawn xhr reqs in bg
$pageVisibility.$on('pageFocused', function(){
minerService.runService(true);
});
$pageVisibility.$on('pageBlurred', function(){
minerService.runService(false);
});
// Register call with timer
timerService.register(loadData, $route.current.controller);
loadData();
$scope.$on("$routeChangeStart", function () {
timerService.remove($route.current.controller);
});
});
|
'use strict';
/**
* Encode the given string through `encodeURIComponent`
* and encode parenthesis as well.
* This is needed to avoid an nginx error (method not allowed)
*/
module.exports = function encodeURIComponentAndParentheses(string) {
string = encodeURIComponent(string);
string = string.replace(/\(/g, "%28");
string = string.replace(/\)/g, "%29");
return string;
};
|
// Generic Super Objects
function BCAsyncObject() {
this.addDeferred = function (def) {
this.deferreds.push(def);
};
this.executeDeferreds = function (callback) {
allDeferred = [];
var context = this;
$.each(this.deferreds, function (i, def) {
allDeferred.push(def.apply(context));
});
$.when.apply(this, allDeferred).then(callback);
};
}
BCSyncedObject.prototype = new BCAsyncObject();
function BCSyncedObject() {
this.saveToOutlook = function () {
//To be overwritten;
};
this.saveToCloud = function (oldEntity, command) {
//To be overwritten
};
}
//Object Factory
function BCObjectUtility() {
var self = this;
self.getObjectType = function (obj) {
if (!obj) {
return 'unknown';
}
if (obj.hasOwnProperty("type")) {
return obj.type;
}
if (obj.hasOwnProperty("completed") && obj.hasOwnProperty("due_on") && obj.hasOwnProperty("due_at") && obj.hasOwnProperty("todolist_id")) {
type = 'todo';
} else if (obj.hasOwnProperty("ends_at") && obj.hasOwnProperty("starts_at") && obj.hasOwnProperty("all_day")) {
type = 'calendar';
} else if (obj.hasOwnProperty("private") && !obj.hasOwnProperty("last_updater")) {
type = 'discussion';
} else if (obj.hasOwnProperty("last_updater")) {
type = 'document';
} else if (obj.hasOwnProperty("attachments")) {
type = 'file';
} else {
type = 'unknown';
}
return type;
};
self.createObject = function (json, type) {
var result;
if (typeof json === 'string') {
result = JSON.parse(json);
} else {
result = json;
}
var obj = null;
//Determine type
if (type === undefined) {
type = self.getObjectType(result);
}
// Obj Creation based on type
if (type === 'todo' || type === 'Todo') {
obj = new BCTask(result);
//Enrich based on settings
if (basecamp.settings.SyncTasksFolders || basecamp.settings.SyncTasksProjectCategory)
obj.addDeferred(BCProjectNameGetter);
if (basecamp.settings.SyncTasksToDoCategory)
obj.addDeferred(BCTodolistNameGetter);
} else if (type === 'calendar' || type === 'CalendarEvent') {
obj = new BCAppointment(result);
obj.addDeferred(BCCalendarIdGetter);
if (basecamp.settings.SyncNewCalendar || basecamp.settings.SyncCalendarProjectCategory)
obj.addDeferred(BCCalendarNameGetter);
}
return obj;
};
}
//Deferred Getters
function BCProjectNameGetter() {
var deferredObject = this.deferredObject;
return $.Deferred(function (dfd) {
if (deferredObject && !deferredObject.projectName) {
var projectId = bcGetProjectId(deferredObject.url);
yasoon.oauth({
url: basecamp.settings.baseUrl + '/projects/' + projectId + '.json',
oauthServiceName: 'auth',
headers: basecamp.CONST_HEADER,
type: yasoon.ajaxMethod.Get,
error: basecamp.handleError,
success: function (data) {
var result = JSON.parse(data);
deferredObject.projectName = result.name;
dfd.resolve();
}
});
} else {
dfd.resolve();
}
});
}
function BCTodolistNameGetter() {
var deferredObject = this.deferredObject;
return $.Deferred(function (dfd) {
if (deferredObject && deferredObject.todolist_id && !deferredObject.todoListName ) {
var projectId = bcGetProjectId(deferredObject.url);
yasoon.oauth({
url: basecamp.settings.baseUrl + '/projects/' + projectId + '/todolists/' + deferredObject.todolist_id + '.json',
oauthServiceName: 'auth',
headers: basecamp.CONST_HEADER,
type: yasoon.ajaxMethod.Get,
error: basecamp.handleError,
success: function (data) {
var result = JSON.parse(data);
deferredObject.todoListName = result.name;
dfd.resolve();
}
});
} else {
dfd.resolve();
}
}).promise();
}
function BCAssigneeGetter() {
var deferredObject = this.deferredObject;
return $.Deferred(function (dfd) {
if (deferredObject && deferredObject.assignee && !deferredObject.assigneeObj ) {
basecamp.contacts.getContact(deferredObject.assignee.id, function (data) {
deferredObject.assigneeObj = JSON.parse(data);
bcLog('Assignee loaded: ', deferredObject.assigneeObj);
dfd.resolve();
});
} else {
dfd.resolve();
}
}).promise();
}
function BCCalendarIdGetter() {
var deferredObject = this.deferredObject;
return $.Deferred(function (dfd) {
if (deferredObject && !deferredObject.calendarId) {
deferredObject.calendarId = bcGetProjectId(deferredObject.url);
if (deferredObject.calendarId === 0) {
//Not an project calendar --> Personal Calendar
deferredObject.calendarId = bcGetCalendarId(deferredObject.url);
}
}
dfd.resolve();
});
}
function BCCalendarNameGetter() {
var deferredObject = this.deferredObject;
return $.Deferred(function (dfd) {
if (deferredObject && !deferredObject.calendarName) {
//Calendar Name is either project name or calendar Name.
var projectId = bcGetProjectId(deferredObject.url);
var calendarId = bcGetCalendarId(deferredObject.url);
if (projectId !== 0) {
//project
yasoon.oauth({
url: basecamp.settings.baseUrl + '/projects/' + projectId + '.json',
oauthServiceName: 'auth',
headers: basecamp.CONST_HEADER,
type: yasoon.ajaxMethod.Get,
error: basecamp.handleError,
success: function (jsonData) {
var result = JSON.parse(jsonData);
deferredObject.calendarName = result.name;
dfd.resolve();
}
});
} else if (calendarId !== 0) {
//calendar
yasoon.oauth({
url: basecamp.settings.baseUrl + '/calendars/' + calendarId + '.json',
oauthServiceName: 'auth',
headers: basecamp.CONST_HEADER,
type: yasoon.ajaxMethod.Get,
error: basecamp.handleError,
success: function (jsonData) {
var result = JSON.parse(jsonData);
deferredObject.calendarName = result.name;
dfd.resolve();
}
});
}
} else {
dfd.resolve();
}
}).promise();
}
//Tiny Controllers
function BCContactController() {
var self = this;
this.getOwnUserId = function () {
bcLog('Own User requested');
yasoon.oauth({
url: basecamp.settings.baseUrl + '/people/me.json',
oauthServiceName: 'auth',
headers: basecamp.CONST_HEADER,
type: yasoon.ajaxMethod.Get,
error: basecamp.handleError,
success: function (jsonData) {
var person = JSON.parse(jsonData);
bcLog('OwnUser: ', person);
basecamp.settings.userId = person.id;
yasoon.setting.setAppParameter(basecamp.CONST_SETTINGS, JSON.stringify(basecamp.settings));
self.updateYasoonContact(person);
}
});
};
this.getContact = function (id, doneCbk) {
yasoon.oauth({
url: basecamp.settings.baseUrl + '/people/' + id + '.json',
oauthServiceName: 'auth',
headers: basecamp.CONST_HEADER,
type: yasoon.ajaxMethod.Get,
error: basecamp.handleError,
success: doneCbk
});
};
this.updateYasoonContact = function (contact) {
if (!contact || !contact.id) {
return;
}
if (contact.avatar_url && contact.avatar_url.indexOf('.96.gif') == -1) {
contact.avatar_url = contact.avatar_url.replace('.gif', '.96.gif');
}
var c = yasoon.contact.get(contact.id);
if (!c) {
var newContact = {
contactId: contact.id,
contactLastName: contact.name,
externalAvatarUrl: contact.avatar_url
};
bcLog('New Contact created: ', newContact);
yasoon.contact.add(newContact);
} else {
if (c.externalAvatarUrl != contact.avatar_url || c.contactLastName != contact.name) {
c.contactLastName = contact.name;
c.externalAvatarUrl = contact.avatar_url;
bcLog('Contact updated: ', c);
yasoon.contact.save(c);
}
}
};
}
function BCProjectController() {
var self = this;
this.syncAllowed = function (projectId) {
if (projectId === 0) {
return true;
}
if (basecamp.settings.SyncAllProjects) {
return true;
}
if (basecamp.settings.hasOwnProperty('Project-' + projectId) && basecamp.settings['Project-' + projectId]) {
return true;
}
bcLog('Sync for project disabled: ' + projectId);
return false;
};
this.getAllProjects = function (callback) {
bcLog('All projects requested');
//Get Projects and notify callback
yasoon.oauth({
url: basecamp.settings.baseUrl + '/projects.json',
oauthServiceName: 'auth',
headers: basecamp.CONST_HEADER,
type: yasoon.ajaxMethod.Get,
error: basecamp.handleError,
success: callback
});
};
}
/****** URL parsing Methods ******/
/* Converts an attachment URL that needs an login into an SSO version */
function bcConvertAttachmentUrl(url) {
if (url === undefined)
return;
//basecamp API returns Urls that needs a seperat login, even if basecamp user is already logged in. We transform the urls, so no login is needed.
//from: https://asset1.basecamp.com/1234/api/v1/projects/1234-test-project/attachments/12345/2a39519c84f26d1cf054e3542da41a710010/original/OutlookError.PNG
//to: https://basecamp.com/1234/projects/1234-test-project/attachments/12345/download
var myRegexp = /(https:\/\/.*?\.basecamp.com\/(\d+)\/api\/v1\/((?:projects|calendars)\/[^/]+)\/(attachments\/\d+)\/[a-z0-9]+\/.*)/g;
var match = myRegexp.exec(url);
if (match && match.length == 5) {
return 'https://basecamp.com/' + match[2] + '/' + match[3] + '/' + match[4] + '/download';
} else {
//Unexpected behaviour... return original url which may need login.
yasoon.util.log('Could not determine Attachment Url: ' + url, yasoon.util.severity.error);
return url;
}
}
/* Parses the project Id of an URL */
function bcGetProjectId(url) {
//Parse Project URL
var myRegexp = /projects\/(\d+)-([^/]+)\//g;
var match = myRegexp.exec(url);
if (match && match.length > 0) {
return match[1];
} else {
//Parse Any project object URL
myRegexp = /projects\/(\d+)\//g;
match = myRegexp.exec(url);
if (match && match.length > 0) {
return match[1];
} else {
//Calendar URL --> does not work
return 0;
}
}
}
/*Parses calendar ID of an URL */
function bcGetCalendarId(url) {
//Parse Calendar URL
var myRegexp = /calendars\/(\d+)\//g;
var match = myRegexp.exec(url);
if (match && match.length > 0) {
return match[1];
} else {
return 0;
}
}
/* Converts an API URL into the corresponding UI Url*/
function bcParseAPIUrl(url) {
var result = url.replace('/api/v1/', '/');
result = result.replace('.json', '');
return result;
}
function bcCommandSuccess(data, cmd) {
bcLog('Command successfull: ', JSON.parse(data));
cmd.complete();
var resync = function () { basecamp.sync(); };
debounce(resync, 2000)();
}
function bcLog(text, obj, stacktrace) {
if (yasoon.logLevel === 0) {
var stack = '';
var json = '';
if (stacktrace) {
try {
var a = doesNotExit + forceException;
} catch (e) {
stack = '\n' + printStackTrace(e).split('\n')
.slice(1)
.join('\n');
}
}
if (obj) {
json = '\n' + JSON.stringify(obj);
}
yasoon.util.log(text + ' ' + json + ' ' + stack);
}
}
//Queue Helper Function
function bcQueue(funcs, scope) {
(function next() {
if (funcs.length > 0) {
funcs.shift().apply(scope || {}, [next].concat(Array.prototype.slice.call(arguments, 0)));
}
})();
}
//@ sourceURL=http://Basecamp/functions.js
|
//curl -X POST "https://api.groupme.com/v3/bots/post?bot_id=a50adb57a9892969de430abaee&text=Hello+an+faggots,+this+is+Johnny"
//"https://api.groupme.com/v3/bots/post?bot_id=a50adb57a9892969de430abaee&text=Hello+an+faggots,+this+is+Johnny"
var https = require('https');
var makeURI = function (message,botId) {
//tester group
//a50adb57a9892969de430abaee == asshole group
var botId = botId || '46614c61b21cb2f6f43fde0ca6'
var encodedURI = encodeURI("/v3/bots/post?bot_id="+botId+"&text="+message);
return encodedURI;
}
var path = makeURI("Do you boys want to party?",'a50adb57a9892969de430abaee')
//The url we want is `www.nodejitsu.com:1337/`
var options = {
host: 'api.groupme.com',
path: path,
method: 'POST',
headers: {
accept: '*/*'
},
port:443
};
callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
response.on('error', function (error) {
console.log(error);
});
}
var req = https.request(options, callback);
//This is the data we are posting, it needs to be a string or a buffer
req.write('');
req.end();
req.on('error', function (err) {
console.log(err)
})
|
/* ************************************************************************ */
/*
*/
var React = require('react');
var Recipes = require('./panels/Recipes.js');
var helper = require('../utils/helpers');
const title = (<span><h2>Recipes</h2> <i>Click one to edit</i></span>);
var RecipeList = React.createClass({
getInitialState: function() {
console.log('Main getInitialState: function () {');
return {
userRecipes: {}
};
},
// Runs before render
componentDidMount: function(){
console.log('componentDidMount: function(){');
helper.getUserRecipeList().then(function(response) {
//console.log(JSON.stringify(response.data));
this.setState({
userRecipes: response.data
});
}.bind(this));
},
createClick: function() {
console.log('create recipe click');
},
render: function() {
console.log('RecipeList RENDER')
return (
<div id="RecipeList">
<div className="row">
<div className="col-lg-10 col-lg-offset-1 col-md-10 col-md-offset-1 col-sm-10 col-sm-offset-1 col-xs-10 col-xs-offset-1">
<div className="panel panel-primary">
<div className="panel-heading">
<h3 className="panel-title">{title}</h3>
</div>
<div className="panel-body">
<Recipes userRecipes={this.state.userRecipes}/>
</div>
</div>
</div>
</div>
</div>
);
}
});
module.exports = RecipeList;
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.0.0-rc4-master-7cb035d
*/
goog.provide('ng.material.components.autocomplete');
goog.require('ng.material.components.icon');
goog.require('ng.material.components.virtualRepeat');
goog.require('ng.material.core');
/**
* @ngdoc module
* @name material.components.autocomplete
*/
/*
* @see js folder for autocomplete implementation
*/
angular.module('material.components.autocomplete', [
'material.core',
'material.components.icon',
'material.components.virtualRepeat'
]);
angular
.module('material.components.autocomplete')
.controller('MdAutocompleteCtrl', MdAutocompleteCtrl);
var ITEM_HEIGHT = 41,
MAX_HEIGHT = 5.5 * ITEM_HEIGHT,
MENU_PADDING = 8,
INPUT_PADDING = 2; // Padding provided by `md-input-container`
function MdAutocompleteCtrl ($scope, $element, $mdUtil, $mdConstant, $mdTheming, $window,
$animate, $rootElement, $attrs, $q) {
//-- private variables
var ctrl = this,
itemParts = $scope.itemsExpr.split(/ in /i),
itemExpr = itemParts[ 1 ],
elements = null,
cache = {},
noBlur = false,
selectedItemWatchers = [],
hasFocus = false,
lastCount = 0;
//-- public variables with handlers
defineProperty('hidden', handleHiddenChange, true);
//-- public variables
ctrl.scope = $scope;
ctrl.parent = $scope.$parent;
ctrl.itemName = itemParts[ 0 ];
ctrl.matches = [];
ctrl.loading = false;
ctrl.hidden = true;
ctrl.index = null;
ctrl.messages = [];
ctrl.id = $mdUtil.nextUid();
ctrl.isDisabled = null;
ctrl.isRequired = null;
ctrl.hasNotFound = false;
//-- public methods
ctrl.keydown = keydown;
ctrl.blur = blur;
ctrl.focus = focus;
ctrl.clear = clearValue;
ctrl.select = select;
ctrl.listEnter = onListEnter;
ctrl.listLeave = onListLeave;
ctrl.mouseUp = onMouseup;
ctrl.getCurrentDisplayValue = getCurrentDisplayValue;
ctrl.registerSelectedItemWatcher = registerSelectedItemWatcher;
ctrl.unregisterSelectedItemWatcher = unregisterSelectedItemWatcher;
ctrl.notFoundVisible = notFoundVisible;
ctrl.loadingIsVisible = loadingIsVisible;
return init();
//-- initialization methods
/**
* Initialize the controller, setup watchers, gather elements
*/
function init () {
$mdUtil.initOptionalProperties($scope, $attrs, { searchText: null, selectedItem: null });
$mdTheming($element);
configureWatchers();
$mdUtil.nextTick(function () {
gatherElements();
moveDropdown();
focusElement();
$element.on('focus', focusElement);
});
}
/**
* Calculates the dropdown's position and applies the new styles to the menu element
* @returns {*}
*/
function positionDropdown () {
if (!elements) return $mdUtil.nextTick(positionDropdown, false, $scope);
var hrect = elements.wrap.getBoundingClientRect(),
vrect = elements.snap.getBoundingClientRect(),
root = elements.root.getBoundingClientRect(),
top = vrect.bottom - root.top,
bot = root.bottom - vrect.top,
left = hrect.left - root.left,
width = hrect.width,
offset = getVerticalOffset(),
styles;
// Adjust the width to account for the padding provided by `md-input-container`
if ($attrs.mdFloatingLabel) {
left += INPUT_PADDING;
width -= INPUT_PADDING * 2;
}
styles = {
left: left + 'px',
minWidth: width + 'px',
maxWidth: Math.max(hrect.right - root.left, root.right - hrect.left) - MENU_PADDING + 'px'
};
if (top > bot && root.height - hrect.bottom - MENU_PADDING < MAX_HEIGHT) {
styles.top = 'auto';
styles.bottom = bot + 'px';
styles.maxHeight = Math.min(MAX_HEIGHT, hrect.top - root.top - MENU_PADDING) + 'px';
} else {
styles.top = (top - offset) + 'px';
styles.bottom = 'auto';
styles.maxHeight = Math.min(MAX_HEIGHT, root.bottom - hrect.bottom - MENU_PADDING) + 'px';
}
elements.$.scrollContainer.css(styles);
$mdUtil.nextTick(correctHorizontalAlignment, false);
/**
* Calculates the vertical offset for floating label examples to account for ngMessages
* @returns {number}
*/
function getVerticalOffset () {
var offset = 0;
var inputContainer = $element.find('md-input-container');
if (inputContainer.length) {
var input = inputContainer.find('input');
offset = inputContainer.prop('offsetHeight');
offset -= input.prop('offsetTop');
offset -= input.prop('offsetHeight');
// add in the height left up top for the floating label text
offset += inputContainer.prop('offsetTop');
}
return offset;
}
/**
* Makes sure that the menu doesn't go off of the screen on either side.
*/
function correctHorizontalAlignment () {
var dropdown = elements.scrollContainer.getBoundingClientRect(),
styles = {};
if (dropdown.right > root.right - MENU_PADDING) {
styles.left = (hrect.right - dropdown.width) + 'px';
}
elements.$.scrollContainer.css(styles);
}
}
/**
* Moves the dropdown menu to the body tag in order to avoid z-index and overflow issues.
*/
function moveDropdown () {
if (!elements.$.root.length) return;
$mdTheming(elements.$.scrollContainer);
elements.$.scrollContainer.detach();
elements.$.root.append(elements.$.scrollContainer);
if ($animate.pin) $animate.pin(elements.$.scrollContainer, $rootElement);
}
/**
* Sends focus to the input element.
*/
function focusElement () {
if ($scope.autofocus) elements.input.focus();
}
/**
* Sets up any watchers used by autocomplete
*/
function configureWatchers () {
var wait = parseInt($scope.delay, 10) || 0;
$attrs.$observe('disabled', function (value) { ctrl.isDisabled = !!value; });
$attrs.$observe('required', function (value) { ctrl.isRequired = !!value; });
$scope.$watch('searchText', wait ? $mdUtil.debounce(handleSearchText, wait) : handleSearchText);
$scope.$watch('selectedItem', selectedItemChange);
angular.element($window).on('resize', positionDropdown);
$scope.$on('$destroy', cleanup);
}
/**
* Removes any events or leftover elements created by this controller
*/
function cleanup () {
angular.element($window).off('resize', positionDropdown);
if ( elements ){
var items = 'ul scroller scrollContainer input'.split(' ');
angular.forEach(items, function(key){
elements.$[key].remove();
});
}
}
/**
* Gathers all of the elements needed for this controller
*/
function gatherElements () {
elements = {
main: $element[0],
scrollContainer: $element[0].getElementsByClassName('md-virtual-repeat-container')[0],
scroller: $element[0].getElementsByClassName('md-virtual-repeat-scroller')[0],
ul: $element.find('ul')[0],
input: $element.find('input')[0],
wrap: $element.find('md-autocomplete-wrap')[0],
root: document.body
};
elements.li = elements.ul.getElementsByTagName('li');
elements.snap = getSnapTarget();
elements.$ = getAngularElements(elements);
}
/**
* Finds the element that the menu will base its position on
* @returns {*}
*/
function getSnapTarget () {
for (var element = $element; element.length; element = element.parent()) {
if (angular.isDefined(element.attr('md-autocomplete-snap'))) return element[ 0 ];
}
return elements.wrap;
}
/**
* Gathers angular-wrapped versions of each element
* @param elements
* @returns {{}}
*/
function getAngularElements (elements) {
var obj = {};
for (var key in elements) {
if (elements.hasOwnProperty(key)) obj[ key ] = angular.element(elements[ key ]);
}
return obj;
}
//-- event/change handlers
/**
* Handles changes to the `hidden` property.
* @param hidden
* @param oldHidden
*/
function handleHiddenChange (hidden, oldHidden) {
if (!hidden && oldHidden) {
positionDropdown();
if (elements) {
$mdUtil.nextTick(function () {
$mdUtil.disableScrollAround(elements.ul);
}, false, $scope);
}
} else if (hidden && !oldHidden) {
$mdUtil.nextTick(function () {
$mdUtil.enableScrolling();
}, false, $scope);
}
}
/**
* When the user mouses over the dropdown menu, ignore blur events.
*/
function onListEnter () {
noBlur = true;
}
/**
* When the user's mouse leaves the menu, blur events may hide the menu again.
*/
function onListLeave () {
if (!hasFocus) elements.input.focus();
noBlur = false;
ctrl.hidden = shouldHide();
}
/**
* When the mouse button is released, send focus back to the input field.
*/
function onMouseup () {
elements.input.focus();
}
/**
* Handles changes to the selected item.
* @param selectedItem
* @param previousSelectedItem
*/
function selectedItemChange (selectedItem, previousSelectedItem) {
if (selectedItem) {
getDisplayValue(selectedItem).then(function (val) {
$scope.searchText = val;
handleSelectedItemChange(selectedItem, previousSelectedItem);
});
}
if (selectedItem !== previousSelectedItem) announceItemChange();
}
/**
* Use the user-defined expression to announce changes each time a new item is selected
*/
function announceItemChange () {
angular.isFunction($scope.itemChange) && $scope.itemChange(getItemAsNameVal($scope.selectedItem));
}
/**
* Use the user-defined expression to announce changes each time the search text is changed
*/
function announceTextChange () {
angular.isFunction($scope.textChange) && $scope.textChange();
}
/**
* Calls any external watchers listening for the selected item. Used in conjunction with
* `registerSelectedItemWatcher`.
* @param selectedItem
* @param previousSelectedItem
*/
function handleSelectedItemChange (selectedItem, previousSelectedItem) {
selectedItemWatchers.forEach(function (watcher) { watcher(selectedItem, previousSelectedItem); });
}
/**
* Register a function to be called when the selected item changes.
* @param cb
*/
function registerSelectedItemWatcher (cb) {
if (selectedItemWatchers.indexOf(cb) == -1) {
selectedItemWatchers.push(cb);
}
}
/**
* Unregister a function previously registered for selected item changes.
* @param cb
*/
function unregisterSelectedItemWatcher (cb) {
var i = selectedItemWatchers.indexOf(cb);
if (i != -1) {
selectedItemWatchers.splice(i, 1);
}
}
/**
* Handles changes to the searchText property.
* @param searchText
* @param previousSearchText
*/
function handleSearchText (searchText, previousSearchText) {
ctrl.index = getDefaultIndex();
// do nothing on init
if (searchText === previousSearchText) return;
getDisplayValue($scope.selectedItem).then(function (val) {
// clear selected item if search text no longer matches it
if (searchText !== val) {
$scope.selectedItem = null;
// trigger change event if available
if (searchText !== previousSearchText) announceTextChange();
// cancel results if search text is not long enough
if (!isMinLengthMet()) {
ctrl.matches = [];
setLoading(false);
updateMessages();
} else {
handleQuery();
}
}
});
}
/**
* Handles input blur event, determines if the dropdown should hide.
*/
function blur () {
hasFocus = false;
if (!noBlur) {
ctrl.hidden = shouldHide();
}
}
/**
* Force blur on input element
* @param forceBlur
*/
function doBlur(forceBlur) {
if (forceBlur) {
noBlur = false;
hasFocus = false;
}
elements.input.blur();
}
/**
* Handles input focus event, determines if the dropdown should show.
*/
function focus () {
hasFocus = true;
//-- if searchText is null, let's force it to be a string
if (!angular.isString($scope.searchText)) $scope.searchText = '';
ctrl.hidden = shouldHide();
if (!ctrl.hidden) handleQuery();
}
/**
* Handles keyboard input.
* @param event
*/
function keydown (event) {
switch (event.keyCode) {
case $mdConstant.KEY_CODE.DOWN_ARROW:
if (ctrl.loading) return;
event.stopPropagation();
event.preventDefault();
ctrl.index = Math.min(ctrl.index + 1, ctrl.matches.length - 1);
updateScroll();
updateMessages();
break;
case $mdConstant.KEY_CODE.UP_ARROW:
if (ctrl.loading) return;
event.stopPropagation();
event.preventDefault();
ctrl.index = ctrl.index < 0 ? ctrl.matches.length - 1 : Math.max(0, ctrl.index - 1);
updateScroll();
updateMessages();
break;
case $mdConstant.KEY_CODE.TAB:
// If we hit tab, assume that we've left the list so it will close
onListLeave();
if (ctrl.hidden || ctrl.loading || ctrl.index < 0 || ctrl.matches.length < 1) return;
select(ctrl.index);
break;
case $mdConstant.KEY_CODE.ENTER:
if (ctrl.hidden || ctrl.loading || ctrl.index < 0 || ctrl.matches.length < 1) return;
if (hasSelection()) return;
event.stopPropagation();
event.preventDefault();
select(ctrl.index);
break;
case $mdConstant.KEY_CODE.ESCAPE:
event.stopPropagation();
event.preventDefault();
clearValue();
// Force the component to blur if they hit escape
doBlur(true);
break;
default:
}
}
//-- getters
/**
* Returns the minimum length needed to display the dropdown.
* @returns {*}
*/
function getMinLength () {
return angular.isNumber($scope.minLength) ? $scope.minLength : 1;
}
/**
* Returns the display value for an item.
* @param item
* @returns {*}
*/
function getDisplayValue (item) {
return $q.when(getItemText(item) || item);
/**
* Getter function to invoke user-defined expression (in the directive)
* to convert your object to a single string.
*/
function getItemText (item) {
return (item && $scope.itemText) ? $scope.itemText(getItemAsNameVal(item)) : null;
}
}
/**
* Returns the locals object for compiling item templates.
* @param item
* @returns {{}}
*/
function getItemAsNameVal (item) {
if (!item) return undefined;
var locals = {};
if (ctrl.itemName) locals[ ctrl.itemName ] = item;
return locals;
}
/**
* Returns the default index based on whether or not autoselect is enabled.
* @returns {number}
*/
function getDefaultIndex () {
return $scope.autoselect ? 0 : -1;
}
/**
* Sets the loading parameter and updates the hidden state.
* @param value {boolean} Whether or not the component is currently loading.
*/
function setLoading(value) {
if (ctrl.loading != value) {
ctrl.loading = value;
}
// Always refresh the hidden variable as something else might have changed
ctrl.hidden = shouldHide();
}
/**
* Determines if the menu should be hidden.
* @returns {boolean}
*/
function shouldHide () {
if (ctrl.loading && !hasMatches()) return true; // Hide while loading initial matches
else if (hasSelection()) return true; // Hide if there is already a selection
else if (!hasFocus) return true; // Hide if the input does not have focus
else return !shouldShow(); // Defer to standard show logic
}
/**
* Determines if the menu should be shown.
* @returns {boolean}
*/
function shouldShow() {
return (isMinLengthMet() && hasMatches()) || notFoundVisible();
}
/**
* Returns true if the search text has matches.
* @returns {boolean}
*/
function hasMatches() {
return ctrl.matches.length ? true : false;
}
/**
* Returns true if the autocomplete has a valid selection.
* @returns {boolean}
*/
function hasSelection() {
return ctrl.scope.selectedItem ? true : false;
}
/**
* Returns true if the loading indicator is, or should be, visible.
* @returns {boolean}
*/
function loadingIsVisible() {
return ctrl.loading && !hasSelection();
}
/**
* Returns the display value of the current item.
* @returns {*}
*/
function getCurrentDisplayValue () {
return getDisplayValue(ctrl.matches[ ctrl.index ]);
}
/**
* Determines if the minimum length is met by the search text.
* @returns {*}
*/
function isMinLengthMet () {
return ($scope.searchText || '').length >= getMinLength();
}
//-- actions
/**
* Defines a public property with a handler and a default value.
* @param key
* @param handler
* @param value
*/
function defineProperty (key, handler, value) {
Object.defineProperty(ctrl, key, {
get: function () { return value; },
set: function (newValue) {
var oldValue = value;
value = newValue;
handler(newValue, oldValue);
}
});
}
/**
* Selects the item at the given index.
* @param index
*/
function select (index) {
//-- force form to update state for validation
$mdUtil.nextTick(function () {
getDisplayValue(ctrl.matches[ index ]).then(function (val) {
var ngModel = elements.$.input.controller('ngModel');
ngModel.$setViewValue(val);
ngModel.$render();
}).finally(function () {
$scope.selectedItem = ctrl.matches[ index ];
setLoading(false);
});
}, false);
}
/**
* Clears the searchText value and selected item.
*/
function clearValue () {
// Set the loading to true so we don't see flashes of content
setLoading(true);
// Reset our variables
ctrl.index = 0;
ctrl.matches = [];
$scope.searchText = '';
// Tell the select to fire and select nothing
select(-1);
// Per http://www.w3schools.com/jsref/event_oninput.asp
var eventObj = document.createEvent('CustomEvent');
eventObj.initCustomEvent('input', true, true, { value: $scope.searchText });
elements.input.dispatchEvent(eventObj);
elements.input.focus();
}
/**
* Fetches the results for the provided search text.
* @param searchText
*/
function fetchResults (searchText) {
var items = $scope.$parent.$eval(itemExpr),
term = searchText.toLowerCase();
if (angular.isArray(items)) {
handleResults(items);
} else if (items) {
setLoading(true);
$mdUtil.nextTick(function () {
if (items.success) items.success(handleResults);
if (items.then) items.then(handleResults);
if (items.finally) items.finally(function () {
setLoading(false);
});
},true, $scope);
}
function handleResults (matches) {
cache[ term ] = matches;
if ((searchText || '') !== ($scope.searchText || '')) return; //-- just cache the results if old request
ctrl.matches = matches;
ctrl.hidden = shouldHide();
if ($scope.selectOnMatch) selectItemOnMatch();
updateMessages();
positionDropdown();
}
}
/**
* Updates the ARIA messages
*/
function updateMessages () {
getCurrentDisplayValue().then(function (msg) {
ctrl.messages = [ getCountMessage(), msg ];
});
}
/**
* Returns the ARIA message for how many results match the current query.
* @returns {*}
*/
function getCountMessage () {
if (lastCount === ctrl.matches.length) return '';
lastCount = ctrl.matches.length;
switch (ctrl.matches.length) {
case 0:
return 'There are no matches available.';
case 1:
return 'There is 1 match available.';
default:
return 'There are ' + ctrl.matches.length + ' matches available.';
}
}
/**
* Makes sure that the focused element is within view.
*/
function updateScroll () {
if (!elements.li[0]) return;
var height = elements.li[0].offsetHeight,
top = height * ctrl.index,
bot = top + height,
hgt = elements.scroller.clientHeight,
scrollTop = elements.scroller.scrollTop;
if (top < scrollTop) {
scrollTo(top);
} else if (bot > scrollTop + hgt) {
scrollTo(bot - hgt);
}
}
function scrollTo (offset) {
elements.$.scrollContainer.controller('mdVirtualRepeatContainer').scrollTo(offset);
}
function notFoundVisible () {
var textLength = (ctrl.scope.searchText || '').length;
return ctrl.hasNotFound && !hasMatches() && !ctrl.loading && textLength >= getMinLength() && hasFocus && !hasSelection();
}
/**
* Starts the query to gather the results for the current searchText. Attempts to return cached
* results first, then forwards the process to `fetchResults` if necessary.
*/
function handleQuery () {
var searchText = $scope.searchText || '',
term = searchText.toLowerCase();
//-- if results are cached, pull in cached results
if (!$scope.noCache && cache[ term ]) {
ctrl.matches = cache[ term ];
updateMessages();
} else {
fetchResults(searchText);
}
ctrl.hidden = shouldHide();
}
/**
* If there is only one matching item and the search text matches its display value exactly,
* automatically select that item. Note: This function is only called if the user uses the
* `md-select-on-match` flag.
*/
function selectItemOnMatch () {
var searchText = $scope.searchText,
matches = ctrl.matches,
item = matches[ 0 ];
if (matches.length === 1) getDisplayValue(item).then(function (displayValue) {
if (searchText == displayValue) select(0);
});
}
}
MdAutocompleteCtrl.$inject = ["$scope", "$element", "$mdUtil", "$mdConstant", "$mdTheming", "$window", "$animate", "$rootElement", "$attrs", "$q"];
angular
.module('material.components.autocomplete')
.directive('mdAutocomplete', MdAutocomplete);
/**
* @ngdoc directive
* @name mdAutocomplete
* @module material.components.autocomplete
*
* @description
* `<md-autocomplete>` is a special input component with a drop-down of all possible matches to a
* custom query. This component allows you to provide real-time suggestions as the user types
* in the input area.
*
* To start, you will need to specify the required parameters and provide a template for your
* results. The content inside `md-autocomplete` will be treated as a template.
*
* In more complex cases, you may want to include other content such as a message to display when
* no matches were found. You can do this by wrapping your template in `md-item-template` and
* adding a tag for `md-not-found`. An example of this is shown below.
*
* ### Validation
*
* You can use `ng-messages` to include validation the same way that you would normally validate;
* however, if you want to replicate a standard input with a floating label, you will have to
* do the following:
*
* - Make sure that your template is wrapped in `md-item-template`
* - Add your `ng-messages` code inside of `md-autocomplete`
* - Add your validation properties to `md-autocomplete` (ie. `required`)
* - Add a `name` to `md-autocomplete` (to be used on the generated `input`)
*
* There is an example below of how this should look.
*
*
* @param {expression} md-items An expression in the format of `item in items` to iterate over
* matches for your search.
* @param {expression=} md-selected-item-change An expression to be run each time a new item is
* selected
* @param {expression=} md-search-text-change An expression to be run each time the search text
* updates
* @param {expression=} md-search-text A model to bind the search query text to
* @param {object=} md-selected-item A model to bind the selected item to
* @param {expression=} md-item-text An expression that will convert your object to a single string.
* @param {string=} placeholder Placeholder text that will be forwarded to the input.
* @param {boolean=} md-no-cache Disables the internal caching that happens in autocomplete
* @param {boolean=} ng-disabled Determines whether or not to disable the input field
* @param {number=} md-min-length Specifies the minimum length of text before autocomplete will
* make suggestions
* @param {number=} md-delay Specifies the amount of time (in milliseconds) to wait before looking
* for results
* @param {boolean=} md-autofocus If true, will immediately focus the input element
* @param {boolean=} md-autoselect If true, the first item will be selected by default
* @param {string=} md-menu-class This will be applied to the dropdown menu for styling
* @param {string=} md-floating-label This will add a floating label to autocomplete and wrap it in
* `md-input-container`
* @param {string=} md-input-name The name attribute given to the input element to be used with
* FormController
* @param {string=} md-input-id An ID to be added to the input element
* @param {number=} md-input-minlength The minimum length for the input's value for validation
* @param {number=} md-input-maxlength The maximum length for the input's value for validation
* @param {boolean=} md-select-on-match When set, autocomplete will automatically select exact
* the item if the search text is an exact match
*
* @usage
* ### Basic Example
* <hljs lang="html">
* <md-autocomplete
* md-selected-item="selectedItem"
* md-search-text="searchText"
* md-items="item in getMatches(searchText)"
* md-item-text="item.display">
* <span md-highlight-text="searchText">{{item.display}}</span>
* </md-autocomplete>
* </hljs>
*
* ### Example with "not found" message
* <hljs lang="html">
* <md-autocomplete
* md-selected-item="selectedItem"
* md-search-text="searchText"
* md-items="item in getMatches(searchText)"
* md-item-text="item.display">
* <md-item-template>
* <span md-highlight-text="searchText">{{item.display}}</span>
* </md-item-template>
* <md-not-found>
* No matches found.
* </md-not-found>
* </md-autocomplete>
* </hljs>
*
* In this example, our code utilizes `md-item-template` and `md-not-found` to specify the
* different parts that make up our component.
*
* ### Example with validation
* <hljs lang="html">
* <form name="autocompleteForm">
* <md-autocomplete
* required
* md-input-name="autocomplete"
* md-selected-item="selectedItem"
* md-search-text="searchText"
* md-items="item in getMatches(searchText)"
* md-item-text="item.display">
* <md-item-template>
* <span md-highlight-text="searchText">{{item.display}}</span>
* </md-item-template>
* <div ng-messages="autocompleteForm.autocomplete.$error">
* <div ng-message="required">This field is required</div>
* </div>
* </md-autocomplete>
* </form>
* </hljs>
*
* In this example, our code utilizes `md-item-template` and `md-not-found` to specify the
* different parts that make up our component.
*/
function MdAutocomplete () {
var hasNotFoundTemplate = false;
return {
controller: 'MdAutocompleteCtrl',
controllerAs: '$mdAutocompleteCtrl',
scope: {
inputName: '@mdInputName',
inputMinlength: '@mdInputMinlength',
inputMaxlength: '@mdInputMaxlength',
searchText: '=?mdSearchText',
selectedItem: '=?mdSelectedItem',
itemsExpr: '@mdItems',
itemText: '&mdItemText',
placeholder: '@placeholder',
noCache: '=?mdNoCache',
selectOnMatch: '=?mdSelectOnMatch',
itemChange: '&?mdSelectedItemChange',
textChange: '&?mdSearchTextChange',
minLength: '=?mdMinLength',
delay: '=?mdDelay',
autofocus: '=?mdAutofocus',
floatingLabel: '@?mdFloatingLabel',
autoselect: '=?mdAutoselect',
menuClass: '@?mdMenuClass',
inputId: '@?mdInputId'
},
link: function(scope, element, attrs, controller) {
controller.hasNotFound = hasNotFoundTemplate;
},
template: function (element, attr) {
var noItemsTemplate = getNoItemsTemplate(),
itemTemplate = getItemTemplate(),
leftover = element.html(),
tabindex = attr.tabindex;
// Set our variable for the link function above which runs later
hasNotFoundTemplate = noItemsTemplate ? true : false;
if (attr.hasOwnProperty('tabindex')) {
element.attr('tabindex', '-1');
}
return '\
<md-autocomplete-wrap\
layout="row"\
ng-class="{ \'md-whiteframe-z1\': !floatingLabel, \'md-menu-showing\': !$mdAutocompleteCtrl.hidden }"\
role="listbox">\
' + getInputElement() + '\
<md-progress-linear\
class="' + (attr.mdFloatingLabel ? 'md-inline' : '') + '"\
ng-if="$mdAutocompleteCtrl.loadingIsVisible()"\
md-mode="indeterminate"></md-progress-linear>\
<md-virtual-repeat-container\
md-auto-shrink\
md-auto-shrink-min="1"\
ng-mouseenter="$mdAutocompleteCtrl.listEnter()"\
ng-mouseleave="$mdAutocompleteCtrl.listLeave()"\
ng-mouseup="$mdAutocompleteCtrl.mouseUp()"\
ng-hide="$mdAutocompleteCtrl.hidden"\
class="md-autocomplete-suggestions-container md-whiteframe-z1"\
ng-class="{ \'md-not-found\': $mdAutocompleteCtrl.notFoundVisible() }"\
role="presentation">\
<ul class="md-autocomplete-suggestions"\
ng-class="::menuClass"\
id="ul-{{$mdAutocompleteCtrl.id}}">\
<li md-virtual-repeat="item in $mdAutocompleteCtrl.matches"\
ng-class="{ selected: $index === $mdAutocompleteCtrl.index }"\
ng-click="$mdAutocompleteCtrl.select($index)"\
md-extra-name="$mdAutocompleteCtrl.itemName">\
' + itemTemplate + '\
</li>' + noItemsTemplate + '\
</ul>\
</md-virtual-repeat-container>\
</md-autocomplete-wrap>\
<aria-status\
class="md-visually-hidden"\
role="status"\
aria-live="assertive">\
<p ng-repeat="message in $mdAutocompleteCtrl.messages track by $index" ng-if="message">{{message}}</p>\
</aria-status>';
function getItemTemplate() {
var templateTag = element.find('md-item-template').detach(),
html = templateTag.length ? templateTag.html() : element.html();
if (!templateTag.length) element.empty();
return '<md-autocomplete-parent-scope md-autocomplete-replace>' + html + '</md-autocomplete-parent-scope>';
}
function getNoItemsTemplate() {
var templateTag = element.find('md-not-found').detach(),
template = templateTag.length ? templateTag.html() : '';
return template
? '<li ng-if="$mdAutocompleteCtrl.notFoundVisible()"\
md-autocomplete-parent-scope>' + template + '</li>'
: '';
}
function getInputElement () {
if (attr.mdFloatingLabel) {
return '\
<md-input-container flex ng-if="floatingLabel">\
<label>{{floatingLabel}}</label>\
<input type="search"\
' + (tabindex != null ? 'tabindex="' + tabindex + '"' : '') + '\
id="{{ inputId || \'fl-input-\' + $mdAutocompleteCtrl.id }}"\
name="{{inputName}}"\
autocomplete="off"\
ng-required="$mdAutocompleteCtrl.isRequired"\
ng-minlength="inputMinlength"\
ng-maxlength="inputMaxlength"\
ng-disabled="$mdAutocompleteCtrl.isDisabled"\
ng-model="$mdAutocompleteCtrl.scope.searchText"\
ng-keydown="$mdAutocompleteCtrl.keydown($event)"\
ng-blur="$mdAutocompleteCtrl.blur()"\
ng-focus="$mdAutocompleteCtrl.focus()"\
aria-owns="ul-{{$mdAutocompleteCtrl.id}}"\
aria-label="{{floatingLabel}}"\
aria-autocomplete="list"\
aria-haspopup="true"\
aria-activedescendant=""\
aria-expanded="{{!$mdAutocompleteCtrl.hidden}}"/>\
<div md-autocomplete-parent-scope md-autocomplete-replace>' + leftover + '</div>\
</md-input-container>';
} else {
return '\
<input flex type="search"\
' + (tabindex != null ? 'tabindex="' + tabindex + '"' : '') + '\
id="{{ inputId || \'input-\' + $mdAutocompleteCtrl.id }}"\
name="{{inputName}}"\
ng-if="!floatingLabel"\
autocomplete="off"\
ng-required="$mdAutocompleteCtrl.isRequired"\
ng-disabled="$mdAutocompleteCtrl.isDisabled"\
ng-model="$mdAutocompleteCtrl.scope.searchText"\
ng-keydown="$mdAutocompleteCtrl.keydown($event)"\
ng-blur="$mdAutocompleteCtrl.blur()"\
ng-focus="$mdAutocompleteCtrl.focus()"\
placeholder="{{placeholder}}"\
aria-owns="ul-{{$mdAutocompleteCtrl.id}}"\
aria-label="{{placeholder}}"\
aria-autocomplete="list"\
aria-haspopup="true"\
aria-activedescendant=""\
aria-expanded="{{!$mdAutocompleteCtrl.hidden}}"/>\
<button\
type="button"\
tabindex="-1"\
ng-if="$mdAutocompleteCtrl.scope.searchText && !$mdAutocompleteCtrl.isDisabled"\
ng-click="$mdAutocompleteCtrl.clear()">\
<md-icon md-svg-icon="md-close"></md-icon>\
<span class="md-visually-hidden">Clear</span>\
</button>\
';
}
}
}
};
}
angular
.module('material.components.autocomplete')
.directive('mdAutocompleteParentScope', MdAutocompleteItemScopeDirective);
function MdAutocompleteItemScopeDirective($compile, $mdUtil) {
return {
restrict: 'AE',
link: postLink,
terminal: true
};
function postLink(scope, element, attr) {
var ctrl = scope.$mdAutocompleteCtrl;
var newScope = ctrl.parent.$new();
var itemName = ctrl.itemName;
// Watch for changes to our scope's variables and copy them to the new scope
watchVariable('$index', '$index');
watchVariable('item', itemName);
// Recompile the contents with the new/modified scope
$compile(element.contents())(newScope);
// Replace it if required
if (attr.hasOwnProperty('mdAutocompleteReplace')) {
element.after(element.contents());
element.remove();
}
/**
* Creates a watcher for variables that are copied from the parent scope
* @param variable
* @param alias
*/
function watchVariable(variable, alias) {
newScope[alias] = scope[variable];
scope.$watch(variable, function(value) {
$mdUtil.nextTick(function() {
newScope[alias] = value;
});
});
}
}
}
MdAutocompleteItemScopeDirective.$inject = ["$compile", "$mdUtil"];
angular
.module('material.components.autocomplete')
.controller('MdHighlightCtrl', MdHighlightCtrl);
function MdHighlightCtrl ($scope, $element, $attrs) {
this.init = init;
function init (termExpr, unsafeTextExpr) {
var text = null,
regex = null,
flags = $attrs.mdHighlightFlags || '',
watcher = $scope.$watch(function($scope) {
return {
term: termExpr($scope),
unsafeText: unsafeTextExpr($scope)
};
}, function (state, prevState) {
if (text === null || state.unsafeText !== prevState.unsafeText) {
text = angular.element('<div>').text(state.unsafeText).html()
}
if (regex === null || state.term !== prevState.term) {
regex = getRegExp(state.term, flags);
}
$element.html(text.replace(regex, '<span class="highlight">$&</span>'));
}, true);
$element.on('$destroy', function () { watcher(); });
}
function sanitize (term) {
return term && term.replace(/[\\\^\$\*\+\?\.\(\)\|\{}\[\]]/g, '\\$&');
}
function getRegExp (text, flags) {
var str = '';
if (flags.indexOf('^') >= 1) str += '^';
str += text;
if (flags.indexOf('$') >= 1) str += '$';
return new RegExp(sanitize(str), flags.replace(/[\$\^]/g, ''));
}
}
MdHighlightCtrl.$inject = ["$scope", "$element", "$attrs"];
angular
.module('material.components.autocomplete')
.directive('mdHighlightText', MdHighlight);
/**
* @ngdoc directive
* @name mdHighlightText
* @module material.components.autocomplete
*
* @description
* The `md-highlight-text` directive allows you to specify text that should be highlighted within
* an element. Highlighted text will be wrapped in `<span class="highlight"></span>` which can
* be styled through CSS. Please note that child elements may not be used with this directive.
*
* @param {string} md-highlight-text A model to be searched for
* @param {string=} md-highlight-flags A list of flags (loosely based on JavaScript RexExp flags).
* #### **Supported flags**:
* - `g`: Find all matches within the provided text
* - `i`: Ignore case when searching for matches
* - `$`: Only match if the text ends with the search term
* - `^`: Only match if the text begins with the search term
*
* @usage
* <hljs lang="html">
* <input placeholder="Enter a search term..." ng-model="searchTerm" type="text" />
* <ul>
* <li ng-repeat="result in results" md-highlight-text="searchTerm">
* {{result.text}}
* </li>
* </ul>
* </hljs>
*/
function MdHighlight ($interpolate, $parse) {
return {
terminal: true,
controller: 'MdHighlightCtrl',
compile: function mdHighlightCompile(tElement, tAttr) {
var termExpr = $parse(tAttr.mdHighlightText);
var unsafeTextExpr = $interpolate(tElement.html());
return function mdHighlightLink(scope, element, attr, ctrl) {
ctrl.init(termExpr, unsafeTextExpr);
};
}
};
}
MdHighlight.$inject = ["$interpolate", "$parse"];
ng.material.components.autocomplete = angular.module("material.components.autocomplete");
|
var engine = require("../engine");
var manager = require("../manager");
// TODO: This should be part of 'set', see nextstatus.js
module.exports = engine.promiseCommand(function(doc,cb) {
return manager.requireRelativeDoc(doc).then(function(doc) {
if (typeof doc === "undefined") {
throw new engine.CommandError("Not in a stew project.");
}
return doc.properties().then(function(props) {
if (props.decStatus) {
props.decStatus();
return props.save().then(function() {
return props.status();
});
} else {
throw new engine.CommandError("Please specify a document.");
}
});
});
},function(doc) {
if ((typeof doc === "undefined") ||
((typeof doc === "object") && (typeof doc.ensurePrimary === "function")) ||
(typeof doc === "string")) {
return [doc];
}
throw new engine.CommandError("Invalid document argument.");
});
|
var settings = require('../settings');
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
module.exports = new Db(settings.db, new Server(settings.host, Connection.DEFAULT_PORT),{});
|
process.env.NODE_ENV = 'test'
const chai = require('chai')
const chaiHttp = require('chai-http')
const server = require('../server')
chai.use(chaiHttp)
describe('Next-Metro API', () => {
describe('/GET trains', (done) => {
it('should return a list of all the train preditions', (done) => {
chai.request(server)
.get('/trains')
.end((err, res) => {
chai.expect(res).to.have.status(200)
done()
})
})
})
})
|
import CImage from './c-image'
export default CImage
|
const move = require("move");
const utilitiy = require("utility");
module.exports = {
attack: function (creep) {
if (!utilitiy.bodyContains(creep, ATTACK)) {
return false
}
if (creep.room.memory.targetHostile === void 0) {
return false;
}
let hostile = Game.getObjectById(creep.room.memory.targetHostile);
if (move.moveToObject(creep, hostile) !== OK) {
return false;
}
let target = Game.getObjectById(creep.memory.moveTarget);
let result = creep.attack(target);
return result === OK || result === ERR_NOT_IN_RANGE;
},
harvest: function (creep) {
if (!utilitiy.bodyContains(creep, WORK)) {
return false
}
let sources = creep.room.find(FIND_SOURCES);
if (sources.length === 0) {
return false;
}
sources = _(sources).sortByOrder(s => s.energy, "desc")
.take(Memory.moveCandidate)
.value();
if (move.moveToObject(creep, sources) !== OK) {
return false;
}
let target = Game.getObjectById(creep.memory.moveTarget);
let result = creep.harvest(target);
return result === OK || result === ERR_NOT_IN_RANGE;
},
withdraw: function (creep) {
if (!utilitiy.bodyContains(creep, CARRY)) {
return false
}
let stores = creep.room.find(FIND_STRUCTURES,
{ filter: s =>
(s.structureType === STRUCTURE_STORAGE ||
s.structureType === STRUCTURE_CONTAINER) &&
s.store[RESOURCE_ENERGY] > 0
});
if (stores.length === 0) {
stores = creep.room.find(FIND_STRUCTURES,
{ filter: s => (s.structureType === STRUCTURE_SPAWN ||
s.structureType === STRUCTURE_EXTENSION) &&
s.energy > 0
});
if (stores.length === 0) {
return false;
}
}
let store = _.max(stores, s => {
if (_.isNumber(s.energy)) {
return s.energy;
}
else {
return s.store[RESOURCE_ENERGY]
}});
if (move.moveToObject(creep, store) !== OK) {
return false;
}
let target = Game.getObjectById(creep.memory.moveTarget);
let result = creep.withdraw(target, RESOURCE_ENERGY);
return result === OK || result === ERR_NOT_IN_RANGE;
},
pickup: function (creep) {
if (!utilitiy.bodyContains(creep, CARRY)) {
return false
}
let sources = creep.room.find(FIND_DROPPED_RESOURCES,
{ filter: s =>
s.resourceType === RESOURCE_ENERGY
});
if (sources.length === 0) {
return false;
}
sources = _(sources).sortByOrder(s => s.amount, "desc")
.take(Memory.moveCandidate)
.value();
if (move.moveToObject(creep, sources) !== OK) {
return false;
}
let target = Game.getObjectById(creep.memory.moveTarget);
let result = creep.pickup(target);
return result === OK || result === ERR_NOT_IN_RANGE;
},
transfer: function (creep) {
let stores = creep.room.find(FIND_MY_STRUCTURES,
{ filter: s => (s.structureType === STRUCTURE_SPAWN ||
s.structureType === STRUCTURE_EXTENSION) &&
s.energy < s.energyCapacity
});
if (stores.length === 0) {
stores = creep.room.find(FIND_STRUCTURES,
{ filter: s =>
(s.structureType === STRUCTURE_STORAGE ||
s.structureType === STRUCTURE_CONTAINER) &&
_.sum(s.store) < s.storeCapacity
});
if (stores.length === 0) {
return false;
}
}
stores = _(stores).sortByOrder(s => {
if (_.isNumber(s.energy)) {
return s.energyCapacity - s.energy;
}
else {
return s.storeCapacity - _.sum(s.store);
}
}, "desc")
.take(Memory.moveCandidate)
.value();
if (move.moveToObject(creep, stores) !== OK) {
return false;
}
let target = Game.getObjectById(creep.memory.moveTarget);
let result = creep.transfer(target, RESOURCE_ENERGY);
return result === OK || result === ERR_NOT_IN_RANGE;
},
transferToTower: function (creep) {
let towers = creep.room.find(FIND_MY_STRUCTURES,
{ filter: t => t.structureType === STRUCTURE_TOWER &&
t.energy < t.energyCapacity
});
if (towers.length === 0) {
return false;
}
towers = _(towers).sortByOrder(t => t.energyCapacity - t.energy, "desc")
.take(Memory.moveCandidate)
.value();
if (move.moveToObject(creep, towers) !== OK) {
return false;
}
let target = Game.getObjectById(creep.memory.moveTarget);
let result = creep.transfer(target, RESOURCE_ENERGY);
return result === OK || result === ERR_NOT_IN_RANGE;
},
build: function (creep) {
if (!utilitiy.bodyContains(creep, WORK)) {
return false
}
let site = null;
if (!_.isUndefined(creep.room.memory.buildTarget)) {
site = Game.getObjectById(creep.room.memory.buildTarget);
}
if (site === null)
{
let sites = creep.room.find(FIND_MY_CONSTRUCTION_SITES);
if (sites.length === 0) {
return false;
}
site = _.max(sites, s => s.progressTotal - s.progress);
creep.room.memory.buildTarget = site.id;
}
let result = creep.build(site);
if (result === ERR_NOT_IN_RANGE) {
return move.moveToObject(creep, site) === OK;
}
return result === OK;
},
repair: function (creep) {
if (!utilitiy.bodyContains(creep, WORK)) {
return false
}
let structure = null;
if (!_.isUndefined(creep.memory.repairTarget)) {
structure = Game.getObjectById(creep.memory.repairTarget);
}
if (structure === null || structure.hits === structure.hitsMax) {
let structures = creep.room.find(FIND_STRUCTURES,
{ filter: s =>
s.structureType !== STRUCTURE_WALL &&
s.structureType !== STRUCTURE_RAMPART &&
s.hits < s.hitsMax
});
if (structures.length === 0) {
structures = creep.room.find(FIND_STRUCTURES,
{ filter: s =>
s.structureType === STRUCTURE_WALL &&
s.hits < s.hitsMax
});
if (structures.length === 0) {
return false;
}
}
structure = _.max(structures, s => s.hitsMax - s.hits);
creep.memory.repairTarget = structure.id;
}
let result = creep.repair(structure);
if (result === ERR_NOT_IN_RANGE) {
return move.moveToObject(creep, structure) === OK;
}
return result === OK;
},
repairRoad: function (creep) {
if (!utilitiy.bodyContains(creep, WORK)) {
return false
}
let structure = null;
if (!_.isUndefined(creep.memory.repairTarget)) {
structure = Game.getObjectById(creep.memory.repairTarget);
}
if (structure === null || structure.hits === structure.hitsMax) {
let structures = creep.room.find(FIND_STRUCTURES,
{ filter: s =>
s.structureType === STRUCTURE_ROAD &&
s.hits < s.hitsMax
});
if (structures.length === 0) {
return false;
}
let structure = _.min(structures, s => s.hits);
creep.memory.repairTarget = structure.id;
}
let result = creep.repair(structure);
if (result === ERR_NOT_IN_RANGE) {
return move.moveToObject(creep, structure) === OK;
}
return result === OK;
},
repairWall: function (creep) {
if (!utilitiy.bodyContains(creep, WORK)) {
return false
}
let structure = null;
if (!_.isUndefined(creep.memory.repairTarget)) {
structure = Game.getObjectById(creep.memory.repairTarget);
}
if (structure === null || structure.hits === structure.hitsMax) {
let structures = creep.room.find(FIND_STRUCTURES,
{ filter: s =>
(s.structureType === STRUCTURE_WALL ||
s.structureType === STRUCTURE_RAMPART && s.my) &&
s.hits < s.hitsMax
});
if (structures.length === 0) {
return false;
}
let structure = _.min(structures, s => s.hits);
creep.memory.repairTarget = structure.id;
}
let result = creep.repair(structure);
if (result === ERR_NOT_IN_RANGE) {
return move.moveToObject(creep, structure) === OK;
}
return result === OK;
},
repairTower: function (creep) {
if (!utilitiy.bodyContains(creep, WORK)) {
return false
}
let structure = null;
if (!_.isUndefined(creep.memory.repairTarget)) {
structure = Game.getObjectById(creep.memory.repairTarget);
}
if (structure === null || structure.hits === structure.hitsMax) {
let structures = creep.room.find(FIND_STRUCTURES,
{
filter: s =>
s.structureType === STRUCTURE_TOWER &&
s.hits < s.hitsMax
});
if (structures.length === 0) {
return false;
}
let structure = _.min(structures, s => s.hits);
creep.memory.repairTarget = structure.id;
}
let result = creep.repair(structure);
if (result === ERR_NOT_IN_RANGE) {
return move.moveToObject(creep, structure) === OK;
}
return result === OK;
},
upgrade: function (creep) {
if (!utilitiy.bodyContains(creep, WORK)) {
return false
}
let controller = creep.room.controller;
if (controller === null) {
return false;
}
let result = creep.upgradeController(controller);
if (result === ERR_NOT_IN_RANGE) {
return move.moveToObject(creep, controller) === OK;
}
return result === OK;
},
travel: function (creep, roomName) {
return move.moveToRoom(creep, roomName) === OK;
},
claim: function (creep) {
if (!utilitiy.bodyContains(creep, CLAIM)) {
return false
}
let controller = creep.room.controller;
if (controller === null) {
return false;
}
let result = creep.claimController(controller);
if (result === ERR_NOT_IN_RANGE) {
return move.moveToObject(creep, controller) === OK;
}
let resultOk = result === OK;
if (resultOk) {
creep.memory.done = true;
}
return resultOk;
},
};
|
'use strict';
const path = require('path');
const simpleGit = require('simple-git');
const git = simpleGit(path.join(__dirname, '..'));
const format = require('stringformat');
const fs = require('fs');
const utils = {
formatPrs: commits => {
const result = [];
commits.forEach(commit => {
const commitMessages = commit.message.split('Merge pull request');
const isPr = commitMessages.length > 1;
const isSquashedPr = !!commit.message.match(/(.*?)\(#(.*?)\)/g);
let commitMessage;
let prNumber;
if (isPr) {
const split = commitMessages[1].split('from');
prNumber = split[0].trim().replace('#', '');
commitMessage = commit.body;
result.push(
format(
'- [#{0}](https://github.com/opencomponents/oc/pull/{0}) {1}',
prNumber,
commitMessage
)
);
} else if (isSquashedPr) {
const lines = commit.message.split('\n');
const commitLine = lines[0];
const prNumberStartIndex = commitLine.lastIndexOf(' (');
const prNumberEndIndex = commitLine.lastIndexOf(')');
prNumber = commitLine.substr(
prNumberStartIndex + 3,
prNumberEndIndex - prNumberStartIndex - 3
);
commitMessage = commitLine.substr(0, prNumberStartIndex).trim();
result.push(
format(
'- [#{0}](https://github.com/opencomponents/oc/pull/{0}) {1}',
prNumber,
commitMessage
)
);
}
});
return result;
},
getFirstCommitHash: cb => {
git.log(['--reverse'], (err, changes) => {
if (err) {
cb(err, null);
}
cb(null, changes.latest.hash);
});
},
tagIntervals: (tags, hash) => {
const logIntervals = [];
for (let i = tags.length; i > 0; i--) {
const logInterval = {
to: tags[i - 1],
from: hash
};
if (i >= 2) {
logInterval.from = tags[i - 2];
}
logIntervals.push(logInterval);
}
fs.writeFileSync(
path.join(__dirname, '../logintervals.md'),
JSON.stringify(logIntervals)
);
return logIntervals;
}
};
module.exports = {
// Fetches PRs
prs: (options, cb) => {
const opts = Object.assign({}, options, {
format: {
message: '%s',
body: '%b'
}
});
git.log(opts, (err, changes) => {
if (err) {
cb(err, null);
}
cb(null, utils.formatPrs(changes.all));
});
},
// Fetches all tags
tags: cb => {
utils.getFirstCommitHash((err, hash) => {
git.tags((err, tags) => {
if (err) {
cb(err, null);
}
cb(null, utils.tagIntervals(tags.all, hash));
});
});
}
};
|
const gulp = require('gulp');
const path = require('path');
const paths = require('../paths');
module.exports = {
images() {
return gulp.src(paths.content.assets.images)
.pipe(gulp.dest(paths.compiled.assets.images));
},
fonts() {
return gulp.src(paths.content.assets.fonts)
.pipe(gulp.dest(paths.compiled.assets.fonts));
},
resources() {
return gulp.src(paths.content.assets.resources)
.pipe(gulp.dest(paths.compiled.assets.resources));
},
favicon() {
return gulp.src(paths.content.assets.favicon)
.pipe(gulp.dest(paths.compiled.path));
},
compiledToDist() {
return gulp.src(path.join(paths.compiled.path, '**/*'))
.pipe(gulp.dest(paths.dist.path));
}
};
|
import IGVGraphics from "../igv-canvas.js";
function paintAxis(ctx, pixelWidth, pixelHeight) {
var x1,
x2,
y1,
y2,
a,
b,
reference,
shim,
font = {
'font': 'normal 10px Arial',
'textAlign': 'right',
'strokeStyle': "black"
};
if (undefined === this.dataRange || undefined === this.dataRange.max || undefined === this.dataRange.min) {
return;
}
IGVGraphics.fillRect(ctx, 0, 0, pixelWidth, pixelHeight, {'fillStyle': "rgb(255, 255, 255)"});
reference = 0.95 * pixelWidth;
x1 = reference - 8;
x2 = reference;
//shim = 0.5 * 0.125;
shim = .01;
y1 = y2 = shim * pixelHeight;
a = {x: x2, y: y1};
// tick
IGVGraphics.strokeLine(ctx, x1, y1, x2, y2, font);
IGVGraphics.fillText(ctx, prettyPrint(this.dataRange.max), x1 + 4, y1 + 12, font);
//shim = 0.25 * 0.125;
y1 = y2 = (1.0 - shim) * pixelHeight;
b = {x: x2, y: y1};
// tick
IGVGraphics.strokeLine(ctx, x1, y1, x2, y2, font);
IGVGraphics.fillText(ctx, prettyPrint(this.dataRange.min), x1 + 4, y1 - 4, font);
IGVGraphics.strokeLine(ctx, a.x, a.y, b.x, b.y, font);
function prettyPrint(number) {
// if number >= 100, show whole number
// if >= 1 show 1 significant digits
// if < 1 show 2 significant digits
if (number === 0) {
return "0";
} else if (Math.abs(number) >= 10) {
return number.toFixed();
} else if (Math.abs(number) >= 1) {
return number.toFixed(1);
} else {
return number.toFixed(2);
}
}
}
export default paintAxis;
|
const path = require("path");
const co = require("co");
const { cacheDir } = require("./config");
const { exists, mkdir, exec } = require("./helpers");
module.exports = co.wrap(function*(hash) {
const cachePath = path.join(cacheDir, hash);
const cachePathExists = yield exists(cachePath);
if (!cachePathExists) {
throw new Error("Current node_modules is not cached.");
}
});
|
import React from 'react';
import { shallow } from 'enzyme';
import Book from '../../../components/Books/Book';
const props = {
book: {
title: 'Magnolia Table: A Collection of Recipes for Gathering',
author: 'Joanna Gaines',
description: 'Book for test',
subject: 'Recipe',
imageURL: 'https://images-na.3,200_.jpg',
quantity: 6,
favCount: 2,
upvotes: 1,
downvotes: 2,
bookReviews: [
{
id: 3,
review: 'I love it',
createdAt: '2018-06-27T12:18:05.917Z',
updatedAt: '2018-06-27T12:18:05.917Z',
userId: 12,
bookId: 98,
userReviews: {
id: 12,
firstName: 'Amarachi',
lastName: 'Agbo',
email: 'amarachukwu.agbo@gmail.com',
role: 'User',
imageURL: null,
createdAt: '2018-06-27T12:01:52.036Z',
updatedAt: '2018-06-27T12:01:52.036Z',
},
},
],
},
};
describe('<Book>', () => {
it('should render correctly', () => {
const tree = shallow(<Book { ...props }/>);
expect(tree).toMatchSnapshot();
});
});
|
/**
* Module dependencies
*/
var _ = require('lodash')
, path = require('path')
, util = require('util')
, consolidate = require('./consolidate');
/**
* Marshal relevant parts of sails global configuration,
* issue deprecation notices, etc.
*
* @param {Sails} sails
*/
module.exports = function configure ( sails ) {
if (sails.config.viewEngine) {
sails.log.warn('The `config.viewEngine` config has been deprecated in favor of `config.views.engine`.');
sails.log.warn('It has been automatically migrated, but you\'ll continue to see this warning until you change your configuration files.');
sails.config.views.engine = sails.config.viewEngine;
}
// Normalize view engine config
if (typeof sails.config.views.engine === 'string') {
var viewExt = sails.config.views.engine;
sails.config.views.engine = {
ext: viewExt
};
}
// Ensure valid config
if (! (sails.config.views.engine && sails.config.views.engine.ext) ) {
sails.log.error('Invalid view engine configuration. `config.views.engine` should');
sails.log.error('be set to either a `string` or an `object` with the following properties:');
sails.log.error(' {');
sails.log.error(' ext: <string>, // the file extension');
sails.log.error(' fn: <function> // the template engine render function');
sails.log.error(' }');
sails.log.error('For example: {ext:"html", fn: require("consolidate").swig}');
sails.log.error('For details: http://expressjs.com/api.html#app.engine');
throw new Error('Invalid view engine configuration.');
}
// Try to load view module if a function wasn't specified directly
if ( !sails.config.views.engine.fn ) {
var appDependenciesPath;
var fn;
appDependenciesPath = path.join(
sails.config.appPath,
'node_modules'
);
try {
fn = consolidate(appDependenciesPath)[sails.config.views.engine.ext];
if ( !_.isFunction(fn) ) {
sails.log.error(util.format('Invalid view engine (%s)-- are you sure it supports `consolidate`?', sails.config.views.engine.ext));
throw new Error();
}
}
catch (e) {
sails.log.error('Your configured server-side view engine (' + sails.config.views.engine.ext + ') could not be found.');
sails.log.error('Usually, this just means you need to install a dependency.');
sails.log.error('To install ' + sails.config.views.engine.ext + ', run: `npm install ' + sails.config.views.engine.ext + ' --save`');
sails.log.error('Otherwise, please change your `engine` configuration in config/views.js.');
throw e;
}
// Save reference to view rendering function
sails.config.views.engine.fn = fn;
sails.log.silly('Configured view engine, `' + sails.config.views.engine.ext + '`');
}
// Let user know that a leading . is not required in the viewEngine option and then fix it
if (sails.config.views.engine.ext[0] === '.') {
sails.log.warn('A leading `.` is not required in the views.engine option. Removing it for you...');
sails.config.views.engine.ext = sails.config.views.engine.ext.substr(1);
}
// Custom layout location
// (if string specified, it's used as the relative path from the views folder)
// (if not string, but truthy, relative path from views folder defaults to ./layout.*)
// (if falsy, don't use layout)
if ( !_.isString(sails.config.views.layout) && sails.config.views.layout ) {
sails.config.views.layout = 'layout.' + sails.config.views.engine.ext;
}
if ( sails.config.views.engine.ext !== 'ejs' && sails.config.views.engine.ext !== 'handlebars' && sails.config.views.layout ) {
sails.log.warn('Sails\' built-in layout support only works with the `ejs` and `handlebars` view engines.');
sails.log.warn('You\'re using `'+ sails.config.views.engine.ext +'`.');
sails.log.warn('Ignoring `sails.config.views.layout`...');
}
};
|
export { default } from './PostgresqlPlainWordmark'
|
import React, {PropTypes} from 'react'
class LoadingDots extends React.Component {
constructor (props, context) {
super(props, context)
this.state = {
frame: 1
}
}
componentDidMount () {
this.interval = setInterval(() => {
this.setState({
frame: this.state.frame + 1
})
}, this.props.interval)
}
componentWillUnmount () {
clearInterval(this.interval)
}
render () {
let dots = this.state.frame % (this.props.dots + 1)
let text = ''
while (dots > 0) {
text += '.'
dots--
}
return <span {...this.props}>{text}</span>
}
}
LoadingDots.defaultProps = {
interval: 300,
dots: 3
}
LoadingDots.propTypes = {
interval: PropTypes.number,
dots: PropTypes.number
}
export default LoadingDots
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "M13 9V4H6v16h12V9h-5zm3 8.06L14 16v1c0 .55-.45 1-1 1H9c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h4c.55 0 1 .45 1 1v1l2-1.06v4.12z",
opacity: ".3"
}, "0"), /*#__PURE__*/_jsx("path", {
d: "M14 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8l-6-6zM6 20V4h7v5h5v11H6zm8-6 2-1.06v4.12L14 16v1c0 .55-.45 1-1 1H9c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h4c.55 0 1 .45 1 1v1z"
}, "1")], 'VideoFileTwoTone');
|
'use strict';
/* Filters */
angular.module('odyssey.filters', []).
filter('interpolate', ['version', function(version) {
return function(text) {
return String(text).replace(/\%VERSION\%/mg, version);
}
}]);
|
/* Simplifr, v0.2.1 */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.simplifr = global.simplifr || {})));
}(this, function (exports) { 'use strict';
function defaults(){
return {
root: 'root',
dilimiter: '.'
}
}
function simplify(obj, dilimiter, root){
dilimiter = dilimiter || defaults().dilimiter;
root = root || defaults().root;
return simplifyNode({}, root, obj, dilimiter);
}
function add(data, path, obj, dilimiter){
dilimiter = dilimiter || defaults().dilimiter;
var node = data[path];
if (typeof node === 'undefined' || typeof node === 'null')
return data;
if (node.type === 'array') {
var max = !node.childs.length ? -1 : Math.max.apply(null, node.childs);
if (!isArray(obj)) obj = [obj];
obj.forEach(function(d){
node.childs.push(++max);
simplifyNode(data, path + dilimiter + max, d, dilimiter);
});
}
else if (node.type === 'object') {
var keys = Object.keys(obj);
keys.forEach(function(key){
if (node.childs.indexOf(key) > -1) return;
node.childs.push(key);
simplifyNode(data, path + dilimiter + key, obj[key], dilimiter);
});
}
return data;
}
function update(data, path, obj, dilimiter){
reset(data, path, dilimiter);
simplifyNode(data, path, obj, dilimiter);
return data;
}
function remove(data, path, dilimiter){
dilimiter = dilimiter || defaults().dilimiter;
var pathSeq = path.split(dilimiter);
var key = pathSeq.pop();
var parentNode = pathSeq.length ? data[pathSeq.join(dilimiter)] : data;
if (parentNode.type === 'array') key = +key;
var idx = parentNode.childs.indexOf(key);
if (idx > -1) parentNode.childs.splice(idx, 1);
removeChildNode(data, path, dilimiter);
return data;
}
function reset(data, path, dilimiter){
dilimiter = dilimiter || defaults().dilimiter;
removeChildNode(data, path, dilimiter);
data[path] = null;
return data;
}
function desimplify(data, path, dilimiter){
dilimiter = dilimiter || defaults().dilimiter;
path = path || defaults().root;
return dive(path);
function dive(path){
var obj;
var node = data[path];
if (typeof node === 'undefined' || typeof node === 'null')
return node;
if (node.type === 'array') {
obj = [];
node.childs.forEach(function(key){
obj.push(dive(path + dilimiter + key));
});
}
else if (node.type === 'object') {
obj = {};
node.childs.forEach(function(key){
obj[key] = dive(path + dilimiter + key);
});
}
else obj = node;
return obj;
}
}
function join(){
if (!arguments.length) return;
var fargs = Array.prototype.filter.call(arguments, function(v){ return v != undefined && v != '' });
return Array.prototype.join.call(fargs, '.');
}
function simplifyNode(data, path, obj, dilimiter){
dilimiter = dilimiter || defaults().dilimiter;
dive(obj, path);
return data;
function dive(obj, path){
data[path] = {
type: 'object',
childs: []
};
if (isArray(obj)) {
data[path].type = 'array';
for (var i = -1, l = obj.length; ++i < l;) {
data[path].childs.push(i);
dive(obj[i], path + dilimiter + i);
}
}
else if (isObject(obj)) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
data[path].childs.push(key);
dive(obj[key], path + dilimiter + key);
}
}
}
else data[path] = obj;
return data;
}
}
function removeChildNode(data, path, dilimiter){
dilimiter = dilimiter || defaults().dilimiter;
var node = data[path];
if (typeof node === 'undefined' || typeof node === 'null')
return data;
if (node.type === 'array' || node.type === 'object') {
node.childs.forEach(function(key){
removeChildNode(data, path + dilimiter + key);
});
}
delete data[path];
return data;
}
function isArray(_) {
return Object.prototype.toString.call(_) === '[object Array]';
}
function isObject(_) {
return Object.prototype.toString.call(_) === '[object Object]';
}
exports.simplify = simplify;
exports.add = add;
exports.update = update;
exports.remove = remove;
exports.reset = reset;
exports.desimplify = desimplify;
exports.join = join;
}));
|
// The contents of this file will be executed before any of
// your view controllers are ever executed, including the index.
// You have access to all functionality on the `Alloy` namespace.
//
// This is a great place to do any initialization for your app
// or create any global variables/functions that you'd like to
// make available throughout your app. You can easily make things
// accessible globally by attaching them to the `Alloy.Globals`
// object. For example:
//
// Alloy.Globals.someGlobalFunction = function(){};
Alloy.Globals.windowStack = require('ti-window-stack').createWindowStack();
|
var EventProxy = require('eventproxy'),
models = require('../models'),
Note = models.Note,
Notebook = models.Notebook;
/**
* @desc: 新建一个笔记本
* @param {String} title: 笔记标题
* @param {String} author: 笔记作者
* @param {Boolean} private: 是否
* @param {Function} callback: 查询回调函数
*/
exports.newAndSave = function(title, author, private, desc, callback) {
var notebook = new Notebook();
notebook.title = title;
notebook.author = author;
notebook.private = private;
notebook.desc = desc;
notebook.save(callback);
};
/**
* @desc: 根据笔记本id查询所有笔记
* @param {String} id: 笔记本id
* @param {Function} callback: 查询回调函数
*/
exports.getNotebookById = function(id, callback) {
if ( !id )
return callback();
Note.find({notebook: id}, callback);
};
/**
* @desc: 根据笔记本标题查询笔记本
* @param {String} title: 笔记本标题
* @param {Function} callback: 查询回调函数
*/
exports.getNotebookByTitle = function(title, callback) {
Notebook.find({title: title}, callback);
};
/**
* @desc: 根据笔记本标题查询笔记本
* @param {String} title: 笔记本标题
* @param {Function} callback: 查询回调函数
*/
exports.getBookById = function(id, callback) {
Notebook.findOne({_id: id}, callback);
};
exports.getLastNotebooks = function(count, callback) {
Notebook.find({deleted: false}).limit(count).sort({create_at: -1}).exec(callback);
}
exports.countAllBook = function(callback) {
Notebook.count({deleted: false}, callback);
}
|
'use strict';
var utils = require('../lib/utils');
var should = require('should');
describe('Tests merge helper', function () {
it('object should have all properties', function () {
var objA = {'a': 'A', 'b': 'B'},
objB = {'c': 'C', 'd': 'D'},
objC = utils.merge(objA, objB);
objC.should.have.property('a', 'A');
objC.should.have.property('b', 'B');
objC.should.have.property('c', 'C');
objC.should.have.property('d', 'D');
});
});
describe('Tests array clean function', function () {
it('extraneous nested arrays should be removed', function () {
var obj = {
element: new Array
};
obj.element.push({
foo: 'bar'
});
utils.arrayClean(obj).element.should.have.property('foo', 'bar');
});
});
|
'use strict';
const countryInfo = require('../metadata/countryInfo');
const logger = require( 'pelias-logger' ).get( 'geonames' );
function error( message ){
logger.error( '\n ' + message + '\n' );
process.exit( 1 );
}
function validateISOCode( input ){
var isocode = ( 'string' === typeof input ) ? input.toUpperCase() : null;
if( !isocode || ( isocode !== 'ALL' && !( isocode in countryInfo ) ) ){
const message = `${isocode} is an invalid ISO code. either use \'ALL\'` +
`or list available ISO codes with \`npm run countryCodes\``;
error( message);
}
return isocode;
}
module.exports = validateISOCode;
|
var Grid, assert, indices1, indices2, vows;
var __indexOf = Array.prototype.indexOf || function(item) {
for (var i = 0, l = this.length; i < l; i++) {
if (this[i] === item) return i;
}
return -1;
};
vows = require('vows');
Grid = require('../grid-lookup.js');
assert = require('assert');
indices1 = [0, 19, 19 * 20, 20 * 20 - 1];
indices2 = [6 + 8 * 20, 7 + 8 * 20, 8 + 8 * 20, 9 + 8 * 20, 10 + 8 * 20, 6 + 9 * 20, 7 + 9 * 20, 8 + 9 * 20, 9 + 9 * 20, 10 + 9 * 20, 6 + 10 * 20, 7 + 10 * 20, 8 + 10 * 20, 9 + 10 * 20, 10 + 10 * 20];
vows.describe('Grid').addBatch({
'A grid': {
topic: new Grid(1000, 1000, 20, 20),
'inserts objects': function(grid) {
var i, _i, _j, _len, _len2, _results;
grid.insert('an id', 995, 995, 10, 10);
grid.insert('another id', 345, 433, 192, 88);
for (_i = 0, _len = indices1.length; _i < _len; _i++) {
i = indices1[_i];
assert.include(grid.grid[i], 'an id');
}
_results = [];
for (_j = 0, _len2 = indices2.length; _j < _len2; _j++) {
i = indices2[_j];
_results.push(assert.include(grid.grid[i], 'another id'));
}
return _results;
},
'has no incorrect insertions': function(grid) {
var i, _ref, _results;
_results = [];
for (i = 0, _ref = 20 * 20; 0 <= _ref ? i < _ref : i > _ref; 0 <= _ref ? i++ : i--) {
if (__indexOf.call(indices1.concat(indices2), i) >= 0) {
continue;
}
_results.push(assert.isEmpty(grid.grid[i]));
}
return _results;
},
'finds objects by range': function(grid) {
var found;
found = grid.rangeSearch(49, 49, 251, 351);
assert.include(found, 'an id');
return assert.include(found, 'another id');
},
'give no false positives for range search': function(grid) {
var found;
found = grid.rangeSearch(50, 50, 1000, 349);
return assert.isEmpty(found);
},
'deletes objects': function(grid) {
var i, _i, _len, _ref, _results;
grid["delete"]('an id', 995, 995, 10, 10);
grid["delete"]('another id', 345, 433, 192, 88);
_ref = indices1.concat(indices2);
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
i = _ref[_i];
_results.push(assert.isUndefined(grid.grid[i].pop()));
}
return _results;
}
}
})["export"](module);
|
/**
* Created by Alex on 8/17/2014.
*/
module.exports = function () {
return {
};
}();
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import TableContext from './TableContext';
export default class TableCell extends Component {
static propTypes = {
children: PropTypes.node,
renderCell: PropTypes.func,
store: PropTypes.object,
};
_handleClick = () => {
const { store } = this.props;
if (store && store.record) {
this.tableContext.toggleSelectedKey(store.record.key);
}
};
_renderChildren(children, other) {
return (
<td {...other} onClick={this._handleClick}>
{children}
</td>
);
}
_render = (tableContext) => {
this.tableContext = tableContext;
const { renderCell, store, children, ...other } = this.props;
if (!renderCell) return this._renderChildren(children, other);
return renderCell(
store,
(render) =>
render ? (
this._renderChildren(render(), other)
) : (
<td style={{ padding: 0 }} />
)
// (render) => (render ? this._renderChildren(render(), other) : null)
);
};
render() {
return <TableContext.Consumer>{this._render}</TableContext.Consumer>;
}
}
|
/* @flow */
import { warn } from '../util'
export default {
name: 'i18n',
functional: true,
props: {
tag: {
type: String
},
path: {
type: String,
required: true
},
locale: {
type: String
},
places: {
type: [Array, Object]
}
},
render (h: Function, { data, parent, props, slots }: Object) {
const { $i18n } = parent
if (!$i18n) {
if (process.env.NODE_ENV !== 'production') {
warn('Cannot find VueI18n instance!')
}
return
}
const { path, locale, places } = props
const params = slots()
const children = $i18n.i(
path,
locale,
onlyHasDefaultPlace(params) || places
? useLegacyPlaces(params.default, places)
: params
)
const tag = props.tag || 'span'
return tag ? h(tag, data, children) : children
}
}
function onlyHasDefaultPlace (params) {
let prop
for (prop in params) {
if (prop !== 'default') { return false }
}
return Boolean(prop)
}
function useLegacyPlaces (children, places) {
const params = places ? createParamsFromPlaces(places) : {}
if (!children) { return params }
// Filter empty text nodes
children = children.filter(child => {
return child.tag || child.text.trim() !== ''
})
const everyPlace = children.every(vnodeHasPlaceAttribute)
if (process.env.NODE_ENV !== 'production' && everyPlace) {
warn('`place` attribute is deprecated in next major version. Please switch to Vue slots.')
}
return children.reduce(
everyPlace ? assignChildPlace : assignChildIndex,
params
)
}
function createParamsFromPlaces (places) {
if (process.env.NODE_ENV !== 'production') {
warn('`places` prop is deprecated in next major version. Please switch to Vue slots.')
}
return Array.isArray(places)
? places.reduce(assignChildIndex, {})
: Object.assign({}, places)
}
function assignChildPlace (params, child) {
if (child.data && child.data.attrs && child.data.attrs.place) {
params[child.data.attrs.place] = child
}
return params
}
function assignChildIndex (params, child, index) {
params[index] = child
return params
}
function vnodeHasPlaceAttribute (vnode) {
return Boolean(vnode.data && vnode.data.attrs && vnode.data.attrs.place)
}
|
var View = require('view');
var template = require('./template');
var dom = require('dom');
var BillTransformer = require('./BillSection');
var TextSection = require('text-section');
var move = require('move');
function DiffView() {
if (!this instanceof DiffView) {
return new DiffView();
}
View.call(this, template);
this.sections = [];
}
module.exports = DiffView;
View(DiffView);
/**
* Change bill content for the moment only when click in some step.
*
* @param {StepSchema} currentStep The Step Schema to show up in the view.
* @param {StepSchema} previousStep Previous Step for calculateDiff difference.
*/
DiffView.prototype.changeBillContent = function (currentStep, previousStep) {
//TODO: the only purpose of have 2 steps in the same view, is to be compare them.
// Maybe this should be resolved outside of this view.
//Here should append the current text, and anchor the differences, calculated.
var section = new BillTransformer();
var currentParagraph = section.transformToSection(currentStep);
if (previousStep) {
var previousParagraph = section.transformToSection(previousStep);
currentParagraph = section.calculateDiff(currentParagraph, previousParagraph);
}
this.showBillText(currentParagraph);
};
/**
* Move the main text to the left.
*/
DiffView.prototype.collapseLeftText = function () {
move('#bill-diff .text')
.to(-250, 0)
.duration('1.0s')
.end();
dom('#bill-diff .text p').addClass('low-point');
};
/**
* Center the main text in the middle of the screen
*/
DiffView.prototype.centerText = function () {
move('#bill-diff .text')
.to(0, 0)
.duration('1.0s')
.end();
dom('#bill-diff .text p').removeClass('low-point');
};
/**
* Convert the model called 'paragraphs to html for show on the template.
*
* @param paragraphs
*/
DiffView.prototype.showBillText = function (paragraphs) {
var textContainer = dom('#bill-diff .text');
var self = this;
textContainer.text(''); //Clean up the text container.
paragraphs.forEach(function (paragraph) {
var section = new TextSection(paragraph);
section.on('section:side-view:hide', self.centerText.bind(self));
section.on('section:side-view:show', self.collapseLeftText.bind(self));
textContainer.append(section.el);
});
};
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.transposeDocs = void 0;
var transposeDocs = {
name: 'transpose',
category: 'Matrix',
syntax: ['x\'', 'transpose(x)'],
description: 'Transpose a matrix',
examples: ['a = [1, 2, 3; 4, 5, 6]', 'a\'', 'transpose(a)'],
seealso: ['concat', 'det', 'diag', 'identity', 'inv', 'ones', 'range', 'size', 'squeeze', 'subset', 'trace', 'zeros']
};
exports.transposeDocs = transposeDocs;
|
export { default } from './Resultstest';
|
import { ADD_PRODUCT, DELETE_PRODUCT } from './actions'
const initialState = []
export default (state = initialState, action) => {
const inList = product => state.filter(i => i.id === product.id).length > 0
const getPosition = id => state.findIndex(i => i.id === id)
switch (action.type) {
case ADD_PRODUCT:
if (!action.product || !action.product.id) return state
if (inList(action.product)) return state
return [
...state,
action.product
]
case DELETE_PRODUCT:
const index = getPosition(action.id)
if (index === -1) return state
return [
...state.slice(0, index),
...state.slice(index + 1)
]
default:
return state
}
}
|
// XML namespaces:
const http = "http://www.w3.org/";
/** @type {Object} */
const ns = {
svg: http + "2000/svg",
xlink: http + "1999/xlink"
};
export default ns;
|
var version = "TEST";
|
/**
* Production environment settings
*
* This file can include shared settings for a production environment,
* such as API keys or remote database passwords. If you're using
* a version control solution for your Sails app, this file will
* be committed to your repository unless you add it to your .gitignore
* file. If your repository will be publicly viewable, don't add
* any private information to this file!
*
*/
module.exports = {
/***************************************************************************
* Set the default database connection for models in the production *
* environment (see config/connections.js and config/models.js ) *
***************************************************************************/
models: {
connection: 'mysql_production'
}
/***************************************************************************
* Set the port in the production environment to 80 *
***************************************************************************/
// port: 80,
/***************************************************************************
* Set the log level in production environment to "silent" *
***************************************************************************/
// log: {
// level: "silent"
// }
};
|
/*
Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dijit.PopupMenuItem"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dijit.PopupMenuItem"] = true;
dojo.provide("dijit.PopupMenuItem");
dojo.require("dijit.MenuItem");
dojo.declare("dijit.PopupMenuItem",
dijit.MenuItem,
{
_fillContent: function(){
// summary:
// When Menu is declared in markup, this code gets the menu label and
// the popup widget from the srcNodeRef.
// description:
// srcNodeRefinnerHTML contains both the menu item text and a popup widget
// The first part holds the menu item text and the second part is the popup
// example:
// | <div dojoType="dijit.PopupMenuItem">
// | <span>pick me</span>
// | <popup> ... </popup>
// | </div>
// tags:
// protected
if(this.srcNodeRef){
var nodes = dojo.query("*", this.srcNodeRef);
dijit.PopupMenuItem.superclass._fillContent.call(this, nodes[0]);
// save pointer to srcNode so we can grab the drop down widget after it's instantiated
this.dropDownContainer = this.srcNodeRef;
}
},
startup: function(){
if(this._started){ return; }
this.inherited(arguments);
// we didn't copy the dropdown widget from the this.srcNodeRef, so it's in no-man's
// land now. move it to dojo.doc.body.
if(!this.popup){
var node = dojo.query("[widgetId]", this.dropDownContainer)[0];
this.popup = dijit.byNode(node);
}
dojo.body().appendChild(this.popup.domNode);
this.popup.startup();
this.popup.domNode.style.display="none";
if(this.arrowWrapper){
dojo.style(this.arrowWrapper, "visibility", "");
}
dijit.setWaiState(this.focusNode, "haspopup", "true");
},
destroyDescendants: function(){
if(this.popup){
// Destroy the popup, unless it's already been destroyed. This can happen because
// the popup is a direct child of <body> even though it's logically my child.
if(!this.popup._destroyed){
this.popup.destroyRecursive();
}
delete this.popup;
}
this.inherited(arguments);
}
});
}
|
/* Sudo Slider v. 3.1.1 ( http://webbies.dk/SudoSlider/ ), licenced under GPL and MIT license */
(function(h,ja){function Y(a,b,d,q,f){if(h.isFunction(b))q?Y(a,["","Up","Right","Down","Left",b],d,0,f):a[d]=function(a){var d=[a].concat(f),n=d.length-1;if(0===q&&0==d[n]){var g=a.diff;d[n]=a.options.vertical?0>g?1:3:0>g?2:4}b.apply(this,d)};else if(h.isArray(b))for(var g=b.length-1,p=b[g],l=0;l<g;l++){var k=f.slice();k.push(l);Y(a,p,d+b[l],q,k)}else h.each(b,function(b,g){Y(a,g,d+b,q,f)})}function O(a,b,n,f,s,g,p,l){var k=a.options,z=k.ease,x=k.boxrows,t=k.boxcols,r=x*t,Ea=k.speed/(1==r?1:2.5),
m=ka(a,t,x,!l),A=k=0,T=0,K=[];K[A]=[];b&&U(m);s&&ca(m);m.each(function(){K[A][T]=this;T++;T==t&&(n&&U(K[A]),A++,T=0,K[A]=[])});s=[];if(1==g)for(m=0;m<2*t+1;m++){g=m;for(var r=[],y=0;y<x;y++){if(0<=g&&g<t){var v=K[y][g];if(!v)return;r.push(v)}g--}0!=r.length&&s.push(r)}else if(2==g){g=x/2;for(var B=b?r:-1,w=b?-1:1,v=0;v<g;v++){for(r=y=v;r<t-v-1;r++)s[B+=w]=m.eq(y*t+r);r=t-v-1;for(y=v;y<x-v-1;y++)s[B+=w]=m.eq(y*t+r);y=x-v-1;for(r=t-v-1;r>v;r--)s[B+=w]=m.eq(y*t+r);r=v;for(y=x-v-1;y>v;y--)s[B+=w]=m.eq(y*
t+r)}}else for(m=0;m<x;m++)for(g=0;g<t;g++)s.push([K[m][g]]);l&&a.goToNext();for(var F=0,x=0;x<s.length;x++){m=s[x];for(g=0;g<m.length;g++)(function(g,h){var s=g.children(),k=g.width(),t=g.height(),m=da(g.css("left")),r=da(g.css("top")),v=m,A=r,x=da(s.css("left")),y=da(s.css("top")),w=x,B=y;if(p){var T=b!=n?-k:k,K=b?-t:t;l?(v-=T,A-=K):g.css({left:m+T,top:r+K})}f&&(l?(w-=k/2,v+=k/2,B-=t/2,A+=t/2,t=k=0):(g.css({left:m+k/2,top:r+t/2}),s.css({left:x-k/2,top:y-t/2}),g.width(0).height(0)));l&&g.css({opacity:1});
F++;setTimeout(function(){E(s,{left:w,top:B},Ea,z,d,a);E(g,{opacity:l?0:1,width:k,height:t,left:v,top:A},Ea,z,function(){F--;0==F&&a.callback()},a)},h)})(h(m[g]),k);k+=1.5*(Ea/s.length)}}function I(a,b,n,q,s,g,p,l){var k=a.options,z=k.slices,x=k.speed/2,t=k.ease,k=a.slider,r=ka(a,b?z:1,b?1:z,!l),F=0,m=d;n?U(r):h(U(r.get())).appendTo(k);q&&ca(r);r.each(function(q){q*=x/z;var k=h(this),r=k.width(),y=k.height(),v=k.css("left"),B=k.css("top"),w=b?v:B,I=k.children()[b?"width":"height"]();1==g?w=0:2==g&&
(w=I/2);n&&(w=I-w);b?k.css({width:s||p?r:0,left:w}):k.css({height:s||p?y:0,top:w});l&&(w=1==p?-1:1,k.css({top:B,left:v,width:r,height:y,opacity:1}),b?B=w*y:v=w*r);p&&(w=f,3==p?m=m?w=d:f:2==p&&(w=d),b?l?B=(w?-1:1)*y:k.css({bottom:w?0:y,top:w?y:0,height:l?y:0}):l?v=(w?-1:1)*r:k.css({right:w?0:r,left:w?r:0,width:l?r:0}));F++;setTimeout(function(){E(k,{width:r,height:y,opacity:l?0:1,left:v,top:B},x,t,function(){F--;0==F&&a.callback()},a)},q)});l&&a.goToNext()}function E(a,b,n,q,h,g){function p(){var b=
{};b[x]="0s";b[t]="";b[z]="";a.css(b)}var l=!g||g.options.usecss;if(P!==d&&l){var k={},z=P+"transition",l=na(b);k[z]=l.join(" ")+(""==P?"":" "+P+l.join(" "+P));var x=z+"-duration";k[x]=n+"ms";var t=z+"-timing-function";"swing"==q&&(q="ease-in-out");k[t]=q;g&&g.stopCallbacks.push(p);q=P.replace(/\-/g,"");var r=q+((q?"T":"t")+"ransitionend")+" transitionend",E=d,m=function(){E||(E=f,a.unbind(r),p(),h&&h())};F(function(){20>n?(a.css(b),m()):(a.css(k),F(function(){a.css(b);a.bind(r,m);setTimeout(m,n+
100)}))});return m}a.animate(b,n,q,h)}function oa(a,b){var d=a.options;d.boxcols=1;d.boxrows=1;d.speed=b;O(a)}function ka(a,b,n,q){for(var s=a.slider,g=h(),p,l,k=f,z=0;z<n;z++)for(var x=0;x<b;x++){var t=ea(a,q);k&&(k=d,p=Math.ceil(t.width()/b),l=Math.ceil(t.height()/n));t=pa(t,l*z,p*x,l,p,a);s.append(t);g=g.add(t)}return g}function pa(a,b,d,f,s,g){a.css({width:a.width(),height:a.height(),display:"block",top:-b,left:-d});b=h("<div>").css({left:d,top:b,width:s,height:f,opacity:0,overflow:"hidden",position:Z,
zIndex:g.options.animationzindex});b.append(a).addClass(va);return b}function ea(a,b){var d=b?a.toSlides:a.fromSlides,f=d.eq(0).position(),s=f.left,g=f.top,p=0,l=0,k=h("<div>").css({zIndex:a.options.animationzindex,position:Z,top:0,left:0}).addClass(va);d.each(function(a,b){var d=h(b),n=d.outerWidth(!0),f=d.outerHeight(!0),q=d.clone(),A=d.position(),d=A.left-s,A=A.top-g;q.css({position:Z,left:d,top:A,opacity:1});p=$(p,A+f);l=$(l,d+n);k.append(q)});k.width(l).height(p);return k}function na(a){var b=
[],d;for(d in a)b.push(d);return b}function F(a){setTimeout(a,0)}function U(a){return[].reverse.call(a)}function fa(a){return a.children().not("."+va)}function qa(a){var b={},d;for(d in a)b[d.toLowerCase()]=a[d];return b}function ca(a){for(var b,d,f=a.length;f;b=parseInt(Math.random()*f),d=a[--f],a[f]=a[b],a[b]=d);return a}function da(a){return parseFloat(a)}function $(a,b){return a>b?a:b}function ra(a){if(h.isArray(a))return V(a);if(h.isFunction(a))return a;a=a.trim();if(-1!=a.indexOf(",")){var b=
a.split(",");return V(b)}var d=qa(h.fn.sudoSlider.effects);a=a.toLowerCase();if(b=d[a])return b;var b=[],f;for(f in d)0==f.indexOf(a)&&b.push(d[f]);return b.length?V(b):ra("slide")}function V(a){return function(b){var d=a[ca(na(a))[0]];return ra(d)(b)}}var d=!1,f=!0,Ga="pages",ga="next",sa="prev",Ta="last",Ua="first",Z="absolute",W=function(){},va="sudo-box",P=function(){var a;a:{var b=h("<div>")[0].style;for(a in b)if(b=a.toLowerCase(),-1!==b.indexOf("transition",b.length-10))break a;a=!1}if(a===
d)return d;a=a.slice(0,a.length-10);return 0!=a.length?"-"+a+"-":""}();h.fn.sudoSlider=function(a){var b=this;a=h.extend(qa({effect:d,speed:1500,customLink:d,controlsShow:f,controlsFadeSpeed:400,controlsFade:f,insertAfter:f,vertical:d,slideCount:1,moveCount:1,startSlide:1,responsive:d,ease:"swing",auto:d,pause:2E3,resumePause:d,continuous:d,prevNext:f,numeric:d,numericText:[],slices:15,boxCols:8,boxRows:4,initCallback:W,ajaxLoad:W,beforeAnimation:W,afterAnimation:W,history:d,autoHeight:f,autoWidth:f,
updateBefore:d,ajax:d,preloadAjax:100,loadingText:"",prevHtml:'<a href="#" class="prevBtn"></a>',nextHtml:'<a href="#" class="nextBtn"></a>',controlsAttr:'id="controls"',numericAttr:'class="controls"',animationZIndex:1E4,interruptible:d,useCSS:d,loadStart:W,loadFinish:W}),qa(a));P===d&&(a.usecss=d);return this.each(function(){function n(){var c=0,a;for(a in aa)e[c]=aa[a],c++;N=f;D=fa(H);c=D.length;a=h("<div></div>");c?D.is("ul")||Na||(a.append(D),H.append(D=a)):H.append(D=a);Na=f;
G=fa(D);C=G.length;if(e[31]&&e[31].length>C){for(c=1;c<=e[31].length-C;c++)D.append("<div>"+e[33]+"</div>");G=fa(D);C=G.length}u=Q===d?0:Q;wa=C-1;R=f;xa=[];ta=d;H.css({overflow:"hidden"});"static"==H.css("position")&&H.css({position:"relative"});G.css({"float":"left",listStyle:"none"});D.add(G).css({display:"block",position:"relative"});e[8]=parseInt(e[8],10);J=e[8];e[8]+=e[9]-1;e[10]=parseInt(e[10],10)-1||0;e[0]||(e[0]="slide");e[0]=ra(e[0]);e[16]&&(M=[]);for(c=0;c<C;c++)e[19][c]||""==e[19][c]||
(e[19][c]=c+1),e[31][c]=e[31][c]||d;S=[];for(a=0;a<C;a++)S[a]=[],S[a].push(G.eq(a));if(M)for(a=e[8];1<=a&&0<C;a--){var b=L(-e[8]+a-1),n=L(e[8]-a),Ha=G.eq(b).clone();M.push(Ha);var t=G.eq(n).clone();M.push(t);S[b].push(Ha);S[n].push(t);D.prepend(Ha).append(t)}e[5]=e[5]&&!e[16];D[e[7]?"height":"width"](9E6);ba=fa(D);e[29]=e[29]&&!e[11];if(e[11])h(ja).on("resize focus",q);if(e[3]){ha=h("<span "+e[36]+"></span>");H[e[6]?"after":"before"](ha);if(e[18])for(Ia=h("<ol "+e[37]+"></ol>"),ha.prepend(Ia),b=(a=
e[18]==Ga)?J:1,c=0;c<C-(e[16]||a?1:J)+1;c+=b)xa[c]=h("<li data-rel='"+(c+1)+"'><a href='#'><span>"+e[19][c]+"</span></a></li>").appendTo(Ia).click(function(){z(h(this).attr("data-rel")-1,f);return d});e[17]&&(ka=k(e[35],ga),na=k(e[34],sa))}a=[4,1,14];for(c in a)e[a[c]]=parseInt(e[a[c]],10)||0==e[a[c]]?parseInt(e[a[c]],10):"fast"==e[a[c]]?200:"normal"==e[a[c]]||"medium"==e[a[c]]?400:"slow"==e[a[c]]?600:400;if(e[2])h(document).on("click",e[2],function(){var c;if(c=h(this).attr("data-rel"))"stop"==c?(e[13]=d,l()):
"start"==c?(p(e[14]),e[13]=f):"block"==c?R=d:"unblock"==c?R=f:z(c==parseInt(c,10)?c-1:c,f);return d});c=h();for(a=0;a<e[8];a++)c=c.add(O(e[10]+a));m(c,f,function(){if(Q!==d)ua(Q,d);else if(e[27]){var c=h(ja),a;if(a=c.hashchange)a(s);else if(a=h.address)a.change(s);else c.on("hashchange",s);s()}else ua(e[10],d);r(u)});e[31][e[10]]&&la(e[10]);if(e[32]===f)for(a=0;a<=wa;a++)e[31][a]&&e[10]!=a&&la(a);else g()}function q(){if(H.is(":visible")&&!N){var c=ba.width(),a=H.width()/J;ba.width(a);c!=a&&(ma(),
v(u),A(u,0))}}function s(){var c;a:{c=location.hash.substr(1);for(var a in e[19])if(e[19][a]==c){c=a;break a}c=c?u:0}N?ua(c,d):z(c,d)}function g(){var c=parseInt(e[32],10);if(e[31]&&c)for(var a in e[31])if(e[31][a]){clearTimeout(ya);ya=setTimeout(function(){e[31][a]?la(parseInt(a,10)):g()},c);break}}function p(c){l();za=f;oa=setTimeout(function(){za&&z(ga,d)},c)}function l(c){clearTimeout(oa);c||(za=d)}function k(c,a){return h(c).prependTo(ha).click(function(){z(a,f);return d})}function z(c,a,b){if(R&&
!N)l(f),ta||qa(c,a,b);else if(e[39]&&ia)ma(),z(c,a,b);else if(Aa=c,Oa=a,Pa=b,e[31])for(a=c=X(c);a<c+J;a++)e[31][a]&&la(L(a))}function x(c,a,b){function f(){c||0!=g.css("opacity")||g.css({visibility:"hidden"})}c=c?1:0;var g=h();e[3]&&e[17]&&(g=b?ka:na);e[2]&&(b=h(e[2]).filter("[rel='"+(b?ga:sa)+"']"),g=g.add(b));b={opacity:c};c&&g.css({visibility:"visible"});e[40]?E(g,b,a,e[12],f):g.animate(b,{queue:d,duration:a,easing:e[12],callback:f})}function t(c,a){x(c,a,d);x(c<C-J,a,f)}function r(c){c=L(c)+1;
e[18]!=Ga||(c!=C-J+1||e[16])||(c=C);if(e[18])for(var a in xa)I(xa[a],c);e[2]&&I(h(e[2]),c)}function I(c,a){c.filter&&(c.filter(".current").removeClass("current"),c.filter(function(){var c=h(this).attr("data-rel");if(e[18]==Ga)for(var b=J-1;0<=b;b--){if(c==a-b)return f}else return c==a;return d}).addClass("current"))}function m(c,a,b){c=c.add(c.find("img")).filter("img");var e=c.length;if(!e)return b(),this;c.each(function(){var c=this;h(c).on("load error",function(){h(c).off("load error");c.naturalHeight&&
!c.clientHeight&&h(c).height(c.naturalHeight).width(c.naturalWidth);a?(e--,0==e&&b()):b()});if("complete"==c.readyState)h(c).trigger("load");else if(c.readyState)c.src=c.src;else if(c.complete)h(c).trigger("load");else if(void 0===c.complete){var d=c.src;c.src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";c.src=d}})}function A(c,a){pa=c=L(c);Ja=+new Date+a;(e[28]||e[29])&&T(c)}function T(c){H.ready(function(){y(c);m(G.eq(c),d,function(){y(c)})})}function K(c,a){for(var b=
0,d=c;d<c+J;d++)var g=G.eq(L(d))["outer"+(a?"Height":"Width")](f),b=a==e[7]?b+g:$(g,b);return b}function y(c){if(c==pa&&H.is(":visible")&&!N){var a=Ja-+new Date,a=$(a,0),b={};e[28]&&(b.height=K(c,f)||1);e[29]&&(b.width=K(c,d)||1);e[40]?E(H,b,a,e[12]):0==a?H.stop().css(b):H.animate(b,{queue:d,duration:a,easing:e[12]})}}function v(c){D.css({marginLeft:0,marginTop:0});var a=B(c,d);c=B(c,f);D.css({marginLeft:a,marginTop:c})}function B(c,a){c=ba.eq(c+(M?e[8]:0));return c.length?-c.position()[a?"top":"left"]:
0}function w(){if(Aa!==d){var c=Aa;Aa=d;F(function(){z(c,Oa,Pa)})}}function P(c,a,b){c=L(c);var e=O(c),d=function(){(a?W:Y)(e,c+1)};b?d():F(d)}function W(c,a){e[26].call(c,a)}function Y(c,a){e[25].call(c,a)}function O(c){c=L(c);var a=h(),b;for(b in S[c])a=a.add(S[c][b]);return a}function X(c){return c==ga?U(u+e[9],c):c==sa?U(u-e[9],c):c==Ua?0:c==Ta?wa:U(parseInt(c,10),c)}function U(c,a){if(e[16])return a==ga||a==sa?c:L(c);var b=C-J;return c>b?u==b&&a==ga?0:b:0>c?0==u&&a==sa?b:0:c}function la(c,a){if(a){var b=
Ka[c];b||(b=Ka[c]=[]);b.push(a)}if(La[c])a&&F(a);else if(!Ba[c]){Ba[c]=f;ya&&clearTimeout(ya);var g=e[31][c],k=G.eq(c),n=d;h.ajax({url:g,success:function(a,b,e){V(function(){var b=e.getResponseHeader("Content-Type");b&&"i"!=b.substr(0,1)&&(n=f,k.html(a),ca(c,d))})},complete:function(){if(!n){var a=new Image;a.src=g;var b=h(a);m(b,!0,function(){V(function(){var e="";b.height()||(e=20);b.height(e).width(e);k.empty().append(a);ca(c,f)})})}}});e[31][c]=d;aa.ajax[c]=d}}function V(a){ia?Qa.push(a):F(a)}
function ca(a,b){var k=G.eq(a);if(M){var n=d,h;for(h in S[a])n&&(n=k.clone(),M.push(n),S[a][h].replaceWith(n),S[a][h]=n),n=f;ba=fa(D)}v(u);A(u,0);m(k,f,function(){V(function(){v(u);A(u,0);La[a]=f;var k=Ka[a];k&&Z(k);g();F(function(){e[24].call(O(a),parseInt(a,10)+1,b)});N&&(N=d,F(ea))})})}function ea(){A(u,0);w();e[11]&&h(ja).resize();e[13]&&p(e[14]);e[23].call(b)}function Z(a){for(;a.length;)a.splice(0,1)[0]()}function qa(a,d,g){var f=X(a);a=L(f);if(a!=u)if(e[31]){for(var k=0,n=a;n<a+J;n++)if(e[31][n]||
Ba[n]&&!La[n])k++,la(L(n),function(){k--;0==k&&(e[42].call(b,f+1),Fa(f,g,d))});0==k?Fa(f,g,d):e[41].call(b,f+1)}else Fa(f,g,d)}function Fa(a,g,k){e[30]&&r(a);e[27]&&k&&(ja.location.hash=e[19][a]);e[5]&&t(a,e[4]);R=d;for(var n=h(),l=h(),q=0;q<J;q++)n=n.add(ba.eq(u+q+(M?e[8]:0))),l=l.add(ba.eq(a+q+(M?e[8]:0)));var q=-(u-a),s;if(e[16]){var p=0>q?-q:q;s=a;var m=-(u-a-C);a<e[8]-J+1&&(0>m?-m:m)<p&&(s=a+C,q=m,p=0>q?-q:q);m=-(u-a+C);a>wa-e[8]&&(0>m?-m:m)<p&&(s=a-C,q=m)}else s=a;p=B(s,d)-da(D.css("marginLeft"));
s=B(s,f)-da(D.css("marginTop"));var y=G.eq(a),m=h.extend(f,{},aa),w=e[1],z=y.attr("data-speed");void 0!=z&&(w=parseInt(z,10));void 0!=g&&(w=parseInt(g,10));m.speed=w;var x=e[0];(g=y.attr("data-effect"))&&(x=ra(g));(g=G.eq(u).attr("data-effectout"))&&(x=ra(g));ia=f;Ra=x;var E=f;Sa=function(){E=ia=d;ua(a,k);screen.fontSmoothingEnabled&&l.style&&l.style.removeAttribute("filter");P(a,f);Z(Qa)};Ma={fromSlides:n,toSlides:l,slider:H,options:m,to:a+1,from:u+1,diff:q,target:{left:p,top:s},stopCallbacks:[],
callback:function(){E&&(E=d,ma())},goToNext:function(){E&&v(a)}};A(a,w);F(function(){P(a,d,f);x.call(b,Ma)})}function ma(){if(ia){Sa();Z(Ma.stopCallbacks);var a=Ra.stop;a?a():(h("."+va,H).remove(),D.stop());A(u,0);v(u)}}function ua(a,b){R=!b&&!e[13];u=a;A(u,0);u=L(u);e[30]||r(u);v(u);R=f;e[13]&&(b?(l(),e[15]&&p(e[15])):N||p(e[14]));w();e[5]&&N&&t(u,0);!N||(e[31][u]||Ba[u])||(N=d,F(ea))}function L(a){if(0==C)return 0;for(a=parseInt(a,10);0>a;)a+=C;return a%C}function Ca(){ma();ta=f;Q=u;e[11]&&h(ja).off("resize focus",
q);ha&&ha.remove();h(e[2]).off("click");if(M)for(var a=0;a<M.length;a++)M[a].remove();v(u);A(u,0)}function Da(){ta&&n()}var N,D,G,ba,C,u,wa,R,xa,Ia,ta,Q=d,ha,ka,na,oa,za,M,J,ya,S,H=h(this),pa,Ja=0,ia=d,Ra,Sa,Ma,Qa=[],Ka=[],Ba=[],La=[],Aa=d,Oa,Pa,Na=d,e=[],aa={};h.extend(f,aa,a);b.destroy=Ca;b.init=Da;b.getOption=function(a){return aa[a.toLowerCase()]};b.setOption=function(a,b){Ca();aa[a.toLowerCase()]=b;Da()};b.insertSlide=function(a,b,d,g){Ca();b>C&&(b=C);a="<li>"+a+"</li>";b&&0!=b?G.eq(b-1).after(a):
D.prepend(a);g?Q=g-1:(b<=Q||!b||0==b)&&Q++;e[19].length<b&&(e[19].length=b);e[19].splice(b,0,d||parseInt(b,10)+1);Da()};b.removeSlide=function(a){a--;Ca();G.eq(a).remove();e[19].splice(a,1);a<Q&&Q--;Da()};b.goToSlide=function(a,b){var e=a==parseInt(a,10)?a-1:a;F(function(){z(e,f,b)})};b.block=function(){R=d};b.unblock=function(){R=f};b.startAuto=function(){e[13]=f;p(e[14])};b.stopAuto=function(){e[13]=d;l()};b.adjust=function(){var a=$(Ja-+new Date,0);A(u,a);ia||v(u)};b.getValue=function(a){return{currentslide:u+
1,totalslides:C,clickable:R,destroyed:ta,autoanimation:za}[a.toLowerCase()]};b.getSlide=function(a){a=parseInt(a,10)-1;return O(a)};b.stopAnimation=ma;n()})};var X={};Y(X,{blinds:["1","2",function(a,b,f){b++;I(a,2==f||4==f,1==f||4==f,d,d,b)}],fold:function(a,b){I(a,2==b||4==b,1==b||4==b)},push:function(a,b){var d=2==b||4==b,q=2==b||3==b?-1:1,h=a.options,g=h.ease,p=a.fromSlides,l=ea(a,f).hide();l.prependTo(a.slider);var k=$(l.height(),p.height()),p=$(l.width(),p.width()),h=h.speed;l.css(d?{left:q*
p}:{top:q*k}).show();E(l,{left:0,top:0},h,g,a.callback,a)},reveal:function(a,b){var n=1==b||3==b,h=a.options,s=h.ease,h=h.speed,g=ea(a,f),p=g.width(),l=g.height(),k=pa(g,0,0,0,0,a).css({opacity:1}).appendTo(a.slider),z=k.add(g);z.hide();n?(k.css({width:p}),1==b&&(g.css({top:-l}),k.css({bottom:0,top:"auto"}))):(k.css({height:l}),4==b&&(g.css({left:-p}),k.css({right:0,left:"auto"})));z.show();n?z.width(p):z.height(l);E(g,{left:0,top:0},h,s,d,a);E(k,{width:p,height:l},h,s,a.callback,a)},slice:{"":["",
"Reveal",["","Reverse","Random",function(a,b,f,h){I(a,1==h||3==h,f,2==f,d,0,1==h||4==h?1:2,b)}]],Fade:function(a,b){I(a,2==b||4==b,1==b||4==b,d,f)}},zip:function(a,b){I(a,2==b||4==b,1==b||4==b,d,d,0,3)},unzip:function(a,b){I(a,2==b||4==b,1==b||4==b,d,d,0,3,f)}},"",f,[]);Y(X,{box:{Random:["","GrowIn","GrowOut",function(a,b){O(a,d,d,b,f,0,d,2==b)}],Rain:["","GrowIn","GrowOut","FlyIn","FlyOut",["UpLeft","DownLeft","DownRight","UpRight",function(a,b,f){O(a,0==f||3==f,1==f||3==f,1==b||2==b,d,1,3==b||4==
b,4==b||2==b)}]],Spiral:["InWards","OutWards",{"":function(a,b){O(a,b,d,d,d,2,d,d)},Grow:["In","Out",function(a,b,h){O(a,b,d,f,d,2,d,h)}]}]},fade:{"":function(a){oa(a,a.options.speed)},OutIn:function(a){var b=a.options,d=b.speed,b=b.ease,f=parseInt(0.6*d,10),f=d-f;a.stopCallbacks.push(function(){a.fromSlides.stop().css({opacity:1})});E(a.fromSlides,{opacity:1E-4},f,b,function(){oa(a,d)},a)}},foldRandom:["Horizontal","Vertical",function(a,b){I(a,b,d,f)}],slide:function(a){var b=fa(a.slider),d=a.options,
f=d.ease,d=d.speed,h=a.target,g=h.left,h=h.top;if(a.options.usecss){var p=function(){b.css({transform:"translate(0px, 0px)"})};a.stopCallbacks.push(p);p();E(b,{transform:"translate("+g+"px, "+h+"px)"},d,f,a.callback,a)}else E(b,{marginTop:"+="+h,marginLeft:"+="+g},d,f,a.callback,a)}},"",d,[]);X.random=V(X);h.fn.sudoSlider.effects=X})(jQuery,window);
|
module.exports = {
"env": {
"es6" : true,
"browser" : true
},
"parserOptions": {
"sourceType": "module"
},
"extends": "eslint:recommended",
"plugins": [
"import"
]
};
|
// Underscore.js 1.8.2
// http://underscorejs.org
// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
// Underscore may be freely distributed under the MIT license.
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `exports` on the server.
const root = this;
// Save the previous value of the `_` variable.
const previousUnderscore = root._;
// Save bytes in the minified (but not gzipped) version:
let ArrayProto = Array.prototype,
ObjProto = Object.prototype,
FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
let
push = ArrayProto.push,
slice = ArrayProto.slice,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
let
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind,
nativeCreate = Object.create;
// Naked function reference for surrogate-prototype-swapping.
const Ctor = function() {};
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.8.2';
// Internal function that returns an efficient (for current engines) version
// of the passed-in callback, to be repeatedly applied in other Underscore
// functions.
const optimizeCb = function(func, context, argCount) {
if (context === void 0) return func;
switch (argCount == null ? 3 : argCount) {
case 1: return function(value) {
return func.call(context, value);
};
case 2: return function(value, other) {
return func.call(context, value, other);
};
case 3: return function(value, index, collection) {
return func.call(context, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(context, accumulator, value, index, collection);
};
}
return function() {
return func.apply(context, arguments);
};
};
// A mostly-internal function to generate callbacks that can be applied
// to each element in a collection, returning the desired result — either
// identity, an arbitrary callback, a property matcher, or a property accessor.
const cb = function(value, context, argCount) {
if (value == null) return _.identity;
if (_.isFunction(value)) return optimizeCb(value, context, argCount);
if (_.isObject(value)) return _.matcher(value);
return _.property(value);
};
_.iteratee = function(value, context) {
return cb(value, context, Infinity);
};
// An internal function for creating assigner functions.
const createAssigner = function(keysFunc, undefinedOnly) {
return function(obj) {
const length = arguments.length;
if (length < 2 || obj == null) return obj;
for (let index = 1; index < length; index++) {
let source = arguments[index],
keys = keysFunc(source),
l = keys.length;
for (let i = 0; i < l; i++) {
const key = keys[i];
if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key];
}
}
return obj;
};
};
// An internal function for creating a new object that inherits from another.
const baseCreate = function(prototype) {
if (!_.isObject(prototype)) return {};
if (nativeCreate) return nativeCreate(prototype);
Ctor.prototype = prototype;
const result = new Ctor();
Ctor.prototype = null;
return result;
};
// Helper for collection methods to determine whether a collection
// should be iterated as an array or as an object
// Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
const MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
const isArrayLike = function(collection) {
const length = collection != null && collection.length;
return typeof length === 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
};
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles raw objects in addition to array-likes. Treats all
// sparse array-likes as if they were dense.
_.each = _.forEach = function(obj, iteratee, context) {
iteratee = optimizeCb(iteratee, context);
let i,
length;
if (isArrayLike(obj)) {
for (i = 0, length = obj.length; i < length; i++) {
iteratee(obj[i], i, obj);
}
} else {
const keys = _.keys(obj);
for (i = 0, length = keys.length; i < length; i++) {
iteratee(obj[keys[i]], keys[i], obj);
}
}
return obj;
};
// Return the results of applying the iteratee to each element.
_.map = _.collect = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
let keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length,
results = Array(length);
for (let index = 0; index < length; index++) {
const currentKey = keys ? keys[index] : index;
results[index] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
// Create a reducing function iterating left or right.
function createReduce(dir) {
// Optimized iterator function as using arguments.length
// in the main function will deoptimize the, see #1991.
function iterator(obj, iteratee, memo, keys, index, length) {
for (; index >= 0 && index < length; index += dir) {
const currentKey = keys ? keys[index] : index;
memo = iteratee(memo, obj[currentKey], currentKey, obj);
}
return memo;
}
return function(obj, iteratee, memo, context) {
iteratee = optimizeCb(iteratee, context, 4);
let keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length,
index = dir > 0 ? 0 : length - 1;
// Determine the initial value if none is provided.
if (arguments.length < 3) {
memo = obj[keys ? keys[index] : index];
index += dir;
}
return iterator(obj, iteratee, memo, keys, index, length);
};
}
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`.
_.reduce = _.foldl = _.inject = createReduce(1);
// The right-associative version of reduce, also known as `foldr`.
_.reduceRight = _.foldr = createReduce(-1);
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, predicate, context) {
let key;
if (isArrayLike(obj)) {
key = _.findIndex(obj, predicate, context);
} else {
key = _.findKey(obj, predicate, context);
}
if (key !== void 0 && key !== -1) return obj[key];
};
// Return all the elements that pass a truth test.
// Aliased as `select`.
_.filter = _.select = function(obj, predicate, context) {
const results = [];
predicate = cb(predicate, context);
_.each(obj, function(value, index, list) {
if (predicate(value, index, list)) results.push(value);
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, predicate, context) {
return _.filter(obj, _.negate(cb(predicate)), context);
};
// Determine whether all of the elements match a truth test.
// Aliased as `all`.
_.every = _.all = function(obj, predicate, context) {
predicate = cb(predicate, context);
let keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length;
for (let index = 0; index < length; index++) {
const currentKey = keys ? keys[index] : index;
if (!predicate(obj[currentKey], currentKey, obj)) return false;
}
return true;
};
// Determine if at least one element in the object matches a truth test.
// Aliased as `any`.
_.some = _.any = function(obj, predicate, context) {
predicate = cb(predicate, context);
let keys = !isArrayLike(obj) && _.keys(obj),
length = (keys || obj).length;
for (let index = 0; index < length; index++) {
const currentKey = keys ? keys[index] : index;
if (predicate(obj[currentKey], currentKey, obj)) return true;
}
return false;
};
// Determine if the array or object contains a given value (using `===`).
// Aliased as `includes` and `include`.
_.contains = _.includes = _.include = function(obj, target, fromIndex) {
if (!isArrayLike(obj)) obj = _.values(obj);
return _.indexOf(obj, target, typeof fromIndex === 'number' && fromIndex) >= 0;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
const args = slice.call(arguments, 2);
const isFunc = _.isFunction(method);
return _.map(obj, function(value) {
const func = isFunc ? method : value[method];
return func == null ? func : func.apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, _.property(key));
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs) {
return _.filter(obj, _.matcher(attrs));
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.find(obj, _.matcher(attrs));
};
// Return the maximum element (or element-based computation).
_.max = function(obj, iteratee, context) {
let result = -Infinity,
lastComputed = -Infinity,
value,
computed;
if (iteratee == null && obj != null) {
obj = isArrayLike(obj) ? obj : _.values(obj);
for (let i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value > result) {
result = value;
}
}
} else {
iteratee = cb(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed > lastComputed || computed === -Infinity && result === -Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iteratee, context) {
let result = Infinity,
lastComputed = Infinity,
value,
computed;
if (iteratee == null && obj != null) {
obj = isArrayLike(obj) ? obj : _.values(obj);
for (let i = 0, length = obj.length; i < length; i++) {
value = obj[i];
if (value < result) {
result = value;
}
}
} else {
iteratee = cb(iteratee, context);
_.each(obj, function(value, index, list) {
computed = iteratee(value, index, list);
if (computed < lastComputed || computed === Infinity && result === Infinity) {
result = value;
lastComputed = computed;
}
});
}
return result;
};
// Shuffle a collection, using the modern version of the
// Fisher-Yates shuffle.
_.shuffle = function(obj) {
const set = isArrayLike(obj) ? obj : _.values(obj);
const length = set.length;
const shuffled = Array(length);
for (var index = 0, rand; index < length; index++) {
rand = _.random(0, index);
if (rand !== index) shuffled[index] = shuffled[rand];
shuffled[rand] = set[index];
}
return shuffled;
};
// Sample **n** random values from a collection.
// If **n** is not specified, returns a single random element.
// The internal `guard` argument allows it to work with `map`.
_.sample = function(obj, n, guard) {
if (n == null || guard) {
if (!isArrayLike(obj)) obj = _.values(obj);
return obj[_.random(obj.length - 1)];
}
return _.shuffle(obj).slice(0, Math.max(0, n));
};
// Sort the object's values by a criterion produced by an iteratee.
_.sortBy = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value,
index,
criteria: iteratee(value, index, list),
};
}).sort(function(left, right) {
const a = left.criteria;
const b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index - right.index;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
const group = function(behavior) {
return function(obj, iteratee, context) {
const result = {};
iteratee = cb(iteratee, context);
_.each(obj, function(value, index) {
const key = iteratee(value, index, obj);
behavior(result, value, key);
});
return result;
};
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = group(function(result, value, key) {
if (_.has(result, key)) result[key].push(value); else result[key] = [ value ];
});
// Indexes the object's values by a criterion, similar to `groupBy`, but for
// when you know that your index values will be unique.
_.indexBy = group(function(result, value, key) {
result[key] = value;
});
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = group(function(result, value, key) {
if (_.has(result, key)) result[key]++; else result[key] = 1;
});
// Safely create a real, live array from anything iterable.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (isArrayLike(obj)) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return isArrayLike(obj) ? obj.length : _.keys(obj).length;
};
// Split a collection into two arrays: one whose elements all satisfy the given
// predicate, and one whose elements all do not satisfy the predicate.
_.partition = function(obj, predicate, context) {
predicate = cb(predicate, context);
let pass = [],
fail = [];
_.each(obj, function(value, key, obj) {
(predicate(value, key, obj) ? pass : fail).push(value);
});
return [ pass, fail ];
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[0];
return _.initial(array, array.length - n);
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N.
_.initial = function(array, n, guard) {
return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if (n == null || guard) return array[array.length - 1];
return _.rest(array, Math.max(0, array.length - n));
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, n == null || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, strict, startIndex) {
let output = [],
idx = 0;
for (let i = startIndex || 0, length = input && input.length; i < length; i++) {
let value = input[i];
if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) {
// flatten current level of array or arguments object
if (!shallow) value = flatten(value, shallow, strict);
let j = 0,
len = value.length;
output.length += len;
while (j < len) {
output[idx++] = value[j++];
}
} else if (!strict) {
output[idx++] = value;
}
}
return output;
};
// Flatten out an array, either recursively (by default), or just one level.
_.flatten = function(array, shallow) {
return flatten(array, shallow, false);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iteratee, context) {
if (array == null) return [];
if (!_.isBoolean(isSorted)) {
context = iteratee;
iteratee = isSorted;
isSorted = false;
}
if (iteratee != null) iteratee = cb(iteratee, context);
const result = [];
let seen = [];
for (let i = 0, length = array.length; i < length; i++) {
let value = array[i],
computed = iteratee ? iteratee(value, i, array) : value;
if (isSorted) {
if (!i || seen !== computed) result.push(value);
seen = computed;
} else if (iteratee) {
if (!_.contains(seen, computed)) {
seen.push(computed);
result.push(value);
}
} else if (!_.contains(result, value)) {
result.push(value);
}
}
return result;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(flatten(arguments, true, true));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
if (array == null) return [];
const result = [];
const argsLength = arguments.length;
for (let i = 0, length = array.length; i < length; i++) {
const item = array[i];
if (_.contains(result, item)) continue;
for (var j = 1; j < argsLength; j++) {
if (!_.contains(arguments[j], item)) break;
}
if (j === argsLength) result.push(item);
}
return result;
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
const rest = flatten(arguments, true, true, 1);
return _.filter(array, function(value) {
return !_.contains(rest, value);
});
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
return _.unzip(arguments);
};
// Complement of _.zip. Unzip accepts an array of arrays and groups
// each array's elements on shared indices
_.unzip = function(array) {
const length = array && _.max(array, 'length').length || 0;
const result = Array(length);
for (let index = 0; index < length; index++) {
result[index] = _.pluck(array, index);
}
return result;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
const result = {};
for (let i = 0, length = list && list.length; i < length; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// Return the position of the first occurrence of an item in an array,
// or -1 if the item is not included in the array.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
let i = 0,
length = array && array.length;
if (typeof isSorted === 'number') {
i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted;
} else if (isSorted && length) {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
if (item !== item) {
return _.findIndex(slice.call(array, i), _.isNaN);
}
for (; i < length; i++) if (array[i] === item) return i;
return -1;
};
_.lastIndexOf = function(array, item, from) {
let idx = array ? array.length : 0;
if (typeof from === 'number') {
idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1);
}
if (item !== item) {
return _.findLastIndex(slice.call(array, 0, idx), _.isNaN);
}
while (--idx >= 0) if (array[idx] === item) return idx;
return -1;
};
// Generator function to create the findIndex and findLastIndex functions
function createIndexFinder(dir) {
return function(array, predicate, context) {
predicate = cb(predicate, context);
const length = array != null && array.length;
let index = dir > 0 ? 0 : length - 1;
for (; index >= 0 && index < length; index += dir) {
if (predicate(array[index], index, array)) return index;
}
return -1;
};
}
// Returns the first index on an array-like that passes a predicate test
_.findIndex = createIndexFinder(1);
_.findLastIndex = createIndexFinder(-1);
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iteratee, context) {
iteratee = cb(iteratee, context, 1);
const value = iteratee(obj);
let low = 0,
high = array.length;
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
}
return low;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// the Python documentation.
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = step || 1;
const length = Math.max(Math.ceil((stop - start) / step), 0);
const range = Array(length);
for (let idx = 0; idx < length; idx++, start += step) {
range[idx] = start;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Determines whether to execute a function as a constructor
// or a normal function with the provided arguments
const executeBound = function(sourceFunc, boundFunc, context, callingContext, args) {
if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
const self = baseCreate(sourceFunc.prototype);
const result = sourceFunc.apply(self, args);
if (_.isObject(result)) return result;
return self;
};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
_.bind = function(func, context) {
if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');
const args = slice.call(arguments, 2);
var bound = function() {
return executeBound(func, bound, context, this, args.concat(slice.call(arguments)));
};
return bound;
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context. _ acts
// as a placeholder, allowing any combination of arguments to be pre-filled.
_.partial = function(func) {
const boundArgs = slice.call(arguments, 1);
var bound = function() {
let position = 0,
length = boundArgs.length;
const args = Array(length);
for (let i = 0; i < length; i++) {
args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i];
}
while (position < arguments.length) args.push(arguments[position++]);
return executeBound(func, bound, this, this, args);
};
return bound;
};
// Bind a number of an object's methods to that object. Remaining arguments
// are the method names to be bound. Useful for ensuring that all callbacks
// defined on an object belong to it.
_.bindAll = function(obj) {
let i,
length = arguments.length,
key;
if (length <= 1) throw new Error('bindAll must be passed function names');
for (i = 1; i < length; i++) {
key = arguments[i];
obj[key] = _.bind(obj[key], obj);
}
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memoize = function(key) {
const cache = memoize.cache;
const address = '' + (hasher ? hasher.apply(this, arguments) : key);
if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);
return cache[address];
};
memoize.cache = {};
return memoize;
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
const args = slice.call(arguments, 2);
return setTimeout(function() {
return func.apply(null, args);
}, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = _.partial(_.delay, _, 1);
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time. Normally, the throttled function will run
// as much as it can, without ever going more than once per `wait` duration;
// but if you'd like to disable the execution on the leading edge, pass
// `{leading: false}`. To disable execution on the trailing edge, ditto.
_.throttle = function(func, wait, options) {
let context,
args,
result;
let timeout = null;
let previous = 0;
if (!options) options = {};
const later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
const now = _.now();
if (!previous && options.leading === false) previous = now;
const remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
let timeout,
args,
context,
timestamp,
result;
var later = function() {
const last = _.now() - timestamp;
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = _.now();
const callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return _.partial(wrapper, func);
};
// Returns a negated version of the passed-in predicate.
_.negate = function(predicate) {
return function() {
return !predicate.apply(this, arguments);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
const args = arguments;
const start = args.length - 1;
return function() {
let i = start;
let result = args[start].apply(this, arguments);
while (i--) result = args[i].call(this, result);
return result;
};
};
// Returns a function that will only be executed on and after the Nth call.
_.after = function(times, func) {
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Returns a function that will only be executed up to (but not including) the Nth call.
_.before = function(times, func) {
let memo;
return function() {
if (--times > 0) {
memo = func.apply(this, arguments);
}
if (times <= 1) func = null;
return memo;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = _.partial(_.before, 2);
// Object Functions
// ----------------
// Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
const hasEnumBug = !{ toString: null }.propertyIsEnumerable('toString');
const nonEnumerableProps = [ 'valueOf', 'isPrototypeOf', 'toString',
'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString' ];
function collectNonEnumProps(obj, keys) {
let nonEnumIdx = nonEnumerableProps.length;
const constructor = obj.constructor;
const proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto;
// Constructor is a special case.
let prop = 'constructor';
if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop);
while (nonEnumIdx--) {
prop = nonEnumerableProps[nonEnumIdx];
if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) {
keys.push(prop);
}
}
}
// Retrieve the names of an object's own properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = function(obj) {
if (!_.isObject(obj)) return [];
if (nativeKeys) return nativeKeys(obj);
const keys = [];
for (const key in obj) if (_.has(obj, key)) keys.push(key);
// Ahem, IE < 9.
if (hasEnumBug) collectNonEnumProps(obj, keys);
return keys;
};
// Retrieve all the property names of an object.
_.allKeys = function(obj) {
if (!_.isObject(obj)) return [];
const keys = [];
for (const key in obj) keys.push(key);
// Ahem, IE < 9.
if (hasEnumBug) collectNonEnumProps(obj, keys);
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
const keys = _.keys(obj);
const length = keys.length;
const values = Array(length);
for (let i = 0; i < length; i++) {
values[i] = obj[keys[i]];
}
return values;
};
// Returns the results of applying the iteratee to each element of the object
// In contrast to _.map it returns an object
_.mapObject = function(obj, iteratee, context) {
iteratee = cb(iteratee, context);
let keys = _.keys(obj),
length = keys.length,
results = {},
currentKey;
for (let index = 0; index < length; index++) {
currentKey = keys[index];
results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
}
return results;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
const keys = _.keys(obj);
const length = keys.length;
const pairs = Array(length);
for (let i = 0; i < length; i++) {
pairs[i] = [ keys[i], obj[keys[i]] ];
}
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
const result = {};
const keys = _.keys(obj);
for (let i = 0, length = keys.length; i < length; i++) {
result[obj[keys[i]]] = keys[i];
}
return result;
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
const names = [];
for (const key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = createAssigner(_.allKeys);
// Assigns a given object with all the own properties in the passed-in object(s)
// (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
_.extendOwn = _.assign = createAssigner(_.keys);
// Returns the first key on an object that passes a predicate test
_.findKey = function(obj, predicate, context) {
predicate = cb(predicate, context);
let keys = _.keys(obj),
key;
for (let i = 0, length = keys.length; i < length; i++) {
key = keys[i];
if (predicate(obj[key], key, obj)) return key;
}
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(object, oiteratee, context) {
let result = {},
obj = object,
iteratee,
keys;
if (obj == null) return result;
if (_.isFunction(oiteratee)) {
keys = _.allKeys(obj);
iteratee = optimizeCb(oiteratee, context);
} else {
keys = flatten(arguments, false, false, 1);
iteratee = function(value, key, obj) { return key in obj; };
obj = Object(obj);
}
for (let i = 0, length = keys.length; i < length; i++) {
const key = keys[i];
const value = obj[key];
if (iteratee(value, key, obj)) result[key] = value;
}
return result;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj, iteratee, context) {
if (_.isFunction(iteratee)) {
iteratee = _.negate(iteratee);
} else {
const keys = _.map(flatten(arguments, false, false, 1), String);
iteratee = function(value, key) {
return !_.contains(keys, key);
};
}
return _.pick(obj, iteratee, context);
};
// Fill in a given object with default properties.
_.defaults = createAssigner(_.allKeys, true);
// Creates an object that inherits from the given prototype object.
// If additional properties are provided then they will be added to the
// created object.
_.create = function(prototype, props) {
const result = baseCreate(prototype);
if (props) _.extendOwn(result, props);
return result;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Returns whether an object has a given set of `key:value` pairs.
_.isMatch = function(object, attrs) {
let keys = _.keys(attrs),
length = keys.length;
if (object == null) return !length;
const obj = Object(object);
for (let i = 0; i < length; i++) {
const key = keys[i];
if (attrs[key] !== obj[key] || !(key in obj)) return false;
}
return true;
};
// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the Harmony `egal` proposal.
if (a === b) return a !== 0 || 1 / a === 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
const className = toString.call(a);
if (className !== toString.call(b)) return false;
switch (className) {
// Strings, numbers, regular expressions, dates, and booleans are compared by value.
case '[object RegExp]':
// RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return '' + a === '' + b;
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive.
// Object(NaN) is equivalent to NaN
if (+a !== +a) return +b !== +b;
// An `egal` comparison is performed for other numeric values.
return +a === 0 ? 1 / +a === 1 / b : +a === +b;
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a === +b;
}
const areArrays = className === '[object Array]';
if (!areArrays) {
if (typeof a !== 'object' || typeof b !== 'object') return false;
// Objects with different constructors are not equivalent, but `Object`s or `Array`s
// from different frames are.
let aCtor = a.constructor,
bCtor = b.constructor;
if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor &&
_.isFunction(bCtor) && bCtor instanceof bCtor)
&& ('constructor' in a && 'constructor' in b)) {
return false;
}
}
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
// Initializing stack of traversed objects.
// It's done here since we only need them for objects and arrays comparison.
aStack = aStack || [];
bStack = bStack || [];
let length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] === a) return bStack[length] === b;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
// Recursively compare objects and arrays.
if (areArrays) {
// Compare array lengths to determine if a deep comparison is necessary.
length = a.length;
if (length !== b.length) return false;
// Deep compare the contents, ignoring non-numeric properties.
while (length--) {
if (!eq(a[length], b[length], aStack, bStack)) return false;
}
} else {
// Deep compare objects.
let keys = _.keys(a),
key;
length = keys.length;
// Ensure that both objects contain the same number of properties before comparing deep equality.
if (_.keys(b).length !== length) return false;
while (length--) {
// Deep compare each member
key = keys[length];
if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return true;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0;
return _.keys(obj).length === 0;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
const type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError.
_.each([ 'Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error' ], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) === '[object ' + name + ']';
};
});
// Define a fallback version of the method in browsers (ahem, IE < 9), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return _.has(obj, 'callee');
};
}
// Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8,
// IE 11 (#1621), and in Safari 8 (#1929).
if (typeof /./ !== 'function' && typeof Int8Array !== 'object') {
_.isFunction = function(obj) {
return typeof obj === 'function' || false;
};
}
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj !== +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return obj != null && hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iteratees.
_.identity = function(value) {
return value;
};
// Predicate-generating functions. Often useful outside of Underscore.
_.constant = function(value) {
return function() {
return value;
};
};
_.noop = function() {};
_.property = function(key) {
return function(obj) {
return obj == null ? void 0 : obj[key];
};
};
// Generates a function for a given object that returns a given property.
_.propertyOf = function(obj) {
return obj == null ? function() {} : function(key) {
return obj[key];
};
};
// Returns a predicate for checking whether an object has a given set of
// `key:value` pairs.
_.matcher = _.matches = function(attrs) {
attrs = _.extendOwn({}, attrs);
return function(obj) {
return _.isMatch(obj, attrs);
};
};
// Run a function **n** times.
_.times = function(n, iteratee, context) {
const accum = Array(Math.max(0, n));
iteratee = optimizeCb(iteratee, context, 1);
for (let i = 0; i < n; i++) accum[i] = iteratee(i);
return accum;
};
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
// A (possibly faster) way to get the current timestamp as an integer.
_.now = Date.now || function() {
return new Date().getTime();
};
// List of HTML entities for escaping.
const escapeMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'`': '`',
};
const unescapeMap = _.invert(escapeMap);
// Functions for escaping and unescaping strings to/from HTML interpolation.
const createEscaper = function(map) {
const escaper = function(match) {
return map[match];
};
// Regexes for identifying a key that needs to be escaped
const source = '(?:' + _.keys(map).join('|') + ')';
const testRegexp = RegExp(source);
const replaceRegexp = RegExp(source, 'g');
return function(string) {
string = string == null ? '' : '' + string;
return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
};
};
_.escape = createEscaper(escapeMap);
_.unescape = createEscaper(unescapeMap);
// If the value of the named `property` is a function then invoke it with the
// `object` as context; otherwise, return it.
_.result = function(object, property, fallback) {
let value = object == null ? void 0 : object[property];
if (value === void 0) {
value = fallback;
}
return _.isFunction(value) ? value.call(object) : value;
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
let idCounter = 0;
_.uniqueId = function(prefix) {
const id = ++idCounter + '';
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate: /<%([\s\S]+?)%>/g,
interpolate: /<%=([\s\S]+?)%>/g,
escape: /<%-([\s\S]+?)%>/g,
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
const noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
const escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\u2028': 'u2028',
'\u2029': 'u2029',
};
const escaper = /\\|'|\r|\n|\u2028|\u2029/g;
const escapeChar = function(match) {
return '\\' + escapes[match];
};
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
// NB: `oldSettings` only exists for backwards compatibility.
_.template = function(text, settings, oldSettings) {
if (!settings && oldSettings) settings = oldSettings;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
const matcher = RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source,
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
let index = 0;
let source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset).replace(escaper, escapeChar);
index = offset + match.length;
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
} else if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
} else if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
// Adobe VMs need the match returned to produce the correct offest.
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + 'return __p;\n';
try {
var render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
const template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled source as a convenience for precompilation.
const argument = settings.variable || 'obj';
template.source = 'function(' + argument + '){\n' + source + '}';
return template;
};
// Add a "chain" function. Start chaining a wrapped Underscore object.
_.chain = function(obj) {
const instance = _(obj);
instance._chain = true;
return instance;
};
// OOP
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
// Helper function to continue chaining intermediate results.
const result = function(instance, obj) {
return instance._chain ? _(obj).chain() : obj;
};
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
_.each(_.functions(obj), function(name) {
const func = _[name] = obj[name];
_.prototype[name] = function() {
const args = [ this._wrapped ];
push.apply(args, arguments);
return result(this, func.apply(_, args));
};
});
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
_.each([ 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift' ], function(name) {
const method = ArrayProto[name];
_.prototype[name] = function() {
const obj = this._wrapped;
method.apply(obj, arguments);
if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
return result(this, obj);
};
});
// Add all accessor Array functions to the wrapper.
_.each([ 'concat', 'join', 'slice' ], function(name) {
const method = ArrayProto[name];
_.prototype[name] = function() {
return result(this, method.apply(this._wrapped, arguments));
};
});
// Extracts the result from a wrapped and chained object.
_.prototype.value = function() {
return this._wrapped;
};
// Provide unwrapping proxy for some methods used in engine operations
// such as arithmetic and JSON stringification.
_.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
_.prototype.toString = function() {
return '' + this._wrapped;
};
// AMD registration happens at the end for compatibility with AMD loaders
// that may not enforce next-turn semantics on modules. Even though general
// practice for AMD registration is to be anonymous, underscore registers
// as a named module because, like jQuery, it is a base library that is
// popular enough to be bundled in a third party lib, but not be part of
// an AMD load request. Those cases could generate an error when an
// anonymous define() is called outside of a loader request.
if (typeof define === 'function' && define.amd) {
define('underscore', [], function() {
return _;
});
}
}.call(this));
|
'use strict';
var assert = require('../../helpers/assert');
var commandOptions = require('../../factories/command-options');
var AddonCommand = require('../../../lib/commands/addon');
describe('addon command', function() {
var command, options;
beforeEach(function() {
options = commandOptions({
project: {
isEmberCLIProject: function() {
return false;
}
}
});
command = new AddonCommand(options);
});
it('doesn\'t allow to create an addon named `test`', function() {
return command.validateAndRun(['test']).then(function() {
assert.ok(false, 'should have rejected with an addon name of test');
})
.catch(function(error) {
assert.equal(error.message, 'We currently do not support a name of `test`.');
});
});
it('doesn\'t allow to create an addon named `ember`', function() {
return command.validateAndRun(['ember']).then(function() {
assert.ok(false, 'should have rejected with an addon name of test');
})
.catch(function(error) {
assert.equal(error.message, 'We currently do not support a name of `ember`.');
});
});
it('doesn\'t allow to create an addon named `vendor`', function() {
return command.validateAndRun(['vendor']).then(function() {
assert.ok(false, 'should have rejected with an addon name of `vendor`');
})
.catch(function(error) {
assert.equal(error.message, 'We currently do not support a name of `vendor`.');
});
});
it('doesn\'t allow to create an addon with a period in the name', function() {
return command.validateAndRun(['zomg.awesome']).then(function() {
assert.ok(false, 'should have rejected with period in the addon name');
})
.catch(function(error) {
assert.equal(error.message, 'We currently do not support a name of `zomg.awesome`.');
});
});
it('doesn\'t allow to create an addon with a name beginning with a number', function() {
return command.validateAndRun(['123-my-bagel']).then(function() {
assert.ok(false, 'should have rejected with a name beginning with a number');
})
.catch(function(error) {
assert.equal(error.message, 'We currently do not support a name of `123-my-bagel`.');
});
});
});
|
var api = require('./api')
, frontend = require('./frontend')
, stats = require('./stats')
, user = require('./user');
module.exports = {
api: api,
frontend: frontend,
stats: stats,
user: user
};
|
import React from 'react';
import moment from 'moment';
import { storiesOf } from '@kadira/storybook';
import SingleDatePickerWrapper from '../examples/SingleDatePickerWrapper';
import { VERTICAL_ORIENTATION } from '../constants';
storiesOf('SingleDatePicker', module)
.add('default', () => (
<SingleDatePickerWrapper />
))
.add('single month', () => (
<SingleDatePickerWrapper
numberOfMonths={1}
/>
))
.add('vertical', () => (
<SingleDatePickerWrapper
orientation={VERTICAL_ORIENTATION}
/>
))
.add('horizontal with portal', () => (
<SingleDatePickerWrapper
withPortal
/>
))
.add('horizontal with fullscreen portal', () => (
<SingleDatePickerWrapper withFullScreenPortal />
))
.add('vertical with full screen portal', () => (
<SingleDatePickerWrapper
orientation={VERTICAL_ORIENTATION}
withFullScreenPortal
/>
))
.add('non-english locale', () => {
moment.locale('zh-cn');
return (
<SingleDatePickerWrapper
placeholder="入住日期"
monthFormat="YYYY[年]MMMM"
phrases={{
closeDatePicker: '关闭',
}}
/>
);
})
.add('with custom display format', () => (
<SingleDatePickerWrapper
displayFormat="MMM D"
/>
))
.add('with outside days enabled', () => (
<SingleDatePickerWrapper
numberOfMonths={1}
enableOutsideDays
/>
));
|
/* eslint-env browser, mocha, jasmine */
import {log} from './DebugUtils';
describe('(utils) DebugUtils', () => {
it('should attach a log instance to window as logger', () => {
expect(window.logger).to.be.a('function');
})
});
|
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { asyncConnect } from 'redux-connect';
import Helmet from 'react-helmet';
import { load as loadSuppliers, create } from 'redux/modules/suppliers/suppliers';
import { load as loadProducers } from 'redux/modules/producers/producers';
import { isRole } from 'presenters/member';
import Button from 'components/Button';
import { producersByStatus } from './selectors';
import Item from './Item/';
import CreateProducerModal from './CreateProducerModal';
class GroupProducers extends Component {
static propTypes = {
user: PropTypes.object.isRequired,
group: PropTypes.object.isRequired,
activeProducers: PropTypes.array.isRequired,
inactiveProducers: PropTypes.array.isRequired,
createSupplier: PropTypes.func.isRequired,
}
constructor(props) {
super(props);
this.onOpenModal = this._onOpenModal.bind(this);
this.onCloseModal = this._onCloseModal.bind(this);
this.onProducerCreated = this._onProducerCreated.bind(this);
this.state = { showModal: false };
}
/**
* Open modal
*/
_onOpenModal() {
this.setState({ showModal: true });
}
/**
* Close modal
*/
_onCloseModal() {
this.setState({ showModal: false });
}
/**
* When a new producer is created whe
* close create producer modal/form and
* create a new supplier relation on DB.
*
* @param {Object} producer
*/
_onProducerCreated(producer) {
const { createSupplier, group } = this.props;
this.onCloseModal();
createSupplier({ group_id: group.id, producer_id: producer.id });
}
/**
* If user is group admin she/he can create
* producers
*/
renderCreateProducer() {
const { group, user } = this.props;
const isAdmin = isRole(user, 'admin');
if (!isAdmin) return null;
const { showModal } = this.state;
return (
<div>
<Button primary onClick={this.onOpenModal}>Crear productor</Button>
<CreateProducerModal
showModal={showModal}
group={group}
onCloseModal={this.onCloseModal}
onCreated={this.onProducerCreated}
/>
</div>
);
}
/**
* Render in-active producers list
*/
renderInactiveProducers() {
const { inactiveProducers, user, group } = this.props;
if (!inactiveProducers.length) return (<span>Ningun productor inactivo</span>);
return (
<ul>
{inactiveProducers.map((producer) => (
<Item key={producer.id} user={user} producer={producer} group={group} />
))}
</ul>
);
}
/**
* Render active producers list
*/
renderActiveProducers() {
const { user, activeProducers, group } = this.props;
if (!activeProducers.length) return (<span>Ningun productor activo</span>);
return (
<ul>
{activeProducers.map((producer) => (
<Item key={producer.id} user={user} producer={producer} group={group} />
))}
</ul>
);
}
render() {
const { group } = this.props;
return (
<div>
<Helmet title={`Productores de ${group.name}`}/>
<h3>Productores</h3>
{this.renderCreateProducer()}
<h4>Activos</h4>
{this.renderActiveProducers()}
<h4>Inactivos</h4>
{this.renderInactiveProducers()}
</div>
);
}
}
const mapStateToProps = (_state, ownProps) => {
return (state) => {
const selector = producersByStatus();
const { activeProducers, inactiveProducers } = selector(state, ownProps);
return { activeProducers, inactiveProducers };
};
};
const asyncConnectProps = [{
promise: ({ store: { dispatch }, params: { id } }) => {
const promises = [];
promises.push(dispatch(loadProducers(id)));
promises.push(dispatch(loadSuppliers(id)));
return Promise.all(promises);
},
}];
export default compose(
asyncConnect(asyncConnectProps),
connect(mapStateToProps, { createSupplier: create })
)(GroupProducers);
|
'use strict';
/**
* @ngdoc function
* @name zcGdzcHelperApp.controller:ListCtrl
* @description
* # ListCtrl
* Controller of the zcGdzcHelperApp
*/
angular.module('zcGdzcHelperApp')
.controller('ListCtrl', function ($scope, gdzc) {
$scope.Predicates = Nagu.Gdzc.Predicates;
gdzc.listByLyr('fb1d7ab9-3a13-4e0f-b592-e848438452ef').then(function (gdzcList) {
$scope.gdzcList = gdzcList;
});
});
|
'use strict';
var distance = require('google-distance');
var xmlify = require('xmlify');
var config = require('../config');
var startEmbedUrl= 'https://www.google.com/maps/embed/v1/directions?key='+config.API_KEY+'&mode=walking&origin=';
function getDistance(request, reply) {
var origin = request.params.origin;
var destination = request.params.destination;
var embedUrl = startEmbedUrl + origin + '&destination=' + destination;
distance.get({
mode: 'walking',
origin: origin,
destination: destination
},
function(err, data) {
if (err) {
if (request.query.format === 'xml') {
reply(xmlify(err)).type('application/xml');
} else {
reply(err);
}
} else {
data.directionsEmbedUrl = embedUrl;
if (request.query.format === 'xml') {
reply(xmlify(data)).type('application/xml');
} else {
reply(data);
}
}
});
}
module.exports.getDistance = getDistance;
|
/*!
* gumshoejs v5.1.2
* A simple, framework-agnostic scrollspy script.
* (c) 2019 Chris Ferdinandi
* MIT License
* http://github.com/cferdinandi/gumshoe
*/
/**
* Element.closest() polyfill
* https://developer.mozilla.org/en-US/docs/Web/API/Element/closest#Polyfill
*/
if (!Element.prototype.closest) {
if (!Element.prototype.matches) {
Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
}
Element.prototype.closest = function (s) {
var el = this;
var ancestor = this;
if (!document.documentElement.contains(el)) return null;
do {
if (ancestor.matches(s)) return ancestor;
ancestor = ancestor.parentElement;
} while (ancestor !== null);
return null;
};
}
/**
* CustomEvent() polyfill
* https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent#Polyfill
*/
(function () {
if (typeof window.CustomEvent === "function") return false;
function CustomEvent(event, params) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();
(function (root, factory) {
if ( typeof define === 'function' && define.amd ) {
define([], (function () {
return factory(root);
}));
} else if ( typeof exports === 'object' ) {
module.exports = factory(root);
} else {
root.Gumshoe = factory(root);
}
})(typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : this, (function (window) {
'use strict';
//
// Defaults
//
var defaults = {
// Active classes
navClass: 'active',
contentClass: 'active',
// Nested navigation
nested: false,
nestedClass: 'active',
// Offset & reflow
offset: 0,
reflow: false,
// Event support
events: true
};
//
// Methods
//
/**
* Merge two or more objects together.
* @param {Object} objects The objects to merge together
* @returns {Object} Merged values of defaults and options
*/
var extend = function () {
var merged = {};
Array.prototype.forEach.call(arguments, (function (obj) {
for (var key in obj) {
if (!obj.hasOwnProperty(key)) return;
merged[key] = obj[key];
}
}));
return merged;
};
/**
* Emit a custom event
* @param {String} type The event type
* @param {Node} elem The element to attach the event to
* @param {Object} detail Any details to pass along with the event
*/
var emitEvent = function (type, elem, detail) {
// Make sure events are enabled
if (!detail.settings.events) return;
// Create a new event
var event = new CustomEvent(type, {
bubbles: true,
cancelable: true,
detail: detail
});
// Dispatch the event
elem.dispatchEvent(event);
};
/**
* Get an element's distance from the top of the Document.
* @param {Node} elem The element
* @return {Number} Distance from the top in pixels
*/
var getOffsetTop = function (elem) {
var location = 0;
if (elem.offsetParent) {
while (elem) {
location += elem.offsetTop;
elem = elem.offsetParent;
}
}
return location >= 0 ? location : 0;
};
/**
* Sort content from first to last in the DOM
* @param {Array} contents The content areas
*/
var sortContents = function (contents) {
if(contents) {
contents.sort((function (item1, item2) {
var offset1 = getOffsetTop(item1.content);
var offset2 = getOffsetTop(item2.content);
if (offset1 < offset2) return -1;
return 1;
}));
}
};
/**
* Get the offset to use for calculating position
* @param {Object} settings The settings for this instantiation
* @return {Float} The number of pixels to offset the calculations
*/
var getOffset = function (settings) {
// if the offset is a function run it
if (typeof settings.offset === 'function') {
return parseFloat(settings.offset());
}
// Otherwise, return it as-is
return parseFloat(settings.offset);
};
/**
* Get the document element's height
* @private
* @returns {Number}
*/
var getDocumentHeight = function () {
return Math.max(
document.body.scrollHeight, document.documentElement.scrollHeight,
document.body.offsetHeight, document.documentElement.offsetHeight,
document.body.clientHeight, document.documentElement.clientHeight
);
};
/**
* Determine if an element is in view
* @param {Node} elem The element
* @param {Object} settings The settings for this instantiation
* @param {Boolean} bottom If true, check if element is above bottom of viewport instead
* @return {Boolean} Returns true if element is in the viewport
*/
var isInView = function (elem, settings, bottom) {
var bounds = elem.getBoundingClientRect();
var offset = getOffset(settings);
if (bottom) {
return parseInt(bounds.bottom, 10) < (window.innerHeight || document.documentElement.clientHeight);
}
return parseInt(bounds.top, 10) <= offset;
};
/**
* Check if at the bottom of the viewport
* @return {Boolean} If true, page is at the bottom of the viewport
*/
var isAtBottom = function () {
if (window.innerHeight + window.pageYOffset >= getDocumentHeight()) return true;
return false;
};
/**
* Check if the last item should be used (even if not at the top of the page)
* @param {Object} item The last item
* @param {Object} settings The settings for this instantiation
* @return {Boolean} If true, use the last item
*/
var useLastItem = function (item, settings) {
if (isAtBottom() && isInView(item.content, settings, true)) return true;
return false;
};
/**
* Get the active content
* @param {Array} contents The content areas
* @param {Object} settings The settings for this instantiation
* @return {Object} The content area and matching navigation link
*/
var getActive = function (contents, settings) {
var last = contents[contents.length-1];
if (useLastItem(last, settings)) return last;
for (var i = contents.length - 1; i >= 0; i--) {
if (isInView(contents[i].content, settings)) return contents[i];
}
};
/**
* Deactivate parent navs in a nested navigation
* @param {Node} nav The starting navigation element
* @param {Object} settings The settings for this instantiation
*/
var deactivateNested = function (nav, settings) {
// If nesting isn't activated, bail
if (!settings.nested || !nav.parentNode) return;
// Get the parent navigation
var li = nav.parentNode.closest('li');
if (!li) return;
// Remove the active class
li.classList.remove(settings.nestedClass);
// Apply recursively to any parent navigation elements
deactivateNested(li, settings);
};
/**
* Deactivate a nav and content area
* @param {Object} items The nav item and content to deactivate
* @param {Object} settings The settings for this instantiation
*/
var deactivate = function (items, settings) {
// Make sure there are items to deactivate
if (!items) return;
// Get the parent list item
var li = items.nav.closest('li');
if (!li) return;
// Remove the active class from the nav and content
li.classList.remove(settings.navClass);
items.content.classList.remove(settings.contentClass);
// Deactivate any parent navs in a nested navigation
deactivateNested(li, settings);
// Emit a custom event
emitEvent('gumshoeDeactivate', li, {
link: items.nav,
content: items.content,
settings: settings
});
};
/**
* Activate parent navs in a nested navigation
* @param {Node} nav The starting navigation element
* @param {Object} settings The settings for this instantiation
*/
var activateNested = function (nav, settings) {
// If nesting isn't activated, bail
if (!settings.nested) return;
// Get the parent navigation
var li = nav.parentNode.closest('li');
if (!li) return;
// Add the active class
li.classList.add(settings.nestedClass);
// Apply recursively to any parent navigation elements
activateNested(li, settings);
};
/**
* Activate a nav and content area
* @param {Object} items The nav item and content to activate
* @param {Object} settings The settings for this instantiation
*/
var activate = function (items, settings) {
// Make sure there are items to activate
if (!items) return;
// Get the parent list item
var li = items.nav.closest('li');
if (!li) return;
// Add the active class to the nav and content
li.classList.add(settings.navClass);
items.content.classList.add(settings.contentClass);
// Activate any parent navs in a nested navigation
activateNested(li, settings);
// Emit a custom event
emitEvent('gumshoeActivate', li, {
link: items.nav,
content: items.content,
settings: settings
});
};
/**
* Create the Constructor object
* @param {String} selector The selector to use for navigation items
* @param {Object} options User options and settings
*/
var Constructor = function (selector, options) {
//
// Variables
//
var publicAPIs = {};
var navItems, contents, current, timeout, settings;
//
// Methods
//
/**
* Set variables from DOM elements
*/
publicAPIs.setup = function () {
// Get all nav items
navItems = document.querySelectorAll(selector);
// Create contents array
contents = [];
// Loop through each item, get it's matching content, and push to the array
Array.prototype.forEach.call(navItems, (function (item) {
// Get the content for the nav item
var content = document.getElementById(decodeURIComponent(item.hash.substr(1)));
if (!content) return;
// Push to the contents array
contents.push({
nav: item,
content: content
});
}));
// Sort contents by the order they appear in the DOM
sortContents(contents);
};
/**
* Detect which content is currently active
*/
publicAPIs.detect = function () {
// Get the active content
var active = getActive(contents, settings);
// if there's no active content, deactivate and bail
if (!active) {
if (current) {
deactivate(current, settings);
current = null;
}
return;
}
// If the active content is the one currently active, do nothing
if (current && active.content === current.content) return;
// Deactivate the current content and activate the new content
deactivate(current, settings);
activate(active, settings);
// Update the currently active content
current = active;
};
/**
* Detect the active content on scroll
* Debounced for performance
*/
var scrollHandler = function (event) {
// If there's a timer, cancel it
if (timeout) {
window.cancelAnimationFrame(timeout);
}
// Setup debounce callback
timeout = window.requestAnimationFrame(publicAPIs.detect);
};
/**
* Update content sorting on resize
* Debounced for performance
*/
var resizeHandler = function (event) {
// If there's a timer, cancel it
if (timeout) {
window.cancelAnimationFrame(timeout);
}
// Setup debounce callback
timeout = window.requestAnimationFrame((function () {
sortContents(contents);
publicAPIs.detect();
}));
};
/**
* Destroy the current instantiation
*/
publicAPIs.destroy = function () {
// Undo DOM changes
if (current) {
deactivate(current, settings);
}
// Remove event listeners
window.removeEventListener('scroll', scrollHandler, false);
if (settings.reflow) {
window.removeEventListener('resize', resizeHandler, false);
}
// Reset variables
contents = null;
navItems = null;
current = null;
timeout = null;
settings = null;
};
/**
* Initialize the current instantiation
*/
var init = function () {
// Merge user options into defaults
settings = extend(defaults, options || {});
// Setup variables based on the current DOM
publicAPIs.setup();
// Find the currently active content
publicAPIs.detect();
// Setup event listeners
window.addEventListener('scroll', scrollHandler, false);
if (settings.reflow) {
window.addEventListener('resize', resizeHandler, false);
}
};
//
// Initialize and return the public APIs
//
init();
return publicAPIs;
};
//
// Return the Constructor
//
return Constructor;
}));
|
/**
* Enter your Coinbase Sandbox API credentials below
*/
var Client = require('coinbase').Client;
var client = new Client({
'apiKey': 'your-coinbase-sandbox-api-key',
'apiSecret': 'your-coinbase-sandbox-api-secret',
'baseApiUri': 'https://api.sandbox.coinbase.com/v2/',
});
module.exports = client;
|
"use strict";
const fs = require('fs-extra');
const path = require('path');
const XmlWriter_1 = require('./XmlWriter');
function copyAndReplace(from, to, names, values) {
let data = fs.readFileSync(from, { encoding: 'utf8' });
for (let i = 0; i < names.length; ++i) {
data = data.replace(new RegExp(names[i], 'g'), values[i]);
}
fs.writeFileSync(to, data, { encoding: 'utf8' });
}
function IntelliJ(projectdir, options) {
let indir = path.join(__dirname, '..', 'Data', 'intellij');
let outdir = path.join(projectdir, 'project-' + options.system + '-intellij');
let sources = '';
for (let i = 0; i < options.sources.length; ++i) {
if (path.isAbsolute(options.sources[i])) {
sources += ' <sourceFolder url="file://' + options.sources[i] + '" isTestSource="false" />\n';
}
else {
sources += ' <sourceFolder url="file://$MODULE_DIR$/' + path.relative(outdir, path.resolve(options.from, options.sources[i])).replace(/\\/g, '/') + '" isTestSource="false" />\n';
}
}
let libraries = '';
for (let i = 0; i < options.libraries.length; ++i) {
if (path.isAbsolute(options.libraries[i].libpath)) {
libraries += ' <content url="file://' + options.libraries[i].libroot + '">\n';
libraries += ' <sourceFolder url="file://' + options.libraries[i].libpath + '" isTestSource="false" />\n';
}
else {
libraries += ' <content url="file://$MODULE_DIR$/' + path.relative(outdir, path.resolve(options.from, options.libraries[i].libroot)).replace(/\\/g, '/') + '">\n';
libraries += ' <sourceFolder url="file://$MODULE_DIR$/' + path.relative(outdir, path.resolve(options.from, options.libraries[i].libpath)).replace(/\\/g, '/') + '" isTestSource="false" />\n';
}
libraries += ' </content>\n';
}
let args = '';
let defines = '';
for (let i = 0; i < options.defines.length; ++i) {
defines += options.defines[i];
if (i < options.defines.length - 1)
defines += ',';
}
for (let param of options.parameters) {
defines += param + ',';
}
let target;
switch (options.language) {
case 'hl':
case 'cpp':
target = 'C++';
break;
case 'as':
target = 'Flash';
args = '-swf-version 16.0';
break;
case 'cs':
target = 'C#';
if (fs.existsSync(options.haxeDirectory) && fs.statSync(options.haxeDirectory).isDirectory() && fs.existsSync(path.join(options.haxeDirectory, 'netlib'))) {
args = '-net-std ' + path.relative(outdir, path.join(options.haxeDirectory, 'netlib'));
}
break;
case 'java':
target = 'Java';
if (fs.existsSync(options.haxeDirectory) && fs.statSync(options.haxeDirectory).isDirectory() && fs.existsSync(path.join(options.haxeDirectory, 'hxjava', 'hxjava-std.jar'))) {
args = '-java-lib ' + path.relative(outdir, path.join(options.haxeDirectory, 'hxjava', 'hxjava-std.jar'));
}
break;
case 'js':
target = 'JavaScript';
break;
}
fs.copySync(path.join(indir, 'name.iml'), path.join(outdir, options.name + '.iml'), { clobber: true });
copyAndReplace(path.join(indir, 'name.iml'), path.join(outdir, options.name + '.iml'), ['{name}', '{sources}', '{libraries}', '{target}', '{system}', '{args}'], [options.name, sources, libraries, target, options.system, args]);
fs.copySync(path.join(indir, 'idea', 'compiler.xml'), path.join(outdir, '.idea', 'compiler.xml'), { clobber: true });
copyAndReplace(path.join(indir, 'idea', 'haxe.xml'), path.join(outdir, '.idea', 'haxe.xml'), ['{defines}'], [defines]);
fs.copySync(path.join(indir, 'idea', 'misc.xml'), path.join(outdir, '.idea', 'misc.xml'), { clobber: true });
copyAndReplace(path.join(indir, 'idea', 'modules.xml'), path.join(outdir, '.idea', 'modules.xml'), ['{name}'], [options.name]);
fs.copySync(path.join(indir, 'idea', 'vcs.xml'), path.join(outdir, '.idea', 'vcs.xml'), { clobber: true });
copyAndReplace(path.join(indir, 'idea', 'name'), path.join(outdir, '.idea', '.name'), ['{name}'], [options.name]);
fs.copySync(path.join(indir, 'idea', 'copyright', 'profiles_settings.xml'), path.join(outdir, '.idea', 'copyright', 'profiles_settings.xml'), { clobber: true });
}
function hxml(projectdir, options) {
let data = '';
for (let i = 0; i < options.sources.length; ++i) {
if (path.isAbsolute(options.sources[i])) {
data += '-cp ' + options.sources[i] + '\n';
}
else {
data += '-cp ' + path.relative(projectdir, path.resolve(options.from, options.sources[i])) + '\n'; // from.resolve('build').relativize(from.resolve(this.sources[i])).toString());
}
}
for (let i = 0; i < options.libraries.length; ++i) {
if (path.isAbsolute(options.libraries[i].libpath)) {
data += '-cp ' + options.libraries[i].libpath + '\n';
}
else {
data += '-cp ' + path.relative(projectdir, path.resolve(options.from, options.libraries[i].libpath)) + '\n'; // from.resolve('build').relativize(from.resolve(this.sources[i])).toString());
}
}
for (let d in options.defines) {
let define = options.defines[d];
data += '-D ' + define + '\n';
}
if (options.language === 'cpp') {
data += '-cpp ' + path.normalize(options.to) + '\n';
}
else if (options.language === 'cs') {
data += '-cs ' + path.normalize(options.to) + '\n';
if (fs.existsSync(options.haxeDirectory) && fs.statSync(options.haxeDirectory).isDirectory() && fs.existsSync(path.join(options.haxeDirectory, 'netlib'))) {
data += '-net-std ' + path.relative(projectdir, path.join(options.haxeDirectory, 'netlib')) + '\n';
}
}
else if (options.language === 'java') {
data += '-java ' + path.normalize(options.to) + '\n';
if (fs.existsSync(options.haxeDirectory) && fs.statSync(options.haxeDirectory).isDirectory() && fs.existsSync(path.join(options.haxeDirectory, 'hxjava', 'hxjava-std.jar'))) {
data += '-java-lib ' + path.relative(projectdir, path.join(options.haxeDirectory, 'hxjava', 'hxjava-std.jar')) + '\n';
}
}
else if (options.language === 'js') {
data += '-js ' + path.normalize(options.to) + '\n';
}
else if (options.language === 'as') {
data += '-swf ' + path.normalize(options.to) + '\n';
data += '-swf-version ' + options.swfVersion + '\n';
data += '-swf-header ' + options.width + ':' + options.height + ':' + options.framerate + ':' + options.stageBackground + '\n';
}
else if (options.language === 'xml') {
data += '-xml ' + path.normalize(options.to) + '\n';
data += "--macro include('kha')\n";
}
else if (options.language === 'hl') {
data += '-hl ' + path.normalize(options.to) + '\n';
}
for (let param of options.parameters) {
data += param + '\n';
}
data += '-main Main' + '\n';
fs.outputFileSync(path.join(projectdir, 'project-' + options.system + '.hxml'), data);
}
exports.hxml = hxml;
function FlashDevelop(projectdir, options) {
let platform;
switch (options.language) {
case 'hl':
case 'cpp':
platform = 'C++';
break;
case 'as':
platform = 'Flash Player';
break;
case 'cs':
platform = 'C#';
break;
case 'java':
platform = 'Java';
break;
case 'js':
platform = 'JavaScript';
break;
}
options.swfVersion = 'swfVersion' in options ? options.swfVersion : 16.0;
options.stageBackground = 'stageBackground' in options ? options.stageBackground : 'ffffff';
options.framerate = 'framerate' in options ? options.framerate : 30;
let swfVersion = parseFloat(options.swfVersion).toFixed(1).split('.');
let output = {
n: 'output',
e: [
{
n: 'movie',
outputType: 'Application'
},
{
n: 'movie',
input: ''
},
{
n: 'movie',
path: path.normalize(options.to)
},
{
n: 'movie',
fps: options.framerate
},
{
n: 'movie',
width: options.width
},
{
n: 'movie',
height: options.height
},
{
n: 'movie',
version: swfVersion[0]
},
{
n: 'movie',
minorVersion: swfVersion[1]
},
{
n: 'movie',
platform: platform
},
{
n: 'movie',
background: '#' + options.stageBackground
}
]
};
if (fs.existsSync(options.haxeDirectory) && fs.statSync(options.haxeDirectory).isDirectory()) {
output.e.push({
n: 'movie',
preferredSDK: path.relative(projectdir, options.haxeDirectory)
});
}
var classpaths = [];
for (let i = 0; i < options.sources.length; ++i) {
if (path.isAbsolute(options.sources[i])) {
classpaths.push(options.sources[i]);
}
else {
classpaths.push(path.relative(projectdir, path.resolve(options.from, options.sources[i])));
}
}
for (let i = 0; i < options.libraries.length; ++i) {
if (path.isAbsolute(options.libraries[i].libpath)) {
classpaths.push(options.libraries[i].libpath);
}
else {
classpaths.push(path.relative(projectdir, path.resolve(options.from, options.libraries[i].libpath)));
}
}
let otheroptions = [
{
n: 'option',
showHiddenPaths: 'False'
}
];
if (options.language === 'cpp') {
otheroptions.push({
n: 'option',
testMovie: 'Custom'
});
otheroptions.push({
n: 'option',
testMovieCommand: 'run_' + options.system + '.bat'
});
}
else if (options.language === 'cs' || options.language === 'java') {
otheroptions.push({
n: 'option',
testMovie: 'OpenDocument'
});
otheroptions.push({
n: 'option',
testMovieCommand: ''
});
}
else if (options.language === 'js') {
otheroptions.push({
n: 'option',
testMovie: 'Webserver'
});
otheroptions.push({
n: 'option',
testMovieCommand: path.join(path.parse(options.to).dir, 'index.html')
});
}
else {
otheroptions.push({
n: 'option',
testMovie: 'Default'
});
}
let def = '';
for (let d of options.defines) {
def += '-D ' + d + '
';
}
if (options.language === 'java' && fs.existsSync(options.haxeDirectory) && fs.statSync(options.haxeDirectory).isDirectory() && fs.existsSync(path.join(options.haxeDirectory, 'hxjava', 'hxjava-std.jar'))) {
def += '-java-lib ' + path.relative(projectdir, path.join(options.haxeDirectory, 'hxjava', 'hxjava-std.jar')) + '
';
}
if (options.language === 'cs' && fs.existsSync(options.haxeDirectory) && fs.statSync(options.haxeDirectory).isDirectory() && fs.existsSync(path.join(options.haxeDirectory, 'netlib'))) {
def += '-net-std ' + path.relative(projectdir, path.join(options.haxeDirectory, 'netlib')) + '
';
}
def += '-D kha_output="' + path.resolve(path.join(projectdir, options.to)) + '"
';
for (let param of options.parameters) {
def += param + '
';
}
let project = {
n: 'project',
version: '2',
e: [
'Output SWF options',
output,
'Other classes to be compiled into your SWF',
{
n: 'classpaths',
e: classpaths
.reduce((a, b) => {
if (a.indexOf(b) < 0)
a.push(b);
return a;
}, [])
.map((e) => {
return { n: 'class', path: e };
})
},
'Build options',
{
n: 'build',
e: [
{
n: 'option',
directives: ''
},
{
n: 'option',
flashStrict: 'False'
},
{
n: 'option',
noInlineOnDebug: 'False'
},
{
n: 'option',
mainClass: 'Main'
},
{
n: 'option',
enabledebug: options.language === 'as' ? 'True' : 'False'
},
{
n: 'option',
additional: def
}
]
},
'haxelib libraries',
{
n: 'haxelib',
e: [
'example: <library name="..." />'
]
},
'Class files to compile (other referenced classes will automatically be included)',
{
n: 'compileTargets',
e: [
{
n: 'compile',
path: '..\\Sources\\Main.hx'
}
]
},
'Paths to exclude from the Project Explorer tree',
{
n: 'hiddenPaths',
e: [
'example: <hidden path="..." />'
]
},
'Executed before build',
{
n: 'preBuildCommand'
},
'Executed after build',
{
n: 'postBuildCommand',
alwaysRun: 'False'
},
'Other project options',
{
n: 'options',
e: otheroptions
},
'Plugin storage',
{
n: 'storage'
}
]
};
XmlWriter_1.writeXml(project, path.join(projectdir, 'project-' + options.system + '.hxproj'));
}
function writeHaxeProject(projectdir, options) {
FlashDevelop(projectdir, options);
IntelliJ(projectdir, options);
}
exports.writeHaxeProject = writeHaxeProject;
//# sourceMappingURL=HaxeProject.js.map
|
EventEmitter = Npm.require('events').EventEmitter;
|
import sms from 'sails-service-sms';
export default sms.create("<%= answers['services:sms:provider'] %>", sails.config.services.sms);
|
// This is a karma config file. For more details see
// http://karma-runner.github.io/0.13/config/configuration-file.html
// we are also using it with karma-webpack
// https://github.com/webpack/karma-webpack
var path = require('path')
var merge = require('webpack-merge')
var baseConfig = require('../webpack.config.js')
var utils = require('../build/utils')
var webpack = require('webpack')
var projectRoot = path.resolve(__dirname, '../')
var webpackConfig = merge(baseConfig, {
// use inline sourcemap for karma-sourcemap-loader
module: {
loaders: utils.styleLoaders()
},
devtool: '#inline-source-map',
vue: {
loaders: {
js: 'isparta'
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"testing"'
}
})
]
})
//
delete webpackConfig.output.library
delete webpackConfig.output.libraryTarget
// no need for app entry during tests
delete webpackConfig.entry
// make sure isparta loader is applied before eslint
webpackConfig.module.preLoaders = webpackConfig.module.preLoaders || []
webpackConfig.module.preLoaders.unshift({
test: /\.js$/,
loader: 'isparta',
include: path.resolve(projectRoot, 'src')
})
// only apply babel for test files when using isparta
webpackConfig.module.loaders.some(function (loader, i) {
if (loader.loader === 'babel') {
loader.include = path.resolve(projectRoot, 'test')
return true
}
})
module.exports = function (config) {
config.set({
// to run in additional browsers:
// 1. install corresponding karma launcher
// http://karma-runner.github.io/0.13/config/browsers.html
// 2. add it to the `browsers` array below.
browsers: ['PhantomJS'],
frameworks: ['mocha', 'sinon-chai'],
reporters: ['spec', 'coverage'],
files: ['./index.js'],
preprocessors: {
'./index.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
coverageReporter: {
dir: './coverage',
reporters: [
{ type: 'lcov', subdir: '.' },
{ type: 'text-summary' }
]
}
})
}
|
import { get } from '../get';
import { post } from '../post';
export function postLoginData(name,password){
const result = post('/api/login',{
name,
password
});
return result;
}
export function addUser(name,password){
const result = post('/api/sign',{
name: name,
password: password
});
return result;
}
|
$(document).ready(function() {
var editor = CodeMirror.fromTextArea('query', {
height: "250px",
parserfile: "parsesparql.js",
stylesheet: "css/sparqlcolors.css",
path: "/js/"
});
});
//$(document).ready(function() {
// $('#queryform').submit(function(e){
// // Fallback for browser that don't support the history API
// if (!('replaceState' in window.history)) {
// alert('replaceState not available');
// return true;
// }
//
// // Ensure middle, control and command clicks act normally
// if (e.which == 2 || e.metaKey || e.ctrlKey){
// alert('meta key preventing replaceState');
// return true;
// }
//
// var url = '?query=' + escape(editor.getCode());
// alert(url);
// $.get(url, function(results) {
// window.history.pushState(null, "SPARQL Query Results", url);
// alert(results.results.bindings[0]);
// $('#results').empty();
// if(results['results']['bindings']){
// for (var i in results['results']['bindings']) {
// var w = results['results']['bindings'][i];
// var desc = w['Description']['value'];
// var triples = w['Number_of_Triples']['value'];
// var agency = w['Agency']['value'];
// var title = w['Title']['value'];
//
// var ok = true;
// if (keyword.length > 0) {
// if (title.indexOf(keyword) == -1) {
// ok = false;
// }
// }
//
// if (ok) {
// add_dataset(w);
// }
// }
// }
// });
// return false;
// })
//});
|
'use strict';
(function () {
// Companys Controller Spec
describe('Companys Controller Tests', function () {
// Initialize global variables
var CompanysController,
scope,
$httpBackend,
$stateParams,
$location,
Authentication,
Companys,
mockCompany;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function () {
jasmine.addMatchers({
toEqualData: function (util, customEqualityTesters) {
return {
compare: function (actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function ($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_, _Authentication_, _Companys_) {
// Set a new global scope
scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
Authentication = _Authentication_;
Companys = _Companys_;
// create mock company
mockCompany = new Companys({
_id: '525a8422f6d0f87f0e407a33',
title: 'An Company about MEAN',
content: 'MEAN rocks!'
});
// Mock logged in user
Authentication.user = {
roles: ['user']
};
// Initialize the Companys controller.
CompanysController = $controller('CompanysController', {
$scope: scope
});
}));
it('$scope.find() should create an array with at least one company object fetched from XHR', inject(function (Companys) {
// Create a sample companys array that includes the new company
var sampleCompanys = [mockCompany];
// Set GET response
$httpBackend.expectGET('api/companys').respond(sampleCompanys);
// Run controller functionality
scope.find();
$httpBackend.flush();
// Test scope value
expect(scope.companys).toEqualData(sampleCompanys);
}));
it('$scope.findOne() should create an array with one company object fetched from XHR using a companyId URL parameter', inject(function (Companys) {
// Set the URL parameter
$stateParams.companyId = mockCompany._id;
// Set GET response
$httpBackend.expectGET(/api\/companys\/([0-9a-fA-F]{24})$/).respond(mockCompany);
// Run controller functionality
scope.findOne();
$httpBackend.flush();
// Test scope value
expect(scope.company).toEqualData(mockCompany);
}));
describe('$scope.create()', function () {
var sampleCompanyPostData;
beforeEach(function () {
// Create a sample company object
sampleCompanyPostData = new Companys({
title: 'An Company about MEAN',
content: 'MEAN rocks!'
});
// Fixture mock form input values
scope.title = 'An Company about MEAN';
scope.content = 'MEAN rocks!';
spyOn($location, 'path');
});
it('should send a POST request with the form input values and then locate to new object URL', inject(function (Companys) {
// Set POST response
$httpBackend.expectPOST('api/companys', sampleCompanyPostData).respond(mockCompany);
// Run controller functionality
scope.create(true);
$httpBackend.flush();
// Test form inputs are reset
expect(scope.title).toEqual('');
expect(scope.content).toEqual('');
// Test URL redirection after the company was created
expect($location.path.calls.mostRecent().args[0]).toBe('companys/' + mockCompany._id);
}));
it('should set scope.error if save error', function () {
var errorMessage = 'this is an error message';
$httpBackend.expectPOST('api/companys', sampleCompanyPostData).respond(400, {
message: errorMessage
});
scope.create(true);
$httpBackend.flush();
expect(scope.error).toBe(errorMessage);
});
});
describe('$scope.update()', function () {
beforeEach(function () {
// Mock company in scope
scope.company = mockCompany;
});
it('should update a valid company', inject(function (Companys) {
// Set PUT response
$httpBackend.expectPUT(/api\/companys\/([0-9a-fA-F]{24})$/).respond();
// Run controller functionality
scope.update(true);
$httpBackend.flush();
// Test URL location to new object
expect($location.path()).toBe('/companys/' + mockCompany._id);
}));
it('should set scope.error to error response message', inject(function (Companys) {
var errorMessage = 'error';
$httpBackend.expectPUT(/api\/companys\/([0-9a-fA-F]{24})$/).respond(400, {
message: errorMessage
});
scope.update(true);
$httpBackend.flush();
expect(scope.error).toBe(errorMessage);
}));
});
describe('$scope.remove(company)', function () {
beforeEach(function () {
// Create new companys array and include the company
scope.companys = [mockCompany, {}];
// Set expected DELETE response
$httpBackend.expectDELETE(/api\/companys\/([0-9a-fA-F]{24})$/).respond(204);
// Run controller functionality
scope.remove(mockCompany);
});
it('should send a DELETE request with a valid companyId and remove the company from the scope', inject(function (Companys) {
expect(scope.companys.length).toBe(1);
}));
});
describe('scope.remove()', function () {
beforeEach(function () {
spyOn($location, 'path');
scope.company = mockCompany;
$httpBackend.expectDELETE(/api\/companys\/([0-9a-fA-F]{24})$/).respond(204);
scope.remove();
$httpBackend.flush();
});
it('should redirect to companys', function () {
expect($location.path).toHaveBeenCalledWith('companys');
});
});
});
}());
|
export default {
name: 'ReferenceLine',
props: [
{
name: 'xAxisId',
type: 'String | Number',
defaultVal: '0',
isOptional: false,
desc: {
'en-US': 'The id of x-axis which is corresponding to the data.',
'zh-CN': '参考线对应的 x 轴的 id。',
},
},
{
name: 'yAxisId',
type: 'String | Number',
defaultVal: '0',
isOptional: false,
desc: {
'en-US': 'The id of y-axis which is corresponding to the data.',
'zh-CN': '参考线对应的 y 轴的 id。',
},
},
{
name: 'x',
type: 'Number | String',
defaultVal: 'null',
isOptional: true,
desc: {
'en-US':
'If set a string or a number, a vertical line perpendicular to the x-axis specified by xAxisId will be drawn. If the specified x-axis is a number axis, the type of x must be Number. If the specified x-axis is a category axis, the value of x must be one of the categorys, otherwise no line will be drawn.',
'zh-CN':
'用来描述一条垂直于 x 轴的线,当 x 轴是数值类型的坐标轴时,这个值必须为数值类型。当 x 轴为类目轴时, 这个值必须为 x 轴 domain 中的一个元素。',
},
},
{
name: 'y',
type: 'Number | String',
defaultVal: 'null',
isOptional: true,
desc: {
'en-US':
'If set a string or a number, a horizontal line perpendicular to the y-axis specified by yAxisId will be drawn. If the specified y-axis is a number axis, the type of y must be Number. If the specified y-axis is a category axis, the value of y must be one of the categorys, otherwise no line will be drawn.',
'zh-CN':
'用来描述一条垂直于 y 轴的线,当 y 轴是数值类型的坐标轴时,这个值必须为数值类型。当 y 轴为类目轴时, 这个值必须为 y 轴 domain 中的一个元素。',
},
},
{
name: 'alwaysShow',
type: 'Boolean',
defaultVal: 'false',
isOptional: false,
desc: {
'en-US':
'If the corresponding axis is a number axis and this option is set true, the value of reference line will be take into account when calculate the domain of corresponding axis, so that the reference line will always show.',
'zh-CN': '是否根据整参考线的值调整相应的坐标轴 domain,来保证参考线一定在可视区域内。',
},
examples: [
{
name: 'A LineChart with alwaysShow ReferenceLine',
url: 'https://codesandbox.io/s/reference-line-alwaysshow-ybxon',
isExternal: true,
},
],
},
{
name: 'viewBox',
type: 'Object',
defaultVal: 'null',
isOptional: false,
desc: {
'en-US':
'The box of viewing area, which has the shape of {x: someVal, y: someVal, width: someVal, height: someVal}, usually calculated internally.',
'zh-CN': '图表的可视区域',
},
},
{
name: 'xAxis',
type: 'Object',
defaultVal: 'null',
isOptional: false,
desc: {
'en-US': 'The configuration of the corresponding x-axis, usually calculated internally.',
'zh-CN': 'x 轴配置。',
},
},
{
name: 'yAxis',
type: 'Object',
defaultVal: 'null',
isOptional: false,
desc: {
'en-US': 'The configuration of the corresponding y-axis, usually calculated internally.',
'zh-CN': 'y 轴配置。',
},
},
{
name: 'label',
type: 'String | Number | ReactElement | Function',
defaultVal: 'null',
isOptional: true,
desc: {
'en-US':
'If set a string or a number, default label will be drawn, and the option is content. If set a React element, the option is the custom react element of drawing label. If set a function, the function will be called to render customized label.',
'zh-CN':
'当值为简单类型的数值或者字符串时,这个值会被渲染成文字标签。当值为 React element,会克隆这个元素来渲染文字标签。',
},
format: [
'<ReferenceLine x="05" label="Middle" />',
'<ReferenceLine y={400} yAxisId="left" label={<CustomizedLabel />} />',
],
examples: [
{
name: 'ReferenceLines with label',
url: '/examples/LineChartWithReferenceLines',
},
],
},
{
name: 'isFront',
type: 'Boolean',
defaultVal: 'false',
isOptional: false,
desc: {
'en-US': 'If set true, the line will be rendered in front of bars in BarChart, etc.',
'zh-CN': '是否展示在图表的最上层。',
},
},
{
name: 'strokeWidth',
type: 'Number',
defaultVal: '1',
isOptional: true,
desc: {
'en-US': 'The width of the stroke',
'zh-CN': '虚线的宽度',
},
},
{
name: 'segment',
type: 'Array',
defaultVal: undefined,
isOptional: true,
desc: {
'en-US': 'Array of endpoints in { x, y } format. These endpoints would be used to draw the ReferenceLine.',
'zh-CN': '{x,y}格式的端点数组。这些端点将用于绘制参考线。',
},
},
],
parentComponents: ['AreaChart', 'BarChart', 'LineChart', 'ComposedChart', 'ScatterChart'],
childrenComponents: ['Label'],
};
|
var Class = require('uberclass')
, Q = require('q');
module.exports = Class.extend({
instance: null,
Model: null
}, {
db: null,
setup: function(dbAdapter) {
this.db = dbAdapter;
},
startTransaction: function() {
return this.db.startTransaction();
},
query: function(sql) {
console.log('Running SQL: ' + sql);
return this.db.query(sql, null, { raw: true });
},
findById: function (id) {
var deferred = Q.defer();
if (this.Class.Model !== null) {
if( this.Class.Model.ORM ){
this.Class.Model.find(id).success(deferred.resolve).error(deferred.reject);
} else {
this.Class.Model.findById(id, function(err, result){
if ( err ) {
process.nextTick(function() {
deferred.reject();
});
} else {
process.nextTick(function() {
deferred.resolve(result);
});
}
});
}
} else {
process.nextTick(function() {
deferred.reject('Function not defined and no Model provided');
});
}
return deferred.promise;
},
findAll: function (options) {
options = options || {};
var deferred = Q.defer();
if (this.Class.Model !== null) {
if ( this.Class.Model.ORM ) {
this.Class.Model.findAll().success(deferred.resolve).error(deferred.reject);
} else {
this.Class.Model.find(function(err, result){
if ( err ) {
process.nextTick(function() {
deferred.reject();
});
} else {
process.nextTick(function() {
deferred.resolve(result);
});
}
});
}
} else {
process.nextTick(function() {
deferred.reject('Function not defined and no Model provided.');
});
}
return deferred.promise;
},
find: function (options) {
options = options || {};
var deferred = Q.defer();
if (this.Class.Model !== null) {
if ( this.Class.Model.ORM ) {
this.Class.Model.findAll(options).success(deferred.resolve).error(deferred.reject);
} else {
this.Class.Model.find(options, function(err, result){
if ( err ) {
process.nextTick(function() {
deferred.reject();
});
} else {
process.nextTick(function() {
deferred.resolve(result);
});
}
});
}
} else {
process.nextTick(function() {
deferred.reject('Function not defined and no Model provided.');
});
}
return deferred.promise;
},
create: function (data) {
var deferred = Q.defer();
if (this.Class.Model !== null) {
if ( this.Class.Model.ORM ) {
this.Class.Model.create(data)
.success(deferred.resolve)
.error(deferred.reject);
} else {
new this.Class.Model(data).save(function(err, result){
if ( err ) {
process.nextTick(function() {
deferred.reject();
});
} else {
process.nextTick(function() {
deferred.resolve(result);
});
}
});
}
} else {
process.nextTick(function() {
deferred.reject('Function not defined and no Model provided.');
});
}
return deferred.promise;
},
update: function (id, data) {
var deferred = Q.defer();
if (this.Class.Model !== null) {
if ( this.Class.Model.ORM ) {
this.Class.Model.find(id)
.success(function ( model ) {
model.updateAttributes(data)
.success(deferred.resolve)
.error(deferred.reject);
})
.error(deferred.reject);
} else {
this.Class.Model.findOneAndUpdate({_id: id}, data, function(err, result){
if ( err ) {
process.nextTick(function() {
deferred.reject();
});
} else {
process.nextTick(function() {
deferred.resolve(result);
});
}
});
}
} else {
process.nextTick(function() {
deferred.reject('Function not defined and no Model provided.');
});
}
return deferred.promise;
},
destroy: function (id) {
var deferred = Q.defer();
if (this.Class.Model !== null) {
if ( this.Class.Model.ORM ) {
this.Class.Model.find(id)
.success(function ( model ) {
model.destroy()
.success(deferred.resolve)
.error(deferred.reject);
})
.error(deferred.reject);
} else {
this.Class.Model.findById(id).remove(function(err, result){
if ( err ) {
process.nextTick(function() {
deferred.reject();
});
} else {
process.nextTick(function() {
deferred.resolve(result);
});
}
});
}
} else {
process.nextTick(function() {
deferred.reject('Function not defined and no Model provided.');
});
}
return deferred.promise;
}
});
|
"use strict";
jest.dontMock('../../../src/index.js');
let ReactDOM = require('react-dom');
let React = require('react');
let TestUtils = require('react-addons-test-utils');
let Ad = require('../../../src/index.js').Ad;
describe('Ad', function () {
it('should have .ui.ad class by default', function () {
var instance = TestUtils.renderIntoDocument(
<Ad></Ad>
);
expect(ReactDOM.findDOMNode(instance).className).toMatch('ui');
expect(ReactDOM.findDOMNode(instance).className).toMatch('ad');
});
it('should have child by default', function () {
var instance = TestUtils.renderIntoDocument(
<Ad>123</Ad>
);
expect(ReactDOM.findDOMNode(instance).textContent).toEqual('123');
});
it('should have custom class with custom className', function () {
var instance = TestUtils.renderIntoDocument(
<Ad className="custom"></Ad>
);
expect(ReactDOM.findDOMNode(instance).className).toMatch('custom');
});
});
|
// Custom scripts
$(document).ready(function () {
// MetsiMenu
$('#side-menu').metisMenu();
// Collapse ibox function
$('.collapse-link').click( function() {
var ibox = $(this).closest('div.ibox');
var button = $(this).find('i');
var content = ibox.find('div.ibox-content');
content.slideToggle(200);
button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down');
ibox.toggleClass('').toggleClass('border-bottom');
setTimeout(function () {
ibox.resize();
ibox.find('[id^=map-]').resize();
}, 50);
});
// Close ibox function
$('.close-link').click( function() {
var content = $(this).closest('div.ibox');
content.remove();
});
// Small todo handler
$('.check-link').click( function(){
var button = $(this).find('i');
var label = $(this).next('span');
button.toggleClass('fa-check-square').toggleClass('fa-square-o');
label.toggleClass('todo-completed');
return false;
});
// Append config box / Only for demo purpose
// $.get("skin-config.html", function (data) {
// $('body').append(data);
// });
// minimalize menu
$('.navbar-minimalize').click(function () {
$("body").toggleClass("mini-navbar");
SmoothlyMenu();
})
// tooltips
$('.tooltip-demo').tooltip({
selector: "[data-toggle=tooltip]",
container: "body"
})
// Move modal to body
// Fix Bootstrap backdrop issu with animation.css
$('.modal').appendTo("body")
// Full height of sidebar
function fix_height() {
var heightWithoutNavbar = $("body > #wrapper").height() - 61;
$(".sidebard-panel").css("min-height", heightWithoutNavbar + "px");
}
fix_height();
// Fixed Sidebar
// unComment this only whe you have a fixed-sidebar
// $(window).bind("load", function() {
// if($("body").hasClass('fixed-sidebar')) {
// $('.sidebar-collapse').slimScroll({
// height: 'auto',
// railOpacity: 0.9,
// });
// }
// })
$(window).bind("load resize click scroll", function() {
if(!$("body").hasClass('body-small')) {
fix_height();
}
})
$("[data-toggle=popover]")
.popover();
});
// For demo purpose - animation css script
function animationHover(element, animation){
element = $(element);
element.hover(
function() {
element.addClass('animated ' + animation);
},
function(){
//wait for animation to finish before removing classes
window.setTimeout( function(){
element.removeClass('animated ' + animation);
}, 2000);
});
}
// Minimalize menu when screen is less than 768px
$(function() {
$(window).bind("load resize", function() {
if ($(this).width() < 769) {
$('body').addClass('body-small')
} else {
$('body').removeClass('body-small')
}
})
})
function SmoothlyMenu() {
if (!$('body').hasClass('mini-navbar') || $('body').hasClass('body-small')) {
// Hide menu in order to smoothly turn on when maximize menu
$('#side-menu').hide();
// For smoothly turn on menu
setTimeout(
function () {
$('#side-menu').fadeIn(500);
}, 100);
} else if ($('body').hasClass('fixed-sidebar')){
$('#side-menu').hide();
setTimeout(
function () {
$('#side-menu').fadeIn(500);
}, 300);
} else {
// Remove all inline style from jquery fadeIn function to reset menu state
$('#side-menu').removeAttr('style');
}
}
// Dragable panels
function WinMove() {
var element = "[class*=col]";
var handle = ".ibox-title";
var connect = "[class*=col]";
$(element).sortable(
{
handle: handle,
connectWith: connect,
tolerance: 'pointer',
forcePlaceholderSize: true,
opacity: 0.8,
})
.disableSelection();
};
|
ScalaJS.is.scala_scalajs_js_Function15 = (function(obj) {
return (!(!((obj && obj.$classData) && obj.$classData.ancestors.scala_scalajs_js_Function15)))
});
ScalaJS.as.scala_scalajs_js_Function15 = (function(obj) {
if ((ScalaJS.is.scala_scalajs_js_Function15(obj) || (obj === null))) {
return obj
} else {
ScalaJS.throwClassCastException(obj, "scala.scalajs.js.Function15")
}
});
ScalaJS.isArrayOf.scala_scalajs_js_Function15 = (function(obj, depth) {
return (!(!(((obj && obj.$classData) && (obj.$classData.arrayDepth === depth)) && obj.$classData.arrayBase.ancestors.scala_scalajs_js_Function15)))
});
ScalaJS.asArrayOf.scala_scalajs_js_Function15 = (function(obj, depth) {
if ((ScalaJS.isArrayOf.scala_scalajs_js_Function15(obj, depth) || (obj === null))) {
return obj
} else {
ScalaJS.throwArrayCastException(obj, "Lscala.scalajs.js.Function15;", depth)
}
});
ScalaJS.data.scala_scalajs_js_Function15 = new ScalaJS.ClassTypeData({
scala_scalajs_js_Function15: 0
}, true, "scala.scalajs.js.Function15", undefined, {
scala_scalajs_js_Function15: 1,
java_lang_Object: 1
});
//@ sourceMappingURL=Function15.js.map
|
var Pipeline = require('./pipeline');
var Task = require('./task');
var EventList = require('./eventList');
var actions = require('./actions');
describe('Pipeline', function () {
describe('Series Pipeline', function () {
// We already test that tasks know how to determine their own next actions,
// so it's ok to just test this with one simple task.
it('Should get correct next actions with an empty task list', function () {
var pipeline = new Pipeline.Series([new Task({
name: 'newTask',
type: 'activity'
}), new Task({
name: 'nextTask',
type: 'activity'
})]);
var next = pipeline.getNextActions(new EventList([]));
expect(next.length).toEqual(1);
});
it('Should get correct next actions with all completed tasks', function () {
var pipeline = new Pipeline.Series([new Task({
name: 'newTask',
type: 'activity'
})]);
var next = pipeline.getNextActions(new EventList([{
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "newTask"
},
}]));
expect(next.length).toEqual(0);
});
});
describe('Parallel Pipeline', function () {
it('Should get correct next actions with an empty task list', function () {
var pipeline = new Pipeline.Parallel([new Task({
name: 'newTask',
type: 'activity'
}), new Task({
name: 'nextTask',
type: 'activity'
})]);
var next = pipeline.getNextActions(new EventList([]));
expect(next.length).toEqual(2);
});
it('Should get correct next actions with one completed task', function () {
var pipeline = new Pipeline.Parallel([new Task({
name: 'newTask',
type: 'activity'
}), new Task({
name: 'nextTask',
type: 'activity'
})]);
var next = pipeline.getNextActions(new EventList([{
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "newTask"
},
}]));
expect(next.length).toEqual(1);
});
it('Should get correct next actions with all completed tasks', function () {
var pipeline = new Pipeline.Parallel([new Task({
name: 'newTask',
type: 'activity'
}), new Task({
name: 'nextTask',
type: 'activity'
})]);
var next = pipeline.getNextActions(new EventList([{
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "newTask"
},
}, {
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "nextTask"
},
}]));
expect(next.length).toEqual(0);
});
});
describe('Continuous Pipeline', function () {
it('Should get correct next actions with an empty task list', function () {
var pipeline = new Pipeline.Continuous([new Task({
name: 'newTask',
type: 'activity'
}), new Task({
name: 'nextTask',
type: 'activity'
})]);
var next = pipeline.getNextActions(new EventList([]));
expect(next.length).toEqual(1);
});
it('Should get correct next actions with one completed task', function () {
var pipeline = new Pipeline.Continuous([new Task({
name: 'newTask',
type: 'activity'
}), new Task({
name: 'nextTask',
type: 'activity'
})]);
var next = pipeline.getNextActions(new EventList([{
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {},
}]));
expect(next.length).toEqual(1);
});
it('Should get correct next actions with all completed tasks', function () {
var pipeline = new Pipeline.Continuous([new Task({
name: 'newTask',
type: 'activity'
}), new Task({
name: 'nextTask',
type: 'activity'
})]);
var next = pipeline.getNextActions(new EventList([{
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "newTask"
},
}, {
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "nextTask"
},
}]));
expect(next.length).toEqual(1);
expect(next[0]._name).toEqual('newTask');
});
it('Should get correct next actions with all completed tasks but break signal', function () {
var pipeline = new Pipeline.Continuous([new Task({
name: 'newTask',
type: 'activity'
}), new Task({
name: 'nextTask',
type: 'activity'
})]).onSignal('breakContinuous', 'break');
var next = pipeline.getNextActions(new EventList([{
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "newTask"
},
}, {
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "nextTask"
},
}, {
"eventType": "WorkflowExecutionSignaled",
"workflowExecutionSignaledEventAttributes": {
"signalName": "breakContinuous"
}
}]));
expect(next.length).toEqual(0);
});
it('Should get correct next actions with all completed tasks on second go-around', function () {
var pipeline = new Pipeline.Continuous([new Task({
name: 'newTask',
type: 'activity'
}), new Task({
name: 'nextTask',
type: 'activity'
})]);
var next = pipeline.getNextActions(new EventList([{
"eventId": 1,
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "newTask"
},
}, {
"eventId": 2,
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "nextTask"
},
}, {
"eventId": 3,
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "newTask"
},
}]));
expect(next.length).toEqual(1);
expect(next[0]._name).toEqual('nextTask');
});
});
describe('Compound pipelines', function () {
it('should get next task with noop', function () {
var pipeline = new Pipeline.Series([
new Task({
name: 'TestWorkflowCreate',
type: 'activity',
activityVersion: '0.1'
}),
new Pipeline.Continuous([
new Task({
name: 'TestWorkflowNextOffer',
type: 'activity',
activityVersion: '0.1'
}),
new Task({
name: 'TestWorkflowTimeout',
type: 'timer',
delay: 30
})
]).onSignal(['TestWorkflowAccepted', 'TestWorkflowAllRejected'], 'break')
]);
var next = pipeline.getNextActions(new EventList([{
"eventId": 1,
"eventTimestamp": "2015-07-18T18:56:17.048Z",
"eventType": "WorkflowExecutionStarted",
"workflowExecutionStartedEventAttributes": {
"childPolicy": "TERMINATE",
"executionStartToCloseTimeout": "1800",
"input": "INPUT DATA",
"parentInitiatedEventId": 0,
"taskList": {
"name": "TestWorkflow"
},
"taskStartToCloseTimeout": "1800",
"workflowType": {
"name": "Test Workflow",
"version": "0.1"
}
}
}, {
"decisionTaskScheduledEventAttributes": {
"startToCloseTimeout": "1800",
"taskList": {
"name": "TestWorkflow"
}
},
"eventId": 2,
"eventTimestamp": "2015-07-18T18:56:17.048Z",
"eventType": "DecisionTaskScheduled"
}, {
"decisionTaskStartedEventAttributes": {
"identity": "test-decider2",
"scheduledEventId": 2
},
"eventId": 3,
"eventTimestamp": "2015-07-18T18:56:17.134Z",
"eventType": "DecisionTaskStarted"
}, {
"decisionTaskCompletedEventAttributes": {
"scheduledEventId": 2,
"startedEventId": 3
},
"eventId": 4,
"eventTimestamp": "2015-07-18T18:56:17.587Z",
"eventType": "DecisionTaskCompleted"
}, {
"activityTaskScheduledEventAttributes": {
"activityId": "TestWorkflowCreate",
"activityType": {
"name": "TestWorkflowCreate",
"version": "0.1"
},
"decisionTaskCompletedEventId": 4,
"heartbeatTimeout": "60",
"scheduleToCloseTimeout": "360",
"scheduleToStartTimeout": "60",
"startToCloseTimeout": "300",
"taskList": {
"name": "TestWorkflow"
}
},
"eventId": 5,
"eventTimestamp": "2015-07-18T18:56:17.587Z",
"eventType": "ActivityTaskScheduled"
}, {
"activityTaskStartedEventAttributes": {
"identity": "6092f0c0-2d7e-11e5-98f3-8b31aed30187",
"scheduledEventId": 5
},
"eventId": 6,
"eventTimestamp": "2015-07-18T18:56:17.637Z",
"eventType": "ActivityTaskStarted"
}, {
"activityTaskCompletedEventAttributes": {
"result": "some output",
"scheduledEventId": 5,
"startedEventId": 6
},
"eventId": 7,
"eventTimestamp": "2015-07-18T18:56:17.807Z",
"eventType": "ActivityTaskCompleted"
}, {
"decisionTaskScheduledEventAttributes": {
"startToCloseTimeout": "1800",
"taskList": {
"name": "TestWorkflow"
}
},
"eventId": 8,
"eventTimestamp": "2015-07-18T18:56:17.807Z",
"eventType": "DecisionTaskScheduled"
}, {
"decisionTaskStartedEventAttributes": {
"identity": "test-decider2",
"scheduledEventId": 8
},
"eventId": 9,
"eventTimestamp": "2015-07-18T18:56:17.865Z",
"eventType": "DecisionTaskStarted"
}]));
expect(next.length).toEqual(1);
expect(next[0]._name).toEqual('TestWorkflowNextOffer');
});
});
describe('Bug tests w/ real world data', function () {
it('should get next task in continuous pipe', function () {
var pipeline = new Pipeline.Series([
new Task({
name: 'TestWorkflowCreate',
type: 'activity',
activityVersion: '0.1'
}),
new Pipeline.Continuous([
new Task({
name: 'TestWorkflowNextOffer',
type: 'activity',
activityVersion: '0.1'
}),
new Task({
name: 'TestWorkflowTimeout',
type: 'timer',
delay: 30
})
]).onSignal(['TestWorkflowAccepted', 'TestWorkflowAllRejected'], 'break')
]);
var next = pipeline.getNextActions(new EventList([{
"eventId": 1,
"eventTimestamp": "2015-07-18T19:04:43.625Z",
"eventType": "WorkflowExecutionStarted",
"workflowExecutionStartedEventAttributes": {
"childPolicy": "TERMINATE",
"executionStartToCloseTimeout": "1800",
"input": "INPUT DATA",
"parentInitiatedEventId": 0,
"taskList": {
"name": "TestWorkflow"
},
"taskStartToCloseTimeout": "1800",
"workflowType": {
"name": "Test Workflow",
"version": "0.1"
}
}
}, {
"decisionTaskScheduledEventAttributes": {
"startToCloseTimeout": "1800",
"taskList": {
"name": "TestWorkflow"
}
},
"eventId": 2,
"eventTimestamp": "2015-07-18T19:04:43.625Z",
"eventType": "DecisionTaskScheduled"
}, {
"decisionTaskStartedEventAttributes": {
"identity": "test-decider2",
"scheduledEventId": 2
},
"eventId": 3,
"eventTimestamp": "2015-07-18T19:04:43.722Z",
"eventType": "DecisionTaskStarted"
}, {
"decisionTaskCompletedEventAttributes": {
"scheduledEventId": 2,
"startedEventId": 3
},
"eventId": 4,
"eventTimestamp": "2015-07-18T19:04:43.985Z",
"eventType": "DecisionTaskCompleted"
}, {
"activityTaskScheduledEventAttributes": {
"activityId": "TestWorkflowCreate",
"activityType": {
"name": "TestWorkflowCreate",
"version": "0.1"
},
"decisionTaskCompletedEventId": 4,
"heartbeatTimeout": "60",
"scheduleToCloseTimeout": "360",
"scheduleToStartTimeout": "60",
"startToCloseTimeout": "300",
"taskList": {
"name": "TestWorkflow"
}
},
"eventId": 5,
"eventTimestamp": "2015-07-18T19:04:43.985Z",
"eventType": "ActivityTaskScheduled"
}, {
"activityTaskStartedEventAttributes": {
"identity": "cf37df30-2d7f-11e5-b683-21807b9ad451",
"scheduledEventId": 5
},
"eventId": 6,
"eventTimestamp": "2015-07-18T19:04:44.145Z",
"eventType": "ActivityTaskStarted"
}, {
"activityTaskCompletedEventAttributes": {
"result": "{\"autoCancelSeconds\":60}",
"scheduledEventId": 5,
"startedEventId": 6
},
"eventId": 7,
"eventTimestamp": "2015-07-18T19:04:44.362Z",
"eventType": "ActivityTaskCompleted"
}, {
"decisionTaskScheduledEventAttributes": {
"startToCloseTimeout": "1800",
"taskList": {
"name": "TestWorkflow"
}
},
"eventId": 8,
"eventTimestamp": "2015-07-18T19:04:44.362Z",
"eventType": "DecisionTaskScheduled"
}, {
"decisionTaskStartedEventAttributes": {
"identity": "test-decider2",
"scheduledEventId": 8
},
"eventId": 9,
"eventTimestamp": "2015-07-18T19:04:44.409Z",
"eventType": "DecisionTaskStarted"
}, {
"decisionTaskCompletedEventAttributes": {
"scheduledEventId": 8,
"startedEventId": 9
},
"eventId": 10,
"eventTimestamp": "2015-07-18T19:04:44.608Z",
"eventType": "DecisionTaskCompleted"
}, {
"activityTaskScheduledEventAttributes": {
"activityId": "TestWorkflowNextOffer",
"activityType": {
"name": "TestWorkflowNextOffer",
"version": "0.1"
},
"decisionTaskCompletedEventId": 10,
"heartbeatTimeout": "60",
"scheduleToCloseTimeout": "360",
"scheduleToStartTimeout": "60",
"startToCloseTimeout": "300",
"taskList": {
"name": "TestWorkflow"
}
},
"eventId": 11,
"eventTimestamp": "2015-07-18T19:04:44.608Z",
"eventType": "ActivityTaskScheduled"
}, {
"activityTaskStartedEventAttributes": {
"identity": "cf37df30-2d7f-11e5-b683-21807b9ad451",
"scheduledEventId": 11
},
"eventId": 12,
"eventTimestamp": "2015-07-18T19:04:44.653Z",
"eventType": "ActivityTaskStarted"
}, {
"activityTaskCompletedEventAttributes": {
"result": "{\"autoCancelSeconds\":60}",
"scheduledEventId": 11,
"startedEventId": 12
},
"eventId": 13,
"eventTimestamp": "2015-07-18T19:04:44.864Z",
"eventType": "ActivityTaskCompleted"
}, {
"decisionTaskScheduledEventAttributes": {
"startToCloseTimeout": "1800",
"taskList": {
"name": "TestWorkflow"
}
},
"eventId": 14,
"eventTimestamp": "2015-07-18T19:04:44.864Z",
"eventType": "DecisionTaskScheduled"
}, {
"decisionTaskStartedEventAttributes": {
"identity": "test-decider2",
"scheduledEventId": 14
},
"eventId": 15,
"eventTimestamp": "2015-07-18T19:04:44.922Z",
"eventType": "DecisionTaskStarted"
}, {
"decisionTaskCompletedEventAttributes": {
"scheduledEventId": 14,
"startedEventId": 15
},
"eventId": 16,
"eventTimestamp": "2015-07-18T19:04:45.193Z",
"eventType": "DecisionTaskCompleted"
}, {
"eventId": 17,
"eventTimestamp": "2015-07-18T19:04:45.193Z",
"eventType": "TimerStarted",
"timerStartedEventAttributes": {
"control": "TestWorkflowTimeout",
"decisionTaskCompletedEventId": 16,
"startToFireTimeout": "60",
"timerId": "da4241e0-2d7f-11e5-8349-d971d941cdec"
}
}, {
"eventId": 18,
"eventTimestamp": "2015-07-18T19:05:45.199Z",
"eventType": "TimerFired",
"timerFiredEventAttributes": {
"startedEventId": 17,
"timerId": "da4241e0-2d7f-11e5-8349-d971d941cdec"
}
}, {
"decisionTaskScheduledEventAttributes": {
"startToCloseTimeout": "1800",
"taskList": {
"name": "TestWorkflow"
}
},
"eventId": 19,
"eventTimestamp": "2015-07-18T19:05:45.199Z",
"eventType": "DecisionTaskScheduled"
}]));
expect(next.length).toEqual(1);
expect(next[0]._name).toEqual('TestWorkflowNextOffer');
});
});
describe('onSignal', function () {
it('Should execute a task on signal but also execute the next task in a parallel pipeline',
function () {
var pipeline = new Pipeline.Parallel([new Task({
name: 'newTask',
type: 'activity'
}), new Task({
name: 'nextTask',
type: 'activity'
})]).onSignal('FooSignal', new Task({
name: 'signalTask',
type: 'activity'
}));
var next = pipeline.getNextActions(new EventList([{
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "newTask"
},
}, {
"eventType": "WorkflowExecutionSignaled",
"workflowExecutionSignaledEventAttributes": {
"signalName": "FooSignal"
}
}]));
expect(next.length).toEqual(2);
expect(next[0]._name).toEqual('signalTask');
expect(next[1]._name).toEqual('nextTask');
});
it('Should execute multiple signal tasks in parallel when it a series pipeline receives both signals',
function () {
var pipeline = new Pipeline.Series([new Task({
name: 'newTask',
type: 'activity'
}), new Task({
name: 'nextTask',
type: 'activity'
})]).onSignal('FooSignal', new Task({
name: 'signalTask',
type: 'activity'
})).onSignal('BarSignal', new Task({
name: 'signalTask2',
type: 'activity'
}));
var next = pipeline.getNextActions(new EventList([{
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "newTask"
},
}, {
"eventType": "WorkflowExecutionSignaled",
"workflowExecutionSignaledEventAttributes": {
"signalName": "FooSignal"
}
}, {
"eventType": "WorkflowExecutionSignaled",
"workflowExecutionSignaledEventAttributes": {
"signalName": "BarSignal"
}
}]));
expect(next.length).toEqual(2);
expect(next[0]._name).toEqual('signalTask');
expect(next[1]._name).toEqual('signalTask2');
});
it('Should execute a task on signal and execute only one task in the signal parallel pipe ' +
'because the other one has already completed',
function () {
var pipeline = new Pipeline.Series([new Task({
name: 'newTask',
type: 'activity'
}), new Task({
name: 'nextTask',
type: 'activity'
})]).onSignal('FooSignal', new Pipeline.Parallel([new Task({
name: 'signalTask1',
type: 'activity'
}), new Task({
name: 'signalTask2',
type: 'activity'
})]));
var next = pipeline.getNextActions(new EventList([{
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "newTask"
},
}, {
"eventType": "WorkflowExecutionSignaled",
"workflowExecutionSignaledEventAttributes": {
"signalName": "FooSignal"
}
}, {
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "signalTask1"
}
}]));
expect(next.length).toEqual(1);
expect(next[0]._name).toEqual('signalTask2');
});
it('Should execute a task on signal and execute both tasks in the signal parallel pipe',
function () {
var pipeline = new Pipeline.Series([new Task({
name: 'newTask',
type: 'activity'
}), new Task({
name: 'nextTask',
type: 'activity'
})]).onSignal('FooSignal', new Pipeline.Parallel([new Task({
name: 'signalTask1',
type: 'activity'
}), new Task({
name: 'signalTask2',
type: 'activity'
})]));
var next = pipeline.getNextActions(new EventList([{
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "newTask"
},
}, {
"eventType": "WorkflowExecutionSignaled",
"workflowExecutionSignaledEventAttributes": {
"signalName": "FooSignal"
}
}]));
expect(next.length).toEqual(2);
expect(next[0]._name).toEqual('signalTask1');
expect(next[1]._name).toEqual('signalTask2');
});
it('Should ignore a signal and just execute the next task in a signal pipe if that ' +
'pipeline has not yet finished before the next signal is received',
function () {
var pipeline = new Pipeline.Series([new Task({
name: 'newTask',
type: 'activity'
}), new Task({
name: 'nextTask',
type: 'activity'
})]).onSignal('FooSignal', new Pipeline.Parallel([new Task({
name: 'signalTask1',
type: 'activity'
}), new Task({
name: 'signalTask2',
type: 'activity'
})]));
var next = pipeline.getNextActions(new EventList([{
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "newTask"
},
}, {
"eventType": "WorkflowExecutionSignaled",
"workflowExecutionSignaledEventAttributes": {
"signalName": "FooSignal"
}
}, {
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "signalTask1"
}
}, {
"eventType": "WorkflowExecutionSignaled",
"workflowExecutionSignaledEventAttributes": {
"signalName": "FooSignal"
}
}]));
expect(next.length).toEqual(1);
expect(next[0]._name).toEqual('signalTask2');
});
it('Should ignore a signal and just ignore the tasks in a signal pipe if that pipeline ' +
'has not yet finished before the next signal is received but all tasks have been scheduled',
function () {
var pipeline = new Pipeline.Series([new Task({
name: 'newTask',
type: 'activity'
}), new Task({
name: 'nextTask',
type: 'activity'
})]).onSignal('FooSignal', new Pipeline.Parallel([new Task({
name: 'signalTask1',
type: 'activity'
}), new Task({
name: 'signalTask2',
type: 'activity'
})]));
var next = pipeline.getNextActions(new EventList([{
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "newTask"
},
}, {
"eventType": "WorkflowExecutionSignaled",
"workflowExecutionSignaledEventAttributes": {
"signalName": "FooSignal"
}
}, {
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "signalTask1"
}
}, {
"eventType": "WorkflowExecutionSignaled",
"workflowExecutionSignaledEventAttributes": {
"signalName": "FooSignal"
}
}, {
"eventType": "ActivityTaskStarted",
"activityTaskStartedEventAttributes": {
"activityId": "signalTask2"
}
}]));
expect(next.length).toEqual(1);
expect(next[0] instanceof actions.Noop).toEqual(true);
});
it('Should just proceed normally if a signal was received and handled since it was received',
function () {
var pipeline = new Pipeline.Series([new Task({
name: 'newTask',
type: 'activity'
}), new Task({
name: 'nextTask',
type: 'activity'
})]).onSignal('FooSignal', new Pipeline.Parallel([new Task({
name: 'signalTask1',
type: 'activity'
}), new Task({
name: 'signalTask2',
type: 'activity'
})]));
var next = pipeline.getNextActions(new EventList([{
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "newTask"
},
}, {
"eventType": "WorkflowExecutionSignaled",
"workflowExecutionSignaledEventAttributes": {
"signalName": "FooSignal"
}
}, {
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "signalTask1"
}
}, {
"eventType": "WorkflowExecutionSignaled",
"workflowExecutionSignaledEventAttributes": {
"signalName": "FooSignal"
}
}, {
"eventType": "ActivityTaskCompleted",
"activityTaskCompletedEventAttributes": {
"activityId": "signalTask2"
}
}]));
expect(next.length).toEqual(1);
expect(next[0]._name).toEqual('nextTask');
});
it('Signals should never be called if there are no signal events',
function () {
var pipeline = new Pipeline.Series([new Task({
name: 'newTask',
type: 'activity'
})]).onSignal('FooSignal', new Task({
name: 'signalTask1',
type: 'activity'
}));
var next = pipeline.getNextActions(new EventList([]));
expect(next.length).toEqual(1);
expect(next[0]._name).toEqual('newTask');
});
});
describe('child workflows', function () {
it('should get correct next action', function () {
var pipeline = new Pipeline.Series([
new Task({
name: 'myChildWorkflow',
type: 'childWorkflow',
workflowName: 'FooWorkflow',
workflowVersion: '1.0'
}),
new Task({
name: 'nextTask',
type: 'activity',
})
]);
var next = pipeline.getNextActions(new EventList([{
"eventId": 1,
"eventTimestamp": "2015-07-30T16:09:57.879Z",
"eventType": "WorkflowExecutionStarted",
"workflowExecutionStartedEventAttributes": {
"childPolicy": "TERMINATE",
"executionStartToCloseTimeout": "1800",
"input": "INPUT DATA",
"parentInitiatedEventId": 0,
"taskList": {
"name": "RoundRobin"
},
"taskStartToCloseTimeout": "1800",
"workflowType": {
"name": "Test Workflow",
"version": "0.1"
}
}
}, {
"eventId": 11,
"eventTimestamp": "2015-07-30T16:09:58.822Z",
"eventType": "StartChildWorkflowExecutionInitiated",
"startChildWorkflowExecutionInitiatedEventAttributes": {
"childPolicy": "TERMINATE",
"decisionTaskCompletedEventId": 10,
"executionStartToCloseTimeout": "600",
"taskList": {
"name": "imageProcessingSampleDecisionTaskList"
},
"control": "myChildWorkflow",
"taskStartToCloseTimeout": "300",
"workflowId": "asdf1234",
"workflowType": {
"name": "ProcessFile",
"version": "1.0"
}
}
}, {
"childWorkflowExecutionStartedEventAttributes": {
"initiatedEventId": 11,
"workflowExecution": {
"runId": "22KiNYwGwnzLPWIwirdLML3JWMH6ylHWkHchi/IeCFDKM=",
"workflowId": "asdf1234"
},
"workflowType": {
"name": "ProcessFile",
"version": "1.0"
}
},
"eventId": 12,
"eventTimestamp": "2015-07-30T16:09:58.955Z",
"eventType": "ChildWorkflowExecutionStarted"
}, {
"decisionTaskScheduledEventAttributes": {
"startToCloseTimeout": "1800",
"taskList": {
"name": "RoundRobin"
}
},
"eventId": 13,
"eventTimestamp": "2015-07-30T16:09:58.955Z",
"eventType": "DecisionTaskScheduled"
}, {
"decisionTaskStartedEventAttributes": {
"identity": "test-decider2",
"scheduledEventId": 13
},
"eventId": 14,
"eventTimestamp": "2015-07-30T16:09:59.006Z",
"eventType": "DecisionTaskStarted"
}]));
expect(next).toEqual([new actions.Noop()]);
});
});
});
|
"use strict";
var app = angular.module("MFCCountdown",['ui.bootstrap', 'ui.keypress']);
app.run(function($rootScope){
function uniqueid(){
// always start with a letter (for DOM friendlyness)
var idstr=String.fromCharCode(Math.floor((Math.random()*25)+65));
do {
// between numbers and characters (48 is 0 and 90 is Z (42-48 = 90)
var ascicode=Math.floor((Math.random()*42)+48);
if (ascicode<58 || ascicode>64){
// exclude all chars between : (58) and @ (64)
idstr+=String.fromCharCode(ascicode);
}
} while (idstr.length<32);
return (idstr);
}
if (!localStorage["mfccUserId"])
localStorage["mfccUserId"] = uniqueid();
$rootScope.userId = localStorage["mfccUserId"];
});
// app.factory('FBCountdowns', function($firebase, $rootScope) {
// var fbUrl = 'https://tipbot.firebaseio.com/mfccountdown/users/' + $rootScope.userId;
// return $firebase(new Firebase(fbUrl));
// });
//wrap MFCSocket as an injectable service
app.factory("Socket", function(){
return MFCSocket;
});
FastClick.attach(document.body);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.