code stringlengths 2 1.05M |
|---|
'use strict';
angular.module('categories').controller('CategoriesController', ['$scope','$stateParams','$location','Categories',
function($scope, $stateParams, $location, Categories) {
// Controller Logic
$scope.create = function(){
//redirect after save
var category = new Categories({
name: this.name,
description: this.description
});
category.$save(function(response){
$location.path('categories/'+response._id);
//Clear form fields
$scope.name = '';
},function(errorResponse){
$scope.error = errorResponse.data.message;
});
};
$scope.find = function(){
$scope.categories = Categories.query();
};
$scope.findOne = function() {
$scope.category = Categories.get({
categoryId: $stateParams.categoryId
});
};
}
]); |
var Product = require('../models/product')
module.exports = {
index: function (req, res, next) {
var success = req.flash('success')[0];
Product.getAll({}, function (products) {
res.render('shop/index', {title: 'Shopping cart', products: products, success: success});
});
}
} |
export const defaultState = {
loading: false
};
export default function reducer(state = defaultState, action) {
switch (action.type) {
case "PAY_IS_LOADING":
return {
...state,
loading: true
};
case "PAY_IS_NOT_LOADING":
return {
...state,
loading: false
};
}
return state;
}
|
require("../src/Lay.js");
Lay.server({
path:{
log:"log",
conf:"config"
}
}); |
var assert = require('chai').assert;
var ElMap = require('../uglymol').ElMap;
var util = require('../perf/util');
/* Note: axis order in ccp4 maps is tricky. It was tested by re-sectioning,
* i.e. changing axis order, of a map with CCP4 mapmask:
mapmask mapin 1mru_2mFo-DFc.ccp4 mapout 1mru_yzx.ccp4 << eof
AXIS Y Z X
MODE mapin
eof
*/
describe('ElMap', function () {
'use strict';
var dmap_buf = util.open_as_array_buffer('1mru.omap');
var cmap_buf = util.open_as_array_buffer('1mru.map');
var dmap = new ElMap();
var cmap = new ElMap();
it('#from_dsn6', function () {
dmap.from_dsn6(dmap_buf);
});
it('#from_ccp4', function () {
cmap.from_ccp4(cmap_buf);
});
it('compare unit cells', function () {
for (var i = 0; i < 6; i++) {
assert.closeTo(dmap.unit_cell.parameters[i],
cmap.unit_cell.parameters[i], 0.02);
}
});
});
|
Blockly.Blocks['setup'] = {
init: function() {
this.appendDummyInput()
.appendField("setup");
this.appendStatementInput("do")
.setCheck(null)
.appendField("do");
this.setInputsInline(false);
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setColour(230);
this.setTooltip('The setup() function is called once when the program starts.');
this.setHelpUrl('https://p5js.org/reference/#/p5/setup');
}
}; |
/**
* The Rewriter module that is only executed once at the start of query execution.
* It will split up the query into a static and dynamic part while rewriting the dynamic part to be able to extract the
* time annotation.
*/
var Composer = require('./SparqlComposer.js'),
util = require('./RdfUtils.js');
require('js-object-clone');
var debugMode = !!process.env.DEBUG;
function Rewriter(ldf, type, target, cachingEnabled) {
if (!(this instanceof Rewriter))
return new Rewriter(ldf, type, target, cachingEnabled);
this._ldf = ldf;
this._taCounter = 0;
this._type = type;
this._target = target;
this._timeAnnotationFetchQueries = []; // Only used for implicit graph annotation.
this._cachingEnabled = cachingEnabled;
}
Rewriter.prototype._tripleTransformer = function() {
return {
reification: util.timeAnnotatedReification,
singletonproperties: util.timeAnnotatedSingletonProperties,
graphs: util.timeAnnotatedQuads,
implicitgraphs: util.timeAnnotatedNoop,
}[this._type];
};
/**
* Rewrite the given query.
* @param query The original parsed SPARQL query.
* @param splitCallback The callback that will return a context.
* The context will contain:
* counter: executed queries counter, starts at 0.
* hasTimeAnnotation: If the query has time annotation.
* distinct: If the query has a DISTINCT clause.
* staticHolder: The static query.
* dynamicQuery: The dynamic query.
* intersectedVariables: The intersected variables in both queries.
* staticStep: If the executor should pass through the static step. If false, this means the static query is empty.
* dynamicStep: If the executor should pass through the dynamic step. If false, this means the dynamic query is empty.
*/
Rewriter.prototype.split = function(query, splitCallback) {
var self = this;
this.query = this._bNodesToVariables(query);
this._splitStaticDynamicQuery(this.query.prefixes, this.query.variables, this.query.where, function(staticHolder, dynamicHolder) {
polishQueryHolder(staticHolder);
polishQueryHolder(dynamicHolder);
var intersectedVariables = util.intersection(staticHolder.variables, dynamicHolder.variables);
var hasTimeAnnotation = !!dynamicHolder.where;
// Loop over static patterns and move those to the dynamic holder that only have intersected variables.
self._extractSingularStatic(staticHolder.prefixes, staticHolder.variables, staticHolder.where, intersectedVariables, function (dynamicResult) {
if (dynamicResult) dynamicHolder = self._appendAllQueryHolders(dynamicHolder, [dynamicResult], false);
});
polishQueryHolder(staticHolder);
polishQueryHolder(dynamicHolder);
// It is now possible that the static query is EMPTY, so we indicate whether or not the dynamic results
// should be passed through the static query executor.
var reductedVariables = util.reduction(staticHolder.variables, intersectedVariables);
var staticStep = reductedVariables.length > 0;
// The dynamic query can also be empty!
var dynamicStep = dynamicHolder.variables.length > 0;
var dynamicResult = new Composer(dynamicHolder).compose();
self._debug(function () {
console.log("------\nNew query:\n------");
console.log("Has time annotation? " + (hasTimeAnnotation ? "true" : "false") + "\n");
console.log("~~~ Dynamic:");
console.log(dynamicResult);
console.log("------");
if (staticStep) {
console.log("~~~ Static:");
console.log(new Composer(staticHolder).compose());
console.log("------");
} else {
console.log("~~~ No static step!");
}
console.log("\nLive query results:\n------------------------\n");
});
var context = {
counter: 0,
hasTimeAnnotation: hasTimeAnnotation,
distinct: self.query.distinct,
staticHolder: staticHolder,
dynamicQuery: dynamicResult,
intersectedVariables: intersectedVariables,
staticStep: staticStep,
dynamicStep: dynamicStep,
timeAnnotationQuery: function(bindings) {
return new Composer(polishQueryHolder(self._flattenQueryHolders(self._timeAnnotationFetchQueries.map(function(query) {
return query(bindings);
})))).compose();
},
};
splitCallback(context);
});
/**
* Prepare the query holder to be composed into an actual SPARQL query.
*/
function polishQueryHolder(queryHolder) {
queryHolder.variables = [];
queryHolder.type = 'query';
queryHolder.queryType = 'SELECT';
// Some steps could have introduced patterns that are simply false because we could not remove them from the array
// at that moment, so we remove them now.
var newWhere = [];
queryHolder.where.forEach(function(el) {
if(el) newWhere.push(el);
});
queryHolder.where = newWhere;
// These will not become visible to the user, but is required to make query splitting work.
self._appendAllVariables(queryHolder.variables, queryHolder.where);
queryHolder.variables = Object.keys(queryHolder.variables);
return queryHolder;
}
};
/**
* Convert all blank nodes to variables in the given query.
* Only the WHERE clause will be changed, no new variables will be added to SELECT.
* Collisions with already existing variables will be avoided.
*/
Rewriter.prototype._bNodesToVariables = function(query) {
var newQuery = Object.clone(query, true);
newQuery.variables = {};
this._appendAllVariables(newQuery.variables, newQuery.where);
var convertedVariables = Object.clone(newQuery.variables, true);
this._bNodesToVariablesInner(newQuery.variables, convertedVariables, newQuery.where);
newQuery.variables = Object.keys(newQuery.variables);
return newQuery;
};
/**
* Split up a query into a dynamic and static part.
* @param prefixes The accumulated prefixes
* @param variables The accumulated variables
* @param where The input query part.
* @param resultsCallback Callback with the resulting static and dynamic queries.
*/
Rewriter.prototype._splitStaticDynamicQuery = function(prefixes, variables, where, resultsCallback) {
var self = this,
resultStaticQuery, resultDynamicQuery;
if(where instanceof Array) {
resultStaticQuery = [],
resultDynamicQuery = [];
var called = 0;
for(var i = 0; i < where.length; i++) {
this._splitStaticDynamicQuery(prefixes, variables, where[i], function(staticHolder, dynamicHolder) {
called++;
staticHolder.where && resultStaticQuery.push(staticHolder);
dynamicHolder.where && resultDynamicQuery.push(dynamicHolder);
if(called == where.length) { // If at the end of the loop
resultsCallback(self._flattenQueryHolders(resultStaticQuery), self._flattenQueryHolders(resultDynamicQuery));
}
});
}
} else if(where.type == "bgp") {
this._splitStaticDynamicQuery(prefixes, variables, where.triples, function(staticHolder, dynamicHolder) {
resultStaticQuery = self._initQueryHolder(where),
resultDynamicQuery = self._initQueryHolder(where);
self._appendAllQueryHolders(resultStaticQuery, [staticHolder], true);
self._appendAllQueryHolders(resultDynamicQuery, [dynamicHolder], true);
resultStaticQuery.where.triples = staticHolder.where;
resultDynamicQuery.where.triples = dynamicHolder.where;
resultsCallback(resultStaticQuery, resultDynamicQuery);
});
} else if(where.type == "union") {
this._splitStaticDynamicQuery(prefixes, variables, where.patterns, function(staticHolder, dynamicHolder) {
resultStaticQuery = self._initQueryHolder(where),
resultDynamicQuery = self._initQueryHolder(where);
if(dynamicHolder.where.length == 0) {
self._appendAllQueryHolders(resultStaticQuery, [staticHolder], true);
resultStaticQuery.where.patterns = staticHolder;
} else if(staticHolder.where.length == 0) {
self._appendAllQueryHolders(resultDynamicQuery, [dynamicHolder], true);
resultDynamicQuery.where.patterns = dynamicHolder;
} else {
// In this case we have a mixed union of static and dynamic parts
// IMPOSSIBLE to have disjoint static and dynamic parts, so we will put everything inside the dynamic part.
// Note that optimisations for this case are very likely! (For example when only ONE union-group with mixed
// static/dynamic parts after some transformations to make sure that the union part is last in the query)
// TODO: test this!
self._appendAllQueryHolders(resultDynamicQuery, [staticHolder, dynamicHolder], true);
resultDynamicQuery.where.patterns = self._flattenQueryHolders([staticHolder, dynamicHolder]);
}
resultsCallback(resultStaticQuery, resultDynamicQuery);
});
} else {
this._shouldTransform(prefixes, variables, where, function(shouldTransform) {
var resultStaticQuery = self._initQueryHolder(),
resultDynamicQuery = self._initQueryHolder();
if(shouldTransform) {
var modified = self._tripleTransformer()(where, function() {
resultDynamicQuery.variables["?initial" + self._taCounter] = true;
resultDynamicQuery.variables["?final" + self._taCounter] = true;
resultDynamicQuery.prefixes["tmp"] = util.prefixes.tmp;
resultDynamicQuery.prefixes["sp"] = util.prefixes.sp;
return self._taCounter++;
});
self._appendQueryPart(resultDynamicQuery, modified, prefixes, variables);
} else {
self._appendQueryPart(resultStaticQuery, where, prefixes, variables);
}
resultsCallback(resultStaticQuery, resultDynamicQuery);
});
}
};
/**
* Private function for the blank node to variable conversion.
* @param originalVariables The original variables, immutable.
* @param originalAndNewVariables The original and newly generated variables, mutable. This acts also as output.
* @param queryPart The mutable WHERE clause of the query, also acts as output.
*/
Rewriter.prototype._bNodesToVariablesInner = function(originalVariables, originalAndNewVariables, queryPart) {
var self = this;
if(queryPart instanceof Array) {
queryPart.forEach(function(el) { self._bNodesToVariablesInner(originalVariables, originalAndNewVariables, el); });
} else if(queryPart.type == "bgp") {
this._bNodesToVariablesInner(originalVariables, originalAndNewVariables, queryPart.triples);
} else if(queryPart.type == "union") {
this._bNodesToVariablesInner(originalVariables, originalAndNewVariables, queryPart.patterns);
} else {
util.fields.forEach(function(field) {
if(util.isBlankNode(queryPart[field])) {
var variable,
attempCounter = 0;
// This loop is required to avoid collisions with existing variables.
while(originalVariables[variable = '?' + queryPart[field].substr(2, queryPart[field].length) + attempCounter++]);
queryPart[field] = variable;
originalAndNewVariables[variable] = true;
}
});
}
};
/**
* Append all variables to the variables array from the WHERE clause that are not in that array yet.
*/
Rewriter.prototype._appendAllVariables = function(variables, queryPart) {
var self = this;
if(queryPart instanceof Array) {
queryPart.forEach(function(el) { self._appendAllVariables(variables, el); });
} else if(queryPart.type == "bgp") {
this._appendAllVariables(variables, queryPart.triples);
} else if(queryPart.type == "union") {
this._appendAllVariables(variables, queryPart.patterns);
} else {
util.fields.forEach(function(field) {
if(util.isVariable(queryPart[field])) variables[queryPart[field]] = true;
});
}
};
/**
* Extract the static patterns that only have intersected variables and move them to the dynamic holder which will be
* returned in the callback.
*/
Rewriter.prototype._extractSingularStatic = function(prefixes, variables, where, intersectedVariables, resultsCallback) {
var resultDynamicQuery,
self = this;
if(where instanceof Array) {
resultDynamicQuery = [];
var called = 0;
for(var i = 0; i < where.length; i++) {
this._extractSingularStatic(prefixes, variables, where[i], intersectedVariables, function(dynamicHolder) {
called++;
if(dynamicHolder.where && (!Array.isArray(dynamicHolder.where) || dynamicHolder.where.length > 0)) {
// Remove query part from the static query.
where[i] = false;
// And then add it to the dynamic query.
resultDynamicQuery.push(dynamicHolder);
}
if(called == where.length) { // If at the end of the loop
resultsCallback(self._flattenQueryHolders(resultDynamicQuery));
}
});
}
} else if(where.type == "bgp") {
this._extractSingularStatic(prefixes, variables, where.triples, intersectedVariables, function(dynamicHolder) {
resultDynamicQuery = self._initQueryHolder();
if(dynamicHolder) resultDynamicQuery.where = [];
self._appendAllQueryHolders(resultDynamicQuery, [dynamicHolder], false);
resultDynamicQuery.where.triples = dynamicHolder.where;
resultsCallback(resultDynamicQuery);
});
} else if(where.type == "union") {
this._extractSingularStatic(prefixes, variables, where.patterns, intersectedVariables, function(dynamicHolder) {
resultDynamicQuery = self._initQueryHolder();
if(dynamicHolder) resultDynamicQuery.where = [];
self._appendAllQueryHolders(resultDynamicQuery, [dynamicHolder], false);
resultDynamicQuery.where.patterns = self._flattenQueryHolders([dynamicHolder]);
resultsCallback(resultDynamicQuery);
});
} else {
var shouldExtract = true;
util.fields.forEach(function(field) {
if(util.isVariable(where[field]) && intersectedVariables.indexOf(where[field]) < 0) shouldExtract = false;
});
if(!this._cachingEnabled || shouldExtract) {
resultDynamicQuery = self._initQueryHolder();
self._appendQueryPart(resultDynamicQuery, where, prefixes, variables);
resultsCallback(resultDynamicQuery);
} else {
resultsCallback(false);
}
}
};
Rewriter.prototype._flatten = function(array) { return [].concat.apply([], array); };
/**
* Create a new simple query holder.
* @param where Optional parameter that will be deep-cloned and used as where clause, otherwise where will be false.
*/
Rewriter.prototype._initQueryHolder = function(where) {
return {
variables: {},
prefixes: {},
where: where ? Object.clone(where, true) : false
};
};
/**
* Append data to the given query holder.
*/
Rewriter.prototype._appendQueryPart = function(queryHolder, where, prefixes, variables) {
// Copy query part
queryHolder.where = where;
if(where instanceof Array) {
where.forEach(appendMeta);
} else {
appendMeta(where);
}
function appendMeta(where) {
// Copy used variables
variables.forEach(function (variable) {
var shouldAdd = util.fields.reduce(function (acc, field) {
return acc || (variable == where[field]);
}, false);
if (shouldAdd) {
queryHolder.variables[variable] = true;
}
});
// Copy used prefixes
Object.keys(prefixes).forEach(function (prefix) {
var shouldAdd = util.fields.reduce(function (acc, field) {
return acc || (where[field].indexOf(prefix) == 0);
});
if (shouldAdd) {
queryHolder.prefixes[prefix] = prefixes[prefix];
}
});
}
};
/**
* Merges a list of query holders into one query holder with a list as where clause.
*/
Rewriter.prototype._flattenQueryHolders = function(queryHolders) {
var queryHolder = this._initQueryHolder();
queryHolder.where = [];
return this._appendAllQueryHolders(queryHolder, queryHolders);
};
/**
* Append a list of query holders to one query holder where the concatenation of the where clause
* can be skipped if skipQueryPart is true.
*/
Rewriter.prototype._appendAllQueryHolders = function(queryHolder, queryHolders, skipQueryPart) {
var self = this;
queryHolders.forEach(function(qHolder) {
queryHolder.variables = util.concatMap(queryHolder.variables, qHolder.variables);
queryHolder.prefixes = util.concatMap(queryHolder.prefixes, qHolder.prefixes);
if(!skipQueryPart) queryHolder.where = queryHolder.where.concat(qHolder.where);
});
return queryHolder;
};
/**
* Copy all properties from the source to the self object.
*/
Rewriter.prototype._extendObject = util.extendObject;
/**
* Check if the given triple should be transformed (reified || ...).
* @param prefixes The accumulated prefixes
* @param variables The accumulated variables
* @param triple The triple object.
* @param callback The true/false callback.
*/
Rewriter.prototype._shouldTransform = function(prefixes, variables, triple, callback) {
var self = this;
var subQuery, composer, result;
if(this._type == "implicitgraphs") {
subQuery= util.singularQuery([triple], prefixes);
composer = new Composer(subQuery);
result = composer.compose();
this._isQueryNotEmptyConditional(result, function (bindings, innerCallback) {
composer = new Composer(util.materializedImplicitGraphQuery(bindings, triple, prefixes, self._target));
result = composer.compose();
self._isQueryNotEmpty(result, function (res) {
/*self._debug(function () {
console.log("T: --- \n" + result + "\n--- \n");
console.log(res);
});*/
innerCallback(!res);
});
},
function(isNotEmpty) {
self._debug(function () {
console.log("Triple " + JSON.stringify(triple) + " should" + (isNotEmpty ? "" : " NOT") + " be transformed.");
});
if(isNotEmpty) {
variables["?initial" + self._taCounter] = true;
variables["?final" + self._taCounter] = true;
prefixes["tmp"] = util.prefixes.tmp;
prefixes["sp"] = util.prefixes.sp;
var label = self._taCounter++;
self._timeAnnotationFetchQueries.push(function(bindings) {
return util.materializedImplicitGraphQuery(bindings, triple, prefixes, self._target, function() {
return label;
});
});
}
callback(isNotEmpty);
});
} else {
subQuery = {
"type": "query",
"prefixes": this._extendObject({
"tmp": util.prefixes.tmp,
"sp": util.prefixes.sp
}, prefixes),
"queryType": "SELECT",
"variables": variables.concat([
"?initial",
"?final"
]),
"where": [
{
"type": "bgp",
"triples": this._tripleTransformer()(triple),
}
]
};
composer = new Composer(subQuery);
result = composer.compose();
this._debug(function () {
console.log("Transformation: --- \n" + result + "\n--- \n");
});
this._isQueryNotEmpty(result, function (res) {
self._debug(function () {
console.log("Triple " + JSON.stringify(triple) + " should" + (res ? "" : " NOT") + " be transformed.");
});
callback(res);
});
}
};
/**
* Perform a query to the server to check if the given query gives at least one result.
* @param subQuery The query.
* @param callback The callback with true (query result is not empty) or false (query result is empty).
* Second argument is the optional result.
*/
Rewriter.prototype._isQueryNotEmpty = function(subQuery, callback) {
var results = util.executeQuery(this._ldf, this._target, subQuery);
var shouldCall = true;
results.on('data', function (row) {
results.close();
shouldCall && !(shouldCall = false) && callback(true, row);
// Stop the iterator, we already have all the info we need.
});
results.on('end', function() {
shouldCall && !(shouldCall = false) && callback(false);
shouldCall = false;
});
results.on('error', function(e) {
console.log(e);
shouldCall && callback(false);
shouldCall = false;
});
};
/**
* Perform a query to the server to check if the given query gives at least one result.
* @param subQuery The query.
* @param innerResultsCallback First argument is the actual result row.
* Second argument is the callback for the inner results, should return false if the
* execution should stop.
* @param resultCallback The callback with true (query result is not empty) or false (query result is empty).
*/
Rewriter.prototype._isQueryNotEmptyConditional = function(subQuery, innerResultsCallback, resultCallback) {
var results = util.executeQuery(this._ldf, this._target, subQuery);
var shouldCall = true;
var barrierCounter = 1;
var finished = false;
var globalHadResults = false;
results.on('data', function (row) {
barrierCounter++;
if(shouldCall) {
innerResultsCallback(row, function(shouldCallInner) {
if(!shouldCallInner) {
shouldCall = shouldCallInner;
}
callBarrier(!shouldCallInner);
});
}
});
results.on('end', function() {
shouldCall && !(shouldCall = false) && callBarrier(false);
shouldCall = false;
});
results.on('error', function(e) {
console.log(e);
shouldCall && resultCallback(false);
shouldCall = false;
});
function callBarrier(hadResults) {
barrierCounter--;
globalHadResults = globalHadResults || hadResults;
if((barrierCounter == 0 || hadResults) && !finished) {
finished = true;
resultCallback(globalHadResults);
// Stop the iterator, we already have all the info we need.
if(!ended) results.close();
}
}
};
Rewriter.prototype._debug = function(callback) {
debugMode && callback();
};
module.exports = Rewriter; |
var configuration = require('../../../config/configuration.json')
var utility = require('../../../public/method/utility')
module.exports = {
setCampaignSettingModel: function (redisClient, accountHashID, campaignHashID, payload, callback) {
var table
var score = utility.getUnixTimeStamp()
var multi = redisClient.multi()
var settingKeys = Object.keys(configuration.settingEnum)
var tableName = configuration.TableMACampaignModelSettingModel + campaignHashID
multi.hset(tableName, configuration.ConstantSMPriority, payload[configuration.ConstantSMPriority])
var finalCounter = 0
for (var i = 0; i < settingKeys.length; i++) {
if (settingKeys[i] === configuration.settingEnum.Priority)
continue
var key = settingKeys[i]
var scoreMemberArray = []
var keyValueArray = payload[key]
for (var j = 0; j < keyValueArray.length; j++) {
scoreMemberArray.push(score)
scoreMemberArray.push(keyValueArray[j])
}
table = configuration.TableModel.general.CampaignModel + accountHashID
table = utility.stringReplace(table, '@', key)
redisClient.zrange(table, '0', '-1', function (err, replies) {
if (err) {
callback(err, null)
return
}
for (var k = 0; k < replies.length; k++) {
table = configuration.TableModel.general.CampaignModel + accountHashID
table = utility.stringReplace(table, '@', replies[k])
multi.zrem(table, campaignHashID)
}
for (var j = 0; j < keyValueArray.length; j++) {
/* Add to Model List */
table = configuration.TableModel.general.CampaignModel + accountHashID
table = utility.stringReplace(table, '@', keyValueArray[j])
multi.zadd(table, score, campaignHashID)
/* Add to Model Set */
table = configuration.TableModel.general.CampaignModel
table = utility.stringReplace(table, '@', keyValueArray[j])
multi.zadd(table, score, campaignHashID)
}
/* Model Set */
table = configuration.TableModel.general.CampaignModel + campaignHashID
table = utility.stringReplace(table, '@', key)
/* Remove from Model Set */
multi.zremrangebyrank(table, '0', '-1')
/* Add to Model Set */
scoreMemberArray.unshift(table)
multi.zadd(scoreMemberArray)
finalCounter++
if (finalCounter == keyValueArray.length) {
multi.exec(function (err, replies) {
if (err) {
callback(err, null)
return
}
callback(null, configuration.message.setting.campaign.set.successful)
})
}
})
}
}
} |
/*
* code for Route was extracted from express.js. https://github.com/visionmedia/express
* express.js was published under MIT license at time of extraction.
* We will monitor express' evolution to see if the Routing code gets pulled into a stand-alone lib
*/
module.exports = Route;
/**
* Initialize `Route` with the given HTTP `method`, `path`,
* and an array of `callbacks` and `options`.
*
* Options:
*
* - `sensitive` enable case-sensitive routes
* - `strict` enable strict matching for trailing slashes
*
* @param {String} method
* @param {String} path
* @param {Function} assertion
* @param {Object} options.
* @api private
*/
function Route(method, path, assertion, options) {
options = options || {};
this.path = path;
this.method = method;
this.assertion = assertion;
this.regexp = pathRegexp(path
, this.keys = []
, options.sensitive
, options.strict);
}
/**
* Check if this route matches `path`, if so
* populate `.params`.
*
* @param {String} path
* @return {Boolean}
* @api private
*/
Route.prototype.match = function(path){
var keys = this.keys
, params = this.params = []
, m = this.regexp.exec(path);
if (!m) return false;
for (var i = 1, len = m.length; i < len; ++i) {
var key = keys[i - 1];
var val = 'string' == typeof m[i]
? decodeURIComponent(m[i])
: m[i];
if (key) {
params[key.name] = val;
} else {
params.push(val);
}
}
return true;
};
/**
* Normalize the given path string,
* returning a regular expression.
*
* An empty array should be passed,
* which will contain the placeholder
* key names. For example "/user/:id" will
* then contain ["id"].
*
* @param {String|RegExp|Array} path
* @param {Array} keys
* @param {Boolean} sensitive
* @param {Boolean} strict
* @return {RegExp}
* @api private
*/
function pathRegexp(path, keys, sensitive, strict) {
if (toString.call(path) == '[object RegExp]') return path;
if (Array.isArray(path)) path = '(' + path.join('|') + ')';
path = path
.concat(strict ? '' : '/?')
.replace(/\/\(/g, '(?:/')
.replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star){
keys.push({ name: key, optional: !! optional });
slash = slash || '';
return ''
+ (optional ? '' : slash)
+ '(?:'
+ (optional ? slash : '')
+ (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')'
+ (optional || '')
+ (star ? '(/*)?' : '');
})
.replace(/([\/.])/g, '\\$1')
.replace(/\*/g, '(.*)');
return new RegExp('^' + path + '$', sensitive ? '' : 'i');
}
|
/*eslint-env node, jasmine */
/*eslint no-unused-expressions: 0 */
'use strict'
var jspp = require('../lib/preproc'),
stream = require('stream'),
path = require('path'),
fs = require('fs'),
defaults = require('../lib/options').defaults
var fixtures = path.join(__dirname, 'fixtures'),
WANT_ERR = !0 // make visible
function cat(file) {
var f = path.join(__dirname, file)
return fs.readFileSync(f, {encoding: 'utf8'})
}
function fixPath(file) {
return path.join(fixtures, file)
}
function readExpect(file) {
return cat(path.join('expect', file))
}
//var errText = '--- DEBUG: a stream in error condition emitted an '
function testIt(any, opts, callback, wantErr) {
var text = [],
stpp = jspp(any, opts)
//console.log('--- TRACE: using stream ' + stpp._jspp_id + ' for the next spec')
stpp
.on('data', function (chunk) {
//if (opts.__hasError) console.error(errText + '`data` event')
text.push(chunk)
})
.on('end', function () {
//console.log('--- [' + stpp._jspp_id + '] is done!')
//if (opts.__hasError) console.error(errText + '`end` event')
callback(text = text.join(''))
})
.on('error', function (err) {
//console.error('--- [' + stpp._jspp_id + '] have an error: ' + err)
//opts.__hasError = true
/* istanbul ignore else: make no sense if spec fails */
if (wantErr)
callback(err)
else
fail(err)
})
//.on('close', function () {
// console.error('--- TRACE: closed stream ' + stpp._jspp_id)
//})
}
function testStr(str, opts, callback, wantErr) {
opts.buffer = str
testIt(null, opts, callback, wantErr)
}
function testFile(file, opts, callback, wantErr) {
testIt(fixPath(file), opts, callback, wantErr)
}
function testOther(any, opts, callback, wantErr) {
testIt(any, opts, callback, wantErr)
}
// set default headers and emptyLines to none, for easy test
var defaultHeaders = defaults.headers
defaults.headers = ''
var defaultEmptyLines = defaults.emptyLines
defaults.emptyLines = 0
/*
process.on('uncaughtException', function (err) {
console.error('Uncaught Exception.')
console.error(err.stack)
process.exit(1)
})
jasmine.getEnv().catchExceptions(false)
*/
// Comments Suite
// --------------
describe('Comments', function () {
it('with the defaults, only preserve comments with "@license"', function (done) {
testFile('comments', {}, function (result) {
var lic = /\/\/\s*@license:/
expect(result).toMatch(lic)
// expect(result.replace(lic, '')).not.toMatch(/\/[*\/]/)
done()
})
})
it('are completely removed with the `-C none` option', function (done) {
testFile('comments', {comments: 'none'}, function (result) {
expect(result).not.toMatch(/\/[*\/]/)
done()
})
})
it('are preserved with `-C all`', function (done) {
testFile('comments', {comments: 'all'}, function (result) {
expect(result).toBe(readExpect('comments_all.js'))
done()
})
})
it('are preserved for all filters with `-C filter -F all`', function (done) {
var opts = {comments: 'filter', filter: 'all'}
testFile('comments', opts, function (result) {
expect(result).toBe(readExpect('comments_linters.js'))
done()
})
})
it('can use custom filters, e.g. --custom-filter "\\\\\* @module"', function (done) {
var opts = {customFilter: '\\\\\* @module'}, // "\\* @module" from console
text = [
'/* @module foo */',
'exports = 0'
].join('\n')
testStr(text, opts, function (result) {
expect(result).toMatch(/\* @m/)
done()
})
})
it('the customFiler property can be an array of regexes', function (done) {
var opts = {customFilter: [/@m/, / #/]},
text = [
'/* @module foo */',
'// # bar'
].join('\n')
testStr(text, opts, function (result) {
expect(result).toMatch(/foo[*\/#\s]+bar/)
done()
})
})
})
// Lines Suite
// -----------
describe('Lines', function () {
var buff = [
'\n', '\r\n', '\n', '\r\n', // 4
'a',
'\r', '\r\n', '\r\n', '\r', // 4
'//x',
'\n', '\n', '\n', '\n', '\n', // 5
'/* \n\n */',
'\n', '\n', '\n', '\n', '\n', // 5
'\n' // 1
].join('')
it('default is one empty line and EOLs in Unix style (\\n).', function (done) {
testStr(buff, {emptyLines: defaultEmptyLines}, function (result) {
expect(result).toHasLinesLike('\na\n\n')
done()
})
})
it('EOLs can be converted to Windows style (\\r\\n)', function (done) {
testStr(buff, {eolType: 'win', emptyLines: 1}, function (result) {
expect(result).toHasLinesLike('\r\na\r\n\r\n')
done()
})
})
it('or converted to Mac style (\\r)', function (done) {
testStr(buff, {eolType: 'mac', emptyLines: 1}, function (result) {
expect(result).toHasLinesLike('\ra\r\r')
done()
})
})
it('`--empty-lines -1` disables remotion of empty lines', function (done) {
testStr(buff, {emptyLines: -1}, function (result) {
var test = buff
.replace(/\r\n?|\n/g, '\n')
.replace(/\/\*[\s\S]*\*\//g, '')
.replace(/\/\/[^\n]*/g, '')
.replace(/[ \t]+$/, '')
expect(result).toHasLinesLike(test)
done()
})
})
it('`--empty-lines 0` removes all the empty lines', function (done) {
testStr(buff, {emptyLines: 0}, function (result) {
expect(result).toHasLinesLike('a\n')
done()
})
})
it('`--empty-lines` must obey its limit', function (done) {
var s = '\n\n\n\n1\n\n2\n\n\n\n3\n\n\n\n'
testStr(s, {emptyLines: 2}, function (result) {
expect(result).toHasLinesLike('\n\n1\n\n2\n\n\n3\n\n\n')
done()
})
})
it('force eol after any file, even with emptyLines 0', function (done) {
var text = [
'//#include ' + fixPath('noeol.txt'),
'//#include ' + fixPath('noeol.txt'),
'ok'
].join('\n')
testStr(text, {emptyLines: 0}, function (result) {
expect(result).toHasLinesLike('noEol\nnoEol\nok')
done()
})
})
it('limit empty lines when joining files', function (done) {
var text = '//#include ' + fixPath('manyeols.txt')
text = '\n\n\n\n' + text + '\n' + text + '\n\n\n\n'
testStr(text, {emptyLines: 2}, function (result) {
expect(result).toHasLinesLike('\n\neol\n\n\neol\n\n\n')
done()
})
})
it('don\'t add unnecessary EOLs after insert a file', function (done) {
var text = '//#include ' + fixPath('noeol.txt')
testStr(text, {}, function (result) {
expect(result).toBe('noEol')
done()
})
})
})
// #set Suite
// -------------
describe('#set / #define', function () {
it('once emitted, has global scope to the *top* file', function (done) {
var text = [
'//#define FOO',
'//#ifdef FOO',
'1',
'//#endif'
].join('\n')
testStr(text, {}, function (result) { // text is the top file
var foo = '$_FOO'
expect(result).toBe('1\n')
testStr(foo, {}, function (result2) { // foo is other top file
expect(result2).toBe(foo) // $_FOO is not defined
done()
})
})
})
it('names starting with `$_` can be used anywhere in the file', function (done) {
var text = [
'//#set BAR = "bar"',
'//#set $_FOO "foo" + BAR',
'log($_FOO)'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toBe('log("foobar")')
done()
})
})
it('can include other defined symbols', function (done) {
var text = [
'//#set $_A = "A"',
'//#set $_B = $_A + "." + $_A',
'//#set $_C = $_A + "." + $_B',
'$_C'
].join('\n')
testStr(text, {emptyLines: -1}, function (result) {
//var test = 'A.A.A'
//result = result.replace(/['"]/g, '')
expect(result).toBe('"A.A.A"')
done()
})
})
it('don\'t replace symbols in quotes or regexes', function (done) {
var text = [
'//#set AA = "A"',
'//#set $_A = AA + "AA"',
'//#set $_R = /^AA/',
'$_R.test($_A)'
].join('\n')
testStr(text, {emptyLines: -1}, function (result) {
//var test = 'A.A.A'
//result = result.replace(/['"]/g, '')
expect(result).toBe('/^AA/.test("AAA")')
done()
})
})
it('evaluates the expression immediately', function (done) {
var text = [
'//#set N_1 = 1',
'//#set $_R = N_1 + 2',
'$_R'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toBe('3')
done()
})
})
it('evaluation performs mathematical operations', function (done) {
var text = [
'//#set FOO = 1 + 2',
'//#set BAR = 3',
'//#if FOO+BAR === 6',
'ok',
'//#endif'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toBe('ok\n')
done()
})
})
it('evaluation concatenate strings', function (done) {
var text = [
'//#set FOO = "fo" + "o"',
'//#set BAR = \'bar\'',
'//#if FOO+BAR === "foobar"',
'ok',
'//#endif'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toBe('ok\n')
done()
})
})
it('recognizes and preserves regexes', function (done) {
var text = [
'//#set RE = /^f/',
'//#set $_R = /\\n+/',
'//#set $_V = RE.test("foo")',
'($_V, $_R)'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toBe('(true, /\\n+/)')
done()
})
})
it('recognizes and preserves Date objects', function (done) {
var text = [
'//#set $_D = new Date(2015,9,10)',
'//#set $_E = +$_D',
'//#if ($_D instanceof Date) && (typeof $_E === "number")',
'date',
'//#endif',
'//#set $_E = $_D.getFullYear()',
'//#set $_D = +(new Date("x"))',
'$_E~$_D'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toMatch(/date\D+2015~NaN/)
done()
})
})
it('null, undefined and NaN values are preserved too', function (done) {
var text = [
'//#set $_X = null',
'//#set $_U = undefined',
'//#set $_N = parseInt("x", 10)',
'($_X,$_U,$_N)'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toBe('(null,undefined,NaN)')
done()
})
})
it('Infinity (e.g. division by 0) is converted to zero', function (done) {
var text = [
'//#set $_FOO = Infinity',
'//#set $_BAR = 5/0',
'$_FOO-$_BAR'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toBe('0-0')
done()
})
})
it('in expressions, undefined variables are converted to zero', function (done) {
var text = [
'//#if $_FOO === 0', // no error is emitted
'ok',
'//#endif',
'//#if !defined($_FOO)', // retest
'ok',
'//#endif'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toMatch(/ok\nok/)
done()
})
})
it('#unset or #undef removes the variable completely', function (done) {
var text = [
'//#set $_FOO = 1',
'//#unset $_FOO', // check unset is deleting the var
'//#if $_FOO === 0',
'ok',
'//#endif',
'//#define $_FOO 1',
'//#undef $_FOO',
'//#if $_FOO === 0',
'ok',
'//#endif'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toMatch(/ok\nok/)
done()
})
})
it('emit error event setting invalid symbol names', function (done) {
testStr('//#set $_Foo', {}, function (result) {
expect(result).toErrorContain('symbol name')
testStr('//#set =1', {}, function (result2) {
expect(result2).toErrorContain('symbol name')
done()
}, WANT_ERR)
}, WANT_ERR)
})
it('emit error event on evaluation errors', function (done) {
var text = [
'//#set $_FOO = 5*10)',
'$_FOO'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toErrorContain('Can\'t evaluate')
done()
}, WANT_ERR)
})
it('object varset in options has name-value pairs', function (done) {
var opts = {
varset: {_FOO: 1, _BAR: '2'}
},
text = [
'//#if _FOO + _BAR === "12"',
'ok',
'//#endif'
].join('\n')
testStr(text, opts, function (result) {
expect(result).toBe('ok\n')
done()
})
})
it('be careful with backslashes in macro-substitution!', function (done) {
var text = [
'//#set $_FOO = "a\b"',
'//#set $_BAR = "c\t"',
'//#set $_BAZ = "e\\\\f"',
'$_FOO~$_BAR~$_BAZ',
'//#if ~$_FOO.indexOf("\b")',
'ok',
'//#endif'
].join('\n')
testStr(text, {}, function (result) {
// console.log('--- Result: `' + result + '`')
result = result.replace(/['"]/g, '')
expect(result).toMatch(/a\\b~c\\t~e\\\\f/)
expect(result).toMatch(/ok/)
done()
})
})
it('be careful with backslashes in macro-substitution! (file)', function (done) {
testFile('macrosubs.txt', {}, function (result) {
// console.log('--- Result: `' + result + '`')
result = result.replace(/['"]/g, '')
expect(result).toMatch(/a\\b~c\\t~e\\\\f/)
expect(result).toMatch(/ok/)
done()
})
})
})
// Conditional Blocks
// ------------------
describe('Conditionals Blocks', function () {
var UNCLOSED_BLOCK = 'Unclosed conditional block'
it('can be indented', function (done) {
var text = [
'//#define _A',
'//#if 1',
' //#if _A',
' a',
' //#endif',
'//#endif'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toBe(' a\n')
done()
})
})
it('can include spaces between `//#` and the keyword', function (done) {
var text = [
'//# define _A',
'//# if 1',
'//# if _A',
' a',
' //# endif',
'//# endif'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toBe(' a\n')
done()
})
})
it('can NOT include spaces between `//` and the `#`', function (done) {
var text = [
'// #if 0',
' a',
'// #endif'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toBe(' a\n')
done()
})
})
it('ignore comments in falsy blocks', function (done) {
var text = [
'//#if 0',
'/* @license MIT */',
'//#endif'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toMatch(/^\s*$/)
done()
})
})
it('#if blocks can be nested', function (done) {
var text = [
'//#define _A ',
'//#if 1 ',
'//# if 1 ',
'//# if _A ',
' ok ',
'//# elif 1 ', // test elif after trueish block
' no ',
'//# if 1 ', // test if ignored this
' no ',
'//# endif ',
'//# endif ',
'//# if !0 ',
' yes ',
'//# endif ',
'//# endif ',
'//#endif '
].join('\n')
testStr(text, {}, function (result) {
expect(result).toMatch(/ ok\s*yes\s*$/)
done()
})
})
it('incorrect sequence raises an error event', function (done) {
testStr('//#elif 0', {}, function (result) {
expect(result).toErrorContain('Unexpected #elif')
testStr('//#else', {}, function (result2) {
expect(result2).toErrorContain('Unexpected #else')
testStr('//#endif', {}, function (result3) { // eslint-disable-line max-nested-callbacks
expect(result3).toErrorContain('Unexpected #endif')
done()
}, WANT_ERR)
}, WANT_ERR)
}, WANT_ERR)
})
it('unclosed conditional block emits error event', function (done) {
var text = [
'//#if _A',
'//#else',
'#endif'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toErrorContain(UNCLOSED_BLOCK)
testStr('//#ifndef X\n//#enif', {}, function (result2) {
expect(result2).toErrorContain(UNCLOSED_BLOCK)
done()
}, WANT_ERR)
}, WANT_ERR)
})
it('unclosed block throws even in included files', function (done) {
var text = [
'//#include ' + fixPath('unclosed'),
'//#endif'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toErrorContain(UNCLOSED_BLOCK)
done()
}, WANT_ERR)
})
it('each file have to close theirs blocks', function (done) {
testFile('unclosed', {}, function (result) {
expect(result).toErrorContain(UNCLOSED_BLOCK)
done()
}, WANT_ERR)
})
it('all keywords, except #else/#endif, must have an expression', function (done) {
testStr('//#if\n//#endif', {}, function (result) {
expect(result).toErrorContain('Expected expression for #')
done()
}, WANT_ERR)
})
// can
it('#elif expression can be included after #ifdef/#ifndef', function (done) {
var text = [
'//#ifdef _UNDEF_VAL_',
'no',
'//#elif 0',
'no',
'//#elif 1',
'ok',
'//#else',
'no',
'//#endif'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toMatch(/ok/)
expect(result).not.toMatch(/no/)
done()
})
})
it('expressions are simply JavaScript (buffer)', function (done) {
var text = [
'//#if !""',
'empty',
'//#endif',
'//#if "0" | 1',
'one',
'//#endif',
'//#if typeof {} === "object"',
'object',
'//#endif',
'//#if NaN !== NaN',
'NaN',
'//#endif',
'//#set $_S = "\\ntr\\\\nim\\t ".trim()',
'$_S~'
].join('\n')
testStr(text, {}, function (result) {
var i, test = ['empty', 'one', 'object', 'NaN', (/['"]tr\\\\nim['"]/)] // eslint-disable-line no-extra-parens
for (i = 0; i < test.length; i++) {
expect(result).toMatch(test[i])
}
done()
})
})
it('expressions are simply JavaScript (file)', function (done) {
testFile('simplyjs.txt', {}, function (result) {
var i, test = ['empty', 'one', 'object', 'NaN', (/['"]tr\\\\nim['"]/)] // eslint-disable-line no-extra-parens
for (i = 0; i < test.length; i++)
expect(result).toMatch(test[i])
done()
})
})
it('#if/#elif supports the `defined()` function', function (done) {
var text = [
'//#define _A',
'//#if defined(_B) || defined(_A)',
'ok1',
'//#endif',
'//#if !defined(_Z)',
'ok2',
'//#endif'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toMatch(/ok1[^o]*ok2/)
done()
})
})
it('#ifdef/#ifndef are shorthands to `defined`', function (done) {
var text = [
'//#define _A',
'//#ifdef _A',
'ok1',
'//#endif',
'//#ifndef _Z',
'ok2',
'//#endif'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toMatch(/ok1[^o]*ok2/)
done()
})
})
it('if/ifdef/ifndef/elif/else can start with `/*#` (v0.2.7)', function (done) {
var text = [
'/*#if 1',
'var x = 1',
'//#else*/',
'var x = 2',
'//#endif'
].join('\n')
testStr(text, {comments: 'none'}, function (result) {
expect(result.trim()).toBe('var x = 1')
done()
})
})
it('starting with `/*#` can include another conditionals', function (done) {
var text = [
'//#set FOO=2',
'/*#if FOO==1',
'var x = 1',
'//#elif FOO==2',
'var x = 2',
'//#else*/',
'var x = 3',
'//#endif'
].join('\n')
testStr(text, {comments: 'none'}, function (result) {
expect(result.trim()).toBe('var x = 2')
done()
})
})
it('not recognized keywords following `/*#` are comments', function (done) {
var text = [
'/*#if- 0',
'var x = 1',
'//#else',
'var x = 2',
'//#endif */',
'/*#set $_FOO = 1',
'var x = $_FOO',
'//#unset $_FOO*/'
].join('\n')
testStr(text, {comments: 'none'}, function (result) {
expect(result.trim()).toBe('')
done()
})
})
})
// `#include` Suite
// ----------------
describe('#include', function () {
it('default extension is js, single or double quoted filenames ok', function (done) {
var text = [
'//#include "' + fixPath('dummy') + '"',
"//#include '" + fixPath('dummy') + "'"
].join('\n')
testStr(text, {}, function (result) {
expect(result).toMatch(/Dummy[\S\s]*?Dummy/)
done()
})
})
it('files included in removed blocks are skipped (seems obvious?)', function (done) {
testFile('include1.txt', {}, function (result) {
// ONCE not defined, 3 dummy.js 'cause include_once is skipped
expect(result).toMatch(/Dummy/)
expect(result.match(/Dummy/g).length).toBe(3)
done()
})
})
it('only one copy included from #include_once is seen', function (done) {
testFile('include1.txt', {define: 'ONCE'}, function (result) {
// ONCE defined, found include_once, only 1 dummy.js
expect(result).toMatch(/Dummy/)
expect(result.match(/Dummy/g).length).toBe(1)
done()
})
})
it('only one copy included with #include_once even in nested files', function (done) {
var text = [
'//#include_once ' + fixPath('dummy'),
'//#include ' + fixPath('include2.txt') // has two #include dummy
].join('\n')
testStr(text, {}, function (result) {
expect(result).toMatch(/Dummy/)
expect(result.match(/Dummy/g).length).toBe(1)
done()
})
})
it('defines are available after the included file ends', function (done) {
var text = [
'//#include ' + fixPath('include3.txt'),
'//#if INCLUDED3', // defined in include3.txt
'ok1',
'//#endif',
'//#include ' + fixPath('incundef3.txt'),
'//#if !INCLUDE3',
'ok2',
'//#endif'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toMatch('ok1')
expect(result).toMatch('ok2')
done()
})
})
it('emit error if filename for inclussion is invalid', function (done) {
testStr('//#include " "', {}, function (result) {
expect(result).toErrorContain('Expected filename')
done()
}, WANT_ERR)
})
it('emit error if filename for inclussion is missing', function (done) {
testStr('//#include ', {}, function (result) {
expect(result).toErrorContain('Expected filename')
done()
}, WANT_ERR)
})
describe('Indentation', function () {
it('default of includes is nothing', function (done) {
var text = '//#include ' + fixPath('dummy')
testStr(text, {}, function (result) {
expect(result).toMatch(/^Dummy/)
done()
})
})
it('can set to tab or spaces (e.g. `--indent 1t`)', function (done) {
var text = '//#include ' + fixPath('dummy')
testStr(text, { indent: '1t' }, function (result) {
expect(result).toMatch(/^\tDummy/m)
done()
})
})
it('each level adds one indentation more', function (done) {
// include1 includes dummy.js and include2.txt
// include2 includes dummy.js twice
testFile('include1.txt', { indent: '2s' }, function (result) {
expect(result).toMatch(/^ {2}Dummy/m)
expect(result).toMatch(/^ {4}Dummy/m)
done()
})
})
it('#indent adjust indentation (experimental)', function (done) {
testFile('reindent.js', {}, function (result) {
expect(result).toBe(readExpect('reindent.out'))
done()
})
})
})
})
// Headers suite
// -------------
describe('Headers', function () {
it('for the top file or mainstream default is none', function (done) {
testFile('include3.txt', {}, function (result) {
expect(result).not.toMatch('include3')
done()
})
})
it('for included files is the relative filename', function (done) {
var file = fixPath('sub/child.txt'),
text = '//#include ' + file
testStr(text, {headers: defaultHeaders}, function (result) {
result = result.replace(/\\/g, '/')
expect(result).toMatch(' ' + path.relative('.', file).replace(/\\/g, '/'))
done()
})
})
it('for top and included files can be customized', function (done) {
var opts = {
header1: 'hi top\n',
headers: 'bye\n',
emptyLines: 0
},
text = '//#include ' + fixPath('include3.txt')
testStr(text, opts, function (result) {
expect(result).toMatch('hi top\nbye')
done()
})
})
it('can be removed with the empty string: --headers ""', function (done) {
var opts = {
headers: '',
emptyLines: 0
},
text = '//#include ' + fixPath('noeol.txt')
testStr(text, opts, function (result) {
expect(result).toMatch(/^noEol/)
done()
})
})
it('^ is replaced with eol, and ^^ with the ^ char', function (done) {
var opts = {
header1: '^hi^ ^^top^',
headers: 'bye^^^__FILE^',
emptyLines: 1
},
text = '//#include ' + fixPath('noeol.txt')
testStr(text, opts, function (result) {
expect(result).toMatch(/^\nhi\n \^top\n/)
expect(result).toMatch(/bye\^\n(?!\n)/)
done()
})
})
it('ensure is ending with eol, even with `emptyLines` 0', function (done) {
var opts = {
header1: 'hi', // no EOL in headers
headers: 'bye',
emptyLines: 1
},
text = 'A\n//#include ' + fixPath('noeol.txt')
testStr(text, opts, function (result) {
expect(result).toMatch(/^hi\nA\nbye\nnoEol$/)
done()
})
})
})
describe('Parameters', function () {
it('wrong options throws exceptions', function () {
var jopt = new (require('../lib/options'))(),
opts = {},
vals = ['comments', 'eolType', 'filter', 'define', 'undef', 'indent'],
test = function () { jopt.merge(opts) }
for (var i = 0; i < vals.length; ++i) {
opts = {}
opts[vals[i]] = 'foo'
expect(test).toThrow()
}
opts = {varset: {Foo: 1}}
expect(test).toThrow()
opts = {customFilter: '['}
expect(test).toThrow()
opts = {eolType: null}
expect(test).toThrow()
})
it('can accept different types and formats', function () {
var jopt = new (require('../lib/options'))(),
opts = {},
test = function () { opts = jopt.merge(opts) }
opts = {indent: ''}
expect(test).not.toThrow()
opts = {filter: 'jsdoc, eslint'}
expect(test).not.toThrow()
opts = {filter: ['jsdoc', 'eslint']}
expect(test).not.toThrow()
opts = {customFilter: '@'}
expect(test).not.toThrow()
opts = {customFilter: /@/}
expect(test).not.toThrow()
opts = {emptyLines: 'z'}
expect(test).not.toThrow()
opts = {define: 'FOO,BAR=2,BAZ=""'}
expect(test).not.toThrow()
opts = jopt.getVars()
expect(opts.FOO).toEqual(1)
expect(opts.BAR).toEqual(2)
expect(opts.BAZ).toBe('""')
})
it('undef can be an array or a string delimited with commas', function (done) {
var text = [
'//#if !AA',
'aa',
'//#endif',
'$_BB~$_CC'
].join('\n')
testStr(text, {define: ['AA', '$_BB', '$_CC'], undef: 'AA, $_BB'}, function (result) {
expect(result).toMatch(/aa/)
expect(result).toMatch(/\$_BB~1/)
done()
})
})
it('1st parameter of jspp can be an array of filenames', function (done) {
var files = [fixPath('dummy'), fixPath('noeol.txt')]
testOther(files, {}, function (result) {
expect(result).toMatch(/^Dummy\s+noEol/)
files.splice(1)
testOther(files, {}, function (result2) {
expect(result2).toMatch(/^Dummy\s*$/)
done()
})
})
})
it('jspp input file can be any readable stream', function (done) {
var stin = new stream.Readable()
stin.pause()
stin.push('foo') // queue the data to output through stdin
stin.push(null) // queue the EOF signal
testOther(stin, {}, function (result) {
expect(result).toBe('foo')
done()
})
})
it('if the file parameter is null, jspp uses stdin', function (done) {
process.stdin.pause()
process.stdin.push('foo') // queue the data to output through stdin
process.stdin.push(null) // queue the EOF signal
testOther(null, {}, function (result) {
expect(result).toBe('foo')
done()
})
})
it('you can pipe jspp with the input stream', function (done) {
var buff = '',
stin = fs.createReadStream(fixPath('dummy.js')),
stpp = jspp(null, {})
stin.pipe(stpp)
.on('data', function (chunk) {
buff += chunk
})
.once('end', function () {
expect(buff).toBe('Dummy\n')
done()
})
})
it('if the stream is not readable, jspp throws before start', function () {
var Writable = stream.Writable
expect(function () {
testOther(new Writable(), {})
}).toThrow()
})
/*
it('without an on("error") handler, jspp throws an exception', function (done) {
var stpp = jspp(null, {buffer: '#if'})
})
*/
})
// TODO: test with streams, e.g. pipe a file to stdin
describe('fixes', function () {
it('a regex after a `return` is mistaken for a divisor operator', function (done) {
var text = [
'function foo(s) {',
' return /^[\'"]/.test(s) //\'',
'}'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toBe('function foo(s) {\n return /^[\'"]/.test(s)\n}')
done()
})
})
it('Unicode line and paragraph characters doesn\'t break strings', function (done) {
var text = [
'//#set $_STR = "\\u2028\\u2029"',
'//#set $_STR = $_STR[0]',
'var s = $_STR'
].join('\n')
testStr(text, {}, function (result) {
expect(result).toBe('var s = "\\u2028"')
done()
})
})
})
|
(function() {
'use strict';
angular
.module('noodleApp')
.controller('SearchFilterViewController', SearchFilterViewController);
SearchFilterViewController.$inject = ['$rootScope', '$scope', 'Filters', 'ActiveFilter'];
function SearchFilterViewController($rootScope, $scope, Filters, ActiveFilter) {
// ==================================================
var vm = this;
vm.display = false;
vm.toggle = function(){ vm.display = !vm.display; }
$rootScope.$on('TOGGLE-FILTER', function(brodcast, value) { vm.display = value; });
// ==================================================
vm.toggleActiveFilter = function(filter){
filter.state = !filter.state;
vm.filters.change();
console.log('filter select');
}
vm.updateActiveFilterService = function(){
var activeFilters = [];
vm.filters.collection.forEach(function(filter, index){
activeFilters.push(filter);
});
ActiveFilter.setFilter(activeFilters);
}
// ==================================================
vm.filters = {
collection: [],
//
byCategory: function(category){
var result = [];
vm.filters.collection.forEach(function(element, index){
var filter_category = vm.category.stringify(element.category);
if (filter_category == category){
result.push(element)
}
});
return result;
},
change: function(){
var categories = vm.category.list();
categories.forEach(function(category, index){
var selected = false;
var filters = vm.filters.byCategory(category);
filters.forEach(function(filter, index){
if (filter.state) selected = true;
});
vm.category.selected[category] = selected;
});
vm.updateActiveFilterService();
$rootScope.$broadcast('FILTER-CHANGE', true);
}
}
//
vm.category = {
//
stringify : function(category){
category = category.replace('_', ' ')
category = category.charAt(0).toUpperCase() + category.slice(1).toLowerCase();
return category;
},
//
list: function(){
var categories = [];
//
vm.filters.collection.forEach(function(element, index){
var category = element.category;
category = vm.category.stringify(category)
if (categories.indexOf(category) == -1){
categories.push(category)
}
});
//
return categories;
},
//
selected: {},
//
select : function(category){
var selected = vm.category.selected[category]
var filters = vm.filters.byCategory(category);
filters.forEach(function(filter, index){
filter.state = selected;
});
console.log('category select');
vm.filters.change();
},
//
states : {},
//
toggle : function(category){
//
var state = !vm.category.states[category];
vm.category.states[category] = state;
//
// var filters = vm.filters.byCategory(category);
// filters.forEach(function(filter, index){
// filter.state = state;
// });
// //
// console.log('category toggle');
// vm.filters.change();
},
//
};
//
Filters.get(function(filters){
vm.filters.collection = filters;
vm.filters.change();
});
}
})(); |
// Polarbot
// database.js
// handles database connection and queries
var mysql = require('mysql');
var config = require('./config/config.js');
var logger = require('./logger.js');
// Init MySql-connection
var pool = mysql.createPool({
host : config.dbHost,
port : config.dbPort,
user : config.dbUser,
password : config.dbPassword,
database : config.dbDatabase
});
exports.query = function(qry, callback, esc) {
// get new connection from pool
connect(function(err, connection) {
// execute query
connection.query(qry, esc, function(err, rows) {
connection.release();
if (err) {
logger.log('MYSQL ERROR: ' + err);
}
callback(err, rows);
});
});
}
function connect(callback) {
pool.getConnection(function(err, connection) {
if (err) {
logger.log('MYSQL Error getting connection from pool: ' + err);
}
else return callback(err, connection);
});
} |
/*
Copyright 2014, KISSY v1.49
MIT Licensed
build time: May 22 12:15
*/
/*
Combined processedModules by KISSY Module Compiler:
base
*/
KISSY.add("base", ["attribute"], function(S, require) {
var Attribute = require("attribute");
var ucfirst = S.ucfirst, ON_SET = "_onSet", noop = S.noop;
function __getHook(method, reverse) {
return function(origFn) {
return function wrap() {
var self = this;
if(reverse) {
origFn.apply(self, arguments)
}else {
self.callSuper.apply(self, arguments)
}
var extensions = arguments.callee.__owner__.__extensions__ || [];
if(reverse) {
extensions.reverse()
}
callExtensionsMethod(self, extensions, method, arguments);
if(reverse) {
self.callSuper.apply(self, arguments)
}else {
origFn.apply(self, arguments)
}
}
}
}
var Base = Attribute.extend({constructor:function() {
var self = this;
self.callSuper.apply(self, arguments);
var listeners = self.get("listeners");
for(var n in listeners) {
self.on(n, listeners[n])
}
self.initializer();
constructPlugins(self);
callPluginsMethod.call(self, "pluginInitializer");
self.bindInternal();
self.syncInternal()
}, initializer:noop, __getHook:__getHook, __callPluginsMethod:callPluginsMethod, bindInternal:function() {
var self = this, attrs = self.getAttrs(), attr, m;
for(attr in attrs) {
m = ON_SET + ucfirst(attr);
if(self[m]) {
self.on("after" + ucfirst(attr) + "Change", onSetAttrChange)
}
}
}, syncInternal:function() {
var self = this, cs = [], i, c = self.constructor, attrs = self.getAttrs();
while(c) {
cs.push(c);
c = c.superclass && c.superclass.constructor
}
cs.reverse();
for(i = 0;i < cs.length;i++) {
var ATTRS = cs[i].ATTRS || {};
for(var attributeName in ATTRS) {
if(attributeName in attrs) {
var attributeValue, onSetMethod;
var onSetMethodName = ON_SET + ucfirst(attributeName);
if((onSetMethod = self[onSetMethodName]) && attrs[attributeName].sync !== 0 && (attributeValue = self.get(attributeName)) !== undefined) {
onSetMethod.call(self, attributeValue)
}
}
}
}
}, plug:function(plugin) {
var self = this;
if(typeof plugin === "function") {
var Plugin = plugin;
plugin = new Plugin
}
if(plugin.pluginInitializer) {
plugin.pluginInitializer(self)
}
self.get("plugins").push(plugin);
return self
}, unplug:function(plugin) {
var plugins = [], self = this, isString = typeof plugin === "string";
S.each(self.get("plugins"), function(p) {
var keep = 0, pluginId;
if(plugin) {
if(isString) {
pluginId = p.get && p.get("pluginId") || p.pluginId;
if(pluginId !== plugin) {
plugins.push(p);
keep = 1
}
}else {
if(p !== plugin) {
plugins.push(p);
keep = 1
}
}
}
if(!keep) {
p.pluginDestructor(self)
}
});
self.setInternal("plugins", plugins);
return self
}, getPlugin:function(id) {
var plugin = null;
S.each(this.get("plugins"), function(p) {
var pluginId = p.get && p.get("pluginId") || p.pluginId;
if(pluginId === id) {
plugin = p;
return false
}
return undefined
});
return plugin
}, destructor:S.noop, destroy:function() {
var self = this;
if(!self.get("destroyed")) {
callPluginsMethod.call(self, "pluginDestructor");
self.destructor();
self.set("destroyed", true);
self.fire("destroy");
self.detach()
}
}});
S.mix(Base, {__hooks__:{initializer:__getHook(), destructor:__getHook("__destructor", true)}, ATTRS:{plugins:{value:[]}, destroyed:{value:false}, listeners:{value:[]}}, extend:function extend(extensions, px, sx) {
if(!S.isArray(extensions)) {
sx = px;
px = extensions;
extensions = []
}
sx = sx || {};
px = px || {};
var SubClass = Attribute.extend.call(this, px, sx);
SubClass.__extensions__ = extensions;
baseAddMembers.call(SubClass, {});
if(extensions.length) {
var attrs = {}, prototype = {};
S.each(extensions.concat(SubClass), function(ext) {
if(ext) {
S.each(ext.ATTRS, function(v, name) {
var av = attrs[name] = attrs[name] || {};
S.mix(av, v)
});
var exp = ext.prototype, p;
for(p in exp) {
if(exp.hasOwnProperty(p)) {
prototype[p] = exp[p]
}
}
}
});
SubClass.ATTRS = attrs;
prototype.constructor = SubClass;
S.augment(SubClass, prototype)
}
SubClass.extend = sx.extend || extend;
SubClass.addMembers = baseAddMembers;
return SubClass
}});
var addMembers = Base.addMembers;
function baseAddMembers(px) {
var SubClass = this;
var extensions = SubClass.__extensions__, hooks = SubClass.__hooks__, proto = SubClass.prototype;
if(extensions.length && hooks) {
for(var h in hooks) {
if(proto.hasOwnProperty(h) && !px.hasOwnProperty(h)) {
continue
}
px[h] = px[h] || noop
}
}
return addMembers.call(SubClass, px)
}
function onSetAttrChange(e) {
var self = this, method;
if(e.target === self) {
method = self[ON_SET + e.type.slice(5).slice(0, -6)];
method.call(self, e.newVal, e)
}
}
function constructPlugins(self) {
var plugins = self.get("plugins"), Plugin;
S.each(plugins, function(plugin, i) {
if(typeof plugin === "function") {
Plugin = plugin;
plugins[i] = new Plugin
}
})
}
function callPluginsMethod(method) {
var len, self = this, plugins = self.get("plugins");
if(len = plugins.length) {
for(var i = 0;i < len;i++) {
if(plugins[i][method]) {
plugins[i][method](self)
}
}
}
}
function callExtensionsMethod(self, extensions, method, args) {
var len;
if(len = extensions && extensions.length) {
for(var i = 0;i < len;i++) {
var fn = extensions[i] && (!method ? extensions[i] : extensions[i].prototype[method]);
if(fn) {
fn.apply(self, args || [])
}
}
}
}
S.Base = Base;
return Base
});
|
var GameOpts = require('./game_opts');
//Constructor
var Bullet = function(x,y,color){
var GameOpts = {
screenW : 800,
screenH : 600
};
//this.canvas = document.getElementById("canvas");
//this.ctx = canvas.getContext("2d");
this.rectangle = {x:x,y:y,w:10,h:25};
this.speed = 25;
this.color = color;
this.state = 0;
};
Bullet.prototype.moveX = function(x){
this.rectangle.x += x;
};
Bullet.prototype.moveY = function(y){
if (this.orientation == 1) {
this.rectangle.y -= y;
} else {
this.rectangle.y += y;
}
};
Bullet.prototype.getX = function(){
return this.rectangle.x;
};
Bullet.prototype.getY = function(){
return this.rectangle.y;
};
Bullet.prototype.getW = function(){
return this.rectangle.w;
};
Bullet.prototype.getH = function(){
return this.rectangle.h;
};
Bullet.prototype.fire = function(x,y){
if(this.state == 0) {
this.position(x,y);
this.state = 1;
}
};
Bullet.prototype.position = function(x,y){
this.rectangle.x = x;
this.rectangle.y = y;
};
Bullet.prototype.reset = function(){
this.state = 0;
this.rectangle.x = -50;
this.rectangle.y = -50;
};
Bullet.prototype.draw = function(ctx){
if (this.state == 1) {
//if (this.getY() < GameOpts.screenH && this.getY() > 0) {
//this.moveY(this.speed);
ctx.fillStyle = this.color;
ctx.fillRect(this.getX(),this.getY(),this.getW(),this.getH());
//} else {
// this.reset();
//}
}
};
Bullet.prototype.getState = function(){
if (this.state == 1) {
if (this.getY() < GameOpts.screenH && this.getY() > 0) {
this.moveY(this.speed);
//ctx.fillStyle = this.color;
//ctx.fillRect(this.getX(),this.getY(),this.getW(),this.getH());
} else {
this.reset();
}
} else{
//return;
}
return {s: this.state, x: this.rectangle.x, y: this.rectangle.y};
}
Bullet.prototype.setState = function(data){
this.state = data.s;
this.rectangle.x = data.x;
this.rectangle.y = data.y;
}
module.exports = Bullet;
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var multer = require('multer')
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(logger('dev'));
//app.use(multer({dest:'../public/uploads/'}).array('file'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res, next) {
console.log(req.headers.origin)
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');//注意这里不能使用 *
res.setHeader('Access-Control-Allow-Credentials', true);//告诉客户端可以在HTTP请求中带上Cookie
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With');
next();
});
var routes = require('./routes/index');
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
|
define([ 'backbone', 'metro', 'highcharts' ], function(Backbone, Metro, Highcharts) {
var ChartBtnView = Backbone.View.extend({
className: 'chart-btn-view menu-btn',
events: {
'click': 'toggle',
'mouseover': 'over',
'mouseout': 'out',
},
initialize: function(){
//ensure correct scope
_.bindAll(this, 'render', 'unrender', 'toggle', 'over', 'out', 'setInfo');
//info dialog
this.dialog = $('<div data-role="dialog" id="chart_dialog">');
this.dialog.addClass('padding20');
this.dialog.attr('data-close-button', 'true');
this.dialog.append('<div id="chart" style="min-width: 1200px; height: 500px; margin: 0 auto">');
//add to page
this.render();
},
render: function() {
var $button = $('<span class="mif-chart-dots">');
$(this.el).html($button);
$(this.el).attr('title', 'chart plot...');
$('body > .container').append($(this.el));
$('body > .container').append(this.dialog);
return this;
},
unrender: function() {
$(this.el).remove();
this.dialog.remove();
},
toggle: function() {
toggleMetroDialog('#chart_dialog');
},
over: function() {
$(this.el).addClass('expand');
},
out: function() {
$(this.el).removeClass('expand');
},
setInfo: function(content) {
this.dialog.append(content);
}
});
return ChartBtnView;
}); |
/**
* Express routes
*/
var errorHelper = require('../helpers/errorHelper');
var logger = require('../helpers/logger');
var routes = require('include-all')({
dirname: __dirname + '/../api/routes',
filter: /(.+)\.js$/,
excludeDirs: /^\.(git|svn)$/
});
logger.trace(Object.keys(routes));
/**
* Defines data track routes
* These routes collect data from the js snippet on users' browsers
* @param {Object} app
*/
module.exports.track = function loadTrackRoutes(app) {
////////////////////////////////////////////////////////
// Define data track routes below
// app.use('/company', routes.TrackController);
// app.use('/identify', routes.TrackController);
////////////////////////////////////////////////////////
app.use('/track', routes.TrackController);
};
/**
* Defines dashboard routes
* These routes work on the DoDataDo dashboard
* @param {Object} app
*/
module.exports.dashboard = function loadDashboardRoutes(app) {
////////////////////////////////////////////////////////
// Define dashboard api routes below
// They will be executed in the order
// they are defined
/////////////////////////////////////////////////////////
app.use('/account', routes.AccountController);
app.use('/contact', routes.ContactController);
// "/apps/:aid/invites/"
//
// NOTE:
// GET "/apps/:aid/invites/:inviteId" must not required authentication
// Hence, InviteController route must be at the top
app.use('/apps', routes.InviteController);
app.use('/apps', routes.AppController);
// "/apps/:aid/conversations/"
app.use('/apps', routes.ConversationController);
// "/apps/:aid/automessages/"
app.use('/apps', routes.AutoMessageController);
// "/apps/:aid/alerts/"
app.use('/apps', routes.AlertController);
// "/apps/:aid/query/"
app.use('/apps', routes.QueryController);
// "/apps/:aid/segments/"
app.use('/apps', routes.SegmentController);
// "/apps/:aid/users/"
app.use('/apps', routes.UserController);
// "/apps/:aid/users/:uid/notes"
app.use('/apps', routes.UserNoteController);
app.use('/auth', routes.AuthController);
app.use('/mailgun', routes.MailgunController);
/////////////////////////////////////////////////////////
// Root url router should be defined at the end
/////////////////////////////////////////////////////////
app.use('/', routes.IndexController);
/////////////////////////////////////////////////////////
};
/**
* Defines error routes
* @param {Object} app
*/
module.exports.error = function loadErrorRoutes(app) {
////////////////////////////////////////////////////////
// Define error handling routes below
////////////////////////////////////////////////////////
app.use(function (err, req, res, next) {
logger.crit({
err: err,
path: req.path,
body: req.body,
params: req.params,
query: req.query
});
var badRequestErr = errorHelper(err);
res
.status(badRequestErr.status)
.json(badRequestErr);
});
/// catch 404 and forwarding to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res
.status(404)
.json({
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res
.status(404)
.json({
message: err.message,
error: {}
});
});
};
|
'use strict';
describe('Service: ProgramsService', function () {
// load the service's module
beforeEach(module('riplive'));
// instantiate service
var ProgramsService;
beforeEach(inject(function (_ProgramsService_) {
ProgramsService = _ProgramsService_;
}));
it('should do something', function () {
expect(!!ProgramsService).toBe(true);
});
});
|
/*!
* Parsleyjs
* Guillaume Potier - <guillaume@wisembly.com>
* Version 2.0.0-rc5 - built Wed Mar 26 2014 16:25:10
* MIT Licensed
*
*/
!(function($) {
var ParsleyUtils = {
// Parsley DOM-API
// returns object from dom attributes and values
// if attr is given, returns bool if attr present in DOM or not
attr: function ($element, namespace, checkAttr) {
var attribute,
obj = {},
regex = new RegExp('^' + namespace, 'i');
if ('undefined' === typeof $element || 'undefined' === typeof $element[0])
return {};
for (var i in $element[0].attributes) {
attribute = $element[0].attributes[i];
if ('undefined' !== typeof attribute && null !== attribute && attribute.specified && regex.test(attribute.name)) {
if ('undefined' !== typeof checkAttr && new RegExp(checkAttr + '$', 'i').test(attribute.name))
return true;
obj[this.camelize(attribute.name.replace(namespace, ''))] = this.deserializeValue(attribute.value);
}
}
return 'undefined' === typeof checkAttr ? obj : false;
},
setAttr: function ($element, namespace, attr, value) {
$element[0].setAttribute(this.dasherize(namespace + attr), String(value));
},
// Recursive object / array getter
get: function (obj, path) {
var i = 0,
paths = (path || '').split('.');
while (this.isObject(obj) || this.isArray(obj)) {
obj = obj[paths[i++]];
if (i === paths.length)
return obj;
}
return undefined;
},
hash: function (length) {
return String(Math.random()).substring(2, length ? length + 2 : 9);
},
/** Third party functions **/
// Underscore isArray
isArray: function (mixed) {
return Object.prototype.toString.call(mixed) === '[object Array]';
},
// Underscore isObject
isObject: function (mixed) {
return mixed === Object(mixed);
},
// Zepto deserialize function
deserializeValue: function (value) {
var num;
try {
return value ?
value == "true" ||
(value == "false" ? false :
value == "null" ? null :
!isNaN(num = Number(value)) ? num :
/^[\[\{]/.test(value) ? $.parseJSON(value) :
value)
: value;
} catch (e) { return value; }
},
// Zepto camelize function
camelize: function (str) {
return str.replace(/-+(.)?/g, function(match, chr) {
return chr ? chr.toUpperCase() : '';
});
},
// Zepto dasherize function
dasherize: function (str) {
return str.replace(/::/g, '/')
.replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2')
.replace(/([a-z\d])([A-Z])/g, '$1_$2')
.replace(/_/g, '-')
.toLowerCase();
}
};
// All these options could be overriden and specified directly in DOM using
// `data-parsley-` default DOM-API
// eg: `inputs` can be set in DOM using `data-parsley-inputs="input, textarea"`
// eg: `data-parsley-stop-on-first-failing-constraint="false"`
var ParsleyDefaults = {
// ### General
// Default data-namespace for DOM API
namespace: 'data-parsley-',
// Supported inputs by default
inputs: 'input, textarea, select',
// Excluded inputs by default
excluded: 'input[type=button], input[type=submit], input[type=reset]',
// Stop validating field on highest priority failing constraint
priorityEnabled: true,
// ### UI
// Enable\Disable error messages
uiEnabled: true,
// Key events threshold before validation
validationThreshold: 3,
// Focused field on form validation error. 'fist'|'last'|'none'
focus: 'first',
// `$.Event()` that will trigger validation. eg: `keyup`, `change`..
trigger: false,
// Class that would be added on every failing validation Parsley field
errorClass: 'parsley-error',
// Same for success validation
successClass: 'parsley-success',
// Return the `$element` that will receive these above success or error classes
// Could also be (and given directly from DOM) a valid selector like `'#div'`
classHandler: function (ParsleyField) {},
// Return the `$element` where errors will be appended
// Could also be (and given directly from DOM) a valid selector like `'#div'`
errorsContainer: function (ParsleyField) {},
// ul elem that would receive errors' list
errorsWrapper: '<ul class="parsley-errors-list"></ul>',
// li elem that would receive error message
errorTemplate: '<li></li>'
};
var ParsleyAbstract = function() {};
ParsleyAbstract.prototype = {
asyncSupport: false,
actualizeOptions: function () {
this.options = this.parsleyInstance.OptionsFactory.get(this);
return this;
},
// ParsleyValidator validate proxy function . Could be replaced by third party scripts
validateThroughValidator: function (value, constraints, priority) {
return window.ParsleyValidator.validate.apply(window.ParsleyValidator, [value, constraints, priority]);
},
// Subscribe an event and a handler for a specific field or a specific form
// If on a ParsleyForm instance, it will be attached to form instance and also
// To every field instance for this form
subscribe: function (name, fn) {
$.listenTo(this, name.toLowerCase(), fn);
return this;
},
// Same as subscribe above. Unsubscribe an event for field, or form + its fields
unsubscribe: function (name) {
$.unsubscribeTo(this, name.toLowerCase());
return this;
},
// Reset UI
reset: function () {
// Field case: just emit a reset event for UI
if ('ParsleyForm' !== this.__class__)
return $.emit('parsley:field:reset', this);
// Form case: emit a reset event for each field
for (var i = 0; i < this.fields.length; i++)
$.emit('parsley:field:reset', this.fields[i]);
$.emit('parsley:form:reset', this);
},
// Destroy Parsley instance (+ UI)
destroy: function () {
// Field case: emit destroy event to clean UI and then destroy stored instance
if ('ParsleyForm' !== this.__class__) {
$.emit('parsley:field:destroy', this);
this.$element.removeData('Parsley');
return;
}
// Form case: destroy all its fields and then destroy stored instance
for (var i = 0; i < this.fields.length; i++)
this.fields[i].destroy();
$.emit('parsley:form:destroy', this);
this.$element.removeData('Parsley');
}
};
/*!
* validator.js
* Guillaume Potier - <guillaume@wisembly.com>
* Version 0.5.8 - built Sun Mar 16 2014 17:18:21
* MIT Licensed
*
*/
( function ( exports ) {
/**
* Validator
*/
var Validator = function ( options ) {
this.__class__ = 'Validator';
this.__version__ = '0.5.8';
this.options = options || {};
this.bindingKey = this.options.bindingKey || '_validatorjsConstraint';
return this;
};
Validator.prototype = {
constructor: Validator,
/*
* Validate string: validate( string, Assert, string ) || validate( string, [ Assert, Assert ], [ string, string ] )
* Validate object: validate( object, Constraint, string ) || validate( object, Constraint, [ string, string ] )
* Validate binded object: validate( object, string ) || validate( object, [ string, string ] )
*/
validate: function ( objectOrString, AssertsOrConstraintOrGroup, group ) {
if ( 'string' !== typeof objectOrString && 'object' !== typeof objectOrString )
throw new Error( 'You must validate an object or a string' );
// string / array validation
if ( 'string' === typeof objectOrString || _isArray(objectOrString) )
return this._validateString( objectOrString, AssertsOrConstraintOrGroup, group );
// binded object validation
if ( this.isBinded( objectOrString ) )
return this._validateBindedObject( objectOrString, AssertsOrConstraintOrGroup );
// regular object validation
return this._validateObject( objectOrString, AssertsOrConstraintOrGroup, group );
},
bind: function ( object, constraint ) {
if ( 'object' !== typeof object )
throw new Error( 'Must bind a Constraint to an object' );
object[ this.bindingKey ] = new Constraint( constraint );
return this;
},
unbind: function ( object ) {
if ( 'undefined' === typeof object._validatorjsConstraint )
return this;
delete object[ this.bindingKey ];
return this;
},
isBinded: function ( object ) {
return 'undefined' !== typeof object[ this.bindingKey ];
},
getBinded: function ( object ) {
return this.isBinded( object ) ? object[ this.bindingKey ] : null;
},
_validateString: function ( string, assert, group ) {
var result, failures = [];
if ( !_isArray( assert ) )
assert = [ assert ];
for ( var i = 0; i < assert.length; i++ ) {
if ( ! ( assert[ i ] instanceof Assert) )
throw new Error( 'You must give an Assert or an Asserts array to validate a string' );
result = assert[ i ].check( string, group );
if ( result instanceof Violation )
failures.push( result );
}
return failures.length ? failures : true;
},
_validateObject: function ( object, constraint, group ) {
if ( 'object' !== typeof constraint )
throw new Error( 'You must give a constraint to validate an object' );
if ( constraint instanceof Constraint )
return constraint.check( object, group );
return new Constraint( constraint ).check( object, group );
},
_validateBindedObject: function ( object, group ) {
return object[ this.bindingKey ].check( object, group );
}
};
Validator.errorCode = {
must_be_a_string: 'must_be_a_string',
must_be_an_array: 'must_be_an_array',
must_be_a_number: 'must_be_a_number',
must_be_a_string_or_array: 'must_be_a_string_or_array'
};
/**
* Constraint
*/
var Constraint = function ( data, options ) {
this.__class__ = 'Constraint';
this.options = options || {};
this.nodes = {};
if ( data ) {
try {
this._bootstrap( data );
} catch ( err ) {
throw new Error( 'Should give a valid mapping object to Constraint', err, data );
}
}
return this;
};
Constraint.prototype = {
constructor: Constraint,
check: function ( object, group ) {
var result, failures = {};
// check all constraint nodes if strict validation enabled. Else, only object nodes that have a constraint
for ( var property in this.options.strict ? this.nodes : object ) {
if ( this.options.strict ? this.has( property, object ) : this.has( property ) ) {
result = this._check( property, object[ property ], group );
// check returned an array of Violations or an object mapping Violations
if ( ( _isArray( result ) && result.length > 0 ) || ( !_isArray( result ) && !_isEmptyObject( result ) ) )
failures[ property ] = result;
// in strict mode, get a violation for each constraint node not in object
} else if ( this.options.strict ) {
try {
// we trigger here a HaveProperty Assert violation to have uniform Violation object in the end
new Assert().HaveProperty( property ).validate( object );
} catch ( violation ) {
failures[ property ] = violation;
}
}
}
return _isEmptyObject(failures) ? true : failures;
},
add: function ( node, object ) {
if ( object instanceof Assert || ( _isArray( object ) && object[ 0 ] instanceof Assert ) ) {
this.nodes[ node ] = object;
return this;
}
if ( 'object' === typeof object && !_isArray( object ) ) {
this.nodes[ node ] = object instanceof Constraint ? object : new Constraint( object );
return this;
}
throw new Error( 'Should give an Assert, an Asserts array, a Constraint', object );
},
has: function ( node, nodes ) {
nodes = 'undefined' !== typeof nodes ? nodes : this.nodes;
return 'undefined' !== typeof nodes[ node ];
},
get: function ( node, placeholder ) {
return this.has( node ) ? this.nodes[ node ] : placeholder || null;
},
remove: function ( node ) {
var _nodes = [];
for ( var i in this.nodes )
if ( i !== node )
_nodes[ i ] = this.nodes[ i ];
this.nodes = _nodes;
return this;
},
_bootstrap: function ( data ) {
if ( data instanceof Constraint )
return this.nodes = data.nodes;
for ( var node in data )
this.add( node, data[ node ] );
},
_check: function ( node, value, group ) {
// Assert
if ( this.nodes[ node ] instanceof Assert )
return this._checkAsserts( value, [ this.nodes[ node ] ], group );
// Asserts
if ( _isArray( this.nodes[ node ] ) )
return this._checkAsserts( value, this.nodes[ node ], group );
// Constraint -> check api
if ( this.nodes[ node ] instanceof Constraint )
return this.nodes[ node ].check( value, group );
throw new Error( 'Invalid node', this.nodes[ node ] );
},
_checkAsserts: function ( value, asserts, group ) {
var result, failures = [];
for ( var i = 0; i < asserts.length; i++ ) {
result = asserts[ i ].check( value, group );
if ( 'undefined' !== typeof result && true !== result )
failures.push( result );
// Some asserts (Collection for example) could return an object
// if ( result && ! ( result instanceof Violation ) )
// return result;
//
// // Vast assert majority return Violation
// if ( result instanceof Violation )
// failures.push( result );
}
return failures;
}
};
/**
* Violation
*/
var Violation = function ( assert, value, violation ) {
this.__class__ = 'Violation';
if ( ! ( assert instanceof Assert ) )
throw new Error( 'Should give an assertion implementing the Assert interface' );
this.assert = assert;
this.value = value;
if ( 'undefined' !== typeof violation )
this.violation = violation;
};
Violation.prototype = {
show: function () {
var show = {
assert: this.assert.__class__,
value: this.value
};
if ( this.violation )
show.violation = this.violation;
return show;
},
__toString: function () {
if ( 'undefined' !== typeof this.violation )
this.violation = '", ' + this.getViolation().constraint + ' expected was ' + this.getViolation().expected;
return this.assert.__class__ + ' assert failed for "' + this.value + this.violation || '';
},
getViolation: function () {
var constraint, expected;
for ( constraint in this.violation )
expected = this.violation[ constraint ];
return { constraint: constraint, expected: expected };
}
};
/**
* Assert
*/
var Assert = function ( group ) {
this.__class__ = 'Assert';
this.__parentClass__ = this.__class__;
this.groups = [];
if ( 'undefined' !== typeof group )
this.addGroup( group );
return this;
};
Assert.prototype = {
construct: Assert,
check: function ( value, group ) {
if ( group && !this.hasGroup( group ) )
return;
if ( !group && this.hasGroups() )
return;
try {
return this.validate( value, group );
} catch ( violation ) {
return violation;
}
},
hasGroup: function ( group ) {
if ( _isArray( group ) )
return this.hasOneOf( group );
// All Asserts respond to "Any" group
if ( 'Any' === group )
return true;
// Asserts with no group also respond to "Default" group. Else return false
if ( !this.hasGroups() )
return 'Default' === group;
return -1 !== this.groups.indexOf( group );
},
hasOneOf: function ( groups ) {
for ( var i = 0; i < groups.length; i++ )
if ( this.hasGroup( groups[ i ] ) )
return true;
return false;
},
hasGroups: function () {
return this.groups.length > 0;
},
addGroup: function ( group ) {
if ( _isArray( group ) )
return this.addGroups( group );
if ( !this.hasGroup( group ) )
this.groups.push( group );
return this;
},
removeGroup: function ( group ) {
var _groups = [];
for ( var i = 0; i < this.groups.length; i++ )
if ( group !== this.groups[ i ] )
_groups.push( this.groups[ i ] );
this.groups = _groups;
return this;
},
addGroups: function ( groups ) {
for ( var i = 0; i < groups.length; i++ )
this.addGroup( groups[ i ] );
return this;
},
/**
* Asserts definitions
*/
HaveProperty: function ( node ) {
this.__class__ = 'HaveProperty';
this.node = node;
this.validate = function ( object ) {
if ( 'undefined' === typeof object[ this.node ] )
throw new Violation( this, object, { value: this.node } );
return true;
};
return this;
},
Blank: function () {
this.__class__ = 'Blank';
this.validate = function ( value ) {
if ( 'string' !== typeof value )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } );
if ( '' !== value.replace( /^\s+/g, '' ).replace( /\s+$/g, '' ) )
throw new Violation( this, value );
return true;
};
return this;
},
Callback: function ( fn ) {
this.__class__ = 'Callback';
this.arguments = Array.prototype.slice.call( arguments );
if ( 1 === this.arguments.length )
this.arguments = [];
else
this.arguments.splice( 0, 1 );
if ( 'function' !== typeof fn )
throw new Error( 'Callback must be instanciated with a function' );
this.fn = fn;
this.validate = function ( value ) {
var result = this.fn.apply( this, [ value ].concat( this.arguments ) );
if ( true !== result )
throw new Violation( this, value, { result: result } );
return true;
};
return this;
},
Choice: function ( list ) {
this.__class__ = 'Choice';
if ( !_isArray( list ) && 'function' !== typeof list )
throw new Error( 'Choice must be instanciated with an array or a function' );
this.list = list;
this.validate = function ( value ) {
var list = 'function' === typeof this.list ? this.list() : this.list;
for ( var i = 0; i < list.length; i++ )
if ( value === list[ i ] )
return true;
throw new Violation( this, value, { choices: list } );
};
return this;
},
Collection: function ( constraint ) {
this.__class__ = 'Collection';
this.constraint = 'undefined' !== typeof constraint ? new Constraint( constraint ) : false;
this.validate = function ( collection, group ) {
var result, validator = new Validator(), count = 0, failures = {}, groups = this.groups.length ? this.groups : group;
if ( !_isArray( collection ) )
throw new Violation( this, array, { value: Validator.errorCode.must_be_an_array } );
for ( var i = 0; i < collection.length; i++ ) {
result = this.constraint ?
validator.validate( collection[ i ], this.constraint, groups ) :
validator.validate( collection[ i ], groups );
if ( !_isEmptyObject( result ) )
failures[ count ] = result;
count++;
}
return !_isEmptyObject( failures ) ? failures : true;
};
return this;
},
Count: function ( count ) {
this.__class__ = 'Count';
this.count = count;
this.validate = function ( array ) {
if ( !_isArray( array ) )
throw new Violation( this, array, { value: Validator.errorCode.must_be_an_array } );
var count = 'function' === typeof this.count ? this.count( array ) : this.count;
if ( isNaN( Number( count ) ) )
throw new Error( 'Count must be a valid interger', count );
if ( count !== array.length )
throw new Violation( this, array, { count: count } );
return true;
};
return this;
},
Email: function () {
this.__class__ = 'Email';
this.validate = function ( value ) {
var regExp = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
if ( 'string' !== typeof value )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } );
if ( !regExp.test( value ) )
throw new Violation( this, value );
return true;
};
return this;
},
Eql: function ( eql ) {
this.__class__ = 'Eql';
if ( 'undefined' === typeof eql )
throw new Error( 'Equal must be instanciated with an Array or an Object' );
this.eql = eql;
this.validate = function ( value ) {
var eql = 'function' === typeof this.eql ? this.eql( value ) : this.eql;
if ( !expect.eql( eql, value ) )
throw new Violation( this, value, { eql: eql } );
return true;
};
return this;
},
EqualTo: function ( reference ) {
this.__class__ = 'EqualTo';
if ( 'undefined' === typeof reference )
throw new Error( 'EqualTo must be instanciated with a value or a function' );
this.reference = reference;
this.validate = function ( value ) {
var reference = 'function' === typeof this.reference ? this.reference( value ) : this.reference;
if ( reference !== value )
throw new Violation( this, value, { value: reference } );
return true;
};
return this;
},
GreaterThan: function ( threshold ) {
this.__class__ = 'GreaterThan';
if ( 'undefined' === typeof threshold )
throw new Error( 'Should give a threshold value' );
this.threshold = threshold;
this.validate = function ( value ) {
if ( '' === value || isNaN( Number( value ) ) )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } );
if ( this.threshold >= value )
throw new Violation( this, value, { threshold: this.threshold } );
return true;
};
return this;
},
GreaterThanOrEqual: function ( threshold ) {
this.__class__ = 'GreaterThanOrEqual';
if ( 'undefined' === typeof threshold )
throw new Error( 'Should give a threshold value' );
this.threshold = threshold;
this.validate = function ( value ) {
if ( '' === value || isNaN( Number( value ) ) )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } );
if ( this.threshold > value )
throw new Violation( this, value, { threshold: this.threshold } );
return true;
};
return this;
},
InstanceOf: function ( classRef ) {
this.__class__ = 'InstanceOf';
if ( 'undefined' === typeof classRef )
throw new Error( 'InstanceOf must be instanciated with a value' );
this.classRef = classRef;
this.validate = function ( value ) {
if ( true !== (value instanceof this.classRef) )
throw new Violation( this, value, { classRef: this.classRef } );
return true;
};
return this;
},
IPv4: function () {
this.__class__ = 'IPv4';
this.validate = function ( value ) {
var regExp = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if ( 'string' !== typeof value )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } );
if ( !regExp.test( value ) )
throw new Violation( this, value );
return true;
};
return this;
},
Length: function ( boundaries ) {
this.__class__ = 'Length';
if ( !boundaries.min && !boundaries.max )
throw new Error( 'Lenth assert must be instanciated with a { min: x, max: y } object' );
this.min = boundaries.min;
this.max = boundaries.max;
this.validate = function ( value ) {
if ( 'string' !== typeof value && !_isArray( value ) )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string_or_array } );
if ( 'undefined' !== typeof this.min && this.min === this.max && value.length !== this.min )
throw new Violation( this, value, { min: this.min, max: this.max } );
if ( 'undefined' !== typeof this.max && value.length > this.max )
throw new Violation( this, value, { max: this.max } );
if ( 'undefined' !== typeof this.min && value.length < this.min )
throw new Violation( this, value, { min: this.min } );
return true;
};
return this;
},
LessThan: function ( threshold ) {
this.__class__ = 'LessThan';
if ( 'undefined' === typeof threshold )
throw new Error( 'Should give a threshold value' );
this.threshold = threshold;
this.validate = function ( value ) {
if ( '' === value || isNaN( Number( value ) ) )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } );
if ( this.threshold <= value )
throw new Violation( this, value, { threshold: this.threshold } );
return true;
};
return this;
},
LessThanOrEqual: function ( threshold ) {
this.__class__ = 'LessThanOrEqual';
if ( 'undefined' === typeof threshold )
throw new Error( 'Should give a threshold value' );
this.threshold = threshold;
this.validate = function ( value ) {
if ( '' === value || isNaN( Number( value ) ) )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_number } );
if ( this.threshold < value )
throw new Violation( this, value, { threshold: this.threshold } );
return true;
};
return this;
},
Mac: function () {
this.__class__ = 'Mac';
this.validate = function ( value ) {
var regExp = /^(?:[0-9A-F]{2}:){5}[0-9A-F]{2}$/i;
if ( 'string' !== typeof value )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } );
if ( !regExp.test( value ) )
throw new Violation( this, value );
return true;
};
return this;
},
NotNull: function () {
this.__class__ = 'NotNull';
this.validate = function ( value ) {
if ( null === value || 'undefined' === typeof value )
throw new Violation( this, value );
return true;
};
return this;
},
NotBlank: function () {
this.__class__ = 'NotBlank';
this.validate = function ( value ) {
if ( 'string' !== typeof value )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } );
if ( '' === value.replace( /^\s+/g, '' ).replace( /\s+$/g, '' ) )
throw new Violation( this, value );
return true;
};
return this;
},
Null: function () {
this.__class__ = 'Null';
this.validate = function ( value ) {
if ( null !== value )
throw new Violation( this, value );
return true;
};
return this;
},
Range: function ( min, max ) {
this.__class__ = 'Range';
if ( 'undefined' === typeof min || 'undefined' === typeof max )
throw new Error( 'Range assert expects min and max values' );
this.min = min;
this.max = max;
this.validate = function ( value ) {
try {
// validate strings and objects with their Length
if ( ( 'string' === typeof value && isNaN( Number( value ) ) ) || _isArray( value ) )
new Assert().Length( { min: this.min, max: this.max } ).validate( value );
// validate numbers with their value
else
new Assert().GreaterThanOrEqual( this.min ).validate( value ) && new Assert().LessThanOrEqual( this.max ).validate( value );
return true;
} catch ( violation ) {
throw new Violation( this, value, violation.violation );
}
return true;
};
return this;
},
Regexp: function ( regexp, flag ) {
this.__class__ = 'Regexp';
if ( 'undefined' === typeof regexp )
throw new Error( 'You must give a regexp' );
this.regexp = regexp;
this.flag = flag || '';
this.validate = function ( value ) {
if ( 'string' !== typeof value )
throw new Violation( this, value, { value: Validator.errorCode.must_be_a_string } );
if ( !new RegExp( this.regexp, this.flag ).test( value ) )
throw new Violation( this, value, { regexp: this.regexp, flag: this.flag } );
return true;
};
return this;
},
Required: function () {
this.__class__ = 'Required';
this.validate = function ( value ) {
if ( 'undefined' === typeof value )
throw new Violation( this, value );
try {
if ( 'string' === typeof value )
new Assert().NotNull().validate( value ) && new Assert().NotBlank().validate( value );
else if ( true === _isArray( value ) )
new Assert().Length( { min: 1 } ).validate( value );
} catch ( violation ) {
throw new Violation( this, value );
}
return true;
};
return this;
},
// Unique() or Unique ( { key: foo } )
Unique: function ( object ) {
this.__class__ = 'Unique';
if ( 'object' === typeof object )
this.key = object.key;
this.validate = function ( array ) {
var value, store = [];
if ( !_isArray( array ) )
throw new Violation( this, array, { value: Validator.errorCode.must_be_an_array } );
for ( var i = 0; i < array.length; i++ ) {
value = 'object' === typeof array[ i ] ? array[ i ][ this.key ] : array[ i ];
if ( 'undefined' === typeof value )
continue;
if ( -1 !== store.indexOf( value ) )
throw new Violation( this, array, { value: value } );
store.push( value );
}
return true;
};
return this;
}
};
// expose to the world these awesome classes
exports.Assert = Assert;
exports.Validator = Validator;
exports.Violation = Violation;
exports.Constraint = Constraint;
/**
* Some useful object prototypes / functions here
*/
// IE8<= compatibility
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf)
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
if (this === null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n !== 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
// Test if object is empty, useful for Constraint violations check
var _isEmptyObject = function ( obj ) {
for ( var property in obj )
return false;
return true;
};
var _isArray = function ( obj ) {
return Object.prototype.toString.call( obj ) === '[object Array]';
};
// https://github.com/LearnBoost/expect.js/blob/master/expect.js
var expect = {
eql: function ( actual, expected ) {
if ( actual === expected ) {
return true;
} else if ( 'undefined' !== typeof Buffer && Buffer.isBuffer( actual ) && Buffer.isBuffer( expected ) ) {
if ( actual.length !== expected.length ) return false;
for ( var i = 0; i < actual.length; i++ )
if ( actual[i] !== expected[i] ) return false;
return true;
} else if ( actual instanceof Date && expected instanceof Date ) {
return actual.getTime() === expected.getTime();
} else if ( typeof actual !== 'object' && typeof expected !== 'object' ) {
// loosy ==
return actual == expected;
} else {
return this.objEquiv(actual, expected);
}
},
isUndefinedOrNull: function ( value ) {
return value === null || typeof value === 'undefined';
},
isArguments: function ( object ) {
return Object.prototype.toString.call(object) == '[object Arguments]';
},
keys: function ( obj ) {
if ( Object.keys )
return Object.keys( obj );
var keys = [];
for ( var i in obj )
if ( Object.prototype.hasOwnProperty.call( obj, i ) )
keys.push(i);
return keys;
},
objEquiv: function ( a, b ) {
if ( this.isUndefinedOrNull( a ) || this.isUndefinedOrNull( b ) )
return false;
if ( a.prototype !== b.prototype ) return false;
if ( this.isArguments( a ) ) {
if ( !this.isArguments( b ) )
return false;
return eql( pSlice.call( a ) , pSlice.call( b ) );
}
try {
var ka = this.keys( a ), kb = this.keys( b ), key, i;
if ( ka.length !== kb.length )
return false;
ka.sort();
kb.sort();
for ( i = ka.length - 1; i >= 0; i-- )
if ( ka[ i ] != kb[ i ] )
return false;
for ( i = ka.length - 1; i >= 0; i-- ) {
key = ka[i];
if ( !this.eql( a[ key ], b[ key ] ) )
return false;
}
return true;
} catch ( e ) {
return false;
}
}
};
// AMD Compliance
if ( "function" === typeof define && define.amd ) {
define( 'validator', [],function() { return exports; } );
}
} )( 'undefined' === typeof exports ? this[ 'undefined' !== typeof validatorjs_ns ? validatorjs_ns : 'Validator' ] = {} : exports );
var ParsleyValidator = function (validators, catalog) {
this.__class__ = 'ParsleyValidator';
this.Validator = Validator;
// Default Parsley locale is en
this.locale = 'en';
this.init(validators || {}, catalog || {});
};
ParsleyValidator.prototype = {
init: function (validators, catalog) {
this.catalog = catalog;
for (var name in validators)
this.addValidator(name, validators[name].fn, validators[name].priority);
$.emit('parsley:validator:init');
},
// Set new messages locale if we have dictionary loaded in ParsleyConfig.i18n
setLocale: function (locale) {
if ('undefined' === typeof this.catalog[locale])
throw new Error(locale + ' is not available in the catalog');
this.locale = locale;
return this;
},
// Add a new messages catalog for a given locale. Set locale for this catalog if set === `true`
addCatalog: function (locale, messages, set) {
if ('object' === typeof messages)
this.catalog[locale] = messages;
if (true === set)
return this.setLocale(locale);
return this;
},
// Add a specific message for a given constraint in a given locale
addMessage: function (locale, name, message) {
if (undefined === typeof this.catalog[locale])
this.catalog[locale] = {};
this.catalog[locale][name] = message;
return this;
},
validate: function (value, constraints, priority) {
return new this.Validator.Validator().validate.apply(new Validator.Validator(), arguments);
},
// Add a new validator
addValidator: function (name, fn, priority) {
this.validators[name] = function (requirements) {
return $.extend(new Validator.Assert().Callback(fn, requirements), { priority: priority });
};
return this;
},
updateValidator: function (name, fn, priority) {
return addValidator(name, fn, priority);
},
removeValidator: function (name) {
delete this.validators[name];
return this;
},
getErrorMessage: function (constraint) {
var message;
// Type constraints are a bit different, we have to match their requirements too to find right error message
if ('type' === constraint.name)
message = window.ParsleyConfig.i18n[this.locale][constraint.name][constraint.requirements];
else
message = this.formatMesssage(window.ParsleyConfig.i18n[this.locale][constraint.name], constraint.requirements);
return '' !== message ? message : window.ParsleyConfig.i18n[this.locale].defaultMessage;
},
// Kind of light `sprintf()` implementation
formatMesssage: function (string, parameters) {
if ('object' === typeof parameters) {
for (var i in parameters)
string = this.formatMesssage(string, parameters[i]);
return string;
}
return 'string' === typeof string ? string.replace(new RegExp('%s', 'i'), parameters) : '';
},
// Here is the Parsley default validators list.
// This is basically Validatorjs validators, with different API for some of them
// and a Parsley priority set
validators: {
notblank: function () {
return $.extend(new Validator.Assert().NotBlank(), { priority: 2 });
},
required: function () {
return $.extend(new Validator.Assert().Required(), { priority: 512 });
},
type: function (type) {
var assert;
switch (type) {
case 'email':
assert = new Validator.Assert().Email();
break;
case 'number':
assert = new Validator.Assert().Regexp('^-?(?:\\d+|\\d{1,3}(?:,\\d{3})+)?(?:\\.\\d+)?$');
break;
case 'integer':
assert = new Validator.Assert().Regexp('^-?\\d+$');
break;
case 'digits':
assert = new Validator.Assert().Regexp('^\\d+$');
break;
case 'alphanum':
assert = new Validator.Assert().Regexp('^\\w+$', 'i');
break;
case 'url':
assert = new Validator.Assert().Regexp('(https?:\\/\\/)?(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,4}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)', 'i');
break;
default:
throw new Error('validator type `' + type + '` is not supported');
}
return $.extend(assert, { priority: 256 });
},
pattern: function (regexp) {
var flags = '';
// Test if RegExp is literal, if not, nothing to be done, otherwise, we need to isolate flags and pattern
if (!!(/^\/.*\/(?:[gimy]*)$/.test(regexp))) {
// Replace the regexp literal string with the first match group: ([gimy]*)
// If no flag is present, this will be a blank string
flags = regexp.replace(/.*\/([gimy]*)$/, '$1');
// Again, replace the regexp literal string with the first match group:
// everything excluding the opening and closing slashes and the flags
regexp = regexp.replace(new RegExp('^/(.*?)/' + flags + '$'), '$1');
}
return $.extend(new Validator.Assert().Regexp(regexp, flags), { priority: 64 });
},
minlength: function (value) {
return $.extend(new Validator.Assert().Length({ min: value }), {
priority: 30,
requirementsTransformer: function () {
return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value;
}
});
},
maxlength: function (value) {
return $.extend(new Validator.Assert().Length({ max: value }), {
priority: 30,
requirementsTransformer: function () {
return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value;
}
});
},
length: function (array) {
return $.extend(new Validator.Assert().Length({ min: array[0], max: array[1] }), { priority: 32 });
},
mincheck: function (length) {
return this.minlength(length);
},
maxcheck: function (length) {
return this.maxlength(length);
},
check: function (array) {
return this.length(array);
},
min: function (value) {
return $.extend(new Validator.Assert().GreaterThanOrEqual(value), {
priority: 30,
requirementsTransformer: function () {
return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value;
}
});
},
max: function (value) {
return $.extend(new Validator.Assert().LessThanOrEqual(value), {
priority: 30,
requirementsTransformer: function () {
return 'string' === typeof value && !isNaN(value) ? parseInt(value, 10) : value;
}
});
},
range: function (array) {
return $.extend(new Validator.Assert().Range(array[0], array[1]), {
priority: 32,
requirementsTransformer: function () {
for (var i = 0; i < array.length; i++)
array[i] = 'string' === typeof array[i] && !isNaN(array[i]) ? parseInt(array[i], 10) : array[i];
return array;
}
});
},
equalto: function (value) {
return $.extend(new Validator.Assert().EqualTo(value), {
priority: 256,
requirementsTransformer: function () {
return $(value).length ? $(value).val() : value;
}
});
}
}
};
var ParsleyUI = function (options) {
this.__class__ = 'ParsleyUI';
};
ParsleyUI.prototype = {
listen: function () {
$.listen('parsley:form:init', this, this.setupForm);
$.listen('parsley:field:init', this, this.setupField);
$.listen('parsley:field:validated', this, this.reflow);
$.listen('parsley:form:validated', this, this.focus);
$.listen('parsley:field:reset', this, this.reset);
$.listen('parsley:form:destroy', this, this.destroy);
$.listen('parsley:field:destroy', this, this.destroy);
return this;
},
reflow: function (fieldInstance) {
// If this field has not an active UI (case for multiples) don't bother doing something
if ('undefined' === typeof fieldInstance._ui || false === fieldInstance._ui.active)
return;
// Diff between two validation results
var diff = this._diff(fieldInstance.validationResult, fieldInstance._ui.lastValidationResult);
// Then store current validation result for next reflow
fieldInstance._ui.lastValidationResult = fieldInstance.validationResult;
// Field have been validated at least once if here. Useful for binded key events..
fieldInstance._ui.validatedOnce = true;
// Handle valid / invalid / none field class
this.manageStatusClass(fieldInstance);
// Add, remove, updated errors messages
this.manageErrorsMessages(fieldInstance, diff);
// Triggers impl
this.actualizeTriggers(fieldInstance);
// If field is not valid for the first time, bind keyup trigger to ease UX and quickly inform user
if ((diff.kept.length || diff.added.length) && 'undefined' === typeof fieldInstance._ui.failedOnce)
this.manageFailingFieldTrigger(fieldInstance);
},
manageStatusClass: function (fieldInstance) {
if (true === fieldInstance.validationResult)
this._successClass(fieldInstance);
else if (fieldInstance.validationResult.length > 0)
this._errorClass(fieldInstance);
else
this._resetClass(fieldInstance);
},
manageErrorsMessages: function (fieldInstance, diff) {
if ('undefined' !== typeof fieldInstance.options.errorsMessagesDisabled)
return;
// Case where we have errorMessage option that configure an unique field error message, regardless failing validators
if ('undefined' !== typeof fieldInstance.options.errorMessage) {
if ((diff.added.length || diff.kept.length)) {
if (0 === fieldInstance._ui.$errorsWrapper.find('.parsley-custom-error-message').length)
fieldInstance._ui.$errorsWrapper
.append($(fieldInstance.options.errorTemplate)
.addClass('parsley-custom-error-message'));
fieldInstance._ui.$errorsWrapper
.addClass('filled')
.find('.parsley-custom-error-message')
.html(fieldInstance.options.errorMessage);
} else {
fieldInstance._ui.$errorsWrapper
.removeClass('filled')
.find('.parsley-custom-error-message')
.remove();
}
return;
}
// Show, hide, update failing constraints messages
for (var i = 0; i < diff.removed.length; i++)
this.removeError(fieldInstance, diff.removed[i].assert.name, true);
for (i = 0; i < diff.added.length; i++)
this.addError(fieldInstance, diff.added[i].assert.name, undefined, diff.added[i].assert, true);
for (i = 0; i < diff.kept.length; i++)
this.updateError(fieldInstance, diff.kept[i].assert.name, undefined, diff.kept[i].assert, true);
},
// TODO: strange API here, intuitive for manual usage with addError(pslyInstance, 'foo', 'bar')
// but a little bit complex for above internal usage, with forced undefined parametter..
addError: function (fieldInstance, name, message, assert, doNotUpdateClass) {
fieldInstance._ui.$errorsWrapper
.addClass('filled')
.append($(fieldInstance.options.errorTemplate)
.addClass('parsley-' + name)
.html(message || this._getErrorMessage(fieldInstance, assert)));
if (true !== doNotUpdateClass)
this._errorClass(fieldInstance);
},
// Same as above
updateError: function (fieldInstance, name, message, assert, doNotUpdateClass) {
fieldInstance._ui.$errorsWrapper
.addClass('filled')
.find('.parsley-' + name)
.html(message || this._getErrorMessage(fieldInstance, assert));
if (true !== doNotUpdateClass)
this._errorClass(fieldInstance);
},
// Same as above twice
removeError: function (fieldInstance, name, doNotUpdateClass) {
fieldInstance._ui.$errorsWrapper
.removeClass('filled')
.find('.parsley-' + name)
.remove();
// edge case possible here: remove a standard Parsley error that is still failing in fieldInstance.validationResult
// but highly improbable cuz' manually removing a well Parsley handled error makes no sense.
if (true !== doNotUpdateClass)
this.manageStatusClass(fieldInstance);
},
focus: function (formInstance) {
if (true === formInstance.validationResult || 'none' === formInstance.options.focus)
return formInstance._focusedField = null;
formInstance._focusedField = null;
for (var i = 0; i < formInstance.fields.length; i++)
if (true !== formInstance.fields[i].validationResult && formInstance.fields[i].validationResult.length > 0 && 'undefined' === typeof formInstance.fields[i].options.noFocus) {
if ('first' === formInstance.options.focus) {
formInstance._focusedField = formInstance.fields[i].$element;
return formInstance._focusedField.focus();
}
formInstance._focusedField = formInstance.fields[i].$element;
}
if (null === formInstance._focusedField)
return null;
return formInstance._focusedField.focus();
},
_getErrorMessage: function (fieldInstance, constraint) {
var customConstraintErrorMessage = constraint.name + 'Message';
if ('undefined' !== typeof fieldInstance.options[customConstraintErrorMessage])
return fieldInstance.options[customConstraintErrorMessage];
return window.ParsleyValidator.getErrorMessage(constraint);
},
_diff: function (newResult, oldResult, deep) {
var added = [],
kept = [];
for (var i = 0; i < newResult.length; i++) {
var found = false;
for (var j = 0; j < oldResult.length; j++)
if (newResult[i].assert.name === oldResult[j].assert.name) {
found = true;
break;
}
if (found)
kept.push(newResult[i]);
else
added.push(newResult[i]);
}
return {
kept: kept,
added: added,
removed: !deep ? this._diff(oldResult, newResult, true).added : []
};
},
setupForm: function (formInstance) {
formInstance.$element.on('submit.Parsley', false, $.proxy(formInstance.onSubmitValidate, formInstance));
// UI could be disabled
if (false === formInstance.options.uiEnabled)
return;
formInstance.$element.attr('novalidate', '');
},
setupField: function (fieldInstance) {
var _ui = { active: false };
// UI could be disabled
if (false === fieldInstance.options.uiEnabled)
return;
_ui.active = true;
// Give field its Parsley id in DOM
fieldInstance.$element.attr(fieldInstance.options.namespace + 'id', fieldInstance.__id__);
/** Generate important UI elements and store them in fieldInstance **/
// $errorClassHandler is the $element that woul have parsley-error and parsley-success classes
_ui.$errorClassHandler = this._manageClassHandler(fieldInstance);
// $errorsWrapper is a div that would contain the various field errors, it will be appended into $errorsContainer
_ui.errorsWrapperId = 'parsley-id-' + ('undefined' !== typeof fieldInstance.options.multiple ? 'multiple-' + fieldInstance.options.multiple : fieldInstance.__id__);
_ui.$errorsWrapper = $(fieldInstance.options.errorsWrapper).attr('id', _ui.errorsWrapperId);
// ValidationResult UI storage to detect what have changed bwt two validations, and update DOM accordingly
_ui.lastValidationResult = [];
_ui.validatedOnce = false;
_ui.validationInformationVisible = false;
// Store it in fieldInstance for later
fieldInstance._ui = _ui;
/** Mess with DOM now **/
this._insertErrorWrapper(fieldInstance);
// Bind triggers first time
this.actualizeTriggers(fieldInstance);
},
// Determine which element will have `parsley-error` and `parsley-success` classes
_manageClassHandler: function (fieldInstance) {
// An element selector could be passed through DOM with `data-parsley-class-handler=#foo`
if ('string' === typeof fieldInstance.options.classHandler && $(fieldInstance.options.classHandler).length)
return $(fieldInstance.options.classHandler);
// Class handled could also be determined by function given in Parsley options
var $handler = fieldInstance.options.classHandler(fieldInstance);
// If this function returned a valid existing DOM element, go for it
if ('undefined' !== typeof $handler && $handler.length)
return $handler;
// Otherwise, if simple element (input, texatrea, select..) it will perfectly host the classes
if ('undefined' === typeof fieldInstance.options.multiple || fieldInstance.$element.is('select'))
return fieldInstance.$element;
// But if multiple element (radio, checkbox), that would be their parent
return fieldInstance.$element.parent();
},
_insertErrorWrapper: function (fieldInstance) {
var $errorsContainer;
if ('string' === typeof fieldInstance.options.errorsContainer )
if ($(fieldInstance.options.errorsContainer + '').length)
return $(fieldInstance.options.errorsContainer).append(fieldInstance._ui.$errorsWrapper);
else if (window.console && window.console.warn)
window.console.warn('The errors container `' + fieldInstance.options.errorsContainer + '` does not exist in DOM');
if ('function' === typeof fieldInstance.options.errorsContainer)
$errorsContainer = fieldInstance.options.errorsContainer(fieldInstance);
if ('undefined' !== typeof $errorsContainer && $errorsContainer.length)
return $errorsContainer.append(fieldInstance._ui.$errorsWrapper);
return 'undefined' === typeof fieldInstance.options.multiple ? fieldInstance.$element.after(fieldInstance._ui.$errorsWrapper) : fieldInstance.$element.parent().after(fieldInstance._ui.$errorsWrapper);
},
actualizeTriggers: function (fieldInstance) {
var that = this;
// Remove Parsley events already binded on this field
if (fieldInstance.options.multiple)
$('[' + fieldInstance.options.namespace + 'multiple="' + fieldInstance.options.multiple + '"]').each(function () {
$(this).off('.Parsley');
});
else
fieldInstance.$element.off('.Parsley');
// If no trigger is set, all good
if (false === fieldInstance.options.trigger)
return;
var triggers = fieldInstance.options.trigger.replace(/^\s+/g , '').replace(/\s+$/g , '');
if ('' === triggers)
return;
// Bind fieldInstance.eventValidate if exists (for parsley.ajax for example), ParsleyUI.eventValidate otherwise
if (fieldInstance.options.multiple)
$('[' + fieldInstance.options.namespace + 'multiple="' + fieldInstance.options.multiple + '"]').each(function () {
$(this).on(
triggers.split(' ').join('.Parsley ') + '.Parsley',
false,
$.proxy('function' === typeof fieldInstance.eventValidate ? fieldInstance.eventValidate : that.eventValidate, fieldInstance));
});
else
fieldInstance.$element
.on(
triggers.split(' ').join('.Parsley ') + '.Parsley',
false,
$.proxy('function' === typeof fieldInstance.eventValidate ? fieldInstance.eventValidate : this.eventValidate, fieldInstance));
},
// Called through $.proxy with fieldInstance. `this` context is ParsleyField
eventValidate: function(event) {
// For keyup, keypress, keydown.. events that could be a little bit obstrusive
// do not validate if val length < min threshold on first validation. Once field have been validated once and info
// about success or failure have been displayed, always validate with this trigger to reflect every yalidation change.
if (new RegExp('key').test(event.type))
if (!this._ui.validationInformationVisible && this.getValue().length <= this.options.validationThreshold)
return;
this._ui.validatedOnce = true;
this.validate();
},
manageFailingFieldTrigger: function (fieldInstance) {
fieldInstance._ui.failedOnce = true;
// Radio and checkboxes fields must bind every field multiple
if (fieldInstance.options.multiple)
$('[' + fieldInstance.options.namespace + 'multiple="' + fieldInstance.options.multiple + '"]').each(function () {
if (!new RegExp('change', 'i').test($(this).parsley().options.trigger || ''))
return $(this).on('change.ParsleyFailedOnce', false, $.proxy(fieldInstance.validate, fieldInstance));
});
// Select case
if (fieldInstance.$element.is('select'))
if (!new RegExp('change', 'i').test(fieldInstance.options.trigger || ''))
return fieldInstance.$element.on('change.ParsleyFailedOnce', false, $.proxy(fieldInstance.validate, fieldInstance));
// All other inputs fields
if (!new RegExp('keyup', 'i').test(fieldInstance.options.trigger || ''))
return fieldInstance.$element.on('keyup.ParsleyFailedOnce', false, $.proxy(fieldInstance.validate, fieldInstance));
},
reset: function (parsleyInstance) {
// Nothing to do if UI never initialized for this field
if ('undefined' === typeof parsleyInstance._ui)
return;
// Reset all event listeners
parsleyInstance.$element.off('.Parsley');
parsleyInstance.$element.off('.ParsleyFailedOnce');
if ('ParsleyForm' === parsleyInstance.__class__)
return;
// Reset all errors' li
parsleyInstance._ui.$errorsWrapper.children().each(function () {
$(this).remove();
});
// Reset validation class
this._resetClass(parsleyInstance);
// Reset validation flags and last validation result
parsleyInstance._ui.validatedOnce = false;
parsleyInstance._ui.lastValidationResult = [];
parsleyInstance._ui.validationInformationVisible = false;
},
destroy: function (parsleyInstance) {
// Nothing to do if UI never initialized for this field
if ('undefined' === typeof parsleyInstance._ui)
return;
this.reset(parsleyInstance);
if ('ParsleyForm' === parsleyInstance.__class__)
return;
parsleyInstance._ui.$errorsWrapper.remove();
delete parsleyInstance._ui;
},
_successClass: function (fieldInstance) {
fieldInstance._ui.validationInformationVisible = true;
fieldInstance._ui.$errorClassHandler.removeClass(fieldInstance.options.errorClass).addClass(fieldInstance.options.successClass);
},
_errorClass: function (fieldInstance) {
fieldInstance._ui.validationInformationVisible = true;
fieldInstance._ui.$errorClassHandler.removeClass(fieldInstance.options.successClass).addClass(fieldInstance.options.errorClass);
},
_resetClass: function (fieldInstance) {
fieldInstance._ui.$errorClassHandler.removeClass(fieldInstance.options.successClass).removeClass(fieldInstance.options.errorClass);
}
};
var ParsleyOptionsFactory = function (defaultOptions, globalOptions, userOptions, namespace) {
this.__class__ = 'OptionsFactory';
this.__id__ = ParsleyUtils.hash(4);
this.formOptions = null;
this.fieldOptions = null;
this.staticOptions = $.extend(true, {}, defaultOptions, globalOptions, userOptions, { namespace: namespace });
};
ParsleyOptionsFactory.prototype = {
get: function (parsleyInstance) {
if ('undefined' === typeof parsleyInstance.__class__)
throw new Error('Parsley Instance expected');
switch (parsleyInstance.__class__) {
case 'Parsley':
return this.staticOptions;
case 'ParsleyForm':
return this.getFormOptions(parsleyInstance);
case 'ParsleyField':
case 'ParsleyFieldMultiple':
return this.getFieldOptions(parsleyInstance);
default:
throw new Error('Instance ' + parsleyInstance.__class__ + ' is not supported');
}
},
getFormOptions: function (formInstance) {
this.formOptions = ParsleyUtils.attr(formInstance.$element, this.staticOptions.namespace);
// not deep extend, since formOptions is a 1 level deep object
return $.extend({}, this.staticOptions, this.formOptions);
},
getFieldOptions: function (fieldInstance) {
this.fieldOptions = ParsleyUtils.attr(fieldInstance.$element, this.staticOptions.namespace);
if (null === this.formOptions && 'ParsleyForm' === fieldInstance.parsleyInstance.__proxy__)
this.formOptions = getFormOptions(fieldInstance.parsleyInstance);
// not deep extend, since formOptions and fieldOptions is a 1 level deep object
return $.extend({}, this.staticOptions, this.formOptions, this.fieldOptions);
}
};
var ParsleyForm = function(element, parsleyInstance) {
this.__class__ = 'ParsleyForm';
this.__id__ = ParsleyUtils.hash(4);
if ('Parsley' !== ParsleyUtils.get(parsleyInstance, '__class__'))
throw new Error('You must give a Parsley instance');
this.parsleyInstance = parsleyInstance;
this.$element = $(element);
};
ParsleyForm.prototype = {
init: function () {
this.validationResult = null;
this.options = this.parsleyInstance.OptionsFactory.get(this);
this._bindFields();
return this;
},
onSubmitValidate: function (event) {
this.validate(undefined, undefined, event);
// prevent form submission if validation fails
if (false === this.validationResult && event instanceof $.Event)
event.preventDefault();
return this;
},
// @returns boolean
validate: function (group, force, event) {
this.submitEvent = event;
this.validationResult = true;
var fieldValidationResult = [];
// Refresh form DOM options and form's fields that could have changed
this._refreshFields();
$.emit('parsley:form:validate', this);
// loop through fields to validate them one by one
for (var i = 0; i < this.fields.length; i++) {
// do not validate a field if not the same as given validation group
if (group && group !== this.fields[i].options.group)
continue;
fieldValidationResult = this.fields[i].validate(force);
if (true !== fieldValidationResult && fieldValidationResult.length > 0 && this.validationResult)
this.validationResult = false;
}
$.emit('parsley:form:validated', this);
return this.validationResult;
},
// Iterate over refreshed fields, and stop on first failure
isValid: function (group, force) {
this._refreshFields();
for (var i = 0; i < this.fields.length; i++) {
// do not validate a field if not the same as given validation group
if (group && group !== this.fields[i].options.group)
continue;
if (false === this.fields[i].isValid(force))
return false;
}
return true;
},
_refreshFields: function () {
return this.actualizeOptions()._bindFields();
},
_bindFields: function () {
var self = this;
this.fields = [];
this.fieldsMappedById = {};
this.$element.find(this.options.inputs).each(function () {
var fieldInstance = new window.Parsley(this, {}, self.parsleyInstance);
// Only add valid and not excluded `ParsleyField` and `ParsleyFieldMultiple` children
if (('ParsleyField' === fieldInstance.__class__ || 'ParsleyFieldMultiple' === fieldInstance.__class__) && !fieldInstance.$element.is(fieldInstance.options.excluded))
if ('undefined' === typeof self.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__]) {
self.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__] = fieldInstance;
self.fields.push(fieldInstance);
}
});
return this;
}
};
var ConstraintFactory = function (parsleyField, name, requirements, priority, isDomConstraint) {
if (!new RegExp('ParsleyField').test(ParsleyUtils.get(parsleyField, '__class__')))
throw new Error('ParsleyField or ParsleyFieldMultiple instance expected');
if ('function' !== typeof window.ParsleyValidator.validators[name] &&
'Assert' !== window.ParsleyValidator.validators[name](requirements).__parentClass__)
throw new Error('Valid validator expected');
var getPriority = function (parsleyField, name) {
if ('undefined' !== typeof parsleyField.options[name + 'Priority'])
return parsleyField.options[name + 'Priority'];
return ParsleyUtils.get(window.ParsleyValidator.validators[name](requirements), 'priority') || 2;
};
priority = priority || getPriority(parsleyField, name);
// If validator have a requirementsTransformer, execute it
if ('function' === typeof window.ParsleyValidator.validators[name](requirements).requirementsTransformer)
requirements = window.ParsleyValidator.validators[name](requirements).requirementsTransformer();
return $.extend(window.ParsleyValidator.validators[name](requirements), {
name: name,
requirements: requirements,
priority: priority,
groups: [priority],
isDomConstraint: isDomConstraint || ParsleyUtils.attr(parsleyField.$element, parsleyField.options.namespace, name)
});
};
var ParsleyField = function(field, parsleyInstance) {
this.__class__ = 'ParsleyField';
this.__id__ = ParsleyUtils.hash(4);
if ('Parsley' !== ParsleyUtils.get(parsleyInstance, '__class__'))
throw new Error('You must give a Parsley instance');
this.parsleyInstance = parsleyInstance;
this.$element = $(field);
this.options = this.parsleyInstance.OptionsFactory.get(this);
};
ParsleyField.prototype = {
init: function () {
this.constraints = [];
this.validationResult = [];
this.bindConstraints();
return this;
},
// Returns validationResult. For field, it could be:
// - `true` if all green
// - `[]` if non required field and empty
// - `[Violation, [Violation..]]` if errors
validate: function (force) {
this.value = this.getValue();
// Field Validate event. `this.value` could be altered for custom needs
$.emit('parsley:field:validate', this);
$.emit('parsley:field:' + (this.isValid(force, this.value) ? 'success' : 'error'), this);
// Field validated event. `this.validationResult` could be altered for custom needs too
$.emit('parsley:field:validated', this);
return this.validationResult;
},
getConstraintsSortedPriorities: function () {
var priorities = [];
// Create array unique of priorities
for (var i = 0; i < this.constraints.length; i++)
if (-1 === priorities.indexOf(this.constraints[i].priority))
priorities.push(this.constraints[i].priority);
// Sort them by priority DESC
priorities.sort(function (a, b) { return b - a; });
return priorities;
},
// Same @return as `validate()`
isValid: function (force, value) {
// Recompute options and rebind constraints to have latest changes
this.refreshConstraints();
// Sort priorities to validate more important first
var priorities = this.getConstraintsSortedPriorities();
// Value could be passed as argument, needed to add more power to 'parsley:field:validate'
value = value || this.getValue();
// If a field is empty and not required, leave it alone, it's just fine
// Except if `data-parsley-validate-if-empty` explicitely added, useful for some custom validators
if (0 === value.length && !this.isRequired() && 'undefined' === typeof this.options.validateIfEmpty && true !== force)
return this.validationResult = [];
// If we want to validate field against all constraints, just call Validator and let it do the job
if (false === this.options.priorityEnabled)
return true === (this.validationResult = this.validateThroughValidator(value, this.constraints, 'Any'));
// Else, iterate over priorities one by one, and validate related asserts one by one
for (var i = 0; i < priorities.length; i++)
if (true !== (this.validationResult = this.validateThroughValidator(value, this.constraints, priorities[i])))
return false;
return true;
},
// Field is required if have required constraint without `false` value
isRequired: function () {
var constraintIndex = this._constraintIndex('required');
return !(-1 === constraintIndex || (-1 !== constraintIndex && false === this.constraints[constraintIndex].requirements));
},
getValue: function () {
var value;
// Value could be overriden in DOM
if ('undefined' !== typeof this.options.value)
value = this.options.value;
else
value = this.$element.val();
// Use `data-parsley-trim-value="true"` to auto trim inputs entry
if (true === this.options.trimValue)
return value.replace(/^\s+|\s+$/g, '');
return value;
},
refreshConstraints: function () {
this.actualizeOptions().bindConstraints();
return this;
},
bindConstraints: function () {
var constraints = [];
// clean all existing DOM constraints to only keep javascript user constraints
for (var i = 0; i < this.constraints.length; i++)
if (false === this.constraints[i].isDomConstraint)
constraints.push(this.constraints[i]);
this.constraints = constraints;
// then re-add Parsley DOM-API constraints
for (var name in this.options)
this.addConstraint(name, this.options[name]);
// finally, bind special HTML5 constraints
return this.bindHtml5Constraints();
},
bindHtml5Constraints: function () {
// html5 required
if (this.$element.hasClass('required') || this.$element.attr('required'))
this.addConstraint('required', true, undefined, true);
// html5 pattern
if ('string' === typeof this.$element.attr('pattern'))
this.addConstraint('pattern', this.$element.attr('pattern'), undefined, true);
// range
if ('undefined' !== typeof this.$element.attr('min') && 'undefined' !== typeof this.$element.attr('max'))
this.addConstraint('range', [this.$element.attr('min'), this.$element.attr('max')], undefined, true);
// HTML5 min
else if ('undefined' !== typeof this.$element.attr('min'))
this.addConstraint('min', this.$element.attr('min'), undefined, true);
// HTML5 max
else if ('undefined' !== typeof this.$element.attr('max'))
this.addConstraint('max', this.$element.attr('max'), undefined, true);
// html5 types
var type = this.$element.attr('type');
if ('undefined' === typeof type)
return this;
// Small special case here for HTML5 number, that is in fact an integer validator
if ('number' === type)
return this.addConstraint('type', 'integer', undefined, true);
// Regular other HTML5 supported types
else if (new RegExp(type, 'i').test('email url range'))
return this.addConstraint('type', type, undefined, true);
},
/**
* Add a new constraint to a field
*
* @method addConstraint
* @param {String} name
* @param {Mixed} requirements optional
* @param {Number} priority optional
* @param {Boolean} isDomConstraint optional
*/
addConstraint: function (name, requirements, priority, isDomConstraint) {
name = name.toLowerCase();
if ('function' === typeof window.ParsleyValidator.validators[name]) {
var constraint = new ConstraintFactory(this, name, requirements, priority, isDomConstraint);
// if constraint already exist, delete it and push new version
if (-1 !== this._constraintIndex(constraint.name))
this.removeConstraint(constraint.name);
this.constraints.push(constraint);
}
return this;
},
removeConstraint: function (name) {
for (var i = 0; i < this.constraints.length; i++)
if (name === this.constraints[i].name) {
this.constraints.splice(i, 1);
break;
}
return this;
},
updateConstraint: function (name, parameters, priority) {
return this.removeConstraint(name)
.addConstraint(name, parameters, priority);
},
_constraintIndex: function (name) {
for (var i = 0; i < this.constraints.length; i++)
if (name === this.constraints[i].name)
return i;
return -1;
}
};
var ParsleyMultiple = function() {
this.__class__ = 'ParsleyFieldMultiple';
};
ParsleyMultiple.prototype = {
init: function (multiple) {
this.$elements = [this.$element];
this.options.multiple = multiple;
return this;
},
addElement: function ($element) {
this.$elements.push($element);
return this;
},
refreshConstraints: function () {
this.constraints = [];
// Select multiple special treatment
if (this.$element.is('select')) {
this.actualizeOptions().bindConstraints();
return this;
}
for (var i = 0; i < this.$elements.length; i++)
this.constraints = this.constraints.concat(this.$elements[i].data('ParsleyFieldMultiple').refreshConstraints().constraints);
return this;
},
getValue: function () {
// Value could be overriden in DOM
if ('undefined' !== typeof this.options.value)
return this.options.value;
// Radio input case
if (this.$element.is('input[type=radio]'))
return $('[' + this.options.namespace + 'multiple="' + this.options.multiple + '"]:checked').val() || '';
// checkbox input case
if (this.$element.is('input[type=checkbox]')) {
var values = [];
$('[' + this.options.namespace + 'multiple="' + this.options.multiple + '"]:checked').each(function () {
values.push($(this).val());
});
return values.length ? values : [];
}
// Select multiple case
if (this.$element.is('select'))
return null === this.$element.val() ? [] : this.$element.val();
}
};
var o = $({}), subscribed = {};
// $.listen(name, callback);
// $.listen(name, context, callback);
$.listen = function (name) {
if ('undefined' === typeof subscribed[name])
subscribed[name] = [];
if ('function' === typeof arguments[1])
return subscribed[name].push({ fn: arguments[1] });
if ('object' === typeof arguments[1] && 'function' === typeof arguments[2])
return subscribed[name].push({ fn: arguments[2], ctxt: arguments[1] });
throw new Error('Wrong parameters');
};
$.listenTo = function (instance, name, fn) {
if ('undefined' === typeof subscribed[name])
subscribed[name] = [];
if (!(instance instanceof ParsleyField) && !(instance instanceof ParsleyForm))
throw new Error('Must give Parsley instance');
if ('string' !== typeof name || 'function' !== typeof fn)
throw new Error('Wrong parameters');
subscribed[name].push({ instance: instance, fn: fn });
};
$.unsubscribe = function (name, fn) {
if ('undefined' === typeof subscribed[name])
return;
if ('string' !== typeof name || 'function' !== typeof fn)
throw new Error('Wrong arguments');
for (var i = 0; i < subscribed[name].length; i++)
if (subscribed[name][i].fn === fn)
return subscribed[name].splice(i, 1);
};
$.unsubscribeTo = function (instance, name) {
if ('undefined' === typeof subscribed[name])
return;
if (!(instance instanceof ParsleyField) && !(instance instanceof ParsleyForm))
throw new Error('Must give Parsley instance');
for (var i = 0; i < subscribed[name].length; i++)
if ('undefined' !== typeof subscribed[name][i].instance && subscribed[name][i].instance.__id__ === instance.__id__)
return subscribed[name].splice(i, 1);
};
$.unsubscribeAll = function (name) {
if ('undefined' === typeof subscribed[name])
return;
delete subscribed[name];
};
// $.emit(name [, arguments...]);
// $.emit(name, instance [, arguments..]);
$.emit = function (name, instance) {
if ('undefined' === typeof subscribed[name])
return;
// loop through registered callbacks for this event
for (var i = 0; i < subscribed[name].length; i++) {
// if instance is not registered, simple emit
if ('undefined' === typeof subscribed[name][i].instance) {
subscribed[name][i].fn.apply('undefined' !== typeof subscribed[name][i].ctxt ? subscribed[name][i].ctxt : o, Array.prototype.slice.call(arguments, 1));
continue;
}
// if instance registered but no instance given for the emit, continue
if (!(instance instanceof ParsleyField) && !(instance instanceof ParsleyForm))
continue;
// if instance is registered and same id, emit
if (subscribed[name][i].instance.__id__ === instance.__id__) {
subscribed[name][i].fn.apply(o, Array.prototype.slice.call(arguments, 1));
continue;
}
// if registered instance is a Form and fired one is a Field, loop over all its fields and emit if field found
if (subscribed[name][i].instance instanceof ParsleyForm && instance instanceof ParsleyField)
for (var j = 0; j < subscribed[name][i].instance.fields.length; j++)
if (subscribed[name][i].instance.fields[j].__id__ === instance.__id__) {
subscribed[name][i].fn.apply(o, Array.prototype.slice.call(arguments, 1));
continue;
}
}
};
$.subscribed = function () { return subscribed; };
// ParsleyConfig definition if not already set
window.ParsleyConfig = window.ParsleyConfig || {};
window.ParsleyConfig.i18n = window.ParsleyConfig.i18n || {};
// Define then the messages
window.ParsleyConfig.i18n.en = $.extend(window.ParsleyConfig.i18n.en || {}, {
defaultMessage: "This value seems to be invalid.",
type: {
email: "This value should be a valid email.",
url: "This value should be a valid url.",
number: "This value should be a valid number.",
integer: "This value should be a valid integer.",
digits: "This value should be digits.",
alphanum: "This value should be alphanumeric."
},
notblank: "This value should not be blank.",
required: "This value is required.",
pattern: "This value seems to be invalid.",
min: "This value should be greater than or equal to %s.",
max: "This value should be lower than or equal to %s.",
range: "This value should be between %s and %s.",
minlength: "This value is too short. It should have %s characters or more.",
maxlength: "This value is too long. It should have %s characters or less.",
length: "This value length is invalid. It should be between %s and %s characters long.",
mincheck: "You must select at least %s choices.",
maxcheck: "You must select %s choices or less.",
check: "You must select between %s and %s choices.",
equalto: "This value should be the same."
});
// If file is loaded after Parsley main file, auto-load locale
if ('undefined' !== typeof window.ParsleyValidator)
window.ParsleyValidator.addCatalog('en', window.ParsleyConfig.i18n.en, true);
// Parsley.js 2.0.0-rc5
// http://parsleyjs.org
// (c) 20012-2014 Guillaume Potier, Wisembly
// Parsley may be freely distributed under the MIT license.
// ### Parsley factory
var Parsley = function (element, options, parsleyInstance) {
this.__class__ = 'Parsley';
this.__version__ = '2.0.0-rc5';
this.__id__ = ParsleyUtils.hash(4);
// Parsley must be instanciated with a DOM element or jQuery $element
if ('undefined' === typeof element)
throw new Error('You must give an element');
return this.init($(element), options, parsleyInstance);
};
Parsley.prototype = {
init: function ($element, options, parsleyInstance) {
if (!$element.length)
throw new Error('You must bind Parsley on an existing element.');
this.$element = $element;
// If element have already been binded, returns its saved Parsley instance
if (this.$element.data('Parsley')) {
var savedParsleyInstance = this.$element.data('Parsley');
// If saved instance have been binded without a ParsleyForm parent and there is one given in this call, add it
if ('undefined' !== typeof parsleyInstance && 'ParsleyField' === savedParsleyInstance.parsleyInstance.__proxy__)
savedParsleyInstance.parsleyInstance = parsleyInstance;
return savedParsleyInstance;
}
// Handle 'static' options
this.OptionsFactory = new ParsleyOptionsFactory(ParsleyDefaults, ParsleyUtils.get(window, 'ParsleyConfig') || {}, options, this.getNamespace(options));
this.options = this.OptionsFactory.get(this);
// A ParsleyForm instance is obviously a `<form>` elem but also every node that is not an input and have `data-parsley-validate` attribute
if (this.$element.is('form') || (ParsleyUtils.attr(this.$element, this.options.namespace, 'validate') && !this.$element.is(this.options.inputs)))
return this.bind('parsleyForm', parsleyInstance);
// Every other supported element and not excluded element is binded as a `ParsleyField` or `ParsleyFieldMultiple`
else if (this.$element.is(this.options.inputs) && !this.$element.is(this.options.excluded))
return this.isMultiple() ? this.handleMultiple(parsleyInstance) : this.bind('parsleyField', parsleyInstance);
return this;
},
isMultiple: function () {
return (this.$element.is('input[type=radio], input[type=checkbox]') && 'undefined' === typeof this.options.multiple) || (this.$element.is('select') && 'undefined' !== typeof this.$element.attr('multiple'));
},
// Multiples fields are a real nightmare :(
handleMultiple: function (parsleyInstance) {
var that = this,
name,
multiple,
parsleyMultipleInstance;
this.options = $.extend(this.options, ParsleyUtils.attr(this.$element, this.options.namespace));
if (this.options.multiple) {
multiple = this.options.multiple;
} else if ('undefined' !== typeof this.$element.attr('name') && this.$element.attr('name').length) {
multiple = name = this.$element.attr('name');
} else if ('undefined' !== typeof this.$element.attr('id') && this.$element.attr('id').length) {
multiple = this.$element.attr('id');
}
// Special select multiple input
if (this.$element.is('select') && 'undefined' !== typeof this.$element.attr('multiple')) {
return this.bind('parsleyFieldMultiple', parsleyInstance, multiple || this.__id__);
// Else for radio / checkboxes, we need a `name` or `data-parsley-multiple` to properly bind it
} else if ('undefined' === typeof multiple) {
if (window.console && window.console.warn)
window.console.warn('To be binded by Parsley, a radio, a checkbox and a multiple select input must have either a name or a multiple option.', this.$element);
return this;
}
// Remove special chars
multiple = multiple.replace(/(:|\.|\[|\]|\$)/g, '');
// Add proper `data-parsley-multiple` to siblings if we had a name
if ('undefined' !== typeof name)
$('input[name="' + name + '"]').each(function () {
$(this).attr(that.options.namespace + 'multiple', multiple);
});
// Check here if we don't already have a related multiple instance saved
if ($('[' + this.options.namespace + 'multiple=' + multiple +']').length)
for (var i = 0; i < $('[' + this.options.namespace + 'multiple=' + multiple +']').length; i++)
if ('undefined' !== typeof $($('[' + this.options.namespace + 'multiple=' + multiple +']').get(i)).data('Parsley')) {
parsleyMultipleInstance = $($('[' + this.options.namespace + 'multiple=' + multiple +']').get(i)).data('Parsley');
if (!this.$element.data('ParsleyFieldMultiple')) {
parsleyMultipleInstance.addElement(this.$element);
this.$element.attr(this.options.namespace + 'id', parsleyMultipleInstance.__id__);
}
break;
}
// Create a secret ParsleyField instance for every multiple field. It would be stored in `data('ParsleyFieldMultiple')`
// And would be useful later to access classic `ParsleyField` stuff while being in a `ParsleyFieldMultiple` instance
this.bind('parsleyField', parsleyInstance, multiple, true);
return parsleyMultipleInstance || this.bind('parsleyFieldMultiple', parsleyInstance, multiple);
},
// Retrieve namespace used for DOM-API
getNamespace: function (options) {
// `data-parsley-namespace=<namespace>`
if ('undefined' !== typeof this.$element.data('parsleyNamespace'))
return this.$element.data('parsleyNamespace');
if ('undefined' !== typeof ParsleyUtils.get(options, 'namespace'))
return options.namespace;
if ('undefined' !== typeof ParsleyUtils.get(window, 'ParsleyConfig.namespace'))
return window.ParsleyConfig.namespace;
return ParsleyDefaults.namespace;
},
// Return proper `ParsleyForm`, `ParsleyField` or `ParsleyFieldMultiple`
bind: function (type, parentParsleyInstance, multiple, doNotStore) {
var parsleyInstance;
switch (type) {
case 'parsleyForm':
parsleyInstance = $.extend(
new ParsleyForm(this.$element, parentParsleyInstance || this),
new ParsleyAbstract(),
window.ParsleyExtend
).init();
break;
case 'parsleyField':
parsleyInstance = $.extend(
new ParsleyField(this.$element, parentParsleyInstance || this),
new ParsleyAbstract(),
window.ParsleyExtend
).init();
break;
case 'parsleyFieldMultiple':
parsleyInstance = $.extend(
new ParsleyField(this.$element, parentParsleyInstance || this).init(),
new ParsleyAbstract(),
new ParsleyMultiple(),
window.ParsleyExtend
).init(multiple);
break;
default:
throw new Error(type + 'is not a supported Parsley type');
}
if ('undefined' !== typeof multiple)
ParsleyUtils.setAttr(this.$element, this.options.namespace, 'multiple', multiple);
if ('undefined' !== typeof doNotStore) {
this.$element.data('ParsleyFieldMultiple', parsleyInstance);
return parsleyInstance;
}
// Store instance if `ParsleyForm`, `ParsleyField` or `ParsleyFieldMultiple`
if (new RegExp('ParsleyF', 'i').test(parsleyInstance.__class__)) {
// Store for later access the freshly binded instance in DOM element itself using jQuery `data()`
this.$element.data('Parsley', parsleyInstance);
this.__proxy__ = parsleyInstance.__class__;
// Tell the world we got a new ParsleyForm or ParsleyField instance!
$.emit('parsley:' + ('parsleyForm' === type ? 'form' : 'field') + ':init', parsleyInstance);
}
return parsleyInstance;
}
};
// ### jQuery API
// `$('.elem').parsley(options)` or `$('.elem').psly(options)`
$.fn.parsley = $.fn.psly = function (options) {
if (this.length > 1) {
var instances = [];
this.each(function () {
instances.push($(this).parsley(options));
});
return instances;
}
// Return undefined if applied to non existing DOM element
if (!$(this).length) {
if (window.console && window.console.warn)
window.console.warn('You must bind Parsley on an existing element.');
return;
}
return new Parsley(this, options);
};
// ### ParsleyUI
// UI is a class apart that only listen to some events and them modify DOM accordingly
// Could be overriden by defining a `window.ParsleyConfig.ParsleyUI` appropriate class (with `listen()` method basically)
window.ParsleyUI = 'function' === typeof ParsleyUtils.get(window, 'ParsleyConfig.ParsleyUI') ?
new window.ParsleyConfig.ParsleyUI().listen() : new ParsleyUI().listen();
// ### ParsleyField and ParsleyForm extension
// Ensure that defined if not already the case
if ('undefined' === typeof window.ParsleyExtend)
window.ParsleyExtend = {};
// ### ParsleyConfig
// Ensure that defined if not already the case
if ('undefined' === typeof window.ParsleyConfig)
window.ParsleyConfig = {};
// ### Globals
window.Parsley = window.psly = Parsley;
window.ParsleyUtils = ParsleyUtils;
window.ParsleyValidator = new ParsleyValidator(window.ParsleyConfig.validators, window.ParsleyConfig.i18n);
// ### PARSLEY auto-binding
// Prevent it by setting `ParsleyConfig.autoBind` to `false`
if (false !== ParsleyUtils.get(window, 'ParsleyConfig.autoBind'))
$(document).ready(function () {
// Works only on `data-parsley-validate`.
if ($('[data-parsley-validate]').length)
$('[data-parsley-validate]').parsley();
});
})(window.jQuery);
|
var path = require('path'),
npm_crafty = require('../lib/npm_crafty.server'),
pongBasic = require('./pongBasic.game.js'),
matchmaker;
//setup default server with the following arguments
var Server = npm_crafty.setupDefault( function () { //immediate callback
//setup additional get requests
Server.app.get('/', function (req, res) {
res.sendfile(path.join(__dirname + '/pongBasic.client.html'));
});
Server.app.get('/pongBasic.game.js', function (req, res) {
res.sendfile(path.join(__dirname + '/pongBasic.game.js'));
});
//setup automatic matchmaking
matchmaker = new npm_crafty.Matchmaker( ["CLIENT1", "CLIENT2"], // available slots
function(roomName) { // function to call to create game
var Crafty = Server.createInstance(roomName);
pongBasic.startGame(Crafty);
return Crafty;
}, function(Crafty) { // function to call to destroy game
Crafty.stop();
}, function(Crafty, socket, slot, openSlots) { // function to call when player joins
Server.addClient(Crafty, socket);
if (openSlots.length === 0)
Crafty.scene("main");
}, function(Crafty, socket, slot, openSlots) { // function to call when player leaves
Server.removeClient(Crafty, socket);
if (openSlots.length > 0)
Crafty.scene("loading");
});
}, function (socket) { //connect callback
matchmaker.listen(socket);
}, function (socket) { //disconnect callback
//socket will auto leave room
});
|
/**!
* ajax - v0.0.9
* Ajax module in Vanilla JS
* https://github.com/fdaciuk/ajax
* Wed Aug 26 2015 07:30:42 GMT-0300 (BRT)
* MIT (c) Fernando Daciuk
*/
;
(function(factory) {
'use strict';
var root = (typeof window === 'object' && window.window === window && window) || (typeof global === 'object' && global.global === global && global);
/* istanbul ignore next */
if (typeof define === 'function' && define.amd) {
define('Ajax', function(){
return factory(root);
});
} else if (typeof exports === 'object') {
exports = module.exports = factory(root);
} else {
root.Ajax = factory(root);
}
})(function(r) {
'use strict';
function Ajax() {
var $public = {};
var $private = {};
var root = r;
function getParamUrl(u, p) {
var t;
if (u.indexOf(p + "=") !== -1) {
t = u.substring(u.indexOf(p + "=") + (p.length + 1));
if (t.indexOf("&") !== -1) {
t = t.substring(0, t.indexOf("&"));
}
}
return t || null;
}
$private.methods = {
done: function() {},
error: function() {},
always: function() {}
};
$public.jsonp = function jsonp(url, passedInCallback) {
var jsonPcallback = function(data) {
// remove from global scope
delete root.jsonCallback;
return passedInCallback(data);
};
// Vanilla
var jsonCallback = function(data) {
jsonPcallback(data);
}
if (/\?/gi.test(url)) {
url += "&"
} else if (/\&/gi.test(url)) {
url += "?"
}
url += "callback=jsonCallback";
// put on global scope temporaralllyyyy
root.jsonCallback = jsonCallback;
var scr = root.document.createElement('script');
scr.src = url;
root.document.body.appendChild(scr);
}
$public.get = function get(url) {
return $private.XHRConnection('GET', url, null);
};
$public.post = function post(url, data) {
return $private.XHRConnection('POST', url, data);
};
$public.put = function put(url, data) {
return $private.XHRConnection('PUT', url, data);
};
$public.delete = function del(url, data) {
return $private.XHRConnection('DELETE', url, data);
};
$private.XHRConnection = function XHRConnection(type, url, data) {
var xhr = new XMLHttpRequest();
var contentType = 'application/x-www-form-urlencoded';
xhr.open(type, url || '', true);
xhr.setRequestHeader('Content-Type', contentType);
xhr.addEventListener('readystatechange', $private.ready, false);
xhr.send($private.objectToQueryString(data));
return $private.promises();
};
$private.ready = function ready() {
var xhr = this;
var DONE = 4;
if (xhr.readyState === DONE) {
$private.methods.always.apply($private.methods, $private.parseResponse(xhr));
if (xhr.status >= 200 && xhr.status < 300) {
return $private.methods.done.apply($private.methods, $private.parseResponse(xhr));
}
$private.methods.error.apply($private.methods, $private.parseResponse(xhr));
}
};
$private.parseResponse = function parseResponse(xhr) {
var result;
try {
result = JSON.parse(xhr.responseText);
} catch (e) {
result = xhr.responseText;
}
return [result, xhr];
};
$private.promises = function promises() {
var allPromises = {};
Object.keys($private.methods).forEach(function(promise) {
allPromises[promise] = $private.generatePromise.call(this, promise);
}, this);
return allPromises;
};
$private.generatePromise = function generatePromise(method) {
return function(callback) {
return ($private.methods[method] = callback, this);
};
};
$private.objectToQueryString = function objectToQueryString(data) {
return $private.isObject(data) ? $private.getQueryString(data) : data;
};
$private.getQueryString = function getQueryString(object) {
return Object.keys(object).map(function(item) {
return encodeURIComponent(item) + '=' + encodeURIComponent(object[item]);
}).join('&');
};
$private.isObject = function isObject(data) {
return '[object Object]' === Object.prototype.toString.call(data);
};
return $public;
}
return Ajax;
});
|
import sortByProp from '../../../../utils/sortByProp'
export default (newRef, prop) => (existingRefs = [], { readField }) => {
const toObj = (ref) => ({ ref, [prop]: readField(prop, ref) })
const toRef = (obj) => obj.ref
return [ ...existingRefs, newRef ]
.map(toObj)
.sort(sortByProp(prop))
.map(toRef)
} |
// Copyright 2014 Ecma International. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: Array.prototype.splice sets `length` on `this`
es5id: 15.4.4.12_A6.1_T2
description: Array.prototype.splice throws if `length` is read-only
negative: TypeError
---*/
var a = [0, 1, 2];
Object.defineProperty(a, 'length', {
writable: false
});
a.splice(1, 2, 4);
|
'use strict';
(function () {
//var COOL_COLOURS = [0xffffff, 0x000000, 0xff1bc6, 0x7cff1b, 0xffcc1b, 0x1bc7ff];
var COOL_COLOURS = [0xffffff, 0xffffff, 0xeeeeee, 0xcccccc, 0x999999, 0x555555, 0x777777];
//var COOL_COLOURS = [0xffffff, 0x000000];
window.demoMode = true;
var view = document.getElementById('pixi-view');
var stage = new PIXI.Stage(0xFFFFFF, true);
var container = new PIXI.DisplayObjectContainer();
var width = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
// fire up pixi
var renderer = new PIXI.WebGLRenderer(width, height, view);
// our test display objects
var square = null;
var squares = [];
var steps = 0;
var i = 0;
var whiteBg = new PIXI.Graphics();
whiteBg.beginFill(0xffffff, 1);
whiteBg.drawRect(0, 0, width * 0.5, height);
container.addChild(whiteBg);
var blackBg = new PIXI.Graphics();
blackBg.beginFill(0, 1);
blackBg.drawRect(0, 0, width * 0.5, height);
blackBg.x = width * 0.5;
container.addChild(blackBg);
// create them - a bunch of squares all random
for (i = 0; i < 500; i++) {
var sideLength = (Math.exp(Math.random()) - 1) * 100;
square = new PIXI.Graphics();
square.beginFill(COOL_COLOURS[Math.floor(Math.random() * COOL_COLOURS.length)]);
square.drawRect(sideLength * -0.5, sideLength * -0.5, sideLength, sideLength);
square.position.x = (Math.random() * width * 3) - width;
square.position.y = (Math.random() * height * 3) - height;
square.rotation = Math.random() * Math.PI * 2;
squares.push({
square: square,
sideLength: sideLength,
counter: Math.random() * 1000 - 500
});
container.addChild(square);
}
stage.addChild(container);
var filters = [
// color filters
{
name: 'RedInvert',
filter: new PIXI_GLITCH.RedInvertFilter(),
isActive: false,
demoModeOdds: 0.99
},
{
name: 'RedRaise',
filter: new PIXI_GLITCH.RedRaiseFilter(),
isActive: false,
demoModeOdds: 0.9
},
{
name: 'GreenInvert',
filter: new PIXI_GLITCH.GreenInvertFilter(),
isActive: false,
demoModeOdds: 0.99
},
{
name: 'GreenRaise',
filter: new PIXI_GLITCH.GreenRaiseFilter(),
isActive: false,
demoModeOdds: 0.9
},
{
name: 'BlueInvert',
filter: new PIXI_GLITCH.BlueInvertFilter(),
isActive: false,
demoModeOdds: 0.99
},
{
name: 'BlueRaise',
filter: new PIXI_GLITCH.BlueRaiseFilter(),
isActive: false,
demoModeOdds: 0.85
},
{
name: 'Invert',
filter: new PIXI_GLITCH.InvertFilter(),
isActive: false,
demoModeOdds: 0.95
},
// distorty filters
{
name: 'Convergence',
filter: new PIXI_GLITCH.ConvergenceFilter(),
values: [{name: 'rand', min: 0, max: 5}],
isActive: false,
demoModeOdds: 0.5
},
{
name: 'CutSlider',
filter: new PIXI_GLITCH.CutSliderFilter(),
values: [{name: 'rand', min: 0, max: 20}, {name: 'val1', min: 0, max: 700}, {name: 'val2', min: 0, max: 100} ],
isActive: false,
demoModeOdds: 0.6
},
{
name: 'Glow',
filter: new PIXI_GLITCH.GlowFilter(),
values: [{name: 'blur', min: 1, max: 8}],
isActive: false,
demoModeOdds: 0.9
},
{
name: 'Outline',
filter: new PIXI_GLITCH.OutlineFilter(),
isActive: false,
demoModeOdds: 0.98
},
{
name: 'Shaker',
filter: new PIXI_GLITCH.ShakerFilter(),
values: [{name: 'blurX', min: 0, max: 20}, {name: 'blurY', min: 0, max: 20}],
isActive: false,
demoModeOdds: 1
},
{
name: 'SlitScan',
filter: new PIXI_GLITCH.SlitScanFilter(),
values: [{name: 'rand', min: -100, max: 100}],
isActive: false,
demoModeOdds: 0.9
},
{
name: 'Swell',
filter: new PIXI_GLITCH.SwellFilter(),
values: [{name: 'rand', min: -100, max: 100}, {name: 'timer', min: 0, max: 10000}],
isActive: false,
demoModeOdds: 0.9
},
{
name: 'Twist',
filter: new PIXI_GLITCH.TwistFilter(),
values: [{name: 'rand', min: 0, max: 10}, {name: 'timer', min: 0, max: 500}, {name: 'val2', min: 0, max: 100}, {name: 'val3', min: 0, max: 1000}],
isActive: false,
demoModeOdds: 0.9
},
{
name: 'Noise',
filter: new PIXI_GLITCH.NoiseFilter(),
useAutoRand: true,
values: [{name: 'strength', min: 0, max: 0.5}],
isActive: false,
demoModeOdds: 0.5
}
];
// create a bit of interface
var gui = new dat.GUI();
gui.add(window, 'demoMode').onChange(onDemoModeChange);
for (i = 0; i < filters.length; i++) {
var item = filters[i];
var folder = gui.addFolder(item.name);
folder.add(item, 'isActive').listen().onChange(onIsActiveChange);
if (item.values) {
for (var j = 0; j < item.values.length; j++) {
var valueItem = item.values[j];
folder.add(item.filter, valueItem.name, valueItem.min, valueItem.max).listen();
}
}
}
function onIsActiveChange() {
var activeFilters = [];
for (var i = 0; i < filters.length; i++) {
var item = filters[i];
if (item.isActive) {
activeFilters.push(item.filter);
}
}
container.filters = activeFilters.length ? activeFilters : null;
}
function onDemoModeChange(value) {
if (!value) {
for (i = 0; i < filters.length; i++) {
var item = filters[i];
item.isActive = false;
}
onIsActiveChange();
}
}
function randomBetween(lower, upper, round) {
var range = upper - lower;
var rnd = Math.random() * range;
var result = lower + rnd;
if (round) {
result = Math.round(result);
}
return result;
}
// animate
function step() {
var square = null;
var sideLength = null;
var counter = null;
var item = null;
// move our squares around the screen all trippy and floaty and trigonometry
for (i = 0; i < squares.length; i++) {
square = squares[i].square;
sideLength = squares[i].sideLength;
counter = squares[i].counter++;
square.position.x += Math.sin(counter * 0.002) * sideLength * 0.015;
square.position.y += Math.sin(counter * 0.002) * sideLength * 0.015;
square.rotation += Math.sin(counter * 0.01) * 0.01;
}
// values that the filters might require updating on each step
for (i = 0; i < filters.length; i++) {
item = filters[i];
if (item.useAutoRand) {
item.filter.rand = Math.random();
}
}
// a very clumsy demo mode
if (window.demoMode) {
if (Math.random() > 0.95) {
for (i = 0; i < filters.length; i++) {
item = filters[i];
item.isActive = Math.random() > item.demoModeOdds;
}
onIsActiveChange();
}
for (i = 0; i < filters.length; i++) {
item = filters[i];
if (item.isActive && item.values) {
for (var j = 0; j < item.values.length; j++) {
var value = item.values[j];
if (Math.random() > 0.9) {
item.filter[value.name] = randomBetween(value.min, value.max);
}
}
}
}
}
renderer.render(stage);
steps ++;
window.requestAnimationFrame(step);
}
step();
}());
|
/**
* @author chenx
* @date 2015.12.17
* copyright 2015 Qcplay All Rights Reserved.
*
* 测试 websocket 指令
*/
function main(socket, para1, para2, para3)
{
trace('TestSocket main para1:%j, para2:%j, para3:%j', para1, para2, para3);
socket.emit('MSG_TEST_SOCKET', para1, para2, para3);
}
COMMUNICATE_D.registerSocketCmd('TEST_GS_SOCKET', main);
|
/* ----------------------------------
* PUSH v2.0.1
* Licensed under The MIT License
* inspired by chris's jquery.pjax.js
* http://opensource.org/licenses/MIT
* ---------------------------------- */
/* global _gaq: true */
!(function () {
'use strict';
var noop = function () {};
// Pushstate cacheing
// ==================
var isScrolling;
var maxCacheLength = 20;
var cacheMapping = sessionStorage;
var domCache = {};
var transitionMap = {
'slide-in' : 'slide-out',
'slide-out' : 'slide-in',
'fade' : 'fade'
};
var bars = {
bartab : '.bar-tab',
barnav : '.bar-nav',
barfooter : '.bar-footer',
barheadersecondary : '.bar-header-secondary'
};
var cacheReplace = function (data, updates) {
PUSH.id = data.id;
if (updates) {
data = getCached(data.id);
}
cacheMapping[data.id] = JSON.stringify(data);
window.history.replaceState(data.id, data.title, data.url);
domCache[data.id] = document.body.cloneNode(true);
};
var cachePush = function () {
var id = PUSH.id;
var cacheForwardStack = JSON.parse(cacheMapping.cacheForwardStack || '[]');
var cacheBackStack = JSON.parse(cacheMapping.cacheBackStack || '[]');
cacheBackStack.push(id);
while (cacheForwardStack.length) {
delete cacheMapping[cacheForwardStack.shift()];
}
while (cacheBackStack.length > maxCacheLength) {
delete cacheMapping[cacheBackStack.shift()];
}
window.history.pushState(null, '', cacheMapping[PUSH.id].url);
cacheMapping.cacheForwardStack = JSON.stringify(cacheForwardStack);
cacheMapping.cacheBackStack = JSON.stringify(cacheBackStack);
};
var cachePop = function (id, direction) {
var forward = direction === 'forward';
var cacheForwardStack = JSON.parse(cacheMapping.cacheForwardStack || '[]');
var cacheBackStack = JSON.parse(cacheMapping.cacheBackStack || '[]');
var pushStack = forward ? cacheBackStack : cacheForwardStack;
var popStack = forward ? cacheForwardStack : cacheBackStack;
if (PUSH.id) {
pushStack.push(PUSH.id);
}
popStack.pop();
cacheMapping.cacheForwardStack = JSON.stringify(cacheForwardStack);
cacheMapping.cacheBackStack = JSON.stringify(cacheBackStack);
};
var getCached = function (id) {
return JSON.parse(cacheMapping[id] || null) || {};
};
var getTarget = function (e) {
var target = findTarget(e.target);
if (!target ||
e.which > 1 ||
e.metaKey ||
e.ctrlKey ||
isScrolling ||
location.protocol !== target.protocol ||
location.host !== target.host ||
!target.hash && /#/.test(target.href) ||
target.hash && target.href.replace(target.hash, '') === location.href.replace(location.hash, '') ||
target.getAttribute('data-ignore') === 'push') { return; }
return target;
};
// Main event handlers (touchend, popstate)
// ==========================================
var touchend = function (e) {
var target = getTarget(e);
if (!target) {
return;
}
e.preventDefault();
PUSH({
url : target.href,
hash : target.hash,
timeout : target.getAttribute('data-timeout'),
transition : target.getAttribute('data-transition')
});
};
var popstate = function (e) {
var key;
var barElement;
var activeObj;
var activeDom;
var direction;
var transition;
var transitionFrom;
var transitionFromObj;
var id = e.state;
if (!id || !cacheMapping[id]) {
return;
}
direction = PUSH.id < id ? 'forward' : 'back';
cachePop(id, direction);
activeObj = getCached(id);
activeDom = domCache[id];
if (activeObj.title) {
document.title = activeObj.title;
}
if (direction === 'back') {
transitionFrom = JSON.parse(direction === 'back' ? cacheMapping.cacheForwardStack : cacheMapping.cacheBackStack);
transitionFromObj = getCached(transitionFrom[transitionFrom.length - 1]);
} else {
transitionFromObj = activeObj;
}
if (direction === 'back' && !transitionFromObj.id) {
return (PUSH.id = id);
}
transition = direction === 'back' ? transitionMap[transitionFromObj.transition] : transitionFromObj.transition;
if (!activeDom) {
return PUSH({
id : activeObj.id,
url : activeObj.url,
title : activeObj.title,
timeout : activeObj.timeout,
transition : transition,
ignorePush : true
});
}
if (transitionFromObj.transition) {
activeObj = extendWithDom(activeObj, '.content', activeDom.cloneNode(true));
for (key in bars) {
if (bars.hasOwnProperty(key)) {
barElement = document.querySelector(bars[key]);
if (activeObj[key]) {
swapContent(activeObj[key], barElement);
} else if (barElement) {
barElement.parentNode.removeChild(barElement);
}
}
}
}
swapContent(
(activeObj.contents || activeDom).cloneNode(true),
document.querySelector('.content'),
transition
);
PUSH.id = id;
document.body.offsetHeight; // force reflow to prevent scroll
};
// Core PUSH functionality
// =======================
var PUSH = function (options) {
var key;
var xhr = PUSH.xhr;
options.container = options.container || options.transition ? document.querySelector('.content') : document.body;
for (key in bars) {
if (bars.hasOwnProperty(key)) {
options[key] = options[key] || document.querySelector(bars[key]);
}
}
if (xhr && xhr.readyState < 4) {
xhr.onreadystatechange = noop;
xhr.abort();
}
xhr = new XMLHttpRequest();
xhr.open('GET', options.url, true);
xhr.setRequestHeader('X-PUSH', 'true');
xhr.onreadystatechange = function () {
if (options._timeout) {
clearTimeout(options._timeout);
}
if (xhr.readyState === 4) {
xhr.status === 200 ? success(xhr, options) : failure(options.url);
}
};
if (!PUSH.id) {
cacheReplace({
id : +new Date(),
url : window.location.href,
title : document.title,
timeout : options.timeout,
transition : null
});
}
if (options.timeout) {
options._timeout = setTimeout(function () { xhr.abort('timeout'); }, options.timeout);
}
xhr.send();
if (xhr.readyState && !options.ignorePush) {
cachePush();
}
};
// Main XHR handlers
// =================
var success = function (xhr, options) {
var key;
var barElement;
var data = parseXHR(xhr, options);
if (!data.contents) {
return locationReplace(options.url);
}
if (data.title) {
document.title = data.title;
}
if (options.transition) {
for (key in bars) {
if (bars.hasOwnProperty(key)) {
barElement = document.querySelector(bars[key]);
if (data[key]) {
swapContent(data[key], barElement);
} else if (barElement) {
barElement.parentNode.removeChild(barElement);
}
}
}
}
swapContent(data.contents, options.container, options.transition, function () {
cacheReplace({
id : options.id || +new Date(),
url : data.url,
title : data.title,
timeout : options.timeout,
transition : options.transition
}, options.id);
triggerStateChange();
});
if (!options.ignorePush && window._gaq) {
_gaq.push(['_trackPageview']); // google analytics
}
if (!options.hash) {
return;
}
};
var failure = function (url) {
throw new Error('Could not get: ' + url);
};
// PUSH helpers
// ============
var swapContent = function (swap, container, transition, complete) {
var enter;
var containerDirection;
var swapDirection;
if (!transition) {
if (container) {
container.innerHTML = swap.innerHTML;
} else if (swap.classList.contains('content')) {
document.body.appendChild(swap);
} else {
document.body.insertBefore(swap, document.querySelector('.content'));
}
} else {
enter = /in$/.test(transition);
if (transition === 'fade') {
container.classList.add('in');
container.classList.add('fade');
swap.classList.add('fade');
}
if (/slide/.test(transition)) {
swap.classList.add('sliding-in', enter ? 'right' : 'left');
swap.classList.add('sliding');
container.classList.add('sliding');
}
container.parentNode.insertBefore(swap, container);
}
if (!transition) {
complete && complete();
}
if (transition === 'fade') {
container.offsetWidth; // force reflow
container.classList.remove('in');
var fadeContainerEnd = function () {
container.removeEventListener('webkitTransitionEnd', fadeContainerEnd);
swap.classList.add('in');
swap.addEventListener('webkitTransitionEnd', fadeSwapEnd);
};
var fadeSwapEnd = function () {
swap.removeEventListener('webkitTransitionEnd', fadeSwapEnd);
container.parentNode.removeChild(container);
swap.classList.remove('fade');
swap.classList.remove('in');
complete && complete();
};
container.addEventListener('webkitTransitionEnd', fadeContainerEnd);
}
if (/slide/.test(transition)) {
var slideEnd = function () {
swap.removeEventListener('webkitTransitionEnd', slideEnd);
swap.classList.remove('sliding', 'sliding-in');
swap.classList.remove(swapDirection);
container.parentNode.removeChild(container);
complete && complete();
};
container.offsetWidth; // force reflow
swapDirection = enter ? 'right' : 'left';
containerDirection = enter ? 'left' : 'right';
container.classList.add(containerDirection);
swap.classList.remove(swapDirection);
swap.addEventListener('webkitTransitionEnd', slideEnd);
}
};
var triggerStateChange = function () {
var e = new CustomEvent('push', {
detail: { state: getCached(PUSH.id) },
bubbles: true,
cancelable: true
});
window.dispatchEvent(e);
};
var findTarget = function (target) {
var i;
var toggles = document.querySelectorAll('a');
for (; target && target !== document; target = target.parentNode) {
for (i = toggles.length; i--;) {
if (toggles[i] === target) {
return target;
}
}
}
};
var locationReplace = function (url) {
window.history.replaceState(null, '', '#');
window.location.replace(url);
};
var extendWithDom = function (obj, fragment, dom) {
var i;
var result = {};
for (i in obj) {
if (obj.hasOwnProperty(i)) {
result[i] = obj[i];
}
}
Object.keys(bars).forEach(function (key) {
var el = dom.querySelector(bars[key]);
if (el) {
el.parentNode.removeChild(el);
}
result[key] = el;
});
result.contents = dom.querySelector(fragment);
return result;
};
var parseXHR = function (xhr, options) {
var head;
var body;
var data = {};
var responseText = xhr.responseText;
data.url = options.url;
if (!responseText) {
return data;
}
if (/<html/i.test(responseText)) {
head = document.createElement('div');
body = document.createElement('div');
head.innerHTML = responseText.match(/<head[^>]*>([\s\S.]*)<\/head>/i)[0];
body.innerHTML = responseText.match(/<body[^>]*>([\s\S.]*)<\/body>/i)[0];
} else {
head = body = document.createElement('div');
head.innerHTML = responseText;
}
data.title = head.querySelector('title');
data.title = data.title && data.title.innerText.trim();
if (options.transition) {
data = extendWithDom(data, '.content', body);
} else {
data.contents = body;
}
return data;
};
// Attach PUSH event handlers
// ==========================
window.addEventListener('touchstart', function () { isScrolling = false; });
window.addEventListener('touchmove', function () { isScrolling = true; });
window.addEventListener('touchend', touchend);
window.addEventListener('click', function (e) { if (getTarget(e)) {e.preventDefault();} });
window.addEventListener('popstate', popstate);
window.PUSH = PUSH;
}());
|
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Contains the NIX (Native IE XDC) method transport for
* cross-domain communication. It exploits the fact that Internet Explorer
* allows a window that is the parent of an iframe to set said iframe window's
* opener property to an object. This object can be a function that in turn
* can be used to send a message despite same-origin constraints. Note that
* this function, if a pure JavaScript object, opens up the possibilitiy of
* gaining a hold of the context of the other window and in turn, attacking
* it. This implementation therefore wraps the JavaScript objects used inside
* a VBScript class. Since VBScript objects are passed in JavaScript as a COM
* wrapper (like DOM objects), they are thus opaque to JavaScript
* (except for the interface they expose). This therefore provides a safe
* method of transport.
*
*
* Initially based on FrameElementTransport which shares some similarities
* to this method.
*/
goog.provide('goog.net.xpc.NixTransport');
goog.require('goog.log');
goog.require('goog.net.xpc');
goog.require('goog.net.xpc.CfgFields');
goog.require('goog.net.xpc.CrossPageChannelRole');
goog.require('goog.net.xpc.Transport');
goog.require('goog.net.xpc.TransportTypes');
goog.require('goog.reflect');
/**
* NIX method transport.
*
* NOTE(user): NIX method tested in all IE versions starting from 6.0.
*
* @param {goog.net.xpc.CrossPageChannel} channel The channel this transport
* belongs to.
* @param {goog.dom.DomHelper=} opt_domHelper The dom helper to use for finding
* the correct window.
* @constructor
* @extends {goog.net.xpc.Transport}
* @final
*/
goog.net.xpc.NixTransport = function(channel, opt_domHelper) {
goog.base(this, opt_domHelper);
/**
* The channel this transport belongs to.
* @type {goog.net.xpc.CrossPageChannel}
* @private
*/
this.channel_ = channel;
/**
* The authorization token, if any, used by this transport.
* @type {?string}
* @private
*/
this.authToken_ = channel[goog.net.xpc.CfgFields.AUTH_TOKEN] || '';
/**
* The authorization token, if any, that must be sent by the other party
* for setup to occur.
* @type {?string}
* @private
*/
this.remoteAuthToken_ =
channel[goog.net.xpc.CfgFields.REMOTE_AUTH_TOKEN] || '';
// Conduct the setup work for NIX in general, if need be.
goog.net.xpc.NixTransport.conductGlobalSetup_(this.getWindow());
// Setup aliases so that VBScript can call these methods
// on the transport class, even if they are renamed during
// compression.
this[goog.net.xpc.NixTransport.NIX_HANDLE_MESSAGE] = this.handleMessage_;
this[goog.net.xpc.NixTransport.NIX_CREATE_CHANNEL] = this.createChannel_;
};
goog.inherits(goog.net.xpc.NixTransport, goog.net.xpc.Transport);
// Consts for NIX. VBScript doesn't allow items to start with _ for some
// reason, so we need to make these names quite unique, as they will go into
// the global namespace.
/**
* Global name of the Wrapper VBScript class.
* Note that this class will be stored in the *global*
* namespace (i.e. window in browsers).
* @type {string}
*/
goog.net.xpc.NixTransport.NIX_WRAPPER = 'GCXPC____NIXVBS_wrapper';
/**
* Global name of the GetWrapper VBScript function. This
* constant is used by JavaScript to call this function.
* Note that this function will be stored in the *global*
* namespace (i.e. window in browsers).
* @type {string}
*/
goog.net.xpc.NixTransport.NIX_GET_WRAPPER = 'GCXPC____NIXVBS_get_wrapper';
/**
* The name of the handle message method used by the wrapper class
* when calling the transport.
* @type {string}
*/
goog.net.xpc.NixTransport.NIX_HANDLE_MESSAGE = 'GCXPC____NIXJS_handle_message';
/**
* The name of the create channel method used by the wrapper class
* when calling the transport.
* @type {string}
*/
goog.net.xpc.NixTransport.NIX_CREATE_CHANNEL = 'GCXPC____NIXJS_create_channel';
/**
* A "unique" identifier that is stored in the wrapper
* class so that the wrapper can be distinguished from
* other objects easily.
* @type {string}
*/
goog.net.xpc.NixTransport.NIX_ID_FIELD = 'GCXPC____NIXVBS_container';
/**
* Determines if the installed version of IE supports accessing window.opener
* after it has been set to a non-Window/null value. NIX relies on this being
* possible.
* @return {boolean} Whether window.opener behavior is compatible with NIX.
*/
goog.net.xpc.NixTransport.isNixSupported = function() {
var isSupported = false;
try {
var oldOpener = window.opener;
// The compiler complains (as it should!) if we set window.opener to
// something other than a window or null.
window.opener = /** @type {Window} */ ({});
isSupported = goog.reflect.canAccessProperty(window, 'opener');
window.opener = oldOpener;
} catch (e) { }
return isSupported;
};
/**
* Conducts the global setup work for the NIX transport method.
* This function creates and then injects into the page the
* VBScript code necessary to create the NIX wrapper class.
* Note that this method can be called multiple times, as
* it internally checks whether the work is necessary before
* proceeding.
* @param {Window} listenWindow The window containing the affected page.
* @private
*/
goog.net.xpc.NixTransport.conductGlobalSetup_ = function(listenWindow) {
if (listenWindow['nix_setup_complete']) {
return;
}
// Inject the VBScript code needed.
var vbscript =
// We create a class to act as a wrapper for
// a Javascript call, to prevent a break in of
// the context.
'Class ' + goog.net.xpc.NixTransport.NIX_WRAPPER + '\n ' +
// An internal member for keeping track of the
// transport for which this wrapper exists.
'Private m_Transport\n' +
// An internal member for keeping track of the
// auth token associated with the context that
// created this wrapper. Used for validation
// purposes.
'Private m_Auth\n' +
// Method for internally setting the value
// of the m_Transport property. We have the
// isEmpty check to prevent the transport
// from being overridden with an illicit
// object by a malicious party.
'Public Sub SetTransport(transport)\n' +
'If isEmpty(m_Transport) Then\n' +
'Set m_Transport = transport\n' +
'End If\n' +
'End Sub\n' +
// Method for internally setting the value
// of the m_Auth property. We have the
// isEmpty check to prevent the transport
// from being overridden with an illicit
// object by a malicious party.
'Public Sub SetAuth(auth)\n' +
'If isEmpty(m_Auth) Then\n' +
'm_Auth = auth\n' +
'End If\n' +
'End Sub\n' +
// Returns the auth token to the gadget, so it can
// confirm a match before initiating the connection
'Public Function GetAuthToken()\n ' +
'GetAuthToken = m_Auth\n' +
'End Function\n' +
// A wrapper method which causes a
// message to be sent to the other context.
'Public Sub SendMessage(service, payload)\n ' +
'Call m_Transport.' +
goog.net.xpc.NixTransport.NIX_HANDLE_MESSAGE + '(service, payload)\n' +
'End Sub\n' +
// Method for setting up the inner->outer
// channel.
'Public Sub CreateChannel(channel)\n ' +
'Call m_Transport.' +
goog.net.xpc.NixTransport.NIX_CREATE_CHANNEL + '(channel)\n' +
'End Sub\n' +
// An empty field with a unique identifier to
// prevent the code from confusing this wrapper
// with a run-of-the-mill value found in window.opener.
'Public Sub ' + goog.net.xpc.NixTransport.NIX_ID_FIELD + '()\n ' +
'End Sub\n' +
'End Class\n ' +
// Function to get a reference to the wrapper.
'Function ' +
goog.net.xpc.NixTransport.NIX_GET_WRAPPER + '(transport, auth)\n' +
'Dim wrap\n' +
'Set wrap = New ' + goog.net.xpc.NixTransport.NIX_WRAPPER + '\n' +
'wrap.SetTransport transport\n' +
'wrap.SetAuth auth\n' +
'Set ' + goog.net.xpc.NixTransport.NIX_GET_WRAPPER + ' = wrap\n' +
'End Function';
try {
listenWindow.execScript(vbscript, 'vbscript');
listenWindow['nix_setup_complete'] = true;
}
catch (e) {
goog.log.error(goog.net.xpc.logger,
'exception caught while attempting global setup: ' + e);
}
};
/**
* The transport type.
* @type {number}
* @protected
* @override
*/
goog.net.xpc.NixTransport.prototype.transportType =
goog.net.xpc.TransportTypes.NIX;
/**
* Keeps track of whether the local setup has completed (i.e.
* the initial work towards setting the channel up has been
* completed for this end).
* @type {boolean}
* @private
*/
goog.net.xpc.NixTransport.prototype.localSetupCompleted_ = false;
/**
* The NIX channel used to talk to the other page. This
* object is in fact a reference to a VBScript class
* (see above) and as such, is in fact a COM wrapper.
* When using this object, make sure to not access methods
* without calling them, otherwise a COM error will be thrown.
* @type {Object}
* @private
*/
goog.net.xpc.NixTransport.prototype.nixChannel_ = null;
/**
* Connect this transport.
* @override
*/
goog.net.xpc.NixTransport.prototype.connect = function() {
if (this.channel_.getRole() == goog.net.xpc.CrossPageChannelRole.OUTER) {
this.attemptOuterSetup_();
} else {
this.attemptInnerSetup_();
}
};
/**
* Attempts to setup the channel from the perspective
* of the outer (read: container) page. This method
* will attempt to create a NIX wrapper for this transport
* and place it into the "opener" property of the inner
* page's window object. If it fails, it will continue
* to loop until it does so.
*
* @private
*/
goog.net.xpc.NixTransport.prototype.attemptOuterSetup_ = function() {
if (this.localSetupCompleted_) {
return;
}
// Get shortcut to iframe-element that contains the inner
// page.
var innerFrame = this.channel_.getIframeElement();
try {
// Attempt to place the NIX wrapper object into the inner
// frame's opener property.
var theWindow = this.getWindow();
var getWrapper = theWindow[goog.net.xpc.NixTransport.NIX_GET_WRAPPER];
innerFrame.contentWindow.opener = getWrapper(this, this.authToken_);
this.localSetupCompleted_ = true;
}
catch (e) {
goog.log.error(goog.net.xpc.logger,
'exception caught while attempting setup: ' + e);
}
// If the retry is necessary, reattempt this setup.
if (!this.localSetupCompleted_) {
this.getWindow().setTimeout(goog.bind(this.attemptOuterSetup_, this), 100);
}
};
/**
* Attempts to setup the channel from the perspective
* of the inner (read: iframe) page. This method
* will attempt to *read* the opener object from the
* page's opener property. If it succeeds, this object
* is saved into nixChannel_ and the channel is confirmed
* with the container by calling CreateChannel with an instance
* of a wrapper for *this* page. Note that if this method
* fails, it will continue to loop until it succeeds.
*
* @private
*/
goog.net.xpc.NixTransport.prototype.attemptInnerSetup_ = function() {
if (this.localSetupCompleted_) {
return;
}
try {
var opener = this.getWindow().opener;
// Ensure that the object contained inside the opener
// property is in fact a NIX wrapper.
if (opener && goog.net.xpc.NixTransport.NIX_ID_FIELD in opener) {
this.nixChannel_ = opener;
// Ensure that the NIX channel given to use is valid.
var remoteAuthToken = this.nixChannel_['GetAuthToken']();
if (remoteAuthToken != this.remoteAuthToken_) {
goog.log.error(goog.net.xpc.logger,
'Invalid auth token from other party');
return;
}
// Complete the construction of the channel by sending our own
// wrapper to the container via the channel they gave us.
var theWindow = this.getWindow();
var getWrapper = theWindow[goog.net.xpc.NixTransport.NIX_GET_WRAPPER];
this.nixChannel_['CreateChannel'](getWrapper(this, this.authToken_));
this.localSetupCompleted_ = true;
// Notify channel that the transport is ready.
this.channel_.notifyConnected();
}
}
catch (e) {
goog.log.error(goog.net.xpc.logger,
'exception caught while attempting setup: ' + e);
return;
}
// If the retry is necessary, reattempt this setup.
if (!this.localSetupCompleted_) {
this.getWindow().setTimeout(goog.bind(this.attemptInnerSetup_, this), 100);
}
};
/**
* Internal method called by the inner page, via the
* NIX wrapper, to complete the setup of the channel.
*
* @param {Object} channel The NIX wrapper of the
* inner page.
* @private
*/
goog.net.xpc.NixTransport.prototype.createChannel_ = function(channel) {
// Verify that the channel is in fact a NIX wrapper.
if (typeof channel != 'unknown' ||
!(goog.net.xpc.NixTransport.NIX_ID_FIELD in channel)) {
goog.log.error(goog.net.xpc.logger,
'Invalid NIX channel given to createChannel_');
}
this.nixChannel_ = channel;
// Ensure that the NIX channel given to use is valid.
var remoteAuthToken = this.nixChannel_['GetAuthToken']();
if (remoteAuthToken != this.remoteAuthToken_) {
goog.log.error(goog.net.xpc.logger, 'Invalid auth token from other party');
return;
}
// Indicate to the CrossPageChannel that the channel is setup
// and ready to use.
this.channel_.notifyConnected();
};
/**
* Internal method called by the other page, via the NIX wrapper,
* to deliver a message.
* @param {string} serviceName The name of the service the message is to be
* delivered to.
* @param {string} payload The message to process.
* @private
*/
goog.net.xpc.NixTransport.prototype.handleMessage_ =
function(serviceName, payload) {
/** @this {goog.net.xpc.NixTransport} */
var deliveryHandler = function() {
this.channel_.xpcDeliver(serviceName, payload);
};
this.getWindow().setTimeout(goog.bind(deliveryHandler, this), 1);
};
/**
* Sends a message.
* @param {string} service The name of the service the message is to be
* delivered to.
* @param {string} payload The message content.
* @override
*/
goog.net.xpc.NixTransport.prototype.send = function(service, payload) {
// Verify that the NIX channel we have is valid.
if (typeof(this.nixChannel_) !== 'unknown') {
goog.log.error(goog.net.xpc.logger, 'NIX channel not connected');
}
// Send the message via the NIX wrapper object.
this.nixChannel_['SendMessage'](service, payload);
};
/** @override */
goog.net.xpc.NixTransport.prototype.disposeInternal = function() {
goog.base(this, 'disposeInternal');
this.nixChannel_ = null;
};
|
/**
* HTTP Server Tests
*/
define([ "mocks/http" ], function(http_mock) {
"use strict";
suite("HTTP Server", function() {
var server;
suiteSetup(function(done) {
injector.mock("http", http_mock);
injector.require(["lib/http-server"], function(http_server) {
server = http_server;
done();
});
});
test("should exist", function() {
expect(server).to.be.an("object");
});
suite("get server instance", function() {
test("should exist", function() {
expect(server.instance).to.be.a("function");
});
test("should return created server", function() {
var created_server = server.instance();
expect(created_server).to.be.an.instanceOf(http_mock._Server_mock);
});
});
suite("start server", function() {
setup(function() {
env.created_server = server.instance();
});
test("should exist", function() {
expect(server.start).to.be.a("function");
});
test("should start the server listening on the correct port", function() {
server.start();
expect(env.created_server.listen).to.have.been.calledOnce;
expect(env.created_server.listen).to.have.been.calledWith(8080);
});
});
});
});
|
var Appl = {};
var blnTest = true;
var HEADER_HEIGHT = 48;
var FOOTER_HEIGHT = 26;
var RTCPeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection || window.RTCPeerConnection;
var RTCSessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription;
var RTCIceCandidate = window.RTCIceCandidate;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
window.brURL = window.webkitURL || window.URL;
window.MediaStream = window.MediaStream || window.webkitMediaStream;
var isFirefox = !!navigator.mozGetUserMedia;
var isChrome = !!navigator.webkitGetUserMedia;
var audioConstraints = {
'optional': [],
'mandatory': {
'OfferToReceiveAudio': true,
'OfferToReceiveVideo': false
}
};
var videoConstraints = {
'optional': [],
'mandatory': {
'OfferToReceiveAudio': true,
'OfferToReceiveVideo': true
}
};
if (isChrome) {
audioConstraints.optional = [{
DtlsSrtpKeyAgreement: true
}];
};
var iceServers = [];
if (isFirefox) {
iceServers = [{
url: 'stun:23.21.150.121'
},{
url: 'stun:stun.services.mozilla.com'
}];
}
if (isChrome) {
iceServers = [{
url: 'stun:stun.l.google.com:19302'
},{
url: 'stun:stun.anyfirewall.com:3478'
},{
url: 'turn:turn.bistri.com:80',
credential: 'homeo',
username: 'homeo'
},{
url: 'turn:turn.anyfirewall.com:443?transport=tcp',
credential: 'webrtc',
username: 'webrtc'
}];
};
iceServers = {
iceServers: iceServers
};
var Prerial = {};
Prerial.Templates = {};
Prerial.Templates.ComCenterContent = 'client/partials/comcenter_content.html';
Prerial.Config = {};
Prerial.Config.Constrains = {};
Prerial.Config.Constrains.UserMedia = {
video: {audio: true, video: true},
audio: {audio: true, video: false}
};
Prerial.Config.Constrains.MediaConstraints = {
video: {
'optional': [],
'mandatory': {
'OfferToReceiveAudio': true,
'OfferToReceiveVideo': true
}
},
audio: {
'optional': [],
'mandatory': {
'OfferToReceiveAudio': true,
'OfferToReceiveVideo': false
}
}
};
var audioConstraints = {
};
var videoConstraints = {
};
Prerial.Config.Dialogs = {}
Prerial.Config.Dialogs.DeleteContact = '<li action="delete">Delete Contact</li><li action="cancel">Cancel</li>';
Prerial.Config.Dialogs.EditContacts = '<li action="add">Add Contact</li><li action="info">Contacts Info</li><li action="edit">Delete Contacts</li><li action="cancel">Cancel</li>';
Prerial.Config.Dialogs.EditGroupContacts = '<li action="addgroup">Add Group</li><li action="add">Add Contact</li><li action="info">Contacts Info</li><li action="edit">Delete Contacts</li><li action="cancel">Cancel</li>';
Prerial.Config.Dialogs.Edit = '<li action="edit"><form><textarea cols="25" rows="13" placeholder="let me grow and close the popup" id="editDialog1" name="editDialog"></textarea></form></li>';
Prerial.Config.Dialogs.Invite = null;
Prerial.Config.LoginData = [
{user: "1", name:"John Doe",value:"john.doe@citi.com"},
{user: "2", name:"Jane Doe",value:"jane.doe@citi.com"}
/* ,
{user: "3", name:"Jack Doe",value:"jack.doe@citi.com"},
{user: "4", name:"Norman Spinrad",value:"norman.spinrad@citi.com"},
{user: "5", name:"Alice Snyder",value:"alice.snyder@citi.com"},
{user: "6", name:"Charles Snyder",value:"charles.snyder@citi.com"},
{user: "7", name:"Jane Smith",value:"jane.smith@citi.com"}
*/
];
Prerial.Config.InitContactData = {
"chid": "000",
"cnport": "cn000",
"vrport": "vr000",
"title": "John Doe",
"profile": {
"firstname": "John",
"midname": "",
"lastname": "Doe",
"country": "USA",
"state": "CA",
"city": "Santa Rosa",
"phones": {
"home": "(707) 123-4567",
"office": "(718) 123-4567",
"mobile": ""
},
"email": "john.doe@citi.com",
"location": "1 Court Pl, NY",
"gender": "male"
},
"avatar": "imgs/chat/avatar_m.gif",
"presence": "offline"
};
Prerial.Config.TestChatList = {}
Prerial.Config.TestChatList['john.doe@citi.com'] =
{
"chid": "001",
"cnport": "cn001",
"vrport": "vr001",
"title": "John Doe",
"profile": {
"firstname": "John",
"midname": "",
"lastname": "Doe",
"country": "USA",
"state": "CA",
"city": "Santa Rosa",
"phones": {
"home": "(707) 123-4567",
"office": "(718) 123-4567",
"mobile": ""
},
"email": "john.doe@citi.com",
"location": "1 Court Pl, NY",
"gender": "male"
},
"avatar": "imgs/chat/GregoryPeck.jpg",
"presence": "offline"
};
Prerial.Config.TestChatList['jane.doe@citi.com'] =
{
"chid": "002",
"cnport": "cn002",
"vrport": "vr002",
"title": "Jane Doe",
"location": "1 Court Pl, NY",
"avatar": "imgs/chat/MarilynMonroe.jpg",
"profile": {
"firstname": "Jane",
"midname": "",
"lastname": "Doe",
"country": "USA",
"state": "CA",
"city": "Santa Rosa",
"phones": {
"home": "(707) 123-4567",
"office": "(718) 123-4567",
"mobile": ""
},
"email": "jane.doe@citi.com",
"location": "1 Court Pl, NY",
"gender": "female"
},
"presence": "offline"
};
Prerial.Config.TestChatList['jack.doe@citi.com'] =
{
"chid": "003",
"cnport": "cn003",
"vrport": "vr003",
"title": "Jack Doe",
"location": "1 Court Pl, NY",
"avatar": "imgs/chat/PaulNewman.jpg",
"profile": {
"firstname": "Jack",
"midname": "",
"lastname": "Doe",
"country": "USA",
"state": "CA",
"city": "Santa Rosa",
"phones": {
"home": "(707) 123-4567",
"office": "(718) 123-4567",
"mobile": ""
},
"email": "jack.doe@citi.com",
"location": "1 Court Pl, NY",
"gender": "male"
},
"presence": "offline"
};
Prerial.Config.TestChatList['norman.spinrad@citi.com'] =
{
"chid": "004",
"cnport": "cn004",
"vrport": "vr004",
"title": "Norman Spinrad",
"avatar": "imgs/chat/NormanSpinrad.jpg",
"profile": {
"firstname": "Norman",
"midname": "",
"lastname": "Spinrad",
"country": "USA",
"state": "CA",
"city": "Santa Rosa",
"phones": {
"home": "(707) 123-4567",
"office": "(718) 123-4567",
"mobile": ""
},
"email": "norman.spinrad@citi.com",
"location": "100 Citibank Dr, S. Antonio, TX",
"gender": "male"
},
"presence": "offline"
};
Prerial.Config.TestChatList['alice.snyder@citi.com'] =
{
"chid": "005",
"cnport": "cn005",
"vrport": "vr005",
"title": "Alice Snyder",
"avatar": "imgs/chat/avatar_f.gif",
"profile": {
"firstname": "Alice",
"midname": "",
"lastname": "Snyder",
"country": "USA",
"state": "CA",
"city": "Santa Rosa",
"phones": {
"home": "(707) 123-4567",
"office": "(718) 123-4567",
"mobile": ""
},
"email": "alice.snyder@citi.com",
"location": "1 Court Pl, NY",
"gender": "female"
},
"presence": "offline"
};
Prerial.Config.TestChatList['charles.snyder@citi.com'] =
{
"chid": "006",
"cnport": "cn006",
"vrport": "vr006",
"title": "Charles Snyder",
"avatar": "imgs/chat/avatar_m.gif",
"profile": {
"firstname": "Charles",
"midname": "",
"lastname": "Snyder",
"country": "USA",
"state": "CA",
"city": "Santa Rosa",
"phones": {
"home": "(707) 123-4567",
"office": "(718) 123-4567",
"mobile": ""
},
"email": "charles.snyder@citi.com",
"location": "10 Harborside PL, NJ",
"gender": "male"
},
"presence": "offline"
};
Prerial.Config.TestChatList['jane.smith@citi.com'] =
{
"chid": "007",
"cnport": "cn007",
"vrport": "vr007",
"title": "Jane Smith",
"avatar": "imgs/chat/AudreyHupburn.jpg",
"profile": {
"firstname": "Jane",
"midname": "",
"lastname": "Smith",
"country": "USA",
"state": "CA",
"city": "Santa Rosa",
"phones": {
"home": "(707) 123-4567",
"office": "(718) 123-4567",
"mobile": ""
},
"email": "jane.smith@citi.com",
"location": "100 Citibank Dr, S. Antonio, TX",
"gender": "female"
},
"presence": "offline"
};
Prerial.Config.User = {};
Prerial.Config.ChatSettingsTitles = [
{title: 'Status', icon: ''},
{title: 'My Profile', icon: ''},
{title: 'Settings', icon: ''},
{title: 'Add Contact', icon: ''},
{title: 'Add Chat Group', icon: ''}
];
Prerial.Utils = {};
Prerial.Utils.setContactModel = function () {
var md = Backbone.Model.extend();
var model = new md;
model.set(arguments[0])
return model;
};
Prerial.Utils.stopPropagation = function (e) {
if (e.preventDefault) e.preventDefault();
if (e.stopPropagation) e.stopPropagation();
e.cancelBubble = true;
e.returnValue = false;
return false;
};
/******************** start Video *****************************/
/*
function WebSocket(_socket, limit) {
var channel = _socket.channel;
var dataRef = new window.Firebase('https://chat.firebaseIO.com/' + channel);
dataRef.remove();
dataRef.channel = channel;
// if (limit) {
dataRef.limit(1);
dataRef.onDisconnect().remove();
// }
dataRef.on('child_added', function (data) {
_socket.onmessage(data.val());
});
dataRef.send = function (data) {
this.push(data);
};
if (_socket.isInitiator === true) {
dataRef.onDisconnect().remove();
}
if (_socket.onopen) {
setTimeout(_socket.onopen, 1);
}
console.debug("WebSocket", dataRef)
return dataRef;
};
*/
function NodeWebSocket (req) {
var _this = this;
this.socket = new req.websocket();
this.socket.on(req.evt, function (data) {
req.onmessage(data)
});
this.doSend = function(data) {
_this.send(data);
};
this.send = function(data) {
_this.socket.emit(req.evt, data);
};
this.writable = true;
return this;
};
/********************************* stop Video ************************/
function getToken() {
return (Math.random() * new Date().getTime()).toString(36).replace( /\./g , '');
};
var App = {};
App.isiPad = /iPad/i.test(navigator.userAgent) || /iPhone OS 3_1_2/i.test(navigator.userAgent) || /iPhone OS 3_2_2/i.test(navigator.userAgent);
App.authenticated = true;
App.user = Prerial.Config.User;
App.video = {};
App.video.moderator = false;
App.video.started = false;
App.video.videoRoom = null;
App.audio = {};
App.audio.moderator = false;
App.audio.started = false;
App.audio.audioRoom = null;
App.chat = {};
App.chat.models = {};
App.chat.alerts = {};
App.chat.visible = false;
App.chat.conversations = {};
App.chat.conversations.active = null;
App.chat.conversations.display = {};
App.chat.conversations.connections = {};
|
var code = require('../app');
module.exports = function(app, db){
// --------------------------- API V1 for User model --------------------------------------- //
loginUser = function(req, res){
console.log("POST - login users");
db.get("SELECT * FROM user WHERE email = ? AND password = ?", [req.body.email, req.body.password], function(err, rows) {
console.log('POST login user with email: ' + req.body.email);
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'POST');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
if(rows){
rows.cookie = code.cookie;
res.send(rows);
} else if(err){
console.log("Login failed due to SQLite error", err);
res.send(400);
} else {
console.log("Login failed: user not found.");
var message = '{"error":403}';
var error = JSON.parse(message);
res.send(error);
}
//closeDb();
});
}
// Find all User and return list
findAllUsers = function(req, res){
console.log("GET - read all users");
db.all("SELECT * FROM user", function(err, rows) {
console.log('GET All Users');
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'GET');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
rows.forEach(function (row) {
console.log(row.id + ": " + row.firstname);
});
res.send(rows);
//closeDb();
});
};
// Find User by email specific field
findUser = function(req, res){
console.log("GET - read user by email= " + req.params.email);
db.get("SELECT * FROM user WHERE email = ?", [req.params.email], function(err, rows) {
console.log('GET user with email: ' + req.params.email);
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'GET');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
res.send(rows);
//closeDb();
});
};
// Create User with all fields
createUser = function(req, res){
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'POST');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
var stmt = db.prepare("INSERT INTO user (email, password, firstname, lastname, phone) VALUES (?, ?, ?, ?, ?)");
stmt.run([req.body.email, req.body.password, req.body.firstname, req.body.lastname, req.body.phone], function(err, rows){
if(err){
console.log("Save user failed");
var message = '{"error":403}';
var error = JSON.parse(message);
res.send(error);
} else {
db.get("SELECT * FROM user WHERE email = ?", [req.body.email], function(err, rows) {
if (err) {
res.send(err);
} else {
console.log('POST - save User with data = \n {' + '\n email : ' + req.body.email + '\n password : ' + req.body.password + '\n firstname : ' + req.body.firstname + '\n lastname : ' + req.body.lastname + '\n phone : ' + req.body.phone + '\n }');
rows.cookie = code.cookie;
res.send(rows);
}
});
}
});
}
// Update User with all fields
updateUser = function(req, res){
console.log('POST - update User with data = \n {' + '\n email : ' + req.body.email + '\n firstname : ' + req.body.firstname + '\n lastname : ' + req.body.lastname + '\n phone : ' + req.body.phone + '\n }');
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'POST');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
var stmt = db.prepare("UPDATE user SET firstname = ?, lastname = ?, phone = ? WHERE email = ?");
stmt.run([req.body.firstname, req.body.lastname, req.body.phone, req.body.email], function(err, rows){
if(err){
console.log(err);
res.send(err);
} else{
db.get("SELECT * FROM user WHERE email = ?", [req.body.email], function(err, rows) {
if (err) {
res.send(err);
} else {
console.log('POST - update User with data = \n {' + '\n email : ' + req.body.email + '\n password : ' + req.body.password + '\n firstname : ' + req.body.firstname + '\n lastname : ' + req.body.lastname + '\n phone : ' + req.body.phone + '\n }');
rows.cookie = code.cookie;
res.send(rows);
}
});
}
});
}
// Delete User by email field
deleteUser = function(req, res){
console.log('DELETE user with email : ' + req.body.email);
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'DELETE');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
var stmt = db.prepare("DELETE FROM user WHERE email = ?");
stmt.run(req.body.email);
res.send('update done');
}
//Link routes and functions
// URI for update User
app.post('/api/v1/user/login', loginUser);
// URI for all users
app.get('/api/v1/user/list', findAllUsers);
// URI for search email fiel
app.get('/api/v1/user/:email', findUser);
// URI for create User
app.post('/api/v1/user/create', createUser);
// URI for update User
app.post('/api/v1/user/update', updateUser);
// URI for delete User
app.delete('/api/v1/user/delete', deleteUser);
// --------------------------- API V1 for Product model --------------------------------------- //
// Find all Products and return list
findAllProducts = function(req, res){
console.log("GET - read all Products");
db.all("SELECT * FROM product", function(err, rows) {
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'GET');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
rows.forEach(function (row) {
console.log(row.id + ": " + row.name);
});
res.send(rows);
//closeDb();
});
};
// Find Product by id specific field
findProduct = function(req, res){
console.log("GET - read product by id : " + req.params.id);
db.get("SELECT * FROM product WHERE id = ?", [req.params.id], function(err, rows) {
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'GET');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
res.send(rows);
//closeDb();
});
};
// Create Product with all fields
createProduct = function(req, res){
console.log('POST - save Product with data = \n {' + '\n name : ' + req.body.name + '\n type : ' + req.body.type + '\n amount : ' + req.body.amount + '\n }');
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'POST');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
var stmt = db.prepare("INSERT INTO product (name, type, amount) VALUES (?, ?, ?)");
stmt.run(req.body.name, req.body.type, req.body.amount);
res.send('save done');
}
// Update Product with all fields
updateProduct = function(req, res){
console.log('PUT - update Product with data = \n {' + '\n name : ' + req.body.name + '\n type : ' + req.body.type + '\n amount : ' + req.body.amount + '\n }');
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'PUT');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
var stmt = db.prepare("UPDATE product SET name = ?, type = ?, amount = ? WHERE id = ?");
stmt.run(req.body.name, req.body.type, req.body.amount, req.body.id);
res.send('update done');
}
// Delete Product by id field
deleteProduct = function(req, res){
console.log('DELETE product with id = ' + req.body.id);
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'DELETE');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
var stmt = db.prepare("DELETE FROM product WHERE id = ?");
stmt.run(req.body.id);
res.send('update done');
}
//Link routes and functions
// URI for all products
app.get('/api/v1/product/list', findAllProducts);
// URI for search id fiel
app.get('/api/v1/product/:id', findProduct);
// URI for create Product
app.post('/api/v1/product/create', createProduct);
// URI for update Product
app.put('/api/v1/product/update', updateProduct);
// URI for delete Product
app.delete('/api/v1/product/delete', deleteProduct);
// Close DB
function closeDb() {
console.log("closeDb");
db.close();
}
}
|
var test = require('tap').test;
var sliceFile = require('../');
var through = require('through2');
var fs = require('fs');
var wordFile = __dirname + '/data/words';
test('slice twice on the same instance', function (t) {
t.plan(2);
var xs = sliceFile(wordFile);
var first = [];
var second = [];
xs.slice(-5).pipe(through(
function (line, _, next) {
first.push(line.toString('utf8'));
next();
},
function () {
t.deepEqual(first, [
"épée's\n",
"épées\n",
"étude\n",
"étude's\n",
"études\n",
]);
xs.slice(-10, -5).pipe(through(
function (line, _, next) {
second.push(line.toString('utf8'));
next();
},
function () {
t.deepEqual(second, [
"élan's\n",
"émigré\n",
"émigré's\n",
"émigrés\n",
"épée\n"
]);
}
));
}
));
});
|
expenseTrackerAppModule.directive("exptWhenActive",function($location){"use strict";return{scope:!0,link:function(scope,element){var currentSection=$location.$$path.split("/");currentSection=currentSection[1],element=element[0],currentSection===element.dataset.sectionname&&element.classList.add("active")}}}); |
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }
var _FileDocJs = require('./FileDoc.js');
var _FileDocJs2 = _interopRequireDefault(_FileDocJs);
/**
* Doc class for test code file.
*/
var TestFileDoc = (function (_FileDoc) {
function TestFileDoc() {
_classCallCheck(this, TestFileDoc);
_get(Object.getPrototypeOf(TestFileDoc.prototype), 'constructor', this).apply(this, arguments);
}
_inherits(TestFileDoc, _FileDoc);
_createClass(TestFileDoc, [{
key: '@kind',
/** set ``testFile`` to kind. */
value: function kind() {
this._value.kind = 'testFile';
}
}]);
return TestFileDoc;
})(_FileDocJs2['default']);
exports['default'] = TestFileDoc;
module.exports = exports['default']; |
/**
* React Static Boilerplate
* https://github.com/kriasoft/react-static-boilerplate
*
* Copyright © 2015-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React, { PropTypes } from 'react';
class Layout extends React.Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
export default Layout;
|
'use strict';
phoneApp.controller('ListModelsController',
function ListModelsController($scope, $routeParams, phoneDatas) {
if ($routeParams.smartphone) {
$scope.search = $routeParams.smartphone;
};
phoneDatas
.getAllPhones()
.$promise
.then(function (smartphones) {
var allModels = [];
for (var i = 0; i < smartphones.length; i++) {
var models = smartphones[i].models;
if (models) {
for (var j = 0; j < models.length; j++) {
models[j].smartphone = smartphones[i].name;
models[j].smartphoneId = smartphones[i].id;
allModels.push(models[j]);
}
}
}
$scope.models = allModels;
});
}
); |
Meteor.publish("avatars", function () {
//Meteor._sleepForMs(2000);
return Avatars.find();
});
Meteor.publish("posts", function () {
//Meteor._sleepForMs(2000);
return Posts.find({
$or: [
{ hidden: {$ne: true} },
{ author: this.userId }
]
});
});
Meteor.publish("post", function (id) {
check(id, String);
//Meteor._sleepForMs(2000);
return Posts.find({ _id: id });
});
Meteor.publish("media", function () {
//Meteor._sleepForMs(2000);
return Media.find();
});
Meteor.publish("groups", function () {
//Meteor._sleepForMs(2000);
return Groups.find();
});
Meteor.publish("group", function (slug) {
check(slug, String);
//Meteor._sleepForMs(2000);
return Groups.find({ slug: slug });
});
Meteor.publish("invites", function () {
//Meteor._sleepForMs(2000);
return Invites.find({ uploader: this.userId });
});
|
var EXPRESS=require("EXPRESS"),
PATH=require("path"),
FS=require("fs"),
CLUSTER=require("cluster"),
Q=require("q"),
HDMA=require("./nodejs/api/hdma"),
CONFIG=require("./nodejs/config"),
LOGGER=require("./nodejs/config/logger.js"),
NUMCPU=2, //require("os").cpus().length,
models={
geoviewer: null
},
domain="",
domainFolder="",
MONGODB=null,
port=(CONFIG&&CONFIG.server)?CONFIG.server.port:8080,
app=null,
server=null,
io=null,
argv=require("minimist")(process.argv.slice(2));
//check arguemnts in the command line
var value;
for(var k in argv){
value=argv[k]
//port
if(k=='p' && value && value!=''){
port=value;
}
}
/**
//cluster
if(CLUSTER.isMaster){
for(var i=0;i<NUMCPU;i++){
CLUSTER.fork();
}
Q.all([HDMA.mongodb.connect("localhost:27017", "HDMA"), HDMA.mongodb.connect("localhost:27017", "IBSS")]).then(function(results){
console.log(results);
//console.log(b);
}).catch(function(err){
console.log("error", err)
})
//init();
}else{
//init();
}
// Listen for dying workers
CLUSTER.on('exit', function (worker) {
// Replace the dead worker,
// we're not sentimental
console.log('Worker ' + worker.id + ' died :(');
CLUSTER.fork();
});
*/
init();
//init server
function init(){
app=EXPRESS();
server=app.listen(port);
io=require("socket.io").listen(server, {resource:"/socket/socket.io", log:false});//, transports:["xhr-polling"]}); //because we are using iis7 as the main web server which does not support websocket. we need to change to long-polling for socket. please refer to http://schmod.ruhoh.com/windows/socket-io-and-iis/
//winston.addColors({debug: 'green',info: 'cyan',silly: 'magenta',warn: 'yellow',error: 'red'})
LOGGER.info("Server is started and listened on port "+port);
//config----------------------------------------------------------------------
//log
var logFile = FS.createWriteStream('./log/server.log', {flags: 'a'}); //use {flags: 'w'} to open in write mode
app.use(EXPRESS.logger({stream: logFile}))
//gzip conpress method
app.use(EXPRESS.compress())
//parse the post data of the body
app.use(EXPRESS.bodyParser());
//render engine
app.set('views', __dirname+"/views/");
app.set('view engine', 'jade');
//jsonp
app.set("jsonp callback", true);
//maxlistener
//app.setMaxListeners(0);
//io.setMaxListeners(0);
//passport required config
//app.use(EXPRESS.static("public"))
app.use(EXPRESS.cookieParser());
app.use(EXPRESS.session({secret:'hdma@SDSU'})); // session secret
app.use(app.router)
//-------------------------------------------------------------------------------
models.geoviewer=require("./nodejs/geoviewer")({mongodb:null, io:io, router:app});
/***********************************************************************************
* RESTful
*********************************************************************************/
//if the domain is not equal to domainFolder, we may need to manually set up the path!!!
app.use("/geoviewer", EXPRESS.static(PATH.join(__dirname, "/public/geoviewer/final")));
app.use("/common", EXPRESS.static(PATH.join(__dirname, "/public/common")));
LOGGER.info("******************************")
LOGGER.info("Server Routes inited!")
}
|
const GraphDB = plugins.require('graphql/GraphDb').Instance()
const sequelize = require('sequelize')
class ApiEnvironment extends SuperClass {
get schemas() {
return this.siteManager.schemas
}
get sequelize() {
return GraphDB.sequelize
}
/**
* send a query to the database
* @param sql {String}
* @param vars {Object}
*/
async query(sql, vars, config = {}) {
return GraphDB.sequelize.query( this.query_prepare(sql, vars), Object.assign({ type: sequelize.QueryTypes.SELECT }, config) )
}
/**
* send a query to the database and get the first row
* @param sql {String}
* @param vars {Object}
* @param default
*/
async query_object(sql, vars, def) {
const result = await this.query(sql, vars)
if (result.length === 0 || result[0] === undefined) {
if(def !== undefined)
return def
else
throw('No results found')
}
return result[0]
}
/**
* Prepare an sql statement (for debug testing)
* @param sql {String}
* @param vars {Object}
*/
query_prepare(sql, vars) {
if (vars === undefined || vars === null)
vars = this.post
vars['auth_id'] = this.session['auth_id']
if (this.queryVars) {
for (var key in this.queryVars)
vars[key] = this.queryVars[key]
}
return queryFormat(sql, vars)
}
}
module.exports = ApiEnvironment
// -----------
function queryFormat(sql, values) {
if (values === null || values === undefined)
values = {}
if (!(values instanceof Object || Object.isPrototypeOf(values) || typeof (values) === 'object'))
values = {}
var chunkIndex = 0
var placeholdersRegex = /{@(.*?)}/g
var result = ''
var match, value
while (match = placeholdersRegex.exec(sql)) {
// ToDo Check if surrounded by quotes or not ..?
value = values[match[1]]
value = this.escape(value == undefined ? '' : value)
// this.escapeId(..?)
if (value.substr(0, 1) == "'" && value.substr(value.length - 1) == "'")
value = value.substr(1, value.length - 2)
result += sql.slice(chunkIndex, match.index) + value
chunkIndex = placeholdersRegex.lastIndex
}
if (chunkIndex === 0) {
// Nothing was replaced
if (global.logSQL)
console.log(sql)
return sql
}
if (chunkIndex < sql.length)
result += sql.slice(chunkIndex)
if (global.logSQL)
console.log(result)
return result
} |
require('proof')(24, function (assert) {
var tz = require('timezone')(require('timezone/en_AU'))
// en_AU abbreviated months
assert(tz('2000-01-01', '%b', 'en_AU'), 'Jan', 'Jan')
assert(tz('2000-02-01', '%b', 'en_AU'), 'Feb', 'Feb')
assert(tz('2000-03-01', '%b', 'en_AU'), 'Mar', 'Mar')
assert(tz('2000-04-01', '%b', 'en_AU'), 'Apr', 'Apr')
assert(tz('2000-05-01', '%b', 'en_AU'), 'May', 'May')
assert(tz('2000-06-01', '%b', 'en_AU'), 'Jun', 'Jun')
assert(tz('2000-07-01', '%b', 'en_AU'), 'Jul', 'Jul')
assert(tz('2000-08-01', '%b', 'en_AU'), 'Aug', 'Aug')
assert(tz('2000-09-01', '%b', 'en_AU'), 'Sep', 'Sep')
assert(tz('2000-10-01', '%b', 'en_AU'), 'Oct', 'Oct')
assert(tz('2000-11-01', '%b', 'en_AU'), 'Nov', 'Nov')
assert(tz('2000-12-01', '%b', 'en_AU'), 'Dec', 'Dec')
// ' + name + ' months
assert(tz('2000-01-01', '%B', 'en_AU'), 'January', 'January')
assert(tz('2000-02-01', '%B', 'en_AU'), 'February', 'February')
assert(tz('2000-03-01', '%B', 'en_AU'), 'March', 'March')
assert(tz('2000-04-01', '%B', 'en_AU'), 'April', 'April')
assert(tz('2000-05-01', '%B', 'en_AU'), 'May', 'May')
assert(tz('2000-06-01', '%B', 'en_AU'), 'June', 'June')
assert(tz('2000-07-01', '%B', 'en_AU'), 'July', 'July')
assert(tz('2000-08-01', '%B', 'en_AU'), 'August', 'August')
assert(tz('2000-09-01', '%B', 'en_AU'), 'September', 'September')
assert(tz('2000-10-01', '%B', 'en_AU'), 'October', 'October')
assert(tz('2000-11-01', '%B', 'en_AU'), 'November', 'November')
assert(tz('2000-12-01', '%B', 'en_AU'), 'December', 'December')
})
|
'use strict';
module.exports = {
"prompts": {
"name" : {
"type" : "string",
"required": true,
"message" : "Project name"
},
"version" : {
"type" : "string",
"message" : "Project version",
"default" : "1.0.0"
},
"description": {
"type" : "string",
"required": false,
"message" : "Project description",
"default" : "A new React project"
},
"author" : {
"type" : "string",
"message": "Author"
},
"port" : {
"type" : "input",
"message": "port",
"default" : 10000,
"validate":function (data) {
if(/^(0|([0-9]\d*))$/.test(data)){
return true;
}
return '输入整数';
}
},
"test": {
"type": "confirm",
"message": "Setup unit tests with jest?"
}
},
"filters":{
"__tests__/**/*": "test",
"test/**/*": "test"
},
"completeMessage": "To get started:\n\n cd {{destDirName}}\n npm install\n npm run dev\n\nDocumentation can be found at https://github.com/waka-templates/react-webpack2"
}
|
var UncrapCore =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 1);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/*
License: see license.txt
Originally from http://blog.olkie.com/2013/11/05/online-c-function-prototype-header-generator-tool/
*/
Object.defineProperty(exports, "__esModule", { value: true });
var FoundFunction = /** @class */ (function () {
function FoundFunction() {
this.before = null;
this.comments = null;
this.returnType = null;
this.functionName = null;
this.parameters = null;
this.declared = false;
}
FoundFunction.prototype.hasParameters = function () {
var has = this.parameters && this.parameters != "void";
return has;
};
FoundFunction.prototype.hasNonVoidReturnType = function () {
var result = this.returnType.trim().match(/^(extern\s+)?void/) == null;
return result;
};
FoundFunction.prototype.getParametersDeclArray = function (options) {
options = options || {};
var params = [];
if (this.hasParameters()) {
params = this.getParameters(options).split(/\s*,\s*/);
}
return params;
};
FoundFunction.prototype.hasVariadicArgument = function () {
var result;
result = this.parameters.match(/[.][.][.]/) != null;
return result;
};
FoundFunction.prototype.getParameterNames = function (options) {
options = options || {};
var result = [];
var params = this.getParametersDeclArray(options);
if (params.length == 0) {
return result;
}
for (var _i = 0, params_1 = params; _i < params_1.length; _i++) {
var paramDecl = params_1[_i];
paramDecl = paramDecl.trim();
//skip over variadic parameters "..." and "void".
if (paramDecl.match(/^([.][.][.]|void)$/)) {
continue;
}
var match = paramDecl.trim().match(/\b(\w+)(?=$|\[.*)/);
if (!match) {
throw "didn't match!";
}
var name_1 = match[1];
result.push(name_1);
}
return result;
};
FoundFunction.prototype.getParameterNamesString = function (options) {
options = options || {};
var params = this.getParameterNames(options);
var result = params.join(", ");
return result;
};
FoundFunction.prototype.getParameters = function (options) {
options = options || {};
var result = this.parameters;
if (options.convertVariadic) {
result = convertVariardicToVaList(result);
}
return result;
};
FoundFunction.prototype.getParametersPrepended = function (toPrepend, options) {
options = options || {};
var result = toPrepend;
if (this.hasParameters()) {
result += ", " + this.parameters;
}
if (options.convertVariadic) {
result = convertVariardicToVaList(result);
}
return result;
};
FoundFunction.prototype.getSignatureMismatchString = function (foundFunction) {
//NOTE: not smart enough for 'extern' and stuff like that
if (foundFunction.returnType != this.returnType) {
return "return types do not match!";
}
//count parameters
//NOTE: no support for strings with "," in it
if ((foundFunction.parameters.match(/.+?(,|$)/g) || []).length != (this.parameters.match(/.+?(,|$)/g) || []).length) {
return "parameter count does not match!";
}
return "";
};
;
FoundFunction.prototype.toString = function () {
return "FoundFunction{ returnType='" + this.returnType + "', functionName='" + this.functionName + "', parameters='" + this.parameters + "', declared='" + this.declared + "' }";
};
;
return FoundFunction;
}());
exports.FoundFunction = FoundFunction;
function convertVariardicToVaList(paramDecls) {
var result = paramDecls.replace(/[.][.][.]/, "va_list args");
return result;
}
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/*
For the time being, this module just re-exports other file's functionality combined under "UncrapCore".
See `Re-exports` in https://www.typescriptlang.org/docs/handbook/modules.html
*/
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(2));
__export(__webpack_require__(0));
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/*
License: see license.txt
Originally from http://blog.olkie.com/2013/11/05/online-c-function-prototype-header-generator-tool/
*/
Object.defineProperty(exports, "__esModule", { value: true });
var FoundFunction_1 = __webpack_require__(0);
var CParser = /** @class */ (function () {
function CParser() {
}
CParser.parseFuncProtos = function (inputCode, parseComments) {
var functions = [];
var cKeywords = ["auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "int", "long", "register", "return", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while"];
var invalidFunctionNames = cKeywords;
var invalidReturnTypes = ["auto", "break", "case", "continue", "default", "do", "else", "for", "goto", "if", "return", "sizeof", "switch", "while", "typedef"]; //TODO: may have some of these wrong
//convert all line endings to a \n
inputCode = inputCode.replace(/\r\n|\r/, "\n");
//grab all comment blocks, and comment lines preceeding function definition
var reStringPart = /"(?:\\[\n|.]|[^\n\\])"/.source;
var reCommentPart = /\/(?:[*][\s\S]*?(?:[*]\/|$)|\/.*(?=\n|$))/.source; //NOTE the look ahead! can't capture \n, because js doesn't support \Z and we need our big re pattern below to be able to match on \Z or $ if not using multiline mode
var reStringOrCommentOrAny = "(?:" + reCommentPart + "|" + reStringPart + "|[\\s\\S])*?"; //tries to respect comments and strings
//var reBeforePart = /([\s\S]*?)/.source; //does not respect comments or strings
var reBeforePart = "(" + reStringOrCommentOrAny + ")";
var reDoxygenCommentsPart = /\s*((?:\s*\/[*][*!][\s\S]*?[*]\/|\s*\/\/[\/!].*(?:\n|$))+)/.source;
var re = new RegExp(reBeforePart + /(?:(?:^|\n)\s*(\w+[\s*\t\w]+)\b\s*(\w+)\s*\(\s*([^)]*)\s*\)\s*([{;])|$)/.source, "g"); //can't use multiline mode because we need to match on end of input, not just line
//console.log(re);
var groups;
var lastIndex = -1; //detect stuck in loops
while ((groups = re.exec(inputCode)) !== null && groups.index != lastIndex) {
var result = new FoundFunction_1.FoundFunction();
result.before = (groups[1] || "").trim();
result.returnType = (groups[2] || "").replace(/\s+/g, " ").trim();
result.functionName = (groups[3] || "").trim();
result.parameters = (groups[4] || "").replace(/\s+/g, " ").trim();
if (groups[5] == ";") {
result.declared = true;
}
//if we didn't find a function name, don't add it or invalid keywords used
if (result.functionName) {
//check individual return type words
var returnTypes = result.returnType.toLowerCase().split(/[\s*]+/);
if (arraysIntersect(returnTypes, invalidReturnTypes) || invalidFunctionNames.indexOf(result.functionName.toLowerCase()) != -1) {
//TODO: log use of invalid keyword (or rather that we thought we found a function declaration/definition, but it had invalid keywords).
}
else {
//extract comments, if any
if (parseComments === true) {
var reComments = new RegExp(reBeforePart + reDoxygenCommentsPart + /\s*/.source, "g");
//have to loop and find last match and check if it matches right up to end of .before value. Why loop? because if we tell it to match up to $ (if it can), it will create some problems. /** header */ other lines (not a function) /* comment */ function. It will match right on over. Need to let it stop once it is happy and not force to end of input.
var groups2;
var madeItToEnd = false;
while (!madeItToEnd && (groups2 = reComments.exec(result.before)) !== null) {
madeItToEnd = reComments.lastIndex == result.before.length;
}
//if we made it to the end of the input string, then we found a matching doxygen comment!!!
if (madeItToEnd && groups2) {
result.before = groups2[1];
result.comments = groups2[2].replace(/(\r\n|\r|\n)[ \t]+/g, "$1"); //remove indenting
}
}
functions.push(result);
} //end of invalid keywords test
}
lastIndex = groups.index;
}
return functions;
};
return CParser;
}());
exports.CParser = CParser;
function arraysIntersect(array1, array2) {
var result = false;
for (var i = 0; !result && i < array2.length; i++) {
result = array1.indexOf(array2[i]) !== -1;
}
return result;
}
/***/ })
/******/ ]); |
import controller from './ngbPathwaysPanel.controller';
export default {
template: require('./ngbPathwaysPanel.html'),
controller: controller.UID
};
|
/**
* @jsx React.DOM
*/
'use strict';
var assert = require('assert');
var makeHref = require('../makeHref');
var getPattern = makeHref.getPattern;
var descriptors = require('../descriptors');
var Routes = descriptors.Routes;
var Route = descriptors.Route;
function makeMatchTrace(routes, ref) {
return descriptors.getTraceByName(routes, ref).map((route) => {
return {route, match: {}};
});
}
describe('makeHref', function() {
describe('getPattern()', function() {
var scoped = (
<Routes name="e" path="/e">
<Route>
<Route name="f" path="/f" />
</Route>
<Route name="g" path="/g" />
<Route name="h" path="/h">
<Route name="i" path="/i" />
</Route>
</Routes>
);
var routes = (
<Routes>
<Route name="a" path="/" />
<Route name="b" path="/b">
<Route name="c" path="/c"/>
</Route>
<Route>
<Route name="d" path="/d" />
</Route>
{scoped}
</Routes>
);
it('generates href by absolute route ref', function() {
var matchA = {
route: routes.children[0],
trace: makeMatchTrace(routes, 'a')
};
assert.equal(getPattern(routes, '/a', matchA), '/');
assert.equal(getPattern(routes, '/b', matchA), '/b');
assert.equal(getPattern(routes, '/b/c', matchA), '/b/c');
assert.equal(getPattern(routes, '/d', matchA), '/d');
assert.equal(getPattern(routes, '/e', matchA), '/e');
assert.equal(getPattern(routes, '/e/f', matchA), '/e/f');
});
it('generates href by relative route ref', function() {
var matchA = {
route: routes.children[0],
trace: makeMatchTrace(routes, 'a')
};
assert.equal(getPattern(routes, 'a', matchA), '/');
var matchE = {
route: routes.children[3],
trace: makeMatchTrace(routes, 'e')
};
assert.equal(getPattern(routes, 'e', matchE), '/e');
assert.equal(getPattern(routes, 'e/f', matchE), '/e/f');
assert.equal(getPattern(routes, 'e/g', matchE), '/e/g');
assert.equal(getPattern(routes, 'e/h', matchE), '/e/h');
assert.equal(getPattern(routes, 'e/h/i', matchE), '/e/h/i');
var matchH = {
route: routes.children[3].children[2],
trace: makeMatchTrace(routes, 'e/h')
};
assert.equal(getPattern(routes, 'e/h', matchH), '/e/h');
assert.equal(getPattern(routes, 'e/h/i', matchH), '/e/h/i');
});
});
describe('makeHref()', function() {
var routes = (
<Route>
<Route name="a" path="/" />
<Route name="b" path="/:lastName">
<Route name="c" path="/:firstName"/>
</Route>
</Route>
);
it('generates link by absolute route ref', function() {
var matchA = {
route: routes.children[0],
trace: makeMatchTrace(routes, 'a')
};
assert.equal(
makeHref(routes, '/a', matchA, {}),
'/');
assert.equal(
makeHref(routes, '/b', matchA, {lastName: 'ln'}),
'/ln');
assert.equal(
makeHref(routes, '/b/c', matchA, {lastName: 'ln', firstName: 'fn'}),
'/ln/fn');
});
it('generates link by relative route ref', function() {
var matchB = {
route: routes.children[1],
trace: makeMatchTrace(routes, 'b')
};
assert.equal(
makeHref(routes, 'b', matchB, {lastName: 'ln'}),
'/ln');
assert.equal(
makeHref(routes, 'b/c', matchB, {lastName: 'ln', firstName: 'fn'}),
'/ln/fn');
});
it('throws meaningful error in case route reference cannot be resolved', function() {
var matchA = {
route: routes.children[0],
trace: makeMatchTrace(routes, 'a')
};
assert.throws(
() => makeHref(routes, '/x', matchA, {}),
Error,
'Error: Invariant Violation: cannot resolve "/x" route reference'
);
});
});
});
|
/*
* Copyright (c) André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
const {
assertThrows, fail
} = Assert;
// 24.3.2 JSON.stringify: Missing ReturnIfAbrupt calls
// https://bugs.ecmascript.org/show_bug.cgi?id=3666
class Err extends Error { }
var stringObject = Object.assign(new String, {
toString: () => { throw new Err },
valueOf: () => fail `unreachable`,
});
assertThrows(Err, () => JSON.stringify(null, [stringObject]));
var numberObject = Object.assign(new String, {
toString: () => { throw new Err },
valueOf: () => fail `unreachable`,
});
assertThrows(Err, () => JSON.stringify(null, [numberObject]));
var numberObject = Object.assign(new Number, {
toString: () => fail `unreachable`,
valueOf: () => { throw new Err },
});
assertThrows(Err, () => JSON.stringify(null, null, numberObject));
var stringObject = Object.assign(new String, {
toString: () => { throw new Err },
valueOf: () => fail `unreachable`,
});
assertThrows(Err, () => JSON.stringify(null, null, stringObject));
|
var stringtool = require('../../tools/string-tool');
describe('string-tool', function () {
'use strict';
it('should left pad string', function () {
expect(stringtool.padLeft('x', 4, 'y')).toBe('yyyx');
});
it('should left pad number', function () {
expect(stringtool.padLeft(1, 2, '0')).toBe('01');
});
it('should format time span 00:00', function () {
expect(stringtool.formatTimeSpan(0, 0)).toBe('00:00');
});
it('should format time span 09:31', function () {
expect(stringtool.formatTimeSpan(9, 31)).toBe('09:31');
});
it('should format time span 23:59', function () {
expect(stringtool.formatTimeSpan(23, 59)).toBe('23:59');
});
}); |
/* eslint camelcase:0 */
/**
This is a wrapper for `ember-debug.js`
Wraps the script in a function,
and ensures that the script is executed
only after the dom is ready
and the application has initialized.
Also responsible for sending the first tree.
**/
/*eslint prefer-spread: 0 */
/* globals Ember, adapter, env */
var currentAdapter = 'basic';
if (typeof adapter !== 'undefined') {
currentAdapter = adapter;
}
var currentEnv = 'production';
if (typeof env !== 'undefined') {
currentEnv = env;
}
// @formatter:off
var EMBER_VERSIONS_SUPPORTED = {{EMBER_VERSIONS_SUPPORTED}};
// @formatter:on
(function(adapter) {
onEmberReady(function() {
// global to prevent injection
if (window.NO_EMBER_DEBUG) {
return;
}
if (!versionTest(Ember.VERSION, EMBER_VERSIONS_SUPPORTED)) {
// Wrong inspector version. Redirect to the correct version.
sendVersionMiss();
return;
}
// prevent from injecting twice
if (!Ember.EmberInspectorDebugger) {
// Make sure we only work for the supported version
define('ember-debug/config', function() {
return {
default: {
environment: currentEnv
}
};
});
window.EmberInspector = Ember.EmberInspectorDebugger = requireModule('ember-debug/main')['default'];
Ember.EmberInspectorDebugger.Adapter = requireModule('ember-debug/adapters/' + adapter)['default'];
onApplicationStart(function appStarted(instance) {
let app = instance.application;
if (!('__inspector__booted' in app)) {
// Watch for app reset/destroy
app.reopen({
reset: function() {
this.__inspector__booted = false;
this._super.apply(this, arguments);
}
});
}
if (instance && !('__inspector__booted' in instance)) {
instance.reopen({
// Clean up on instance destruction
willDestroy() {
if (Ember.EmberInspectorDebugger.get('owner') === instance) {
Ember.EmberInspectorDebugger.destroyContainer();
Ember.EmberInspectorDebugger.clear();
}
return this._super.apply(this, arguments);
}
});
if (!Ember.EmberInspectorDebugger._application) {
bootEmberInspector(instance);
}
}
});
}
});
function bootEmberInspector(appInstance) {
appInstance.application.__inspector__booted = true;
appInstance.__inspector__booted = true;
// Boot the inspector (or re-boot if already booted, for example in tests)
Ember.EmberInspectorDebugger.set('_application', appInstance.application);
Ember.EmberInspectorDebugger.set('owner', appInstance);
Ember.EmberInspectorDebugger.start(true);
}
function onEmberReady(callback) {
var triggered = false;
var triggerOnce = function(string) {
if (triggered) {
return;
}
let Ember;
try {
Ember = requireModule('ember')['default'];
} catch {
Ember = window.Ember;
}
if (!Ember) {
return;
}
// `Ember.Application` load hook triggers before all of Ember is ready.
// In this case we ignore and wait for the `Ember` load hook.
if (!Ember.RSVP) {
return;
}
triggered = true;
callback();
};
// Newest Ember versions >= 1.10
window.addEventListener('Ember', triggerOnce, false);
// Old Ember versions
window.addEventListener('Ember.Application', function() {
if (Ember && Ember.VERSION && compareVersion(Ember.VERSION, '1.10.0') === 1) {
// Ember >= 1.10 should be handled by `Ember` load hook instead.
return;
}
triggerOnce();
}, false);
// Oldest Ember versions or if this was injected after Ember has loaded.
onReady(triggerOnce);
}
// There's probably a better way
// to determine when the application starts
// but this definitely works
function onApplicationStart(callback) {
if (typeof Ember === 'undefined') {
return;
}
const adapterInstance = requireModule('ember-debug/adapters/' + currentAdapter)['default'].create();
adapterInstance.onMessageReceived(function(message) {
if (message.type === 'app-picker-loaded') {
sendApps(adapterInstance, getApplications());
}
if (message.type === 'app-selected') {
let current = Ember.EmberInspectorDebugger._application;
let selected = getApplications().find(app => Ember.guidFor(app) === message.applicationId);
if (current !== selected && selected.__deprecatedInstance__) {
bootEmberInspector(selected.__deprecatedInstance__);
}
}
});
var apps = getApplications();
sendApps(adapterInstance, apps);
var app;
for (var i = 0, l = apps.length; i < l; i++) {
app = apps[i];
// We check for the existance of an application instance because
// in Ember > 3 tests don't destroy the app when they're done but the app has no booted instances.
if (app._readinessDeferrals === 0) {
let instance = app.__deprecatedInstance__ || (app._applicationInstances && app._applicationInstances[0]);
if (instance) {
// App started
setupInstanceInitializer(app, callback);
callback(instance);
break;
}
}
}
Ember.Application.initializer({
name: 'ember-inspector-booted',
initialize: function(app) {
setupInstanceInitializer(app, callback);
}
});
}
function setupInstanceInitializer(app, callback) {
if (!app.__inspector__setup) {
app.__inspector__setup = true;
// We include the app's guid in the initializer name because in Ember versions < 3
// registering an instance initializer with the same name, even if on a different app,
// triggers an error because instance initializers seem to be global instead of per app.
app.instanceInitializer({
name: 'ember-inspector-app-instance-booted-' + Ember.guidFor(app),
initialize: function(instance) {
callback(instance);
}
});
}
}
/**
* Get all the Ember.Application instances from Ember.Namespace.NAMESPACES
* and add our own applicationId and applicationName to them
* @return {*}
*/
function getApplications() {
var namespaces = Ember.A(Ember.Namespace.NAMESPACES);
var apps = namespaces.filter(function(namespace) {
return namespace instanceof Ember.Application;
});
return apps.map(function(app) {
// Add applicationId and applicationName to the app
var applicationId = Ember.guidFor(app);
var applicationName = app.name || app.modulePrefix || `(unknown app - ${applicationId})`;
Object.assign(app, {
applicationId,
applicationName
});
return app;
});
}
let channel = new MessageChannel();
let port = channel.port1;
window.postMessage('debugger-client', '*', [channel.port2]);
let registeredMiss = false;
/**
* This function is called if the app's Ember version
* is not supported by this version of the inspector.
*
* It sends a message to the inspector app to redirect
* to an inspector version that supports this Ember version.
*/
function sendVersionMiss() {
if (registeredMiss) {
return;
}
registeredMiss = true;
port.addEventListener('message', message => {
if (message.type === 'check-version') {
sendVersionMismatch();
}
});
sendVersionMismatch();
port.start();
function sendVersionMismatch() {
port.postMessage({
name: 'version-mismatch',
version: Ember.VERSION,
from: 'inspectedWindow'
});
}
}
function sendApps(adapter, apps) {
const serializedApps = apps.map(app => {
return {
applicationName: app.applicationName,
applicationId: app.applicationId
}
});
adapter.sendMessage({
type: 'apps-loaded',
apps: serializedApps,
from: 'inspectedWindow'
});
}
/**
* Checks if a version is between two different versions.
* version should be >= left side, < right side
*
* @param {String} version1
* @param {String} version2
* @return {Boolean}
*/
function versionTest(version, between) {
var fromVersion = between[0];
var toVersion = between[1];
if (compareVersion(version, fromVersion) === -1) {
return false;
}
return !toVersion || compareVersion(version, toVersion) === -1;
}
function onReady(callback) {
if (document.readyState === 'complete' || document.readyState === 'interactive') {
setTimeout(completed);
} else {
document.addEventListener("DOMContentLoaded", completed, false);
// For some reason DOMContentLoaded doesn't always work
window.addEventListener("load", completed, false);
}
function completed() {
document.removeEventListener("DOMContentLoaded", completed, false);
window.removeEventListener("load", completed, false);
callback();
}
}
/**
* Compares two Ember versions.
*
* Returns:
* `-1` if version1 < version
* 0 if version1 == version2
* 1 if version1 > version2
*
* @param {String} version1
* @param {String} version2
* @return {Boolean} result of the comparison
*/
function compareVersion(version1, version2) {
let compared, i;
version1 = cleanupVersion(version1).split('.');
version2 = cleanupVersion(version2).split('.');
for (i = 0; i < 3; i++) {
compared = compare(+version1[i], +version2[i]);
if (compared !== 0) {
return compared;
}
}
return 0;
}
/**
* Remove -alpha, -beta, etc from versions
*
* @param {String} version
* @return {String} The cleaned up version
*/
function cleanupVersion(version) {
return version.replace(/-.*/g, '');
}
/**
* @method compare
* @param {Number} val
* @param {Number} number
* @return {Number}
* 0: same
* -1: <
* 1: >
*/
function compare(val, number) {
if (val === number) {
return 0;
} else if (val < number) {
return -1;
} else if (val > number) {
return 1;
}
}
}(currentAdapter));
|
import Ember from 'ember';
export default Ember.Component.extend({
questionCart: Ember.inject.service()
});
|
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
fileLoaded(file) {
this.set('data', file.data);
this.set('loaded', true);
this.set('name', file.name);
this.set('size', file.size);
}
},
data: null,
loaded: false,
name: null,
readAs: 'readAsFile',
readAsValues: [
'readAsFile',
'readAsArrayBuffer',
'readAsBinaryString',
'readAsDataUrl',
'readAsText'
],
size: null
});
|
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import { createLogger } from 'redux-logger';
import app from '../redux';
const configureStore = () => {
// only plain object reach createLogger middleware and then reducers
const middlewares = [thunk];
if (process.env.NODE_ENV !== 'production') {
middlewares.push(createLogger());
}
/* eslint-disable no-underscore-dangle */
const composeEnhancers =
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
/* eslint-enable */
return createStore(app, composeEnhancers(applyMiddleware(...middlewares)));
};
export default configureStore;
|
var fs2obj = require('../lib/');
var modules = fs2obj('./test/exampleFolder');
console.log(JSON.stringify(modules)); |
document.addEventListener("DOMContentLoaded", function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://service.yokunaine.mzyy94.com/api/v1/statistics/dislike", true);
xhr.responseType = "json";
xhr.onload = function(e) {
if (xhr.status === 200) {
document.getElementById("total").innerText = xhr.response.total;
}
}
xhr.send();
var dlLink = document.getElementById("download");
if (window.chrome && chrome.webstore && typeof chrome.webstore.install === "function") {
dlLink.addEventListener("click", function() {
chrome.webstore.install();
}, false);
} else {
dlLink.href = "https://chrome.google.com/webstore/detail/fceocghaogpidgglkglhdadcaechdeln";
}
}, false);
|
import Popper from '@vusion/popper.js';
import MEmitter from '../m-emitter.vue';
import ev from '../../utils/event';
import single from '../../utils/event/single';
export const MPopper = {
name: 'm-popper',
mixins: [MEmitter],
isPopper: true,
props: {
opened: { type: Boolean, default: false },
trigger: { type: String, default: 'click' },
triggerElement: { type: [String, HTMLElement, Function], default: 'reference' },
reference: { type: [String, HTMLElement, Function], default: 'context-parent', validator: (value) => {
if (typeof value !== 'string')
return true;
else
return ['parent', '$parent', 'context-parent', 'prev', 'next'].includes(value);
} },
placement: {
type: String, default: 'bottom-start',
validator: (value) => /^(top|bottom|left|right)(-start|-end)?$/.test(value),
},
hoverDelay: { type: Number, default: 0 },
hideDelay: { type: Number, default: 0 },
appendTo: { type: String, default: 'body', validator: (value) => ['body', 'reference'].includes(value) },
boundariesElement: { default: 'window' },
arrowElement: { type: String, default: '[u-arrow]' },
escapeWithReference: { type: Boolean, default: true },
followCursor: { type: [Boolean, Number, Object], default: false },
offset: { type: [Number, String], default: 0 },
options: {
type: Object,
default() {
return {
modifiers: {},
};
},
},
disabled: { type: Boolean, default: false },
},
data() {
return {
currentOpened: this.opened,
referenceEl: undefined,
triggers: [], // 所有的触发器,为了方便,第一项始终为默认的
// popper: undefined,
// 在出现滚动条的时候 需要特殊处理下
offEvents: [],
};
},
computed: {
currentFollowCursor() {
if (typeof this.followCursor === 'object')
return this.followCursor;
else {
let followCursor;
if (typeof this.followCursor === 'boolean')
followCursor = { offsetX: 10, offsetY: 10 };
else if (typeof this.followCursor === 'number')
followCursor = { offsetX: this.followCursor, offsetY: this.followCursor };
if (this.placement.startsWith('top'))
followCursor.offsetY = -followCursor.offsetY;
if (this.placement.startsWith('left'))
followCursor.offsetX = -followCursor.offsetX;
if (this.placement === 'top' || this.placement === 'bottom')
followCursor.offsetX = 0;
if (this.placement === 'top-end' || this.placement === 'bottom-end')
followCursor.offsetX = -followCursor.offsetX;
if (this.placement === 'left' || this.placement === 'right')
followCursor.offsetY = 0;
if (this.placement === 'left-end' || this.placement === 'right-end')
followCursor.offsetY = -followCursor.offsetY;
return followCursor;
}
},
},
watch: {
opened(opened) {
this.currentOpened = opened;
},
currentOpened(currentOpened) {
// 不直接用样式的显隐,而是用 popper 的 create 和 destroy,是因为 popper 有可能是从不同的地方触发的,reference 对象会变
if (currentOpened) {
this.createPopper();
this.$emit('open', undefined, this);
} else {
this.destroyPopper();
this.$emit('close', undefined, this);
}
},
reference() {
/**
* 问题:现在的 popper 不支持动态改变 reference,导致 popper 的位置显示有问题
* 解决方法:暂时在 popper.js 文档中未找到理想的解决方案,采取先删除 popper,再新创建 popper 的方法修复位置问题,
* 后面需要研究下 popper.js 的源码
*/
this.destroyPopper();
this.referenceEl = this.getReferenceEl();
this.createPopper();
},
},
mounted() {
// 字符串类型的 reference 只有首次获取是有效的,因为之后节点会被插到别的地方
this.referenceEl = this.getReferenceEl();
const triggerEl = this.getTriggerEl(this.referenceEl);
this.addTrigger(triggerEl, this.trigger);
this.currentOpened && this.createPopper();
},
beforeDestroy() {
this.destroyPopper();
// 取消绑定事件
this.offEvents.forEach((off) => off());
this.timers.forEach((timer) => {
clearTimeout(timer);
});
},
methods: {
getOptions() {
const options = Object.assign({}, this.options, {
placement: this.placement,
});
// 自定义options 传入offset值情况
if (!options.modifiers.offset && this.offset) {
options.modifiers.offset = {
offset: this.offset,
};
}
options.escapeWithReference = this.escapeWithReference;
options.modifiers.arrow = { element: this.arrowElement };
options.modifiers.preventOverflow = { boundariesElement: this.boundariesElement };
return options;
},
getReferenceEl() {
if (this.reference instanceof HTMLElement)
return this.reference;
else if (this.reference instanceof Function)
return this.reference(this.$el);
else if (this.$el) {
if (this.reference === 'parent')
return this.$el.parentElement;
else if (this.reference === '$parent')
return this.$parent.$el;
else if (this.reference === 'context-parent') {
// 求上下文中的 parent
if (this.$parent === this.$vnode.context)
return this.$el.parentElement;
// Vue 的 vnode.parent 没有连接起来,需要自己找,不知道有没有更好的方法
let parentVNode = this.$parent._vnode;
while (parentVNode && !parentVNode.children.includes(this.$vnode))
parentVNode = parentVNode.children.find((child) => child.elm.contains(this.$el));
// if (!parentVNode)
if (parentVNode.context === this.$vnode.context)
return parentVNode.elm;
// 否则,找第一个上下文一致的组件
let parentVM = this.$parent;
while (parentVM && parentVM.$vnode.context !== this.$vnode.context)
parentVM = parentVM.$parent;
return parentVM.$el;
} else if (this.reference === 'prev')
return this.$el.previousElementSibling;
else if (this.reference === 'next')
return this.$el.nextElementSibling;
}
},
getTriggerEl(referenceEl) {
if (this.triggerElement === 'reference')
return referenceEl;
else if (this.triggerElement instanceof HTMLElement)
return this.triggerElement;
else if (this.triggerElement instanceof Function)
return this.triggerElement(referenceEl);
},
/**
* 添加触发器时,绑定事件
*/
addTrigger(el, event) {
const popperEl = this.$el;
// @TODO: support directives
const arr = event.split('.');
event = arr[0];
this.triggers.push({ el, event });
// 收集 setTimeout
this.timers = this.timers || [];
// 绑定事件
this.followCursor && this.offEvents.push(
single.on('m-popper-proto', {
el,
self: this,
}, document, 'mousemove', (e, datas) => {
Object.values(datas).forEach(({ el, self }) => {
self.updatePositionByCursor(e, el);
});
})
);
if (event === 'click')
this.offEvents.push(ev.on(el, 'click', (e) => {
if (arr[1] === 'stop')
e.stopPropagation();
else if (arr[1] === 'prevent')
e.preventDefault();
this.toggle();
this.followCursor && this.$nextTick(() => this.updatePositionByCursor(e, el));
}));
else if (event === 'hover') {
let timer;
this.offEvents.push(ev.on(el, 'mouseenter', (e) => {
timer = clearTimeout(timer);
this.timers[0] = setTimeout(() => {
this.open();
this.followCursor && this.$nextTick(() => this.updatePositionByCursor(e, el));
}, this.hoverDelay);
}));
this.offEvents.push(
single.on('m-popper-proto', {
self: this,
el,
popperEl,
timer,
}, document, 'mousemove', (e, datas) => {
Object.values(datas).forEach(({ el, popperEl, self, timer }) => {
if (self.currentOpened && !timer && !el.contains(e.target) && !popperEl.contains(e.target)) {
self.timers[1] = setTimeout(() => self.close(), self.hideDelay);
}
});
})
);
} else if (event === 'double-click')
this.offEvents.push(ev.on(el, 'dblclick', (e) => {
this.toggle();
this.followCursor && this.$nextTick(() => this.updatePositionByCursor(e, el));
}));
else if (event === 'right-click') {
this.offEvents.push(ev.on(el, 'contextmenu', (e) => {
e.preventDefault();
this.toggle();
this.followCursor && this.$nextTick(() => this.updatePositionByCursor(e, el));
}));
}
// @TODO: 有没有必要搞 focus-in
this.offEvents.push(
single.on('m-popper-proto', {
el,
popperEl,
self: this,
}, document, 'mousedown', (e, datas) => {
Object.values(datas).forEach(({ el, popperEl, self }) => {
!el.contains(e.target) && !popperEl.contains(e.target) && self.close();
});
})
);
},
createPopper() {
const referenceEl = this.referenceEl;
const popperEl = this.$el;
if (this.appendTo === 'body')
document.body.appendChild(popperEl);
else if (this.appendTo === 'reference')
referenceEl.appendChild(popperEl);
const options = this.getOptions();
this.popper = new Popper(referenceEl, popperEl, options);
},
update() {
this.popper && this.popper.update();
},
scheduleUpdate() {
this.popper && this.popper.scheduleUpdate();
},
destroyPopper() {
const referenceEl = this.referenceEl;
const popperEl = this.$el;
if (this.appendTo === 'body')
popperEl.parentElement === document.body && document.body.removeChild(popperEl);
else if (this.appendTo === 'reference')
popperEl.parentElement === referenceEl && referenceEl.removeChild(popperEl);
this.popper && this.popper.destroy();
this.popper = undefined;
},
updatePositionByCursor(e, el) {
// @TODO: 两种 offset 属性有些冗余
if (e.target !== el || !this.popper)
return;
const top = e.clientY + this.currentFollowCursor.offsetY;
const left = e.clientX + this.currentFollowCursor.offsetX;
const right = e.clientX + this.currentFollowCursor.offsetX;
const bottom = e.clientY + this.currentFollowCursor.offsetY;
this.popper.reference = {
getBoundingClientRect: () => ({
width: 0,
height: 0,
top,
left,
right,
bottom,
}),
clientWidth: 0,
clientHeight: 0,
};
this.popper.scheduleUpdate();
},
open() {
// Check if enabled
if (this.disabled)
return;
// Prevent replication
if (this.currentOpened)
return;
// Emit a `before-` event with preventDefault()
if (this.$emitPrevent('before-open', undefined, this))
return;
// Assign and sync `opened`
this.currentOpened = true;
this.$emit('update:opened', true, this);
// Emit `after-` events
// this.$emit('open', undefined, this);
},
close() {
// Check if enabled
if (this.disabled)
return;
// Prevent replication
if (!this.currentOpened)
return;
// Emit a `before-` event with preventDefault()
if (this.$emitPrevent('before-close', undefined, this))
return;
// Assign and sync `opened`
this.currentOpened = false;
this.$emit('update:opened', false, this);
// Emit `after-` events
// this.$emit('close', undefined, this);
},
toggle(opened) {
// Method overloading
if (opened === undefined)
opened = !this.currentOpened;
// @deprecated start
if (this.disabled)
return;
const oldOpened = this.currentOpened;
if (opened === oldOpened)
return;
if (this.$emitPrevent('before-toggle', { opened }, this))
return;
opened ? this.open() : this.close();
this.$emit('toggle', { opened }, this);
// @deprecated end
},
},
};
export default MPopper;
|
var eventName = typeof(Turbolinks) !== 'undefined' ? 'turbolinks:load' : 'DOMContentLoaded';
if (!document.documentElement.hasAttribute("data-turbolinks-preview")) {
document.addEventListener(eventName, function flash() {
var flashData = JSON.parse(document.getElementById('shopify-app-flash').dataset.flash);
var Toast = window['app-bridge'].actions.Toast;
if (flashData.notice) {
Toast.create(app, {
message: flashData.notice,
duration: 5000,
}).dispatch(Toast.Action.SHOW);
}
if (flashData.error) {
Toast.create(app, {
message: flashData.error,
duration: 5000,
isError: true,
}).dispatch(Toast.Action.SHOW);
}
});
}
|
import DES from './DES';
let d = new DES('qwertyui');
// let cipher = d.encrypt64bit('heleo we')
// console.log(cipher);
// let decipheredBits = d.decrypt64bit(cipher, true);
// console.log(decipheredBits.length);
// console.log(decipheredBits);
let cipher = d.encrypt('hello world!');
// console.log(cipher);
let deciphered = d.decrypt(cipher, true);
console.log(deciphered);
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import _find from 'lodash/find';
import _isEmpty from 'lodash/isEmpty';
import { slate } from 'utils';
import permission from 'utils/privileges';
// STORE
import { editArticle, removeArticle } from 'redux/modules/articlesModule';
import { submitComment } from 'redux/modules/conversationModule';
// COMPONENTS
import { Conversation } from 'containers';
import { PlainTextEditor, RichTextEditor, CommentEditor } from 'components';
import { Link } from 'react-router';
// LAYOUT
import Grid from 'react-bootstrap/lib/Grid';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import FlatButton from 'material-ui/FlatButton';
import { ArticleHeader, List, Div } from 'components/styled';
import styles from './ArticlePage.scss';
const mappedState = ({ articles, auth }, props) => ({
article: _find(articles.all, art => props.params.id === `${art.id}`),
editingArticle: articles.editingArticle,
articleEdited: articles.articleEdited,
removingArticle: articles.removingArticle,
loggedIn: auth.loggedIn,
permissions: permission(auth.user)
});
const mappedActions = {
editArticle,
removeArticle,
submitComment,
redirect: push
};
@connect(mappedState, mappedActions)
export default class ArticlePage extends Component {
static propTypes = {
article: PropTypes.object,
params: PropTypes.object.isRequired,
editingArticle: PropTypes.bool.isRequired,
articleEdited: PropTypes.bool.isRequired,
removingArticle: PropTypes.number,
editArticle: PropTypes.func.isRequired,
removeArticle: PropTypes.func.isRequired,
submitComment: PropTypes.func.isRequired,
redirect: PropTypes.func.isRequired,
loggedIn: PropTypes.bool.isRequired,
permissions: PropTypes.object.isRequired
}
state = {
editingMode: false,
article: this.prepareArticle(this.props.article),
validationErrors: {
title: '',
description: '',
content: ''
}
}
componentDidMount() {
const { article = {}, params = {} } = this.props;
// TODO: move it to "onEnter"?
this.checkSlugAndRedirect(article.slug, params.slug, article.id);
}
componentWillReceiveProps(nextProps) {
const { article = {}, params = {} } = nextProps;
this.checkSlugAndRedirect(article.slug, params.slug, article.id);
// When article was successfully updated...
if (nextProps.articleEdited !== this.props.articleEdited) {
this.setState({
editingMode: false,
article: this.prepareArticle(article)
});
}
}
checkSlugAndRedirect = (articleSlug, paramsSlug, articleId) => {
if ((articleSlug && articleId) && articleSlug !== paramsSlug ) {
this.props.redirect(`/article/${articleId}/${articleSlug}`);
}
}
// Prepares article content to use Slate's state objects
prepareArticle(article) {
if (!article) return {};
return {
...article,
content: _isEmpty(article.content) ? {} : slate.objectToState(article.content),
description: slate.textToState(article.description),
link: slate.textToState(article.link),
title: slate.textToState(article.title)
};
}
// EDITING ARTICLE
// Updates state of the article
change = (property) => (value) => {
const article = { ...this.state.article };
const validationErrors = { ...this.state.validationErrors };
// Update article
article[property] = value;
// Hide existing validation error
if (validationErrors[property] && value) validationErrors[property] = '';
this.setState({ article, validationErrors });
}
toggleEditMode = () => {
this.setState({ editingMode: !this.state.editingMode });
}
cancelEditing = () => {
this.setState({
editingMode: false,
article: this.prepareArticle(this.props.article)
});
}
validateArticle = (articleData) => {
const { title, description } = articleData;
const validationErrors = {};
if (!title) validationErrors.title = 'Title is required';
if (!description) validationErrors.description = 'Description is required';
this.setState({ validationErrors });
return _isEmpty(validationErrors);
}
// API CALLS
saveEdits = () => {
const article = { ...this.state.article };
if (!this.validateArticle(article)) return;
if (!_isEmpty(article.content)) article.content = slate.stateToObject(article.content);
if (!_isEmpty(article.plainText)) article.plainText = slate.stateToText(article.content);
if (!_isEmpty(article.description)) article.description = slate.stateToText(article.description);
if (!_isEmpty(article.title)) article.title = slate.stateToText(article.title);
if (!_isEmpty(article.link)) article.link = slate.stateToText(article.link);
this.props.editArticle(article);
}
removeArticle = () => {
this.props.removeArticle(this.props.article.id);
}
// RENDERING
renderTitleEditor = () => (
<PlainTextEditor
state={this.state.article.title}
onChange={this.change('title')}
readOnly={!this.state.editingMode}
style={{ fontSize: 20 }}
/>
)
renderLinkEditor = () => (
<PlainTextEditor
state={this.state.article.link}
onChange={this.change('link')}
readOnly={!this.state.editingMode}
style={{ fontSize: 20 }}
/>
)
renderDescriptionEditor = () => (
<PlainTextEditor
state={this.state.article.description}
onChange={this.change('description')}
readOnly={!this.state.editingMode}
style={{ fontSize: 20, margin: '20px 0 24px' }}
/>
)
renderContentEditor = () => (
<RichTextEditor
state={this.state.article.content}
onChange={this.change('content')}
readOnly={!this.state.editingMode}
style={{ width: '100%', fontSize: 20 }}
/>
)
renderEditButton = () => {
if (!this.props.loggedIn || !this.props.permissions.isStaff) return null;
const { editingMode } = this.state;
return (
<FlatButton
label={editingMode ? 'Cancel' : 'Edit'}
primary={!editingMode}
secondary={editingMode}
onTouchTap={editingMode ? this.cancelEditing : this.toggleEditMode}
/>
);
}
renderDeleteButton = () => {
if (!this.props.loggedIn || this.state.editingMode || !this.props.permissions.isStaff) return null;
return (
<FlatButton
label={this.props.removingArticle ? 'Deleting...' : 'Delete'}
secondary
onTouchTap={this.removeArticle}
disabled={this.props.removingArticle !== null}
/>
);
}
renderSaveButton = () => {
if (!this.state.editingMode) return null;
return (
<FlatButton
label={this.props.editingArticle ? 'Saving...' : 'Save'}
primary
onTouchTap={this.saveEdits}
/>
);
}
renderCoverEditor = () => {
if (this.state.editingMode) {
return (
<div style={{ marginTop: 20 }}>
Image URL:
<PlainTextEditor
state={slate.textToState(this.state.article.coverImageUrl)}
onChange={this.change('coverImageUrl')}
placeholder="Cover image URL"
/>
</div>
);
}
return this.state.article.coverImageUrl &&
<img className={styles.coverImagePreview} src={this.state.article.coverImageUrl} />;
}
render = () => {
const { article } = this.props;
if (!article) return null;
const isExternal = article.type === 'external';
return (
<Grid style={{ height: '100%' }}>
<Div flex column fullHeight>
<Div flexNone>
<ArticleHeader>
{this.renderTitleEditor()}
<List right>
{this.renderSaveButton()}
{this.renderEditButton()}
</List>
</ArticleHeader>
{this.renderDescriptionEditor()}
{isExternal && this.renderLinkEditor()}
{!isExternal && this.renderContentEditor()}
{this.renderCoverEditor()}
<List right>
{this.renderDeleteButton()}
</List>
{this.props.loggedIn ?
<Row>
<Col sm={12} md={8}>
<h3>Add a comment:</h3>
<CommentEditor articleId={article.id} />
</Col>
</Row> :
<Row>
<Col sm={12} md={8}>
<h3>Please <Link to="/login">login</Link> to add your comments</h3>
</Col>
</Row>
}
</Div>
<Conversation articleId={article.id} />
</Div>
</Grid>
);
}
}
|
(function (cf, test) {
var fakeYellowPlayer;
QUnit.module("Slots", {
beforeEach: function() {
fakeYellowPlayer = {};
}
});
test("Can create default slot", function(assert) {
var slot = new cf.Slot();
assert.ok(!!slot);
});
test("Default slots are empty", function(assert) {
var slot = new cf.Slot();
assert.strictEqual(slot.isEmpty(), true);
});
test("Slot can be taken by player", function(assert) {
var slot = new cf.Slot();
slot.setPlayer(fakeYellowPlayer);
assert.strictEqual(slot.getPlayer(), fakeYellowPlayer);
});
test("Taking a slot makes it non empty", function(assert) {
var slot = new cf.Slot();
slot.setPlayer(fakeYellowPlayer);
assert.strictEqual(slot.isEmpty(), false);
});
test("Clearing a taken slot makes it empty", function(assert) {
var slot = new cf.Slot();
slot.setPlayer(fakeYellowPlayer);
slot.clear();
assert.strictEqual(slot.isEmpty(), true);
});
test("Slot state change event will fire on setPlayer", function(assert) {
var slot = new cf.Slot();
slot.addChangeEventHandler(function(_) {
assert.ok(true);
});
assert.expect(1);
slot.setPlayer(fakeYellowPlayer);
});
test("Slot state change event will NOT fire on setPlayer if player is unchanged", function(assert) {
var slot = new cf.Slot();
slot.addChangeEventHandler(function(_) {
assert.ok(true);
});
assert.expect(1); // And only 1!
slot.setPlayer(fakeYellowPlayer);
slot.setPlayer(fakeYellowPlayer);
});
test("Slot state change event will fire on clear", function(assert) {
var slot = new cf.Slot();
slot.addChangeEventHandler(function(_) {
assert.ok(true);
});
assert.expect(2);
slot.setPlayer(fakeYellowPlayer);
slot.clear();
});
test("Slot state change event will NOT fire on clear if cell isEmpty", function(assert) {
var slot = new cf.Slot();
slot.addChangeEventHandler(function(_) {
assert.ok(true);
});
assert.expect(0);
slot.clear();
});
}(window.ConnectFour = window.ConnectFour || {}, QUnit.test)); |
export const CHANGE_LIST = 'CHANGE_LIST' |
//////////////////////////////////////////////////////
// Collection Hooks //
//////////////////////////////////////////////////////
/**
* Generate HTML body from Markdown on user bio insert
*/
Users.after.insert(function (userId, user) {
// run create user async callbacks
Telescope.callbacks.runAsync("onCreateUserAsync", user);
// check if all required fields have been filled in. If so, run profile completion callbacks
if (Users.hasCompletedProfile(user)) {
Telescope.callbacks.runAsync("profileCompletedAsync", user);
}
});
/**
* Generate HTML body from Markdown when user bio is updated
*/
Users.before.update(function (userId, doc, fieldNames, modifier) {
// if bio is being modified, update htmlBio too
if (Meteor.isServer && modifier.$set && modifier.$set["telescope.bio"]) {
modifier.$set["telescope.htmlBio"] = Telescope.utils.sanitize(marked(modifier.$set["telescope.bio"]));
}
});
/**
* Disallow $rename
*/
Users.before.update(function (userId, doc, fieldNames, modifier) {
if (!!modifier.$rename) {
throw new Meteor.Error("illegal $rename operator detected!");
}
});
/**
* If user.telescope.email has changed, check for existing emails and change user.emails and email hash if needed
*/
if (Meteor.isServer) {
Users.before.update(function (userId, doc, fieldNames, modifier) {
var user = doc;
// if email is being modified, update user.emails too
if (Meteor.isServer && modifier.$set && modifier.$set["telescope.email"]) {
var newEmail = modifier.$set["telescope.email"];
// check for existing emails and throw error if necessary
var userWithSameEmail = Users.findByEmail(newEmail);
if (userWithSameEmail && userWithSameEmail._id !== doc._id) {
throw new Meteor.Error("email_taken2", i18n.t("this_email_is_already_taken") + " (" + newEmail + ")");
}
// if user.emails exists, change it too
if (!!user.emails) {
user.emails[0].address = newEmail;
modifier.$set.emails = user.emails;
}
// update email hash
//modifier.$set["telescope.emailHash"] = Gravatar.hash(newEmail);
}
});
}
//////////////////////////////////////////////////////
// Callbacks //
//////////////////////////////////////////////////////
/**
* Set up user object on creation
* @param {Object} user – the user object being iterated on and returned
* @param {Object} options – user options
*/
function setupUser (user, options) {
// ------------------------------ Properties ------------------------------ //
var userProperties = {
profile: options.profile || {},
telescope: {
karma: 0,
isInvited: false,
postCount: 0,
commentCount: 0,
invitedCount: 0,
upvotedPosts: [],
downvotedPosts: [],
upvotedComments: [],
downvotedComments: []
}
};
user = _.extend(user, userProperties);
// look in a few places for the user email
if (options.email) {
user.telescope.email = options.email;
} else if (user.services['meteor-developer'] && user.services['meteor-developer'].emails) {
user.telescope.email = _.findWhere(user.services['meteor-developer'].emails, { primary: true }).address;
} else if (user.services.facebook && user.services.facebook.email) {
user.telescope.email = user.services.facebook.email;
} else if (user.services.github && user.services.github.email) {
user.telescope.email = user.services.github.email;
} else if (user.services.google && user.services.google.email) {
user.telescope.email = user.services.google.email;
}
// generate email hash
/*
if (!!user.telescope.email) {
user.telescope.emailHash = Gravatar.hash(user.telescope.email);
}*/
// look in a few places for the displayName
if (user.profile.username) {
user.telescope.displayName = user.profile.username;
} else if (user.profile.name) {
user.telescope.displayName = user.profile.name;
} else {
user.telescope.displayName = user.username;
}
// create slug from display name
user.telescope.slug = Telescope.utils.slugify(user.telescope.displayName);
// if this is not a dummy account, and is the first user ever, make them an admin
user.isAdmin = (!user.profile.isDummy && Meteor.users.find({'profile.isDummy': {$ne: true}}).count() === 0) ? true : false;
Events.track('new user', {username: user.username, email: user.telescope.email});
return user;
}
Telescope.callbacks.add("onCreateUser", setupUser);
function hasCompletedProfile (user) {
return Users.hasCompletedProfile(user);
}
Telescope.callbacks.add("profileCompletedChecks", hasCompletedProfile);
|
import actionsHandlers, {
setActiveCalculatedVariables,
updateActiveCalculatedVariables,
} from './active-calculated-variables-by-id';
import { SET_ACTIVE_VARIABLES } from 'actions/app-state';
import { CREATE_COMPONENT, UPDATE_COMPONENT } from 'actions/component';
describe('setActiveCalculatedVariables', () => {
test('when called directly', () => {
const result = setActiveCalculatedVariables(
{ state: 'previous' },
{ activeCalculatedVariablesById: 'activeCalculatedVariablesById' },
);
expect(result).toEqual('activeCalculatedVariablesById');
});
test('when called when we trigger SET_ACTIVE_VARIABLES', () => {
const result = actionsHandlers(
{ state: 'previous' },
{
type: SET_ACTIVE_VARIABLES,
payload: {
activeCalculatedVariablesById: 'activeCalculatedVariablesById',
},
},
);
expect(result).toEqual('activeCalculatedVariablesById');
});
});
describe('setActiveCalculatedVariables', () => {
test('when called directly', () => {
const result = updateActiveCalculatedVariables(
{ state: 'previous' },
{
update: {
activeCalculatedVariablesById: 'activeCalculatedVariablesById',
},
},
);
expect(result).toEqual('activeCalculatedVariablesById');
});
[CREATE_COMPONENT, UPDATE_COMPONENT].forEach(action => {
test(`when called when we trigger ${action}`, () => {
const result = actionsHandlers(
{ state: 'previous' },
{
type: action,
payload: {
update: {
activeCalculatedVariablesById: 'activeCalculatedVariablesById',
},
},
},
);
expect(result).toEqual('activeCalculatedVariablesById');
});
});
});
|
/*
* grunt-static-i18next
*
*
* Copyright (c) 2014 Stas Yermakov
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
// load all npm grunt tasks
require('load-grunt-tasks')(grunt);
// Project configuration.
grunt.initConfig({
yeoman: {
// configurable paths
tasks: 'tasks',
src: 'src',
dist: 'dist',
test_app: 'test/fixtures/app'
},
watch: {
gruntfile: {
files: ['Gruntfile.js']
},
typescript: {
files: ["<%= yeoman.src %>/**/*.ts"],
tasks: ["typescript", "test"]
}
},
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>'
],
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
}
},
// Unit tests.
nodeunit: {
tests: ['test/*_test.js']
},
// Compile TypeScript source codes
typescript: {
dist: {
src: ['<%= yeoman.src %>/**/*.ts'],
dest: '<%= yeoman.tasks %>',
options: {
expand: true,
target: 'es5', //or es3
rootDir: '<%= yeoman.src %>/',
sourceMap: false,
declaration: false,
module: 'commonjs'
}
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [
{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/*',
'!<%= yeoman.dist %>/.git*'
]
}
]
},
server: '.tmp'
},
// Run some tasks in parallel to speed up the build process
concurrent: {
server: [
'typescript'
],
test: [
'typescript'
],
dist: [
'typescript'
]
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
grunt.registerTask('serve', function (target) {
grunt.task.run([
'clean:server',
'concurrent:server',
'watch'
]);
});
// Whenever the "test" task is run, first clean the ".tmp" dir, then run this
// plugin's task(s), then test the result.
grunt.registerTask('test', ['clean', 'nodeunit']);
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint', 'test']);
};
|
var helper = require("../../../helper");
var sqlHelper = require("../../../sql-helper");
var Manager = require("../../../../src/etl/dim/dim-staff-etl-manager");
var instanceManager = null;
var should = require("should");
before("#00. connect db", function (done) {
Promise.all([helper, sqlHelper])
.then((result) => {
var db = result[0];
var sql = result[1];
db.getDb().then((db) => {
instanceManager = new Manager(db, {
username: "unit-test"
}, sql);
done();
})
.catch((e) => {
done(e);
})
});
});
it("#01. should success when run etl dim staff", function (done) {
instanceManager.run()
.then(() => {
done();
})
.catch((e) => {
console.log(e);
done(e);
});
}); |
/*global createRegistryWrapper:true, cloneEvents: true */
function createErrorMessage(code) {
return 'Error "' + code + '". For more information visit http://thoraxjs.org/error-codes.html' + '#' + code;
}
function createRegistryWrapper(klass, hash) {
var $super = klass.extend;
klass.extend = function() {
var child = $super.apply(this, arguments);
if (child.prototype.name) {
hash[child.prototype.name] = child;
}
return child;
};
}
function registryGet(object, type, name, ignoreErrors) {
var target = object[type],
value;
if (_.indexOf(name, '.') >= 0) {
var bits = name.split(/\./);
name = bits.pop();
_.each(bits, function(key) {
target = target[key];
});
}
target && (value = target[name]);
if (!value && !ignoreErrors) {
throw new Error(type + ': ' + name + ' does not exist.');
} else {
return value;
}
}
function assignView(attributeName, options) {
var ViewClass;
// if attribute is the name of view to fetch
if (_.isString(this[attributeName])) {
ViewClass = Thorax.Util.getViewClass(this[attributeName], true);
// else try and fetch the view based on the name
} else if (this.name && !_.isFunction(this[attributeName])) {
ViewClass = Thorax.Util.getViewClass(this.name + (options.extension || ''), true);
}
// if we found something, assign it
if (ViewClass && !_.isFunction(this[attributeName])) {
this[attributeName] = ViewClass;
}
// if nothing was found and it's required, throw
if (options.required && !_.isFunction(this[attributeName])) {
throw new Error('View ' + (this.name || this.cid) + ' requires: ' + attributeName);
}
}
function assignTemplate(attributeName, options) {
var template;
// if attribute is the name of template to fetch
if (_.isString(this[attributeName])) {
template = Thorax.Util.getTemplate(this[attributeName], true);
// else try and fetch the template based on the name
} else if (this.name && !_.isFunction(this[attributeName])) {
template = Thorax.Util.getTemplate(this.name + (options.extension || ''), true);
}
// CollectionView and LayoutView have a defaultTemplate that may be used if none
// was found, regular views must have a template if render() is called
if (!template && attributeName === 'template' && this._defaultTemplate) {
template = this._defaultTemplate;
}
// if we found something, assign it
if (template && !_.isFunction(this[attributeName])) {
this[attributeName] = template;
}
// if nothing was found and it's required, throw
if (options.required && !_.isFunction(this[attributeName])) {
throw new Error('View ' + (this.name || this.cid) + ' requires: ' + attributeName);
}
}
// getValue is used instead of _.result because we
// need an extra scope parameter, and will minify
// better than _.result
function getValue(object, prop, scope) {
if (!(object && object[prop])) {
return null;
}
return _.isFunction(object[prop])
? object[prop].call(scope || object)
: object[prop];
}
var inheritVars = {};
function createInheritVars(self) {
// Ensure that we have our static event objects
_.each(inheritVars, function(obj) {
if (!self[obj.name]) {
self[obj.name] = [];
}
});
}
function resetInheritVars(self) {
// Ensure that we have our static event objects
_.each(inheritVars, function(obj) {
self[obj.name] = [];
});
}
function walkInheritTree(source, fieldName, isStatic, callback) {
var tree = [];
if (_.has(source, fieldName)) {
tree.push(source);
}
var iterate = source;
if (isStatic) {
while (iterate = iterate.__parent__) {
if (_.has(iterate, fieldName)) {
tree.push(iterate);
}
}
} else {
iterate = iterate.constructor;
while (iterate) {
if (iterate.prototype && _.has(iterate.prototype, fieldName)) {
tree.push(iterate.prototype);
}
iterate = iterate.__super__ && iterate.__super__.constructor;
}
}
var i = tree.length;
while (i--) {
_.each(getValue(tree[i], fieldName, source), callback);
}
}
function objectEvents(target, eventName, callback, context) {
if (_.isObject(callback)) {
var spec = inheritVars[eventName];
if (spec && spec.event) {
if (target && target.listenTo && target[eventName] && target[eventName].cid) {
addEvents(target, callback, context, eventName);
} else {
addEvents(target['_' + eventName + 'Events'], callback, context);
}
return true;
}
}
}
// internal listenTo function will error on destroyed
// race condition
function listenTo(object, target, eventName, callback, context) {
// getEventCallback will resolve if it is a string or a method
// and return a method
var callbackMethod = getEventCallback(callback, object),
destroyedCount = 0;
function eventHandler() {
if (object.el) {
callbackMethod.apply(context, arguments);
} else {
// If our event handler is removed by destroy while another event is processing then we
// we might see one latent event percolate through due to caching in the event loop. If we
// see multiple events this is a concern and a sign that something was not cleaned properly.
if (destroyedCount) {
throw new Error('destroyed-event:' + object.name + ':' + eventName);
}
destroyedCount++;
}
}
eventHandler._callback = callbackMethod._callback || callbackMethod;
eventHandler._thoraxBind = true;
object.listenTo(target, eventName, eventHandler);
}
function addEvents(target, source, context, listenToObject) {
function addEvent(callback, eventName) {
if (listenToObject) {
listenTo(target, target[listenToObject], eventName, callback, context || target);
} else {
target.push([eventName, callback, context]);
}
}
_.each(source, function(callback, eventName) {
if (_.isArray(callback)) {
_.each(callback, function(cb) {
addEvent(cb, eventName);
});
} else {
addEvent(callback, eventName);
}
});
}
function getOptionsData(options) {
if (!options || !options.data) {
throw new Error(createErrorMessage('handlebars-no-data'));
}
return options.data;
}
// In helpers "tagName" or "tag" may be specified, as well
// as "class" or "className". Normalize to "tagName" and
// "className" to match the property names used by Backbone
// jQuery, etc. Special case for "className" in
// Thorax.Util.tag: will be rewritten as "class" in
// generated HTML.
function normalizeHTMLAttributeOptions(options) {
if (options.tag) {
options.tagName = options.tag;
delete options.tag;
}
if (options['class']) {
options.className = options['class'];
delete options['class'];
}
}
Thorax.Util = {
getViewInstance: function(name, attributes) {
var ViewClass = Thorax.Util.getViewClass(name, true);
return ViewClass ? new ViewClass(attributes || {}) : name;
},
getViewClass: function(name, ignoreErrors) {
if (_.isString(name)) {
return registryGet(Thorax, 'Views', name, ignoreErrors);
} else if (_.isFunction(name)) {
return name;
} else {
return false;
}
},
getTemplate: function(file, ignoreErrors) {
//append the template path prefix if it is missing
var pathPrefix = Thorax.templatePathPrefix,
template;
if (pathPrefix && file.substr(0, pathPrefix.length) !== pathPrefix) {
file = pathPrefix + file;
}
// Without extension
file = file.replace(/\.handlebars$/, '');
template = Handlebars.templates[file];
if (!template) {
// With extension
file = file + '.handlebars';
template = Handlebars.templates[file];
}
if (!template && !ignoreErrors) {
throw new Error('templates: ' + file + ' does not exist.');
}
return template;
},
//'selector' is not present in $('<p></p>')
//TODO: investigage a better detection method
is$: function(obj) {
return _.isObject(obj) && ('length' in obj);
},
expandToken: function(input, scope) {
if (input && input.indexOf && input.indexOf('{{') >= 0) {
var re = /(?:\{?[^{]+)|(?:\{\{([^}]+)\}\})/g,
match,
ret = [];
function deref(token, scope) {
if (token.match(/^("|')/) && token.match(/("|')$/)) {
return token.replace(/(^("|')|('|")$)/g, '');
}
var segments = token.split('.'),
len = segments.length;
for (var i = 0; scope && i < len; i++) {
if (segments[i] !== 'this') {
scope = scope[segments[i]];
}
}
return scope;
}
while (match = re.exec(input)) {
if (match[1]) {
var params = match[1].split(/\s+/);
if (params.length > 1) {
var helper = params.shift();
params = _.map(params, function(param) { return deref(param, scope); });
if (Handlebars.helpers[helper]) {
ret.push(Handlebars.helpers[helper].apply(scope, params));
} else {
// If the helper is not defined do nothing
ret.push(match[0]);
}
} else {
ret.push(deref(params[0], scope));
}
} else {
ret.push(match[0]);
}
}
input = ret.join('');
}
return input;
},
tag: function(attributes, content, scope) {
var htmlAttributes = _.omit(attributes, 'tagName'),
tag = attributes.tagName || 'div';
return '<' + tag + ' ' + _.map(htmlAttributes, function(value, key) {
if (_.isUndefined(value) || key === 'expand-tokens') {
return '';
}
var formattedValue = value;
if (scope) {
formattedValue = Thorax.Util.expandToken(value, scope);
}
return (key === 'className' ? 'class' : key) + '="' + Handlebars.Utils.escapeExpression(formattedValue) + '"';
}).join(' ') + '>' + (_.isUndefined(content) ? '' : content) + '</' + tag + '>';
}
};
|
/**
*
* FooterNav2
*
*/
import React from 'react';
import {Link} from "react-router";
import Responsive from 'react-responsive';
class FooterNav2 extends React.PureComponent {
render() {
const footerStyle={
display:"flex",
flexDirection:"row",
justifyContent:"space-around",
backgroundColor:"rgba(0, 0, 0, 0.10)",
height:"100px",
alignItems:"center",
paddingRight:"10px",
textDecoration:"none",
color:"#000000",
fontSize:"1.10em",
fontFamily:"Josefin Sans",
fontStyle:"light",
fontWeight:"300",
textAlign:"right",
textTransform:"uppercase",
letterSpacing:"2px",
}
const linkStyle={
display:"flex",
flexDirection:"column",
textDecoration:"none",
color:"#000000",
fontSize:".75em",
fontFamily:"Josefin Sans",
fontStyle:"light",
fontWeight:"400",
textAlign:"center",
textTransform:"uppercase",
letterSpacing:"2px",
}
const BodyStyle={
color:"#ffffff",
fontSize:"1em",
fontFamily:"Open Sans",
fontWeight:"400",
textAlign:"center",
}
const footerStyleMobile={
display:"flex",
flexDirection:"column",
textDecoration:"none",
color:"#000000",
fontSize:"1em",
fontFamily:"Josefin Sans",
fontStyle:"light",
fontWeight:"500",
textAlign:"center",
textTransform:"uppercase",
letterSpacing:"2px",
}
const headStyleMobile={
display:"flex",
marginTop:"20px",
flexDirection:"column",
alignItems:"center",
}
return (
<div>
<Responsive minDeviceWidth={1024}>
<div>
<nav style={footerStyle}>
<Link to="/" style={linkStyle}>
Main
</Link>
<Link to="/Blog" style={linkStyle}>
Blog
</Link>
<Link to="/Contact" style={linkStyle}>
Contact
</Link>
</nav>
</div>
</Responsive>
<Responsive maxDeviceWidth={1023}>
<div style={headStyleMobile}>
<nav style={footerStyleMobile}>
<Link to="/" style={linkStyle}>
Main
</Link>
<Link to="/Blog" style={linkStyle}>
Blog
</Link>
<Link to="/Contact" style={linkStyle}>
Contact
</Link>
</nav>
</div>
</Responsive>
</div>
);
}
}
export default FooterNav2;
|
import {EventEmitter} from 'events'//nodejs自带模块,不用另外安装
export default new EventEmitter(); |
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
_ = require('lodash'),
async = require('async'),
Transaction = mongoose.model('Transaction'),
User = mongoose.model('User');
exports.list = function (req, res) {
Transaction.aggregate()
.match({
'$or': [
{ user: req.user._id },
{ friend: req.user._id }
],
status: { $nin: ['paid', 'revoked'] }
})
.group({
_id: {
friend: {
$cond: [
{ $eq: ['$friend', req.user._id] },
'$user',
{ $ifNull: ['$friend', '$to'] }
]
}
},
total: {
$sum: {
$cond: [
{
$or: [
{ $and: [
{ $eq: ['$user', req.user._id] },
{ $eq: ['$kind', 'receive'] }
]},
{ $and: [
{ $eq: ['$friend', req.user._id] },
{ $eq: ['$kind', 'pay'] }
]}
]
},
'$value',
{ $multiply: ['$value', -1] }
]
}
},
average: { $avg: '$value' },
count: { $sum: 1 }
})
.exec(function (err, result) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
var payables = [];
async.each(result, function (payable, done) {
// horrivel!
User.findById(payable._id.friend).select('id displayName').exec(function (err, friend) {
if (friend) {
payable._id.to = friend.displayName;
} else {
payable._id.to = payable._id.friend;
}
payables.push(payable);
done();
});
}, function (err) {
res.jsonp(payables);
});
}
});
};
|
defineClass('Consoloid.Server.ServerSideContainer', 'Consoloid.Service.ChainedContainer',
{
__constructor: function(options)
{
this.__base(options);
if(!('sessionId' in this)) {
throw new Error('sessionId must be injected');
};
},
getSessionId: function()
{
return this.sessionId;
},
addSharedObject: function(name, object, remoting, cls)
{
remoting = remoting || { mode: 'disabled' };
this.definitions[name] = {
shared: true,
cls: cls || null,
options: null,
remoting: remoting
};
this.services[name] = object;
return this;
},
getRemoteDefinition: function(name)
{
var definition = this.getDefinition(name);
if (!definition || !('remoting' in definition) ||
('mode' in definition.remoting && definition.remoting.mode == 'disabled')
) {
throw new Error('Service does not exist or not accessible; name=' + name);
}
var cls = typeof definition.cls == 'string' ? getClass(definition.cls) : definition.cls;
var result = {
id: name,
shared: definition.shared,
methods: this.__getMethodNames(cls ? cls.prototype : this.services[name])
};
return result;
},
__getMethodNames: function(object)
{
var
methodNames = [];
for (var property in object) {
try {
if (typeof(object[property]) == "function") {
methodNames.push({ name: property });
}
} catch (err) {
// inaccessible
}
}
return methodNames;
}
}
);
|
export class GithubAuthProvider {
static credential(idToken, accessToken) {
throw new Error("not implemented");
}
addScope(scope) {
throw new Error("not implemented");
}
setCustomParameters(params) {
throw new Error("not implemented");
}
}
//# sourceMappingURL=GithubAuthProvider.js.map |
const sqlite3 = require('sqlite3').verbose();
const userHome = process.env.HOME || process.env.USERPROFILE;
let db = null;
const create = (cb = () => {
}) => {
const sqlPlaylist = `CREATE TABLE IF NOT EXISTS playlist (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
artist TEXT NOT NULL,
albumArtist TEXT NOT NULL,
album TEXT NOT NULL,
title TEXT NOT NULL,
file TEXT NOT NULL UNIQUE,
diskNumber TEXT,
trackNumber TEXT
)`;
const sqlAlbums = `CREATE TABLE IF NOT EXISTS albums (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
albumArtist TEXT NOT NULL,
album TEXT NOT NULL UNIQUE,
coverArt BLOB
)`;
db.serialize(() => {
db.run(sqlPlaylist);
db.run(sqlAlbums, cb);
});
};
const clear = () => {
db.serialize(() => {
db.run('DROP TABLE IF EXISTS `playlist`');
db.run('DROP TABLE IF EXISTS `albums`');
});
};
export default {
create: create,
clear: clear,
recreate: (cb) => {
db.serialize(() => {
clear();
create(cb);
});
},
open: (cb) => {
if (db) {
cb(db);
} else {
db = new sqlite3.Database(`${userHome}/rotesonne.db`,
sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE,
() => {
create(() => {
cb(db);
});
});
}
}
};
|
const fs = require('fs')
const http = require('http')
const mst = require('mustache')
const config = require('config')
const util = require('./util')
// Begin module
module.exports = function() {
// Create a server
http.createServer(function(req, res) {
const response = (res, output, content_type, status) => {
// Write the headers
res.writeHead(status = status || 200, {
'Content-Type': content_type || 'text/html',
'Access-Control-Allow-Origin': '*'
})
// Send the result with output
res.end(output)
console.log(status + ' ' + req.method + ' ' + req.url)
}
let output
if(req.url == '/') {
// Read the JSON log file
let log = util.readLog()
// Read the template
let template = fs.readFileSync(util.appPath('template'))
// Render the template with colours from log
output = mst.render(template.toString(), {
colours: log,
google_analytics: config.google_analytics,
formatDate: function() {
return function(date, render) {
return util.formatDate(render(date))
}
}
})
return response(res, output)
}
else if(req.url == '/style.css') {
// Read the css file
output = fs.readFileSync(util.appPath('style'))
return response(res, output, 'text/css')
}
else if(req.url == '/json') {
// Read the JSON log file
output = fs.readFileSync(util.appPath('log'))
return response(res, output, 'text/json')
}
else {
return response(res, '404 Page Not Found', 'text/html', 404)
}
}).listen(config.server_port, config.server_address)
console.log('Server running at http://%s:%s/', config.server_address, config.server_port)
console.log('Close with CTRL + C')
}
|
/**
* Copyright 2012-2020, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var tube2mesh = require('gl-streamtube3d');
var createTubeMesh = tube2mesh.createTubeMesh;
var Lib = require('../../lib');
var parseColorScale = require('../../lib/gl_format_color').parseColorScale;
var extractOpts = require('../../components/colorscale').extractOpts;
var zip3 = require('../../plots/gl3d/zip3');
var axisName2scaleIndex = {xaxis: 0, yaxis: 1, zaxis: 2};
function Streamtube(scene, uid) {
this.scene = scene;
this.uid = uid;
this.mesh = null;
this.data = null;
}
var proto = Streamtube.prototype;
proto.handlePick = function(selection) {
var sceneLayout = this.scene.fullSceneLayout;
var dataScale = this.scene.dataScale;
function fromDataScale(v, axisName) {
var ax = sceneLayout[axisName];
var scale = dataScale[axisName2scaleIndex[axisName]];
return ax.l2c(v) / scale;
}
if(selection.object === this.mesh) {
var pos = selection.data.position;
var uvx = selection.data.velocity;
selection.traceCoordinate = [
fromDataScale(pos[0], 'xaxis'),
fromDataScale(pos[1], 'yaxis'),
fromDataScale(pos[2], 'zaxis'),
fromDataScale(uvx[0], 'xaxis'),
fromDataScale(uvx[1], 'yaxis'),
fromDataScale(uvx[2], 'zaxis'),
// u/v/w norm
selection.data.intensity * this.data._normMax,
// divergence
selection.data.divergence
];
selection.textLabel = this.data.hovertext || this.data.text;
return true;
}
};
function getDfltStartingPositions(vec) {
var len = vec.length;
var s;
if(len > 2) {
s = vec.slice(1, len - 1);
} else if(len === 2) {
s = [(vec[0] + vec[1]) / 2];
} else {
s = vec;
}
return s;
}
function getBoundPads(vec) {
var len = vec.length;
if(len === 1) {
return [0.5, 0.5];
} else {
return [vec[1] - vec[0], vec[len - 1] - vec[len - 2]];
}
}
function convert(scene, trace) {
var sceneLayout = scene.fullSceneLayout;
var dataScale = scene.dataScale;
var len = trace._len;
var tubeOpts = {};
function toDataCoords(arr, axisName) {
var ax = sceneLayout[axisName];
var scale = dataScale[axisName2scaleIndex[axisName]];
return Lib.simpleMap(arr, function(v) { return ax.d2l(v) * scale; });
}
tubeOpts.vectors = zip3(
toDataCoords(trace._u, 'xaxis'),
toDataCoords(trace._v, 'yaxis'),
toDataCoords(trace._w, 'zaxis'),
len
);
// Over-specified mesh case, this would error in tube2mesh
if(!len) {
return {
positions: [],
cells: []
};
}
var meshx = toDataCoords(trace._Xs, 'xaxis');
var meshy = toDataCoords(trace._Ys, 'yaxis');
var meshz = toDataCoords(trace._Zs, 'zaxis');
tubeOpts.meshgrid = [meshx, meshy, meshz];
tubeOpts.gridFill = trace._gridFill;
var slen = trace._slen;
if(slen) {
tubeOpts.startingPositions = zip3(
toDataCoords(trace._startsX, 'xaxis'),
toDataCoords(trace._startsY, 'yaxis'),
toDataCoords(trace._startsZ, 'zaxis')
);
} else {
// Default starting positions:
//
// if len>2, cut xz plane at min-y,
// takes all x/y/z pts on that plane except those on the edges
// to generate "well-defined" tubes,
//
// if len=2, take position halfway between two the pts,
//
// if len=1, take that pt
var sy0 = meshy[0];
var sx = getDfltStartingPositions(meshx);
var sz = getDfltStartingPositions(meshz);
var startingPositions = new Array(sx.length * sz.length);
var m = 0;
for(var i = 0; i < sx.length; i++) {
for(var k = 0; k < sz.length; k++) {
startingPositions[m++] = [sx[i], sy0, sz[k]];
}
}
tubeOpts.startingPositions = startingPositions;
}
tubeOpts.colormap = parseColorScale(trace);
tubeOpts.tubeSize = trace.sizeref;
tubeOpts.maxLength = trace.maxdisplayed;
// add some padding around the bounds
// to e.g. allow tubes starting from a slice of the x/y/z mesh
// to go beyond bounds a little bit w/o getting clipped
var xbnds = toDataCoords(trace._xbnds, 'xaxis');
var ybnds = toDataCoords(trace._ybnds, 'yaxis');
var zbnds = toDataCoords(trace._zbnds, 'zaxis');
var xpads = getBoundPads(meshx);
var ypads = getBoundPads(meshy);
var zpads = getBoundPads(meshz);
var bounds = [
[xbnds[0] - xpads[0], ybnds[0] - ypads[0], zbnds[0] - zpads[0]],
[xbnds[1] + xpads[1], ybnds[1] + ypads[1], zbnds[1] + zpads[1]]
];
var meshData = tube2mesh(tubeOpts, bounds);
// N.B. cmin/cmax correspond to the min/max vector norm
// in the u/v/w arrays, which in general is NOT equal to max
// intensity that colors the tubes.
var cOpts = extractOpts(trace);
meshData.vertexIntensityBounds = [cOpts.min / trace._normMax, cOpts.max / trace._normMax];
// pass gl-mesh3d lighting attributes
var lp = trace.lightposition;
meshData.lightPosition = [lp.x, lp.y, lp.z];
meshData.ambient = trace.lighting.ambient;
meshData.diffuse = trace.lighting.diffuse;
meshData.specular = trace.lighting.specular;
meshData.roughness = trace.lighting.roughness;
meshData.fresnel = trace.lighting.fresnel;
meshData.opacity = trace.opacity;
// stash autorange pad value
trace._pad = meshData.tubeScale * trace.sizeref * 2;
return meshData;
}
proto.update = function(data) {
this.data = data;
var meshData = convert(this.scene, data);
this.mesh.update(meshData);
};
proto.dispose = function() {
this.scene.glplot.remove(this.mesh);
this.mesh.dispose();
};
function createStreamtubeTrace(scene, data) {
var gl = scene.glplot.gl;
var meshData = convert(scene, data);
var mesh = createTubeMesh(gl, meshData);
var streamtube = new Streamtube(scene, data.uid);
streamtube.mesh = mesh;
streamtube.data = data;
mesh._trace = streamtube;
scene.glplot.add(mesh);
return streamtube;
}
module.exports = createStreamtubeTrace;
|
const Promise = require('bluebird');
const fse = require('fs-extra');
const promisedFs = Promise.promisifyAll(fse);
module.exports = promisedFs;
|
var mongoose = require('mongoose'),
config = require('config');
// Require models
require('./example');
exports.initialize = function(cb) {
cb = cb || function() {};
// Connect
mongoose.set('debug', config.mongo.debug)
mongoose.connect(config.mongo.connectionString);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'Mongo connection error:'));
db.once('open', function() {
console.log('Mongo ready');
cb()
});
}
|
(function () {
window.SnakeGame = window.SnakeGame || {};
var Board = SnakeGame.Board = function (options) {
options = options || {};
this.height = options.height || Board.HEIGHT;
this.width = options.width || Board.WIDTH;
this.player = options.player || new SnakeGame.Snake(this);
this.opponent = options.opponent || new SnakeGame.SnakeAI(this);
this.placeApple();
};
Board.HEIGHT = 24;
Board.WIDTH = 24;
Board.prototype.placeApple = function () {
var emptySpaces = this.emptySpaces();
var randomSpaceIdx = Math.floor(Math.random() * emptySpaces.length);
this.applePos = emptySpaces[randomSpaceIdx];
};
Board.prototype.emptySpaces = function () {
var emptySpaces = [];
for (row = 0; row < this.height; row++) {
for (col = 0; col < this.width; col++) {
var pos = [row, col];
var segments = this.player.segments.concat(this.opponent.segments);
if (!SnakeGame.Util.samePos(this.applePos, pos) &&
!SnakeGame.Util.inSegments(segments, pos)) {
emptySpaces.push([row, col]);
}
}
}
return emptySpaces;
}
Board.prototype.render = function () {
var board = [];
for (row = 0; row < this.height; row++) {
board[row] = $("<ul>").addClass("snake-row").addClass("group");
for (col = 0; col < this.width; col++) {
var pos = row + "-" + col;
var $li = $("<li>").attr("id", pos);
board[row].append($li);
}
}
return board;
}
Board.prototype.inRange = function (pos) {
return (pos[0] >= 0 && pos[0] < this.height) &&
(pos[1] >= 0 && pos[1] < this.width);
}
Board.prototype.winner = function () {
if (this.player.isDead) {
return this.opponent;
} else if (this.opponent.isDead) {
return this.player;
}
}
Board.prototype.isOver = function () {
return !!this.winner();
}
})();
|
import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router-dom";
import { fetch_single_user, reset_password } from '../../api';
import { notify } from 'react-notify-toast';
import validatePassword from '../../common/utilities/validatePassword';
import Spinner from '../../common/components/Spinner';
class EditUserPW extends React.Component {
constructor(props) {
super(props);
this.state = {
id: "",
password: "",
confpassword: "",
header: "",
loading: false,
deleting: false,
saving: false,
error: {
password: null,
confirmPassword: null,
generic: null,
}
};
this.loadUser = this.loadUser.bind(this);
this.editPassword = this.editPassword.bind(this);
this.changeField = this.changeField.bind(this);
}
componentDidMount() {
this.loadUser();
}
loadUser() {
this.setState({ loading: true });
const fullstr = document.location.pathname.toString();
const tmpfullsre = fullstr.split("/");
const id = tmpfullsre[3] ;
let self = this;
fetch_single_user(id).then(response => response.json()).then(function(result) {
if (result.success) {
self.setState({
id: result.message.id,
password: "",
confpassword: "",
header: result.message.fullName,
loading: false
});
} else {
self.props.history.push("/users");
}
});
}
editPassword() {
this.setState({ loading: true, saving: true });
let errors = this.state.error;
errors.password = "";
errors.confirmPassword = "";
errors.generic = "";
// Check fields are not empty
if (this.state.password.trim() == "") {
errors.password = "Please enter a password.";
} else {
errors.password = "";
}
if (this.state.confpassword.trim() == "") {
errors.confirmPassword = "Please retype the password.";
} else {
errors.confirmPassword = "";
}
if (validatePassword(this.state.password) == false) {
errors.password = "Invalid password! Password to be of at least 8 characters including a number and an uppercase letter.";
} else {
errors.password = "";
}
if(this.state.password.trim() !== this.state.confpassword.trim())
{
errors.confirmPassword = "The two entered passwords don't match!"
}
// Attempt save to database
if (errors.password === "" && errors.confirmPassword === "") {
let self = this;
reset_password(this.state.id, this.state.password).then(response => response.json()).then(function(result) {
if (result.success == true) {
notify.show('Password has been successfully updated');
self.props.history.push("/users");
} else {
notify.show('Sorry, something went wrong :/');
self.setState({ loading: false, saving: false, error: {generic: "Sorry, something went wrong and we could not save your changes :/. Please refresh the page and try again."} });
}
});
} else {
this.setState({ loading: false, saving: false });
}
this.setState({error: errors});
}
changeField(evt) {
this.setState({[evt.target.name]: evt.target.value});
}
render() {
const {
password,
confpassword,
header,
error,
loading,
saving,
deleting,
} = this.state;
const {
user,
} = this.props;
return <div className="page">
<div className="box">
<div className="title">
<p><img src={require('../../common/images/go_back.png')} onClick={() => this.props.history.push("/users")}/> Reset {header}'s Password</p>
</div>
<div className="components">
<div className="input">
<label>Password</label>
<input
name="password"
type="password"
value={password}
onChange={this.changeField}
disabled={loading}
/>
{error.password && <div className="error">{error.password}</div>}
</div>
<div className="input">
<label>Confirm Password</label>
<input
type="password"
name="confpassword"
value={confpassword}
onChange={this.changeField}
disabled={loading}
/>
{error.confirmPassword && <div className="error">{error.confirmPassword}</div>}
</div>
{error.generic && <div className="error">{error.generic}</div>}
<div>
<button type="button" className="submit width60 float-right" onClick={this.editPassword} disabled={loading}>{saving && <Spinner />}Update User Info</button>
</div>
</div>
</div>
</div>;
};
};
EditUserPW.propTypes = {
user: PropTypes.object,
};
export default withRouter(EditUserPW);
|
/**
* Interactive Linter Copyright (c) 2015 Miguel Castillo.
*
* Licensed under MIT
*/
define(function (/*require, exports, module*/) {
"use strict";
function getType(message) {
return (message.fatal || message.severity === 2) ? "error" : "warning";
}
/**
* Generates codemirror tokens. Also massages the message so that it has the
* data that interactive linter is expecting in the proper place.
*
* @param message {Object} message - A linting result item
* @param settings {Object} settings - Settings used during the linting step
*/
function groom(message /*, settings*/) {
message.type = getType(message);
message.evidence = "[" + message.ruleId + "] - " + message.source;
message.token = {
start: {
line: (message.line - 1),
ch: (message.column - 1)
},
end: {
line: (message.line - 1),
ch: (message.column)
}
};
message.pos = {
line: message.line,
ch: message.column
};
}
return {
groom: groom
};
});
|
import React, { Component, PropTypes } from 'react';
import he from 'he';
import { format } from 'd3-format';
const formatNumber = format('.2s');
export default class Link extends Component {
render() {
const { onClick } = this.props;
const { title, score, link, is_answered, answer_count, view_count } = this.props.link;
const answered = is_answered ? 'is-success' : '';
const views = `${formatNumber(view_count)} views`;
return (
<div className='box pointer' tabIndex='0' onClick={onClick}>
<article className='media'>
<div className='media-left'>
<a className={`button ${answered} is-disabled`}>
{score}
</a>
</div>
<div className='media-content'>
<div className='content'>
<span className='is-medium'>
<strong>{formatTitle(title)}</strong>
</span>
<br />
<small><i>{link}</i></small>
<br />
<a className='tag link-tag'>{views}</a>
<a className='tag link-tag'>{`${answer_count} answers`}</a>
</div>
</div>
</article>
</div>
);
}
}
function formatTitle(title) {
return he.decode(title).replace(' - Stack Overflow', '');
}
Link.propTypes = {
link: PropTypes.object.isRequired,
onClick: PropTypes.func.isRequired,
};
|
import pkg from "../../../package.json";
import GoogleAnalytics from "../../vendors/GoogleAnalytics";
const config = {
vendors: [
{
name: "Test Override",
api: {
name: "Test",
pageView(eventName, params) {
return new Promise(resolve => {
resolve({
eventName,
params
});
});
},
track(eventName, params) {
return new Promise(resolve => {
resolve({
eventName,
params
});
});
},
user(user) {
return new Promise(resolve => {
// reject(new Error("dummy error Test"));
resolve({
user
});
});
}
}
},
{
api: new GoogleAnalytics({
trackingId: "UA-68539421-1"
})
}
],
pageDefaults: routeState => {
const paths = routeState.pathname.substr(1).split("/");
const timestamp = new Date();
return {
timestamp,
build: pkg.version,
siteName: "React Metrics Example",
category: !paths[0] ? "landing" : paths[0]
};
},
pageViewEvent: "pageLoad",
debug: true
};
export default config;
|
import * as Types from './types';
import iView from 'iview';
import {
cgiPrefix,
cgiName
} from '../commons/cgiConst.js';
const mutations = {
[Types.exportFile](state) {
let exportUrl = cgiPrefix + cgiName['download'];
let s = state.searchCgiParam;
let pStr = {
ClassL1Id: s.ClassL1Id || '',
ClassL2Id: s.ClassL2Id || '',
ClassL1Name: s.ClassL1Name || '',
ClassL2Name: s.ClassL2Name || '',
ClassShop: s.ClassShop || '',
BusinessShop: s.BusinessShop || '',
ModBy: s.ModBy || '',
ClassState: s.ClassState === 0 ? '' : s.ClassState
};
pStr = Object.keys(pStr).reduce((i1, i2) => i1 + i2 + '=' + pStr[i2] + '&', '?');
pStr = pStr.substring(0, pStr.length - 1);
console.log(exportUrl + pStr);
window.location.href = exportUrl + pStr;
},
[Types.fileFormatError]() {
iView.LoadingBar.finish();
iView.Message.warning({
content: '文件格式错误,仅支持csv文件格式',
duration: 2
});
},
[Types.beforeUpload]() {
iView.LoadingBar.start();
},
[Types.fileUpError]() {
iView.LoadingBar.finish();
iView.Message.error({
content: '文件上传失败',
duration: 2
});
},
[Types.ok](state) {
state.visible = false;
},
[Types.cancel](state) {
state.visible = false;
},
[Types.updateFormItem](state, payload) {
state.formItem = Object.assign({}, state.formItem, payload);
},
[Types.updateModalVisible](state, val) {
state.visible = val;
},
[Types.updateEditInVal](state, val) {
state.inVal = val;
},
[Types.updateEditVisible](state, val) {
state.editVisible = val;
},
[Types.modifyCancel](state) {
state.editLoading = false;
state.inVal = '';
},
[Types.closePop]() {
document.getElementById('blur').click();
}
};
export default mutations;
|
function changeLogoLocation(src, orientation, logow, logoh){
var width = 960;
var height = 720;
var margin_left = "10px";
if (orientation == "tr" || orientation == "tl") margin_left = (width - logow - 10) + "px";
var margin_top = "10px";
if (orientation == "br" || orientation == "bl") margin_top = (height - logoh - 10) + "px";
html_img_logo = "<img id='img_logo' src='assets/img/logos/" + src + "' width='" +logow+ "' style='margin-left:" +margin_left+ ";margin-top:" +margin_top+";'>";
$("#div_logo_display").empty();
//$("#div_logo_display").html(html_img_logo);
}
/*
* Start the upload & hide & show dives
*/
function startUpload(){
$("#div_loading").show();
}
/*
* Stop the upload and hide & show dives
*/
function stopUpload(){
$("#div_loading").hide();
//$("#div_logo").hide();
//$("#div_form").show();
}
function zipAll(){
startUpload();
$.ajax({
type: "GET",
url: "zip.php",
success: function(msg){
$("#span_info").hide();
$("#div_zip").html(msg);
// var path = $("#path").html();
// download(path);
}
});
stopUpload();
}
function download(file)
{
window.location=file;
} |
$('input').each(function() {
var default_value = this.value;
$(this).focus(function(){
if(this.value == default_value) {
this.value = '';
}
});
$(this).blur(function(){
if(this.value == '') {
this.value = default_value;
}
});
});
var clock;
$(document).ready(function() {
// Grab the current date
var currentDate = new Date();
// Set date in the future.
var futureDate = new Date("October 13, 2014 08:00:00");
// Calculate the difference in seconds between the future and current date
var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
// Instantiate a coutdown FlipClock
clock = $('.clock').FlipClock(diff, {
clockFace: 'DailyCounter',
countdown: true
});
});
Parse.initialize("UjgvePXacuR4ahO7jagVvYEjrbWtDTKolP54ks5f", "3aeKGDCOsy0GzZARPNM9itls5ocrlmzeP2rr5nJC");
$("#email_submit").click(function() {
var ConvergeEmail = Parse.Object.extend("ConvergeEmail");
var convergeEmail = new ConvergeEmail();
var emailformval = $("#email_input").val();
convergeEmail.set("emailAddress", emailformval);
convergeEmail.save(null, {
success: function(convergeEmail) {
// Execute any logic that should take place after the object is saved.
alert('Welcome to our list! Stay tuned for updates coming soon! - Converge');
},
error: function(convergeEmail, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert("Oh no! Something went wrong. Try again after reloading the page!");
}
});
}); |
import ElementCollector from './../src/index';
describe('ElementCollector', function() {
var x = new ElementCollector;
afterEach(function() {
x.reset();
});
describe('add', function() {
it('should add valid item', function() {
var elm = document.createElement('div');
x.add('div');
x.add(elm);
expect(x.items).toContain('div');
expect(x.items).toContain(elm);
});
it('should add valid items via constructor', function () {
var x = new ElementCollector('div');
expect(x.items).toContain('div');
});
it('should linearize added enumerable', function() {
x.add(['div', 'span']);
expect(x.items).toContain('div');
expect(x.items).toContain('span');
});
it('should not add invalid item', function() {
x.add(null);
x.add('');
expect(x.items).not.toContain(null);
expect(x.items).not.toContain('');
});
it('keeps items unique', function() {
x.add('div');
x.add('div');
expect(x.items).toContain('div');
expect(x.items.length).toEqual(1);
});
});
describe('remove', function() {
it('should remove item', function() {
x.add(['div', 'span']);
expect(x.items).toContain('div');
x.remove('div');
expect(x.items).not.toContain('div');
expect(x.items).toContain('span');
});
});
describe('reset', function() {
it('should clean up items list', function() {
x.reset();
expect(x.items).toEqual([]);
});
});
describe('set', function() {
it('should replace existing items list', function() {
x.add(['div', 'span']);
x.set('div');
expect(x.items).toContain('div');
expect(x.items).not.toContain('span');
});
});
describe('get', function() {
it('should list of elements (document.body by default)', function() {
var elm = document.body.appendChild(document.createElement('div'));
x.add(elm);
var result = x.get();
expect(result).toContain(elm);
expect(result.length).toEqual(1);
elm.parentNode.removeChild(elm);
});
it('should list of elements from node', function() {
var elm_outer = document.createElement('div');
var elm_inner = elm_outer.appendChild(document.createElement('div'));
x.add(elm_inner);
var result_node = x.get(elm_outer);
var result_body = x.get(document.body);
expect(result_node).toContain(elm_inner);
expect(result_body).not.toContain(elm_inner);
});
it('keeps results unique', function() {
var elm = document.body.appendChild(document.createElement('div'));
elm.className = 'aaa bbb';
x.add('.aaa');
x.add('.bbb');
var result = x.get();
expect(result).toContain(elm);
expect(result.length).toEqual(1);
elm.parentNode.removeChild(elm);
});
});
}); |
define("ghost/helpers/ghost-paths",
["ghost/utils/ghost-paths","exports"],
function(__dependency1__, __exports__) {
"use strict";
// Handlebars Helper {{gh-path}}
// Usage: Assume 'http://www.myghostblog.org/myblog/'
// {{gh-path}} or {{gh-path ‘blog’}} for Ghost’s root (/myblog/)
// {{gh-path ‘admin’}} for Ghost’s admin root (/myblog/ghost/)
// {{gh-path ‘api’}} for Ghost’s api root (/myblog/ghost/api/v0.1/)
// {{gh-path 'admin' '/assets/hi.png'}} for resolved url (/myblog/ghost/assets/hi.png)
var ghostPaths = __dependency1__["default"];
function ghostPathsHelper(path, url) {
var base,
argsLength = arguments.length,
paths = ghostPaths();
// function is always invoked with at least one parameter, so if
// arguments.length is 1 there were 0 arguments passed in explicitly
if (argsLength === 1) {
path = 'blog';
} else if (argsLength === 2 && !/^(blog|admin|api)$/.test(path)) {
url = path;
path = 'blog';
}
switch (path.toString()) {
case 'blog':
base = paths.blogRoot;
break;
case 'admin':
base = paths.adminRoot;
break;
case 'api':
base = paths.apiRoot;
break;
default:
base = paths.blogRoot;
break;
}
// handle leading and trailing slashes
base = base[base.length - 1] !== '/' ? base + '/' : base;
if (url && url.length > 0) {
if (url[0] === '/') {
url = url.substr(1);
}
base = base + url;
}
return new Ember.Handlebars.SafeString(base);
}
__exports__["default"] = ghostPathsHelper;
}); |
/******************************************************************************
* Copyright © 2013-2015 The Nxt Core Developers. *
* *
* See the AUTHORS.txt, DEVELOPER-AGREEMENT.txt and LICENSE.txt files at *
* the top-level directory of this distribution for the individual copyright *
* holder information and the developer policies on copyright and licensing. *
* *
* Unless otherwise agreed in a custom licensing agreement, no part of the *
* Nxt software, including this file, may be copied, modified, propagated, *
* or distributed except according to the terms contained in the LICENSE.txt *
* file. *
* *
* Removal or modification of this copyright notice is prohibited. *
* *
******************************************************************************/
/**
* @depends {3rdparty/jquery-2.1.0.js}
* @depends {3rdparty/bootstrap.js}
* @depends {3rdparty/big.js}
* @depends {3rdparty/jsbn.js}
* @depends {3rdparty/jsbn2.js}
* @depends {3rdparty/pako.js}
* @depends {3rdparty/webdb.js}
* @depends {3rdparty/ajaxmultiqueue.js}
* @depends {3rdparty/growl.js}
* @depends {3rdparty/zeroclipboard.js}
* @depends {crypto/curve25519.js}
* @depends {crypto/curve25519_.js}
* @depends {crypto/passphrasegenerator.js}
* @depends {crypto/sha256worker.js}
* @depends {crypto/3rdparty/cryptojs/aes.js}
* @depends {crypto/3rdparty/cryptojs/sha256.js}
* @depends {crypto/3rdparty/jssha256.js}
* @depends {crypto/3rdparty/seedrandom.js}
* @depends {util/converters.js}
* @depends {util/extensions.js}
* @depends {util/nxtaddress.js}
*/
var NRS = (function(NRS, $, undefined) {
"use strict";
NRS.server = "http://jnxt.org:7876";
NRS.state = {};
NRS.blocks = [];
NRS.account = "";
NRS.accountRS = "";
NRS.publicKey = "";
NRS.accountInfo = {};
NRS.database = null;
NRS.databaseSupport = false;
NRS.databaseFirstStart = false;
// Legacy database, don't use this for data storage
NRS.legacyDatabase = null;
NRS.legacyDatabaseWithData = false;
NRS.serverConnect = false;
NRS.peerConnect = false;
NRS.settings = {};
NRS.contacts = {};
NRS.isTestNet = false;
NRS.isLocalHost = false;
NRS.isForging = false;
NRS.isLeased = false;
NRS.needsAdminPassword = true;
NRS.lastBlockHeight = 0;
NRS.downloadingBlockchain = false;
NRS.rememberPassword = true;
NRS.selectedContext = null;
NRS.currentPage = "dashboard";
NRS.currentSubPage = "";
NRS.pageNumber = 1;
//NRS.itemsPerPage = 50; /* Now set in nrs.settings.js */
NRS.pages = {};
NRS.incoming = {};
NRS.setup = {};
if (!_checkDOMenabled()) {
NRS.hasLocalStorage = false;
} else {
NRS.hasLocalStorage = true;
}
NRS.inApp = false;
NRS.appVersion = "";
NRS.appPlatform = "";
NRS.assetTableKeys = [];
var stateInterval;
var stateIntervalSeconds = 30;
var isScanning = false;
NRS.init = function() {
NRS.sendRequest("getState", {
"includeCounts": "false"
}, function (response) {
var isTestnet = false;
var isOffline = false;
var peerPort = 0;
for (var key in response) {
if (key == "isTestnet") {
isTestnet = response[key];
}
if (key == "isOffline") {
isOffline = response[key];
}
if (key == "peerPort") {
peerPort = response[key];
}
if (key == "needsAdminPassword") {
NRS.needsAdminPassword = response[key];
}
}
if (!isTestnet) {
$(".testnet_only").hide();
} else {
NRS.isTestNet = true;
var testnetWarningDiv = $("#testnet_warning");
var warningText = testnetWarningDiv.text() + " The testnet peer port is " + peerPort + (isOffline ? ", the peer is working offline." : ".");
NRS.logConsole(warningText);
testnetWarningDiv.text(warningText);
$(".testnet_only, #testnet_login, #testnet_warning").show();
}
NRS.loadServerConstants();
NRS.loadTransactionTypeConstants();
NRS.initializePlugins();
NRS.printEnvInfo();
});
if (!NRS.server) {
var hostName = window.location.hostname.toLowerCase();
NRS.isLocalHost = hostName == "localhost" || hostName == "127.0.0.1" || NRS.isPrivateIP(hostName);
NRS.logProperty("NRS.isLocalHost");
}
if (!NRS.isLocalHost) {
$(".remote_warning").show();
}
try {
window.localStorage;
} catch (err) {
NRS.hasLocalStorage = false;
}
if(!(navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1)) {
// Not Safari
// Don't use account based DB in Safari due to a buggy indexedDB implementation (2015-02-24)
NRS.createLegacyDatabase();
}
if (NRS.getCookie("remember_passphrase")) {
$("#remember_password").prop("checked", true);
}
NRS.getSettings();
NRS.getState(function() {
setTimeout(function() {
NRS.checkAliasVersions();
}, 5000);
});
$("body").popover({
"selector": ".show_popover",
"html": true,
"trigger": "hover"
});
NRS.showLockscreen();
if (window.parent) {
var match = window.location.href.match(/\?app=?(win|mac|lin)?\-?([\d\.]+)?/i);
if (match) {
NRS.inApp = true;
if (match[1]) {
NRS.appPlatform = match[1];
}
if (match[2]) {
NRS.appVersion = match[2];
}
if (!NRS.appPlatform || NRS.appPlatform == "mac") {
var macVersion = navigator.userAgent.match(/OS X 10_([0-9]+)/i);
if (macVersion && macVersion[1]) {
macVersion = parseInt(macVersion[1]);
if (macVersion < 9) {
$(".modal").removeClass("fade");
}
}
}
$("#show_console").hide();
parent.postMessage("loaded", "*");
window.addEventListener("message", receiveMessage, false);
}
}
NRS.setStateInterval(30);
if (!NRS.isTestNet) {
setInterval(NRS.checkAliasVersions, 1000 * 60 * 60);
}
NRS.allowLoginViaEnter();
NRS.automaticallyCheckRecipient();
$("#dashboard_table, #transactions_table").on("mouseenter", "td.confirmations", function() {
$(this).popover("show");
}).on("mouseleave", "td.confirmations", function() {
$(this).popover("destroy");
$(".popover").remove();
});
_fix();
$(window).on("resize", function() {
_fix();
if (NRS.currentPage == "asset_exchange") {
NRS.positionAssetSidebar();
}
});
$("[data-toggle='tooltip']").tooltip();
$("#dgs_search_account_top, #dgs_search_account_center").mask("NXT-****-****-****-*****", {
"unmask": false
});
if (NRS.getUrlParameter("account")){
NRS.login(false,NRS.getUrlParameter("account"));
}
/*
$("#asset_exchange_search input[name=q]").addClear({
right: 0,
top: 4,
onClear: function(input) {
$("#asset_exchange_search").trigger("submit");
}
});
$("#id_search input[name=q], #alias_search input[name=q]").addClear({
right: 0,
top: 4
});*/
};
function _fix() {
var height = $(window).height() - $("body > .header").height();
//$(".wrapper").css("min-height", height + "px");
var content = $(".wrapper").height();
$(".content.content-stretch:visible").width($(".page:visible").width());
if (content > height) {
$(".left-side, html, body").css("min-height", content + "px");
} else {
$(".left-side, html, body").css("min-height", height + "px");
}
}
NRS.setStateInterval = function(seconds) {
if (seconds == stateIntervalSeconds && stateInterval) {
return;
}
if (stateInterval) {
clearInterval(stateInterval);
}
stateIntervalSeconds = seconds;
stateInterval = setInterval(function() {
NRS.getState();
}, 1000 * seconds);
};
var _firstTimeAfterLoginRun = false;
NRS.getState = function(callback) {
NRS.sendRequest("getBlockchainStatus", {}, function(response) {
if (response.errorCode) {
NRS.serverConnect = false;
//todo
} else {
var firstTime = !("lastBlock" in NRS.state);
var previousLastBlock = (firstTime ? "0" : NRS.state.lastBlock);
NRS.state = response;
NRS.serverConnect = true;
if (firstTime) {
$("#nrs_version").html(NRS.state.version).removeClass("loading_dots");
NRS.getBlock(NRS.state.lastBlock, NRS.handleInitialBlocks);
} else if (NRS.state.isScanning) {
//do nothing but reset NRS.state so that when isScanning is done, everything is reset.
isScanning = true;
} else if (isScanning) {
//rescan is done, now we must reset everything...
isScanning = false;
NRS.blocks = [];
NRS.tempBlocks = [];
NRS.getBlock(NRS.state.lastBlock, NRS.handleInitialBlocks);
if (NRS.account) {
NRS.getInitialTransactions();
NRS.getAccountInfo();
}
} else if (previousLastBlock != NRS.state.lastBlock) {
NRS.tempBlocks = [];
if (NRS.account) {
NRS.getAccountInfo();
}
NRS.getBlock(NRS.state.lastBlock, NRS.handleNewBlocks);
if (NRS.account) {
NRS.getNewTransactions();
NRS.updateApprovalRequests();
}
} else {
if (NRS.account) {
NRS.getUnconfirmedTransactions(function(unconfirmedTransactions) {
NRS.handleIncomingTransactions(unconfirmedTransactions, false);
});
}
}
if (NRS.account && !_firstTimeAfterLoginRun) {
//Executed ~30 secs after login, can be used for tasks needing this condition state
_firstTimeAfterLoginRun = true;
}
if (callback) {
callback();
}
}
/* Checks if the client is connected to active peers */
NRS.checkConnected();
//only done so that download progress meter updates correctly based on lastFeederHeight
if (NRS.downloadingBlockchain) {
NRS.updateBlockchainDownloadProgress();
}
});
};
$("#logo, .sidebar-menu").on("click", "a", function(e, data) {
if ($(this).hasClass("ignore")) {
$(this).removeClass("ignore");
return;
}
e.preventDefault();
if ($(this).data("toggle") == "modal") {
return;
}
var page = $(this).data("page");
if (page == NRS.currentPage) {
if (data && data.callback) {
data.callback();
}
return;
}
$(".page").hide();
$(document.documentElement).scrollTop(0);
$("#" + page + "_page").show();
$(".content-header h1").find(".loading_dots").remove();
if ($(this).attr("id") && $(this).attr("id") == "logo") {
var $newActiveA = $("#dashboard_link a");
} else {
var $newActiveA = $(this);
}
var $newActivePageLi = $newActiveA.closest("li.treeview");
var $currentActivePageLi = $("ul.sidebar-menu > li.active");
$("ul.sidebar-menu > li.active").each(function(key, elem) {
if ($newActivePageLi.attr("id") != $(elem).attr("id")) {
$(elem).children("a").first().addClass("ignore").click();
}
});
$("ul.sidebar-menu > li.sm_simple").removeClass("active");
if ($newActiveA.parent("li").hasClass("sm_simple")) {
$newActiveA.parent("li").addClass("active");
}
$("ul.sidebar-menu li.sm_treeview_submenu").removeClass("active");
if($(this).parent("li").hasClass("sm_treeview_submenu")) {
$(this).closest("li").addClass("active");
}
if (NRS.currentPage != "messages") {
$("#inline_message_password").val("");
}
//NRS.previousPage = NRS.currentPage;
NRS.currentPage = page;
NRS.currentSubPage = "";
NRS.pageNumber = 1;
NRS.showPageNumbers = false;
if (NRS.pages[page]) {
NRS.pageLoading();
NRS.resetNotificationState(page);
if (data) {
if (data.callback) {
var callback = data.callback;
} else {
var callback = data;
}
} else {
var callback = undefined;
}
if (data && data.subpage) {
var subpage = data.subpage;
} else {
var subpage = undefined;
}
NRS.pages[page](callback, subpage);
}
});
$("button.goto-page, a.goto-page").click(function(event) {
event.preventDefault();
NRS.goToPage($(this).data("page"), undefined, $(this).data("subpage"));
});
NRS.loadPage = function(page, callback, subpage) {
NRS.pageLoading();
NRS.pages[page](callback, subpage);
};
NRS.goToPage = function(page, callback, subpage) {
var $link = $("ul.sidebar-menu a[data-page=" + page + "]");
if ($link.length > 1) {
if ($link.last().is(":visible")) {
$link = $link.last();
} else {
$link = $link.first();
}
}
if ($link.length == 1) {
$link.trigger("click", [{
"callback": callback,
"subpage": subpage
}]);
NRS.resetNotificationState(page);
} else {
NRS.currentPage = page;
NRS.currentSubPage = "";
NRS.pageNumber = 1;
NRS.showPageNumbers = false;
$("ul.sidebar-menu a.active").removeClass("active");
$(".page").hide();
$("#" + page + "_page").show();
if (NRS.pages[page]) {
NRS.pageLoading();
NRS.resetNotificationState(page);
NRS.pages[page](callback, subpage);
}
}
};
NRS.pageLoading = function() {
NRS.hasMorePages = false;
var $pageHeader = $("#" + NRS.currentPage + "_page .content-header h1");
$pageHeader.find(".loading_dots").remove();
$pageHeader.append("<span class='loading_dots'><span>.</span><span>.</span><span>.</span></span>");
};
NRS.pageLoaded = function(callback) {
var $currentPage = $("#" + NRS.currentPage + "_page");
$currentPage.find(".content-header h1 .loading_dots").remove();
if ($currentPage.hasClass("paginated")) {
NRS.addPagination();
}
if (callback) {
callback();
}
};
NRS.addPagination = function(section) {
var firstStartNr = 1;
var firstEndNr = NRS.itemsPerPage;
var currentStartNr = (NRS.pageNumber-1) * NRS.itemsPerPage + 1;
var currentEndNr = NRS.pageNumber * NRS.itemsPerPage;
var prevHTML = '<span style="display:inline-block;width:48px;text-align:right;">';
var firstHTML = '<span style="display:inline-block;min-width:48px;text-align:right;vertical-align:top;margin-top:4px;">';
var currentHTML = '<span style="display:inline-block;min-width:48px;text-align:left;vertical-align:top;margin-top:4px;">';
var nextHTML = '<span style="display:inline-block;width:48px;text-align:left;">';
if (NRS.pageNumber > 1) {
prevHTML += "<a href='#' data-page='" + (NRS.pageNumber - 1) + "' title='" + $.t("previous") + "' style='font-size:20px;'>";
prevHTML += "<i class='fa fa-arrow-circle-left'></i></a>";
} else {
prevHTML += ' ';
}
if (NRS.hasMorePages) {
currentHTML += currentStartNr + "-" + currentEndNr + " ";
nextHTML += "<a href='#' data-page='" + (NRS.pageNumber + 1) + "' title='" + $.t("next") + "' style='font-size:20px;'>";
nextHTML += "<i class='fa fa-arrow-circle-right'></i></a>";
} else {
if (NRS.pageNumber > 1) {
currentHTML += currentStartNr + "+";
} else {
currentHTML += " ";
}
nextHTML += " ";
}
if (NRS.pageNumber > 1) {
firstHTML += " <a href='#' data-page='1'>" + firstStartNr + "-" + firstEndNr + "</a> | ";
} else {
firstHTML += " ";
}
prevHTML += '</span>';
firstHTML += '</span>';
currentHTML += '</span>';
nextHTML += '</span>';
var output = prevHTML + firstHTML + currentHTML + nextHTML;
var $paginationContainer = $("#" + NRS.currentPage + "_page .data-pagination");
if ($paginationContainer.length) {
$paginationContainer.html(output);
}
};
$(".data-pagination").on("click", "a", function(e) {
e.preventDefault();
NRS.goToPageNumber($(this).data("page"));
});
NRS.goToPageNumber = function(pageNumber) {
/*if (!pageLoaded) {
return;
}*/
NRS.pageNumber = pageNumber;
NRS.pageLoading();
NRS.pages[NRS.currentPage]();
};
NRS.initUserDBSuccess = function() {
NRS.database.select("data", [{
"id": "asset_exchange_version"
}], function(error, result) {
if (!result || !result.length) {
NRS.database.delete("assets", [], function(error, affected) {
if (!error) {
NRS.database.insert("data", {
"id": "asset_exchange_version",
"contents": 2
});
}
});
}
});
NRS.database.select("data", [{
"id": "closed_groups"
}], function(error, result) {
if (result && result.length) {
NRS.closedGroups = result[0].contents.split("#");
} else {
NRS.database.insert("data", {
id: "closed_groups",
contents: ""
});
}
});
NRS.databaseSupport = true;
NRS.logConsole("Browser database initialized");
NRS.loadContacts();
NRS.getSettings();
NRS.updateNotifications();
NRS.setUnconfirmedNotifications();
NRS.setPhasingNotifications();
}
NRS.initUserDBWithLegacyData = function() {
var legacyTables = ["contacts", "assets", "data"];
$.each(legacyTables, function(key, table) {
NRS.legacyDatabase.select(table, null, function(error, results) {
if (!error && results && results.length >= 0) {
NRS.database.insert(table, results, function(error, inserts) {});
}
});
});
setTimeout(function(){ NRS.initUserDBSuccess(); }, 1000);
}
NRS.initUserDBFail = function() {
NRS.database = null;
NRS.databaseSupport = false;
NRS.getSettings();
NRS.updateNotifications();
NRS.setUnconfirmedNotifications();
NRS.setPhasingNotifications();
}
NRS.createLegacyDatabase = function() {
var schema = {}
var versionLegacyDB = 2;
// Legacy DB before switching to account based DBs, leave schema as is
schema["contacts"] = {
id: {
"primary": true,
"autoincrement": true,
"type": "NUMBER"
},
name: "VARCHAR(100) COLLATE NOCASE",
email: "VARCHAR(200)",
account: "VARCHAR(25)",
accountRS: "VARCHAR(25)",
description: "TEXT"
}
schema["assets"] = {
account: "VARCHAR(25)",
accountRS: "VARCHAR(25)",
asset: {
"primary": true,
"type": "VARCHAR(25)"
},
description: "TEXT",
name: "VARCHAR(10)",
decimals: "NUMBER",
quantityQNT: "VARCHAR(15)",
groupName: "VARCHAR(30) COLLATE NOCASE"
}
schema["data"] = {
id: {
"primary": true,
"type": "VARCHAR(40)"
},
contents: "TEXT"
}
if (versionLegacyDB = NRS.constants.DB_VERSION) {
try {
NRS.legacyDatabase = new WebDB("NRS_USER_DB", schema, versionLegacyDB, 4, function(error, db) {
if (!error) {
NRS.legacyDatabase.select("data", [{
"id": "settings"
}], function(error, result) {
if (result && result.length > 0) {
NRS.legacyDatabaseWithData = true;
}
});
}
});
} catch (err) {
NRS.logConsole("error creating database " + err.message);
}
}
};
NRS.createDatabase = function(dbName) {
var schema = {}
schema["contacts"] = {
id: {
"primary": true,
"autoincrement": true,
"type": "NUMBER"
},
name: "VARCHAR(100) COLLATE NOCASE",
email: "VARCHAR(200)",
account: "VARCHAR(25)",
accountRS: "VARCHAR(25)",
description: "TEXT"
}
schema["assets"] = {
account: "VARCHAR(25)",
accountRS: "VARCHAR(25)",
asset: {
"primary": true,
"type": "VARCHAR(25)"
},
description: "TEXT",
name: "VARCHAR(10)",
decimals: "NUMBER",
quantityQNT: "VARCHAR(15)",
groupName: "VARCHAR(30) COLLATE NOCASE"
}
schema["polls"] = {
account: "VARCHAR(25)",
accountRS: "VARCHAR(25)",
name: "VARCHAR(100)",
description: "TEXT",
poll: "VARCHAR(25)",
finishHeight: "VARCHAR(25)"
}
schema["data"] = {
id: {
"primary": true,
"type": "VARCHAR(40)"
},
contents: "TEXT"
}
NRS.assetTableKeys = ["account", "accountRS", "asset", "description", "name", "position", "decimals", "quantityQNT", "groupName"];
NRS.pollsTableKeys = ["account", "accountRS", "poll", "description", "name", "finishHeight"];
try {
NRS.database = new WebDB(dbName, schema, NRS.constants.DB_VERSION, 4, function(error, db) {
if (!error) {
NRS.database.select("data", [{
"id": "settings"
}], function(error, result) {
if (result && result.length > 0) {
NRS.databaseFirstStart = false;
NRS.initUserDBSuccess();
} else {
NRS.databaseFirstStart = true;
if (NRS.databaseFirstStart && NRS.legacyDatabaseWithData) {
NRS.initUserDBWithLegacyData();
} else {
NRS.initUserDBSuccess();
}
}
});
} else {
NRS.initUserDBFail();
}
});
} catch (err) {
NRS.initUserDBFail();
}
};
/* Display connected state in Sidebar */
NRS.checkConnected = function() {
NRS.sendRequest("getPeers+", {
"state": "CONNECTED"
}, function(response) {
if (response.peers && response.peers.length) {
NRS.peerConnect = true;
$("#connected_indicator").addClass("connected");
$("#connected_indicator span").html($.t("Connected")).attr("data-i18n", "connected");
$("#connected_indicator").show();
} else {
NRS.peerConnect = false;
$("#connected_indicator").removeClass("connected");
$("#connected_indicator span").html($.t("Not Connected")).attr("data-i18n", "not_connected");
$("#connected_indicator").show();
}
});
};
NRS.getAccountInfo = function(firstRun, callback) {
NRS.sendRequest("getAccount", {
"account": NRS.account
}, function(response) {
var previousAccountInfo = NRS.accountInfo;
NRS.accountInfo = response;
if (response.errorCode) {
$("#account_balance, #account_balance_sidebar, #account_nr_assets, #account_assets_balance, #account_currency_count, #account_purchase_count, #account_pending_sale_count, #account_completed_sale_count, #account_message_count, #account_alias_count").html("0");
if (NRS.accountInfo.errorCode == 5) {
if (NRS.downloadingBlockchain) {
if (NRS.newlyCreatedAccount) {
$("#dashboard_message").addClass("alert-success").removeClass("alert-danger").html($.t("status_new_account", {
"account_id": String(NRS.accountRS).escapeHTML(),
"public_key": String(NRS.publicKey).escapeHTML()
}) + "<br /><br />" + $.t("status_blockchain_downloading")).show();
} else {
$("#dashboard_message").addClass("alert-success").removeClass("alert-danger").html($.t("status_blockchain_downloading")).show();
}
} else if (NRS.state && NRS.state.isScanning) {
$("#dashboard_message").addClass("alert-danger").removeClass("alert-success").html($.t("status_blockchain_rescanning")).show();
} else {
if (NRS.publicKey == "") {
$("#dashboard_message").addClass("alert-success").removeClass("alert-danger").html($.t("status_new_account_no_pk", {
"account_id": String(NRS.accountRS).escapeHTML()
})).show();
} else {
$("#dashboard_message").addClass("alert-success").removeClass("alert-danger").html($.t("status_new_account", {
"account_id": String(NRS.accountRS).escapeHTML(),
"public_key": String(NRS.publicKey).escapeHTML()
})).show();
}
}
} else {
$("#dashboard_message").addClass("alert-danger").removeClass("alert-success").html(NRS.accountInfo.errorDescription ? NRS.accountInfo.errorDescription.escapeHTML() : $.t("error_unknown")).show();
}
} else {
if (NRS.accountRS && NRS.accountInfo.accountRS != NRS.accountRS) {
$.growl("Generated Reed Solomon address different from the one in the blockchain!", {
"type": "danger"
});
NRS.accountRS = NRS.accountInfo.accountRS;
}
if (NRS.downloadingBlockchain) {
$("#dashboard_message").addClass("alert-success").removeClass("alert-danger").html($.t("status_blockchain_downloading")).show();
} else if (NRS.state && NRS.state.isScanning) {
$("#dashboard_message").addClass("alert-danger").removeClass("alert-success").html($.t("status_blockchain_rescanning")).show();
} else if (!NRS.accountInfo.publicKey) {
$("#dashboard_message").addClass("alert-danger").removeClass("alert-success").html($.t("no_public_key_warning") + " " + $.t("public_key_actions")).show();
} else {
$("#dashboard_message").hide();
}
//only show if happened within last week
var showAssetDifference = (!NRS.downloadingBlockchain || (NRS.blocks && NRS.blocks[0] && NRS.state && NRS.state.time - NRS.blocks[0].timestamp < 60 * 60 * 24 * 7));
if (NRS.databaseSupport) {
NRS.database.select("data", [{
"id": "asset_balances"
}], function(error, asset_balance) {
if (asset_balance && asset_balance.length) {
var previous_balances = asset_balance[0].contents;
if (!NRS.accountInfo.assetBalances) {
NRS.accountInfo.assetBalances = [];
}
var current_balances = JSON.stringify(NRS.accountInfo.assetBalances);
if (previous_balances != current_balances) {
if (previous_balances != "undefined" && typeof previous_balances != "undefined") {
previous_balances = JSON.parse(previous_balances);
} else {
previous_balances = [];
}
NRS.database.update("data", {
contents: current_balances
}, [{
id: "asset_balances"
}]);
if (showAssetDifference) {
NRS.checkAssetDifferences(NRS.accountInfo.assetBalances, previous_balances);
}
}
} else {
NRS.database.insert("data", {
id: "asset_balances",
contents: JSON.stringify(NRS.accountInfo.assetBalances)
});
}
});
} else if (showAssetDifference && previousAccountInfo && previousAccountInfo.assetBalances) {
var previousBalances = JSON.stringify(previousAccountInfo.assetBalances);
var currentBalances = JSON.stringify(NRS.accountInfo.assetBalances);
if (previousBalances != currentBalances) {
NRS.checkAssetDifferences(NRS.accountInfo.assetBalances, previousAccountInfo.assetBalances);
}
}
$("#account_balance, #account_balance_sidebar").html(NRS.formatStyledAmount(response.unconfirmedBalanceNQT));
$("#account_forged_balance").html(NRS.formatStyledAmount(response.forgedBalanceNQT));
/*** Need to clean up and optimize code if possible ***/
var nr_assets = 0;
var assets = {
"asset": [],
"quantity": {},
"trades": {}
};
var tradeNum = 0;
var assets_LastTrade = [];
if (response.assetBalances) {
for (var i = 0; i < response.assetBalances.length; i++) {
if (response.assetBalances[i].balanceQNT != "0") {
nr_assets++;
assets.quantity[response.assetBalances[i].asset] = response.assetBalances[i].balanceQNT;
assets.asset.push(response.assetBalances[i].asset);
NRS.sendRequest("getTrades", {
"asset": response.assetBalances[i].asset,
"firstIndex": 0,
"lastIndex": 0
}, function(responseTrade, input) {
if (responseTrade.trades && responseTrade.trades.length) {
assets.trades[input.asset] = responseTrade.trades[0].priceNQT/100000000;
}
else{
assets.trades[input.asset] = 0;
}
if (tradeNum == nr_assets-1)
NRS.updateAssetsValue(assets);
else
tradeNum++;
});
}
}
}
else {
$("#account_assets_balance").html(0);
}
$("#account_nr_assets").html(nr_assets);
if (NRS.accountInfo.accountCurrencies && NRS.accountInfo.accountCurrencies.length) {
$("#account_currency_count").empty().append(NRS.accountInfo.accountCurrencies.length);
} else {
$("#account_currency_count").empty().append("0");
}
/* Display message count in top and limit to 100 for now because of possible performance issues*/
NRS.sendRequest("getBlockchainTransactions+", {
"account": NRS.account,
"type": 1,
"subtype": 0,
"firstIndex": 0,
"lastIndex": 99
}, function(response) {
if (response.transactions && response.transactions.length) {
if (response.transactions.length > 99)
$("#account_message_count").empty().append("99+");
else
$("#account_message_count").empty().append(response.transactions.length);
} else {
$("#account_message_count").empty().append("0");
}
});
/*** ****************** ***/
NRS.sendRequest("getAliasCount+", {
"account":NRS.account
}, function(response) {
if (response.numberOfAliases != null) {
$("#account_alias_count").empty().append(response.numberOfAliases);
}
});
NRS.sendRequest("getDGSPurchaseCount+", {
"buyer": NRS.account
}, function(response) {
if (response.numberOfPurchases != null) {
$("#account_purchase_count").empty().append(response.numberOfPurchases);
}
});
NRS.sendRequest("getDGSPendingPurchases+", {
"seller": NRS.account
}, function(response) {
if (response.purchases && response.purchases.length) {
$("#account_pending_sale_count").empty().append(response.purchases.length);
} else {
$("#account_pending_sale_count").empty().append("0");
}
});
NRS.sendRequest("getDGSPurchaseCount+", {
"seller": NRS.account,
"completed": true
}, function(response) {
if (response.numberOfPurchases != null) {
$("#account_completed_sale_count").empty().append(response.numberOfPurchases);
}
});
if (NRS.lastBlockHeight) {
var isLeased = NRS.lastBlockHeight >= NRS.accountInfo.currentLeasingHeightFrom;
if (isLeased != NRS.IsLeased) {
var leasingChange = true;
NRS.isLeased = isLeased;
}
} else {
var leasingChange = false;
}
if (leasingChange ||
(response.currentLeasingHeightFrom != previousAccountInfo.currentLeasingHeightFrom) ||
(response.lessors && !previousAccountInfo.lessors) ||
(!response.lessors && previousAccountInfo.lessors) ||
(response.lessors && previousAccountInfo.lessors && response.lessors.sort().toString() != previousAccountInfo.lessors.sort().toString())) {
NRS.updateAccountLeasingStatus();
}
if (response.name) {
$("#account_name").html(response.name.escapeHTML()).removeAttr("data-i18n");
}
}
if (firstRun) {
$("#account_balance, #account_balance_sidebar, #account_assets_balance, #account_nr_assets, #account_currency_count, #account_purchase_count, #account_pending_sale_count, #account_completed_sale_count, #account_message_count, #account_alias_count").removeClass("loading_dots");
}
if (callback) {
callback();
}
});
};
NRS.updateAssetsValue = function(assets) {
var assetTotal = 0;
for (var i = 0; i < assets.asset.length; i++) {
if (assets.quantity[assets.asset[i]] && assets.trades[assets.asset[i]])
assetTotal += assets.quantity[assets.asset[i]]*assets.trades[assets.asset[i]];
}
$("#account_assets_balance").html(NRS.formatStyledAmount(new Big(assetTotal).toFixed(8)));
};
NRS.updateAccountLeasingStatus = function() {
var accountLeasingLabel = "";
var accountLeasingStatus = "";
var nextLesseeStatus = "";
if (NRS.accountInfo.nextLeasingHeightFrom < NRS.constants.MAX_INT_JAVA) {
nextLesseeStatus = $.t("next_lessee_status", {
"start": String(NRS.accountInfo.nextLeasingHeightFrom).escapeHTML(),
"end": String(NRS.accountInfo.nextLeasingHeightTo).escapeHTML(),
"account": String(NRS.convertNumericToRSAccountFormat(NRS.accountInfo.nextLessee)).escapeHTML()
})
}
if (NRS.lastBlockHeight >= NRS.accountInfo.currentLeasingHeightFrom) {
accountLeasingLabel = $.t("leased_out");
accountLeasingStatus = $.t("balance_is_leased_out", {
"blocks": String(NRS.accountInfo.currentLeasingHeightTo - NRS.lastBlockHeight).escapeHTML(),
"end": String(NRS.accountInfo.currentLeasingHeightTo).escapeHTML(),
"account": String(NRS.accountInfo.currentLesseeRS).escapeHTML()
});
$("#lease_balance_message").html($.t("balance_leased_out_help"));
} else if (NRS.lastBlockHeight < NRS.accountInfo.currentLeasingHeightTo) {
accountLeasingLabel = $.t("leased_soon");
accountLeasingStatus = $.t("balance_will_be_leased_out", {
"blocks": String(NRS.accountInfo.currentLeasingHeightFrom - NRS.lastBlockHeight).escapeHTML(),
"start": String(NRS.accountInfo.currentLeasingHeightFrom).escapeHTML(),
"end": String(NRS.accountInfo.currentLeasingHeightTo).escapeHTML(),
"account": String(NRS.accountInfo.currentLesseeRS).escapeHTML()
});
$("#lease_balance_message").html($.t("balance_leased_out_help"));
} else {
accountLeasingStatus = $.t("balance_not_leased_out");
$("#lease_balance_message").html($.t("balance_leasing_help"));
}
if (nextLesseeStatus != "") {
accountLeasingStatus += "<br>" + nextLesseeStatus;
}
if (NRS.accountInfo.effectiveBalanceNXT == 0) {
var forgingIndicator = $("#forging_indicator");
forgingIndicator.removeClass("forging");
forgingIndicator.find("span").html($.t("not_forging")).attr("data-i18n", "not_forging");
forgingIndicator.show();
NRS.isForging = false;
}
//no reed solomon available? do it myself? todo
if (NRS.accountInfo.lessors) {
if (accountLeasingLabel) {
accountLeasingLabel += ", ";
accountLeasingStatus += "<br /><br />";
}
accountLeasingLabel += $.t("x_lessor", {
"count": NRS.accountInfo.lessors.length
});
accountLeasingStatus += $.t("x_lessor_lease", {
"count": NRS.accountInfo.lessors.length
});
var rows = "";
for (var i = 0; i < NRS.accountInfo.lessorsRS.length; i++) {
var lessor = NRS.accountInfo.lessorsRS[i];
var lessorInfo = NRS.accountInfo.lessorsInfo[i];
var blocksLeft = lessorInfo.currentHeightTo - NRS.lastBlockHeight;
var blocksLeftTooltip = "From block " + lessorInfo.currentHeightFrom + " to block " + lessorInfo.currentHeightTo;
var nextLessee = "Not set";
var nextTooltip = "Next lessee not set";
if (lessorInfo.nextLesseeRS == NRS.accountRS) {
nextLessee = "You";
nextTooltip = "From block " + lessorInfo.nextHeightFrom + " to block " + lessorInfo.nextHeightTo;
} else if (lessorInfo.nextHeightFrom < NRS.constants.MAX_INT_JAVA) {
nextLessee = "Not you";
nextTooltip = "Account " + NRS.getAccountTitle(lessorInfo.nextLesseeRS) +" from block " + lessorInfo.nextHeightFrom + " to block " + lessorInfo.nextHeightTo;
}
rows += "<tr>" +
"<td><a href='#' data-user='" + String(lessor).escapeHTML() + "' class='show_account_modal_action'>" + NRS.getAccountTitle(lessor) + "</a></td>" +
"<td>" + String(lessorInfo.effectiveBalanceNXT).escapeHTML() + "</td>" +
"<td><label>" + String(blocksLeft).escapeHTML() + " <i class='fa fa-question-circle show_popover' data-toggle='tooltip' title='" + blocksLeftTooltip + "' data-placement='right' style='color:#4CAA6E'></i></label></td>" +
"<td><label>" + String(nextLessee).escapeHTML() + " <i class='fa fa-question-circle show_popover' data-toggle='tooltip' title='" + nextTooltip + "' data-placement='right' style='color:#4CAA6E'></i></label></td>" +
"</tr>";
}
$("#account_lessor_table tbody").empty().append(rows);
$("#account_lessor_container").show();
$("#account_lessor_table [data-toggle='tooltip']").tooltip();
} else {
$("#account_lessor_table tbody").empty();
$("#account_lessor_container").hide();
}
if (accountLeasingLabel) {
$("#account_leasing").html(accountLeasingLabel).show();
} else {
$("#account_leasing").hide();
}
if (accountLeasingStatus) {
$("#account_leasing_status").html(accountLeasingStatus).show();
} else {
$("#account_leasing_status").hide();
}
};
NRS.checkAssetDifferences = function(current_balances, previous_balances) {
var current_balances_ = {};
var previous_balances_ = {};
if (previous_balances && previous_balances.length) {
for (var k in previous_balances) {
previous_balances_[previous_balances[k].asset] = previous_balances[k].balanceQNT;
}
}
if (current_balances && current_balances.length) {
for (var k in current_balances) {
current_balances_[current_balances[k].asset] = current_balances[k].balanceQNT;
}
}
var diff = {};
for (var k in previous_balances_) {
if (!(k in current_balances_)) {
diff[k] = "-" + previous_balances_[k];
} else if (previous_balances_[k] !== current_balances_[k]) {
var change = (new BigInteger(current_balances_[k]).subtract(new BigInteger(previous_balances_[k]))).toString();
diff[k] = change;
}
}
for (k in current_balances_) {
if (!(k in previous_balances_)) {
diff[k] = current_balances_[k]; // property is new
}
}
var nr = Object.keys(diff).length;
if (nr == 0) {
return;
} else if (nr <= 3) {
for (k in diff) {
NRS.sendRequest("getAsset", {
"asset": k,
"_extra": {
"asset": k,
"difference": diff[k]
}
}, function(asset, input) {
if (asset.errorCode) {
return;
}
asset.difference = input["_extra"].difference;
asset.asset = input["_extra"].asset;
if (asset.difference.charAt(0) != "-") {
var quantity = NRS.formatQuantity(asset.difference, asset.decimals)
if (quantity != "0") {
$.growl($.t("you_received_assets", {
"asset": String(asset.asset).escapeHTML(),
"name": String(asset.name).escapeHTML(),
"count": quantity
}), {
"type": "success"
});
NRS.loadAssetExchangeSidebar();
}
} else {
asset.difference = asset.difference.substring(1);
var quantity = NRS.formatQuantity(asset.difference, asset.decimals)
if (quantity != "0") {
$.growl($.t("you_sold_assets", {
"asset": String(asset.asset).escapeHTML(),
"name": String(asset.name).escapeHTML(),
"count": quantity
}), {
"type": "success"
});
NRS.loadAssetExchangeSidebar();
}
}
});
}
} else {
$.growl($.t("multiple_assets_differences"), {
"type": "success"
});
}
};
NRS.checkLocationHash = function(password) {
if (window.location.hash) {
var hash = window.location.hash.replace("#", "").split(":")
if (hash.length == 2) {
if (hash[0] == "message") {
var $modal = $("#send_message_modal");
} else if (hash[0] == "send") {
var $modal = $("#send_money_modal");
} else if (hash[0] == "asset") {
NRS.goToAsset(hash[1]);
return;
} else {
var $modal = "";
}
if ($modal) {
var account_id = String($.trim(hash[1]));
$modal.find("input[name=recipient]").val(account_id.unescapeHTML()).trigger("blur");
if (password && typeof password == "string") {
$modal.find("input[name=secretPhrase]").val(password);
}
$modal.modal("show");
}
}
window.location.hash = "#";
}
};
NRS.updateBlockchainDownloadProgress = function() {
var lastNumBlocks = 5000;
$('#downloading_blockchain .last_num_blocks').html($.t('last_num_blocks', { "blocks": lastNumBlocks }));
if (!NRS.serverConnect || !NRS.peerConnect) {
$("#downloading_blockchain .db_active").hide();
$("#downloading_blockchain .db_halted").show();
} else {
$("#downloading_blockchain .db_halted").hide();
$("#downloading_blockchain .db_active").show();
var percentageTotal = 0;
var blocksLeft = undefined;
var percentageLast = 0;
if (NRS.state.lastBlockchainFeederHeight && NRS.state.numberOfBlocks <= NRS.state.lastBlockchainFeederHeight) {
percentageTotal = parseInt(Math.round((NRS.state.numberOfBlocks / NRS.state.lastBlockchainFeederHeight) * 100), 10);
blocksLeft = NRS.state.lastBlockchainFeederHeight - NRS.state.numberOfBlocks;
if (blocksLeft <= lastNumBlocks && NRS.state.lastBlockchainFeederHeight > lastNumBlocks) {
percentageLast = parseInt(Math.round(((lastNumBlocks - blocksLeft) / lastNumBlocks) * 100), 10);
}
}
if (!blocksLeft || blocksLeft < parseInt(lastNumBlocks / 2)) {
$("#downloading_blockchain .db_progress_total").hide();
} else {
$("#downloading_blockchain .db_progress_total").show();
$("#downloading_blockchain .db_progress_total .progress-bar").css("width", percentageTotal + "%");
$("#downloading_blockchain .db_progress_total .sr-only").html($.t("percent_complete", {
"percent": percentageTotal
}));
}
if (!blocksLeft || blocksLeft >= (lastNumBlocks * 2) || NRS.state.lastBlockchainFeederHeight <= lastNumBlocks) {
$("#downloading_blockchain .db_progress_last").hide();
} else {
$("#downloading_blockchain .db_progress_last").show();
$("#downloading_blockchain .db_progress_last .progress-bar").css("width", percentageLast + "%");
$("#downloading_blockchain .db_progress_last .sr-only").html($.t("percent_complete", {
"percent": percentageLast
}));
}
if (blocksLeft) {
$("#downloading_blockchain .blocks_left_outer").show();
$("#downloading_blockchain .blocks_left").html($.t("blocks_left", { "numBlocks": blocksLeft }));
}
}
};
NRS.checkIfOnAFork = function() {
if (!NRS.downloadingBlockchain) {
var onAFork = true;
if (NRS.blocks && NRS.blocks.length >= 10) {
for (var i = 0; i < 10; i++) {
if (NRS.blocks[i].generator != NRS.account) {
onAFork = false;
break;
}
}
} else {
onAFork = false;
}
if (onAFork) {
$.growl($.t("fork_warning"), {
"type": "danger"
});
}
}
};
NRS.printEnvInfo = function() {
NRS.logProperty("navigator.userAgent");
NRS.logProperty("navigator.platform");
NRS.logProperty("navigator.appVersion");
NRS.logProperty("navigator.appName");
NRS.logProperty("navigator.appCodeName");
NRS.logProperty("navigator.hardwareConcurrency");
NRS.logProperty("navigator.maxTouchPoints");
NRS.logProperty("navigator.languages");
NRS.logProperty("navigator.language");
NRS.logProperty("navigator.cookieEnabled");
NRS.logProperty("navigator.onLine");
NRS.logProperty("NRS.isTestNet");
NRS.logProperty("NRS.needsAdminPassword");
};
$("#id_search").on("submit", function(e) {
e.preventDefault();
var id = $.trim($("#id_search input[name=q]").val());
if (/NXT\-/i.test(id)) {
NRS.sendRequest("getAccount", {
"account": id
}, function(response, input) {
if (!response.errorCode) {
response.account = input.account;
NRS.showAccountModal(response);
} else {
$.growl($.t("error_search_no_results"), {
"type": "danger"
});
}
});
} else {
if (!/^\d+$/.test(id)) {
$.growl($.t("error_search_invalid"), {
"type": "danger"
});
return;
}
NRS.sendRequest("getTransaction", {
"transaction": id
}, function(response, input) {
if (!response.errorCode) {
response.transaction = input.transaction;
NRS.showTransactionModal(response);
} else {
NRS.sendRequest("getAccount", {
"account": id
}, function(response, input) {
if (!response.errorCode) {
response.account = input.account;
NRS.showAccountModal(response);
} else {
NRS.sendRequest("getBlock", {
"block": id,
"includeTransactions": "true"
}, function(response, input) {
if (!response.errorCode) {
response.block = input.block;
NRS.showBlockModal(response);
} else {
$.growl($.t("error_search_no_results"), {
"type": "danger"
});
}
});
}
});
}
});
}
});
return NRS;
}(NRS || {}, jQuery));
$(document).ready(function() {
NRS.init();
NRS.initJay();
});
function receiveMessage(event) {
if (event.origin != "file://") {
return;
}
//parent.postMessage("from iframe", "file://");
}
function _checkDOMenabled() {
var storage;
var fail;
var uid;
try {
uid = new Date;
(storage = window.localStorage).setItem(uid, uid);
fail = storage.getItem(uid) != uid;
storage.removeItem(uid);
fail && (storage = false);
} catch (exception) {}
return storage;
} |
define([
], function () {
var MyConstructor = function () {
this.testProp = false;
console.log(!this.testProp);
};
return new MyConstructor();
}); |
//= link_tree ../images
//= link_directory ../javascripts .js
//= link_directory ../stylesheets .css
//= link shopping_cart_manifest.js
|
function table(factory) {
var dom = $.create({"table":{"class":"ku-table", "cellspacing":0}});
table.base.call(this, dom);
var colgroup = $.create({"colgroup":{"class":"ku-table-colgroup"}}),
caption = $.create({"caption":{"class":"ku-table-caption"}}),
head = $.create({"thead":{"class":"ku-table-head"}}),
headRow = $.create({"tr":{"class":"ku-table-head-row"}}),
body = $.create({"tbody":{"class":"ku-table-body"}}),
foot = $.create({"tfoot":{"class":"ku-table-foot"}});
this._columns = new $.hash();
this._rows = new $.hash();
this._cells = new $.hash();
this._onCellSelect = $.observer();
this.appendChild(colgroup).colgroup(colgroup)
.appendChild(caption).caption(caption)
.appendChild(head).head(head)
.appendChild(headRow).headRow(headRow)
.appendChild(body).body(body)
.appendChild(foot).foot(foot)
.factory(factory || new table_factory())
.head().appendChild(this.headRow());
}
table.prototype = {
title: function(title){
if($.isString(title)) this.caption().innerHTML = title;
else if($.exists(title)) this.caption().appendChild(title);
return this.property("title", title);
},
factory: function(factory){ return this.property("factory", factory.table(this)); },
caption: function(caption){ return this.property("caption", caption); },
colgroup: function(colgroup){ return this.property("colgroup", colgroup); },
head: function(head){ return this.property("head", head); },
headRow: function(headRow){ return this.property("headRow", headRow); },
body: function(body){ return this.property("body", body); },
foot: function(foot){ return this.property("foot", foot); },
listColumns: function(){ return $.list(this._columns.values()); },
listRows: function(){ return $.list(this._rows.values()); },
listCells: function(){ return $.list(this._cells.values()); },
selectCell: function(cell) { this._onCellSelect.notify(cell); return this; },
onCellSelect: function(f, s) { this._onCellSelect.add(f, s); return this; },
addColumn: function(key, obj, value) {
var columns = this._columns,
rows = this._rows;
if(columns.containsKey(key)) return this._updateColumn(key, obj, value);
else return this._addColumn(key, obj, value);
},
_addColumn: function(key, obj, value){
var column = this._factory.createColumn($.uid(), key, value);
this._columns.add(column.key(), column);
$.list(this._rows.values()).each(function(row){
this.addCell(row, column, obj[row.key()]);
}, this);
this._colgroup.appendChild(column.col());
this._headRow.appendChild(column.dom());
return this;
},
_updateColumn: function(key, obj, value){
var column = this._columns.find(key);
$.list(his._rows.values()).each(function(row){
this.findCell(row.key(), column.key()).value(obj[row.key()]);
}, this);
if($.exists(value)) column.value(value);
return this;
},
findColumn: function(key){ return this._columns.find(key); },
removeColumn: function(key){
var rows = this._rows,
column = this.findColumn(key);
if(!$.exists(column)) return this;
$.list(rows.values()).each(function(row){
this.removeCell(column.findCell(row.key()));
}, this);
this._columns.remove(column.key());
return this;
},
addRow: function(key, obj) {
var rows = this._rows,
columns = this._columns;
if(rows.containsKey(key)) return this._updateRow(key, obj);
else return this._addRow(key, obj);
},
_addRow: function(key, obj){
var row = this._factory.createRow($.uid(), key);
this._rows.add(row.key(), row);
$.list(this._columns.values()).each(function(column){
this.addCell(row, column, obj[column.key()])
}, this);
this.body().appendChild(row.dom());
return this;
},
_updateRow: function(key, obj){
var row = this._rows.find(key);
$.list(this._columns.values()).each(function(column){
this.findCell(row.key(), column.key()).value(obj[column.key()]);
}, this);
return this;
},
findRow: function(key){ return this._rows.find(key); },
removeRow: function(key){
var columns = this._columns,
row = this.findRow(key);
if(!$.exists(row)) return this;
$.list(columns.values()).each(function(column){
this.removeCell(row.findCell(column.key()));
}, this);
this._rows.remove(row.key());
return this;
},
addCell: function(row, column, value){
var cell = this._factory.createCell(value, column.index(), column.key(), row.index(), row.key());
column.addCell(cell);
row.addCell(cell);
this._cells.add(cell.id(), cell);
return this;
},
findCellById: function(id){ return this._cells.find(id); },
findCell: function(rowKey, colKey){
var cells = $.list(this._cells.values()), value;
cells.each(function(cell){
if((cell.rKey() == rowKey) &&
(cell.cKey() == colKey)) {
value = cell;
cells.quit();
}
});
return value;
},
removeCell: function(cell){
this._cells.remove(cell.id());
this._columns.find(cell.cKey()).removeCell(cell);
this._rows.find(cell.rKey()).removeCell(cell);
return this;
},
format: function(){
var i = 0,
e = "ku-table-row-even",
o = "ku-table-row-odd",
cn = function(){ (i % 2 == 0) ? e : o; };
this._rows.each(function(row){
row.removeClass(e)
.removeClass(o)
.addClass(cn());
i++;
});
},
toObject: function(){
return { "title": this.title(),
"columns": this._columns.toObject(),
"rows": this._rows.toObject() }
}
}
$.Class.extend(table, $.dom.Class);
$.table = function(factory){ return new table(factory); }
$.table.Class = table; |
var searchData=
[
['local_680',['Local',['../namespacektt.html#a27feefe5217ccf7232f658cd88143f0fa509820290d57f333403f490dde7316f4',1,'ktt::Local()'],['../namespacektt.html#ac17be234b9c499fc808a40ba1fb17af5a509820290d57f333403f490dde7316f4',1,'ktt::Local()'],['../namespacektt.html#ac5bc0a65f097bc3326d6497c0f3877b0a509820290d57f333403f490dde7316f4',1,'ktt::Local()']]],
['long_681',['Long',['../namespacektt.html#a79871821a23eee2b543fec77b52c54d7a8394f0347c184cf156ac5924dccb773b',1,'ktt']]]
];
|
/*!
* SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5)
* (c) Copyright 2009-2014 SAP AG or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
/* ----------------------------------------------------------------------------------
* Hint: This is a derived (generated) file. Changes should be done in the underlying
* source files only (*.control, *.js) or they will be lost after the next generation.
* ---------------------------------------------------------------------------------- */
// Provides control sap.ui.layout.form.FormElement.
jQuery.sap.declare("sap.ui.layout.form.FormElement");
jQuery.sap.require("sap.ui.layout.library");
jQuery.sap.require("sap.ui.core.Element");
/**
* Constructor for a new form/FormElement.
*
* Accepts an object literal <code>mSettings</code> that defines initial
* property values, aggregated and associated objects as well as event handlers.
*
* If the name of a setting is ambiguous (e.g. a property has the same name as an event),
* then the framework assumes property, aggregation, association, event in that order.
* To override this automatic resolution, one of the prefixes "aggregation:", "association:"
* or "event:" can be added to the name of the setting (such a prefixed name must be
* enclosed in single or double quotes).
*
* The supported settings are:
* <ul>
* <li>Properties
* <ul>
* <li>{@link #getVisible visible} : boolean (default: true)</li></ul>
* </li>
* <li>Aggregations
* <ul>
* <li>{@link #getLabel label} : sap.ui.core.Label|string</li>
* <li>{@link #getFields fields} <strong>(default aggregation)</strong> : sap.ui.core.Control[]</li></ul>
* </li>
* <li>Associations
* <ul></ul>
* </li>
* <li>Events
* <ul></ul>
* </li>
* </ul>
*
*
* In addition, all settings applicable to the base type {@link sap.ui.core.Element#constructor sap.ui.core.Element}
* can be used as well.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* A form element is a combination of one label and different controls associated to this label.
* @extends sap.ui.core.Element
*
* @author SAP AG
* @version 1.22.5
*
* @constructor
* @public
* @since 1.16.0
* @name sap.ui.layout.form.FormElement
*/
sap.ui.core.Element.extend("sap.ui.layout.form.FormElement", { metadata : {
// ---- object ----
publicMethods : [
// methods
"getLabelControl"
],
// ---- control specific ----
library : "sap.ui.layout",
properties : {
"visible" : {type : "boolean", group : "Misc", defaultValue : true}
},
defaultAggregation : "fields",
aggregations : {
"label" : {type : "sap.ui.core.Label", altTypes : ["string"], multiple : false},
"fields" : {type : "sap.ui.core.Control", multiple : true, singularName : "field"}
}
}});
/**
* Creates a new subclass of class sap.ui.layout.form.FormElement with name <code>sClassName</code>
* and enriches it with the information contained in <code>oClassInfo</code>.
*
* <code>oClassInfo</code> might contain the same kind of informations as described in {@link sap.ui.core.Element.extend Element.extend}.
*
* @param {string} sClassName name of the class to be created
* @param {object} [oClassInfo] object literal with informations about the class
* @param {function} [FNMetaImpl] constructor function for the metadata object. If not given, it defaults to sap.ui.core.ElementMetadata.
* @return {function} the created class / constructor function
* @public
* @static
* @name sap.ui.layout.form.FormElement.extend
* @function
*/
/**
* Getter for property <code>visible</code>.
* Invisible FormElements are not rendered.
*
* Default value is <code>true</code>
*
* @return {boolean} the value of property <code>visible</code>
* @public
* @name sap.ui.layout.form.FormElement#getVisible
* @function
*/
/**
* Setter for property <code>visible</code>.
*
* Default value is <code>true</code>
*
* @param {boolean} bVisible new value for property <code>visible</code>
* @return {sap.ui.layout.form.FormElement} <code>this</code> to allow method chaining
* @public
* @name sap.ui.layout.form.FormElement#setVisible
* @function
*/
/**
* Getter for aggregation <code>label</code>.<br/>
* Label of the fields. Can either be a Label object, or a simple string.
*
* @return {sap.ui.core.Label|string}
* @public
* @name sap.ui.layout.form.FormElement#getLabel
* @function
*/
/**
* Setter for the aggregated <code>label</code>.
* @param {sap.ui.core.Label|string} oLabel
* @return {sap.ui.layout.form.FormElement} <code>this</code> to allow method chaining
* @public
* @name sap.ui.layout.form.FormElement#setLabel
* @function
*/
/**
* Destroys the label in the aggregation
* named <code>label</code>.
* @return {sap.ui.layout.form.FormElement} <code>this</code> to allow method chaining
* @public
* @name sap.ui.layout.form.FormElement#destroyLabel
* @function
*/
/**
* Getter for aggregation <code>fields</code>.<br/>
* Formular controls.
*
* <strong>Note</strong>: this is the default aggregation for form/FormElement.
* @return {sap.ui.core.Control[]}
* @public
* @name sap.ui.layout.form.FormElement#getFields
* @function
*/
/**
* Inserts a field into the aggregation named <code>fields</code>.
*
* @param {sap.ui.core.Control}
* oField the field to insert; if empty, nothing is inserted
* @param {int}
* iIndex the <code>0</code>-based index the field should be inserted at; for
* a negative value of <code>iIndex</code>, the field is inserted at position 0; for a value
* greater than the current size of the aggregation, the field is inserted at
* the last position
* @return {sap.ui.layout.form.FormElement} <code>this</code> to allow method chaining
* @public
* @name sap.ui.layout.form.FormElement#insertField
* @function
*/
/**
* Adds some field <code>oField</code>
* to the aggregation named <code>fields</code>.
*
* @param {sap.ui.core.Control}
* oField the field to add; if empty, nothing is inserted
* @return {sap.ui.layout.form.FormElement} <code>this</code> to allow method chaining
* @public
* @name sap.ui.layout.form.FormElement#addField
* @function
*/
/**
* Removes an field from the aggregation named <code>fields</code>.
*
* @param {int | string | sap.ui.core.Control} vField the field to remove or its index or id
* @return {sap.ui.core.Control} the removed field or null
* @public
* @name sap.ui.layout.form.FormElement#removeField
* @function
*/
/**
* Removes all the controls in the aggregation named <code>fields</code>.<br/>
* Additionally unregisters them from the hosting UIArea.
* @return {sap.ui.core.Control[]} an array of the removed elements (might be empty)
* @public
* @name sap.ui.layout.form.FormElement#removeAllFields
* @function
*/
/**
* Checks for the provided <code>sap.ui.core.Control</code> in the aggregation named <code>fields</code>
* and returns its index if found or -1 otherwise.
*
* @param {sap.ui.core.Control}
* oField the field whose index is looked for.
* @return {int} the index of the provided control in the aggregation if found, or -1 otherwise
* @public
* @name sap.ui.layout.form.FormElement#indexOfField
* @function
*/
/**
* Destroys all the fields in the aggregation
* named <code>fields</code>.
* @return {sap.ui.layout.form.FormElement} <code>this</code> to allow method chaining
* @public
* @name sap.ui.layout.form.FormElement#destroyFields
* @function
*/
/**
* Returns the Label Control, even if the Label is entered as Text.
*
* @name sap.ui.layout.form.FormElement.prototype.getLabelControl
* @function
* @type sap.ui.core.Label
* @public
*/
// Start of sap\ui\layout\form\FormElement.js
/**
* This file defines behavior for the control,
*/
jQuery.sap.require("sap.ui.core.EnabledPropagator");
// TODO deactivated until Element/Control has been clarified: sap.ui.core.EnabledPropagator.call(sap.ui.layout.form.FormElement.prototype);
(function() {
sap.ui.layout.form.FormElement.prototype.init = function(){
this._oFieldDelegate = {oElement: this, onAfterRendering: _fieldOnAfterRendering};
};
sap.ui.layout.form.FormElement.prototype.exit = function(){
if (this._oLabel) {
this._oLabel.destroy();
delete this._oLabel;
}
this._oFieldDelegate = undefined;
};
/*
* sets the label for the FormElement. If it's only a string an internal label is created.
* overwrite the isRequired and the getLabelForRendering functions with Form specific ones.
*/
sap.ui.layout.form.FormElement.prototype.setLabel = function(vAny) {
if (!this._oLabel) {
var oOldLabel = this.getLabel();
if (oOldLabel) {
if (oOldLabel.isRequired) {
oOldLabel.isRequired = oOldLabel._sapui_isRequired;
oOldLabel._sapui_isRequired = undefined;
}
if (oOldLabel.getLabelForRendering) {
oOldLabel.getLabelForRendering = oOldLabel._sapui_getLabelForRendering;
oOldLabel._sapui_getLabelForRendering = undefined;
}
}
}
this.setAggregation("label", vAny);
var oLabel = vAny;
if (typeof oLabel === "string") {
if (!this._oLabel) {
this._oLabel = sap.ui.layout.form.FormHelper.createLabel(oLabel);
this._oLabel.setParent(this);
if (oLabel.isRequired) {
this._oLabel.isRequired = _labelIsRequired;
}
this._oLabel.getLabelForRendering = _getLabelForRendering;
}else{
this._oLabel.setText(oLabel);
}
} else {
if (this._oLabel) {
this._oLabel.destroy();
delete this._oLabel;
}
if (!oLabel) return this; //set label is called with null if label is removed by ManagedObject.removeChild
if (oLabel.isRequired) {
oLabel._sapui_isRequired = oLabel.isRequired;
oLabel.isRequired = _labelIsRequired;
}
if (oLabel.getLabelForRendering) {
oLabel._sapui_getLabelForRendering = oLabel.getLabelForRendering;
oLabel.getLabelForRendering = _getLabelForRendering;
}
}
return this;
};
sap.ui.layout.form.FormElement.prototype.getLabelControl = function() {
if (this._oLabel) {
return this._oLabel;
} else {
return this.getLabel();
}
};
sap.ui.layout.form.FormElement.prototype.addField = function(oField) {
this.addAggregation("fields", oField);
oField.addDelegate(this._oFieldDelegate);
return this;
};
sap.ui.layout.form.FormElement.prototype.insertField = function(oField, iIndex) {
this.insertAggregation("fields", oField, iIndex);
oField.addDelegate(this._oFieldDelegate);
return this;
};
sap.ui.layout.form.FormElement.prototype.removeField = function(oField) {
var oRemovedField = this.removeAggregation("fields", oField);
oRemovedField.removeDelegate(this._oFieldDelegate);
return oRemovedField;
};
sap.ui.layout.form.FormElement.prototype.removeAllFields = function() {
var aRemovedFields = this.removeAllAggregation("fields");
for ( var i = 0; i < aRemovedFields.length; i++) {
var oRemovedField = aRemovedFields[i];
oRemovedField.removeDelegate(this._oFieldDelegate);
}
return aRemovedFields;
};
sap.ui.layout.form.FormElement.prototype.destroyFields = function() {
var aFields = this.getFields();
for ( var i = 0; i < aFields.length; i++) {
var oField = aFields[i];
oField.removeDelegate(this._oFieldDelegate);
}
this.destroyAggregation("fields");
return this;
};
sap.ui.layout.form.FormElement.prototype.updateFields = function() {
var aFields = this.getFields();
for ( var i = 0; i < aFields.length; i++) {
var oField = aFields[i];
oField.removeDelegate(this._oFieldDelegate);
}
this.updateAggregation("fields");
aFields = this.getFields();
for ( var i = 0; i < aFields.length; i++) {
var oField = aFields[i];
oField.addDelegate(this._oFieldDelegate);
}
return this;
};
/*
* Enhance Aria properties of fields to set aria-labelledby to FormElements label if not set otherwise
* Set aria-describedby to the title of the container, but only for the first field in the container
* This function is called during rendering.
*/
sap.ui.layout.form.FormElement.prototype.enhanceAccessibilityState = function(oElement, mAriaProps) {
var oLabel = this.getLabelControl();
if (oLabel && oLabel != oElement) {
if (!mAriaProps["labelledby"]) {
mAriaProps["labelledby"] = oLabel.getId();
}
var oContainer = this.getParent();
var aElements = oContainer.getFormElements();
if (this == aElements[0]) {
// it's the first Element
var aControls = this.getFields();
if (oElement == aControls[0]) {
//it's the first field
var oTitle = oContainer.getTitle();
if (oTitle) {
var sId = "";
if (typeof oTitle == "string") {
sId = oContainer.getId()+"--title";
} else {
sId = oTitle.getId();
}
var sDescribedBy = mAriaProps["describedby"];
if (sDescribedBy) {
sDescribedBy = sDescribedBy + " " + sId;
} else {
sDescribedBy = sId;
}
mAriaProps["describedby"] = sDescribedBy;
}
}
}
}
return mAriaProps;
};
/*
* If LayoutData changed on control this may need changes on the layout. So bubble to the form
*/
sap.ui.layout.form.FormElement.prototype.onLayoutDataChange = function(oEvent){
// call function of parent (if assigned)
var oParent = this.getParent();
if (oParent && oParent.onLayoutDataChange) {
oParent.onLayoutDataChange(oEvent);
}
};
// *** Private helper functions ***
/*
* overwrite Labels isRequired function to check if one of the fields in the element is required,
* not only the one directly assigned.
*/
var _labelIsRequired = function(){
var oFormElement = this.getParent();
var aFields = oFormElement.getFields();
for ( var i = 0; i < aFields.length; i++) {
var oField = aFields[i];
if (oField.getRequired && oField.getRequired() === true) {
return true;
}
}
return false;
};
/*
* overwrite Labels getLabelForRendering function to point always to the first field.
* But only if the application does not set a labelFor explicitly.
*/
var _getLabelForRendering = function(){
if (this.getLabelFor()) {
return this.getLabelFor();
}else {
var oFormElement = this.getParent();
var aFields = oFormElement.getFields();
if (aFields[0]) {
return aFields[0].getId();
}
}
};
/*
* If onAfterRendering of a field is processed the Form (layout) might need to change it.
*/
var _fieldOnAfterRendering = function(oEvent){
// call function of parent (if assigned)
var oParent = this.oElement.getParent();
if (oParent && oParent.contentOnAfterRendering) {
oParent.contentOnAfterRendering( this.oElement, oEvent.srcControl);
}
};
}()); |
/* eslint-env node, mocha */
var chai = require('chai');
chai.use(require('chai-string'));
chai.use(require('chai-spies'));
var expect = chai.expect;
var alexaAseagSkill = require('../index');
describe('alexa-aseag-skill', function() {
const locales = ['en-GB', 'de-DE'];
locales.forEach(function(locale) {
describe('#TimetableIntent - ' + locale, function() {
it('should work for Kuckelkorn', function(done) {
this.timeout(5000);
fakeIntentRequest({
locale,
intent: {
name: 'TimetableIntent',
slots: {
Stage: {
value: 'Kuckelkorn'
}
}
}
}, function(err, response) {
if (err) {
done(err);
} else {
// console.log(response);
done();
}
});
});
it('should work for kuckelkorn', function(done) {
this.timeout(5000);
fakeIntentRequest({
locale,
intent: {
name: 'TimetableIntent',
slots: {
Stage: {
value: 'Kuckelkorn'
}
}
}
}, function(err, response) {
if (err) {
done(err);
} else {
// console.log(response);
done();
}
});
});
});
});
describe('#TimetableIntent - empty Stage slot', function() {
it('should emit HelpIntent if Stage slot has no value', function(done) {
let skill = fakeIntentRequest({
intent: {
name: 'TimetableIntent',
slots: {
Stage: {
name: 'Stage'
}
}
}
}, function(err, response) {
if(err) {
done(err);
} else {
done();
}
});
let spyEmit = chai.spy(skill.emit);
expect(spyEmit).to.be.called.with('AMAZON.HelpIntent');
});
});
describe('Built in intents', function() {
it('should emit :tell on LaunchRequest', function(done) {
let skill = fakeIntentRequest({
intent: {
name: 'AMAZON.CancelIntent',
}
}, function(err, response) {
if(err) {
done(err);
} else {
done();
}
});
let spyEmit = chai.spy(skill.emit);
expect(spyEmit).to.be.called.with(':tell');
});
it('should emit StopIntent on AMAZON.CancelIntent', function(done) {
let skill = fakeIntentRequest({
intent: {
name: 'AMAZON.CancelIntent',
}
}, function(err, response) {
if(err) {
done(err);
} else {
done();
}
});
let spyEmit = chai.spy(skill.emit);
expect(spyEmit).to.be.called.with('StopIntent');
});
it('should emit StopIntent on AMAZON.StopIntent', function(done) {
let skill = fakeIntentRequest({
intent: {
name: 'AMAZON.StopIntent',
}
}, function(err, response) {
if(err) {
done(err);
} else {
done();
}
});
let spyEmit = chai.spy(skill.emit);
expect(spyEmit).to.be.called.with('StopIntent');
});
it('should emit :ask on AMAZON.HelpIntent', function(done) {
let skill = fakeIntentRequest({
intent: {
name: 'AMAZON.HelpIntent',
}
}, function(err, response) {
if(err) {
done(err);
} else {
done();
}
});
let spyEmit = chai.spy(skill.emit);
expect(spyEmit).to.be.called.with(':ask');
});
});
});
function fakeIntentRequest(options, callback) {
var intent = options.intent || {};
var locale = options.locale || 'en-GB';
return alexaAseagSkill.handler({
request: {
locale: locale,
type: options.intent
? 'IntentRequest'
: LaunchRequest,
intent: intent
},
session: {
application: {
applicationId: process.env['APP_ID']
},
user: {
userId: 'testUser'
}
}
}, {
fail: callback,
succeed: function(response) {
callback(null, response);
}
});
}
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define("require exports ../../../../core/has ../../../../core/maybe ../../../../core/now ../../../../core/libs/gl-matrix-2/mat4f64 ../../../../core/libs/gl-matrix-2/vec3 ../../../../core/libs/gl-matrix-2/vec3f64 ../../support/geometryUtils ./intersectorUtils".split(" "),function(h,k,v,q,w,u,r,g,p,m){Object.defineProperty(k,"__esModule",{value:!0});h=function(){function a(c){this.options=new m.IntersectorOptions;this.results=new m.IntersectorResults;this.transform=new m.IntersectorTransform;this.performanceInfo=
{queryDuration:0,numObjectsTested:0};this.tolerance=1E-5;this.verticalOffset=null;this._ray={origin:g.vec3f64.create(),direction:g.vec3f64.create()};this._rayEndPoint=g.vec3f64.create();this._rayStartPointTransformed=g.vec3f64.create();this._rayEndPointTransformed=g.vec3f64.create();this.viewingMode=c||"global"}Object.defineProperty(a.prototype,"ray",{get:function(){return this._ray},enumerable:!0,configurable:!0});Object.defineProperty(a.prototype,"rayBeginPoint",{get:function(){return this._ray.origin},
enumerable:!0,configurable:!0});Object.defineProperty(a.prototype,"rayEndPoint",{get:function(){return this._rayEndPoint},enumerable:!0,configurable:!0});a.prototype.reset=function(c,b){this.resetWithRay(p.ray.fromPoints(c,b,this._ray))};a.prototype.resetWithRay=function(c){c!==this._ray&&p.ray.copy(c,this._ray);0!==this.options.verticalOffset?"local"===this.viewingMode?this._ray.origin[2]-=this.options.verticalOffset:this.verticalOffset=this.options.verticalOffset:this.verticalOffset=null;r.vec3.add(this._rayEndPoint,
this._ray.origin,this._ray.direction);this._numObjectsTested=0;this.results.init(this._ray)};a.prototype.intersect=function(c,b,a,l,f,t){var g=this;this.point=b;this.camera=a;this.filterPredicate=f;this.tolerance=null==l?1E-5:l;b=m.getVerticalOffsetObject3D(this.verticalOffset);a=t?function(b){t(b)&&g.intersectObject(b)}:function(b){g.intersectObject(b)};if(c&&0<c.length)for(l=0;l<c.length;l++){f=c[l];var e=f.getSpatialQueryAccelerator&&f.getSpatialQueryAccelerator();if(e)q.isSome(b)?e.forEachAlongRayWithVerticalOffset(this._ray.origin,
this._ray.direction,a,b):e.forEachAlongRay(this._ray.origin,this._ray.direction,a),this.options.selectionMode&&this.options.hud&&e.forEachDegenerateObject(a);else for(e=0,f=f.getObjects();e<f.length;e++)a(f[e])}this.sortResults()};a.prototype.intersectObject=function(c){var b=this;this._numObjectsTested++;var a=c.geometryRecords;if(a)for(var l=c.id,f=c.objectTransformation,g,h=m.getVerticalOffsetObject3D(this.verticalOffset),e=function(a){var e=a.geometry,n=a.material,k=a.instanceParameters;if(k.hidden)return"continue";
g=e.id;d.transform.setAndInvalidateLazyTransforms(f,a.getShaderTransformation());r.vec3.transformMat4(d._rayStartPointTransformed,d._ray.origin,d.transform.inverse);r.vec3.transformMat4(d._rayEndPointTransformed,d._rayEndPoint,d.transform.inverse);var p=d.transform.transform;q.isSome(h)&&(h.objectTransform=d.transform);n.intersect(e,k,d.transform.transform,d,d._rayStartPointTransformed,d._rayEndPointTransformed,function(a,d,e,f,h,k){0<=a&&(!q.isSome(b.filterPredicate)||b.filterPredicate(b._ray.origin,
b._rayEndPoint,a))&&(h?(null==b.results.hud.dist||a<b.results.hud.dist)&&b.results.hud.set(c,l,a,d,u.mat4f64.IDENTITY,f,k,g,e):(h=function(b){return b.set(c,l,a,d,p,f,null,g,e)},(null==b.results.min.drapedLayerOrder||f>=b.results.min.drapedLayerOrder)&&(null==b.results.min.dist||a<b.results.min.dist)&&h(b.results.min),0!==b.options.store&&(null==b.results.max.drapedLayerOrder||f<b.results.max.drapedLayerOrder)&&(null==b.results.max.dist||a>b.results.max.dist)&&h(b.results.max),2===b.options.store&&
(k=new m.IntersectorResult(b._ray),h(k),b.results.all.push(k))))},a.shaderTransformation)},d=this,n=0;n<a.length;n++)e(a[n])};a.prototype.sortResults=function(){this.results.all.sort(function(a,b){return a.dist!==b.dist?a.dist-b.dist:a.drapedLayerOrder!==b.drapedLayerOrder?(void 0!==a.drapedLayerOrder?a.drapedLayerOrder:Number.MAX_VALUE)-(void 0!==b.drapedLayerOrder?b.drapedLayerOrder:Number.MAX_VALUE):(void 0!==b.drapedLayerGraphicOrder?b.drapedLayerGraphicOrder:Number.MIN_VALUE)-(void 0!==a.drapedLayerGraphicOrder?
a.drapedLayerGraphicOrder:Number.MIN_VALUE)})};a.DEFAULT_TOLERANCE=1E-5;return a}();k.Intersector=h}); |
/*! firebase-admin v5.5.1 */
"use strict";
/*!
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
var error_1 = require("../utils/error");
var api_request_1 = require("../utils/api-request");
var error_2 = require("../utils/error");
var validator = require("../utils/validator");
// FCM backend constants
var FIREBASE_MESSAGING_PORT = 443;
var FIREBASE_MESSAGING_TIMEOUT = 10000;
var FIREBASE_MESSAGING_HTTP_METHOD = 'POST';
var FIREBASE_MESSAGING_HEADERS = {
'Content-Type': 'application/json',
'Sdk-Version': 'Node/Admin/5.5.1',
access_token_auth: 'true',
};
/**
* Class that provides a mechanism to send requests to the Firebase Cloud Messaging backend.
*/
var FirebaseMessagingRequestHandler = /** @class */ (function () {
/**
* @param {FirebaseApp} app The app used to fetch access tokens to sign API requests.
* @constructor
*/
function FirebaseMessagingRequestHandler(app) {
this.signedApiRequestHandler = new api_request_1.SignedApiRequestHandler(app);
}
/**
* @param {Object} response The response to check for errors.
* @return {string|null} The error code if present; null otherwise.
*/
FirebaseMessagingRequestHandler.getErrorCode = function (response) {
if (validator.isNonNullObject(response) && 'error' in response) {
if (typeof response.error === 'string') {
return response.error;
}
else {
return response.error.message;
}
}
return null;
};
/**
* Invokes the request handler with the provided request data.
*
* @param {string} host The host to which to send the request.
* @param {string} path The path to which to send the request.
* @param {Object} requestData The request data.
* @return {Promise<Object>} A promise that resolves with the response.
*/
FirebaseMessagingRequestHandler.prototype.invokeRequestHandler = function (host, path, requestData) {
return this.signedApiRequestHandler.sendRequest(host, FIREBASE_MESSAGING_PORT, path, FIREBASE_MESSAGING_HTTP_METHOD, requestData, FIREBASE_MESSAGING_HEADERS, FIREBASE_MESSAGING_TIMEOUT).then(function (response) {
// Send non-JSON responses to the catch() below where they will be treated as errors.
if (typeof response === 'string') {
return Promise.reject({
error: response,
statusCode: 200,
});
}
// Check for backend errors in the response.
var errorCode = FirebaseMessagingRequestHandler.getErrorCode(response);
if (errorCode) {
return Promise.reject({
error: response,
statusCode: 200,
});
}
// Return entire response.
return response;
})
.catch(function (response) {
// Re-throw the error if it already has the proper format.
if (response instanceof error_1.FirebaseError) {
throw response;
}
else if (response.error instanceof error_1.FirebaseError) {
throw response.error;
}
// Add special handling for non-JSON responses.
if (typeof response.error === 'string') {
var error = void 0;
switch (response.statusCode) {
case 400:
error = error_2.MessagingClientErrorCode.INVALID_ARGUMENT;
break;
case 401:
case 403:
error = error_2.MessagingClientErrorCode.AUTHENTICATION_ERROR;
break;
case 500:
error = error_2.MessagingClientErrorCode.INTERNAL_ERROR;
break;
case 503:
error = error_2.MessagingClientErrorCode.SERVER_UNAVAILABLE;
break;
default:
// Treat non-JSON responses with unexpected status codes as unknown errors.
error = error_2.MessagingClientErrorCode.UNKNOWN_ERROR;
}
throw new error_2.FirebaseMessagingError({
code: error.code,
message: error.message + " Raw server response: \"" + response.error + "\". Status code: " +
(response.statusCode + "."),
});
}
// For JSON responses, map the server response to a client-side error.
var errorCode = FirebaseMessagingRequestHandler.getErrorCode(response.error);
throw error_2.FirebaseMessagingError.fromServerError(errorCode, /* message */ undefined, response.error);
});
};
return FirebaseMessagingRequestHandler;
}());
exports.FirebaseMessagingRequestHandler = FirebaseMessagingRequestHandler;
|
import {
sanitize,
sanitizeElement
} from './utils/sanitize';
import SanitizeMixin from './mixins/sanitize';
export {
sanitize,
sanitizeElement,
SanitizeMixin
}; |
var EcommerceOrders = function () {
var initPickers = function () {
//init date pickers
$('.date-picker').datepicker({
rtl: Metronic.isRTL(),
autoclose: true
});
}
var handleOrders = function () {
var grid = new Datatable();
grid.init({
src: $("#datatable_orders"),
onSuccess: function (grid) {
// execute some code after table records loaded
},
onError: function (grid) {
// execute some code on network or other general error
},
dataTable: { // here you can define a typical datatable settings from http://datatables.net/usage/options
"lengthMenu": [
[20, 50, 100, 150, -1],
[20, 50, 100, 150, "All"] // change per page values here
],
"pageLength": 20, // default record count per page
"ajax": {
"url": "demo/ecommerce_orders.php", // ajax source
},
"order": [
[1, "asc"]
] // set first column as a default sort by asc
}
});
// handle group actionsubmit button click
grid.getTableWrapper().on('click', '.table-group-action-submit', function (e) {
e.preventDefault();
var action = $(".table-group-action-input", grid.getTableWrapper());
if (action.val() != "" && grid.getSelectedRowsCount() > 0) {
grid.setAjaxParam("customActionType", "group_action");
grid.setAjaxParam("customActionName", action.val());
grid.setAjaxParam("id", grid.getSelectedRows());
grid.getDataTable().ajax.reload();
grid.clearAjaxParams();
} else if (action.val() == "") {
Metronic.alert({
type: 'danger',
icon: 'warning',
message: 'Please select an action',
container: grid.getTableWrapper(),
place: 'prepend'
});
} else if (grid.getSelectedRowsCount() === 0) {
Metronic.alert({
type: 'danger',
icon: 'warning',
message: 'No record selected',
container: grid.getTableWrapper(),
place: 'prepend'
});
}
});
}
return {
//main function to initiate the module
init: function () {
initPickers();
handleOrders();
}
};
}(); |
/**
* Developer: Ksenia Kartvelishvili
* Date: 28.11.2014
* Copyright: 2009-2014 Comindware®
* All Rights Reserved
*
* THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Comindware
* The copyright notice above does not evidence any
* actual or intended publication of such source code.
*/
import list from 'list';
import { htmlHelpers } from 'utils';
import template from '../templates/membersListItem.html';
export default Marionette.ItemView.extend({
templateHelpers() {
return {
isGroup: this.model.get('type') === 'groups'
};
},
ui: {
name: '.js-name'
},
behaviors: {
ListItemViewBehavior: {
behaviorClass: list.views.behaviors.ListItemViewBehavior
}
},
onHighlighted(fragment) {
const text = htmlHelpers.highlightText(this.model.get('name'), fragment);
this.ui.name.html(text);
},
onUnhighlighted() {
this.ui.name.text(this.model.get('name'));
},
template: Handlebars.compile(template)
});
|
/**
* Created by trnay on 2017/01/12.
*/
'use strict';
angular.module('canvasJoin', [
'ngRoute',
'logoHeader'
]); |
module.exports = function assert(cond, message) {
if (!cond) {
throw new Error(message);
}
};
|
module.exports = {
env: {
browser: true,
es6: true,
'jest/globals': true,
},
extends: 'airbnb-base',
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly',
},
parserOptions: {
ecmaVersion: 2018,
},
plugins: ['jest'],
rules: {
'no-unused-vars': 1,
'no-param-reassign': ['error', { props: false }],
'no-restricted-syntax': ['error', 'ForInStatement', 'LabeledStatement', 'WithStatement'],
'jest/no-disabled-tests': 'warn',
'jest/no-focused-tests': 'error',
'jest/no-identical-title': 'error',
'jest/prefer-to-have-length': 'warn',
'jest/valid-expect': 'error',
},
};
|
var fs = require("fs");
var express = require("express");
var https = require('https');
var http = require('http');
/////////////////////////////////////////////
var HTTP_PORT = 3102;
var HTTPS_PORT = 3101;
/////////////////////////////////////////////
var app = express();
// Route all Traffic to Secure Server
// Order is important (this should be the first route)
app.all('*', function(req, res, next){
if (req.secure) {
return next();
};
res.redirect('https://localhost:'+HTTPS_PORT+req.url);
// res.redirect('https://'+req.hostname+':'+HTTPS_PORT+req.url);
});
// Hello World
app.get('/', function (req, res) {
res.send('Hello World!');
});
/////////////////////////////////////////////
// Setup Servers
// HTTPS
var secureServer = https.createServer({
key: fs.readFileSync('keys/private.key'),
cert: fs.readFileSync('keys/certificate.pem')
}, app)
.listen(HTTPS_PORT, function () {
console.log('Secure Server listening on port ' + HTTPS_PORT);
});
var insecureServer = http.createServer(app).listen(HTTP_PORT, function() {
console.log('Insecure Server listening on port ' + HTTP_PORT);
})
|
version https://git-lfs.github.com/spec/v1
oid sha256:b61ede29ddb0328c7b5128fc67de19a398ef803b361667669ae06e9f1e214b0c
size 45395
|
//Header copied from jQuery
(function(global, factory) {
/* istanbul ignore else */
if ((typeof module == "object") && (typeof module.exports == "object")) {
// For CommonJS and CommonJS-like environments where a proper window
// is present execute the factory and get Fluid
// For environments that do not inherently posses a window with a
// document (such as Node.js), expose a Fluid-making factory as
// module.exports
// This accentuates the need for the creation of a real window
// e.g. var Fluid = require("./fluid.js")(window);
module.exports =
global.jQuery && /* istanbul ignore next */ global.Fluid ?
/* istanbul ignore next */ factory(global, global.jQuery,
global.Fluid)
: factory;
} else {
return factory(global, jQuery, Fluid);
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ?
/* istanbul ignore next */ window : this, function(window, $, Fluid){
"use strict";
/****************************************************************************
* EXTENTION STATE VARIABLES
****************************************************************************
*
* ctMap - A map from hashes to custom type objects
* ctListeners - A map from hashes to functions listening to the element
* ctCursorPos - A map from hashes to cursor positions
*
* listeners - The function or object passed at declaration
* listenTrgts - Map from selectors to places where the data needs to be
* pushed. Either the same as listeners or the result of
* calling listeners
* prevValues - Values of elements the last time they were checked.
* Formatted, rather than stripped, values are used. Used
* so that a value will only be pushed if it is different
* from the last value pushed.
* Map from selectors or custom type hashes to values.
*
***************************************************************************/
/*************************************\
* Helper Functions for Custom Types *
\*************************************/
//TODO remove ignore when jsdom fixes get pushed
/* istanbul ignore next */
function setCursorPos($elem, start, end, ctHash, view)
{
var elem = $elem[0];
if( (elem instanceof window.HTMLInputElement) ||
(elem instanceof window.HTMLTextAreaElement)) try {
if(arguments.length == 2)
end = start;
start = Math.min(start, end = Math.min(end, $elem.val().length));
/* istanbul ignore else */
if(elem.setSelectionRange)
elem.setSelectionRange(start, end);
else {
//IE<=8
var rng = elem.createTextRange();
rng.collapse(true);
rng.moveStart('character', start);
rng.moveEnd('character', end);
rng.select()
}
if(ctHash)
ctLogCursor(view, ctHash, $elem);
} catch(ex) {}
}
//TODO remove ignore when jsdom fixes get pushed
/* istanbul ignore next */
function getTextSel($elem) {
var elem = $elem[0];
if( (elem instanceof window.HTMLInputElement) ||
(elem instanceof window.HTMLTextAreaElement)) try {
/* istanbul ignore else */
if(elem.setSelectionRange)
return {s: elem.selectionStart, e: elem.selectionEnd};
else {
//IE<=8
var sel = document.selection.createRange();
var selLen = sel.text.length;
sel.moveStart('character', -elem.value.length);
var end = sel.text.length;
return {s: end-selLen, e: end};
}
} catch(ex) {}
return {s: 0, e: 0};
}
//TODO remove ignore when jsdom fixes get pushed
/* istanbul ignore next */
function sanitizeSelection(sel, oldSel, val, formatChars)
{
(window.x = window.x || []).push({s: sel.s, e: sel.e,
oS: oldSel.s, oE: oldSel.e});
//Find right of the start's strip of format chars
var right = sel.s;
while((right < val.length) && formatChars(val[right]))
right++;
//Find left side of the end's strip of format chars
var left = sel.e;
while((left > 0) && formatChars(val[left-1]))
left--;
//CASE 0: Not touching format chars
if((sel.s == right) && (sel.e == left))
return false;
if(sel.s == sel.e) {
//CASE 1: Moving cursor through format chars
if((oldSel.s == oldSel.e) && (sel.e != oldSel.e)) {
if(oldSel.s == right) {
sel.s = sel.e = Math.max(left-1, 0);
return true;
}
if(oldSel.s == left) {
sel.s = sel.e = Math.min(right+1, val.length);
return true;
}
}
//CASE 2: Cursor in middle
if((sel.s != right) && (sel.e != left)) {
sel.s = sel.e = right;
return true;
}
//CASE 3: Cursor on side
return false;
} else {
//CASE 4: Selection
sel.s = right;
sel.e = left;
return true;
}
}
function ctLogCursor(view, hash, $elem) {
var sel = getTextSel($elem);
var val = ""+$elem.val();
//TODO remove ignore when jsdom fixes get pushed
/* istanbul ignore if */
if((view.prevValues[hash] == val) && sanitizeSelection(sel,
view.ctCursorPos[hash], val, view.ctMap[hash].formatChars))
setCursorPos($elem, sel.s, sel.e, hash, view);
else
view.ctCursorPos[hash] = sel;
}
//TODO remove ignore when jsdom fixes get pushed
/* istanbul ignore next */
function transIndex(formatChars, index, src, dest) {
var valCharsToPass = 0;
var i;
for(i = 0; i < index; i++)
if(!formatChars(src[i]))
valCharsToPass++;
for(i = 0; (i < dest.length) && (valCharsToPass > 0); i++)
if(!formatChars(dest[i]))
valCharsToPass--;
while((i < dest.length) && formatChars(dest[i]))
i++;
return i;
}
//TODO remove ignore when jsdom fixes get pushed
/* istanbul ignore next */
function ctSpecialCaseUpdate($elem, type, cursor, curr, prev, hash,view){
//The only special case we have is backspace/delete keys
if((curr.length != prev.length-1) || (cursor.s != cursor.e))
return false;
cursor = cursor.s;
var bksp = false;
var del = false;
if(cursor == 0) {
if(prev.slice(1) == curr)
del = true;
else
return false;
} else if(cursor == prev.length) {
if(prev.slice(0, -1) == curr)
bksp = true;
else
return false;
} else {
if( (prev.substr(0, cursor-1) != curr.substr(0, cursor-1)) ||
(prev.substr(cursor+1) != curr.substr(cursor)))
return false;
var p = prev.substr(cursor-1, 2);
var c = curr.substr(cursor-1, 1);
if(p[0] == c)
del = true;
else if(p[1] == c)
bksp = true;
else
return false;
}
var val = null;
if(bksp) {
while((cursor > 0) && type.formatChars(prev[cursor-1]))
cursor--;
if(cursor == 0)
return false;
val = type.unformat(prev.slice(0, cursor-1)+prev.slice(cursor));
cursor--;
} else if(del) {
var i = cursor;
while((i < prev.length) && type.formatChars(prev[i]))
i++;
if(i == prev.length)
return false;
val = type.unformat(prev.slice(0, i) + prev.slice(i+1));
}
if((val == null) || !type.validate(val))
return false;
$elem.val(type.format(val));
setCursorPos($elem, cursor, cursor, hash, view);
return true;
}
function ctReformat($elem, type, curr, fVal, hash, view) {
var newTextSel = undefined;
if($elem.is(":focus")) {
var sel = getTextSel($elem);
newTextSel = {
s: transIndex(type.formatChars, sel.s, curr, fVal),
e: transIndex(type.formatChars, sel.e, curr, fVal)
};
}
$elem.val(fVal);
if(newTextSel != undefined)
setCursorPos($elem, newTextSel.s, newTextSel.e, hash, view);
}
function revertInvalid($elem, prevVal, oldSel) {
$elem.val(prevVal);
//TODO remove ignore when jsdom fixes get pushed
/* istanbul ignore if */
if($elem.is(":focus"))
setCursorPos($elem, oldSel.s, oldSel.e);
}
function ctKeyListener(view, hash, $elem) {
var prev = view.prevValues[hash];
/* istanbul ignore if */
if(!($elem[0].validity || {valid:true}).valid)
return revertInvalid($elem, prev, view.ctCursorPos[hash]);
var curr = ""+$elem.val();
if(curr != prev) {
var oldSel = view.ctCursorPos[hash];
var type = view.ctMap[hash];
var val = type.unformat(curr);
if(!type.validate(val)) {
revertInvalid($elem, prev, oldSel);
} else {
var fVal = type.format(val);
if(fVal != curr) {
//Reformat
//TODO remove ignore when jsdom fixes get pushed
/* istanbul ignore else */
if(!ctSpecialCaseUpdate($elem, type, oldSel, curr, prev,
hash, view))
ctReformat($elem, type, curr, fVal, hash, view);
//Refresh curr/val
curr = ""+$elem.val();
val = type.unformat(curr);
}
//Call listeners
if(type.unformat(prev) != val) {
var listeners = view.ctListeners[hash];
for(var i = 0; i < listeners.length; i++)
listeners[i](val);
}
view.prevValues[hash] = curr;
}
}
ctLogCursor(view, hash, $elem);
};
/**********************************\
* Helper Functions for Listeners *
\**********************************/
function getValue($elem) {
return Fluid.utils.isCheckable($elem) ? $elem[0].checked:$elem.val();
}
function watch(view, sel)
{
function send(val) {
var trgt = view.listenTrgts[sel] || [];
if(typeof trgt == "function")
trgt = [trgt];
for(var i = 0; i < trgt.length; i++)
trgt[i](val);
}
if(!view.prevValues.hasOwnProperty(sel)) {
var $elem = view.find(sel);
if($elem.is("["+ctHashAttr+"]")) {
view.prevValues[sel] = undefined; //We just want to stop
//more listeners
var hash = $elem.attr(ctHashAttr);
send(view.ctMap[hash].unformat($elem.val()));
view.ctListeners[hash].push(send);
} else {
send(view.prevValues[sel] = getValue($elem));
var hear = function() {
var val = getValue($elem);
if(val != view.prevValues[sel])
send(view.prevValues[sel] = val);
}
$elem.on("input", hear);
$elem.keypress(hear);
$elem.keydown(hear);
$elem.keyup(hear);
$elem.change(hear);
}
}
}
/***************************\
* Fluid.defineInputType *
\***************************/
//NOTE: the real work is done in the view code
var customTypes = {}
var ctHashAttr = "__fluid__custom_type_hash";
function type_unformat(x) {
return ((x || "") + "").split("").filter(function(x) {
return !this.formatChars(x)}.bind(this)).join("");
}
function type_reformat(x) {
return this.format(this.unformat(x));
}
Fluid.defineInputType = function(typeName, props) {
props = props || {};
var typeAttr = undefined;
var typeAttrs = props.typeAttr || typeName;
if(typeof typeAttrs == "string")
typeAttrs = [typeAttrs];
var $i = $("<input>");
for(var i = 0; !typeAttr && (i < typeAttrs.length); i++)
/* instanbul ignore else */
if($i.attr("type", typeAttrs[i]).prop("type") == typeAttrs[i])
typeAttr = typeAttrs[i];
/* istanbul ignore if */
if(!typeAttr)
typeAttr = "text";
for(var i = 0; i < 3; i++) {
var k = ["validate", "format", "formatChars"][i];
if((typeof props[k] == "object")&&!(props[k] instanceof RegExp))
props[k] = props[k][typeAttr]
}
var formatChars=props.formatChars instanceof RegExp ?
props.formatChars.test.bind(props.formatChars) :
props.formatChars instanceof Function ?
props.formatChars : function() {return false;};
return customTypes[typeName] = { //Return for testing reasons
attr: typeAttr,
validate: props.validate instanceof RegExp ?
props.validate.test.bind(props.validate) :
props.validate instanceof Function ? props.validate:
function() {return true;},
format: props.format instanceof Function ? props.format :
function(x) {return x;},
formatChars:formatChars,
unformat: type_unformat,
reformat: type_reformat
};
};
/************\
* Extend! *
\************/
Fluid.extendViews({
compile: function(props) {
this.listeners = props.listeners || {};
this.ctMap = {};
},
modifyTemplate: function(tmplt) {
var view = this;
return tmplt.replace(/type=["']\s*[^"']*\s*["']/g, function(m) {
var typeStr = m.slice(6, -1).trim();
if(customTypes[typeStr]) {
var type = customTypes[typeStr];
var hash = Fluid.utils.rndAttrName();
view.ctMap[hash] = type;
var q = m.slice(-1);
return ctHashAttr + "=" + q + hash + q + " type=" +
q + type.attr + q;
} else
return m;
});
},
init: function() {
this.vals = {};
this.prevValues = {};
this.ctListeners = {};
this.ctCursorPos = {};
for(var hash in this.ctMap) {
var $elem = this.find('['+ctHashAttr+'="'+hash+'"]');
var val = this.ctMap[hash].reformat(""+$elem.val());
$elem.val(val);
this.prevValues[hash] = val;
this.ctListeners[hash] = [];
this.ctCursorPos[hash] = {s: val.length, e: val.length};
//Add listeners for custom types
var keyListener = ctKeyListener.bind({}, this, hash, $elem);
var clickListener = ctLogCursor.bind({}, this, hash, $elem);
$elem.on("input", keyListener);
$elem.keypress(keyListener);
$elem.keydown(keyListener);
$elem.keyup(keyListener);
$elem.change(keyListener);
$elem.click(clickListener);
$elem.mouseup(clickListener);
$elem.mousedown(clickListener);
$elem.focus(clickListener);
}
},
control: function() {
this.listenTrgts = this.listeners instanceof Function ?
this.listeners.apply(this,
this.getState()) : this.listeners;
for(var sel in this.listenTrgts)
watch(this, sel);
},
preprocessValue: function(value, $elem) {
var ctHash = $elem.attr(ctHashAttr);
if(ctHash)
return this.ctMap[ctHash].reformat(value);
else
return value;
},
postValueProcessing: function(value, $elem) {
if($elem.is(":focus"))
setCursorPos($elem, value.length, value.length,
$elem.attr(ctHashAttr), this);
}
});
return Fluid;
}));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.