code stringlengths 2 1.05M |
|---|
module.exports = function(config){
config.set({
basePath : './',
files : [
'app/vendor/angular/angular.js',
'app/vendor/**/*.js',
'app/components/**/*.js',
'app/directives/*.js',
'app/services/*.js',
'app/general-categories/**/*.js',
],
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['Chrome'],
plugins : [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine',
'karma-junit-reporter'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
});
};
|
// Copyright (c) 2016 Henrique Daitx.
// Released under the MIT License.
angular.module('fenwickTreesApp', ['ngAnimate'])
.controller('fenwickTreesCtrl', function ($scope) {
// underscore.js
$scope._ = _;
// maximum number of elements
$scope.max_vlen = 32;
// actual number of elements
$scope.vlen = $scope.max_vlen >> 1;
// algorithm data vector
$scope.v = [];
var reset_v = function () {
$scope.v = [];
for (var i = 0; i < $scope.vlen; i++)
$scope.v.push(0);
}
// prefix sum vector
$scope.ps_v = [];
// elements vector
$scope.el_v = _.range($scope.max_vlen);
// "traces" for the add and prefix sum operations
$scope.trace_add = [];
$scope.trace_ps = [];
// end element symbol
$scope.end_element = 0;
// drawing data for the add and lookup trees
$scope.ps_d = {};
$scope.add_d = {};
// "container" element, because reasons - apparently anything that will be directly modified inside a ngRepeat (for example, by a ngMouseEnter) has to be inside an object inside the scope (don't ask) (but if you do: http://stackoverflow.com/questions/15623698/angularjs-directive-isolate-scope-with-ng-repeat-scope)
$scope.s = {};
// node currently pointed to by the mouse (-1 if none)
$scope.s.act_node = -1;
// list of elements accumulated in each data vector position
$scope.contains = [];
// add k to the ith element
var add = function (k, i) {
i0 = i;
$scope.trace_add[i0] = [];
if (!i) {
$scope.v[i] += k;
$scope.trace_add[i0].push(i);
}
else {
while (i <= $scope.end_element) {
// only actually add to existing elements; the other ones (i > vlen) are only for diplaying the tree correctly
if (i < $scope.vlen)
$scope.v[i] += k;
$scope.trace_add[i0].push(i);
i += i & -i;
}
}
}
// return the ith prefix sum
var pref_sum = function (i) {
var i0 = i;
$scope.trace_ps[i0] = [];
var sum = 0;
while (i) {
sum += $scope.v[i];
$scope.trace_ps[i0].push(i);
i &= i - 1;
}
sum += $scope.v[0];
$scope.trace_ps[i0].push(0);
return sum;
}
var in_vec = function (x, v) {
return v.findIndex(function(y) {return x == y});
}
// recalculate the whole tree
var tree_reset = function () {
// calculate the end element so that we can complete the add tree with non-existing elements for display
$scope.end_element = ($scope.vlen - 1) << 1;
while ($scope.end_element & ($scope.end_element - 1))
$scope.end_element &= $scope.end_element - 1;
reset_v();
$scope.ps_v = [];
for (var i = 0; i < $scope.vlen; i++) {
add($scope.el_v[i], i);
$scope.ps_v[i] = pref_sum(i);
}
}
// recalculate display variables
var tree_recalc = function (trace, root) {
// translate the tree into child list and parent list formats
var child_list = [];
var parent_list = [];
parent_list[root] = root;
for (var i = 0; i <= $scope.vlen; i++)
child_list.push([]);
// add an entry for the root in case it's not zero (it's an update tree)
child_list[root] = [];
for (var i = 0; i < $scope.vlen; i++) {
if (i != root) {
var vec = trace[i];
for (var j = 1; j < vec.length; j++) {
// create entries for non-existing elements
if (child_list[vec[j]] == undefined)
child_list[vec[j]] = [];
child_list[vec[j]].push(vec[j - 1]);
parent_list[vec[j - 1]] = vec[j];
}
}
}
for (var i in child_list)
if (root == 0)
child_list[i] = _.uniq(child_list[i].sort(function(a, b) {return a - b}), true);
else
child_list[i] = _.uniq(child_list[i].sort(function(a, b) {return b - a}), true);
// establish each element's "grid position" by counting leaves in each subtree
var depth_list = [];
var lat_list = []
var leaves_dfs = function (i, depth, lat) {
depth_list[i] = depth;
lat_list[i] = lat;
var leaves_below = 0;
var vec = child_list[i];
if (vec.length != 0)
for (var j = 0; j < vec.length; j++)
leaves_below += leaves_dfs(vec[j], depth + 1, lat + leaves_below);
else
leaves_below = 1;
return leaves_below;
}
leaves_dfs(root, 0, 0);
// calculate actual position in % from "grid position"
var max_lat = _.max(lat_list);
var max_depth = _.max(depth_list);
var node_x = [];
var node_y = [];
var nodes = _.keys(parent_list);
for (var i in nodes) {
var guard_x = 4;
var guard_y = 8;
if (max_lat === 0)
nx = 50;
else
nx = lat_list[nodes[i]] * (100 - 2 * guard_x) / max_lat + guard_x;
ny = depth_list[nodes[i]] * (100 - 2 * guard_y) / max_depth + guard_y;
node_x[nodes[i]] = nx.toString() + '%';
node_y[nodes[i]] = ny.toString() + '%';
}
// angular apparently can't make ngIf or ngClass work for SVGs, so we have to precalculate everything in order to display non-existent nodes as separate elements "on top" of regular nodes
var non_exist = [];
var non_exist_parent = [];
for (var i in nodes)
if (nodes[i] >= $scope.vlen) {
non_exist.push(nodes[i]);
for (var j in child_list[nodes[i]])
non_exist_parent.push(child_list[nodes[i]][j]);
}
return {
non_exist: non_exist,
non_exist_parent: non_exist_parent,
nodes: nodes,
parent: parent_list,
node_x: node_x,
node_y: node_y
};
}
$scope.recalc = function () {
tree_reset();
$scope.ps_d = tree_recalc($scope.trace_ps, 0);
$scope.add_d = tree_recalc($scope.trace_add, $scope.end_element);
$scope.s.act_node = -1;
// recalculate list of elements contained in each data vector position
var contains = [];
for (var i = 0; i < $scope.vlen; i++) {
contains[i] = [];
for (var j = 0; j < $scope.vlen; j++)
contains[i].push(false);
for (var j = i; j > (i & (i - 1)); j--)
contains[i][j] = true;
}
contains[-1] = [];
contains[0][0] = true;
$scope.contains = contains;
}
// initialize
$scope.recalc();
})
.directive('trees', function () {
return {
templateUrl: '/res/fenwick-trees/trees.html'
}
});
|
'use strict';
angular
.module('ngGeolocation', [])
.factory('$geolocation', ['$rootScope', '$window', '$q', function($rootScope, $window, $q) {
function supported() {
return 'geolocation' in $window.navigator;
}
var retVal = {
getCurrentPosition: function(options) {
var deferred = $q.defer();
if(supported()) {
$window.navigator.geolocation.getCurrentPosition(
function(position) {
$rootScope.$apply(function() {
deferred.resolve(position);
});
},
function(error) {
$rootScope.$apply(function() {
deferred.reject({error: error});
});
}, options);
} else {
deferred.reject({error: {
code: 2,
message: 'This web browser does not support HTML5 Geolocation'
}});
}
return deferred.promise;
},
watchPosition: function(options) {
if(supported()) {
if(!this.watchId) {
this.watchId = $window.navigator.geolocation.watchPosition(
function(position) {
$rootScope.$apply(function() {
retVal.position.coords = position.coords;
retVal.position.timestamp = position.timestamp;
delete retVal.position.error;
$rootScope.$broadcast('$geolocation.position.changed', position);
});
},
function(error) {
$rootScope.$apply(function() {
retVal.position.error = error;
delete retVal.position.coords;
delete retVal.position.timestamp;
$rootScope.$broadcast('$geolocation.position.error', error);
});
}, options);
}
} else {
retVal.position = {
error: {
code: 2,
message: 'This web browser does not support HTML5 Geolocation'
}
};
}
},
clearWatch: function() {
if(this.watchId) {
$window.navigator.geolocation.clearWatch(this.watchId);
delete this.watchId;
}
},
position: {}
};
return retVal;
}]); |
import ToolTipsterComponent from 'ember-cli-tooltipster/components/tool-tipster';
export default ToolTipsterComponent;
|
/**
* SEA3D - Rigid Body
* @author Sunag / http://www.sunag.com.br/
*/
'use strict';
//
// Sphere
//
SEA3D.Sphere = function ( name, data, sea3d ) {
this.name = name;
this.data = data;
this.sea3d = sea3d;
this.radius = data.readFloat();
};
SEA3D.Sphere.prototype.type = "sph";
//
// Box
//
SEA3D.Box = function ( name, data, sea3d ) {
this.name = name;
this.data = data;
this.sea3d = sea3d;
this.width = data.readFloat();
this.height = data.readFloat();
this.depth = data.readFloat();
};
SEA3D.Box.prototype.type = "box";
//
// Cone
//
SEA3D.Cone = function ( name, data, sea3d ) {
this.name = name;
this.data = data;
this.sea3d = sea3d;
this.radius = data.readFloat();
this.height = data.readFloat();
};
SEA3D.Cone.prototype.type = "cone";
//
// Capsule
//
SEA3D.Capsule = function ( name, data, sea3d ) {
this.name = name;
this.data = data;
this.sea3d = sea3d;
this.radius = data.readFloat();
this.height = data.readFloat();
};
SEA3D.Capsule.prototype.type = "cap";
//
// Cylinder
//
SEA3D.Cylinder = function ( name, data, sea3d ) {
this.name = name;
this.data = data;
this.sea3d = sea3d;
this.radius = data.readFloat();
this.height = data.readFloat();
};
SEA3D.Cylinder.prototype.type = "cyl";
//
// Convex Geometry
//
SEA3D.ConvexGeometry = function ( name, data, sea3d ) {
this.name = name;
this.data = data;
this.sea3d = sea3d;
this.geometry = sea3d.getObject( data.readUInt() );
this.subGeometryIndex = data.readUByte();
};
SEA3D.ConvexGeometry.prototype.type = "gs";
//
// Triangle Geometry
//
SEA3D.TriangleGeometry = function ( name, data, sea3d ) {
this.name = name;
this.data = data;
this.sea3d = sea3d;
this.geometry = sea3d.getObject( data.readUInt() );
this.subGeometryIndex = data.readUByte();
};
SEA3D.TriangleGeometry.prototype.type = "sgs";
//
// Compound
//
SEA3D.Compound = function ( name, data, sea3d ) {
this.name = name;
this.data = data;
this.sea3d = sea3d;
this.compounds = [];
var count = data.readUByte();
for ( var i = 0; i < count; i ++ ) {
this.compounds.push( {
shape: sea3d.getObject( data.readUInt() ),
transform: data.readMatrix()
} );
}
};
SEA3D.Compound.prototype.type = "cmps";
//
// Physics
//
SEA3D.Physics = function ( name, data, sea3d ) {
this.name = name;
this.data = data;
this.sea3d = sea3d;
this.attrib = data.readUShort();
this.shape = sea3d.getObject( data.readUInt() );
if ( this.attrib & 1 ) this.target = sea3d.getObject( data.readUInt() );
else this.transform = data.readMatrix();
if ( this.attrib & 2 ) this.offset = data.readMatrix();
if ( this.attrib & 4 ) this.scripts = data.readScriptList( sea3d );
if ( this.attrib & 16 ) this.attributes = sea3d.getObject( data.readUInt() );
};
SEA3D.Physics.prototype.readTag = function ( kind, data, size ) {
};
//
// Rigidy Body Base
//
SEA3D.RigidBodyBase = function ( name, data, sea3d ) {
SEA3D.Physics.call( this, name, data, sea3d );
if ( this.attrib & 32 ) {
this.linearDamping = data.readFloat();
this.angularDamping = data.readFloat();
} else {
this.linearDamping = 0;
this.angularDamping = 0;
}
this.mass = data.readFloat();
this.friction = data.readFloat();
this.restitution = data.readFloat();
};
SEA3D.RigidBodyBase.prototype = Object.create( SEA3D.Physics.prototype );
SEA3D.RigidBodyBase.prototype.constructor = SEA3D.RigidBodyBase;
//
// Rigidy Body
//
SEA3D.RigidBody = function ( name, data, sea3d ) {
SEA3D.RigidBodyBase.call( this, name, data, sea3d );
data.readTags( this.readTag.bind( this ) );
};
SEA3D.RigidBody.prototype = Object.create( SEA3D.RigidBodyBase.prototype );
SEA3D.RigidBody.prototype.constructor = SEA3D.RigidBody;
SEA3D.RigidBody.prototype.type = "rb";
//
// Car Controller
//
SEA3D.CarController = function ( name, data, sea3d ) {
SEA3D.RigidBodyBase.call( this, name, data, sea3d );
this.suspensionStiffness = data.readFloat();
this.suspensionCompression = data.readFloat();
this.suspensionDamping = data.readFloat();
this.maxSuspensionTravelCm = data.readFloat();
this.frictionSlip = data.readFloat();
this.maxSuspensionForce = data.readFloat();
this.dampingCompression = data.readFloat();
this.dampingRelaxation = data.readFloat();
var count = data.readUByte();
this.wheel = [];
for ( var i = 0; i < count; i ++ ) {
this.wheel[ i ] = new SEA3D.CarController.Wheel( data, sea3d );
}
data.readTags( this.readTag.bind( this ) );
};
SEA3D.CarController.Wheel = function ( data, sea3d ) {
this.data = data;
this.sea3d = sea3d;
this.attrib = data.readUShort();
this.isFront = ( this.attrib & 1 ) != 0;
if ( this.attrib & 2 ) {
this.target = sea3d.getObject( data.readUInt() );
}
if ( this.attrib & 4 ) {
this.offset = data.readMatrix();
}
this.pos = data.readVector3();
this.dir = data.readVector3();
this.axle = data.readVector3();
this.radius = data.readFloat();
this.suspensionRestLength = data.readFloat();
};
SEA3D.CarController.prototype = Object.create( SEA3D.RigidBodyBase.prototype );
SEA3D.CarController.prototype.constructor = SEA3D.CarController;
SEA3D.CarController.prototype.type = "carc";
//
// Constraints
//
SEA3D.Constraints = function ( name, data, sea3d ) {
this.name = name;
this.data = data;
this.sea3d = sea3d;
this.attrib = data.readUShort();
this.disableCollisionsBetweenBodies = this.attrib & 1 != 0;
this.targetA = sea3d.getObject( data.readUInt() );
this.pointA = data.readVector3();
if ( this.attrib & 2 ) {
this.targetB = sea3d.getObject( data.readUInt() );
this.pointB = data.readVector3();
}
};
//
// P2P Constraint
//
SEA3D.P2PConstraint = function ( name, data, sea3d ) {
this.name = name;
this.data = data;
this.sea3d = sea3d;
SEA3D.Constraints.call( this, name, data, sea3d );
};
SEA3D.P2PConstraint.prototype = Object.create( SEA3D.Constraints.prototype );
SEA3D.P2PConstraint.prototype.constructor = SEA3D.P2PConstraint;
SEA3D.P2PConstraint.prototype.type = "p2pc";
//
// Hinge Constraint
//
SEA3D.HingeConstraint = function ( name, data, sea3d ) {
SEA3D.Constraints.call( this, name, data, sea3d );
this.axisA = data.readVector3();
if ( this.attrib & 1 ) {
this.axisB = data.readVector3();
}
if ( this.attrib & 4 ) {
this.limit = {
low: data.readFloat(),
high: data.readFloat(),
softness: data.readFloat(),
biasFactor: data.readFloat(),
relaxationFactor: data.readFloat()
};
}
if ( this.attrib & 8 ) {
this.angularMotor = {
velocity: data.readFloat(),
impulse: data.readFloat()
};
}
};
SEA3D.HingeConstraint.prototype = Object.create( SEA3D.Constraints.prototype );
SEA3D.HingeConstraint.prototype.constructor = SEA3D.HingeConstraint;
SEA3D.HingeConstraint.prototype.type = "hnec";
//
// Cone Twist Constraint
//
SEA3D.ConeTwistConstraint = function ( name, data, sea3d ) {
SEA3D.Constraints.call( this, name, data, sea3d );
this.axisA = data.readVector3();
if ( this.attrib & 1 ) {
this.axisB = data.readVector3();
}
if ( this.attrib & 4 ) {
this.limit = {
swingSpan1: data.readFloat(),
swingSpan2: data.readFloat(),
twistSpan: data.readFloat(),
softness: data.readFloat(),
biasFactor: data.readFloat(),
relaxationFactor: data.readFloat()
};
}
};
SEA3D.ConeTwistConstraint.prototype = Object.create( SEA3D.Constraints.prototype );
SEA3D.ConeTwistConstraint.prototype.constructor = SEA3D.ConeTwistConstraint;
SEA3D.ConeTwistConstraint.prototype.type = "ctwc";
//
// Extension
//
SEA3D.File.setExtension( function () {
// PHYSICS
this.addClass( SEA3D.Sphere );
this.addClass( SEA3D.Box );
this.addClass( SEA3D.Cone );
this.addClass( SEA3D.Capsule );
this.addClass( SEA3D.Cylinder );
this.addClass( SEA3D.ConvexGeometry );
this.addClass( SEA3D.TriangleGeometry );
this.addClass( SEA3D.Compound );
this.addClass( SEA3D.RigidBody );
this.addClass( SEA3D.P2PConstraint );
this.addClass( SEA3D.HingeConstraint );
this.addClass( SEA3D.ConeTwistConstraint );
this.addClass( SEA3D.CarController );
} );
|
'use strict';
function ListNode(val) {
this.val = val;
this.next = null;
}
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function (l1, l2) {
let list = null,
head = null
let remain = 0
while (l1 !== null || l2 !== null) {
let sum = 0
if (l1 !== null) {
sum += l1.val
l1 = l1.next
}
if (l2 != null) {
sum += l2.val
l2 = l2.next
}
sum += remain
if (sum >= 10) {
remain = Math.floor(sum / 10)
sum -= remain * 10
} else {
remain = 0
}
var newVal = new ListNode(sum)
if (list === null) {
list = newVal
head = newVal
} else {
head.next = newVal
head = head.next
}
}
if (remain !== 0) {
var newVal = new ListNode(remain)
head.next = newVal
head = head.next
}
return list
};
|
class VueState {
constructor () {
this.count = 0
this.isLoading = false
}
begin () {
this.count = this.count + 1
this.isLoading = this.count > 0
}
end () {
this.count = this.count - 1
this.isLoading = this.count > 0
}
}
export default VueState
|
'use strict'
const URI = require('..')
const test = require('ava')
test('valid', function (t) {
;[
'https://github.com/garycourt/uri-js',
'magnet:?xt=urn:sha1:PDAQRAOQQRYS76MRZJ33LK4MMVZBDSCL',
'https://🐀.ws/🐀🐀'
].forEach(function (url) {
t.truthy(URI(url).protocol)
})
})
test('invalid', function (t) {
;[undefined, null, false, ''].forEach(function (url) {
t.is(URI(url), undefined)
})
})
|
/*
Author: Andrew Spencer
Description: Generates a random westpac number
*/
let bank
let branch
function start() {
bank = '03'
branch = '0'
for(i = 0; i < 3; i++) {
branch += Math.floor(Math.random() * 10)
}
let general_ledger = '0'
let suffix = '000'
general_ledger += Math.floor(Math.random() * 9)
for (i = 0; i < 4; i++) {
general_ledger += Math.floor(Math.random() * 10)
}
let weightings = [ 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
let positions = [ 2, 3, 4, 5, 7, 8, 9, 10, 11 ];
let modulus = 11;
const digits = [bank, branch, general_ledger]
let sum = 0
for (i = 0; i < positions.length -1; i++) {
sum += digits[positions[i]] * weightings[i]
}
// const suffix = '000'
// return {
// bank: bank,
// branch: branch,
// general_ledger: general_ledger,
// suffix: suffix,
// check_digit: check_digit
// }
let dividend = Math.ceil( sum / modulus ) * modulus;
let check_digit = dividend - sum;
let result = start()
while (check_digit > 9) {
let result = start()
}
general_ledger = general_ledger - check_digit
console.log('blah')
console.log( bank-branch-general_ledger-suffix)
}
|
import React from 'react'
import { Link } from 'react-router-dom';
import NumberFormat from 'react-number-format';
const TopTen = (props) => (
<div className="card">
<header className="card-header has-text-centered">
<p className="card-header-title">
{props.title}
</p>
</header>
<div className="card-content">
<div className="content is-size-7 p-5">
<table className="table">
<thead>
<tr>
<th><abbr title="Position">#</abbr></th>
<th>{props.name}</th>
<th>{props.score}</th>
</tr>
</thead>
<tbody>
{
props.packages.map((p, index) => {
return <tr key={p._id}>
<th>{(index + 1)}</th>
<td><span>{p.name}</span></td>
<td><NumberFormat value={p.score} displayType={'text'} thousandSeparator={true} /></td>
</tr>
})}
</tbody>
</table>
</div>
</div>
</div>
)
export default TopTen |
angular.module('myApp')
.directive("addFilters", ['$timeout', '$window',
function($timeout, $window) {
'use strict';
return {
restrict: "E",
templateUrl: "templates/directives/add-filters.html",
controller: function($scope) {},
replace: true,
link: function(scope, element, attributes, ctlr) {
/**
* [showHideFilters function to execute when side filter is clicked]
*/
scope.showHideFilters = function() {
$('.add_filters').toggleClass('hide');
};
/**
* [clearFilters removes all the applied fitlers]
*/
scope.clearFilters = function() {
$('.searched').removeClass('searched');
$('input:checked').attr('checked', false);
$('.teams').addClass('hide');
$('.designations').addClass('hide');
scope.nameFilter = '';
scope.teamFilter = {};
scope.designationFilter = {};
scope.filtered_employees = [];
$('.add_filters').addClass('hide');
};
/* events binded to side filters i.e. teams and designations */
$('input[name="teams"], input[name="designations"]').on('change', function(e) {
scope.applySideFilters($(e.currentTarget));
});
/**
* [applySideFilters show/hide and applies the checked values in side filters]
* @param {DOM Element} ele element which was checked
*/
scope.applySideFilters = function(ele) {
if (!ele.is(':checked')) {
scope.clearChecks(ele.attr('name'));
$('.' + ele.attr('name')).addClass('hide');
} else {
$('.' + ele.attr('name')).removeClass('hide');
}
scope.highlight(true);
};
/**
* [clearChecks clears unchecked filters]
*/
scope.clearChecks = function(name) {
$('.' + name).find('input:checked').attr('checked', false);
if (name === 'teams') {
scope.teamFilter = {};
} else if (name === 'designations') {
scope.designationFilter = {};
}
};
/**
* [highlight highlights the employees who pass the match criteria]
*/
scope.highlight = function(hideAlertFlag) {
$('.searched').removeClass('searched');
scope.filtered_employees = scope.filterEmployees();
scope.highlightSearched(scope.filtered_employees);
if (scope.$root.$$phase != '$apply' && scope.$root.$$phase != '$digest') {
scope.$digest();
}
if (!scope.filtered_employees.length && !hideAlertFlag) {
scope.newAlert('No Matching Results Found!!');
};
};
/**
* [filterEmployees helper function used to filter employees]
* @return {Array} list of employees who passed the search criteria
*/
scope.filterEmployees = function() {
var arr = [];
_.each(scope.employeeList, function(employee) {
if (scope.searchFilterName(employee) || scope.searchFilterTeam(employee) || scope.searchFilterDesignation(employee)) {
arr.push(employee);
}
});
return arr;
};
/**
* [highlightSearched helper function used to highlight the above fetched employees]
* @param {Array} arr list of employees to be hightlighted
*/
scope.highlightSearched = function(arr) {
_.each(arr, function(employee) {
$('[emp-name=\'' + employee.name + '\']').addClass('searched');
});
};
/**
* [searchFilterName used to filter employee based on name]
* @param {Object} employee
* @return {Boolean} true/false based on whether employee's name matches the searched string
*/
scope.searchFilterName = function(employee) {
if (!scope.nameFilter) {
return false;
}
var keyword = new RegExp(scope.nameFilter, 'i');
return keyword.test(employee.name);
};
/**
* [searchFilterTeam used to filter employee based on their teams]
* @param {Object} employee
* @return {Boolean} true/false based on whether employee's teams matches the checked team
*/
scope.searchFilterTeam = function(employee) {
/* return true if matched else false */
if (_.isEmpty(scope.teamFilter)) {
return false;
}
var values = _.values(scope.teamFilter);
var all_empty = _.every(values, function(val, index) {
return !val;
});
if (all_empty) {
return false;
} else {
/* returns true if any teams matches employee's team */
return _.some(values, function(val, index) {
return val == employee.team;
});
}
};
/**
* [searchFilterDesignation used to filter employee based on their desigations]
* @param {Object} employee
* @return {Boolean} true/false based on whether employee's designation matches the checked designation
*/
scope.searchFilterDesignation = function(employee) {
/* return true if matched else false */
if (_.isEmpty(scope.designationFilter)) {
return false;
}
var values = _.values(scope.designationFilter);
var all_empty = _.every(values, function(val, index) {
return !val;
});
if (all_empty) {
return false;
} else {
/* returns true if any desinations matches employee's designation */
return _.some(values, function(val, index) {
return val == employee.designation;
});
}
};
}
};
}
]); |
// might not be necessary with express-jwt
// however, using jwt.validate might give you more control |
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
username: { type: String, required: true, unique: true },
password: { type: String },
fname: { type: String },
lname: { type: String },
role: { type: String, default: 'user' },
created_at: { type: Date },
updated_at: { type: Date }
});
userSchema.pre('save', function(next) {
// get current date
var currentDate = new Date();
// change updated_at to current date
this.updated_at = currentDate;
// if created_at is not filled, set to current date
if (!this.created_at) {
this.created_at = currentDate;
}
console.log('User successfully created!');
next();
});
var User = mongoose.model('User', userSchema)
module.exports = User;
|
'use strict';
var CacheStorageProvider = require('./provider/cache-storage');
var GeolocationService = require('./service/geolocation');
var TracerFactory = require('./factory/tracer');
module.exports = angular
.module('velocity.common', [])
.provider('CacheStorage', CacheStorageProvider)
.service('Geolocation', GeolocationService)
.factory('Tracer', TracerFactory);
|
/* globals EmberDev */
import {
moduleFor,
RenderingTestCase,
strip,
classes,
equalTokens,
equalsElement,
styles,
runTask,
} from 'internal-test-helpers';
import { run } from '@ember/runloop';
import { DEBUG } from '@glimmer/env';
import { set, get, observer, on, computed } from '@ember/-internals/metal';
import Service, { inject as injectService } from '@ember/service';
import { Object as EmberObject, A as emberA } from '@ember/-internals/runtime';
import { jQueryDisabled } from '@ember/-internals/views';
import { Component, compile, htmlSafe } from '../../utils/helpers';
moduleFor(
'Components test: curly components',
class extends RenderingTestCase {
['@test it can render a basic component']() {
this.registerComponent('foo-bar', { template: 'hello' });
this.render('{{foo-bar}}');
this.assertComponentElement(this.firstChild, { content: 'hello' });
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, { content: 'hello' });
}
['@test it can have a custom id and it is not bound']() {
this.registerComponent('foo-bar', { template: '{{id}} {{elementId}}' });
this.render('{{foo-bar id=customId}}', {
customId: 'bizz',
});
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { id: 'bizz' },
content: 'bizz bizz',
});
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { id: 'bizz' },
content: 'bizz bizz',
});
runTask(() => set(this.context, 'customId', 'bar'));
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { id: 'bizz' },
content: 'bar bizz',
});
runTask(() => set(this.context, 'customId', 'bizz'));
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { id: 'bizz' },
content: 'bizz bizz',
});
}
['@test elementId cannot change'](assert) {
let component;
let FooBarComponent = Component.extend({
elementId: 'blahzorz',
init() {
this._super(...arguments);
component = this;
},
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: '{{elementId}}',
});
this.render('{{foo-bar}}');
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { id: 'blahzorz' },
content: 'blahzorz',
});
if (EmberDev && !EmberDev.runningProdBuild) {
let willThrow = () => run(null, set, component, 'elementId', 'herpyderpy');
assert.throws(willThrow, /Changing a view's elementId after creation is not allowed/);
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { id: 'blahzorz' },
content: 'blahzorz',
});
}
}
['@test can specify template with `layoutName` property']() {
let FooBarComponent = Component.extend({
elementId: 'blahzorz',
layoutName: 'fizz-bar',
init() {
this._super(...arguments);
this.local = 'hey';
},
});
this.registerTemplate('fizz-bar', `FIZZ BAR {{local}}`);
this.registerComponent('foo-bar', { ComponentClass: FooBarComponent });
this.render('{{foo-bar}}');
this.assertText('FIZZ BAR hey');
}
['@test layout supports computed property']() {
let FooBarComponent = Component.extend({
elementId: 'blahzorz',
layout: computed(function() {
return compile('so much layout wat {{lulz}}');
}),
init() {
this._super(...arguments);
this.lulz = 'heyo';
},
});
this.registerComponent('foo-bar', { ComponentClass: FooBarComponent });
this.render('{{foo-bar}}');
this.assertText('so much layout wat heyo');
}
['@test passing undefined elementId results in a default elementId'](assert) {
let FooBarComponent = Component.extend({
tagName: 'h1',
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: 'something',
});
this.render('{{foo-bar id=somethingUndefined}}');
let foundId = this.$('h1').attr('id');
assert.ok(
/^ember/.test(foundId),
'Has a reasonable id attribute (found id=' + foundId + ').'
);
runTask(() => this.rerender());
let newFoundId = this.$('h1').attr('id');
assert.ok(
/^ember/.test(newFoundId),
'Has a reasonable id attribute (found id=' + newFoundId + ').'
);
assert.equal(foundId, newFoundId);
}
['@test id is an alias for elementId'](assert) {
let FooBarComponent = Component.extend({
tagName: 'h1',
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: 'something',
});
this.render('{{foo-bar id="custom-id"}}');
let foundId = this.$('h1').attr('id');
assert.equal(foundId, 'custom-id');
runTask(() => this.rerender());
let newFoundId = this.$('h1').attr('id');
assert.equal(newFoundId, 'custom-id');
assert.equal(foundId, newFoundId);
}
['@test cannot pass both id and elementId at the same time']() {
this.registerComponent('foo-bar', { template: '' });
expectAssertion(() => {
this.render('{{foo-bar id="zomg" elementId="lol"}}');
}, /You cannot invoke a component with both 'id' and 'elementId' at the same time./);
}
['@test it can have a custom tagName']() {
let FooBarComponent = Component.extend({
tagName: 'foo-bar',
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: 'hello',
});
this.render('{{foo-bar}}');
this.assertComponentElement(this.firstChild, {
tagName: 'foo-bar',
content: 'hello',
});
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, {
tagName: 'foo-bar',
content: 'hello',
});
}
['@test it can have a custom tagName set in the constructor']() {
let FooBarComponent = Component.extend({
init() {
this._super();
this.tagName = 'foo-bar';
},
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: 'hello',
});
this.render('{{foo-bar}}');
this.assertComponentElement(this.firstChild, {
tagName: 'foo-bar',
content: 'hello',
});
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, {
tagName: 'foo-bar',
content: 'hello',
});
}
['@test it can have a custom tagName from the invocation']() {
this.registerComponent('foo-bar', { template: 'hello' });
this.render('{{foo-bar tagName="foo-bar"}}');
this.assertComponentElement(this.firstChild, {
tagName: 'foo-bar',
content: 'hello',
});
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, {
tagName: 'foo-bar',
content: 'hello',
});
}
['@test tagName can not be a computed property']() {
let FooBarComponent = Component.extend({
tagName: computed(function() {
return 'foo-bar';
}),
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: 'hello',
});
expectAssertion(() => {
this.render('{{foo-bar}}');
}, /You cannot use a computed property for the component's `tagName` \(<.+?>\)\./);
}
['@test class is applied before didInsertElement'](assert) {
let componentClass;
let FooBarComponent = Component.extend({
didInsertElement() {
componentClass = this.element.className;
},
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: 'hello',
});
this.render('{{foo-bar class="foo-bar"}}');
assert.equal(componentClass, 'foo-bar ember-view');
}
['@test it can have custom classNames']() {
let FooBarComponent = Component.extend({
classNames: ['foo', 'bar'],
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: 'hello',
});
this.render('{{foo-bar}}');
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { class: classes('ember-view foo bar') },
content: 'hello',
});
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { class: classes('ember-view foo bar') },
content: 'hello',
});
}
['@test should not apply falsy class name']() {
this.registerComponent('foo-bar', { template: 'hello' });
this.render('{{foo-bar class=somethingFalsy}}', {
somethingFalsy: false,
});
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { class: 'ember-view' },
content: 'hello',
});
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { class: 'ember-view' },
content: 'hello',
});
}
['@test should update class using inline if, initially false, no alternate']() {
this.registerComponent('foo-bar', { template: 'hello' });
this.render('{{foo-bar class=(if predicate "thing") }}', {
predicate: false,
});
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { class: 'ember-view' },
content: 'hello',
});
runTask(() => set(this.context, 'predicate', true));
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { class: classes('ember-view thing') },
content: 'hello',
});
runTask(() => set(this.context, 'predicate', false));
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { class: 'ember-view' },
content: 'hello',
});
}
['@test should update class using inline if, initially true, no alternate']() {
this.registerComponent('foo-bar', { template: 'hello' });
this.render('{{foo-bar class=(if predicate "thing") }}', {
predicate: true,
});
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { class: classes('ember-view thing') },
content: 'hello',
});
runTask(() => set(this.context, 'predicate', false));
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { class: 'ember-view' },
content: 'hello',
});
runTask(() => set(this.context, 'predicate', true));
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { class: classes('ember-view thing') },
content: 'hello',
});
}
['@test should apply classes of the dasherized property name when bound property specified is true']() {
this.registerComponent('foo-bar', { template: 'hello' });
this.render('{{foo-bar class=model.someTruth}}', {
model: { someTruth: true },
});
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { class: classes('ember-view some-truth') },
content: 'hello',
});
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { class: classes('ember-view some-truth') },
content: 'hello',
});
runTask(() => set(this.context, 'model.someTruth', false));
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { class: classes('ember-view') },
content: 'hello',
});
runTask(() => set(this.context, 'model', { someTruth: true }));
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { class: classes('ember-view some-truth') },
content: 'hello',
});
}
['@test class property on components can be dynamic']() {
this.registerComponent('foo-bar', { template: 'hello' });
this.render('{{foo-bar class=(if fooBar "foo-bar")}}', {
fooBar: true,
});
this.assertComponentElement(this.firstChild, {
content: 'hello',
attrs: { class: classes('ember-view foo-bar') },
});
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, {
content: 'hello',
attrs: { class: classes('ember-view foo-bar') },
});
runTask(() => set(this.context, 'fooBar', false));
this.assertComponentElement(this.firstChild, {
content: 'hello',
attrs: { class: classes('ember-view') },
});
runTask(() => set(this.context, 'fooBar', true));
this.assertComponentElement(this.firstChild, {
content: 'hello',
attrs: { class: classes('ember-view foo-bar') },
});
}
['@test it can have custom classNames from constructor']() {
let FooBarComponent = Component.extend({
init() {
this._super();
this.classNames = this.classNames.slice();
this.classNames.push('foo', 'bar', `outside-${this.get('extraClass')}`);
},
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: 'hello',
});
this.render('{{foo-bar extraClass="baz"}}');
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { class: classes('ember-view foo bar outside-baz') },
content: 'hello',
});
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { class: classes('ember-view foo bar outside-baz') },
content: 'hello',
});
}
['@test it can set custom classNames from the invocation']() {
let FooBarComponent = Component.extend({
classNames: ['foo'],
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: 'hello',
});
this.render(strip`
{{foo-bar class="bar baz"}}
{{foo-bar classNames="bar baz"}}
{{foo-bar}}
`);
this.assertComponentElement(this.nthChild(0), {
tagName: 'div',
attrs: { class: classes('ember-view foo bar baz') },
content: 'hello',
});
this.assertComponentElement(this.nthChild(1), {
tagName: 'div',
attrs: { class: classes('ember-view foo bar baz') },
content: 'hello',
});
this.assertComponentElement(this.nthChild(2), {
tagName: 'div',
attrs: { class: classes('ember-view foo') },
content: 'hello',
});
runTask(() => this.rerender());
this.assertComponentElement(this.nthChild(0), {
tagName: 'div',
attrs: { class: classes('ember-view foo bar baz') },
content: 'hello',
});
this.assertComponentElement(this.nthChild(1), {
tagName: 'div',
attrs: { class: classes('ember-view foo bar baz') },
content: 'hello',
});
this.assertComponentElement(this.nthChild(2), {
tagName: 'div',
attrs: { class: classes('ember-view foo') },
content: 'hello',
});
}
['@test it has an element']() {
let instance;
let FooBarComponent = Component.extend({
init() {
this._super();
instance = this;
},
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: 'hello',
});
this.render('{{foo-bar}}');
let element1 = instance.element;
this.assertComponentElement(element1, { content: 'hello' });
runTask(() => this.rerender());
let element2 = instance.element;
this.assertComponentElement(element2, { content: 'hello' });
this.assertSameNode(element2, element1);
}
['@test an empty component does not have childNodes'](assert) {
let fooBarInstance;
let FooBarComponent = Component.extend({
tagName: 'input',
init() {
this._super();
fooBarInstance = this;
},
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: '',
});
this.render('{{foo-bar}}');
this.assertComponentElement(this.firstChild, { tagName: 'input' });
assert.strictEqual(fooBarInstance.element.childNodes.length, 0);
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, { tagName: 'input' });
assert.strictEqual(fooBarInstance.element.childNodes.length, 0);
}
['@test it has the right parentView and childViews'](assert) {
let fooBarInstance, fooBarBazInstance;
let FooBarComponent = Component.extend({
init() {
this._super();
fooBarInstance = this;
},
});
let FooBarBazComponent = Component.extend({
init() {
this._super();
fooBarBazInstance = this;
},
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: 'foo-bar {{foo-bar-baz}}',
});
this.registerComponent('foo-bar-baz', {
ComponentClass: FooBarBazComponent,
template: 'foo-bar-baz',
});
this.render('{{foo-bar}}');
this.assertText('foo-bar foo-bar-baz');
assert.equal(fooBarInstance.parentView, this.component);
assert.equal(fooBarBazInstance.parentView, fooBarInstance);
assert.deepEqual(this.component.childViews, [fooBarInstance]);
assert.deepEqual(fooBarInstance.childViews, [fooBarBazInstance]);
runTask(() => this.rerender());
this.assertText('foo-bar foo-bar-baz');
assert.equal(fooBarInstance.parentView, this.component);
assert.equal(fooBarBazInstance.parentView, fooBarInstance);
assert.deepEqual(this.component.childViews, [fooBarInstance]);
assert.deepEqual(fooBarInstance.childViews, [fooBarBazInstance]);
}
['@feature(ember-glimmer-named-arguments) it renders passed named arguments']() {
this.registerComponent('foo-bar', {
template: '{{@foo}}',
});
this.render('{{foo-bar foo=model.bar}}', {
model: {
bar: 'Hola',
},
});
this.assertText('Hola');
runTask(() => this.rerender());
this.assertText('Hola');
runTask(() => this.context.set('model.bar', 'Hello'));
this.assertText('Hello');
runTask(() => this.context.set('model', { bar: 'Hola' }));
this.assertText('Hola');
}
['@test it reflects named arguments as properties']() {
this.registerComponent('foo-bar', {
template: '{{foo}}',
});
this.render('{{foo-bar foo=model.bar}}', {
model: {
bar: 'Hola',
},
});
this.assertText('Hola');
runTask(() => this.rerender());
this.assertText('Hola');
runTask(() => this.context.set('model.bar', 'Hello'));
this.assertText('Hello');
runTask(() => this.context.set('model', { bar: 'Hola' }));
this.assertText('Hola');
}
['@test it can render a basic component with a block']() {
this.registerComponent('foo-bar', {
template: '{{yield}} - In component',
});
this.render('{{#foo-bar}}hello{{/foo-bar}}');
this.assertComponentElement(this.firstChild, {
content: 'hello - In component',
});
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, {
content: 'hello - In component',
});
}
['@test it can render a basic component with a block when the yield is in a partial']() {
this.registerPartial('_partialWithYield', 'yielded: [{{yield}}]');
this.registerComponent('foo-bar', {
template: '{{partial "partialWithYield"}} - In component',
});
this.render('{{#foo-bar}}hello{{/foo-bar}}');
this.assertComponentElement(this.firstChild, {
content: 'yielded: [hello] - In component',
});
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, {
content: 'yielded: [hello] - In component',
});
}
['@test it can render a basic component with a block param when the yield is in a partial']() {
this.registerPartial('_partialWithYield', 'yielded: [{{yield "hello"}}]');
this.registerComponent('foo-bar', {
template: '{{partial "partialWithYield"}} - In component',
});
this.render('{{#foo-bar as |value|}}{{value}}{{/foo-bar}}');
this.assertComponentElement(this.firstChild, {
content: 'yielded: [hello] - In component',
});
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, {
content: 'yielded: [hello] - In component',
});
}
['@test it renders the layout with the component instance as the context']() {
let instance;
let FooBarComponent = Component.extend({
init() {
this._super();
instance = this;
this.set('message', 'hello');
},
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: '{{message}}',
});
this.render('{{foo-bar}}');
this.assertComponentElement(this.firstChild, { content: 'hello' });
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, { content: 'hello' });
runTask(() => set(instance, 'message', 'goodbye'));
this.assertComponentElement(this.firstChild, { content: 'goodbye' });
runTask(() => set(instance, 'message', 'hello'));
this.assertComponentElement(this.firstChild, { content: 'hello' });
}
['@test it preserves the outer context when yielding']() {
this.registerComponent('foo-bar', { template: '{{yield}}' });
this.render('{{#foo-bar}}{{message}}{{/foo-bar}}', { message: 'hello' });
this.assertComponentElement(this.firstChild, { content: 'hello' });
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, { content: 'hello' });
runTask(() => set(this.context, 'message', 'goodbye'));
this.assertComponentElement(this.firstChild, { content: 'goodbye' });
runTask(() => set(this.context, 'message', 'hello'));
this.assertComponentElement(this.firstChild, { content: 'hello' });
}
['@test it can yield a block param named for reserved words [GH#14096]']() {
let instance;
let FooBarComponent = Component.extend({
init() {
this._super(...arguments);
instance = this;
},
name: 'foo-bar',
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: '{{yield this}}',
});
this.render('{{#foo-bar as |component|}}{{component.name}}{{/foo-bar}}');
this.assertComponentElement(this.firstChild, { content: 'foo-bar' });
this.assertStableRerender();
runTask(() => set(instance, 'name', 'derp-qux'));
this.assertComponentElement(this.firstChild, { content: 'derp-qux' });
runTask(() => set(instance, 'name', 'foo-bar'));
this.assertComponentElement(this.firstChild, { content: 'foo-bar' });
}
['@test it can yield internal and external properties positionally']() {
let instance;
let FooBarComponent = Component.extend({
init() {
this._super(...arguments);
instance = this;
},
greeting: 'hello',
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: '{{yield greeting greetee.firstName}}',
});
this.render(
'{{#foo-bar greetee=person as |greeting name|}}{{name}} {{person.lastName}}, {{greeting}}{{/foo-bar}}',
{
person: {
firstName: 'Joel',
lastName: 'Kang',
},
}
);
this.assertComponentElement(this.firstChild, {
content: 'Joel Kang, hello',
});
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, {
content: 'Joel Kang, hello',
});
runTask(() =>
set(this.context, 'person', {
firstName: 'Dora',
lastName: 'the Explorer',
})
);
this.assertComponentElement(this.firstChild, {
content: 'Dora the Explorer, hello',
});
runTask(() => set(instance, 'greeting', 'hola'));
this.assertComponentElement(this.firstChild, {
content: 'Dora the Explorer, hola',
});
runTask(() => {
set(instance, 'greeting', 'hello');
set(this.context, 'person', {
firstName: 'Joel',
lastName: 'Kang',
});
});
this.assertComponentElement(this.firstChild, {
content: 'Joel Kang, hello',
});
}
['@test #11519 - block param infinite loop']() {
let instance;
let FooBarComponent = Component.extend({
init() {
this._super(...arguments);
instance = this;
},
danger: 0,
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: '{{danger}}{{yield danger}}',
});
// On initial render, create streams. The bug will not have manifested yet, but at this point
// we have created streams that create a circular invalidation.
this.render(`{{#foo-bar as |dangerBlockParam|}}{{/foo-bar}}`);
this.assertText('0');
// Trigger a non-revalidating re-render. The yielded block will not be dirtied
// nor will block param streams, and thus no infinite loop will occur.
runTask(() => this.rerender());
this.assertText('0');
// Trigger a revalidation, which will cause an infinite loop without the fix
// in place. Note that we do not see the infinite loop is in testing mode,
// because a deprecation warning about re-renders is issued, which Ember
// treats as an exception.
runTask(() => set(instance, 'danger', 1));
this.assertText('1');
runTask(() => set(instance, 'danger', 0));
this.assertText('0');
}
['@test the component and its child components are destroyed'](assert) {
let destroyed = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0 };
this.registerComponent('foo-bar', {
template: '{{id}} {{yield}}',
ComponentClass: Component.extend({
willDestroy() {
this._super();
destroyed[this.get('id')]++;
},
}),
});
this.render(
strip`
{{#if cond1}}
{{#foo-bar id=1}}
{{#if cond2}}
{{#foo-bar id=2}}{{/foo-bar}}
{{#if cond3}}
{{#foo-bar id=3}}
{{#if cond4}}
{{#foo-bar id=4}}
{{#if cond5}}
{{#foo-bar id=5}}{{/foo-bar}}
{{#foo-bar id=6}}{{/foo-bar}}
{{#foo-bar id=7}}{{/foo-bar}}
{{/if}}
{{#foo-bar id=8}}{{/foo-bar}}
{{/foo-bar}}
{{/if}}
{{/foo-bar}}
{{/if}}
{{/if}}
{{/foo-bar}}
{{/if}}`,
{
cond1: true,
cond2: true,
cond3: true,
cond4: true,
cond5: true,
}
);
this.assertText('1 2 3 4 5 6 7 8 ');
runTask(() => this.rerender());
assert.deepEqual(destroyed, {
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0,
7: 0,
8: 0,
});
runTask(() => set(this.context, 'cond5', false));
this.assertText('1 2 3 4 8 ');
assert.deepEqual(destroyed, {
1: 0,
2: 0,
3: 0,
4: 0,
5: 1,
6: 1,
7: 1,
8: 0,
});
runTask(() => {
set(this.context, 'cond3', false);
set(this.context, 'cond5', true);
set(this.context, 'cond4', false);
});
assert.deepEqual(destroyed, {
1: 0,
2: 0,
3: 1,
4: 1,
5: 1,
6: 1,
7: 1,
8: 1,
});
runTask(() => {
set(this.context, 'cond2', false);
set(this.context, 'cond1', false);
});
assert.deepEqual(destroyed, {
1: 1,
2: 1,
3: 1,
4: 1,
5: 1,
6: 1,
7: 1,
8: 1,
});
}
['@test should escape HTML in normal mustaches']() {
let component;
let FooBarComponent = Component.extend({
init() {
this._super(...arguments);
component = this;
},
output: 'you need to be more <b>bold</b>',
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: '{{output}}',
});
this.render('{{foo-bar}}');
this.assertText('you need to be more <b>bold</b>');
runTask(() => this.rerender());
this.assertText('you need to be more <b>bold</b>');
runTask(() => set(component, 'output', 'you are so <i>super</i>'));
this.assertText('you are so <i>super</i>');
runTask(() => set(component, 'output', 'you need to be more <b>bold</b>'));
}
['@test should not escape HTML in triple mustaches']() {
let expectedHtmlBold = 'you need to be more <b>bold</b>';
let expectedHtmlItalic = 'you are so <i>super</i>';
let component;
let FooBarComponent = Component.extend({
init() {
this._super(...arguments);
component = this;
},
output: expectedHtmlBold,
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: '{{{output}}}',
});
this.render('{{foo-bar}}');
equalTokens(this.firstChild, expectedHtmlBold);
runTask(() => this.rerender());
equalTokens(this.firstChild, expectedHtmlBold);
runTask(() => set(component, 'output', expectedHtmlItalic));
equalTokens(this.firstChild, expectedHtmlItalic);
runTask(() => set(component, 'output', expectedHtmlBold));
equalTokens(this.firstChild, expectedHtmlBold);
}
['@test should not escape HTML if string is a htmlSafe']() {
let expectedHtmlBold = 'you need to be more <b>bold</b>';
let expectedHtmlItalic = 'you are so <i>super</i>';
let component;
let FooBarComponent = Component.extend({
init() {
this._super(...arguments);
component = this;
},
output: htmlSafe(expectedHtmlBold),
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: '{{output}}',
});
this.render('{{foo-bar}}');
equalTokens(this.firstChild, expectedHtmlBold);
runTask(() => this.rerender());
equalTokens(this.firstChild, expectedHtmlBold);
runTask(() => set(component, 'output', htmlSafe(expectedHtmlItalic)));
equalTokens(this.firstChild, expectedHtmlItalic);
runTask(() => set(component, 'output', htmlSafe(expectedHtmlBold)));
equalTokens(this.firstChild, expectedHtmlBold);
}
['@test late bound layouts return the same definition'](assert) {
let templateIds = [];
// This is testing the scenario where you import a template and
// set it to the layout property:
//
// import Component from '@ember/component';
// import layout from './template';
//
// export default Component.extend({
// layout
// });
let hello = compile('Hello');
let bye = compile('Bye');
let FooBarComponent = Component.extend({
init() {
this._super(...arguments);
this.layout = this.cond ? hello : bye;
templateIds.push(this.layout.id);
},
});
this.registerComponent('foo-bar', { ComponentClass: FooBarComponent });
this.render(
'{{foo-bar cond=true}}{{foo-bar cond=false}}{{foo-bar cond=true}}{{foo-bar cond=false}}'
);
let [t1, t2, t3, t4] = templateIds;
assert.equal(t1, t3);
assert.equal(t2, t4);
}
['@test can use isStream property without conflict (#13271)']() {
let component;
let FooBarComponent = Component.extend({
isStream: true,
init() {
this._super(...arguments);
component = this;
},
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: strip`
{{#if isStream}}
true
{{else}}
false
{{/if}}
`,
});
this.render('{{foo-bar}}');
this.assertComponentElement(this.firstChild, { content: 'true' });
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, { content: 'true' });
runTask(() => set(component, 'isStream', false));
this.assertComponentElement(this.firstChild, { content: 'false' });
runTask(() => set(component, 'isStream', true));
this.assertComponentElement(this.firstChild, { content: 'true' });
}
['@test lookup of component takes priority over property']() {
this.registerComponent('some-component', {
template: 'some-component',
});
this.render('{{some-prop}} {{some-component}}', {
'some-component': 'not-some-component',
'some-prop': 'some-prop',
});
this.assertText('some-prop some-component');
runTask(() => this.rerender());
this.assertText('some-prop some-component');
}
['@test component without dash is not looked up']() {
this.registerComponent('somecomponent', {
template: 'somecomponent',
});
this.render('{{somecomponent}}', {
somecomponent: 'notsomecomponent',
});
this.assertText('notsomecomponent');
runTask(() => this.rerender());
this.assertText('notsomecomponent');
runTask(() => this.context.set('somecomponent', 'not not notsomecomponent'));
this.assertText('not not notsomecomponent');
runTask(() => this.context.set('somecomponent', 'notsomecomponent'));
this.assertText('notsomecomponent');
}
['@test non-block with properties on attrs']() {
this.registerComponent('non-block', {
template: 'In layout - someProp: {{attrs.someProp}}',
});
this.render('{{non-block someProp=prop}}', {
prop: 'something here',
});
this.assertText('In layout - someProp: something here');
runTask(() => this.rerender());
this.assertText('In layout - someProp: something here');
runTask(() => this.context.set('prop', 'other thing there'));
this.assertText('In layout - someProp: other thing there');
runTask(() => this.context.set('prop', 'something here'));
this.assertText('In layout - someProp: something here');
}
['@feature(ember-glimmer-named-arguments) non-block with named argument']() {
this.registerComponent('non-block', {
template: 'In layout - someProp: {{@someProp}}',
});
this.render('{{non-block someProp=prop}}', {
prop: 'something here',
});
this.assertText('In layout - someProp: something here');
runTask(() => this.rerender());
this.assertText('In layout - someProp: something here');
runTask(() => this.context.set('prop', 'other thing there'));
this.assertText('In layout - someProp: other thing there');
runTask(() => this.context.set('prop', 'something here'));
this.assertText('In layout - someProp: something here');
}
['@test non-block with properties overridden in init']() {
let instance;
this.registerComponent('non-block', {
ComponentClass: Component.extend({
init() {
this._super(...arguments);
instance = this;
this.someProp = 'value set in instance';
},
}),
template: 'In layout - someProp: {{someProp}}',
});
this.render('{{non-block someProp=prop}}', {
prop: 'something passed when invoked',
});
this.assertText('In layout - someProp: value set in instance');
runTask(() => this.rerender());
this.assertText('In layout - someProp: value set in instance');
runTask(() => this.context.set('prop', 'updated something passed when invoked'));
this.assertText('In layout - someProp: updated something passed when invoked');
runTask(() => instance.set('someProp', 'update value set in instance'));
this.assertText('In layout - someProp: update value set in instance');
runTask(() => this.context.set('prop', 'something passed when invoked'));
runTask(() => instance.set('someProp', 'value set in instance'));
this.assertText('In layout - someProp: value set in instance');
}
['@test rerendering component with attrs from parent'](assert) {
let willUpdateCount = 0;
let didReceiveAttrsCount = 0;
function expectHooks({ willUpdate, didReceiveAttrs }, callback) {
willUpdateCount = 0;
didReceiveAttrsCount = 0;
callback();
if (willUpdate) {
assert.strictEqual(willUpdateCount, 1, 'The willUpdate hook was fired');
} else {
assert.strictEqual(willUpdateCount, 0, 'The willUpdate hook was not fired');
}
if (didReceiveAttrs) {
assert.strictEqual(didReceiveAttrsCount, 1, 'The didReceiveAttrs hook was fired');
} else {
assert.strictEqual(didReceiveAttrsCount, 0, 'The didReceiveAttrs hook was not fired');
}
}
this.registerComponent('non-block', {
ComponentClass: Component.extend({
didReceiveAttrs() {
didReceiveAttrsCount++;
},
willUpdate() {
willUpdateCount++;
},
}),
template: 'In layout - someProp: {{someProp}}',
});
expectHooks({ willUpdate: false, didReceiveAttrs: true }, () => {
this.render('{{non-block someProp=someProp}}', {
someProp: 'wycats',
});
});
this.assertText('In layout - someProp: wycats');
// Note: Hooks are not fired in Glimmer for idempotent re-renders
expectHooks({ willUpdate: false, didReceiveAttrs: false }, () => {
runTask(() => this.rerender());
});
this.assertText('In layout - someProp: wycats');
expectHooks({ willUpdate: true, didReceiveAttrs: true }, () => {
runTask(() => this.context.set('someProp', 'tomdale'));
});
this.assertText('In layout - someProp: tomdale');
// Note: Hooks are not fired in Glimmer for idempotent re-renders
expectHooks({ willUpdate: false, didReceiveAttrs: false }, () => {
runTask(() => this.rerender());
});
this.assertText('In layout - someProp: tomdale');
expectHooks({ willUpdate: true, didReceiveAttrs: true }, () => {
runTask(() => this.context.set('someProp', 'wycats'));
});
this.assertText('In layout - someProp: wycats');
}
['@feature(!ember-glimmer-named-arguments) this.attrs.foo === attrs.foo === foo']() {
this.registerComponent('foo-bar', {
template: strip`
Args: {{this.attrs.value}} | {{attrs.value}} | {{value}}
{{#each this.attrs.items as |item|}}
{{item}}
{{/each}}
{{#each attrs.items as |item|}}
{{item}}
{{/each}}
{{#each items as |item|}}
{{item}}
{{/each}}
`,
});
this.render('{{foo-bar value=model.value items=model.items}}', {
model: {
value: 'wat',
items: [1, 2, 3],
},
});
this.assertStableRerender();
runTask(() => {
this.context.set('model.value', 'lul');
this.context.set('model.items', [1]);
});
this.assertText(strip`Args: lul | lul | lul111`);
runTask(() => this.context.set('model', { value: 'wat', items: [1, 2, 3] }));
this.assertText('Args: wat | wat | wat123123123');
}
['@feature(ember-glimmer-named-arguments) this.attrs.foo === attrs.foo === @foo === foo']() {
this.registerComponent('foo-bar', {
template: strip`
Args: {{this.attrs.value}} | {{attrs.value}} | {{@value}} | {{value}}
{{#each this.attrs.items as |item|}}
{{item}}
{{/each}}
{{#each attrs.items as |item|}}
{{item}}
{{/each}}
{{#each @items as |item|}}
{{item}}
{{/each}}
{{#each items as |item|}}
{{item}}
{{/each}}
`,
});
this.render('{{foo-bar value=model.value items=model.items}}', {
model: {
value: 'wat',
items: [1, 2, 3],
},
});
this.assertStableRerender();
runTask(() => {
this.context.set('model.value', 'lul');
this.context.set('model.items', [1]);
});
this.assertText(strip`Args: lul | lul | lul | lul1111`);
runTask(() => this.context.set('model', { value: 'wat', items: [1, 2, 3] }));
this.assertText('Args: wat | wat | wat | wat123123123123');
}
['@test non-block with properties on self']() {
this.registerComponent('non-block', {
template: 'In layout - someProp: {{someProp}}',
});
this.render('{{non-block someProp=prop}}', {
prop: 'something here',
});
this.assertText('In layout - someProp: something here');
runTask(() => this.rerender());
this.assertText('In layout - someProp: something here');
runTask(() => this.context.set('prop', 'something else'));
this.assertText('In layout - someProp: something else');
runTask(() => this.context.set('prop', 'something here'));
this.assertText('In layout - someProp: something here');
}
['@test block with properties on self']() {
this.registerComponent('with-block', {
template: 'In layout - someProp: {{someProp}} - {{yield}}',
});
this.render(
strip`
{{#with-block someProp=prop}}
In template
{{/with-block}}`,
{
prop: 'something here',
}
);
this.assertText('In layout - someProp: something here - In template');
runTask(() => this.rerender());
this.assertText('In layout - someProp: something here - In template');
runTask(() => this.context.set('prop', 'something else'));
this.assertText('In layout - someProp: something else - In template');
runTask(() => this.context.set('prop', 'something here'));
this.assertText('In layout - someProp: something here - In template');
}
['@test block with properties on attrs']() {
this.registerComponent('with-block', {
template: 'In layout - someProp: {{attrs.someProp}} - {{yield}}',
});
this.render(
strip`
{{#with-block someProp=prop}}
In template
{{/with-block}}`,
{
prop: 'something here',
}
);
this.assertText('In layout - someProp: something here - In template');
runTask(() => this.rerender());
this.assertText('In layout - someProp: something here - In template');
runTask(() => this.context.set('prop', 'something else'));
this.assertText('In layout - someProp: something else - In template');
runTask(() => this.context.set('prop', 'something here'));
this.assertText('In layout - someProp: something here - In template');
}
['@feature(ember-glimmer-named-arguments) block with named argument']() {
this.registerComponent('with-block', {
template: 'In layout - someProp: {{@someProp}} - {{yield}}',
});
this.render(
strip`
{{#with-block someProp=prop}}
In template
{{/with-block}}`,
{
prop: 'something here',
}
);
this.assertText('In layout - someProp: something here - In template');
runTask(() => this.rerender());
this.assertText('In layout - someProp: something here - In template');
runTask(() => this.context.set('prop', 'something else'));
this.assertText('In layout - someProp: something else - In template');
runTask(() => this.context.set('prop', 'something here'));
this.assertText('In layout - someProp: something here - In template');
}
['@test static arbitrary number of positional parameters'](assert) {
this.registerComponent('sample-component', {
ComponentClass: Component.extend().reopenClass({
positionalParams: 'names',
}),
template: strip`
{{#each names as |name|}}
{{name}}
{{/each}}`,
});
this.render(strip`
{{sample-component "Foo" 4 "Bar" elementId="args-3"}}
{{sample-component "Foo" 4 "Bar" 5 "Baz" elementId="args-5"}}`);
assert.equal(this.$('#args-3').text(), 'Foo4Bar');
assert.equal(this.$('#args-5').text(), 'Foo4Bar5Baz');
runTask(() => this.rerender());
assert.equal(this.$('#args-3').text(), 'Foo4Bar');
assert.equal(this.$('#args-5').text(), 'Foo4Bar5Baz');
}
['@test arbitrary positional parameter conflict with hash parameter is reported']() {
this.registerComponent('sample-component', {
ComponentClass: Component.extend().reopenClass({
positionalParams: 'names',
}),
template: strip`
{{#each names as |name|}}
{{name}}
{{/each}}`,
});
expectAssertion(() => {
this.render(`{{sample-component "Foo" 4 "Bar" names=numbers id="args-3"}}`, {
numbers: [1, 2, 3],
});
}, 'You cannot specify positional parameters and the hash argument `names`.');
}
['@test can use hash parameter instead of arbitrary positional param [GH #12444]']() {
this.registerComponent('sample-component', {
ComponentClass: Component.extend().reopenClass({
positionalParams: 'names',
}),
template: strip`
{{#each names as |name|}}
{{name}}
{{/each}}`,
});
this.render('{{sample-component names=things}}', {
things: emberA(['Foo', 4, 'Bar']),
});
this.assertText('Foo4Bar');
runTask(() => this.rerender());
this.assertText('Foo4Bar');
runTask(() => this.context.get('things').pushObject(5));
this.assertText('Foo4Bar5');
runTask(() => this.context.get('things').shiftObject());
this.assertText('4Bar5');
runTask(() => this.context.get('things').clear());
this.assertText('');
runTask(() => this.context.set('things', emberA(['Foo', 4, 'Bar'])));
this.assertText('Foo4Bar');
}
['@test can use hash parameter instead of positional param'](assert) {
this.registerComponent('sample-component', {
ComponentClass: Component.extend().reopenClass({
positionalParams: ['first', 'second'],
}),
template: '{{first}} - {{second}}',
});
// TODO: Fix when id is implemented
this.render(strip`
{{sample-component "one" "two" elementId="two-positional"}}
{{sample-component "one" second="two" elementId="one-positional"}}
{{sample-component first="one" second="two" elementId="no-positional"}}`);
assert.equal(this.$('#two-positional').text(), 'one - two');
assert.equal(this.$('#one-positional').text(), 'one - two');
assert.equal(this.$('#no-positional').text(), 'one - two');
runTask(() => this.rerender());
assert.equal(this.$('#two-positional').text(), 'one - two');
assert.equal(this.$('#one-positional').text(), 'one - two');
assert.equal(this.$('#no-positional').text(), 'one - two');
}
['@test dynamic arbitrary number of positional parameters']() {
this.registerComponent('sample-component', {
ComponentClass: Component.extend().reopenClass({
positionalParams: 'n',
}),
template: strip`
{{#each n as |name|}}
{{name}}
{{/each}}`,
});
this.render(`{{sample-component user1 user2}}`, {
user1: 'Foo',
user2: 4,
});
this.assertText('Foo4');
runTask(() => this.rerender());
this.assertText('Foo4');
runTask(() => this.context.set('user1', 'Bar'));
this.assertText('Bar4');
runTask(() => this.context.set('user2', '5'));
this.assertText('Bar5');
runTask(() => {
this.context.set('user1', 'Foo');
this.context.set('user2', 4);
});
this.assertText('Foo4');
}
['@test with ariaRole specified']() {
this.registerComponent('aria-test', {
template: 'Here!',
});
this.render('{{aria-test ariaRole=role}}', {
role: 'main',
});
this.assertComponentElement(this.firstChild, { attrs: { role: 'main' } });
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, { attrs: { role: 'main' } });
runTask(() => this.context.set('role', 'input'));
this.assertComponentElement(this.firstChild, {
attrs: { role: 'input' },
});
runTask(() => this.context.set('role', 'main'));
this.assertComponentElement(this.firstChild, { attrs: { role: 'main' } });
}
['@test with ariaRole defined but initially falsey GH#16379']() {
this.registerComponent('aria-test', {
template: 'Here!',
});
this.render('{{aria-test ariaRole=role}}', {
role: undefined,
});
this.assertComponentElement(this.firstChild, { attrs: {} });
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, { attrs: {} });
runTask(() => this.context.set('role', 'input'));
this.assertComponentElement(this.firstChild, {
attrs: { role: 'input' },
});
runTask(() => this.context.set('role', undefined));
this.assertComponentElement(this.firstChild, { attrs: {} });
}
['@test without ariaRole defined initially']() {
// we are using the ability to lazily add a role as a sign that we are
// doing extra work
let instance;
this.registerComponent('aria-test', {
ComponentClass: Component.extend({
init() {
this._super(...arguments);
instance = this;
},
}),
template: 'Here!',
});
this.render('{{aria-test}}');
this.assertComponentElement(this.firstChild, { attrs: {} });
runTask(() => this.rerender());
this.assertComponentElement(this.firstChild, { attrs: {} });
runTask(() => instance.set('ariaRole', 'input'));
this.assertComponentElement(this.firstChild, { attrs: {} });
}
['@test `template` specified in component is overridden by block']() {
this.registerComponent('with-template', {
ComponentClass: Component.extend({
template: compile('Should not be used'),
}),
template: '[In layout - {{name}}] {{yield}}',
});
this.render(
strip`
{{#with-template name="with-block"}}
[In block - {{name}}]
{{/with-template}}
{{with-template name="without-block"}}`,
{
name: 'Whoop, whoop!',
}
);
this.assertText(
'[In layout - with-block] [In block - Whoop, whoop!][In layout - without-block] '
);
runTask(() => this.rerender());
this.assertText(
'[In layout - with-block] [In block - Whoop, whoop!][In layout - without-block] '
);
runTask(() => this.context.set('name', 'Ole, ole'));
this.assertText('[In layout - with-block] [In block - Ole, ole][In layout - without-block] ');
runTask(() => this.context.set('name', 'Whoop, whoop!'));
this.assertText(
'[In layout - with-block] [In block - Whoop, whoop!][In layout - without-block] '
);
}
['@test hasBlock is true when block supplied']() {
this.registerComponent('with-block', {
template: strip`
{{#if hasBlock}}
{{yield}}
{{else}}
No Block!
{{/if}}`,
});
this.render(strip`
{{#with-block}}
In template
{{/with-block}}`);
this.assertText('In template');
runTask(() => this.rerender());
this.assertText('In template');
}
['@test hasBlock is false when no block supplied']() {
this.registerComponent('with-block', {
template: strip`
{{#if hasBlock}}
{{yield}}
{{else}}
No Block!
{{/if}}`,
});
this.render('{{with-block}}');
this.assertText('No Block!');
runTask(() => this.rerender());
this.assertText('No Block!');
}
['@test hasBlockParams is true when block param supplied']() {
this.registerComponent('with-block', {
template: strip`
{{#if hasBlockParams}}
{{yield this}} - In Component
{{else}}
{{yield}} No Block!
{{/if}}`,
});
this.render(strip`
{{#with-block as |something|}}
In template
{{/with-block}}`);
this.assertText('In template - In Component');
runTask(() => this.rerender());
this.assertText('In template - In Component');
}
['@test hasBlockParams is false when no block param supplied']() {
this.registerComponent('with-block', {
template: strip`
{{#if hasBlockParams}}
{{yield this}}
{{else}}
{{yield}} No Block Param!
{{/if}}`,
});
this.render(strip`
{{#with-block}}
In block
{{/with-block}}`);
this.assertText('In block No Block Param!');
runTask(() => this.rerender());
this.assertText('In block No Block Param!');
}
['@test static named positional parameters']() {
this.registerComponent('sample-component', {
ComponentClass: Component.extend().reopenClass({
positionalParams: ['name', 'age'],
}),
template: '{{name}}{{age}}',
});
this.render('{{sample-component "Quint" 4}}');
this.assertText('Quint4');
runTask(() => this.rerender());
this.assertText('Quint4');
}
['@test dynamic named positional parameters']() {
this.registerComponent('sample-component', {
ComponentClass: Component.extend().reopenClass({
positionalParams: ['name', 'age'],
}),
template: '{{name}}{{age}}',
});
this.render('{{sample-component myName myAge}}', {
myName: 'Quint',
myAge: 4,
});
this.assertText('Quint4');
runTask(() => this.rerender());
this.assertText('Quint4');
runTask(() => this.context.set('myName', 'Sergio'));
this.assertText('Sergio4');
runTask(() => this.context.set('myAge', 2));
this.assertText('Sergio2');
runTask(() => {
this.context.set('myName', 'Quint');
this.context.set('myAge', 4);
});
this.assertText('Quint4');
}
['@test if a value is passed as a non-positional parameter, it raises an assertion']() {
this.registerComponent('sample-component', {
ComponentClass: Component.extend().reopenClass({
positionalParams: ['name'],
}),
template: '{{name}}',
});
expectAssertion(() => {
this.render('{{sample-component notMyName name=myName}}', {
myName: 'Quint',
notMyName: 'Sergio',
});
}, 'You cannot specify both a positional param (at position 0) and the hash argument `name`.');
}
['@test yield to inverse']() {
this.registerComponent('my-if', {
template: strip`
{{#if predicate}}
Yes:{{yield someValue}}
{{else}}
No:{{yield to="inverse"}}
{{/if}}`,
});
this.render(
strip`
{{#my-if predicate=activated someValue=42 as |result|}}
Hello{{result}}
{{else}}
Goodbye
{{/my-if}}`,
{
activated: true,
}
);
this.assertText('Yes:Hello42');
runTask(() => this.rerender());
this.assertText('Yes:Hello42');
runTask(() => this.context.set('activated', false));
this.assertText('No:Goodbye');
runTask(() => this.context.set('activated', true));
this.assertText('Yes:Hello42');
}
['@test expression hasBlock inverse']() {
this.registerComponent('check-inverse', {
template: strip`
{{#if (hasBlock "inverse")}}
Yes
{{else}}
No
{{/if}}`,
});
this.render(strip`
{{#check-inverse}}{{/check-inverse}}
{{#check-inverse}}{{else}}{{/check-inverse}}`);
this.assertComponentElement(this.firstChild, { content: 'No' });
this.assertComponentElement(this.nthChild(1), { content: 'Yes' });
this.assertStableRerender();
}
['@test expression hasBlock default']() {
this.registerComponent('check-block', {
template: strip`
{{#if (hasBlock)}}
Yes
{{else}}
No
{{/if}}`,
});
this.render(strip`
{{check-block}}
{{#check-block}}{{/check-block}}`);
this.assertComponentElement(this.firstChild, { content: 'No' });
this.assertComponentElement(this.nthChild(1), { content: 'Yes' });
this.assertStableRerender();
}
['@test expression hasBlockParams inverse']() {
this.registerComponent('check-inverse', {
template: strip`
{{#if (hasBlockParams "inverse")}}
Yes
{{else}}
No
{{/if}}`,
});
this.render(strip`
{{#check-inverse}}{{/check-inverse}}
{{#check-inverse as |something|}}{{/check-inverse}}`);
this.assertComponentElement(this.firstChild, { content: 'No' });
this.assertComponentElement(this.nthChild(1), { content: 'No' });
this.assertStableRerender();
}
['@test expression hasBlockParams default']() {
this.registerComponent('check-block', {
template: strip`
{{#if (hasBlockParams)}}
Yes
{{else}}
No
{{/if}}`,
});
this.render(strip`
{{#check-block}}{{/check-block}}
{{#check-block as |something|}}{{/check-block}}`);
this.assertComponentElement(this.firstChild, { content: 'No' });
this.assertComponentElement(this.nthChild(1), { content: 'Yes' });
this.assertStableRerender();
}
['@test non-expression hasBlock']() {
this.registerComponent('check-block', {
template: strip`
{{#if hasBlock}}
Yes
{{else}}
No
{{/if}}`,
});
this.render(strip`
{{check-block}}
{{#check-block}}{{/check-block}}`);
this.assertComponentElement(this.firstChild, { content: 'No' });
this.assertComponentElement(this.nthChild(1), { content: 'Yes' });
this.assertStableRerender();
}
['@test expression hasBlockParams']() {
this.registerComponent('check-params', {
template: strip`
{{#if (hasBlockParams)}}
Yes
{{else}}
No
{{/if}}`,
});
this.render(strip`
{{#check-params}}{{/check-params}}
{{#check-params as |foo|}}{{/check-params}}`);
this.assertComponentElement(this.firstChild, { content: 'No' });
this.assertComponentElement(this.nthChild(1), { content: 'Yes' });
this.assertStableRerender();
}
['@test non-expression hasBlockParams']() {
this.registerComponent('check-params', {
template: strip`
{{#if hasBlockParams}}
Yes
{{else}}
No
{{/if}}`,
});
this.render(strip`
{{#check-params}}{{/check-params}}
{{#check-params as |foo|}}{{/check-params}}`);
this.assertComponentElement(this.firstChild, { content: 'No' });
this.assertComponentElement(this.nthChild(1), { content: 'Yes' });
this.assertStableRerender();
}
['@test hasBlock expression in an attribute'](assert) {
this.registerComponent('check-attr', {
template: '<button name={{hasBlock}}></button>',
});
this.render(strip`
{{check-attr}}
{{#check-attr}}{{/check-attr}}`);
equalsElement(assert, this.$('button')[0], 'button', { name: 'false' }, '');
equalsElement(assert, this.$('button')[1], 'button', { name: 'true' }, '');
this.assertStableRerender();
}
['@test hasBlock inverse expression in an attribute'](assert) {
this.registerComponent(
'check-attr',
{
template: '<button name={{hasBlock "inverse"}}></button>',
},
''
);
this.render(strip`
{{#check-attr}}{{/check-attr}}
{{#check-attr}}{{else}}{{/check-attr}}`);
equalsElement(assert, this.$('button')[0], 'button', { name: 'false' }, '');
equalsElement(assert, this.$('button')[1], 'button', { name: 'true' }, '');
this.assertStableRerender();
}
['@test hasBlockParams expression in an attribute'](assert) {
this.registerComponent('check-attr', {
template: '<button name={{hasBlockParams}}></button>',
});
this.render(strip`
{{#check-attr}}{{/check-attr}}
{{#check-attr as |something|}}{{/check-attr}}`);
equalsElement(assert, this.$('button')[0], 'button', { name: 'false' }, '');
equalsElement(assert, this.$('button')[1], 'button', { name: 'true' }, '');
this.assertStableRerender();
}
['@test hasBlockParams inverse expression in an attribute'](assert) {
this.registerComponent(
'check-attr',
{
template: '<button name={{hasBlockParams "inverse"}}></button>',
},
''
);
this.render(strip`
{{#check-attr}}{{/check-attr}}
{{#check-attr as |something|}}{{/check-attr}}`);
equalsElement(assert, this.$('button')[0], 'button', { name: 'false' }, '');
equalsElement(assert, this.$('button')[1], 'button', { name: 'false' }, '');
this.assertStableRerender();
}
['@test hasBlock as a param to a helper']() {
this.registerComponent('check-helper', {
template: '{{if hasBlock "true" "false"}}',
});
this.render(strip`
{{check-helper}}
{{#check-helper}}{{/check-helper}}`);
this.assertComponentElement(this.firstChild, { content: 'false' });
this.assertComponentElement(this.nthChild(1), { content: 'true' });
this.assertStableRerender();
}
['@test hasBlock as an expression param to a helper']() {
this.registerComponent('check-helper', {
template: '{{if (hasBlock) "true" "false"}}',
});
this.render(strip`
{{check-helper}}
{{#check-helper}}{{/check-helper}}`);
this.assertComponentElement(this.firstChild, { content: 'false' });
this.assertComponentElement(this.nthChild(1), { content: 'true' });
this.assertStableRerender();
}
['@test hasBlock inverse as a param to a helper']() {
this.registerComponent('check-helper', {
template: '{{if (hasBlock "inverse") "true" "false"}}',
});
this.render(strip`
{{#check-helper}}{{/check-helper}}
{{#check-helper}}{{else}}{{/check-helper}}`);
this.assertComponentElement(this.firstChild, { content: 'false' });
this.assertComponentElement(this.nthChild(1), { content: 'true' });
this.assertStableRerender();
}
['@test hasBlockParams as a param to a helper']() {
this.registerComponent('check-helper', {
template: '{{if hasBlockParams "true" "false"}}',
});
this.render(strip`
{{#check-helper}}{{/check-helper}}
{{#check-helper as |something|}}{{/check-helper}}`);
this.assertComponentElement(this.firstChild, { content: 'false' });
this.assertComponentElement(this.nthChild(1), { content: 'true' });
this.assertStableRerender();
}
['@test hasBlockParams as an expression param to a helper']() {
this.registerComponent('check-helper', {
template: '{{if (hasBlockParams) "true" "false"}}',
});
this.render(strip`
{{#check-helper}}{{/check-helper}}
{{#check-helper as |something|}}{{/check-helper}}`);
this.assertComponentElement(this.firstChild, { content: 'false' });
this.assertComponentElement(this.nthChild(1), { content: 'true' });
this.assertStableRerender();
}
['@test hasBlockParams inverse as a param to a helper']() {
this.registerComponent('check-helper', {
template: '{{if (hasBlockParams "inverse") "true" "false"}}',
});
this.render(strip`
{{#check-helper}}{{/check-helper}}
{{#check-helper as |something|}}{{/check-helper}}`);
this.assertComponentElement(this.firstChild, { content: 'false' });
this.assertComponentElement(this.nthChild(1), { content: 'false' });
this.assertStableRerender();
}
['@test component in template of a yielding component should have the proper parentView'](
assert
) {
let outer, innerTemplate, innerLayout;
this.registerComponent('x-outer', {
ComponentClass: Component.extend({
init() {
this._super(...arguments);
outer = this;
},
}),
template: '{{x-inner-in-layout}}{{yield}}',
});
this.registerComponent('x-inner-in-template', {
ComponentClass: Component.extend({
init() {
this._super(...arguments);
innerTemplate = this;
},
}),
});
this.registerComponent('x-inner-in-layout', {
ComponentClass: Component.extend({
init() {
this._super(...arguments);
innerLayout = this;
},
}),
});
this.render('{{#x-outer}}{{x-inner-in-template}}{{/x-outer}}');
assert.equal(
innerTemplate.parentView,
outer,
'receives the wrapping component as its parentView in template blocks'
);
assert.equal(
innerLayout.parentView,
outer,
'receives the wrapping component as its parentView in layout'
);
assert.equal(
outer.parentView,
this.context,
'x-outer receives the ambient scope as its parentView'
);
runTask(() => this.rerender());
assert.equal(
innerTemplate.parentView,
outer,
'receives the wrapping component as its parentView in template blocks'
);
assert.equal(
innerLayout.parentView,
outer,
'receives the wrapping component as its parentView in layout'
);
assert.equal(
outer.parentView,
this.context,
'x-outer receives the ambient scope as its parentView'
);
}
['@test newly-added sub-components get correct parentView'](assert) {
let outer, inner;
this.registerComponent('x-outer', {
ComponentClass: Component.extend({
init() {
this._super(...arguments);
outer = this;
},
}),
});
this.registerComponent('x-inner', {
ComponentClass: Component.extend({
init() {
this._super(...arguments);
inner = this;
},
}),
});
this.render(
strip`
{{#x-outer}}
{{#if showInner}}
{{x-inner}}
{{/if}}
{{/x-outer}}`,
{
showInner: false,
}
);
assert.equal(
outer.parentView,
this.context,
'x-outer receives the ambient scope as its parentView'
);
runTask(() => this.rerender());
assert.equal(
outer.parentView,
this.context,
'x-outer receives the ambient scope as its parentView (after rerender)'
);
runTask(() => this.context.set('showInner', true));
assert.equal(
outer.parentView,
this.context,
'x-outer receives the ambient scope as its parentView'
);
assert.equal(
inner.parentView,
outer,
'receives the wrapping component as its parentView in template blocks'
);
runTask(() => this.context.set('showInner', false));
assert.equal(
outer.parentView,
this.context,
'x-outer receives the ambient scope as its parentView'
);
}
["@test when a property is changed during children's rendering"](assert) {
let outer, middle;
this.registerComponent('x-outer', {
ComponentClass: Component.extend({
init() {
this._super(...arguments);
outer = this;
},
value: 1,
}),
template: '{{#x-middle}}{{x-inner value=value}}{{/x-middle}}',
});
this.registerComponent('x-middle', {
ComponentClass: Component.extend({
init() {
this._super(...arguments);
middle = this;
},
value: null,
}),
template: '<div id="middle-value">{{value}}</div>{{yield}}',
});
this.registerComponent('x-inner', {
ComponentClass: Component.extend({
value: null,
pushDataUp: observer('value', function() {
middle.set('value', this.get('value'));
}),
}),
template: '<div id="inner-value">{{value}}</div>',
});
this.render('{{x-outer}}');
assert.equal(this.$('#inner-value').text(), '1', 'initial render of inner');
assert.equal(
this.$('#middle-value').text(),
'',
'initial render of middle (observers do not run during init)'
);
runTask(() => this.rerender());
assert.equal(this.$('#inner-value').text(), '1', 'initial render of inner');
assert.equal(
this.$('#middle-value').text(),
'',
'initial render of middle (observers do not run during init)'
);
let expectedBacktrackingMessage = /modified "value" twice on <.+?> in a single render\. It was rendered in "component:x-middle" and modified in "component:x-inner"/;
expectAssertion(() => {
runTask(() => outer.set('value', 2));
}, expectedBacktrackingMessage);
}
["@test when a shared dependency is changed during children's rendering"]() {
this.registerComponent('x-outer', {
ComponentClass: Component.extend({
value: 1,
wrapper: EmberObject.create({ content: null }),
}),
template:
'<div id="outer-value">{{wrapper.content}}</div> {{x-inner value=value wrapper=wrapper}}',
});
this.registerComponent('x-inner', {
ComponentClass: Component.extend({
didReceiveAttrs() {
this.get('wrapper').set('content', this.get('value'));
},
value: null,
}),
template: '<div id="inner-value">{{wrapper.content}}</div>',
});
let expectedBacktrackingMessage = /modified "wrapper\.content" twice on <.+?> in a single render\. It was rendered in "component:x-outer" and modified in "component:x-inner"/;
expectAssertion(() => {
this.render('{{x-outer}}');
}, expectedBacktrackingMessage);
}
['@test non-block with each rendering child components']() {
this.registerComponent('non-block', {
template: strip`
In layout. {{#each items as |item|}}
[{{child-non-block item=item}}]
{{/each}}`,
});
this.registerComponent('child-non-block', {
template: 'Child: {{item}}.',
});
let items = emberA(['Tom', 'Dick', 'Harry']);
this.render('{{non-block items=items}}', { items });
this.assertText('In layout. [Child: Tom.][Child: Dick.][Child: Harry.]');
runTask(() => this.rerender());
this.assertText('In layout. [Child: Tom.][Child: Dick.][Child: Harry.]');
runTask(() => this.context.get('items').pushObject('Sergio'));
this.assertText('In layout. [Child: Tom.][Child: Dick.][Child: Harry.][Child: Sergio.]');
runTask(() => this.context.get('items').shiftObject());
this.assertText('In layout. [Child: Dick.][Child: Harry.][Child: Sergio.]');
runTask(() => this.context.set('items', emberA(['Tom', 'Dick', 'Harry'])));
this.assertText('In layout. [Child: Tom.][Child: Dick.][Child: Harry.]');
}
['@test specifying classNames results in correct class'](assert) {
this.registerComponent('some-clicky-thing', {
ComponentClass: Component.extend({
tagName: 'button',
classNames: ['foo', 'bar'],
}),
});
this.render(strip`
{{#some-clicky-thing classNames="baz"}}
Click Me
{{/some-clicky-thing}}`);
// TODO: ember-view is no longer viewable in the classNames array. Bug or
// feature?
let expectedClassNames = ['ember-view', 'foo', 'bar', 'baz'];
assert.ok(
this.$('button').is('.foo.bar.baz.ember-view'),
`the element has the correct classes: ${this.$('button').attr('class')}`
);
// `ember-view` is no longer in classNames.
// assert.deepEqual(clickyThing.get('classNames'), expectedClassNames, 'classNames are properly combined');
this.assertComponentElement(this.firstChild, {
tagName: 'button',
attrs: { class: classes(expectedClassNames.join(' ')) },
});
runTask(() => this.rerender());
assert.ok(
this.$('button').is('.foo.bar.baz.ember-view'),
`the element has the correct classes: ${this.$('button').attr('class')} (rerender)`
);
// `ember-view` is no longer in classNames.
// assert.deepEqual(clickyThing.get('classNames'), expectedClassNames, 'classNames are properly combined (rerender)');
this.assertComponentElement(this.firstChild, {
tagName: 'button',
attrs: { class: classes(expectedClassNames.join(' ')) },
});
}
['@test specifying custom concatenatedProperties avoids clobbering']() {
this.registerComponent('some-clicky-thing', {
ComponentClass: Component.extend({
concatenatedProperties: ['blahzz'],
blahzz: ['blark', 'pory'],
}),
template: strip`
{{#each blahzz as |p|}}
{{p}}
{{/each}}
- {{yield}}`,
});
this.render(strip`
{{#some-clicky-thing blahzz="baz"}}
Click Me
{{/some-clicky-thing}}`);
this.assertText('blarkporybaz- Click Me');
runTask(() => this.rerender());
this.assertText('blarkporybaz- Click Me');
}
['@test a two way binding flows upstream when consumed in the template']() {
let component;
let FooBarComponent = Component.extend({
init() {
this._super(...arguments);
component = this;
},
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: '{{bar}}',
});
this.render('{{localBar}} - {{foo-bar bar=localBar}}', {
localBar: 'initial value',
});
this.assertText('initial value - initial value');
runTask(() => this.rerender());
this.assertText('initial value - initial value');
if (DEBUG) {
expectAssertion(() => {
component.bar = 'foo-bar';
}, /You must use set\(\) to set the `bar` property \(of .+\) to `foo-bar`\./);
this.assertText('initial value - initial value');
}
runTask(() => {
component.set('bar', 'updated value');
});
this.assertText('updated value - updated value');
runTask(() => {
component.set('bar', undefined);
});
this.assertText(' - ');
runTask(() => {
this.component.set('localBar', 'initial value');
});
this.assertText('initial value - initial value');
}
['@test a two way binding flows upstream through a CP when consumed in the template']() {
let component;
let FooBarComponent = Component.extend({
init() {
this._super(...arguments);
component = this;
},
bar: computed({
get() {
return this._bar;
},
set(key, value) {
this._bar = value;
return this._bar;
},
}),
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: '{{bar}}',
});
this.render('{{localBar}} - {{foo-bar bar=localBar}}', {
localBar: 'initial value',
});
this.assertText('initial value - initial value');
runTask(() => this.rerender());
this.assertText('initial value - initial value');
runTask(() => {
component.set('bar', 'updated value');
});
this.assertText('updated value - updated value');
runTask(() => {
this.component.set('localBar', 'initial value');
});
this.assertText('initial value - initial value');
}
['@test a two way binding flows upstream through a CP without template consumption']() {
let component;
let FooBarComponent = Component.extend({
init() {
this._super(...arguments);
component = this;
},
bar: computed({
get() {
return this._bar;
},
set(key, value) {
this._bar = value;
return this._bar;
},
}),
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: '',
});
this.render('{{localBar}}{{foo-bar bar=localBar}}', {
localBar: 'initial value',
});
this.assertText('initial value');
runTask(() => this.rerender());
this.assertText('initial value');
runTask(() => {
component.set('bar', 'updated value');
});
this.assertText('updated value');
runTask(() => {
this.component.set('localBar', 'initial value');
});
this.assertText('initial value');
}
['@test services can be injected into components']() {
let service;
this.registerService(
'name',
Service.extend({
init() {
this._super(...arguments);
service = this;
},
last: 'Jackson',
})
);
this.registerComponent('foo-bar', {
ComponentClass: Component.extend({
name: injectService(),
}),
template: '{{name.last}}',
});
this.render('{{foo-bar}}');
this.assertText('Jackson');
runTask(() => this.rerender());
this.assertText('Jackson');
runTask(() => {
service.set('last', 'McGuffey');
});
this.assertText('McGuffey');
runTask(() => {
service.set('last', 'Jackson');
});
this.assertText('Jackson');
}
['@test injecting an unknown service raises an exception']() {
this.registerComponent('foo-bar', {
ComponentClass: Component.extend({
missingService: injectService(),
}),
});
expectAssertion(() => {
this.render('{{foo-bar}}');
}, "Attempting to inject an unknown injection: 'service:missingService'");
}
['@test throws if `this._super` is not called from `init`']() {
this.registerComponent('foo-bar', {
ComponentClass: Component.extend({
init() {},
}),
});
expectAssertion(() => {
this.render('{{foo-bar}}');
}, /You must call `this._super\(...arguments\);` when overriding `init` on a framework object. Please update .* to call `this._super\(...arguments\);` from `init`./);
}
['@test should toggle visibility with isVisible'](assert) {
let assertStyle = expected => {
let matcher = styles(expected);
let actual = this.firstChild.getAttribute('style');
assert.pushResult({
result: matcher.match(actual),
message: matcher.message(),
actual,
expected,
});
};
this.registerComponent('foo-bar', {
template: `<p>foo</p>`,
});
this.render(`{{foo-bar id="foo-bar" isVisible=visible}}`, {
visible: false,
});
assertStyle('display: none;');
this.assertStableRerender();
runTask(() => {
set(this.context, 'visible', true);
});
assertStyle('');
runTask(() => {
set(this.context, 'visible', false);
});
assertStyle('display: none;');
}
['@test isVisible does not overwrite component style']() {
this.registerComponent('foo-bar', {
ComponentClass: Component.extend({
attributeBindings: ['style'],
style: htmlSafe('color: blue;'),
}),
template: `<p>foo</p>`,
});
this.render(`{{foo-bar id="foo-bar" isVisible=visible}}`, {
visible: false,
});
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { id: 'foo-bar', style: styles('color: blue; display: none;') },
});
this.assertStableRerender();
runTask(() => {
set(this.context, 'visible', true);
});
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { id: 'foo-bar', style: styles('color: blue;') },
});
runTask(() => {
set(this.context, 'visible', false);
});
this.assertComponentElement(this.firstChild, {
tagName: 'div',
attrs: { id: 'foo-bar', style: styles('color: blue; display: none;') },
});
}
['@test adds isVisible binding when style binding is missing and other bindings exist'](
assert
) {
let assertStyle = expected => {
let matcher = styles(expected);
let actual = this.firstChild.getAttribute('style');
assert.pushResult({
result: matcher.match(actual),
message: matcher.message(),
actual,
expected,
});
};
this.registerComponent('foo-bar', {
ComponentClass: Component.extend({
attributeBindings: ['foo'],
foo: 'bar',
}),
template: `<p>foo</p>`,
});
this.render(`{{foo-bar id="foo-bar" foo=foo isVisible=visible}}`, {
visible: false,
foo: 'baz',
});
assertStyle('display: none;');
this.assertStableRerender();
runTask(() => {
set(this.context, 'visible', true);
});
assertStyle('');
runTask(() => {
set(this.context, 'visible', false);
set(this.context, 'foo', 'woo');
});
assertStyle('display: none;');
assert.equal(this.firstChild.getAttribute('foo'), 'woo');
}
['@test it can use readDOMAttr to read input value']() {
let component;
let assertElement = expectedValue => {
// value is a property, not an attribute
this.assertHTML(`<input class="ember-view" id="${component.elementId}">`);
this.assert.equal(this.firstChild.value, expectedValue, 'value property is correct');
this.assert.equal(
get(component, 'value'),
expectedValue,
'component.get("value") is correct'
);
};
this.registerComponent('one-way-input', {
ComponentClass: Component.extend({
tagName: 'input',
attributeBindings: ['value'],
init() {
this._super(...arguments);
component = this;
},
change() {
let value = this.readDOMAttr('value');
this.set('value', value);
},
}),
});
this.render('{{one-way-input value=value}}', {
value: 'foo',
});
assertElement('foo');
this.assertStableRerender();
runTask(() => {
this.firstChild.value = 'bar';
this.$('input').trigger('change');
});
assertElement('bar');
runTask(() => {
this.firstChild.value = 'foo';
this.$('input').trigger('change');
});
assertElement('foo');
runTask(() => {
set(component, 'value', 'bar');
});
assertElement('bar');
runTask(() => {
this.firstChild.value = 'foo';
this.$('input').trigger('change');
});
assertElement('foo');
}
['@test child triggers revalidate during parent destruction (GH#13846)']() {
this.registerComponent('x-select', {
ComponentClass: Component.extend({
tagName: 'select',
init() {
this._super();
this.options = emberA([]);
this.value = null;
},
updateValue() {
var newValue = this.get('options.lastObject.value');
this.set('value', newValue);
},
registerOption(option) {
this.get('options').addObject(option);
},
unregisterOption(option) {
this.get('options').removeObject(option);
this.updateValue();
},
}),
template: '{{yield this}}',
});
this.registerComponent('x-option', {
ComponentClass: Component.extend({
tagName: 'option',
attributeBindings: ['selected'],
didInsertElement() {
this._super(...arguments);
this.get('select').registerOption(this);
},
selected: computed('select.value', function() {
return this.get('value') === this.get('select.value');
}),
willDestroyElement() {
this._super(...arguments);
this.get('select').unregisterOption(this);
},
}),
});
this.render(strip`
{{#x-select value=value as |select|}}
{{#x-option value="1" select=select}}1{{/x-option}}
{{#x-option value="2" select=select}}2{{/x-option}}
{{/x-select}}
`);
this.teardown();
this.assert.ok(true, 'no errors during teardown');
}
['@test setting a property in willDestroyElement does not assert (GH#14273)'](assert) {
assert.expect(2);
this.registerComponent('foo-bar', {
ComponentClass: Component.extend({
init() {
this._super(...arguments);
this.showFoo = true;
},
willDestroyElement() {
this.set('showFoo', false);
assert.ok(true, 'willDestroyElement was fired');
this._super(...arguments);
},
}),
template: `{{#if showFoo}}things{{/if}}`,
});
this.render(`{{foo-bar}}`);
this.assertText('things');
}
['@test didReceiveAttrs fires after .init() but before observers become active'](assert) {
let barCopyDidChangeCount = 0;
this.registerComponent('foo-bar', {
ComponentClass: Component.extend({
init() {
this._super(...arguments);
this.didInit = true;
},
didReceiveAttrs() {
assert.ok(this.didInit, 'expected init to have run before didReceiveAttrs');
this.set('barCopy', this.attrs.bar.value + 1);
},
barCopyDidChange: observer('barCopy', () => {
barCopyDidChangeCount++;
}),
}),
template: '{{bar}}-{{barCopy}}',
});
this.render(`{{foo-bar bar=bar}}`, { bar: 3 });
this.assertText('3-4');
assert.strictEqual(barCopyDidChangeCount, 1, 'expected observer firing for: barCopy');
runTask(() => set(this.context, 'bar', 7));
this.assertText('7-8');
assert.strictEqual(barCopyDidChangeCount, 2, 'expected observer firing for: barCopy');
}
['@test overriding didReceiveAttrs does not trigger deprecation'](assert) {
this.registerComponent('foo-bar', {
ComponentClass: Component.extend({
didReceiveAttrs() {
assert.equal(1, this.get('foo'), 'expected attrs to have correct value');
},
}),
template: '{{foo}}-{{fooCopy}}-{{bar}}-{{barCopy}}',
});
this.render(`{{foo-bar foo=foo bar=bar}}`, { foo: 1, bar: 3 });
}
['@test overriding didUpdateAttrs does not trigger deprecation'](assert) {
this.registerComponent('foo-bar', {
ComponentClass: Component.extend({
didUpdateAttrs() {
assert.equal(5, this.get('foo'), 'expected newAttrs to have new value');
},
}),
template: '{{foo}}-{{fooCopy}}-{{bar}}-{{barCopy}}',
});
this.render(`{{foo-bar foo=foo bar=bar}}`, { foo: 1, bar: 3 });
runTask(() => set(this.context, 'foo', 5));
}
['@test returning `true` from an action does not bubble if `target` is not specified (GH#14275)'](
assert
) {
this.registerComponent('display-toggle', {
ComponentClass: Component.extend({
actions: {
show() {
assert.ok(true, 'display-toggle show action was called');
return true;
},
},
}),
template: `<button {{action 'show'}}>Show</button>`,
});
this.render(`{{display-toggle}}`, {
send() {
assert.notOk(true, 'send should not be called when action is not "subscribed" to');
},
});
this.assertText('Show');
runTask(() => this.$('button').click());
}
['@test returning `true` from an action bubbles to the `target` if specified'](assert) {
assert.expect(4);
this.registerComponent('display-toggle', {
ComponentClass: Component.extend({
actions: {
show() {
assert.ok(true, 'display-toggle show action was called');
return true;
},
},
}),
template: `<button {{action 'show'}}>Show</button>`,
});
this.render(`{{display-toggle target=this}}`, {
send(actionName) {
assert.ok(true, 'send should be called when action is "subscribed" to');
assert.equal(actionName, 'show');
},
});
this.assertText('Show');
runTask(() => this.$('button').click());
}
['@test triggering an event only attempts to invoke an identically named method, if it actually is a function (GH#15228)'](
assert
) {
assert.expect(3);
let payload = ['arbitrary', 'event', 'data'];
this.registerComponent('evented-component', {
ComponentClass: Component.extend({
someTruthyProperty: true,
init() {
this._super(...arguments);
this.trigger('someMethod', ...payload);
this.trigger('someTruthyProperty', ...payload);
},
someMethod(...data) {
assert.deepEqual(
data,
payload,
'the method `someMethod` should be called, when `someMethod` is triggered'
);
},
listenerForSomeMethod: on('someMethod', function(...data) {
assert.deepEqual(
data,
payload,
'the listener `listenerForSomeMethod` should be called, when `someMethod` is triggered'
);
}),
listenerForSomeTruthyProperty: on('someTruthyProperty', function(...data) {
assert.deepEqual(
data,
payload,
'the listener `listenerForSomeTruthyProperty` should be called, when `someTruthyProperty` is triggered'
);
}),
}),
});
this.render(`{{evented-component}}`);
}
['@test component yielding in an {{#each}} has correct block values after rerendering (GH#14284)']() {
this.registerComponent('list-items', {
template: `{{#each items as |item|}}{{yield item}}{{/each}}`,
});
this.render(
strip`
{{#list-items items=items as |thing|}}
|{{thing}}|
{{#if editMode}}
Remove {{thing}}
{{/if}}
{{/list-items}}
`,
{
editMode: false,
items: ['foo', 'bar', 'qux', 'baz'],
}
);
this.assertText('|foo||bar||qux||baz|');
this.assertStableRerender();
runTask(() => set(this.context, 'editMode', true));
this.assertText('|foo|Remove foo|bar|Remove bar|qux|Remove qux|baz|Remove baz');
runTask(() => set(this.context, 'editMode', false));
this.assertText('|foo||bar||qux||baz|');
}
['@test unimplimented positionalParams do not cause an error GH#14416']() {
this.registerComponent('foo-bar', {
template: 'hello',
});
this.render('{{foo-bar wat}}');
this.assertText('hello');
}
['@test using attrs for positional params']() {
let MyComponent = Component.extend();
this.registerComponent('foo-bar', {
ComponentClass: MyComponent.reopenClass({
positionalParams: ['myVar'],
}),
template: 'MyVar1: {{attrs.myVar}} {{myVar}} MyVar2: {{myVar2}} {{attrs.myVar2}}',
});
this.render('{{foo-bar 1 myVar2=2}}');
this.assertText('MyVar1: 1 1 MyVar2: 2 2');
}
['@feature(ember-glimmer-named-arguments) using named arguments for positional params']() {
let MyComponent = Component.extend();
this.registerComponent('foo-bar', {
ComponentClass: MyComponent.reopenClass({
positionalParams: ['myVar'],
}),
template: 'MyVar1: {{@myVar}} {{myVar}} MyVar2: {{myVar2}} {{@myVar2}}',
});
this.render('{{foo-bar 1 myVar2=2}}');
this.assertText('MyVar1: 1 1 MyVar2: 2 2');
}
["@test can use `{{this}}` to emit the component's toString value [GH#14581]"]() {
this.registerComponent('foo-bar', {
ComponentClass: Component.extend({
toString() {
return 'special sauce goes here!';
},
}),
template: '{{this}}',
});
this.render('{{foo-bar}}');
this.assertText('special sauce goes here!');
}
['@test can use `{{this` to access paths on current context [GH#14581]']() {
let instance;
this.registerComponent('foo-bar', {
ComponentClass: Component.extend({
init() {
this._super(...arguments);
instance = this;
},
foo: {
bar: {
baz: 'huzzah!',
},
},
}),
template: '{{this.foo.bar.baz}}',
});
this.render('{{foo-bar}}');
this.assertText('huzzah!');
this.assertStableRerender();
runTask(() => set(instance, 'foo.bar.baz', 'yippie!'));
this.assertText('yippie!');
runTask(() => set(instance, 'foo.bar.baz', 'huzzah!'));
this.assertText('huzzah!');
}
['@test can use custom element in component layout']() {
this.registerComponent('foo-bar', {
template: '<blah-zorz>Hi!</blah-zorz>',
});
this.render('{{foo-bar}}');
this.assertText('Hi!');
}
['@test can use nested custom element in component layout']() {
this.registerComponent('foo-bar', {
template: '<blah-zorz><hows-it-going>Hi!</hows-it-going></blah-zorz>',
});
this.render('{{foo-bar}}');
this.assertText('Hi!');
}
['@feature(!ember-glimmer-named-arguments) can access properties off of rest style positionalParams array']() {
this.registerComponent('foo-bar', {
ComponentClass: Component.extend().reopenClass({
positionalParams: 'things',
}),
// using `attrs` here to simulate `@things.length`
template: `{{attrs.things.length}}`,
});
this.render('{{foo-bar "foo" "bar" "baz"}}');
this.assertText('3');
}
['@feature(ember-glimmer-named-arguments) can access properties off of rest style positionalParams array']() {
this.registerComponent('foo-bar', {
ComponentClass: Component.extend().reopenClass({
positionalParams: 'things',
}),
template: `{{@things.length}}`,
});
this.render('{{foo-bar "foo" "bar" "baz"}}');
this.assertText('3');
}
['@test has attrs by didReceiveAttrs with native classes'](assert) {
class FooBarComponent extends Component {
constructor(injections) {
super(injections);
// analagous to class field defaults
this.foo = 'bar';
}
didReceiveAttrs() {
assert.equal(this.foo, 'bar', 'received default attrs correctly');
}
}
this.registerComponent('foo-bar', { ComponentClass: FooBarComponent });
this.render('{{foo-bar}}');
}
}
);
if (jQueryDisabled) {
moduleFor(
'Components test: curly components: jQuery disabled',
class extends RenderingTestCase {
['@test jQuery proxy is not available without jQuery']() {
let instance;
let FooBarComponent = Component.extend({
init() {
this._super();
instance = this;
},
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: 'hello',
});
this.render('{{foo-bar}}');
expectAssertion(() => {
instance.$()[0];
}, 'You cannot access this.$() with `jQuery` disabled.');
}
}
);
} else {
moduleFor(
'Components test: curly components: jQuery enabled',
class extends RenderingTestCase {
['@test it has a jQuery proxy to the element']() {
let instance;
let FooBarComponent = Component.extend({
init() {
this._super();
instance = this;
},
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: 'hello',
});
this.render('{{foo-bar}}');
let element1 = instance.$()[0];
this.assertComponentElement(element1, { content: 'hello' });
runTask(() => this.rerender());
let element2 = instance.$()[0];
this.assertComponentElement(element2, { content: 'hello' });
this.assertSameNode(element2, element1);
}
['@test it scopes the jQuery proxy to the component element'](assert) {
let instance;
let FooBarComponent = Component.extend({
init() {
this._super();
instance = this;
},
});
this.registerComponent('foo-bar', {
ComponentClass: FooBarComponent,
template: '<span class="inner">inner</span>',
});
this.render('<span class="outer">outer</span>{{foo-bar}}');
let $span = instance.$('span');
assert.equal($span.length, 1);
assert.equal($span.attr('class'), 'inner');
runTask(() => this.rerender());
$span = instance.$('span');
assert.equal($span.length, 1);
assert.equal($span.attr('class'), 'inner');
}
}
);
}
|
import jwt from 'jsonwebtoken';
import chai from 'chai';
import chaiHttp from 'chai-http';
import server from '../../../server';
const should = chai.should();
chai.use(chaiHttp);
describe('The user authentication API', () => {
// beforeEach((done) => {
// setTimeout(() => {
// done();
// }, 2000);
// });
let authenticatedUser;
describe('the login route', () => {
describe('for valid users', () => {
it('should login an existing user with valid username and password', (done) => {
chai.request(server)
.post('/api/users/login/')
.send({
identifier: 'SiliconValley',
password: 'password123',
})
.end((err, res) => {
authenticatedUser = res.body;
res.should.have.status(200);
done();
});
});
it('should login an existing user with valid email and password', (done) => {
chai.request(server)
.post('/api/users/login/')
.send({
identifier: 'ajudensi@breed101.com',
password: 'password123',
})
.end((err, res) => {
authenticatedUser = res.body;
res.should.have.status(200);
res.body.status.should.eql('true');
jwt.decode(res.body.token).roleId.should.eql(2);
done();
});
});
it('should generate an access token for a valid user', (done) => {
should.exist(authenticatedUser.token);
done();
});
it('should return `404` if user does not exist', (done) => {
chai.request(server)
.post('/api/users/login/')
.send({
identifier: 'idont@exist.com',
password: 'password123',
})
.end((err, res) => {
res.should.have.status(404);
res.body.message.should.eql('You don\'t exist');
done();
});
});
it('should return `bad request` for bad credentials', (done) => {
chai.request(server)
.post('/api/users/login/')
.send({
identifier: 'idont@exist.com',
password: 'password123',
})
.end((err, res) => {
res.should.have.status(404);
res.body.message.should.eql('You don\'t exist');
done();
});
});
});
describe('the logout route', () => {
it('should log a user out', (done) => {
chai.request(server)
.post('/api/users/logout/')
.set('authorization', `bearer ${authenticatedUser.token}`)
.end((err, res) => {
res.should.have.status(200);
res.body.message.should.eql('logout successful');
done();
});
});
it('should prevent a user from authenticated actions', (done) => {
chai.request(server)
.get('/api/search/users/')
.set('authorization', `bearer ${authenticatedUser.token}`)
.end((err, res) => {
res.should.have.status(401);
res.body.message.should.eql('you are not signed in');
done();
});
});
});
describe('for invalid users', () => {
it('should invalidate wrong credentials', (done) => {
chai.request(server)
.post('/api/users/login/')
.send({
identifier: 'somefaker@dude.com',
password: 'whateverpassword',
})
.end((err, res) => {
res.should.have.status(404);
res.body.message.should.eql('You don\'t exist');
done();
});
});
it('should invalidate users with wrong password', (done) => {
chai.request(server)
.post('/api/users/login/')
.send({
identifier: 'SiliconValley',
password: 'trysomethingfake',
})
.end((err, res) => {
res.should.have.status(401);
res.body.message.should.eql('wrong login credentials');
done();
});
});
it('should invalidate users without a token', (done) => {
chai.request(server)
.get('/api/search/users/')
.end((err, res) => {
res.should.have.status(401);
res.body.message.should.eql('you are not signed in');
done();
});
});
it('should invalidate users with a wrong token', (done) => {
chai.request(server)
.get('/api/users/')
.set('authorization', 'bearer 1234567890abcdefgh')
.end((err, res) => {
res.should.have.status(401);
res.body.message.should.eql('you are not signed in');
done();
});
});
it('should invalidate users with no password or identfier', (done) => {
chai.request(server)
.post('/api/users/login/')
.send({
identifier: 'SiliconValley',
})
.end((err, res) => {
res.should.have.status(400);
res.body.message.should.eql('username and password are required');
done();
});
});
});
});
});
|
exports.up = async knex => {
await knex.schema.createTable('admins', table => {
table.increments('adminId').primary()
table.date('createdAt')
table.date('loginAt')
table.string('mail')
table.string('password')
table.unique('mail')
})
}
exports.down = async knex => {
await knex.schema.dropTableIfExists('admins')
}
|
// flow-typed signature: c79c170227bc01f812c1a22fd1fedcae
// flow-typed version: <<STUB>>/babel-plugin-transform-react-constant-elements_v^6.3.13/flow_v0.37.0
/**
* This is an autogenerated libdef stub for:
*
* 'babel-plugin-transform-react-constant-elements'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'babel-plugin-transform-react-constant-elements' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'babel-plugin-transform-react-constant-elements/lib/index' {
declare module.exports: any;
}
// Filename aliases
declare module 'babel-plugin-transform-react-constant-elements/lib/index.js' {
declare module.exports: $Exports<'babel-plugin-transform-react-constant-elements/lib/index'>;
}
|
const visit = require('../../src/javascript/visit');
describe('visit', () => {
it('should handle empty', () => {
const found = [];
visit([], (node) => found.push(node));
expect(found).toEqual([]);
});
it('should handle an array with an empty object', () => {
const found = [];
visit([
{},
], (node) => found.push(node));
expect(found).toEqual([]);
});
});
|
var async = require("async");
var archieml = require('archieml');
var htmlparser = require('htmlparser2');
var Entities = require('html-entities').AllHtmlEntities;
var url = require('url');
var google = require('googleapis');
var lowerCase = function(str) {
return str.replace(/\s+/g, '_').toLowerCase();
};
var credentialsPath = (process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE) + '/.credentials.json';
module.exports = function(grunt) {
grunt.registerTask('gdocs', 'Parses Google Doc and downloads as JSON', function() {
var options = this.options({
credentials: (process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE) + '/.credentials.json',
docsID: '',
dest: 'json'
});
var credentials = grunt.file.readJSON(options.credentials);
if(!credentials.client_id || !credentials.client_secret) {
throw new Error('Missing client_id or client_secret');
};
if(!options.docsID) {
throw new Error('Missing Google Doc ID');
};
var OAuth2 = google.auth.OAuth2;
oauth2Client = new OAuth2(credentials.client_id, credentials.client_secret);
gDrive = google.drive({ version: 'v3', auth: oauth2Client });
oauth2Client.setCredentials(credentials.oAuthTokens);
var done = this.async();
gDrive.files.export({ fileId:options.docsID, mimeType: 'text/html'}, function (err, docHtml) {
var handler = new htmlparser.DomHandler(function (error, dom) {
var tagHandlers = {
_base: function (tag) {
var str = '';
tag.children.forEach(function (child) {
if (func = tagHandlers[child.name || child.type]) str += func(child);
});
return str;
},
text: function (textTag) {
return textTag.data;
},
span: function (spanTag) {
return tagHandlers._base(spanTag);
},
p: function (pTag) {
return tagHandlers._base(pTag) + '\n';
},
a: function (aTag) {
var href = aTag.attribs.href;
if (href === undefined) return '';
// extract real URLs from Google's tracking
// from: http://www.google.com/url?q=http%3A%2F%2Fwww.sfchronicle.com...
// to: http://www.sfchronicle.com...
if (aTag.attribs.href && url.parse(aTag.attribs.href, true).query && url.parse(aTag.attribs.href, true).query.q) {
href = url.parse(aTag.attribs.href, true).query.q;
}
var str = '<a href="' + href + '">';
str += tagHandlers._base(aTag);
str += '</a>';
return str;
},
li: function (tag) {
return '* ' + tagHandlers._base(tag) + '\n';
}
};
['ul', 'ol'].forEach(function (tag) {
tagHandlers[tag] = tagHandlers.span;
});
['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].forEach(function (tag) {
tagHandlers[tag] = tagHandlers.p;
});
var body = dom[0].children[1];
var parsedText = tagHandlers._base(body);
// Convert html entities into the characters as they exist in the google doc
var entities = new Entities();
parsedText = entities.decode(parsedText);
// Remove smart quotes from inside tags
parsedText = parsedText.replace(/<[^<>]*>/g, function (match) {
return match.replace(/”|“/g, '"').replace(/‘|’/g, "'");
});
var parsed = archieml.load(parsedText);
gDrive.files.get({ fileId:options.docsID}, function (err, doc) {
var doc_title = doc.name;
grunt.file.write(options.dest + '/' + lowerCase(doc_title) + '.json', JSON.stringify(parsed, null, 2));
});
});
var parser = new htmlparser.Parser(handler);
parser.write(docHtml);
parser.done();
grunt.log.ok();
});
});
}; |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S9.6_A2.2;
* @section: 9.6, 11.7.3;
* @assertion: Compute result modulo 2^32;
* @description: Use operator >>>0;
*/
// CHECK#1
if ((-2147483647 >>> 0) !== 2147483649) {
$ERROR('#1: (-2147483647 >>> 0) === 2147483649. Actual: ' + ((-2147483647 >>> 0)));
}
// CHECK#2
if ((-2147483648 >>> 0) !== 2147483648) {
$ERROR('#2: (-2147483648 >>> 0) === 2147483648. Actual: ' + ((-2147483648 >>> 0)));
}
// CHECK#3
if ((-2147483649 >>> 0) !== 2147483647) {
$ERROR('#3: (-2147483649 >>> 0) === 2147483647. Actual: ' + ((-2147483649 >>> 0)));
}
// CHECK#4
if ((-4294967295 >>> 0) !== 1) {
$ERROR('#4: (-4294967295 >>> 0) === 1. Actual: ' + ((-4294967295 >>> 0)));
}
// CHECK#5
if ((-4294967296 >>> 0) !== -0) {
$ERROR('#5: (-4294967296 >>> 0) === 0. Actual: ' + ((-4294967296 >>> 0)));
}
// CHECK#6
if ((-4294967297 >>> 0) !== 4294967295) {
$ERROR('#6: (-4294967297 >>> 0) === 4294967295. Actual: ' + ((-4294967297 >>> 0)));
}
// CHECK#7
if ((4294967295 >>> 0) !== 4294967295) {
$ERROR('#7: (4294967295 >>> 0) === 4294967295. Actual: ' + ((4294967295 >>> 0)));
}
// CHECK#8
if ((4294967296 >>> 0) !== 0) {
$ERROR('#8: (4294967296 >>> 0) === 0. Actual: ' + ((4294967296 >>> 0)));
}
// CHECK#9
if ((4294967297 >>> 0) !== 1) {
$ERROR('#9: (4294967297 >>> 0) === 1. Actual: ' + ((4294967297 >>> 0)));
}
// CHECK#10
if ((8589934591 >>> 0) !== 4294967295) {
$ERROR('#10: (8589934591 >>> 0) === 4294967295. Actual: ' + ((8589934591 >>> 0)));
}
// CHECK#11
if ((8589934592 >>> 0) !== 0) {
$ERROR('#11: (8589934592 >>> 0) === 0. Actual: ' + ((8589934592 >>> 0)));
}
// CHECK#12
if ((8589934593 >>> 0) !== 1) {
$ERROR('#12: (8589934593 >>> 0) === 1. Actual: ' + ((8589934593 >>> 0)));
}
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
crypto = require('crypto'),
validator = require('validator'),
generatePassword = require('generate-password'),
owasp = require('owasp-password-strength-test');
/**
* A Validation function for local strategy properties
*/
var validateLocalStrategyProperty = function (property) {
return ((this.provider !== 'local' && !this.updated) || property.length);
};
/**
* A Validation function for local strategy email
*/
var validateLocalStrategyEmail = function (email) {
return ((this.provider !== 'local' && !this.updated) || validator.isEmail(email));
};
/**
* User Schema
*/
var UserSchema = new Schema({
firstName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your first name']
},
lastName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your last name']
},
displayName: {
type: String,
trim: true
},
email: {
type: String,
unique: 'Email already exists',
lowercase: true,
trim: true,
default: '',
validate: [validateLocalStrategyEmail, 'Please fill a valid email address']
},
username: {
type: String,
unique: 'Username already exists',
required: 'Please fill in a username',
lowercase: true,
trim: true
},
password: {
type: String,
default: ''
},
salt: {
type: String
},
profileImageURL: {
type: String,
default: 'modules/users/client/img/profile/default.png'
},
provider: {
type: String,
required: 'Provider is required'
},
providerData: {},
additionalProvidersData: {},
roles: {
type: [{
type: String,
enum: ['user', 'admin']
}],
default: ['user'],
required: 'Please provide at least one role'
},
updated: {
type: Date
},
created: {
type: Date,
default: Date.now
},
/* For reset password */
resetPasswordToken: {
type: String
},
resetPasswordExpires: {
type: Date
},
friends:[{
type:String
}],
activities:[{
type:String
}],
active: {
type: Boolean,
default: false
},
stage: {
type: Number,
default: 0
}
});
/**
* Hook a pre save method to hash the password
*/
UserSchema.pre('save', function (next) {
if (this.password && this.isModified('password')) {
this.salt = crypto.randomBytes(16).toString('base64');
this.password = this.hashPassword(this.password);
}
next();
});
/**
* Hook a pre validate method to test the local password
*/
UserSchema.pre('validate', function (next) {
if (this.provider === 'local' && this.password && this.isModified('password')) {
var result = owasp.test(this.password);
if (result.errors.length) {
var error = result.errors.join(' ');
this.invalidate('password', error);
}
}
next();
});
/**
* Create instance method for hashing a password
*/
UserSchema.methods.hashPassword = function (password) {
if (this.salt && password) {
return crypto.pbkdf2Sync(password, new Buffer(this.salt, 'base64'), 10000, 64).toString('base64');
} else {
return password;
}
};
/**
* Create instance method for authenticating user
*/
UserSchema.methods.authenticate = function (password) {
return this.password === this.hashPassword(password);
};
/**
* Find possible not used username
*/
UserSchema.statics.findUniqueUsername = function (username, suffix, callback) {
var _this = this;
var possibleUsername = username.toLowerCase() + (suffix || '');
_this.findOne({
username: possibleUsername
}, function (err, user) {
if (!err) {
if (!user) {
callback(possibleUsername);
} else {
return _this.findUniqueUsername(username, (suffix || 0) + 1, callback);
}
} else {
callback(null);
}
});
};
/**
* Generates a random passphrase that passes the owasp test.
* Returns a promise that resolves with the generated passphrase, or rejects with an error if something goes wrong.
* NOTE: Passphrases are only tested against the required owasp strength tests, and not the optional tests.
*/
UserSchema.statics.generateRandomPassphrase = function () {
return new Promise(function (resolve, reject) {
var password = '';
var repeatingCharacters = new RegExp('(.)\\1{2,}', 'g');
// iterate until the we have a valid passphrase.
// NOTE: Should rarely iterate more than once, but we need this to ensure no repeating characters are present.
while (password.length < 20 || repeatingCharacters.test(password)) {
// build the random password
password = generatePassword.generate({
length: Math.floor(Math.random() * (20)) + 20, // randomize length between 20 and 40 characters
numbers: true,
symbols: false,
uppercase: true,
excludeSimilarCharacters: true,
});
// check if we need to remove any repeating characters.
password = password.replace(repeatingCharacters, '');
}
// Send the rejection back if the passphrase fails to pass the strength test
if (owasp.test(password).errors.length) {
reject(new Error('An unexpected problem occured while generating the random passphrase'));
} else {
// resolve with the validated passphrase
resolve(password);
}
});
};
mongoose.model('User', UserSchema);
|
import Shape from './graph.shape.js';
/**
* Represents a line that extends the Shape class. Used by the plugin {@link PluginSerieLineDifference}
* @extends Shape
* @see Graph#newShape
*/
class ShapePolyline extends Shape {
constructor( graph, options ) {
super( graph, options );
}
/**
* Creates the DOM
* @private
* @return {Shape} The current shape
*/
createDom() {
this._dom = document.createElementNS( this.graph.ns, 'path' );
if ( !this.getStrokeColor() ) {
this.setStrokeColor( 'black' );
}
if ( this.getStrokeWidth() === undefined ) {
this.setStrokeWidth( 1 );
}
}
/**
* No handles for the polyline
* @private
* @return {Shape} The current shape
*/
createHandles() {}
/**
* Force the points of the polyline already computed in pixels
* @param {String} a SVG string to be used in the ```d``` attribute of the path.
* @return {ShapePolyline} The current polyline instance
*/
setPointsPx( points ) {
this.setProp( 'pxPoints', points );
return this;
}
/**
* Recalculates the positions and applies them
* @private
* @return {Boolean} Whether the shape should be redrawn
*/
applyPosition() {
let str = '';
let index = 0;
while ( true ) {
let pos = this.getPosition( index );
if ( pos === undefined ) {
break;
}
let posXY;
if ( this.serie ) {
posXY = pos.compute( this.graph, this.serie.getXAxis(), this.serie.getYAxis(), this.serie );
} else {
posXY = pos.compute( this.graph, this.getXAxis(), this.getYAxis() );
}
if ( isNaN( posXY.x ) || isNaN( posXY.y ) ) {
return;
}
if ( index == 0 ) {
str += ' M ';
} else {
str += ' L ';
}
str += `${posXY.x} ${posXY.y}`;
index++;
}
str += 'z';
this.setDom( 'd', str );
this.changed();
return true;
}
}
export default ShapePolyline; |
/*
The MIT License (MIT)
Copyright (c) 2013 Bryan Hughes <bryan@theoreticalideations.com> (http://theoreticalideations.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
'use commascript';
var w = '',
x = true,
y = 10,
z = 20;
w = x ? y : z;
|
"use strict";
let AWS = require('aws-sdk');
let SNSService = require("./snsService");
let Util = require("../util");
let SQSService = function (region) {
AWS.config.update({region: region});
this.SQS = new AWS.SQS();
this.snsService = new SNSService(region);
};
SQSService.prototype.getQueueUrl = function (queueName) {
Util.log("INFO", "Getting queue url");
return new Promise((resolve, reject) => {
let self = this;
let params = {QueueName: queueName};
self.SQS.getQueueUrl(params, function (err, data) {
if (err || !data.QueueUrl) {
Util.log("WARN", "Failed to locate queue " + queueName, err);
self.SQS.createQueue(params, function (err, data) {
if (err) {
Util.log("ERROR", "Failed to create queue " + params.QueueName, err);
return reject(err);
} else {
Util.log("INFO", "Successfully created queue", data);
return resolve(data);
}
});
} else {
Util.log("INFO", "Successfully retrieved queue url", data);
return resolve(data);
}
});
});
};
SQSService.prototype.processMessages = function (queueName, maxNumberOfMessagesToRead, readConfigFromMessage, sqsConfig) {
Util.log("INFO", "Processing messages");
if (!queueName) {
Util.log("ERROR", "QueueName is empty");
return Promise.reject({message: "QueueName is empty"});
}
if (readConfigFromMessage === false) {
if (!sqsConfig) {
Util.log("ERROR", "SQS Config is invalid");
return Promise.reject({message: "SQS Config is invalid"});
}
if (!sqsConfig.triggerTopicName) {
Util.log("ERROR", "triggerTopicName missing from SQSConfig");
return Promise.reject({message: "triggerTopicName missing from SQSConfig"});
}
if (!sqsConfig.failureTopicName) {
Util.log("ERROR", "failureTopicName missing from SQSConfig");
return Promise.reject({message: "failureTopicName missing from SQSConfig"});
}
if (!sqsConfig.maxRetryAttempts) {
sqsConfig.maxRetryAttempts = 1;
}
}
return this.getQueueUrl(queueName)
.then(response => {
return this.readMessage(response.QueueUrl, maxNumberOfMessagesToRead);
})
.then(response => {
if (response && response.Messages) {
let queueUrl = response.QueueUrl;
let messagesProcessed = response.Messages.length;
let hasPoisonMessage = false;
let sendAndDeleteMessage = response.Messages.map(message => {
let parsedMessage = Util.tryParseJSON(message.Body);
if (parsedMessage) {
let parsedMessageContent = Util.tryParseJSON(parsedMessage.Message);
if (parsedMessageContent) {
let asrConfig = readConfigFromMessage ? Util.tryParseJSON(parsedMessageContent.asrConfig) : sqsConfig;
let isValidASRConfig = Util.validateASRConfig(asrConfig, "SQS");
if (isValidASRConfig) {
let retryCount = parsedMessageContent.retryCount || parsedMessageContent.retrycount;
let destinationTopicName = retryCount > asrConfig.maxRetryAttempts ? asrConfig.failureTopicName : asrConfig.triggerTopicName;
delete parsedMessageContent.asrConfig;
return this.snsService.sendToTopic(destinationTopicName, parsedMessageContent)
.then(response => {
return this.deleteMessage(queueUrl, message.ReceiptHandle);
});
} else {
hasPoisonMessage = true;
Util.log("ERROR", "ASRConfig not valid. Message cannot be deleted from Queue", asrConfig);
return Promise.resolve({message: "ASRConfig not valid. Message cannot be deleted from Queue."});
}
} else {
hasPoisonMessage = true;
Util.log("ERROR", "Message content is not a valid JSON and cannot be deleted from Queue", parsedMessage.Message);
return Promise.resolve({message: "Message is not a valid JSON and cannot be deleted from Queue"});
}
} else {
hasPoisonMessage = true;
Util.log("ERROR", "Message is not a valid JSON and cannot be deleted from Queue", message.Body);
return Promise.resolve({message: "Message is not a valid JSON and cannot be deleted from Queue"});
}
});
return Promise.all(sendAndDeleteMessage)
.then(responses => {
Util.log("INFO", "Successfully processed all messages");
let response = {
responses: responses,
messagesProcessed: messagesProcessed,
hasPoisonMessage: hasPoisonMessage
};
return Promise.resolve(response);
})
.catch(err => {
Util.log("WARN", "Failed to process all messages", err);
return Promise.reject(err);
});
} else {
Util.log("INFO", "No messages to process");
let response = {
message: "No messages to process",
messagesProcessed: 0,
hasPoisonMessage: false
};
return Promise.resolve(response);
}
})
.catch(err => {
return Promise.reject(err);
});
};
SQSService.prototype.readMessage = function (queueUrl, maxNumberOfMessagesToRead) {
Util.log("INFO", "Reading messages");
return new Promise((resolve, reject) => {
let params = {
QueueUrl: queueUrl,
MaxNumberOfMessages: maxNumberOfMessagesToRead || 10
};
this.SQS.receiveMessage(params, function (err, data) {
if (err) {
Util.log("ERROR", "Failed to receive message");
return reject(err);
} else {
let messageCount = data.Messages ? data.Messages.length : 0;
Util.log("INFO", "Successfully received message " + queueUrl + ": " + messageCount);
data.QueueUrl = queueUrl;
return resolve(data);
}
});
});
};
SQSService.prototype.deleteMessage = function (queueUrl, receiptHandle) {
Util.log("INFO", "Deleting message");
return new Promise((resolve, reject) => {
let params = {
ReceiptHandle: receiptHandle,
QueueUrl: queueUrl
};
this.SQS.deleteMessage(params, function (err, data) {
if (err) {
Util.log("ERROR", "Failed to delete message", err);
return reject(err);
}
Util.log("INFO", "Successfully deleted message from queue " + queueUrl, data);
return resolve(data);
});
});
};
module.exports = SQSService; |
import { render, setLocals, created, deleted, updated } from './helpers';
export class UsersController {
constructor(userRepo) {
this.userRepo = userRepo;
}
showList(req, res, next) {
this.userRepo.getAll()
.then(users => setLocals(res, { users }))
.then(() => render(res, 'userList'))
.catch(next);
}
addNew(req, res, next) {
const name = req.body.userName;
this.userRepo.addDrinkType(name)
.then(id => created(res, `/users/${id}/`))
.catch(next);
}
deleteSingle(req, res, next) {
const id = req.params.userId;
this.userRepo.deleteById(id)
.then(() => deleted(res, '/users'))
.catch(next);
}
changeAdminStatus(req, res, next) {
console.log(req.body);
const newIsAdmin = req.body.setAdmin === 'true';
console.log(req.body.setAdmin, newIsAdmin);
const id = req.params.userId;
this.userRepo.setAdminStatusById(id, newIsAdmin)
.then(() => updated(res, `/users/${id}/`))
.catch(next);
}
}
|
// -----------------------------------------------------------------------------
// ACCORDION
// -----------------------------------------------------------------------------
const KEYBOARD = window.Muilessium.KEYBOARD;
const FACTORY = window.Muilessium.FACTORY;
const _ = window.Muilessium.UTILS;
export default class Accordion extends FACTORY.BaseComponent {
constructor(element, options) {
super(element, options);
this.domCache = _.extend(this.domCache, {
items: element.querySelectorAll('.item'),
titles: element.querySelectorAll('.title'),
indicators: element.querySelectorAll('.indicator'),
contents: element.querySelectorAll('.content')
});
this.state = _.extend(this.state, {
isExpanded: []
});
_.forEach(this.domCache.items, (item, index) => {
this.state.isExpanded[index] = false;
});
this.initAria();
this.initControls();
}
initAria() {
_.aria.setRole(this.domCache.element, 'tablist');
_.setAttribute(this.domCache.element, 'multiselectable', true);
_.forEach(this.domCache.titles, (title, index) => {
_.aria.setRole(title, 'tab');
_.aria.set(title, 'expanded', false);
_.aria.set(title, 'controls', _.aria.setId(this.domCache.contents[index]));
});
_.forEach(this.domCache.contents, (content, index) => {
_.aria.setRole(content, 'tabpanel');
_.aria.set(content, 'hidden', true);
_.aria.set(content, 'labelledby', _.aria.setId(this.domCache.titles[index]));
});
_.forEach(this.domCache.indicators, (indicator) => {
_.aria.set(indicator, 'hidden', true);
});
return this;
}
initControls() {
_.makeChildElementsClickable(this.domCache.element, this.domCache.titles, (index) => {
this.toggleItem(index);
});
_.forEach(this.domCache.titles, (title, index) => {
KEYBOARD.onSpacePressed(title, this.toggleItem.bind(this, index));
if (title !== _.firstOfList(this.domCache.titles)) {
KEYBOARD.onArrowUpPressed(title, () => {
this.domCache.titles[index - 1].focus();
});
}
if (title !== _.lastOfList(this.domCache.titles)) {
KEYBOARD.onArrowDownPressed(title, () => {
this.domCache.titles[index + 1].focus();
});
}
});
return this;
}
restoreState() {
if (!this.savedStates.isEmpty()) {
const oldState = JSON.parse(this.savedStates.pop());
_.forEach(oldState.isExpanded, (isExpanded, index) => {
if (isExpanded) {
this.unfoldItem(index);
} else {
this.foldItem(index);
}
});
}
return this;
}
foldItem(index) {
_.removeClass(this.domCache.items[index], '-unfold');
_.aria.set(this.domCache.titles[index], 'expanded', false);
_.aria.set(this.domCache.contents[index], 'hidden', true);
this.state.isExpanded[index] = false;
return this;
}
foldAllItems() {
_.forEach(this.domCache.items, (item, index) => {
this.foldItem(index);
});
return this;
}
unfoldItem(index) {
_.addClass(this.domCache.items[index], '-unfold');
_.aria.set(this.domCache.titles[index], 'expanded', true);
_.aria.set(this.domCache.contents[index], 'hidden', false);
this.state.isExpanded[index] = true;
return this;
}
unfoldAllItems() {
_.forEach(this.domCache.items, (item, index) => {
this.unfoldItem(index);
});
return this;
}
toggleItem(index) {
_.toggleClass(this.domCache.items[index], '-unfold');
_.aria.toggleState(this.domCache.titles[index], 'expanded');
_.aria.toggleState(this.domCache.contents[index], 'hidden');
this.state.isExpanded[index] = !this.state.isExpanded[index];
return this;
}
}
|
'use strict';
/*!
*
* Copyright(c) 2011 Vladimir Dronnikov <dronnikov@gmail.com>
* MIT Licensed
*
*/
/**
* Listen to specified URL and respond with status 200
* to signify this server is alive
*
* Use to notify upstream haproxy load-balancer
*/
module.exports = function setup(url) {
if (!url) url = '/haproxy?monitor';
return function handler(req, res, next) {
if (req.url === url) {
res.writeHead(200);
res.end();
} else {
next();
}
};
};
|
'use strict'
import { APP } from '../constant'
/**
* Switch tab
*/
const changeTab = (tab) => {
return (dispatch) => {
return Promise.resolve(dispatch({
type: APP.TAB,
data: tab
}))
}
}
/**
* Navigation, now only used for gamelist to gamedetail
* when enter game detail, game list should stop requesting data continuously
*/
const toNavigation = targetComponent => {
return dispatch => {
return Promise.resolve(dispatch({
type: APP.NAVIGATION,
data: targetComponent
}))
}
}
export default {
changeTab,
toNavigation
}
|
function make_slides(f) {
var slides = {};
slides.i0 = slide({
name : "i0",
start: function() {
exp.startT = Date.now();
}
});
slides.instructions = slide({
name : "instructions",
start: function() {
$(".err").hide();
$("#total-num").html(exp.nTrials);
},
button : function() {
exp.go();
}
});
slides.main_task = slide({
name: "main_task",
present : exp.stims,
//this gets run only at the beginning of the block
present_handle : function(stim) {
var prompt, utt;
// hide prior question and prior dependent measure
$(".question0").hide();
$("#slider_table0").hide();
$("#prior_number").hide();
// hide listener/speaker question
$(".question2").hide();
$(".task_prompt").hide();
// hide listener task dependent measure
$("#listener_number").hide();
$("#slider_table2").hide();
// hide speaker task dependent measure
$("#speaker_choices").hide();
// "uncheck" radio buttons
$('input[name="speaker"]').prop('checked', false);
// hide error message
$(".err").hide();
// show "data"
$(".data").show();
// get index number of trial
this.trialNum = exp.stimscopy.indexOf(stim);
// record trial start time
this.startTime = Date.now();
// replace CATEGORY, EXEMPLAR, TREATMENT, PAST from stimuli
var story = replaceTerms(stim, "storyline")
// display story
$(".data").html("You are on planet " + stim.planet +
". " + story + " " +
replaceTerms(_.extend(stim, {preamble}), "preamble"));
// which "experiment" is not yet finished?
this.missing = _.sample([1,2,3,4,5,6,7,8,9]);
this.experimentNames = ["A","B","C","D","E","F","G","H","I","J","K"];
stim.data.splice(this.missing, 0, "?");
for (var i=0; i<=stim.data.length; i++){
$("#h" + i).html(stim.treatment + " " + this.experimentNames[i])
$("#h" + i).css({"font-size":"13px", "border":"1px dotted black"})
$("#d" + i).css({"padding":"10px", "font-weight":"bold", "border":"1px solid black"});
$("#d" + i).html(stim.data[i]);
$("#d" + i + "a").html("100")
$("#d" + i + "a").css({"border":"1px dotted black"});
};
$("#d-1").css({"border":"1px solid black","font-size":"14px", "font-weight":"bold", "width":"20%"});
$("#d-1").html(stim.unit + " " + stim.past);
$("#d-1a").css({"border":"1px dotted black"});
stim.targetTreatment = stim.treatment+ " " + this.experimentNames[this.missing]
if (exp.condition == "prior"){
utils.make_slider("#single_slider0", this.make_slider_callback(0))
$(".question0").html("The experiment using "+ stim.targetTreatment + " is not finished yet.<br>When it finishes, how many of the attempted 100 "+stim.unit + " will be successfully " + stim.past + "?");
$(".question0").show();
$("#slider_table0").show();
$("#prior_number").html("---");
$("#prior_number").show();
} else if (exp.condition == "speaker") {
utils.make_slider("#single_slider1", this.make_slider_callback(1))
$(".question2").html(replaceTerms(stim, "prompt"));
$(".task_prompt").show();
$(".question2").show();
prompt = replaceTerms(stim, "prompt");
prompt += "<br>" + replaceTerms(stim, "frequencyStatement") + " <strong>" +
stim.frequency + "</strong>"
utt = 'Your colleague asks you: <strong>"' + replaceTerms(stim, "question")+ '"</strong>';
$("#speaker_choices").show();
$(".task_prompt").html(prompt);
$(".question2").html(utt);
} else if (exp.condition == "listener") {
$(".question2").html(replaceTerms(stim, "prompt"));
$(".task_prompt").show();
$(".question2").show();
utils.make_slider("#single_slider2", this.make_slider_callback(2))
prompt = replaceTerms(stim, "prompt");
utt = 'Your colleague tells you: <strong>"' + jsUcfirst(replaceTerms(stim, "utterance")) + '"</strong><br>' + replaceTerms(stim, "question");
$("#listener_number").html("---");
$("#listener_number").show();
$("#slider_table2").show();
$(".task_prompt").html(prompt);
$(".question2").html(utt);
}
exp.sliderPost = -1;
this.stim = stim;
},
init_sliders : function(i) {
utils.make_slider("#single_slider" + i, this.make_slider_callback(i));
},
make_slider_callback : function(i) {
return function(event, ui) {
exp.sliderPost = ui.value;
(i==0) ? $("#prior_number").html(Math.round(exp.sliderPost*100)+"") :
(i==2) ? $("#listener_number").html(Math.round(exp.sliderPost*100)+"") : null
};
},
button : function() {
var speakerResponse = $('input[name="speaker"]:checked').val();
var prompt, utt;
console.log(speakerResponse)
var error = 0;
if (exp.condition == "speaker") {
if (!speakerResponse) {
error = 1;
}
} else {
if (exp.sliderPost==-1) {
error = 1;
}
}
if (error == 1) {
$(".err").show();
} else {
this.rt = Date.now() - this.startTime;
this.log_responses();
_stream.apply(this);
}
},
log_responses : function() {
if (exp.condition == "speaker") {
var response = $('input[name="speaker"]:checked').val() == "Yes" ? 1 : 0;
} else {
var response = exp.sliderPost
}
exp.data_trials.push({
"trial_type" : "prior_and_posterior",
"condition": exp.condition,
"trial_num": this.trialNum,
"response" : response,
"rt":this.rt,
"frequency": this.stim.frequency,
"category": this.stim.category,
"story": this.stim.story,
"distribution": this.stim.distribution,
"treatment":this.stim.treatment,
"unit":this.stim.unit,
"target":this.stim.target,
"planet": this.stim.planet,
"query": this.stim.query,
"missing":this.missing
});
}
});
slides.subj_info = slide({
name : "subj_info",
submit : function(e){
exp.subj_data = {
language : $("#language").val(),
enjoyment : $("#enjoyment").val(),
asses : $('input[name="assess"]:checked').val(),
age : $("#age").val(),
gender : $("#gender").val(),
education : $("#education").val(),
problems: $("#problems").val(),
fairprice: $("#fairprice").val(),
comments : $("#comments").val()
};
exp.go(); //use exp.go() if and only if there is no "present" data.
}
});
slides.thanks = slide({
name : "thanks",
start : function() {
exp.data= {
"trials" : exp.data_trials,
"catch_trials" : exp.catch_trials,
"system" : exp.system,
"condition" : exp.condition,
"subject_information" : exp.subj_data,
"time_in_minutes" : (Date.now() - exp.startT)/60000
};
setTimeout(function() {turk.submit(exp.data);}, 1000);
}
});
return slides;
}
/// init ///
function init() {
repeatWorker = false;
(function(){
var ut_id = "mht-causals-20170222";
if (UTWorkerLimitReached(ut_id)) {
$('.slide').empty();
repeatWorker = true;
alert("You have already completed the maximum number of HITs allowed by this requester. Please click 'Return HIT' to avoid any impact on your approval rating.");
}
})();
exp.trials = [];
exp.catch_trials = [];
exp.condition = _.sample(["prior","speaker","speaker","speaker","speaker","listener"])
// exp.condition = "speaker"
exp.nTrials = stories.length;
exp.stims = [];
var shuffledDists = _.shuffle(distributions);
var frequencies = _.shuffle(tasks.speaker.frequencies);
var labels = _.shuffle(creatureNames);
var planets = _.shuffle(["X137","A325","Z142","Q681"])
for (var i=0; i<stories.length; i++) {
var f;
if (exp.condition == "speaker"){
f = {
frequency: frequencies[i],
category: labels[i].category,
exemplar: labels[i].exemplar,
prompt: tasks.speaker.prompt,
utterance: tasks.speaker.utterance,
question: tasks.speaker.question,
frequencyStatement: tasks.speaker.frequencyStatement,
planet: planets[i]
};
} else {
f = {
category: labels[i].category,
exemplar: labels[i].exemplar,
prompt: tasks.listener.prompt,
utterance: tasks.listener.utterance,
question: tasks.listener.question,
planet: planets[i]
}
}
exp.stims.push(
_.extend(stories[i], shuffledDists[i], f)
)
};
exp.stims = _.shuffle(exp.stims);
exp.stimscopy = exp.stims.slice(0);
exp.system = {
Browser : BrowserDetect.browser,
OS : BrowserDetect.OS,
screenH: screen.height,
screenUH: exp.height,
screenW: screen.width,
screenUW: exp.width
};
//blocks of the experiment:
exp.structure=[
"i0",
"instructions",
"main_task",
"subj_info",
"thanks"
];
exp.data_trials = [];
//make corresponding slides:
exp.slides = make_slides(exp);
exp.nQs = utils.get_exp_length(); //this does not work if there are stacks of stims (but does work for an experiment with this structure)
//relies on structure and slides being defined
$('.slide').hide(); //hide everything
//make sure turkers have accepted HIT (or you're not in mturk)
$("#start_button").click(function() {
if (turk.previewMode) {
$("#mustaccept").show();
} else {
$("#start_button").click(function() {$("#mustaccept").show();});
exp.go();
}
});
exp.go(); //show first slide
}
|
var request = require('request'),
fs = require('fs'),
path = require('path'),
merge = require('merge'),
Promise = require('bluebird'),
cheerio = require('cheerio'),
logger = require('./logger'),
ExtractMatch = require('./extractmatch');
function Crawler(opts) {
// defaults
this.opts = {
crawl : [],
cache : path.normalize(__dirname + '/../cache'),
timeout : 3000,
output : {
format : "json",
directory : path.normalize(__dirname + '/../output'),
}
};
if (typeof opts == "string") {
// Load from file
this.opts = merge(this.opts, JSON.parse(fs.readFileSync(opts, 'utf8')));
} else if (opts != undefined) {
this.opts = merge(this.opts, opts);
}
// other attributes
this._html = null;
this._indexed = [];
if (this.opts.cache) {
if (!fs.existsSync(path.normalize(this.opts.cache))) {
fs.mkdirSync(path.normalize(this.opts.cache));
}
}
if (this.opts.output) {
if (this.opts.output.format == "json") {
if (!fs.existsSync(path.normalize(this.opts.output.directory))) {
fs.mkdirSync(path.normalize(this.opts.output.directory));
}
} else if (this.opts.output.format == "database") {
throw new Error("Database output not implemented yet. Sorry :-(")
}
} else {
throw new Error("No output format specified.");
}
};
/**
* Convert URL into system path-friendly format
*/
Crawler.prototype.getCleanUrl = function(url) {
return url.replace(/[^a-zA-Z0-9 -]/g, '');
}
/**
* Writes raw data to file cache
*/
Crawler.prototype.writeCache = function(url, data) {
var _this = this;
return new Promise(function(resolve, reject) {
if (!_this.opts.cache) resolve();
var cleanUrl = _this.getCleanUrl(url);
fs.writeFile(path.normalize(_this.opts.cache + '/' + cleanUrl), data, function(err) {
if (!err) resolve();
else reject(err);
});
});
}
/**
* Writes scraped data to output
*/
Crawler.prototype.writeOutput = function(url, data) {
var _this = this;
var cleanUrl = _this.getCleanUrl(url);
if (_this.opts.output.format == "json") {
var filePath = path.normalize(_this.opts.output.directory + '/' + cleanUrl);
logger.debug("Writing output to " + filePath);
fs.writeFile(filePath, JSON.stringify(data), function(err) {
logger.debug("Done.");
});
} else {
// @todo -- database
}
}
/**
* Read contents of URL from local cachestore
*/
Crawler.prototype.readFromCache = function(url) {
var _this = this;
var filePath = path.normalize(_this.opts.cache + '/' + _this.getCleanUrl(url));
logger.debug("Checking cache: " + filePath);
return new Promise(function(resolve, reject) {
fs.readFile(filePath, function(err, data) {
if (!err) resolve(data);
else reject(err);
});
});
}
/**
* Retrieve HTML from the specified URL
*/
Crawler.prototype.download = function(url) {
var _this = this;
_this._indexed.push(url);
return new Promise(function(resolve, reject) {
var doRequest = function(url) {
request({
url : url,
timeout: _this.opts.timeout
}, function(err, resp, body) {
if (!err && resp.statusCode == 200) {
logger.debug("Content found for " + url);
resolve(body);
} else if (!err && resp.statusCode != 200) {
reject("STATUS " + resp.statusCode + " for " + url);
} else {
reject(err);
}
});
}
if (_this.opts.cache) {
var html = _this.readFromCache(url).then(function(html) {
logger.debug("Data read from cache: " + url);
resolve(html);
}).catch(function(err) {
logger.debug("Failed to read from cache: " + err.message);
doRequest(url);
});
} else {
doRequest(url);
}
});
};
/**
* Begin crawling based on the complete configuration file
*/
Crawler.prototype.start = function() {
var _this = this;
var complete = 0;
return new Promise(function(resolve, reject) {
function checkComplete() {
if (complete == _this.opts.start.length) resolve();
}
for(var i = 0; i < _this.opts.start.length; i++) {
var rootUrl = _this.getRootUrl(_this.opts.start[i]);
_this.crawl(rootUrl, _this.opts.start[i], 0).then(function() {
complete++;
checkComplete();
}).catch(function(err) {
complete++;
checkComplete();
});
}
});
}
/**
* Check if URL has already been indexed
*/
Crawler.prototype.hasIndexed = function(url) {
var _this = this;
if (_this._indexed.indexOf(url) != -1) return true;
return false;
}
/**
* Convert a URL into absolute format
*/
Crawler.prototype.getAbsoluteUrl = function(rootUrl, url) {
var _this = this;
var isAbsolute = _this.isAbsoluteUrl(url);
if (!isAbsolute) {
url = rootUrl + url;
}
return url;
}
/**
* Retrieve root URL path (i.e. http://foo.com/bar ==> http://foo.com)
*/
Crawler.prototype.isAbsoluteUrl = function(url) {
return /^http/.test(url);s
}
/**
* Retrieve root URL path (i.e. http://foo.com/bar ==> http://foo.com)
*/
Crawler.prototype.getRootUrl = function(url) {
var _this = this;
var arr = url.split("/");
var url = arr[0] + "//" + arr[2];
return url;
}
/**
* Scrape all content according to config
*/
Crawler.prototype.scrape = function(url, html) {
var _this = this;
logger.debug("Scraping " + url);
return new Promise(function(resolve, reject) {
_this.writeCache(url, html).then(function() {
_this.loadHtml(html);
var scraped = {};
for(var i = 0; i < _this.opts.extract.length; i++) {
_this.scrapeElement(_this.opts.extract[i], cheerio(html), scraped, null);
}
resolve(scraped);
}).catch(function(err) {
reject(err);
});
});
}
/**
* Recurive method to scrape contents of a single element based on the config
*/
Crawler.prototype.scrapeElement = function(config, el, scraped, parent) {
var _this = this;
var matches = _this.findElements(config.match, el);
for(var i = 0; i < matches.length; i++) {
var nextMatch = matches[i];
var iterate = null;
if (config.type == "array") {
iterate = scraped[config.name] = [];
} else if (config.children) {
if (parent && parent.type == "array") {
var iterate = {};
scraped.push(iterate);
} else {
iterate = scraped[config.name] = {};
}
} else {
scraped[config.name] = cheerio(nextMatch).text();
iterate = scraped;
}
if (config.children) {
for(var j = 0; j < config.children.length; j++) {
_this.scrapeElement(config.children[j], nextMatch, iterate, config);
}
}
}
return scraped;
}
/**
* Recursive function to download a page, index it, find the URLs, and crawl them.
*/
Crawler.prototype.crawl = function(rootUrl, url, depth) {
var _this = this;
depth = depth || 0;
var newRootUrl = rootUrl;
// if URL is relative, use the root provided
// otherwise set the new root for future crawls
if (_this.isAbsoluteUrl(url)) {
newRootUrl = _this.getRootUrl(url);
}
var absoluteUrl = _this.getAbsoluteUrl(newRootUrl, url);
logger.debug("Crawling %s at a depth of %d", absoluteUrl, depth);
return new Promise(function(resolve, reject) {
_this.download(absoluteUrl).then(function(resp) {
// scrape data
_this.scrape(absoluteUrl, resp).then(function(data) {
logger.debug("Scraped " + url);
_this.writeOutput(absoluteUrl, data);
}).catch(function(err) {
logger.error(err);
})
if (depth >= _this.opts.maxDepth) return resolve();
// craw URLs on this page
var urls = _this.findUrls(resp);
var complete = 0;
function checkComplete() {
if (complete == urls.length) {
resolve();
}
}
if (urls.length == 0) {
resolve();
return;
}
logger.info("Found " + urls.length + " urls to crawl.");
for(var i = 0; i < urls.length; i++) {
if (_this.hasIndexed(urls[i])) {
complete++;
continue;
}
_this._indexed.push(urls[i]);
_this.crawl(newRootUrl, urls[i], depth + 1).then(function() {
complete++;
checkComplete();
}).catch(function(err) {
complete++;
checkComplete();
});
}
}).catch(function(err) {
reject(err);
})
});
}
/**
* Scrape HTML and find all matching elements using jQuery specifier
*/
Crawler.prototype.findElements = function(specifier, root) {
if (root == undefined) root = this._html.root();
return cheerio(root).find(specifier);
};
/**
* Scrape HTML and find all matching URLs
*/
Crawler.prototype.findUrls = function(html) {
var matches = [];
for(var i = 0; i < this.opts.crawl.length; i++) {
var regexp = new RegExp(this.opts.crawl[i], 'gm');
var m = html.toString().match(regexp);
if (m) matches = matches.concat(m);
}
// return unique items
return matches.filter(function(item, pos) {
return matches.indexOf(item) == pos;
});
};
/**
* Loads HTML content into crawler for parsing
*/
Crawler.prototype.loadHtml = function(html) {
this._html = cheerio.load(html);
}
module.exports = Crawler; |
import { StyleSheet } from 'react-native';
export default StyleSheet.create({
mainBtn: {
backgroundColor: '#FF9800',
marginBottom: 10,
},
logoutBtn: {
backgroundColor: '#F44336',
marginBottom: 10,
}
});
|
angular.module("myApp")
.filter("to_trusted", ["$sce", function($sce){
return function(text){
return $sce.trustAsHtml(text);
};
}]);
|
var retab = require('../');
describe('retab', function () {
it('should expose a function', function () {
retab.should.be.a.function;
});
it('should throw an error if no file is passed', function () {
(function () {
retab();
}).should.throw('You must specify a file or files.');
});
it('should throw an error for invalid tab size', function () {
(function () {
retab('test.js');
}).should.throw('You must specify a valid tab size.');
});
});
|
import React, { PropTypes } from 'react';
// Import Components
import FoundListItem from './FoundListItem/FoundListItem';
function FoundList(props) {
return (
<div className="listView">
{
props.founds.map(found => (
<FoundListItem
found={found}
key={found.cuid}
onDelete={() => props.handleDeleteFound(found.cuid)}
/>
))
}
</div>
);
}
FoundList.propTypes = {
founds: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
content: PropTypes.string.isRequired,
slug: PropTypes.string.isRequired,
cuid: PropTypes.string.isRequired,
})).isRequired,
handleDeleteFound: PropTypes.func.isRequired,
};
export default FoundList;
|
define(function (require) {
"use strict";
var $ = require('jquery'),
_ = require('underscore'),
Backbone = require('backbone'),
templates = require('text!templates/Home.html'),
template = _.template(templates);
return Backbone.View.extend({
render: function () {
this.$el.html(template());
return this;
}
});
}); |
module.exports={
"entry":[
'./public/app/main.js'
],
"output":{
path:__dirname,
filename:"./public/js/app.js"
},
"module":{
"loaders":[
{
test:/\.jsx?$/,
loader:'babel',
exclude:/node_modules/
},
],
}
} |
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './LeftControl.css';
import cx from 'classnames';
import Link from '../Link';
import Subscribe from '../Subscribe';
class LeftControl extends React.Component {
constructor(props) {
super(props);
this.state = {
authors: false,
similar: false,
leftMenu: false
};
this.toggleAuthors = this.toggleAuthors.bind(this);
this.toggleSimilar = this.toggleSimilar.bind(this);
this.scrollUp = this.scrollUp.bind(this);
this.handleScroll = this.handleScroll.bind(this);
}
scrollUp() {
window.scrollTo(0, 0);
}
toggleAuthors(e) {
this.setState({
authors: !this.state.authors
});
e.preventDefault();
}
toggleSimilar(e) {
this.setState({
similar: !this.state.similar
});
e.preventDefault();
}
componentWillUpdate() {
this.state.authors = false;
this.state.similar = false;
}
checkAuthors(data) {
if (data && data.authors && data.authors.length > 0) {
let popular = data.authors.slice(0,5);
function calcArticles(a, b) {
if (a.article_count > b.article_count) return -1;
if (a.article_count < b.article_count) return 1;
}
return popular.sort(calcArticles);
} else {
return false;
}
}
checkSimilar(data) {
if (data && data.similar && data.similarList && data.similarList.length > 0) {
let similar = data.similarList.slice(0,5);
function calcArticles(a, b) {
if (a.similarity > b.similarity) return -1;
if (a.similarity < b.similarity) return 1;
}
return similar.sort(calcArticles);
} else {
return false;
}
}
handleScroll(event) {
if (window.pageYOffset > 0) {
this.setState({
leftMenu: true
});
if (this.state.scrollPos < window.pageYOffset) {
this.setState({
leftMenu: false
});
} else {
this.setState({
leftMenu: true
});
}
} else {
this.setState({
leftMenu: false
});
}
this.setState({
scrollPos: window.pageYOffset
});
}
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
render() {
const
popular = this.checkAuthors(this.props.data),
similar = this.checkSimilar(this.props.data);
return (
<ul className={cx(s.root, s.leftControl, {[`${s.leftControlVis}`]: this.state.leftMenu})}>
<li className={cx(s.leftControlItem)}>
<button type="button" onClick={this.scrollUp} className={cx(s.leftControlLink, s.leftControlUp)}><i className={cx('fa', 'fa-arrow-up')} aria-hidden="true"></i></button>
</li>
<li className={cx(s.leftControlItem)}>
<a className={cx(s.leftControlLink)} href={this.props.data ? this.props.data.soc.telegram.value: false} target="_blank"><i className={cx('fa', 'fa-telegram')}></i></a>
</li>
<li className={cx(s.leftControlItem)}>
<a className={cx(s.leftControlLink)} href="http://spark-in.me/main.rss" target="_blank"><i className={cx('fa', 'fa-rss')} aria-hidden="true"></i></a>
</li>
<li className={cx(s.leftControlItem)}>
<a className={cx(s.leftControlLink)} href="https://tinyletter.com/snakers41" target="_blank"><i className={cx('fa', 'fa-envelope')} aria-hidden="true"></i></a>
</li>
<li className={cx(s.leftControlItem)}>
<button type="button" className={cx(s.leftControlLink)} onClick={this.toggleAuthors}><i className={cx('fa', 'fa-user')} aria-hidden="true"></i></button>
<ul className={cx(s.popularAuthors, {[`${s.popularAuthorsVis}`]: this.state.authors})}>
{popular ? popular.map((item) => {
return <li key={item.author_alias} className={cx(s.popularAuthorsItem)}>
<Link to={'/author/' + item.author_alias} className={cx(s.popularAuthorsLink)}>
<i className={cx('fa', 'fa-user')} aria-hidden="true"></i>
<span className={cx(s.popularAuthorsName)}>{item.author_alias}</span>
<span className={cx(s.popularAuthorsCount)}><i className={cx('fa', 'fa-file-text-o')} aria-hidden="true"></i>{item.article_count}</span>
</Link>
</li>}): false}
</ul>
</li>
{similar ? <li className={cx(s.leftControlItem)}>
<button type="button" className={cx(s.leftControlLink)} onClick={this.toggleSimilar}><i className={cx('fa', 'fa-file-text-o')} aria-hidden="true"></i></button>
<ul className={cx(s.popularAuthors, {[`${s.popularAuthorsVis}`]: this.state.similar})}>
{similar.map((item) => {
return <li key={item.article_id} className={cx(s.popularAuthorsItem)}>
<Link to={'/post/' + item.article_alias} className={cx(s.popularAuthorsLink)}>
<i className={cx('fa', 'fa-file-text-o')} aria-hidden="true"></i>
<span className={cx(s.popularAuthorsName, s.popularAuthorsNameSimilar)}>{item.article_title}</span>
</Link>
</li>
})}
</ul>
</li>: false}
</ul>
);
}
}
export default withStyles(s)(LeftControl);
|
'use strict';
const linz = require('../');
/* GET /logs/request/list */
var route = function (req, res, next) {
Promise.all([
linz.api.views.getScripts(req, res),
linz.api.views.getStyles(req, res),
])
.then(([scripts, styles]) => {
// update the requestLog data to work with HTML.
const logs = req.linz.requestLog.replace(/\n/g, '<br />');
return res.render(linz.api.views.viewPath('requestLog.jade'), {
logs,
scripts,
styles,
});
})
.catch(next);
};
module.exports = route;
|
angular.module('myApp.components.people', ['myApp.people.list',
'components.person.personService']);
|
DocsApp.Classes.Templates = function () {
function menuTpl(Plugin) {
return '<li class="cmp-plugin-entry">' +
'<a data-scroll-inter href="#' + Plugin.id + '">' + Plugin.name + '</a>' +
'<ul style="display:none" class=".nav">' +
'<li><a href="#' + Plugin.id + '-examples">Examples</a></li>' +
'<li><a href="#' + Plugin.id + '-usage">Usage</a></li>' +
'</ul>' +
'</li>';
}
return {
menuTpl : menuTpl
};
}
|
/**
* Created by jiangcheng.wxd on 14-5-28.
*/
//之一
function hasClass(ele, cls) {
return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
function addClass(ele, cls) {
if (!hasClass(ele, cls)) ele.className += " " + cls;
}
function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
ele.className = ele.className.replace(reg, '');
}
}
//之二.
Node.prototype.hasClass = function (className) {
if (this.classList) {
return this.classList.contains(className);
} else {
return (-1 < this.className.indexOf(className));
}
};
Node.prototype.addClass = function (className) {
if (this.classList) {
this.classList.add(className);
} else if (!this.hasClass(className)) {
var classes = this.className.split(" ");
classes.push(className);
this.className = classes.join(" ");
}
return this;
};
Node.prototype.removeClass = function (className) {
if (this.classList) {
this.classList.remove(className);
} else {
var classes = this.className.split(" ");
classes.splice(classes.indexOf(className), 1);
this.className = classes.join(" ");
}
return this;
};
//之三
var hasClass, addClass, removeClass;
if ( 'classList' in document.documentElement ) {
hasClass = function( elem, c ) {
return elem.classList.contains( c );
};
addClass = function( elem, c ) {
elem.classList.add( c );
};
removeClass = function( elem, c ) {
elem.classList.remove( c );
};
}
else {
hasClass = function( elem, c ) {
return classReg( c ).test( elem.className );
};
addClass = function( elem, c ) {
if ( !hasClass( elem, c ) ) {
elem.className = elem.className + ' ' + c;
}
};
removeClass = function( elem, c ) {
elem.className = elem.className.replace( classReg( c ), ' ' );
};
} |
import { moduleFor, ApplicationTest } from '../../utils/test-case';
import { strip } from '../../utils/abstract-test-case';
import { compile } from '../../utils/helpers';
import Controller from '@ember/controller';
import { RSVP } from '@ember/-internals/runtime';
import { Component } from '@ember/-internals/glimmer';
import Engine from '@ember/engine';
import { Route } from '@ember/-internals/routing';
import { next } from '@ember/runloop';
moduleFor(
'Application test: engine rendering',
class extends ApplicationTest {
get routerOptions() {
return {
location: 'none',
// This creates a handler function similar to what is in use by ember-engines
// internally. Specifically, it returns a promise when transitioning _into_
// the first engine route, but returns the synchronously available handler
// _after_ the engine has been resolved.
_getHandlerFunction() {
let syncHandler = this._super(...arguments);
this._enginePromises = Object.create(null);
this._resolvedEngines = Object.create(null);
return name => {
let engineInfo = this._engineInfoByRoute[name];
if (!engineInfo) {
return syncHandler(name);
}
let engineName = engineInfo.name;
if (this._resolvedEngines[engineName]) {
return syncHandler(name);
}
let enginePromise = this._enginePromises[engineName];
if (!enginePromise) {
enginePromise = new RSVP.Promise(resolve => {
setTimeout(() => {
this._resolvedEngines[engineName] = true;
resolve();
}, 1);
});
this._enginePromises[engineName] = enginePromise;
}
return enginePromise.then(() => syncHandler(name));
};
},
};
}
setupAppAndRoutableEngine(hooks = []) {
let self = this;
this.addTemplate('application', 'Application{{outlet}}');
this.router.map(function() {
this.mount('blog');
});
this.add('route-map:blog', function() {
this.route('post', function() {
this.route('comments');
this.route('likes');
});
this.route('category', { path: 'category/:id' });
this.route('author', { path: 'author/:id' });
});
this.add(
'route:application',
Route.extend({
model() {
hooks.push('application - application');
},
})
);
this.add(
'engine:blog',
Engine.extend({
init() {
this._super(...arguments);
this.register(
'controller:application',
Controller.extend({
queryParams: ['lang'],
lang: '',
})
);
this.register(
'controller:category',
Controller.extend({
queryParams: ['type'],
})
);
this.register(
'controller:authorKtrl',
Controller.extend({
queryParams: ['official'],
})
);
this.register('template:application', compile('Engine{{lang}}{{outlet}}'));
this.register(
'route:application',
Route.extend({
model() {
hooks.push('engine - application');
},
})
);
this.register(
'route:author',
Route.extend({
controllerName: 'authorKtrl',
})
);
if (self._additionalEngineRegistrations) {
self._additionalEngineRegistrations.call(this);
}
},
})
);
}
setupAppAndRoutelessEngine(hooks) {
this.setupRoutelessEngine(hooks);
this.add(
'engine:chat-engine',
Engine.extend({
init() {
this._super(...arguments);
this.register('template:application', compile('Engine'));
this.register(
'controller:application',
Controller.extend({
init() {
this._super(...arguments);
hooks.push('engine - application');
},
})
);
},
})
);
}
setupAppAndRoutableEngineWithPartial(hooks) {
this.addTemplate('application', 'Application{{outlet}}');
this.router.map(function() {
this.mount('blog');
});
this.add('route-map:blog', function() {});
this.add(
'route:application',
Route.extend({
model() {
hooks.push('application - application');
},
})
);
this.add(
'engine:blog',
Engine.extend({
init() {
this._super(...arguments);
this.register('template:foo', compile('foo partial'));
this.register('template:application', compile('Engine{{outlet}} {{partial "foo"}}'));
this.register(
'route:application',
Route.extend({
model() {
hooks.push('engine - application');
},
})
);
},
})
);
}
setupRoutelessEngine(hooks) {
this.addTemplate('application', 'Application{{mount "chat-engine"}}');
this.add(
'route:application',
Route.extend({
model() {
hooks.push('application - application');
},
})
);
}
setupAppAndRoutlessEngineWithPartial(hooks) {
this.setupRoutelessEngine(hooks);
this.add(
'engine:chat-engine',
Engine.extend({
init() {
this._super(...arguments);
this.register('template:foo', compile('foo partial'));
this.register('template:application', compile('Engine {{partial "foo"}}'));
this.register(
'controller:application',
Controller.extend({
init() {
this._super(...arguments);
hooks.push('engine - application');
},
})
);
},
})
);
}
additionalEngineRegistrations(callback) {
this._additionalEngineRegistrations = callback;
}
setupEngineWithAttrs() {
this.addTemplate('application', 'Application{{mount "chat-engine"}}');
this.add(
'engine:chat-engine',
Engine.extend({
init() {
this._super(...arguments);
this.register('template:components/foo-bar', compile(`{{partial "troll"}}`));
this.register('template:troll', compile('{{attrs.wat}}'));
this.register(
'controller:application',
Controller.extend({
contextType: 'Engine',
})
);
this.register('template:application', compile('Engine {{foo-bar wat=contextType}}'));
},
})
);
}
stringsEndWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
['@test attrs in an engine']() {
this.setupEngineWithAttrs([]);
return this.visit('/').then(() => {
this.assertText('ApplicationEngine Engine');
});
}
['@test sharing a template between engine and application has separate refinements']() {
this.assert.expect(1);
let sharedTemplate = compile(strip`
<h1>{{contextType}}</h1>
{{ambiguous-curlies}}
{{outlet}}
`);
this.add('template:application', sharedTemplate);
this.add(
'controller:application',
Controller.extend({
contextType: 'Application',
'ambiguous-curlies': 'Controller Data!',
})
);
this.router.map(function() {
this.mount('blog');
});
this.add('route-map:blog', function() {});
this.add(
'engine:blog',
Engine.extend({
init() {
this._super(...arguments);
this.register(
'controller:application',
Controller.extend({
contextType: 'Engine',
})
);
this.register('template:application', sharedTemplate);
this.register(
'template:components/ambiguous-curlies',
compile(strip`
<p>Component!</p>
`)
);
},
})
);
return this.visit('/blog').then(() => {
this.assertText('ApplicationController Data!EngineComponent!');
});
}
['@test sharing a layout between engine and application has separate refinements']() {
this.assert.expect(1);
let sharedLayout = compile(strip`
{{ambiguous-curlies}}
`);
let sharedComponent = Component.extend({
layout: sharedLayout,
});
this.addTemplate(
'application',
strip`
<h1>Application</h1>
{{my-component ambiguous-curlies="Local Data!"}}
{{outlet}}
`
);
this.add('component:my-component', sharedComponent);
this.router.map(function() {
this.mount('blog');
});
this.add('route-map:blog', function() {});
this.add(
'engine:blog',
Engine.extend({
init() {
this._super(...arguments);
this.register(
'template:application',
compile(strip`
<h1>Engine</h1>
{{my-component}}
{{outlet}}
`)
);
this.register('component:my-component', sharedComponent);
this.register(
'template:components/ambiguous-curlies',
compile(strip`
<p>Component!</p>
`)
);
},
})
);
return this.visit('/blog').then(() => {
this.assertText('ApplicationLocal Data!EngineComponent!');
});
}
['@test visit() with `shouldRender: true` returns a promise that resolves when application and engine templates have rendered'](
assert
) {
assert.expect(2);
let hooks = [];
this.setupAppAndRoutableEngine(hooks);
return this.visit('/blog', { shouldRender: true }).then(() => {
this.assertText('ApplicationEngine');
this.assert.deepEqual(
hooks,
['application - application', 'engine - application'],
'the expected model hooks were fired'
);
});
}
['@test visit() with `shouldRender: false` returns a promise that resolves without rendering'](
assert
) {
assert.expect(2);
let hooks = [];
this.setupAppAndRoutableEngine(hooks);
return this.visit('/blog', { shouldRender: false }).then(() => {
assert.strictEqual(
document.getElementById('qunit-fixture').children.length,
0,
`there are no elements in the qunit-fixture element`
);
this.assert.deepEqual(
hooks,
['application - application', 'engine - application'],
'the expected model hooks were fired'
);
});
}
['@test visit() with `shouldRender: true` returns a promise that resolves when application and routeless engine templates have rendered'](
assert
) {
assert.expect(2);
let hooks = [];
this.setupAppAndRoutelessEngine(hooks);
return this.visit('/', { shouldRender: true }).then(() => {
this.assertText('ApplicationEngine');
this.assert.deepEqual(
hooks,
['application - application', 'engine - application'],
'the expected hooks were fired'
);
});
}
['@test visit() with partials in routable engine'](assert) {
assert.expect(2);
let hooks = [];
this.setupAppAndRoutableEngineWithPartial(hooks);
return this.visit('/blog', { shouldRender: true }).then(() => {
this.assertText('ApplicationEngine foo partial');
this.assert.deepEqual(
hooks,
['application - application', 'engine - application'],
'the expected hooks were fired'
);
});
}
['@test visit() with partials in non-routable engine'](assert) {
assert.expect(2);
let hooks = [];
this.setupAppAndRoutlessEngineWithPartial(hooks);
return this.visit('/', { shouldRender: true }).then(() => {
this.assertText('ApplicationEngine foo partial');
this.assert.deepEqual(
hooks,
['application - application', 'engine - application'],
'the expected hooks were fired'
);
});
}
['@test deactivate should be called on Engine Routes before destruction'](assert) {
assert.expect(3);
this.setupAppAndRoutableEngine();
this.add(
'engine:blog',
Engine.extend({
init() {
this._super(...arguments);
this.register('template:application', compile('Engine{{outlet}}'));
this.register(
'route:application',
Route.extend({
deactivate() {
assert.notOk(this.isDestroyed, 'Route is not destroyed');
assert.notOk(this.isDestroying, 'Route is not being destroyed');
},
})
);
},
})
);
return this.visit('/blog').then(() => {
this.assertText('ApplicationEngine');
});
}
['@test engine should lookup and use correct controller']() {
this.setupAppAndRoutableEngine();
return this.visit('/blog?lang=English').then(() => {
this.assertText('ApplicationEngineEnglish');
});
}
['@test error substate route works for the application route of an Engine'](assert) {
assert.expect(2);
let errorEntered = RSVP.defer();
this.setupAppAndRoutableEngine();
this.additionalEngineRegistrations(function() {
this.register(
'route:application_error',
Route.extend({
activate() {
next(errorEntered.resolve);
},
})
);
this.register('template:application_error', compile('Error! {{model.message}}'));
this.register(
'route:post',
Route.extend({
model() {
return RSVP.reject(new Error('Oh, noes!'));
},
})
);
});
return this.visit('/')
.then(() => {
this.assertText('Application');
return this.transitionTo('blog.post');
})
.then(() => {
return errorEntered.promise;
})
.then(() => {
this.assertText('ApplicationError! Oh, noes!');
});
}
['@test error route works for the application route of an Engine'](assert) {
assert.expect(2);
let errorEntered = RSVP.defer();
this.setupAppAndRoutableEngine();
this.additionalEngineRegistrations(function() {
this.register(
'route:error',
Route.extend({
activate() {
next(errorEntered.resolve);
},
})
);
this.register('template:error', compile('Error! {{model.message}}'));
this.register(
'route:post',
Route.extend({
model() {
return RSVP.reject(new Error('Oh, noes!'));
},
})
);
});
return this.visit('/')
.then(() => {
this.assertText('Application');
return this.transitionTo('blog.post');
})
.then(() => {
return errorEntered.promise;
})
.then(() => {
this.assertText('ApplicationEngineError! Oh, noes!');
});
}
['@test error substate route works for a child route of an Engine'](assert) {
assert.expect(2);
let errorEntered = RSVP.defer();
this.setupAppAndRoutableEngine();
this.additionalEngineRegistrations(function() {
this.register(
'route:post_error',
Route.extend({
activate() {
next(errorEntered.resolve);
},
})
);
this.register('template:post_error', compile('Error! {{model.message}}'));
this.register(
'route:post',
Route.extend({
model() {
return RSVP.reject(new Error('Oh, noes!'));
},
})
);
});
return this.visit('/')
.then(() => {
this.assertText('Application');
return this.transitionTo('blog.post');
})
.then(() => {
return errorEntered.promise;
})
.then(() => {
this.assertText('ApplicationEngineError! Oh, noes!');
});
}
['@test error route works for a child route of an Engine'](assert) {
assert.expect(2);
let errorEntered = RSVP.defer();
this.setupAppAndRoutableEngine();
this.additionalEngineRegistrations(function() {
this.register(
'route:post.error',
Route.extend({
activate() {
next(errorEntered.resolve);
},
})
);
this.register('template:post.error', compile('Error! {{model.message}}'));
this.register(
'route:post.comments',
Route.extend({
model() {
return RSVP.reject(new Error('Oh, noes!'));
},
})
);
});
return this.visit('/')
.then(() => {
this.assertText('Application');
return this.transitionTo('blog.post.comments');
})
.then(() => {
return errorEntered.promise;
})
.then(() => {
this.assertText('ApplicationEngineError! Oh, noes!');
});
}
['@test loading substate route works for the application route of an Engine'](assert) {
assert.expect(3);
let done = assert.async();
let loadingEntered = RSVP.defer();
let resolveLoading = RSVP.defer();
this.setupAppAndRoutableEngine();
this.additionalEngineRegistrations(function() {
this.register(
'route:application_loading',
Route.extend({
activate() {
next(loadingEntered.resolve);
},
})
);
this.register('template:application_loading', compile('Loading'));
this.register('template:post', compile('Post'));
this.register(
'route:post',
Route.extend({
model() {
return resolveLoading.promise;
},
})
);
});
return this.visit('/').then(() => {
this.assertText('Application');
let transition = this.transitionTo('blog.post');
loadingEntered.promise.then(() => {
this.assertText('ApplicationLoading');
resolveLoading.resolve();
return this.runTaskNext().then(() => {
this.assertText('ApplicationEnginePost');
done();
});
});
return transition;
});
}
['@test loading route works for the application route of an Engine'](assert) {
assert.expect(3);
let done = assert.async();
let loadingEntered = RSVP.defer();
let resolveLoading = RSVP.defer();
this.setupAppAndRoutableEngine();
this.additionalEngineRegistrations(function() {
this.register(
'route:loading',
Route.extend({
activate() {
next(loadingEntered.resolve);
},
})
);
this.register('template:loading', compile('Loading'));
this.register('template:post', compile('Post'));
this.register(
'route:post',
Route.extend({
model() {
return resolveLoading.promise;
},
})
);
});
return this.visit('/').then(() => {
this.assertText('Application');
let transition = this.transitionTo('blog.post');
loadingEntered.promise.then(() => {
this.assertText('ApplicationEngineLoading');
resolveLoading.resolve();
return this.runTaskNext().then(() => {
this.assertText('ApplicationEnginePost');
done();
});
});
return transition;
});
}
['@test loading substate route works for a child route of an Engine'](assert) {
assert.expect(3);
let resolveLoading;
this.setupAppAndRoutableEngine();
this.additionalEngineRegistrations(function() {
this.register('template:post', compile('{{outlet}}'));
this.register('template:post.comments', compile('Comments'));
this.register('template:post.likes_loading', compile('Loading'));
this.register('template:post.likes', compile('Likes'));
this.register(
'route:post.likes',
Route.extend({
model() {
return new RSVP.Promise(resolve => {
resolveLoading = resolve;
});
},
})
);
});
return this.visit('/blog/post/comments').then(() => {
this.assertText('ApplicationEngineComments');
let transition = this.transitionTo('blog.post.likes');
this.runTaskNext().then(() => {
this.assertText('ApplicationEngineLoading');
resolveLoading();
});
return transition
.then(() => this.runTaskNext())
.then(() => this.assertText('ApplicationEngineLikes'));
});
}
['@test loading route works for a child route of an Engine'](assert) {
assert.expect(3);
let done = assert.async();
let loadingEntered = RSVP.defer();
let resolveLoading = RSVP.defer();
this.setupAppAndRoutableEngine();
this.additionalEngineRegistrations(function() {
this.register('template:post', compile('{{outlet}}'));
this.register('template:post.comments', compile('Comments'));
this.register(
'route:post.loading',
Route.extend({
activate() {
next(loadingEntered.resolve);
},
})
);
this.register('template:post.loading', compile('Loading'));
this.register('template:post.likes', compile('Likes'));
this.register(
'route:post.likes',
Route.extend({
model() {
return resolveLoading.promise;
},
})
);
});
return this.visit('/blog/post/comments').then(() => {
this.assertText('ApplicationEngineComments');
let transition = this.transitionTo('blog.post.likes');
loadingEntered.promise.then(() => {
this.assertText('ApplicationEngineLoading');
resolveLoading.resolve();
return this.runTaskNext().then(() => {
this.assertText('ApplicationEngineLikes');
done();
});
});
return transition;
});
}
["@test query params don't have stickiness by default between model"](assert) {
assert.expect(1);
let tmpl = '{{#link-to "blog.category" 1337}}Category 1337{{/link-to}}';
this.setupAppAndRoutableEngine();
this.additionalEngineRegistrations(function() {
this.register('template:category', compile(tmpl));
});
return this.visit('/blog/category/1?type=news').then(() => {
let suffix = '/blog/category/1337';
let href = this.element.querySelector('a').href;
// check if link ends with the suffix
assert.ok(this.stringsEndWith(href, suffix));
});
}
['@test query params in customized controllerName have stickiness by default between model'](
assert
) {
assert.expect(2);
let tmpl =
'{{#link-to "blog.author" 1337 class="author-1337"}}Author 1337{{/link-to}}{{#link-to "blog.author" 1 class="author-1"}}Author 1{{/link-to}}';
this.setupAppAndRoutableEngine();
this.additionalEngineRegistrations(function() {
this.register('template:author', compile(tmpl));
});
return this.visit('/blog/author/1?official=true').then(() => {
let suffix1 = '/blog/author/1?official=true';
let href1 = this.element.querySelector('.author-1').href;
let suffix1337 = '/blog/author/1337';
let href1337 = this.element.querySelector('.author-1337').href;
// check if link ends with the suffix
assert.ok(this.stringsEndWith(href1, suffix1), `${href1} ends with ${suffix1}`);
assert.ok(this.stringsEndWith(href1337, suffix1337), `${href1337} ends with ${suffix1337}`);
});
}
['@test visit() routable engine which errors on init'](assert) {
assert.expect(1);
let hooks = [];
this.additionalEngineRegistrations(function() {
this.register(
'route:application',
Route.extend({
init() {
throw new Error('Whoops! Something went wrong...');
},
})
);
});
this.setupAppAndRoutableEngine(hooks);
return this.visit('/', { shouldRender: true })
.then(() => {
return this.visit('/blog');
})
.catch(error => {
assert.equal(error.message, 'Whoops! Something went wrong...');
});
}
}
);
|
import React from "react"
import "react-svg-line-chart/lib/index.css"
import DemoBasic from "./components/DemoBasic"
import DemoAdvanced from "./components/DemoAdvanced"
import readmeHtml from "../../README.md"
const routes = [
{
path: "/",
exact: true,
component: <DemoBasic />,
label: "Basic example",
},
{
path: "/advanced",
component: <DemoAdvanced />,
label: "Advanced example",
},
{
path: "/readme",
html: readmeHtml,
label: "Read me",
},
]
export default routes
|
var AbstractModify = require('./AbstractModify');
var gen = require('./gen');
var PropertyModify = AbstractModify.extend(function(original, propety) {
AbstractModify.call(this, original);
this.propety = propety;
}).methods({
gen: function() {
var repl = gen.getAnbuString(this.propety.content(), this.original);
return '[' + repl + ']';
},
length: function() {
return 1;
}
});
module.exports = PropertyModify; |
/*
Pokemon Showdown Bot, for NodeJS
By: Ecuacion
*/
try {
require('sugar');
global.colors = require('colors');
global.sys = require('sys');
global.fs = require('fs');
global.path = require('path');
global.PSClient = require('./showdown-client.js');
} catch (e) {
console.log(e.stack);
console.log("ERROR: missing dependencies, try 'npm install'");
process.exit(-1);
}
console.log((
'-----------------------------------------------\n' +
' Welcome to Areilite Bot for Node! \n' +
'-----------------------------------------------\n'
).yellow);
global.Tools = require('./tools.js');
var cmdArgs = process.argv.slice(2);
if (!global.AppOptions) global.AppOptions = Tools.paseArguments(cmdArgs);
if (AppOptions.help) {
console.log(
"Options:\n" +
" [-h/-help] - Gives you this guide\n" +
" [-c/-config] config-file - Set a custom configuratioon file\n" +
" [-dt/-data] data-dir - Set a custom data directory\n" +
" [-p/-production] - Production mode (recommended)\n" +
" [-m/-monitor] - Monitor mode\n" +
" [-d/-debug] - Debug mode\n" +
" [-t/-test] - Test Mode\n"
);
process.exit();
}
if (!AppOptions.config) AppOptions.config = './config.js';
if (!AppOptions.data) AppOptions.data = './data/';
if (AppOptions.data.charAt(AppOptions.data.length - 1) !== '/') AppOptions.data += '/';
if (!fs.existsSync(AppOptions.data)) {
console.log(AppOptions.data + " does not exist - creating data directory...");
fs.mkdirSync(AppOptions.data);
}
if (!fs.existsSync(AppOptions.data + "_temp/")) {
console.log(AppOptions.data + "_temp/" + " does not exist - creating temp directory...");
fs.mkdirSync(AppOptions.data + "_temp/");
}
if (!fs.existsSync(AppOptions.config)) {
console.log(AppOptions.config + " does not exist - creating one with default settings...");
fs.writeFileSync(AppOptions.config, fs.readFileSync('./config-example.js'));
}
global.Config = require(AppOptions.config);
Tools.checkConfig();
if (AppOptions.debugmode) info((['Debug', 'Monitor', 'Production'])[AppOptions.debugmode - 1] + ' mode');
info('Loading globals');
/* Globals */
global.Formats = {};
global.Settings = require('./settings.js');
global.DataDownloader = require('./data-downloader.js');
global.CommandParser = require('./command-parser.js');
global.SecurityLog = require('./security-log.js');
/* Commands */
if (!AppOptions.testmode) CommandParser.loadCommands();
/* Languages (translations) */
if (!AppOptions.testmode) Tools.loadTranslations();
/* Features */
global.Features = {};
if (!AppOptions.testmode) {
var featureList = fs.readdirSync('./features/');
featureList.forEach(function (feature) {
if (fs.existsSync('./features/' + feature + '/index.js')) {
try {
var f = require('./features/' + feature + '/index.js');
if (f.id) {
Features[f.id] = f;
ok("New feature: " + f.id + ' | ' + f.desc);
} else {
error("Failed to load feature: " + './features/' + feature);
}
} catch (e) {
errlog(e.stack);
error("Failed to load feature: " + './features/' + feature);
}
}
});
}
global.reloadFeatures = function () {
var featureList = fs.readdirSync('./features/');
var errs = [];
featureList.forEach(function (feature) {
if (fs.existsSync('./features/' + feature + '/index.js')) {
try {
Tools.uncacheTree('./features/' + feature + '/index.js');
var f = require('./features/' + feature + '/index.js');
if (f.id) {
if (Features[f.id] && typeof Features[f.id].destroy === "function") Features[f.id].destroy();
Features[f.id] = f;
if (typeof Features[f.id].init === "function") Features[f.id].init();
}
} catch (e) {
errlog(e.stack);
errs.push(feature);
}
}
});
info('Features reloaded' + (errs.length ? ('. Errors: ' + errs.join(', ')) : ''));
return errs;
};
/* Bot creation and connection */
function botAfterConnect () {
//join rooms
if (typeof Config.rooms === "string") {
joinByQueryRequest(Config.rooms);
} else {
var cmds = [];
var featureInitCmds;
for (var i = 0; i < Config.rooms.length; i++) {
cmds.push('|/join ' + Config.rooms[i]);
}
for (var i = 0; i < Config.initCmds.length; i++) {
cmds.push(Config.initCmds[i]);
}
for (var f in Features) {
if (typeof Features[f].getInitCmds === "function") {
try {
featureInitCmds = Features[f].getInitCmds();
if (featureInitCmds) cmds = cmds.concat(featureInitCmds);
} catch (e) {
errlog(e.stack);
}
}
}
Bot.send(cmds, 2000);
}
}
function joinByQueryRequest(target) {
if (target === 'official' || target === 'public' || target === 'all') {
info('Joining ' + target + ' rooms');
} else {
error('Config.rooms, as a string must be "official", "public" or "all"');
var cmds = [];
var featureInitCmds;
for (var i = 0; i < Config.initCmds.length; i++) {
cmds.push(Config.initCmds[i]);
}
for (var f in Features) {
if (typeof Features[f].getInitCmds === "function") {
try {
featureInitCmds = Features[f].getInitCmds();
if (featureInitCmds) cmds = cmds.concat(featureInitCmds);
} catch (e) {
errlog(e.stack);
}
}
}
Bot.send(cmds, 2000);
return;
}
var qParser = function (data) {
data = data.split('|');
if (data[0] === 'rooms') {
data.splice(0, 1);
var str = data.join('|');
var cmds = [];
var featureInitCmds;
try {
var rooms = JSON.parse(str);
var offRooms = [], publicRooms = [];
if (rooms.official) {
for (var i = 0; i < rooms.official.length; i++) {
if (rooms.official[i].title) offRooms.push(toId(rooms.official[i].title));
}
}
if (rooms.chat) {
for (var i = 0; i < rooms.chat.length; i++) {
if (rooms.chat[i].title) publicRooms.push(toId(rooms.chat[i].title));
}
}
if (target === 'all' || target === 'official') {
for (var i = 0; i < offRooms.length; i++) cmds.push('|/join ' + offRooms[i]);
}
if (target === 'all' || target === 'public') {
for (var i = 0; i < publicRooms.length; i++) cmds.push('|/join ' + publicRooms[i]);
}
} catch (e) {}
for (var i = 0; i < Config.initCmds.length; i++) {
cmds.push(Config.initCmds[i]);
}
for (var f in Features) {
if (typeof Features[f].getInitCmds === "function") {
try {
featureInitCmds = Features[f].getInitCmds();
if (featureInitCmds) cmds = cmds.concat(featureInitCmds);
} catch (e) {
errlog(e.stack);
}
}
}
Bot.send(cmds, 2000);
Bot.removeListener('queryresponse', qParser);
}
};
Bot.on('queryresponse', qParser);
Bot.send('|/cmd rooms');
}
var opts = {
serverid: Config.serverid,
secprotocols: [],
connectionTimeout: Config.connectionTimeout,
loginServer: 'https://play.pokemonshowdown.com/~~' + Config.serverid + '/action.php',
nickName: null,
pass: null,
retryLogin: false,
autoConnect: false,
autoReconnect: false,
autoReconnectDelay: 0,
autoJoin: [],
showErrors: (Config.debug ? Config.debug.debug : true),
debug: (Config.debug ? Config.debug.debug : true)
};
global.Bot = new PSClient(Config.server, Config.port, opts);
var connected = false;
Bot.on('connect', function (con) {
ok('Connected to server ' + Config.serverid + ' (' + Tools.getDateString() + ')');
SecurityLog.log('Connected to server ' + Bot.opts.server + ":" + Bot.opts.port + " (" + Bot.opts.serverid + ")");
connected = true;
for (var f in Features) {
try {
if (typeof Features[f].init === "function") Features[f].init();
} catch (e) {
errlog(e.stack);
error("Feature Crash: " + f + " | " + sys.inspect(e));
SecurityLog.log("FEATURE CRASH: " + f + " | " + e.message + "\n" + e.stack);
}
}
});
Bot.on('formats', function (formats) {
global.Formats = {};
var formatsArr = formats.split('|');
var commaIndex, arg, formatData, code, name;
for (var i = 0; i < formatsArr.length; i++) {
commaIndex = formatsArr[i].indexOf(',');
if (commaIndex === -1) {
Formats[toId(formatsArr[i])] = {name: formatsArr[i], team: true, ladder: true, chall: true};
} else if (commaIndex === 0) {
i++;
continue;
} else {
name = formatsArr[i];
formatData = {name: name, team: true, ladder: true, chall: true};
code = commaIndex >= 0 ? parseInt(name.substr(commaIndex + 1), 16) : NaN;
if (!isNaN(code)) {
name = name.substr(0, commaIndex);
if (code & 1) formatData.team = false;
if (!(code & 2)) formatData.ladder = false;
if (!(code & 4)) formatData.chall = false;
if (!(code & 8)) formatData.disableTournaments = true;
} else {
if (name.substr(name.length - 2) === ',#') { // preset teams
formatData.team = false;
name = name.substr(0, name.length - 2);
}
if (name.substr(name.length - 2) === ',,') { // search-only
formatData.chall = false;
name = name.substr(0, name.length - 2);
} else if (name.substr(name.length - 1) === ',') { // challenge-only
formatData.ladder = false;
name = name.substr(0, name.length - 1);
}
}
formatData.name = name;
Formats[toId(name)] = formatData;
}
}
ok('Received battle formats. Total: ' + formatsArr.length);
if (!Config.disableDownload) {
DataDownloader.download();
}
});
Bot.on('challstr', function (challstr) {
info('Received challstr, logging in...');
if (!Config.nick) {
Bot.rename('Bot ' + Tools.generateRandomNick(10));
} else {
Bot.rename(Config.nick, Config.pass);
}
});
var retryingRename = false;
Bot.on('renamefailure', function (e) {
if (e === -1) {
if (!Config.nick) {
debug('Login failure - generating another random nickname');
Bot.rename('Bot ' + Tools.generateRandomNick(10));
} else {
error('Login failure - name registered, invalid or no password given');
if (!Bot.status.named) {
info("Invalid nick + pass, using a random nickname");
Config.nick = '';
Bot.rename('Bot ' + Tools.generateRandomNick(10));
}
}
} else {
if (Config.autoReloginDelay) {
error('Login failure, retrying in ' + (Config.autoReloginDelay / 1000) + ' seconds');
retryingRename = true;
setTimeout(function () {
retryingRename = false;
if (!Config.nick) {
Bot.rename('Bot ' + Tools.generateRandomNick(10));
} else {
Bot.rename(Config.nick, Config.pass);
}
}, Config.autoReloginDelay);
} else {
error('Login failure');
}
}
});
Bot.on('rename', function (name, named) {
monitor('Bot nickname has changed: ' + (named ? name.green : name.yellow) + (named ? '' : ' [guest]'));
SecurityLog.log('Bot nickname has changed: ' + name + (named ? '' : ' [guest]'));
if (named) {
if (!Config.nick) {
if (Bot.roomcount > 0) return; // Namechange, not initial login
ok('Succesfully logged in as ' + name);
botAfterConnect();
} else if (toId(Config.nick) === toId(name)) {
ok('Succesfully logged in as ' + name);
botAfterConnect();
}
}
});
/* Reconnect timer */
var reconnectTimer = null;
var reconnecting = false;
Bot.on('disconnect', function (e) {
if (connected) SecurityLog.log('Disconnected from server');
connected = false;
if (Config.autoReconnectDelay) {
if (reconnecting) return;
reconnecting = true;
error('Disconnected from server, retrying in ' + (Config.autoReconnectDelay / 1000) + ' seconds');
reconnectTimer = setTimeout(function () {
reconnecting = false;
info('Connecting to server ' + Config.server + ':' + Config.port);
Bot.connect();
}, Config.autoReconnectDelay);
} else {
error('Disconnected from server, exiting...');
process.exit(0);
}
});
/* Commands */
Bot.on('chat', function (room, timeOff, by, msg) {
CommandParser.parse(room, by, msg);
Settings.userManager.reportChat(by, room);
});
Bot.on('pm', function (by, msg) {
CommandParser.parse(',' + by, by, msg);
});
Bot.on('userjoin', function (room, by) {
Settings.userManager.reportJoin(by, room);
});
Bot.on('userleave', function (room, by) {
Settings.userManager.reportLeave(by, room);
});
Bot.on('userrename', function (room, old, by) {
Settings.userManager.reportRename(old, by, room);
});
/* Features */
Bot.on('line', function (room, message, isIntro, spl) {
for (var f in Features) {
try {
if (typeof Features[f].parse === "function") Features[f].parse(room, message, isIntro, spl);
} catch (e) {
errlog(e.stack);
error("Feature Crash: " + f + " | " + sys.inspect(e));
SecurityLog.log("FEATURE CRASH: " + f + " | " + e.message + "\n" + e.stack);
Features[f].disabled = true;
Features[f].parse = null;
info("Feature " + f + " has been disabled");
}
}
});
/* Info and debug */
Bot.on('joinroom', function (room, type) {
SecurityLog.log("Joined room: " + room + " [" + type + "]");
if (type === 'chat') monitor('Joined room ' + room, 'room', 'join');
else if (type === 'battle') monitor('Joined battle ' + room, 'battle', 'join');
else monitor('Joined room ' + room + ' [' + Bot.rooms[room].type + ']', 'room', 'join');
});
Bot.on('joinfailure', function (room, e, moreInfo) {
SecurityLog.log('Could not join ' + room + ': [' + e + '] ' + moreInfo);
monitor('Could not join ' + room + ': [' + e + '] ' + moreInfo, 'room', 'error');
});
Bot.on('leaveroom', function (room) {
var roomType = Bot.rooms[room] ? Bot.rooms[room].type : 'chat';
SecurityLog.log("Left room: " + room + " [" + roomType + "]");
if (roomType === 'chat') monitor('Left room ' + room, 'room', 'leave');
else if (roomType === 'battle') monitor('Left battle ' + room, 'battle', 'leave');
else monitor('Left room ' + room + ' [' + Bot.rooms[room].type + ']', 'room', 'leave');
});
Bot.on('message', function (msg) {
recv(msg);
});
Bot.on('send', function (msg) {
sent(msg);
});
ok('Bot object is ready');
/* Global Monitor */
var checkSystem = function () {
var status = '';
var issue = false;
status += 'Connection: ';
if (connected) {
status += 'connected'.green;
status += ' | Nickname: ';
if (Bot.status.named) {
status += Bot.status.nickName.green;
} else if (retryingRename) {
status += Bot.status.nickName.yellow;
} else {
status += Bot.status.nickName.red;
issue = 'login';
}
} else if (reconnecting) {
status += 'retrying'.yellow;
} else {
issue = 'connect';
status += 'disconnected'.red;
}
monitor(status + ' (' + Tools.getDateString() + ')', 'status');
if (issue) {
switch (issue) {
case 'connect':
monitor("Monitor failed: Connection issue. Reconnecting");
SecurityLog.log("Monitor failed: Connection issue. Reconnecting");
Bot.connect();
break;
case 'login':
monitor("Monitor failed: Login issue. Loging in a random username");
SecurityLog.log("Monitor failed: Login issue. Loging in a random username");
Config.nick = '';
Bot.rename('Bot ' + Tools.generateRandomNick(10));
break;
}
}
};
if (!AppOptions.testmode) {
var sysChecker = setInterval(checkSystem, 60 * 60 * 1000);
ok('Global monitor is working');
}
//CrashGuard
if (!AppOptions.testmode && Config.crashguard) {
process.on('uncaughtException', function (err) {
SecurityLog.log("CRASH: " + err.message + "\n" + err.stack);
error(("" + err.message).red);
errlog(("" + err.stack).red);
});
ok("Crashguard enabled");
}
//WatchConfig
if (!AppOptions.testmode && Config.watchconfig) {
Tools.watchFile(AppOptions.config, function (curr, prev) {
if (curr.mtime <= prev.mtime) return;
try {
Tools.uncacheTree(AppOptions.config);
global.Config = require(AppOptions.config);
Tools.checkConfig();
Settings.applyConfig();
CommandParser.reloadTokens();
info(AppOptions.config + ' reloaded');
} catch (e) {
error('could not reload ' + AppOptions.config + " | " + e.message);
errlog(e.stack);
}
});
ok("Watchconfig enabled");
}
console.log("\n-----------------------------------------------\n".yellow);
//Connection
if (AppOptions.testmode) {
ok("Test mode enabled");
} else {
info('Connecting to server ' + Config.server + ':' + Config.port);
Bot.connect();
Bot.startConnectionTimeOut();
}
|
/*\
title: $:/plugins/tiddlywiki/text-slicer/modules/commands/slice.js
type: application/javascript
module-type: command
Command to slice a specified tiddler
\*/
(function(){
/*jslint node: true, browser: true */
/*global $tw: false */
"use strict";
var widget = require("$:/core/modules/widgets/widget.js");
exports.info = {
name: "slice",
synchronous: false
};
var Command = function(params,commander,callback) {
this.params = params;
this.commander = commander;
this.callback = callback;
};
Command.prototype.execute = function() {
if(this.params.length < 1) {
return "Missing parameters";
}
var self = this,
wiki = this.commander.wiki,
sourceTitle = this.params[0],
destTitle = this.params[1],
slicer = new $tw.Slicer(wiki,sourceTitle,{
destTitle: destTitle
});
slicer.sliceTiddler()
slicer.outputTiddlers();
slicer.destroy();
$tw.utils.nextTick(this.callback);
return null;
};
exports.Command = Command;
})();
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.1.0-rc.5-master-42833aa
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.chips
*/
/*
* @see js folder for chips implementation
*/
angular.module('material.components.chips', [
'material.core',
'material.components.autocomplete'
]);
angular
.module('material.components.chips')
.controller('MdChipCtrl', MdChipCtrl);
/**
* Controller for the MdChip component. Responsible for handling keyboard
* events and editting the chip if needed.
*
* @param $scope
* @param $element
* @param $mdConstant
* @param $timeout
* @param $mdUtil
* @constructor
*/
function MdChipCtrl ($scope, $element, $mdConstant, $timeout, $mdUtil) {
/**
* @type {$scope}
*/
this.$scope = $scope;
/**
* @type {$element}
*/
this.$element = $element;
/**
* @type {$mdConstant}
*/
this.$mdConstant = $mdConstant;
/**
* @type {$timeout}
*/
this.$timeout = $timeout;
/**
* @type {$mdUtil}
*/
this.$mdUtil = $mdUtil;
/**
* @type {boolean}
*/
this.isEditting = false;
/**
* @type {MdChipsCtrl}
*/
this.parentController = undefined;
/**
* @type {boolean}
*/
this.enableChipEdit = false;
}
MdChipCtrl.$inject = ["$scope", "$element", "$mdConstant", "$timeout", "$mdUtil"];
/**
* @param {MdChipsCtrl} controller
*/
MdChipCtrl.prototype.init = function(controller) {
this.parentController = controller;
this.enableChipEdit = this.parentController.enableChipEdit;
if (this.enableChipEdit) {
this.$element.on('keydown', this.chipKeyDown.bind(this));
this.$element.on('mousedown', this.chipMouseDown.bind(this));
this.getChipContent().addClass('_md-chip-content-edit-is-enabled');
}
};
/**
* @return {Object}
*/
MdChipCtrl.prototype.getChipContent = function() {
var chipContents = this.$element[0].getElementsByClassName('_md-chip-content');
return angular.element(chipContents[0]);
};
/**
* @return {Object}
*/
MdChipCtrl.prototype.getContentElement = function() {
return angular.element(this.getChipContent().children()[0]);
};
/**
* @return {number}
*/
MdChipCtrl.prototype.getChipIndex = function() {
return parseInt(this.$element.attr('index'));
};
/**
* Presents an input element to edit the contents of the chip.
*/
MdChipCtrl.prototype.goOutOfEditMode = function() {
if (!this.isEditting) return;
this.isEditting = false;
this.$element.removeClass('_md-chip-editing');
this.getChipContent()[0].contentEditable = 'false';
var chipIndex = this.getChipIndex();
var content = this.getContentElement().text();
if (content) {
this.parentController.updateChipContents(
chipIndex,
this.getContentElement().text()
);
this.$mdUtil.nextTick(function() {
if (this.parentController.selectedChip === chipIndex) {
this.parentController.focusChip(chipIndex);
}
}.bind(this));
} else {
this.parentController.removeChipAndFocusInput(chipIndex);
}
};
/**
* Given an HTML element. Selects contents of it.
* @param node
*/
MdChipCtrl.prototype.selectNodeContents = function(node) {
var range, selection;
if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(node);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(node);
selection.removeAllRanges();
selection.addRange(range);
}
};
/**
* Presents an input element to edit the contents of the chip.
*/
MdChipCtrl.prototype.goInEditMode = function() {
this.isEditting = true;
this.$element.addClass('_md-chip-editing');
this.getChipContent()[0].contentEditable = 'true';
this.getChipContent().on('blur', function() {
this.goOutOfEditMode();
}.bind(this));
this.selectNodeContents(this.getChipContent()[0]);
};
/**
* Handles the keydown event on the chip element. If enable-chip-edit attribute is
* set to true, space or enter keys can trigger going into edit mode. Enter can also
* trigger submitting if the chip is already being edited.
* @param event
*/
MdChipCtrl.prototype.chipKeyDown = function(event) {
if (!this.isEditting &&
(event.keyCode === this.$mdConstant.KEY_CODE.ENTER ||
event.keyCode === this.$mdConstant.KEY_CODE.SPACE)) {
event.preventDefault();
this.goInEditMode();
} else if (this.isEditting &&
event.keyCode === this.$mdConstant.KEY_CODE.ENTER) {
event.preventDefault();
this.goOutOfEditMode();
}
};
/**
* Handles the double click event
*/
MdChipCtrl.prototype.chipMouseDown = function() {
if(this.getChipIndex() == this.parentController.selectedChip &&
this.enableChipEdit &&
!this.isEditting) {
this.goInEditMode();
}
};
angular
.module('material.components.chips')
.directive('mdChip', MdChip);
/**
* @ngdoc directive
* @name mdChip
* @module material.components.chips
*
* @description
* `<md-chip>` is a component used within `<md-chips>` and is responsible for rendering individual
* chips.
*
*
* @usage
* <hljs lang="html">
* <md-chip>{{$chip}}</md-chip>
* </hljs>
*
*/
// This hint text is hidden within a chip but used by screen readers to
// inform the user how they can interact with a chip.
var DELETE_HINT_TEMPLATE = '\
<span ng-if="!$mdChipsCtrl.readonly" class="_md-visually-hidden">\
{{$mdChipsCtrl.deleteHint}}\
</span>';
/**
* MDChip Directive Definition
*
* @param $mdTheming
* @param $mdUtil
* ngInject
*/
function MdChip($mdTheming, $mdUtil) {
var hintTemplate = $mdUtil.processTemplate(DELETE_HINT_TEMPLATE);
return {
restrict: 'E',
require: ['^?mdChips', 'mdChip'],
compile: compile,
controller: 'MdChipCtrl'
};
function compile(element, attr) {
// Append the delete template
element.append($mdUtil.processTemplate(hintTemplate));
return function postLink(scope, element, attr, ctrls) {
var chipsController = ctrls.shift();
var chipController = ctrls.shift();
$mdTheming(element);
if (chipsController) {
chipController.init(chipsController);
angular
.element(element[0]
.querySelector('._md-chip-content'))
.on('blur', function () {
chipsController.resetSelectedChip();
chipsController.$scope.$applyAsync();
});
}
};
}
}
MdChip.$inject = ["$mdTheming", "$mdUtil"];
angular
.module('material.components.chips')
.directive('mdChipRemove', MdChipRemove);
/**
* @ngdoc directive
* @name mdChipRemove
* @module material.components.chips
*
* @description
* `<md-chip-remove>`
* Designates an element to be used as the delete button for a chip. This
* element is passed as a child of the `md-chips` element.
*
* @usage
* <hljs lang="html">
* <md-chips><button md-chip-remove>DEL</button></md-chips>
* </hljs>
*/
/**
* MdChipRemove Directive Definition.
*
* @param $compile
* @param $timeout
* @returns {{restrict: string, require: string[], link: Function, scope: boolean}}
* @constructor
*/
function MdChipRemove ($timeout) {
return {
restrict: 'A',
require: '^mdChips',
scope: false,
link: postLink
};
function postLink(scope, element, attr, ctrl) {
element.on('click', function(event) {
scope.$apply(function() {
ctrl.removeChip(scope.$$replacedScope.$index);
});
});
// Child elements aren't available until after a $timeout tick as they are hidden by an
// `ng-if`. see http://goo.gl/zIWfuw
$timeout(function() {
element.attr({ tabindex: -1, 'aria-hidden': true });
element.find('button').attr('tabindex', '-1');
});
}
}
MdChipRemove.$inject = ["$timeout"];
angular
.module('material.components.chips')
.directive('mdChipTransclude', MdChipTransclude);
function MdChipTransclude ($compile) {
return {
restrict: 'EA',
terminal: true,
link: link,
scope: false
};
function link (scope, element, attr) {
var ctrl = scope.$parent.$mdChipsCtrl,
newScope = ctrl.parent.$new(false, ctrl.parent);
newScope.$$replacedScope = scope;
newScope.$chip = scope.$chip;
newScope.$index = scope.$index;
newScope.$mdChipsCtrl = ctrl;
var newHtml = ctrl.$scope.$eval(attr.mdChipTransclude);
element.html(newHtml);
$compile(element.contents())(newScope);
}
}
MdChipTransclude.$inject = ["$compile"];
angular
.module('material.components.chips')
.controller('MdChipsCtrl', MdChipsCtrl);
/**
* Controller for the MdChips component. Responsible for adding to and
* removing from the list of chips, marking chips as selected, and binding to
* the models of various input components.
*
* @param $scope
* @param $mdConstant
* @param $log
* @param $element
* @param $mdUtil
* @constructor
*/
function MdChipsCtrl ($scope, $mdConstant, $log, $element, $timeout, $mdUtil) {
/** @type {$timeout} **/
this.$timeout = $timeout;
/** @type {Object} */
this.$mdConstant = $mdConstant;
/** @type {angular.$scope} */
this.$scope = $scope;
/** @type {angular.$scope} */
this.parent = $scope.$parent;
/** @type {$log} */
this.$log = $log;
/** @type {$element} */
this.$element = $element;
/** @type {angular.NgModelController} */
this.ngModelCtrl = null;
/** @type {angular.NgModelController} */
this.userInputNgModelCtrl = null;
/** @type {Element} */
this.userInputElement = null;
/** @type {Array.<Object>} */
this.items = [];
/** @type {number} */
this.selectedChip = -1;
/** @type {boolean} */
this.hasAutocomplete = false;
/** @type {string} */
this.enableChipEdit = $mdUtil.parseAttributeBoolean(this.mdEnableChipEdit);
/**
* Hidden hint text for how to delete a chip. Used to give context to screen readers.
* @type {string}
*/
this.deleteHint = 'Press delete to remove this chip.';
/**
* Hidden label for the delete button. Used to give context to screen readers.
* @type {string}
*/
this.deleteButtonLabel = 'Remove';
/**
* Model used by the input element.
* @type {string}
*/
this.chipBuffer = '';
/**
* Whether to use the transformChip expression to transform the chip buffer
* before appending it to the list.
* @type {boolean}
*/
this.useTransformChip = false;
/**
* Whether to use the onAdd expression to notify of chip additions.
* @type {boolean}
*/
this.useOnAdd = false;
/**
* Whether to use the onRemove expression to notify of chip removals.
* @type {boolean}
*/
this.useOnRemove = false;
/**
* Whether to use the onSelect expression to notify the component's user
* after selecting a chip from the list.
* @type {boolean}
*/
this.useOnSelect = false;
}
MdChipsCtrl.$inject = ["$scope", "$mdConstant", "$log", "$element", "$timeout", "$mdUtil"];
/**
* Handles the keydown event on the input element: by default <enter> appends
* the buffer to the chip list, while backspace removes the last chip in the
* list if the current buffer is empty.
* @param event
*/
MdChipsCtrl.prototype.inputKeydown = function(event) {
var chipBuffer = this.getChipBuffer();
// If we have an autocomplete, and it handled the event, we have nothing to do
if (this.hasAutocomplete && event.isDefaultPrevented && event.isDefaultPrevented()) {
return;
}
if (event.keyCode === this.$mdConstant.KEY_CODE.BACKSPACE) {
if (chipBuffer) return;
event.preventDefault();
event.stopPropagation();
if (this.items.length) this.selectAndFocusChipSafe(this.items.length - 1);
return;
}
// By default <enter> appends the buffer to the chip list.
if (!this.separatorKeys || this.separatorKeys.length < 1) {
this.separatorKeys = [this.$mdConstant.KEY_CODE.ENTER];
}
// Support additional separator key codes in an array of `md-separator-keys`.
if (this.separatorKeys.indexOf(event.keyCode) !== -1) {
if ((this.hasAutocomplete && this.requireMatch) || !chipBuffer) return;
event.preventDefault();
// Only append the chip and reset the chip buffer if the max chips limit isn't reached.
if (this.hasMaxChipsReached()) return;
this.appendChip(chipBuffer.trim());
this.resetChipBuffer();
}
};
/**
* Updates the content of the chip at given index
* @param chipIndex
* @param chipContents
*/
MdChipsCtrl.prototype.updateChipContents = function(chipIndex, chipContents){
if(chipIndex >= 0 && chipIndex < this.items.length) {
this.items[chipIndex] = chipContents;
this.ngModelCtrl.$setDirty();
}
};
/**
* Returns true if a chip is currently being edited. False otherwise.
* @return {boolean}
*/
MdChipsCtrl.prototype.isEditingChip = function(){
return !!this.$element[0].getElementsByClassName('_md-chip-editing').length;
};
/**
* Handles the keydown event on the chip elements: backspace removes the selected chip, arrow
* keys switch which chips is active
* @param event
*/
MdChipsCtrl.prototype.chipKeydown = function (event) {
if (this.getChipBuffer()) return;
if (this.isEditingChip()) return;
switch (event.keyCode) {
case this.$mdConstant.KEY_CODE.BACKSPACE:
case this.$mdConstant.KEY_CODE.DELETE:
if (this.selectedChip < 0) return;
event.preventDefault();
this.removeAndSelectAdjacentChip(this.selectedChip);
break;
case this.$mdConstant.KEY_CODE.LEFT_ARROW:
event.preventDefault();
if (this.selectedChip < 0) this.selectedChip = this.items.length;
if (this.items.length) this.selectAndFocusChipSafe(this.selectedChip - 1);
break;
case this.$mdConstant.KEY_CODE.RIGHT_ARROW:
event.preventDefault();
this.selectAndFocusChipSafe(this.selectedChip + 1);
break;
case this.$mdConstant.KEY_CODE.ESCAPE:
case this.$mdConstant.KEY_CODE.TAB:
if (this.selectedChip < 0) return;
event.preventDefault();
this.onFocus();
break;
}
};
/**
* Get the input's placeholder - uses `placeholder` when list is empty and `secondary-placeholder`
* when the list is non-empty. If `secondary-placeholder` is not provided, `placeholder` is used
* always.
*/
MdChipsCtrl.prototype.getPlaceholder = function() {
// Allow `secondary-placeholder` to be blank.
var useSecondary = (this.items && this.items.length &&
(this.secondaryPlaceholder == '' || this.secondaryPlaceholder));
return useSecondary ? this.secondaryPlaceholder : this.placeholder;
};
/**
* Removes chip at {@code index} and selects the adjacent chip.
* @param index
*/
MdChipsCtrl.prototype.removeAndSelectAdjacentChip = function(index) {
var selIndex = this.getAdjacentChipIndex(index);
this.removeChip(index);
this.$timeout(angular.bind(this, function () {
this.selectAndFocusChipSafe(selIndex);
}));
};
/**
* Sets the selected chip index to -1.
*/
MdChipsCtrl.prototype.resetSelectedChip = function() {
this.selectedChip = -1;
};
/**
* Gets the index of an adjacent chip to select after deletion. Adjacency is
* determined as the next chip in the list, unless the target chip is the
* last in the list, then it is the chip immediately preceding the target. If
* there is only one item in the list, -1 is returned (select none).
* The number returned is the index to select AFTER the target has been
* removed.
* If the current chip is not selected, then -1 is returned to select none.
*/
MdChipsCtrl.prototype.getAdjacentChipIndex = function(index) {
var len = this.items.length - 1;
return (len == 0) ? -1 :
(index == len) ? index -1 : index;
};
/**
* Append the contents of the buffer to the chip list. This method will first
* call out to the md-transform-chip method, if provided.
*
* @param newChip
*/
MdChipsCtrl.prototype.appendChip = function(newChip) {
if (this.useTransformChip && this.transformChip) {
var transformedChip = this.transformChip({'$chip': newChip});
// Check to make sure the chip is defined before assigning it, otherwise, we'll just assume
// they want the string version.
if (angular.isDefined(transformedChip)) {
newChip = transformedChip;
}
}
// If items contains an identical object to newChip, do not append
if (angular.isObject(newChip)){
var identical = this.items.some(function(item){
return angular.equals(newChip, item);
});
if (identical) return;
}
// Check for a null (but not undefined), or existing chip and cancel appending
if (newChip == null || this.items.indexOf(newChip) + 1) return;
// Append the new chip onto our list
var index = this.items.push(newChip);
// Update model validation
this.ngModelCtrl.$setDirty();
this.validateModel();
// If they provide the md-on-add attribute, notify them of the chip addition
if (this.useOnAdd && this.onAdd) {
this.onAdd({ '$chip': newChip, '$index': index });
}
};
/**
* Sets whether to use the md-transform-chip expression. This expression is
* bound to scope and controller in {@code MdChipsDirective} as
* {@code transformChip}. Due to the nature of directive scope bindings, the
* controller cannot know on its own/from the scope whether an expression was
* actually provided.
*/
MdChipsCtrl.prototype.useTransformChipExpression = function() {
this.useTransformChip = true;
};
/**
* Sets whether to use the md-on-add expression. This expression is
* bound to scope and controller in {@code MdChipsDirective} as
* {@code onAdd}. Due to the nature of directive scope bindings, the
* controller cannot know on its own/from the scope whether an expression was
* actually provided.
*/
MdChipsCtrl.prototype.useOnAddExpression = function() {
this.useOnAdd = true;
};
/**
* Sets whether to use the md-on-remove expression. This expression is
* bound to scope and controller in {@code MdChipsDirective} as
* {@code onRemove}. Due to the nature of directive scope bindings, the
* controller cannot know on its own/from the scope whether an expression was
* actually provided.
*/
MdChipsCtrl.prototype.useOnRemoveExpression = function() {
this.useOnRemove = true;
};
/*
* Sets whether to use the md-on-select expression. This expression is
* bound to scope and controller in {@code MdChipsDirective} as
* {@code onSelect}. Due to the nature of directive scope bindings, the
* controller cannot know on its own/from the scope whether an expression was
* actually provided.
*/
MdChipsCtrl.prototype.useOnSelectExpression = function() {
this.useOnSelect = true;
};
/**
* Gets the input buffer. The input buffer can be the model bound to the
* default input item {@code this.chipBuffer}, the {@code selectedItem}
* model of an {@code md-autocomplete}, or, through some magic, the model
* bound to any inpput or text area element found within a
* {@code md-input-container} element.
* @return {Object|string}
*/
MdChipsCtrl.prototype.getChipBuffer = function() {
return !this.userInputElement ? this.chipBuffer :
this.userInputNgModelCtrl ? this.userInputNgModelCtrl.$viewValue :
this.userInputElement[0].value;
};
/**
* Resets the input buffer for either the internal input or user provided input element.
*/
MdChipsCtrl.prototype.resetChipBuffer = function() {
if (this.userInputElement) {
if (this.userInputNgModelCtrl) {
this.userInputNgModelCtrl.$setViewValue('');
this.userInputNgModelCtrl.$render();
} else {
this.userInputElement[0].value = '';
}
} else {
this.chipBuffer = '';
}
};
MdChipsCtrl.prototype.hasMaxChipsReached = function() {
if (angular.isString(this.maxChips)) this.maxChips = parseInt(this.maxChips, 10) || 0;
return this.maxChips > 0 && this.items.length >= this.maxChips;
};
/**
* Updates the validity properties for the ngModel.
*/
MdChipsCtrl.prototype.validateModel = function() {
this.ngModelCtrl.$setValidity('md-max-chips', !this.hasMaxChipsReached());
};
/**
* Removes the chip at the given index.
* @param index
*/
MdChipsCtrl.prototype.removeChip = function(index) {
var removed = this.items.splice(index, 1);
// Update model validation
this.ngModelCtrl.$setDirty();
this.validateModel();
if (removed && removed.length && this.useOnRemove && this.onRemove) {
this.onRemove({ '$chip': removed[0], '$index': index });
}
};
MdChipsCtrl.prototype.removeChipAndFocusInput = function (index) {
this.removeChip(index);
this.onFocus();
};
/**
* Selects the chip at `index`,
* @param index
*/
MdChipsCtrl.prototype.selectAndFocusChipSafe = function(index) {
if (!this.items.length) {
this.selectChip(-1);
this.onFocus();
return;
}
if (index === this.items.length) return this.onFocus();
index = Math.max(index, 0);
index = Math.min(index, this.items.length - 1);
this.selectChip(index);
this.focusChip(index);
};
/**
* Marks the chip at the given index as selected.
* @param index
*/
MdChipsCtrl.prototype.selectChip = function(index) {
if (index >= -1 && index <= this.items.length) {
this.selectedChip = index;
// Fire the onSelect if provided
if (this.useOnSelect && this.onSelect) {
this.onSelect({'$chip': this.items[this.selectedChip] });
}
} else {
this.$log.warn('Selected Chip index out of bounds; ignoring.');
}
};
/**
* Selects the chip at `index` and gives it focus.
* @param index
*/
MdChipsCtrl.prototype.selectAndFocusChip = function(index) {
this.selectChip(index);
if (index != -1) {
this.focusChip(index);
}
};
/**
* Call `focus()` on the chip at `index`
*/
MdChipsCtrl.prototype.focusChip = function(index) {
this.$element[0].querySelector('md-chip[index="' + index + '"] ._md-chip-content').focus();
};
/**
* Configures the required interactions with the ngModel Controller.
* Specifically, set {@code this.items} to the {@code NgModelCtrl#$viewVale}.
* @param ngModelCtrl
*/
MdChipsCtrl.prototype.configureNgModel = function(ngModelCtrl) {
this.ngModelCtrl = ngModelCtrl;
var self = this;
ngModelCtrl.$render = function() {
// model is updated. do something.
self.items = self.ngModelCtrl.$viewValue;
};
};
MdChipsCtrl.prototype.onFocus = function () {
var input = this.$element[0].querySelector('input');
input && input.focus();
this.resetSelectedChip();
};
MdChipsCtrl.prototype.onInputFocus = function () {
this.inputHasFocus = true;
this.resetSelectedChip();
};
MdChipsCtrl.prototype.onInputBlur = function () {
this.inputHasFocus = false;
};
/**
* Configure event bindings on a user-provided input element.
* @param inputElement
*/
MdChipsCtrl.prototype.configureUserInput = function(inputElement) {
this.userInputElement = inputElement;
// Find the NgModelCtrl for the input element
var ngModelCtrl = inputElement.controller('ngModel');
// `.controller` will look in the parent as well.
if (ngModelCtrl != this.ngModelCtrl) {
this.userInputNgModelCtrl = ngModelCtrl;
}
var scope = this.$scope;
var ctrl = this;
// Run all of the events using evalAsync because a focus may fire a blur in the same digest loop
var scopeApplyFn = function(event, fn) {
scope.$evalAsync(angular.bind(ctrl, fn, event));
};
// Bind to keydown and focus events of input
inputElement
.attr({ tabindex: 0 })
.on('keydown', function(event) { scopeApplyFn(event, ctrl.inputKeydown) })
.on('focus', function(event) { scopeApplyFn(event, ctrl.onInputFocus) })
.on('blur', function(event) { scopeApplyFn(event, ctrl.onInputBlur) })
};
MdChipsCtrl.prototype.configureAutocomplete = function(ctrl) {
if ( ctrl ) {
this.hasAutocomplete = true;
ctrl.registerSelectedItemWatcher(angular.bind(this, function (item) {
if (item) {
// Only append the chip and reset the chip buffer if the max chips limit isn't reached.
if (this.hasMaxChipsReached()) return;
this.appendChip(item);
this.resetChipBuffer();
}
}));
this.$element.find('input')
.on('focus',angular.bind(this, this.onInputFocus) )
.on('blur', angular.bind(this, this.onInputBlur) );
}
};
MdChipsCtrl.prototype.hasFocus = function () {
return this.inputHasFocus || this.selectedChip >= 0;
};
angular
.module('material.components.chips')
.directive('mdChips', MdChips);
/**
* @ngdoc directive
* @name mdChips
* @module material.components.chips
*
* @description
* `<md-chips>` is an input component for building lists of strings or objects. The list items are
* displayed as 'chips'. This component can make use of an `<input>` element or an
* `<md-autocomplete>` element.
*
* ### Custom templates
* A custom template may be provided to render the content of each chip. This is achieved by
* specifying an `<md-chip-template>` element containing the custom content as a child of
* `<md-chips>`.
*
* Note: Any attributes on
* `<md-chip-template>` will be dropped as only the innerHTML is used for the chip template. The
* variables `$chip` and `$index` are available in the scope of `<md-chip-template>`, representing
* the chip object and its index in the list of chips, respectively.
* To override the chip delete control, include an element (ideally a button) with the attribute
* `md-chip-remove`. A click listener to remove the chip will be added automatically. The element
* is also placed as a sibling to the chip content (on which there are also click listeners) to
* avoid a nested ng-click situation.
*
* <h3> Pending Features </h3>
* <ul style="padding-left:20px;">
*
* <ul>Style
* <li>Colours for hover, press states (ripple?).</li>
* </ul>
*
* <ul>Validation
* <li>allow a validation callback</li>
* <li>hilighting style for invalid chips</li>
* </ul>
*
* <ul>Item mutation
* <li>Support `
* <md-chip-edit>` template, show/hide the edit element on tap/click? double tap/double
* click?
* </li>
* </ul>
*
* <ul>Truncation and Disambiguation (?)
* <li>Truncate chip text where possible, but do not truncate entries such that two are
* indistinguishable.</li>
* </ul>
*
* <ul>Drag and Drop
* <li>Drag and drop chips between related `<md-chips>` elements.
* </li>
* </ul>
* </ul>
*
* <span style="font-size:.8em;text-align:center">
* Warning: This component is a WORK IN PROGRESS. If you use it now,
* it will probably break on you in the future.
* </span>
*
* Sometimes developers want to limit the amount of possible chips.<br/>
* You can specify the maximum amount of chips by using the following markup.
*
* <hljs lang="html">
* <md-chips
* ng-model="myItems"
* placeholder="Add an item"
* md-max-chips="5">
* </md-chips>
* </hljs>
*
* In some cases, you have an autocomplete inside of the `md-chips`.<br/>
* When the maximum amount of chips has been reached, you can also disable the autocomplete selection.<br/>
* Here is an example markup.
*
* <hljs lang="html">
* <md-chips ng-model="myItems" md-max-chips="5">
* <md-autocomplete ng-hide="myItems.length > 5" ...></md-autocomplete>
* </md-chips>
* </hljs>
*
* @param {string=|object=} ng-model A model to bind the list of items to
* @param {string=} placeholder Placeholder text that will be forwarded to the input.
* @param {string=} secondary-placeholder Placeholder text that will be forwarded to the input,
* displayed when there is at least one item in the list
* @param {boolean=} readonly Disables list manipulation (deleting or adding list items), hiding
* the input and delete buttons. If no `ng-model` is provided, the chips will automatically be
* marked as readonly.
* @param {string=} md-enable-chip-edit Set this to "true" to enable editing of chip contents. The user can
* go into edit mode with pressing "space", "enter", or double clicking on the chip. Chip edit is only
* supported for chips with basic template.
* @param {number=} md-max-chips The maximum number of chips allowed to add through user input.
* <br/><br/>The validation property `md-max-chips` can be used when the max chips
* amount is reached.
* @param {expression} md-transform-chip An expression of form `myFunction($chip)` that when called
* expects one of the following return values:
* - an object representing the `$chip` input string
* - `undefined` to simply add the `$chip` input string, or
* - `null` to prevent the chip from being appended
* @param {expression=} md-on-add An expression which will be called when a chip has been
* added.
* @param {expression=} md-on-remove An expression which will be called when a chip has been
* removed.
* @param {expression=} md-on-select An expression which will be called when a chip is selected.
* @param {boolean} md-require-match If true, and the chips template contains an autocomplete,
* only allow selection of pre-defined chips (i.e. you cannot add new ones).
* @param {string=} delete-hint A string read by screen readers instructing users that pressing
* the delete key will remove the chip.
* @param {string=} delete-button-label A label for the delete button. Also hidden and read by
* screen readers.
* @param {expression=} md-separator-keys An array of key codes used to separate chips.
*
* @usage
* <hljs lang="html">
* <md-chips
* ng-model="myItems"
* placeholder="Add an item"
* readonly="isReadOnly">
* </md-chips>
* </hljs>
*
* <h3>Validation</h3>
* When using [ngMessages](https://docs.angularjs.org/api/ngMessages), you can show errors based
* on our custom validators.
* <hljs lang="html">
* <form name="userForm">
* <md-chips
* name="fruits"
* ng-model="myItems"
* placeholder="Add an item"
* md-max-chips="5">
* </md-chips>
* <div ng-messages="userForm.fruits.$error" ng-if="userForm.$dirty">
* <div ng-message="md-max-chips">You reached the maximum amount of chips</div>
* </div>
* </form>
* </hljs>
*
*/
var MD_CHIPS_TEMPLATE = '\
<md-chips-wrap\
ng-keydown="$mdChipsCtrl.chipKeydown($event)"\
ng-class="{ \'md-focused\': $mdChipsCtrl.hasFocus(), \'md-readonly\': !$mdChipsCtrl.ngModelCtrl || $mdChipsCtrl.readonly}"\
class="md-chips">\
<md-chip ng-repeat="$chip in $mdChipsCtrl.items"\
index="{{$index}}"\
ng-class="{\'md-focused\': $mdChipsCtrl.selectedChip == $index, \'md-readonly\': !$mdChipsCtrl.ngModelCtrl || $mdChipsCtrl.readonly}">\
<div class="_md-chip-content"\
tabindex="-1"\
aria-hidden="true"\
ng-click="!$mdChipsCtrl.readonly && $mdChipsCtrl.focusChip($index)"\
ng-focus="!$mdChipsCtrl.readonly && $mdChipsCtrl.selectChip($index)"\
md-chip-transclude="$mdChipsCtrl.chipContentsTemplate"></div>\
<div ng-if="!$mdChipsCtrl.readonly"\
class="_md-chip-remove-container"\
md-chip-transclude="$mdChipsCtrl.chipRemoveTemplate"></div>\
</md-chip>\
<div class="_md-chip-input-container">\
<div ng-if="!$mdChipsCtrl.readonly && $mdChipsCtrl.ngModelCtrl"\
md-chip-transclude="$mdChipsCtrl.chipInputTemplate"></div>\
</div>\
</md-chips-wrap>';
var CHIP_INPUT_TEMPLATE = '\
<input\
class="md-input"\
tabindex="0"\
placeholder="{{$mdChipsCtrl.getPlaceholder()}}"\
aria-label="{{$mdChipsCtrl.getPlaceholder()}}"\
ng-model="$mdChipsCtrl.chipBuffer"\
ng-focus="$mdChipsCtrl.onInputFocus()"\
ng-blur="$mdChipsCtrl.onInputBlur()"\
ng-trim="false"\
ng-keydown="$mdChipsCtrl.inputKeydown($event)">';
var CHIP_DEFAULT_TEMPLATE = '\
<span>{{$chip}}</span>';
var CHIP_REMOVE_TEMPLATE = '\
<button\
class="_md-chip-remove"\
ng-if="!$mdChipsCtrl.readonly"\
ng-click="$mdChipsCtrl.removeChipAndFocusInput($$replacedScope.$index)"\
type="button"\
aria-hidden="true"\
tabindex="-1">\
<md-icon md-svg-src="{{ $mdChipsCtrl.mdCloseIcon }}"></md-icon>\
<span class="_md-visually-hidden">\
{{$mdChipsCtrl.deleteButtonLabel}}\
</span>\
</button>';
/**
* MDChips Directive Definition
*/
function MdChips ($mdTheming, $mdUtil, $compile, $log, $timeout, $$mdSvgRegistry) {
// Run our templates through $mdUtil.processTemplate() to allow custom start/end symbols
var templates = getTemplates();
return {
template: function(element, attrs) {
// Clone the element into an attribute. By prepending the attribute
// name with '$', Angular won't write it into the DOM. The cloned
// element propagates to the link function via the attrs argument,
// where various contained-elements can be consumed.
attrs['$mdUserTemplate'] = element.clone();
return templates.chips;
},
require: ['mdChips'],
restrict: 'E',
controller: 'MdChipsCtrl',
controllerAs: '$mdChipsCtrl',
bindToController: true,
compile: compile,
scope: {
readonly: '=readonly',
placeholder: '@',
mdEnableChipEdit: '@',
secondaryPlaceholder: '@',
maxChips: '@mdMaxChips',
transformChip: '&mdTransformChip',
onAppend: '&mdOnAppend',
onAdd: '&mdOnAdd',
onRemove: '&mdOnRemove',
onSelect: '&mdOnSelect',
deleteHint: '@',
deleteButtonLabel: '@',
separatorKeys: '=?mdSeparatorKeys',
requireMatch: '=?mdRequireMatch'
}
};
/**
* Builds the final template for `md-chips` and returns the postLink function.
*
* Building the template involves 3 key components:
* static chips
* chip template
* input control
*
* If no `ng-model` is provided, only the static chip work needs to be done.
*
* If no user-passed `md-chip-template` exists, the default template is used. This resulting
* template is appended to the chip content element.
*
* The remove button may be overridden by passing an element with an md-chip-remove attribute.
*
* If an `input` or `md-autocomplete` element is provided by the caller, it is set aside for
* transclusion later. The transclusion happens in `postLink` as the parent scope is required.
* If no user input is provided, a default one is appended to the input container node in the
* template.
*
* Static Chips (i.e. `md-chip` elements passed from the caller) are gathered and set aside for
* transclusion in the `postLink` function.
*
*
* @param element
* @param attr
* @returns {Function}
*/
function compile(element, attr) {
// Grab the user template from attr and reset the attribute to null.
var userTemplate = attr['$mdUserTemplate'];
attr['$mdUserTemplate'] = null;
var chipTemplate = getTemplateByQuery('md-chips>md-chip-template');
var chipRemoveSelector = $mdUtil
.prefixer()
.buildList('md-chip-remove')
.map(function(attr) {
return 'md-chips>*[' + attr + ']';
})
.join(',');
// Set the chip remove, chip contents and chip input templates. The link function will put
// them on the scope for transclusion later.
var chipRemoveTemplate = getTemplateByQuery(chipRemoveSelector) || templates.remove,
chipContentsTemplate = chipTemplate || templates.default,
chipInputTemplate = getTemplateByQuery('md-chips>md-autocomplete')
|| getTemplateByQuery('md-chips>input')
|| templates.input,
staticChips = userTemplate.find('md-chip');
// Warn of malformed template. See #2545
if (userTemplate[0].querySelector('md-chip-template>*[md-chip-remove]')) {
$log.warn('invalid placement of md-chip-remove within md-chip-template.');
}
function getTemplateByQuery (query) {
if (!attr.ngModel) return;
var element = userTemplate[0].querySelector(query);
return element && element.outerHTML;
}
/**
* Configures controller and transcludes.
*/
return function postLink(scope, element, attrs, controllers) {
$mdUtil.initOptionalProperties(scope, attr);
$mdTheming(element);
var mdChipsCtrl = controllers[0];
if(chipTemplate) {
// Chip editing functionality assumes we are using the default chip template.
mdChipsCtrl.enableChipEdit = false;
}
mdChipsCtrl.chipContentsTemplate = chipContentsTemplate;
mdChipsCtrl.chipRemoveTemplate = chipRemoveTemplate;
mdChipsCtrl.chipInputTemplate = chipInputTemplate;
mdChipsCtrl.mdCloseIcon = $$mdSvgRegistry.mdClose;
element
.attr({ 'aria-hidden': true, tabindex: -1 })
.on('focus', function () { mdChipsCtrl.onFocus(); });
if (attr.ngModel) {
mdChipsCtrl.configureNgModel(element.controller('ngModel'));
// If an `md-transform-chip` attribute was set, tell the controller to use the expression
// before appending chips.
if (attrs.mdTransformChip) mdChipsCtrl.useTransformChipExpression();
// If an `md-on-append` attribute was set, tell the controller to use the expression
// when appending chips.
//
// DEPRECATED: Will remove in official 1.0 release
if (attrs.mdOnAppend) mdChipsCtrl.useOnAppendExpression();
// If an `md-on-add` attribute was set, tell the controller to use the expression
// when adding chips.
if (attrs.mdOnAdd) mdChipsCtrl.useOnAddExpression();
// If an `md-on-remove` attribute was set, tell the controller to use the expression
// when removing chips.
if (attrs.mdOnRemove) mdChipsCtrl.useOnRemoveExpression();
// If an `md-on-select` attribute was set, tell the controller to use the expression
// when selecting chips.
if (attrs.mdOnSelect) mdChipsCtrl.useOnSelectExpression();
// The md-autocomplete and input elements won't be compiled until after this directive
// is complete (due to their nested nature). Wait a tick before looking for them to
// configure the controller.
if (chipInputTemplate != templates.input) {
// The autocomplete will not appear until the readonly attribute is not true (i.e.
// false or undefined), so we have to watch the readonly and then on the next tick
// after the chip transclusion has run, we can configure the autocomplete and user
// input.
scope.$watch('$mdChipsCtrl.readonly', function(readonly) {
if (!readonly) {
$mdUtil.nextTick(function(){
if (chipInputTemplate.indexOf('<md-autocomplete') === 0)
mdChipsCtrl
.configureAutocomplete(element.find('md-autocomplete')
.controller('mdAutocomplete'));
mdChipsCtrl.configureUserInput(element.find('input'));
});
}
});
}
// At the next tick, if we find an input, make sure it has the md-input class
$mdUtil.nextTick(function() {
var input = element.find('input');
input && input.toggleClass('md-input', true);
});
}
// Compile with the parent's scope and prepend any static chips to the wrapper.
if (staticChips.length > 0) {
var compiledStaticChips = $compile(staticChips.clone())(scope.$parent);
$timeout(function() { element.find('md-chips-wrap').prepend(compiledStaticChips); });
}
};
}
function getTemplates() {
return {
chips: $mdUtil.processTemplate(MD_CHIPS_TEMPLATE),
input: $mdUtil.processTemplate(CHIP_INPUT_TEMPLATE),
default: $mdUtil.processTemplate(CHIP_DEFAULT_TEMPLATE),
remove: $mdUtil.processTemplate(CHIP_REMOVE_TEMPLATE)
};
}
}
MdChips.$inject = ["$mdTheming", "$mdUtil", "$compile", "$log", "$timeout", "$$mdSvgRegistry"];
angular
.module('material.components.chips')
.controller('MdContactChipsCtrl', MdContactChipsCtrl);
/**
* Controller for the MdContactChips component
* @constructor
*/
function MdContactChipsCtrl () {
/** @type {Object} */
this.selectedItem = null;
/** @type {string} */
this.searchText = '';
}
MdContactChipsCtrl.prototype.queryContact = function(searchText) {
var results = this.contactQuery({'$query': searchText});
return this.filterSelected ?
results.filter(angular.bind(this, this.filterSelectedContacts)) : results;
};
MdContactChipsCtrl.prototype.itemName = function(item) {
return item[this.contactName];
};
MdContactChipsCtrl.prototype.filterSelectedContacts = function(contact) {
return this.contacts.indexOf(contact) == -1;
};
angular
.module('material.components.chips')
.directive('mdContactChips', MdContactChips);
/**
* @ngdoc directive
* @name mdContactChips
* @module material.components.chips
*
* @description
* `<md-contact-chips>` is an input component based on `md-chips` and makes use of an
* `md-autocomplete` element. The component allows the caller to supply a query expression which
* returns a list of possible contacts. The user can select one of these and add it to the list of
* chips.
*
* You may also use the `md-highlight-text` directive along with its parameters to control the
* appearance of the matched text inside of the contacts' autocomplete popup.
*
* @param {string=|object=} ng-model A model to bind the list of items to
* @param {string=} placeholder Placeholder text that will be forwarded to the input.
* @param {string=} secondary-placeholder Placeholder text that will be forwarded to the input,
* displayed when there is at least on item in the list
* @param {expression} md-contacts An expression expected to return contacts matching the search
* test, `$query`. If this expression involves a promise, a loading bar is displayed while
* waiting for it to resolve.
* @param {string} md-contact-name The field name of the contact object representing the
* contact's name.
* @param {string} md-contact-email The field name of the contact object representing the
* contact's email address.
* @param {string} md-contact-image The field name of the contact object representing the
* contact's image.
*
*
* @param {expression=} filter-selected Whether to filter selected contacts from the list of
* suggestions shown in the autocomplete. This attribute has been removed but may come back.
*
*
*
* @usage
* <hljs lang="html">
* <md-contact-chips
* ng-model="ctrl.contacts"
* md-contacts="ctrl.querySearch($query)"
* md-contact-name="name"
* md-contact-image="image"
* md-contact-email="email"
* placeholder="To">
* </md-contact-chips>
* </hljs>
*
*/
var MD_CONTACT_CHIPS_TEMPLATE = '\
<md-chips class="md-contact-chips"\
ng-model="$mdContactChipsCtrl.contacts"\
md-require-match="$mdContactChipsCtrl.requireMatch"\
md-autocomplete-snap>\
<md-autocomplete\
md-menu-class="md-contact-chips-suggestions"\
md-selected-item="$mdContactChipsCtrl.selectedItem"\
md-search-text="$mdContactChipsCtrl.searchText"\
md-items="item in $mdContactChipsCtrl.queryContact($mdContactChipsCtrl.searchText)"\
md-item-text="$mdContactChipsCtrl.itemName(item)"\
md-no-cache="true"\
md-autoselect\
placeholder="{{$mdContactChipsCtrl.contacts.length == 0 ?\
$mdContactChipsCtrl.placeholder : $mdContactChipsCtrl.secondaryPlaceholder}}">\
<div class="md-contact-suggestion">\
<img \
ng-src="{{item[$mdContactChipsCtrl.contactImage]}}"\
alt="{{item[$mdContactChipsCtrl.contactName]}}"\
ng-if="item[$mdContactChipsCtrl.contactImage]" />\
<span class="md-contact-name" md-highlight-text="$mdContactChipsCtrl.searchText"\
md-highlight-flags="{{$mdContactChipsCtrl.highlightFlags}}">\
{{item[$mdContactChipsCtrl.contactName]}}\
</span>\
<span class="md-contact-email" >{{item[$mdContactChipsCtrl.contactEmail]}}</span>\
</div>\
</md-autocomplete>\
<md-chip-template>\
<div class="md-contact-avatar">\
<img \
ng-src="{{$chip[$mdContactChipsCtrl.contactImage]}}"\
alt="{{$chip[$mdContactChipsCtrl.contactName]}}"\
ng-if="$chip[$mdContactChipsCtrl.contactImage]" />\
</div>\
<div class="md-contact-name">\
{{$chip[$mdContactChipsCtrl.contactName]}}\
</div>\
</md-chip-template>\
</md-chips>';
/**
* MDContactChips Directive Definition
*
* @param $mdTheming
* @returns {*}
* ngInject
*/
function MdContactChips($mdTheming, $mdUtil) {
return {
template: function(element, attrs) {
return MD_CONTACT_CHIPS_TEMPLATE;
},
restrict: 'E',
controller: 'MdContactChipsCtrl',
controllerAs: '$mdContactChipsCtrl',
bindToController: true,
compile: compile,
scope: {
contactQuery: '&mdContacts',
placeholder: '@',
secondaryPlaceholder: '@',
contactName: '@mdContactName',
contactImage: '@mdContactImage',
contactEmail: '@mdContactEmail',
contacts: '=ngModel',
requireMatch: '=?mdRequireMatch',
highlightFlags: '@?mdHighlightFlags'
}
};
function compile(element, attr) {
return function postLink(scope, element, attrs, controllers) {
$mdUtil.initOptionalProperties(scope, attr);
$mdTheming(element);
element.attr('tabindex', '-1');
};
}
}
MdContactChips.$inject = ["$mdTheming", "$mdUtil"];
})(window, window.angular); |
chrome.storage.sync.get('board', function (items) {
console.log("Jira(+) --- Board saved value: " + items.board);
if (items.board == "true") {
$("#min-board-check").prop('checked', true);
}
else {
$("#min-board-check").prop('checked', false);
}
});
function clickHandler(e) {
if (e.toElement !== undefined && e.toElement.value === 'min-board') {
console.log("Jira(+) --- min-board checkbox clicked");
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, "min-board:" + e.toElement.checked);
});
console.log('Jira(+) --- Message to content.js sent');
}
}
document.addEventListener('DOMContentLoaded', function () {
console.log("Jira(+) --- DOM has fully loaded. Loading listeners.");
$("#min-board-check").click(clickHandler);
}); |
import { EntryNames } from '../constants';
import getEntry from '../';
import getEntryPath from '../getEntryPath';
import writeRenderEntry from '../writeRenderEntry';
import writeSnapshotsEntry from '../writeSnapshotsEntry';
const mockSnapshotFiles = ['/foo/bar.percy.js', '/foo/__percy__/bar.js'];
jest.mock('../findSnapshotFiles', () => jest.fn(() => mockSnapshotFiles));
const mockFrameworkFile = '/mock/framework.js';
const mockRenderFile = '/mock/render.js';
const mockSnapshotsFile = '/mock/snapshots.js';
jest.mock('../getEntryPath', () => jest.fn());
jest.mock('../writeRenderEntry');
jest.mock('../writeSnapshotsEntry');
beforeEach(() => {
getEntryPath.mockImplementation(name => {
switch (name) {
case EntryNames.framework:
return mockFrameworkFile;
case EntryNames.render:
return mockRenderFile;
case EntryNames.snapshots:
return mockSnapshotsFile;
}
});
writeRenderEntry.mockReset();
writeSnapshotsEntry.mockReset();
});
it('returns framework entry', () => {
const percyConfig = {
includeFiles: [],
renderer: '@percy/react-percy-snapshot-render',
rootDir: '/foo',
snapshotPatterns: ['**/__percy__/*.js', '**/*.percy.js'],
};
const entry = getEntry(percyConfig);
expect(entry).toEqual(
expect.objectContaining({
[EntryNames.framework]: mockFrameworkFile,
}),
);
});
it('writes render entry file', () => {
const percyConfig = {
includeFiles: [],
renderer: '@percy/react-percy-snapshot-render',
rootDir: '/foo',
snapshotPatterns: ['**/__percy__/*.js', '**/*.percy.js'],
};
getEntry(percyConfig);
expect(writeRenderEntry).toHaveBeenCalledWith(percyConfig, mockRenderFile);
});
it('returns render entry', () => {
const percyConfig = {
includeFiles: [],
renderer: '@percy/react-percy-snapshot-render',
rootDir: '/foo',
snapshotPatterns: ['**/__percy__/*.js', '**/*.percy.js'],
};
const entry = getEntry(percyConfig);
expect(entry).toEqual(
expect.objectContaining({
[EntryNames.render]: mockRenderFile,
}),
);
});
it('writes snapshots entry file', () => {
const percyConfig = {
includeFiles: [],
renderer: '@percy/react-percy-snapshot-render',
rootDir: '/foo',
snapshotPatterns: ['**/__percy__/*.js', '**/*.percy.js'],
};
getEntry(percyConfig);
expect(writeSnapshotsEntry).toHaveBeenCalledWith(mockSnapshotFiles, mockSnapshotsFile);
});
it('returns snapshots entry containing snapshots entry file given no include files in percy config', () => {
const percyConfig = {
includeFiles: [],
renderer: '@percy/react-percy-snapshot-render',
rootDir: '/foo',
snapshotPatterns: ['**/__percy__/*.js', '**/*.percy.js'],
};
const entry = getEntry(percyConfig);
expect(entry).toEqual(
expect.objectContaining({
[EntryNames.snapshots]: [mockSnapshotsFile],
}),
);
});
it('returns snapshots entry containing include files and snapshots entry file given include files in percy config', () => {
const percyConfig = {
includeFiles: ['babel-polyfill', './src/foo.js'],
renderer: '@percy/react-percy-snapshot-render',
rootDir: '/foo',
snapshotPatterns: ['**/__percy__/*.js', '**/*.percy.js'],
};
const entry = getEntry(percyConfig);
expect(entry).toEqual(
expect.objectContaining({
[EntryNames.snapshots]: ['babel-polyfill', './src/foo.js', mockSnapshotsFile],
}),
);
});
it('returns vendor entry containing react and react-dom', () => {
const percyConfig = {
includeFiles: [],
renderer: '@percy/react-percy-snapshot-render',
rootDir: '/foo',
snapshotPatterns: ['**/__percy__/*.js', '**/*.percy.js'],
};
const entry = getEntry(percyConfig);
expect(entry).toEqual(
expect.objectContaining({
[EntryNames.vendor]: ['react', 'react-dom'],
}),
);
});
|
import React from 'react'
import getAllCats from '../api/getAllCats'
module.exports = ({state, dispatch}) => {
console.log('this is the state',state);
return (
<div>
<h1>meowtown</h1>
{state.cats.map(cat => {
return(
<div>
<h3>they call me {cat.name}</h3>
<img src={cat.imageUrl} />
</div>
)
})}
</div>
)
}
|
/**
* # Profession Factory Test
*/
"use strict";
module.exports = (function(){
var expect = require("chai").expect,
mock = require("../helper"),
Profession;
describe("Profession Factory", function () {
beforeEach(function(){
mock.module("sFactories");
mock.inject(function(_Profession_) {
Profession = _Profession_;
});
});
it("Should contain a search method", function() {
expect(!!Profession.search).to.equal(true);
expect(Profession.search).to.be.a("function");
});
});
})();
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.4.4.17-7-c-i-16
description: >
Array.prototype.some - element to be retrieved is inherited
accessor property on an Array
includes: [runTestCase.js]
---*/
function testcase() {
var kValue = "abc";
function callbackfn(val, idx, obj) {
if (idx === 1) {
return val === kValue;
}
return false;
}
try {
Object.defineProperty(Array.prototype, "1", {
get: function () {
return kValue;
},
configurable: true
});
return [, , ].some(callbackfn);
} finally {
delete Array.prototype[1];
}
}
runTestCase(testcase);
|
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
$(document).ready(
function() {
idArray = ["first_name", "last_name", "email", "password", "pesel", "address", "city", "zip", "gender", "born_city", "identity_id", "nip", "phone_number", "nn_patient" ];
var prefix = "auth_user_";
var prefix_contact = "contacts_";
$("#"+prefix+"first_name").attr({"data-parsley-pattern":"^[A-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ][a-zA-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ ]*$", "data-parsley-required":"true", "data-parsley-group":"patient"});
$("#"+prefix+"first_name").after("<ul class=\"parsley-errors-list\"></ul>");
$("#"+prefix+"last_name").attr({"data-parsley-pattern":"^([A-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ][a-zA-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ ]*)(-[A-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ][a-zA-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ ]*)?$", "data-parsley-required":"true", "data-parsley-group":"patient"});
$("#"+prefix+"last_name").after("<ul class=\"parsley-errors-list\"></ul>");
$("#"+prefix+"email").attr({"data-parsley-type":"email", "data-parsley-required":"true","data-parsley-group":"patient"});
$("#"+prefix+"email").after("<ul class=\"parsley-errors-list\"></ul>");
$("#"+prefix+"password").attr({"data-parsley-required":"true", "data-parsley-required":"true","data-parsley-group":"patient"});
$("#"+prefix+"password").after("<ul class=\"parsley-errors-list\"></ul>");
$("#"+prefix+"pesel").attr({"data-parsley-pattern":"^[0-9]{11}$", "data-parsley-required":"true","data-parsley-group":"patient"});
$("#"+prefix+"pesel").after("<ul class=\"parsley-errors-list\"></ul>");
$("#"+prefix+"address").attr({"data-parsley-presence":"true", "data-parsley-required":"true","data-parsley-group":"patient"});
$("#"+prefix+"address").after("<ul class=\"parsley-errors-list\"></ul>");
$("#"+prefix+"city").attr({"data-parsley-pattern":"^[A-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ][a-zA-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ ]*$", "data-parsley-required":"true","data-parsley-group":"patient"});
$("#"+prefix+"city").after("<ul class=\"parsley-errors-list\"></ul>");
$("#"+prefix+"zip").attr({"data-parsley-presence":"true", "data-parsley-required":"true","data-parsley-group":"patient"});
$("#"+prefix+"zip").after("<ul class=\"parsley-errors-list\"></ul>");
$("#"+prefix+"gender").attr({"data-parsley-pattern":"^(mężczyzna|kobieta|nieznana|nie dotyczy)$", "data-parsley-required":"true","data-parsley-required":"true","data-parsley-group":"patient"});
$("#"+prefix+"gender").after("<ul class=\"parsley-errors-list\"></ul>");
$("#"+prefix+"born_city").attr({"data-parsley-presence":"true","data-parsley-required":"true", "data-parsley-group":"patient"});
$("#"+prefix+"born_city").after("<ul class=\"parsley-errors-list\"></ul>");
$("#"+prefix+"identity_id").attr({"data-parsley-length":"[9,9]", "data-parsley-required":"true","data-parsley-group":"patient"});
$("#"+prefix+"identity_id").after("<ul class=\"parsley-errors-list\"></ul>");
$("#"+prefix+"nip").attr({"data-parsley-pattern":"^([0-9](-)?){9}[0-9]$", "data-parsley-required":"true","data-parsley-group":"patient"});
$("#"+prefix+"nip").after("<ul class=\"parsley-errors-list\"></ul>");
$("#"+prefix+"phone_number").attr({"data-parsley-pattern":"^(([+]|[0]{2})[0-9]{2})?[0-9]{9}$", "data-parsley-required":"true","data-parsley-group":"patient"});
$("#"+prefix+"phone_number").after("<ul class=\"parsley-errors-list\"></ul>");
$("#"+prefix+"nn_patient").before("<p>");
$("#"+prefix+"nn_patient").attr({"data-parsley-check":"[1,1]", "data-parsley-group":"nn_patient"});
$("#"+prefix+"nn_patient").after("<ul class=\"parsley-errors-list\"></ul>");
$("#"+prefix+"nn_patient").after("<p>");
$("#"+prefix_contact+"name").attr({"data-parsley-pattern":"^[A-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ][a-zA-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ ]*$", "data-parsley-required":"true", "data-parsley-group":"patient"});
$("#"+prefix_contact+"name").after("<ul class=\"parsley-errors-list\"></ul>");
$("#"+prefix_contact+"surname").attr({"data-parsley-pattern":"^([A-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ][a-zA-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ ]*)(-[A-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ][a-zA-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ ]*)?$", "data-parsley-required":"true", "data-parsley-group":"patient"});
$("#"+prefix_contact+"surname").after("<ul class=\"parsley-errors-list\"></ul>");
$("#"+prefix_contact+"phone_numer").attr({"data-parsley-pattern":"^(([+]|[0]{2})[0-9]{2})?[0-9]{9}$", "data-parsley-required":"true", "data-parsley-group":"patient"});
$("#"+prefix_contact+"phone_numer").after("<ul class=\"parsley-errors-list\"></ul>");
$("form").parsley({trigger: "click focus mousedown focusin focusout change keyup"});
checked = 0;
$("form").parsley().subscribe('parsley:form:validate', function (formInstance) {
// if one of these blocks is not failing do not prevent submission
// we use here group validation with option force (validate even non required fields)
if (formInstance.isValid("patient", true, checked) || formInstance.isValid("nn_patient", true, checked)) {
$("form").parsley().destroy();
$("form").submit();
return true;
}
// else stop form submission
else if(checked == 0) {
checked = 1;
formInstance.submitEvent.preventDefault();
alert("Niektóre pola wydają się być wypełnione niepoprawnie. Upewnij się, że wprowadzasz poprawnie swoje dane. Jeśli na pewno chcesz zatwierdzić dane, które podałeś, ponownie zatwierdź wysłanie formularza.");
$('.invalid-form-error-message')
.html("You must correctly fill at least one of these 2 blocks' fields!")
.addClass("filled");
return false;
}
if(checked == 1) {
$("form").parsley().destroy();
$("form").submit();
}
});
}
); |
var config = require('s-conf');
var POSITIONS_COUNT = config.require('positions_count');
var positionMaps = (function(stepsPerRevolution){
var maps = {};
var map;
for(var motorId in stepsPerRevolution){
map = {};
for(var i=0; i<=POSITIONS_COUNT; i++){
map[i] = Math.round(i*stepsPerRevolution[motorId]/POSITIONS_COUNT);
}
maps[motorId] = map;
}
return maps;
}(config.require('steps_per_revolution')));
exports.position2steps = function position2steps(motorId, position){
if(position < 0 || position >= POSITIONS_COUNT){
throw new Error("Invalid position "+position);
}
var positionMap = positionMaps[motorId];
if(!positionMap){
throw new Error("Invalid motor "+motorId);
}
return positionMap[position];
};
|
var axon = require('..')
, should = require('should');
var req = axon.socket('req')
, rep = axon.socket('rep');
req.bind(4000);
rep.connect(4000);
var pending = 10
, n = pending
, msgs = [];
rep.on('message', function(msg, reply){
reply('got "' + msg + '"');
});
while (n--) {
(function(n){
n = String(n);
setTimeout(function(){
req.send(n, function(msg){
msgs.push(msg.toString());
--pending || done();
});
}, Math.random() * 200 | 0);
})(n);
}
function done() {
msgs.should.have.length(10);
for (var i = 0; i < 10; ++i) {
msgs.should.include('got "' + i + '"');
}
req.close();
rep.close();
} |
var baseDelay = require('../internal/baseDelay');
/**
* Invokes `func` after `wait` milliseconds. Any additional arguments are
* provided to `func` when it is invoked.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to delay.
* @param {number} wait The number of milliseconds to delay invocation.
* @param {...*} [args] The arguments to invoke the function with.
* @returns {number} Returns the timer id.
* @example
*
* _.delay(function(text) {
* console.log(text);
* }, 1000, 'later');
* // => logs 'later' after one second
*/
function delay(func, wait) {
return baseDelay(func, wait, arguments, 2);
}
module.exports = delay;
|
var input = document.getElementById('edit-template');
input.addEventListener('keyup', function onkeyup(event) {
self.port.emit("entered", input.value);
}, false);
self.port.on('show', function (template) {
input.value = template;
input.focus();
});
|
import Ember from 'ember';
import randomGenerator from 'chan-front-end/utils/random-generator';
const chance = randomGenerator();
const RANDOM_STRING_LENGTH = 24;
const RANDOM_STRING_POOL = 'abcdefghijklmnopqrstuvwxyz0123456789';
// Todo:
// 1, pass in params to control whether the two dates is the same
// 2, rewrite function docs
// Return an object contains create-date and update-date
// Have 50% chance of same date by default.
function createDates() {
const isSameDate = chance.bool();
const date = chance.date({ year: 2016 });
const createDate = date;
let updateDate = date;
if (!isSameDate) {
updateDate = new Date(createDate.valueOf() + 1000 * 60 * 60);
}
return { createDate, updateDate };
}
function responseItemForPost(data, id) {
const post_id = id || data.id || chance.string({
length: RANDOM_STRING_LENGTH,
pool: RANDOM_STRING_POOL
});
const { createDate, updateDate } = createDates();
const response = Ember.Object.create({
"id": post_id,
"type": "post",
"attributes": {
'create-date':createDate,
'update-date': updateDate,
"is-publish": false,
"is-featured": false,
"image-url": null,
"title": chance.word(),
"author": chance.name(),
"content": chance.paragraph(),
"short-description": chance.sentence()
}
});
Ember.assign(response.attributes, data.attributes);
return response;
}
export default {
stubPosts: function(pretender, data) {
let responseForPosts = [];
data.forEach(function(post) {
const responseForPost = responseItemForPost(post);
responseForPosts.push(responseForPost);
});
pretender.get('/posts/:post_id', function(request) {
const responseForPost = responseItemForPost({}, request.params['post_id']);
return [200, { 'Content-Type': 'application/vnd.api+json' }, JSON.stringify({ data: responseForPost })];
});
pretender.get('/posts', function(request) {
if (request.queryParams['is-publish']) {
responseForPosts = responseForPosts.filter((responseForPost) => {
return responseForPost.attributes['is-publish'];
});
}
responseForPosts.sort((postOne, postTwo) => {
return postTwo.attributes['update-date'].valueOf() - postOne.attributes['update-date'].valueOf();
});
return [200, { 'Content-Type': 'application/vnd.api+json' }, JSON.stringify({ data: responseForPosts })];
});
}
};
|
module.exports = {
verbose: true,
testEnvironment: 'node',
transform: {
'^.+\\.ts$': 'ts-jest'
},
testRegex: 'tests/config/.*\\.tests\\.ts$',
moduleFileExtensions: [
'ts',
'js'
],
rootDir: '../../',
collectCoverage: false,
coverageDirectory: 'tests/coverage',
collectCoverageFrom: [
'<rootDir>/src/**/*.ts',
],
globals: {
'ts-jest': {
tsconfig: './tests/config/tsconfig.json'
}
}
};
|
var mongoose=require("mongoose");
var commentsSchema=new mongoose.Schema({
text:String,
author:{
id:{
type:mongoose.Schema.Types.ObjectId,
ref:"User"
},
username: String
}
});
module.exports=mongoose.model("Comments",commentsSchema);
|
(function (GRA) {
"use strict";
GRA.kernel = GRA.kernel || {};
/**
* Classe Message
* Permet la communication entre les applications.
*
* @constructor
*/
GRA.kernel.Message = function Message(requestCode, messageDescription) {
/**
* @type {number}
*/
var id = +new Date(),
/**
* @type {int}
*/
request = requestCode,
/**
* @type {string}
*/
description = messageDescription || '',
/**
* @type {object}
*/
integers = {},
/**
* @type {object}
*/
strings = {},
/**
* @type {object}
*/
objects = {};
/**
* Retourne l'identifiant du message
*
* @returns {number}
*/
this.getId = function getId() {
return id;
};
/**
* Retourne le code de requête du message
*
* @returns {number}
*/
this.getRequestCode = function getRequestCode() {
return request;
};
/**
* Retourne la description du message
*
* @returns {string}
*/
this.getDescription = function getDescription() {
return description;
};
/**
* Retourne l'entier dont la clé est fournie en paramètre.
* Si la clé n'est pas trouvée, la valeur par défaut est retournée.
*
* @param {string} key Clé sous laquelle est contenue l'entier
* @param {number} defaultValue Valeur par défaut à retourner si la clé est introuvable
* @returns {number} L'entier
*/
this.getInt = function getInt(key, defaultValue) {
var value = defaultValue;
if (integers.hasOwnProperty(key)) {
value = integers[key];
}
return value;
};
/**
* Retourne la chaîne de caractères dont la clé est fournie en paramètre.
* Si la clé n'est pas trouvée, la valeur par défaut est retournée.
*
* @param {string} key Clé sous laquelle est contenue la chaîne de caractères
* @param {string} defaultValue Valeur par défaut à retourner si la clé est introuvable
* @returns {string} La chaîne de caractères
*/
this.getString = function getString(key, defaultValue) {
return strings[key] || defaultValue;
};
/**
* Retourne l'objet dont la clé est fournie en paramètre.
* Si la clé n'est pas trouvée, la valeur par défaut est retournée.
*
* @param {string} key Clé sous laquelle est contenue l'objet
* @param {object} defaultValue Valeur par défaut à retourner si la clé est introuvable
* @returns {object} L'objet
*/
this.getObject = function getObject(key, defaultValue) {
return objects[key] || defaultValue;
};
/**
* Permet de stocker un entier dans le Message
*
* @param {string} key Clé sous laquelle sera contenue l'entier
* @param {number} value L'entier à stocker
*/
this.putInt = function putInt(key, value) {
integers[key] = value;
};
/**
* Permet de stocker une chaîne de caractères dans le Message
*
* @param {string} key Clé sous laquelle sera contenue la chaîne de caractères
* @param {string} value La chaîne de caractères à stocker
*/
this.putString = function putString(key, value) {
strings[key] = value;
};
/**
* Permet de stocker un objet dans le Message
*
* @param {string} key Clé sous laquelle sera contenue l'objet
* @param {object} value L'objet à stocker
*/
this.putObject = function putObject(key, value) {
objects[key] = value;
};
};
}(GRA || {})); |
'use strict'
const Generator = require('yeoman-generator')
const fs = require('fs')
const readline = require('readline')
const fileTemplate = 'epic.js'
const combineEpicsLine = 'const rootEpic = combineEpics('.replace(/\s/g, '')
const singleLineEpicsLineEmpty = 'const rootEpic = combineEpics()'.replace(
/\s/g,
''
)
const singleLineEpicsLineRegex = new RegExp(
'const rootEpic = combineEpics(.+)'.replace(/\s/g, '')
)
module.exports = class extends Generator {
prompting () {
return this.prompt([
{
type: 'input',
name: 'name',
message: 'Your epic name',
default: 'MyEpic'
},
{
type: 'input',
name: 'path',
message: 'Path to use relative to the src folder',
default: 'epics'
}
]).then(answers => {
this.promptOptions = answers
})
}
writing () {
const name = this.promptOptions.name.toLowerCase()
const fileName = `${name}.${fileTemplate}`
const path = `src/${this.promptOptions.path}/${fileName}`
const epicsPath = this.destinationPath('src/rootEpic.js')
const newImport = `import ${name}Epic from '${path}'`
const importLine = newImport.replace(/\s/g, '')
const newData = ` ${name}Epic`
const dataLine = newData.replace(/\s/g, '')
let data = []
let foundEpic = false
let foundCombine = false
let foundImport = false
let rl = readline.createInterface({
input: fs.createReadStream(epicsPath)
})
rl.on('line', line => {
let testLine = line.replace(/\s/g, '')
foundImport |= testLine === importLine
if (testLine === combineEpicsLine) {
foundCombine = true
if (!foundImport) {
data.splice(-1, 0, newImport)
}
}
if (foundCombine) {
foundEpic |= testLine === dataLine
if (testLine === ')') {
foundCombine = false
if (!foundEpic) {
let lastDataLine = data[data.length - 1].replace(/\s/g, '')
if (lastDataLine !== combineEpicsLine) {
data[data.length - 1] += ','
}
data.push(newData)
}
}
}
if (!foundCombine && testLine === singleLineEpicsLineEmpty) {
if (!foundImport) {
data.splice(-1, 0, newImport)
}
data.push(line.slice(0, line.length - 1))
data.push(newData)
data.push(')')
} else if (!foundCombine && singleLineEpicsLineRegex.test(testLine)) {
if (!foundImport) {
data.splice(-1, 0, newImport)
}
data.push(
`${line.slice(0, line.length - 1)}, ${newData.replace(/ /g, '')})`
)
} else {
data.push(line)
}
})
rl.on('close', () => {
let stream = fs.createWriteStream(epicsPath)
data.forEach(d => stream.write(`${d}\n`))
stream.end()
stream.on('finish', () => {
this.fs.copy(
this.templatePath(fileTemplate),
this.destinationPath(path)
)
})
})
}
}
|
/******/ (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] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = 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;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(1);
module.exports = {
name: 'a'
};
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
// style-loader: Adds some css to the DOM by adding a <style> tag
// load the styles
var content = __webpack_require__(2);
if(typeof content === 'string') content = [[module.id, content, '']];
// add the styles to the DOM
var update = __webpack_require__(4)(content, {});
if(content.locals) module.exports = content.locals;
// Hot Module Replacement
if(false) {
// When the styles change, update the <style> tags
if(!content.locals) {
module.hot.accept("!!./../../../../../node_modules/css-loader/index.js!./../node_modules/postcss-loader/index.js!./css.css", function() {
var newContent = require("!!./../../../../../node_modules/css-loader/index.js!./../node_modules/postcss-loader/index.js!./css.css");
if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];
update(newContent);
});
}
// When the module is disposed, remove the <style> tags
module.hot.dispose(function() { update(); });
}
/***/ },
/* 2 */
/***/ function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(3)();
// imports
// module
exports.push([module.id, "#header {\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n}\n", ""]);
// exports
/***/ },
/* 3 */
/***/ function(module, exports) {
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
module.exports = function() {
var list = [];
// return the list of modules as css string
list.toString = function toString() {
var result = [];
for(var i = 0; i < this.length; i++) {
var item = this[i];
if(item[2]) {
result.push("@media " + item[2] + "{" + item[1] + "}");
} else {
result.push(item[1]);
}
}
return result.join("");
};
// import a list of modules into the list
list.i = function(modules, mediaQuery) {
if(typeof modules === "string")
modules = [[null, modules, ""]];
var alreadyImportedModules = {};
for(var i = 0; i < this.length; i++) {
var id = this[i][0];
if(typeof id === "number")
alreadyImportedModules[id] = true;
}
for(i = 0; i < modules.length; i++) {
var item = modules[i];
// skip already imported module
// this implementation is not 100% perfect for weird media query combinations
// when a module is imported multiple times with different media queries.
// I hope this will never occur (Hey this way we have smaller bundles)
if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) {
if(mediaQuery && !item[2]) {
item[2] = mediaQuery;
} else if(mediaQuery) {
item[2] = "(" + item[2] + ") and (" + mediaQuery + ")";
}
list.push(item);
}
}
};
return list;
};
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var stylesInDom = {},
memoize = function(fn) {
var memo;
return function () {
if (typeof memo === "undefined") memo = fn.apply(this, arguments);
return memo;
};
},
isOldIE = memoize(function() {
return /msie [6-9]\b/.test(window.navigator.userAgent.toLowerCase());
}),
getHeadElement = memoize(function () {
return document.head || document.getElementsByTagName("head")[0];
}),
singletonElement = null,
singletonCounter = 0,
styleElementsInsertedAtTop = [];
module.exports = function(list, options) {
if(false) {
if(typeof document !== "object") throw new Error("The style-loader cannot be used in a non-browser environment");
}
options = options || {};
// Force single-tag solution on IE6-9, which has a hard limit on the # of <style>
// tags it will allow on a page
if (typeof options.singleton === "undefined") options.singleton = isOldIE();
// By default, add <style> tags to the bottom of <head>.
if (typeof options.insertAt === "undefined") options.insertAt = "bottom";
var styles = listToStyles(list);
addStylesToDom(styles, options);
return function update(newList) {
var mayRemove = [];
for(var i = 0; i < styles.length; i++) {
var item = styles[i];
var domStyle = stylesInDom[item.id];
domStyle.refs--;
mayRemove.push(domStyle);
}
if(newList) {
var newStyles = listToStyles(newList);
addStylesToDom(newStyles, options);
}
for(var i = 0; i < mayRemove.length; i++) {
var domStyle = mayRemove[i];
if(domStyle.refs === 0) {
for(var j = 0; j < domStyle.parts.length; j++)
domStyle.parts[j]();
delete stylesInDom[domStyle.id];
}
}
};
}
function addStylesToDom(styles, options) {
for(var i = 0; i < styles.length; i++) {
var item = styles[i];
var domStyle = stylesInDom[item.id];
if(domStyle) {
domStyle.refs++;
for(var j = 0; j < domStyle.parts.length; j++) {
domStyle.parts[j](item.parts[j]);
}
for(; j < item.parts.length; j++) {
domStyle.parts.push(addStyle(item.parts[j], options));
}
} else {
var parts = [];
for(var j = 0; j < item.parts.length; j++) {
parts.push(addStyle(item.parts[j], options));
}
stylesInDom[item.id] = {id: item.id, refs: 1, parts: parts};
}
}
}
function listToStyles(list) {
var styles = [];
var newStyles = {};
for(var i = 0; i < list.length; i++) {
var item = list[i];
var id = item[0];
var css = item[1];
var media = item[2];
var sourceMap = item[3];
var part = {css: css, media: media, sourceMap: sourceMap};
if(!newStyles[id])
styles.push(newStyles[id] = {id: id, parts: [part]});
else
newStyles[id].parts.push(part);
}
return styles;
}
function insertStyleElement(options, styleElement) {
var head = getHeadElement();
var lastStyleElementInsertedAtTop = styleElementsInsertedAtTop[styleElementsInsertedAtTop.length - 1];
if (options.insertAt === "top") {
if(!lastStyleElementInsertedAtTop) {
head.insertBefore(styleElement, head.firstChild);
} else if(lastStyleElementInsertedAtTop.nextSibling) {
head.insertBefore(styleElement, lastStyleElementInsertedAtTop.nextSibling);
} else {
head.appendChild(styleElement);
}
styleElementsInsertedAtTop.push(styleElement);
} else if (options.insertAt === "bottom") {
head.appendChild(styleElement);
} else {
throw new Error("Invalid value for parameter 'insertAt'. Must be 'top' or 'bottom'.");
}
}
function removeStyleElement(styleElement) {
styleElement.parentNode.removeChild(styleElement);
var idx = styleElementsInsertedAtTop.indexOf(styleElement);
if(idx >= 0) {
styleElementsInsertedAtTop.splice(idx, 1);
}
}
function createStyleElement(options) {
var styleElement = document.createElement("style");
styleElement.type = "text/css";
insertStyleElement(options, styleElement);
return styleElement;
}
function createLinkElement(options) {
var linkElement = document.createElement("link");
linkElement.rel = "stylesheet";
insertStyleElement(options, linkElement);
return linkElement;
}
function addStyle(obj, options) {
var styleElement, update, remove;
if (options.singleton) {
var styleIndex = singletonCounter++;
styleElement = singletonElement || (singletonElement = createStyleElement(options));
update = applyToSingletonTag.bind(null, styleElement, styleIndex, false);
remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true);
} else if(obj.sourceMap &&
typeof URL === "function" &&
typeof URL.createObjectURL === "function" &&
typeof URL.revokeObjectURL === "function" &&
typeof Blob === "function" &&
typeof btoa === "function") {
styleElement = createLinkElement(options);
update = updateLink.bind(null, styleElement);
remove = function() {
removeStyleElement(styleElement);
if(styleElement.href)
URL.revokeObjectURL(styleElement.href);
};
} else {
styleElement = createStyleElement(options);
update = applyToTag.bind(null, styleElement);
remove = function() {
removeStyleElement(styleElement);
};
}
update(obj);
return function updateStyle(newObj) {
if(newObj) {
if(newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap)
return;
update(obj = newObj);
} else {
remove();
}
};
}
var replaceText = (function () {
var textStore = [];
return function (index, replacement) {
textStore[index] = replacement;
return textStore.filter(Boolean).join('\n');
};
})();
function applyToSingletonTag(styleElement, index, remove, obj) {
var css = remove ? "" : obj.css;
if (styleElement.styleSheet) {
styleElement.styleSheet.cssText = replaceText(index, css);
} else {
var cssNode = document.createTextNode(css);
var childNodes = styleElement.childNodes;
if (childNodes[index]) styleElement.removeChild(childNodes[index]);
if (childNodes.length) {
styleElement.insertBefore(cssNode, childNodes[index]);
} else {
styleElement.appendChild(cssNode);
}
}
}
function applyToTag(styleElement, obj) {
var css = obj.css;
var media = obj.media;
if(media) {
styleElement.setAttribute("media", media)
}
if(styleElement.styleSheet) {
styleElement.styleSheet.cssText = css;
} else {
while(styleElement.firstChild) {
styleElement.removeChild(styleElement.firstChild);
}
styleElement.appendChild(document.createTextNode(css));
}
}
function updateLink(linkElement, obj) {
var css = obj.css;
var sourceMap = obj.sourceMap;
if(sourceMap) {
// http://stackoverflow.com/a/26603875
css += "\n/*# sourceMappingURL=data:application/json;base64," + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + " */";
}
var blob = new Blob([css], { type: "text/css" });
var oldSrc = linkElement.href;
linkElement.href = URL.createObjectURL(blob);
if(oldSrc)
URL.revokeObjectURL(oldSrc);
}
/***/ }
/******/ ]); |
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _OVERFLOW;
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _2 = require('./util/_');
var _3 = _interopRequireDefault(_2);
var _style = require('dom-helpers/style');
var _style2 = _interopRequireDefault(_style);
var _height = require('dom-helpers/query/height');
var _height2 = _interopRequireDefault(_height);
var _camelizeStyle = require('dom-helpers/util/camelizeStyle');
var _camelizeStyle2 = _interopRequireDefault(_camelizeStyle);
var _configuration = require('./util/configuration');
var _configuration2 = _interopRequireDefault(_configuration);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _compat = require('./util/compat');
var _compat2 = _interopRequireDefault(_compat);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var transform = (0, _camelizeStyle2.default)(_configuration2.default.animate.transform);
var CLOSING = 0,
CLOSED = 1,
OPENING = 2,
OPEN = 3;
function properties(prop, value) {
var _ref, _ref2;
var TRANSLATION_MAP = _configuration2.default.animate.TRANSLATION_MAP;
if (TRANSLATION_MAP && TRANSLATION_MAP[prop]) return _ref = {}, _ref[transform] = TRANSLATION_MAP[prop] + '(' + value + ')', _ref;
return _ref2 = {}, _ref2[prop] = value, _ref2;
}
var OVERFLOW = (_OVERFLOW = {}, _OVERFLOW[CLOSED] = 'hidden', _OVERFLOW[CLOSING] = 'hidden', _OVERFLOW[OPENING] = 'hidden', _OVERFLOW);
var propTypes = {
open: _react2.default.PropTypes.bool,
dropUp: _react2.default.PropTypes.bool,
duration: _react2.default.PropTypes.number,
onClosing: _react2.default.PropTypes.func,
onOpening: _react2.default.PropTypes.func,
onClose: _react2.default.PropTypes.func,
onOpen: _react2.default.PropTypes.func
};
exports.default = _react2.default.createClass({
displayName: 'Popup',
propTypes: propTypes,
getInitialState: function getInitialState() {
return {
initialRender: true,
status: this.props.open ? OPENING : CLOSED
};
},
getDefaultProps: function getDefaultProps() {
return {
duration: 200,
open: false,
onClosing: function onClosing() {},
onOpening: function onOpening() {},
onClose: function onClose() {},
onOpen: function onOpen() {}
};
},
componentWillReceiveProps: function componentWillReceiveProps(nextProps) {
this.setState({
contentChanged: childKey(nextProps.children) !== childKey(this.props.children)
});
},
componentDidMount: function componentDidMount() {
var _this = this;
var isOpen = this.state.status === OPENING;
_compat2.default.batchedUpdates(function () {
_this.setState({ initialRender: false });
if (isOpen) {
_this.open();
}
});
},
componentDidUpdate: function componentDidUpdate(pvProps) {
var closing = pvProps.open && !this.props.open,
opening = !pvProps.open && this.props.open,
open = this.props.open,
status = this.state.status;
if (!!pvProps.dropUp !== !!this.props.dropUp) {
this.cancelNextCallback();
if (status === OPENING) this.open();
if (status === CLOSING) this.close();
return;
}
if (opening) this.open();else if (closing) this.close();else if (open) {
// this.height() returns a floating point number with the desired height
// for this popup. Because of potential rounding errors in floating point
// aritmetic we must allow an error margin when comparing to the current
// state, otherwise we can end up in an infinite loop where the height
// is never exactly equal to our target value.
var height = this.height(),
diff = Math.abs(height - this.state.height);
if (isNaN(diff) || diff > 0.1) this.setState({ height: height });
}
},
render: function render() {
var _props = this.props,
className = _props.className,
dropUp = _props.dropUp,
style = _props.style,
_state = this.state,
status = _state.status,
height = _state.height;
var overflow = OVERFLOW[status] || 'visible',
display = status === CLOSED ? 'none' : 'block';
return _react2.default.createElement(
'div',
{
style: _extends({
display: display,
overflow: overflow,
height: height
}, style),
className: (0, _classnames2.default)(className, 'rw-popup-container', dropUp && 'rw-dropup', this.isTransitioning() && 'rw-popup-animating')
},
this.renderChildren()
);
},
renderChildren: function renderChildren() {
if (!this.props.children) return _react2.default.createElement('span', { className: 'rw-popup rw-widget' });
var offset = this.getOffsetForStatus(this.state.status),
child = _react2.default.Children.only(this.props.children);
return (0, _react.cloneElement)(child, {
style: _extends({}, child.props.style, offset, {
position: this.isTransitioning() ? 'absolute' : undefined
}),
className: (0, _classnames2.default)(child.props.className, 'rw-popup rw-widget')
});
},
open: function open() {
var _this2 = this;
this.cancelNextCallback();
var el = _compat2.default.findDOMNode(this).firstChild,
height = this.height();
this.props.onOpening();
this.safeSetState({ status: OPENING, height: height }, function () {
var offset = _this2.getOffsetForStatus(OPEN),
duration = _this2.props.duration;
_this2.animate(el, offset, duration, 'ease', function () {
_this2.safeSetState({ status: OPEN }, function () {
_this2.props.onOpen();
});
});
});
},
close: function close() {
var _this3 = this;
this.cancelNextCallback();
var el = _compat2.default.findDOMNode(this).firstChild,
height = this.height();
this.props.onClosing();
this.safeSetState({ status: CLOSING, height: height }, function () {
var offset = _this3.getOffsetForStatus(CLOSED),
duration = _this3.props.duration;
_this3.animate(el, offset, duration, 'ease', function () {
return _this3.safeSetState({ status: CLOSED }, function () {
_this3.props.onClose();
});
});
});
},
getOffsetForStatus: function getOffsetForStatus(status) {
var _CLOSED$CLOSING$OPENI;
if (this.state.initialRender) return {};
var _in = properties('top', this.props.dropUp ? '100%' : '-100%'),
out = properties('top', 0);
return (_CLOSED$CLOSING$OPENI = {}, _CLOSED$CLOSING$OPENI[CLOSED] = _in, _CLOSED$CLOSING$OPENI[CLOSING] = out, _CLOSED$CLOSING$OPENI[OPENING] = _in, _CLOSED$CLOSING$OPENI[OPEN] = out, _CLOSED$CLOSING$OPENI)[status] || {};
},
height: function height() {
var container = _compat2.default.findDOMNode(this),
content = container.firstChild,
margin = parseInt((0, _style2.default)(content, 'margin-top'), 10) + parseInt((0, _style2.default)(content, 'margin-bottom'), 10);
var old = container.style.display,
height = void 0;
container.style.display = 'block';
height = ((0, _height2.default)(content) || 0) + (isNaN(margin) ? 0 : margin);
container.style.display = old;
return height;
},
isTransitioning: function isTransitioning() {
return this.state.status === OPENING || this.state.status === CLOSED;
},
animate: function animate(el, props, dur, easing, cb) {
this._transition = _configuration2.default.animate(el, props, dur, easing, this.setNextCallback(cb));
},
cancelNextCallback: function cancelNextCallback() {
if (this._transition && this._transition.cancel) {
this._transition.cancel();
this._transition = null;
}
if (this.nextCallback) {
this.nextCallback.cancel();
this.nextCallback = null;
}
},
safeSetState: function safeSetState(nextState, callback) {
this.setState(nextState, this.setNextCallback(callback));
},
setNextCallback: function setNextCallback(callback) {
var _this4 = this;
var active = true;
this.nextCallback = function (event) {
if (active) {
active = false;
_this4.nextCallback = null;
callback(event);
}
};
this.nextCallback.cancel = function () {
return active = false;
};
return this.nextCallback;
}
});
function childKey(children) {
var nextChildMapping = _react2.default.Children.map(children, function (c) {
return c;
});
for (var key in nextChildMapping) {
return key;
}
}
module.exports = exports['default']; |
var utils = require("./utils");
var proc = require('process');
var chp = require('child_process');
var val;
module.exports = {
init : (value)=>{
val = value;
var svc = utils.obj(val);
if(svc.indexOf('services') < 0) {
console.log("Service can't defined.");
proc.exit(1);
}
var app = utils.obj(val.services);
app.forEach((v)=>{
module.exports.prs(v);
});
},
execution : (keyMap)=>{
var name = keyMap.name;
var cmd = "docker service rm "+name;
chp.exec(cmd,(e, stdout, stderr)=> {
if(stdout){
console.log("delete :"+stdout);
}
if(stderr){
console.log(stderr)
}
})
},
prs : (key)=>{
var keyMap = {
name: key
}
module.exports.execution(keyMap);
}
}
|
const extractSeparator = (source, separators) => {
return separators.filter(separator=>{
let cache = -1
return source.split('\n').every(line=>{
if(!line) { return true }
let length = line.split(separator).length
if(cache < 0) { cache = length }
return length>1 && cache===length
})
})[0]
}
const parseCsv = (rawData) => {
let lines = rawData.split('\r\n')
let separator = extractSeparator(lines[0], [',', ';'])
// return lines.map(line => line.split(/(?:(?!("\w+))),(?:(?!(\w+")))/).filter(e=>e!==undefined))
return lines.map(line => line.split(separator))
}
export default parseCsv
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M3 3v8h8V3H3zm6 6H5V5h4v4zm-6 4v8h8v-8H3zm6 6H5v-4h4v4zm4-16v8h8V3h-8zm6 6h-4V5h4v4zm-6 4v8h8v-8h-8zm6 6h-4v-4h4v4z" />
, 'GridViewOutlined');
|
Module.register("MMM-Pushbullet",{
new_notification: false,
// Default module config.
defaults: {
api_key: '',
no_message_text: 'No new notifications',
message_read_time: 30000,
message_length: 10,
show_message_body: true,
},
start: function() {
self = this;
Log.info('Starting module: ' + this.name);
this.sendSocketNotification('Starting node_helper');
this.sendSocketNotification('INIT', this.config.api_key);
this.title = this.config.no_message_text;
setTimeout(function() {
self.updateDom();
}, 1000);
},
// Override dom generator.
getDom: function(){
no_message_text = this.config.no_message_text;
var wrapper = document.createElement("div");
var header = document.createElement("header");
header.classList.add("align-left");
var logo = document.createElement("i");
logo.classList.add("fa", "fa-bell-o", "logo");
header.appendChild(logo);
var banner = document.createElement("span");
banner.innerHTML = this.translate("NOTIFICATIONS");
header.appendChild(banner);
wrapper.appendChild(header);
var message_from = document.createElement("div");
message_from.classList.add("dimmed", "light", "small");
if (this.new_notification === false) {
message_from.innerHTML = this.config.no_message_text;
wrapper.appendChild(message_from);
}else{
message_from.classList.add("bright");
message_from.innerHTML = this.payload.title;
wrapper.appendChild(message_from);
// Show the body if we set it to true
if (this.config.show_message_body === true) {
var i = this.payload.message;
var message_body_wrapper = document.createElement("div");
message_body_wrapper.setAttribute("id", "message_body_wrapper");
var message_body;
var regexp = /\d+ new messages/gi;
i.split('\n').forEach(function(j) {
// If an element matches the string 'new messages' then skip it.
if (! j.match(regexp)) {
message_body = document.createElement("div");
message_body.classList.add("dimmed", "light", "xsmall", "address" );
message_body.innerHTML = j;
message_body_wrapper.appendChild(message_body);
}
});
wrapper.appendChild(message_body_wrapper);
}
// Remove notifications after n milliseconds if option is non-zero
if (this.config.message_read_time !== 0) {
that = this;
setTimeout(function() {
message_from.classList.remove("bright");
message_from.innerHTML = no_message_text;
if (that.config.show_message_body === true) {
var element = document.getElementById("message_body_wrapper");
if (element !== null) {
element.parentNode.removeChild(element);
}
}
}, this.config.message_read_time);
}
}
//return notification_area;
return wrapper;
},
// Define required scripts.
getStyles: function() {
return ["MMM-Pushbullet.css", "font-awesome.css"];
},
getTranslations: function () {
return {
en: "translations/en.json",
};
},
// Socket reponse
socketNotificationReceived: function(notification, payload) {
if (notification === 'PUSH') {
console.log('Recieved push notification.');
this.payload = payload
this.new_notification = true;
this.updateDom(1000);
}
},
}); |
/*
---
name: BehaviorAPI
description: HTML getters for Behavior's API model.
requires: [Core/Class, /Element.Data]
provides: [BehaviorAPI]
...
*/
(function(){
//see Docs/BehaviorAPI.md for documentation of public methods.
var reggy = /[^a-z0-9\-]/gi,
dots = /\./g;
window.BehaviorAPI = new Class({
element: null,
prefix: '',
defaults: {},
initialize: function(element, prefix){
this.element = element;
this.prefix = prefix.toLowerCase().replace(dots, '-').replace(reggy, '');
},
/******************
* PUBLIC METHODS
******************/
get: function(/* name[, name, name, etc] */){
if (arguments.length > 1) return this._getObj(Array.from(arguments));
return this._getValue(arguments[0]);
},
getAs: function(/*returnType, name, defaultValue OR {name: returnType, name: returnType, etc}*/){
if (typeOf(arguments[0]) == 'object') return this._getValuesAs.apply(this, arguments);
return this._getValueAs.apply(this, arguments);
},
require: function(/* name[, name, name, etc] */){
for (var i = 0; i < arguments.length; i++){
if (this._getValue(arguments[i]) == undefined) throw new Error('Could not retrieve ' + this.prefix + '-' + arguments[i] + ' option from element.');
}
return this;
},
requireAs: function(returnType, name /* OR {name: returnType, name: returnType, etc}*/){
var val;
if (typeOf(arguments[0]) == 'object'){
for (var objName in arguments[0]){
val = this._getValueAs(arguments[0][objName], objName);
if (val === undefined || val === null) throw new Error("Could not retrieve " + this.prefix + '-' + objName + " option from element.");
}
} else {
val = this._getValueAs(returnType, name);
if (val === undefined || val === null) throw new Error("Could not retrieve " + this.prefix + '-' + name + " option from element.");
}
return this;
},
setDefault: function(name, value /* OR {name: value, name: value, etc }*/){
if (typeOf(arguments[0]) == 'object'){
for (var objName in arguments[0]){
this.setDefault(objName, arguments[0][objName]);
}
return this;
}
name = name.camelCase();
switch (typeOf(value)){
case 'object': value = Object.clone(value); break;
case 'array': value = Array.clone(value); break;
case 'hash': value = new Hash(value); break;
}
this.defaults[name] = value;
var setValue = this._getValue(name);
var options = this._getOptions();
if (setValue == null){
options[name] = value;
} else if (typeOf(setValue) == 'object' && typeOf(value) == 'object') {
options[name] = Object.merge({}, value, setValue);
}
return this;
},
refreshAPI: function(){
delete this.options;
this.setDefault(this.defaults);
return;
},
/******************
* PRIVATE METHODS
******************/
//given an array of names, returns an object of key/value pairs for each name
_getObj: function(names){
var obj = {};
names.each(function(name){
var value = this._getValue(name);
if (value !== undefined) obj[name] = value;
}, this);
return obj;
},
//gets the data-behaviorname-options object and parses it as JSON
_getOptions: function(){
try {
if (!this.options){
var options = this.element.getData(this.prefix + '-options', '{}').trim();
if (options === "") return this.options = {};
if (options && options.substring(0,1) != '{') options = '{' + options + '}';
var isSecure = JSON.isSecure(options);
if (!isSecure) throw new Error('warning, options value for element is not parsable, check your JSON format for quotes, etc.');
this.options = isSecure ? JSON.decode(options, false) : {};
for (option in this.options) {
this.options[option.camelCase()] = this.options[option];
}
}
} catch (e){
throw new Error('Could not get options from element; check your syntax. ' + this.prefix + '-options: "' + this.element.getData(this.prefix + '-options', '{}') + '"');
}
return this.options;
},
//given a name (string) returns the value for it
_getValue: function(name){
name = name.camelCase();
var options = this._getOptions();
if (!options.hasOwnProperty(name)){
var inline = this.element.getData(this.prefix + '-' + name.hyphenate());
if (inline) options[name] = inline;
}
return options[name];
},
//given a Type and a name (string) returns the value for it coerced to that type if possible
//else returns the defaultValue or null
_getValueAs: function(returnType, name, defaultValue){
var value = this._getValue(name);
if (value == null || value == undefined) return defaultValue;
var coerced = this._coerceFromString(returnType, value);
if (coerced == null) throw new Error("Could not retrieve value '" + name + "' as the specified type. Its value is: " + value);
return coerced;
},
//given an object of name/Type pairs, returns those as an object of name/value (as specified Type) pairs
_getValuesAs: function(obj){
var returnObj = {};
for (var name in obj){
returnObj[name] = this._getValueAs(obj[name], name);
}
return returnObj;
},
//attempts to run a value through the JSON parser. If the result is not of that type returns null.
_coerceFromString: function(toType, value){
if (typeOf(value) == 'string' && toType != String){
if (JSON.isSecure(value)) value = JSON.decode(value, false);
}
if (instanceOf(value, toType)) return value;
return null;
}
});
})();
|
var loadSettings, mouseDown, saveRelease, resetRelease, fetchSettings;
var fade, save, saveClicked, resetClicked, reset, linkHintCharacters, commandBarCSS, commandBarOnBottom, hoverDelay, settings, editor, mappingContainerFadeOut, usedPlaceholder, firstLoad;
var placeholder = '<- Click here for command names\n\nCommands are prefixed by "map" and "unmap"\n\nExample:\n # unmap j\n # map j scrollDown\n\nCommands can also be mapped to command mode commands\n\nExample:\n # map v :tabopen http://www.google.com\n\nCommand mode commands followed by <CR> executes the command immediately (enter does not need to be pressed)\n # map v :tabopen http://www.google.com<CR>\n\nModifier keys may also be mapped (if not already used by Chrome or the operating system)\n\nExample:\n "<C-" => Control key\n # map <C-i> goToInput\n "<M-" => Meta key (Windows key / Command key [Mac])\n # map <M-i> goToInput\n "<A-" => Alt key\n # map <A-i> goToInput\n';
loadSettings = function () {
for (var key in settings) {
if (typeof settings[key] === "boolean") {
document.getElementById(key).checked = settings[key];
} else {
document.getElementById(key).value = settings[key];
}
}
if (editor) {
editor.setValue(settings.commandBarCSS);
}
if (document.getElementById("mappings").value.trim() === "") {
usedPlaceholder = true;
document.getElementById("mappings").value = placeholder;
}
document.getElementById("mappings").addEventListener("focus", onFocus, false);
document.getElementById("mappings").addEventListener("blur", onBlur, false);
};
resetRelease = function() {
if (resetClicked) {
chrome.runtime.sendMessage({setDefault: true});
fetchSettings();
}
};
saveRelease = function() {
if (saveClicked) {
for (var key in settings) {
if (typeof settings[key] === "boolean") {
settings[key] = document.getElementById(key).checked;
} else if (key === "commandBarCSS") {
settings[key] = editor.getValue();
} else if (key === "mappings" && usedPlaceholder) {
settings[key] = "";
} else {
settings[key] = document.getElementById(key).value;
}
}
chrome.storage.sync.set({settings: settings});
chrome.runtime.sendMessage({reloadSettings: true});
save.innerText = "Saved";
setTimeout(function () {
save.innerText = "Save";
}, 3000);
}
};
fadeTransitionEnd = function(e) {
if (e.target.id === "mappingContainer" && e.propertyName === "opacity" && mappingContainerFadeOut) {
mappingContainerFadeOut = false;
mappingContainer.style.display = "none";
}
};
mouseDown = function (e) {
saveClicked = false;
resetClicked = false;
if (e.target.id === "save_button") {
saveClicked = true;
} else if (e.target.id === "reset_button") {
resetClicked = true;
} else if (e.target.id === "clearHistory") {
localStorage.search = "";
localStorage.url = "";
localStorage.action = "";
} else if (e.target.id === "close") {
mappingContainer.style.opacity = "0";
mappingContainerFadeOut = true;
}
save.innerText = "Save";
};
fetchSettings = function () {
chrome.runtime.sendMessage({getSettings: true});
};
editMode = function (e) {
if (editor) {
if (e.target.value === "Vim") {
editor.setOption("keyMap", "vim");
} else {
editor.setOption("keyMap", "default");
}
}
};
onFocus = function(e) {
if (e.target.id === "mappings" && usedPlaceholder) {
document.getElementById("mappings").value = "";
usedPlaceholder = true;
} else if (e.target.id !== "mappings" && document.getElementById("mappings").value.trim() === "") {
usedPlaceholder = true;
document.getElementById("mappings").value = placeholder;
}
};
onBlur = function() {
if (document.getElementById("mappings").value.trim() === "") {
usedPlaceholder = true;
document.getElementById("mappings").value = placeholder;
} else {
usedPlaceholder = false;
}
};
document.addEventListener("DOMContentLoaded", function () {
firstLoad = true;
document.body.spellcheck = false;
save = document.getElementById("save_button");
reset = document.getElementById("reset_button");
smoothScroll = document.getElementById("smoothScroll");
mappingContainer = document.getElementById("mappingContainer");
linkHintCharacters = document.getElementById("linkHintCharacters");
commandBarOnBottom = document.getElementById("commandBarOnBottom");
commandBarCSS = document.getElementById("commandBarCSS");
dropDown = document.getElementById("edit_mode");
fetchSettings(function () {
editor = CodeMirror.fromTextArea(document.getElementById("commandBarCSS"), {lineNumbers: true});
});
document.addEventListener("mousedown", mouseDown, false);
document.addEventListener("transitionend", fadeTransitionEnd, false);
dropDown.addEventListener("change", editMode, false);
save.addEventListener("mouseup", saveRelease, false);
reset.addEventListener("mouseup", resetRelease, false);
});
chrome.extension.onMessage.addListener(function(request) {
if (request.action === "sendSettings") {
settings = request.settings;
if (firstLoad) {
editor = CodeMirror.fromTextArea(document.getElementById("commandBarCSS"), {lineNumbers: true});
firstLoad = false;
}
loadSettings();
}
});
|
#!/usr/bin/env node
"use strict";
var Promise = require("babybird");
var browserify = require("browserify");
var concat = require("concat-stream");
var fs = require("fs");
var moment = require("moment");
var path = require("path");
var shell = require("shelljs");
var version = require("../package.json").version;
var buildDir = path.join(__dirname, "../dist");
var srcDir = path.join(__dirname, "../src");
var testsDir = path.join(__dirname, "../tests");
var RIGHT_NOW = moment().locale("en-US").format("D-MMMM-YYYY HH:mm:ss");
var LICENSE = [
"/*!",
shell.cat(path.join(__dirname, "../LICENSE")),
"*/",
"/* Version v" + version + ", Build time: " + RIGHT_NOW + " */"
].map(function(s) {
return s.trim();
}).join("\n");
function writeFile(filename, contents) {
return new Promise(function(resolve, reject) {
var fullname = path.join(buildDir, filename);
console.log("Writing", path.relative(process.cwd(), fullname));
fs.writeFile(fullname, contents, "utf8", function(err) {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
function concatP() {
var resolve;
var promise = new Promise(function(r) {
resolve = r;
});
var stream = concat(resolve);
return {
stream: stream,
promise: promise
};
}
function build(target, filename) {
var results = [null];
results[0] = new Promise(function(resolve, reject) {
var bundle = browserify();
bundle.require(path.join(srcDir, "index.js"), { expose: "parserlib" });
if (target === "split") {
bundle.require(path.join(srcDir, "util"),
{ expose: "parserlib-core" });
var css = concatP();
results.push(css.promise);
var stub = concatP();
results.push(stub.promise);
bundle.plugin("factor-bundle", {
outputs: [ css.stream, stub.stream ]
});
}
bundle.bundle(function(err, src) {
if (err) {
reject(err);
} else {
resolve(src);
}
});
});
return Promise.all(results).then(function(results) {
if (target === "split") {
var core = results[0];
var css = results[1];
var stub = results[2];
core = [
LICENSE,
"var parserlib = (function () {",
"var require;",
core,
stub,
"return { _require: require, util: require('parserlib-core') };",
"})();"
].join("\n");
css = [
LICENSE,
"(function () {",
"var require = parserlib._require;",
css,
"parserlib.css = require('parserlib').css;",
"})();"
].join("\n");
return Promise.all([
writeFile("parserlib-core.js", core),
writeFile("parserlib-css.js", css)
]);
} else {
var src = results[0];
src = [
LICENSE,
"var parserlib = (function () {",
"var require;",
src,
"return require('parserlib');",
"})();"
];
if (target === "node") {
src.push("module.exports = parserlib;");
}
return writeFile(filename, src.join("\n"));
}
});
}
function buildTests(filename) {
// Build the list of test files
var tests = shell.find(testsDir).filter(function(file) {
return file.match(/\.js$/);
});
return new Promise(function(resolve, reject) {
var bundle = browserify();
tests.forEach(function(f, i) {
bundle.require(f, { expose: "test"+i });
});
bundle.exclude("yuitest");
bundle.exclude(path.join(srcDir, "index.js"));
bundle.bundle(function(err, src) {
if (err) {
reject(err);
} else {
resolve(src);
}
});
}).then(function(src) {
src = [
LICENSE,
"(function () {",
"var require = function(x) {",
"if (x==='yuitest') { return YUITest; }",
"return parserlib;",
"};",
src
].concat(tests.map(function(f, i) {
return "require('test"+i+"');";
})).concat([
"})();"
]);
writeFile(filename, src.join("\n"));
});
}
Promise.resolve().then(function() {
// Ensure build directory is present.
shell.mkdir("-p", buildDir);
}).then(function() {
return build("full", "parserlib.js");
}).then(function() {
return build("node", "node-parserlib.js");
}).then(function() {
return build("split");
}).then(function() {
return buildTests("parserlib-tests.js");
});
|
'use strict';
var fs = require('fs');
var path = require('path');
var router = require('koa-router')();
module.exports = function (server) {
fs.readdirSync(path.join('lib', 'auth')).forEach(function (file) {
require('./auth/' + file)(router);
});
router.prefix('/api/auth');
server.use(router.routes());
};
|
import decorator from './decorator';
/**
* @decorator
* Provides easy onexecute wrapping. The supplied function is executed last.
*
* @param fn - Function to be executed on execution of the method.
*
* @returns Method decorator.
*/
export function onexecute(fn) {
return decorator((target, propertyKey, descriptor) => {
descriptor.onexecute(fn);
});
}
export default onexecute;
//# sourceMappingURL=onexecute.js.map |
var root = 'https://dl.dropboxusercontent.com/u/5613860/audio/nino_rota_trimmed/'
root = '/audio/'
var pool = [
{
"id": "whistling",
"src": root + 'four_devices_computer.mp3'
},
{
"id": "snare",
"src": root + 'snare.mp3'
},
{
"id": "cymbals",
"src": root + 'cymbals.mp3'
},
{
"id": "bass_drum",
"src": root + 'bass_drum.mp3'
},
{
"id": "sax1",
"src": root + 'sax1.mp3'
}
]
var tracks = [
{
"name": "track 1",
"type": "audioRegions",
"regions": [
{
"clipId": "whistling",
"clipStart": 0,
"clipEnd": 10,
"startTime": 4
}
],
"over": false,
"pan": 0,
"volume": 60
},
{
"name": "track 2",
"type": "audioRegions",
"regions": [
{
"clipId": "whistling",
"clipStart": 0,
"clipEnd": 1,
"startTime": 0
},
{
"clipId": "whistling",
"clipStart": 1,
"clipEnd": 3,
"startTime": 4
}
],
"over": false,
"pan": 0,
"volume": 60
}
] |
var JSONEditor = function(element,options) {
if (!(element instanceof Element)) {
throw new Error('element should be an instance of Element');
}
options = $extend({},JSONEditor.defaults.options,options||{});
this.element = element;
this.options = options;
this.init();
};
JSONEditor.prototype = {
// necessary since we remove the ctor property by doing a literal assignment. Without this
// the $isplainobject function will think that this is a plain object.
constructor: JSONEditor,
init: function() {
var self = this;
this.ready = false;
this.copyClipboard = null;
var theme_class = JSONEditor.defaults.themes[this.options.theme || JSONEditor.defaults.theme];
if(!theme_class) throw "Unknown theme " + (this.options.theme || JSONEditor.defaults.theme);
this.schema = this.options.schema;
this.theme = new theme_class();
this.template = this.options.template;
this.refs = this.options.refs || {};
this.uuid = 0;
this.__data = {};
var icon_class = JSONEditor.defaults.iconlibs[this.options.iconlib || JSONEditor.defaults.iconlib];
if(icon_class) this.iconlib = new icon_class();
this.root_container = this.theme.getContainer();
this.element.appendChild(this.root_container);
this.translate = this.options.translate || JSONEditor.defaults.translate;
// Fetch all external refs via ajax
this._loadExternalRefs(this.schema, function() {
self._getDefinitions(self.schema);
// Validator options
var validator_options = {};
if(self.options.custom_validators) {
validator_options.custom_validators = self.options.custom_validators;
}
self.validator = new JSONEditor.Validator(self,null,validator_options);
// Create the root editor
var schema = self.expandRefs(self.schema);
var editor_class = self.getEditorClass(schema);
self.root = self.createEditor(editor_class, {
jsoneditor: self,
schema: schema,
required: true,
container: self.root_container
});
self.root.preBuild();
self.root.build();
self.root.postBuild();
// Starting data
if(self.options.hasOwnProperty('startval')) self.root.setValue(self.options.startval);
self.validation_results = self.validator.validate(self.root.getValue());
self.root.showValidationErrors(self.validation_results);
self.ready = true;
// Fire ready event asynchronously
window.requestAnimationFrame(function() {
if(!self.ready) return;
self.validation_results = self.validator.validate(self.root.getValue());
self.root.showValidationErrors(self.validation_results);
self.trigger('ready');
self.trigger('change');
});
});
},
getValue: function() {
if(!this.ready) throw "JSON Editor not ready yet. Listen for 'ready' event before getting the value";
return this.root.getValue();
},
setValue: function(value) {
if(!this.ready) throw "JSON Editor not ready yet. Listen for 'ready' event before setting the value";
this.root.setValue(value);
return this;
},
validate: function(value) {
if(!this.ready) throw "JSON Editor not ready yet. Listen for 'ready' event before validating";
// Custom value
if(arguments.length === 1) {
return this.validator.validate(value);
}
// Current value (use cached result)
else {
return this.validation_results;
}
},
destroy: function() {
if(this.destroyed) return;
if(!this.ready) return;
this.schema = null;
this.options = null;
this.root.destroy();
this.root = null;
this.root_container = null;
this.validator = null;
this.validation_results = null;
this.theme = null;
this.iconlib = null;
this.template = null;
this.__data = null;
this.ready = false;
this.element.innerHTML = '';
this.destroyed = true;
},
on: function(event, callback) {
this.callbacks = this.callbacks || {};
this.callbacks[event] = this.callbacks[event] || [];
this.callbacks[event].push(callback);
return this;
},
off: function(event, callback) {
// Specific callback
if(event && callback) {
this.callbacks = this.callbacks || {};
this.callbacks[event] = this.callbacks[event] || [];
var newcallbacks = [];
for(var i=0; i<this.callbacks[event].length; i++) {
if(this.callbacks[event][i]===callback) continue;
newcallbacks.push(this.callbacks[event][i]);
}
this.callbacks[event] = newcallbacks;
}
// All callbacks for a specific event
else if(event) {
this.callbacks = this.callbacks || {};
this.callbacks[event] = [];
}
// All callbacks for all events
else {
this.callbacks = {};
}
return this;
},
trigger: function(event) {
if(this.callbacks && this.callbacks[event] && this.callbacks[event].length) {
for(var i=0; i<this.callbacks[event].length; i++) {
this.callbacks[event][i].apply(this, []);
}
}
return this;
},
setOption: function(option, value) {
if(option === "show_errors") {
this.options.show_errors = value;
this.onChange();
}
// Only the `show_errors` option is supported for now
else {
throw "Option "+option+" must be set during instantiation and cannot be changed later";
}
return this;
},
getEditorClass: function(schema) {
var classname;
schema = this.expandSchema(schema);
$each(JSONEditor.defaults.resolvers,function(i,resolver) {
var tmp = resolver(schema);
if(tmp) {
if(JSONEditor.defaults.editors[tmp]) {
classname = tmp;
return false;
}
}
});
if(!classname) throw "Unknown editor for schema "+JSON.stringify(schema);
if(!JSONEditor.defaults.editors[classname]) throw "Unknown editor "+classname;
return JSONEditor.defaults.editors[classname];
},
createEditor: function(editor_class, options) {
options = $extend({},editor_class.options||{},options);
return new editor_class(options);
},
onChange: function() {
if(!this.ready) return;
if(this.firing_change) return;
this.firing_change = true;
var self = this;
window.requestAnimationFrame(function() {
self.firing_change = false;
if(!self.ready) return;
// Validate and cache results
self.validation_results = self.validator.validate(self.root.getValue());
if(self.options.show_errors !== "never") {
self.root.showValidationErrors(self.validation_results);
}
else {
self.root.showValidationErrors([]);
}
// Fire change event
self.trigger('change');
});
return this;
},
compileTemplate: function(template, name) {
name = name || JSONEditor.defaults.template;
var engine;
// Specifying a preset engine
if(typeof name === 'string') {
if(!JSONEditor.defaults.templates[name]) throw "Unknown template engine "+name;
engine = JSONEditor.defaults.templates[name]();
if(!engine) throw "Template engine "+name+" missing required library.";
}
// Specifying a custom engine
else {
engine = name;
}
if(!engine) throw "No template engine set";
if(!engine.compile) throw "Invalid template engine set";
return engine.compile(template);
},
_data: function(el,key,value) {
// Setting data
if(arguments.length === 3) {
var uuid;
if(el.hasAttribute('data-jsoneditor-'+key)) {
uuid = el.getAttribute('data-jsoneditor-'+key);
}
else {
uuid = this.uuid++;
el.setAttribute('data-jsoneditor-'+key,uuid);
}
this.__data[uuid] = value;
}
// Getting data
else {
// No data stored
if(!el.hasAttribute('data-jsoneditor-'+key)) return null;
return this.__data[el.getAttribute('data-jsoneditor-'+key)];
}
},
registerEditor: function(editor) {
this.editors = this.editors || {};
this.editors[editor.path] = editor;
return this;
},
unregisterEditor: function(editor) {
this.editors = this.editors || {};
this.editors[editor.path] = null;
return this;
},
getEditor: function(path) {
if(!this.editors) return;
return this.editors[path];
},
watch: function(path,callback) {
this.watchlist = this.watchlist || {};
this.watchlist[path] = this.watchlist[path] || [];
this.watchlist[path].push(callback);
return this;
},
unwatch: function(path,callback) {
if(!this.watchlist || !this.watchlist[path]) return this;
// If removing all callbacks for a path
if(!callback) {
this.watchlist[path] = null;
return this;
}
var newlist = [];
for(var i=0; i<this.watchlist[path].length; i++) {
if(this.watchlist[path][i] === callback) continue;
else newlist.push(this.watchlist[path][i]);
}
this.watchlist[path] = newlist.length? newlist : null;
return this;
},
notifyWatchers: function(path) {
if(!this.watchlist || !this.watchlist[path]) return this;
for(var i=0; i<this.watchlist[path].length; i++) {
this.watchlist[path][i]();
}
},
isEnabled: function() {
return !this.root || this.root.isEnabled();
},
enable: function() {
this.root.enable();
},
disable: function() {
this.root.disable();
},
_getDefinitions: function(schema,path) {
path = path || '#/definitions/';
if(schema.definitions) {
for(var i in schema.definitions) {
if(!schema.definitions.hasOwnProperty(i)) continue;
this.refs[path+i] = schema.definitions[i];
if(schema.definitions[i].definitions) {
this._getDefinitions(schema.definitions[i],path+i+'/definitions/');
}
}
}
},
_getExternalRefs: function(schema) {
var refs = {};
var merge_refs = function(newrefs) {
for(var i in newrefs) {
if(newrefs.hasOwnProperty(i)) {
refs[i] = true;
}
}
};
if(schema.$ref && typeof schema.$ref !== "object" && schema.$ref.substr(0,1) !== "#" && !this.refs[schema.$ref]) {
refs[schema.$ref] = true;
}
for(var i in schema) {
if(!schema.hasOwnProperty(i)) continue;
if(schema[i] && typeof schema[i] === "object" && Array.isArray(schema[i])) {
for(var j=0; j<schema[i].length; j++) {
if(schema[i][j] && typeof schema[i][j]==="object") {
merge_refs(this._getExternalRefs(schema[i][j]));
}
}
}
else if(schema[i] && typeof schema[i] === "object") {
merge_refs(this._getExternalRefs(schema[i]));
}
}
return refs;
},
_getFileBase: function() {
var fileBase = this.options.ajaxBase;
if (typeof fileBase === 'undefined') {
fileBase = this._getFileBaseFromFileLocation(document.location.toString());
}
return fileBase;
},
_getFileBaseFromFileLocation: function(fileLocationString) {
var pathItems = fileLocationString.split("/");
pathItems.pop();
return pathItems.join("/")+"/";
},
_loadExternalRefs: function(schema, callback, fileBase) {
fileBase = fileBase || this._getFileBase();
var self = this;
var refs = this._getExternalRefs(schema);
var done = 0, waiting = 0, callback_fired = false;
$each(refs,function(url) {
if(self.refs[url]) return;
if(!self.options.ajax) throw "Must set ajax option to true to load external ref "+url;
self.refs[url] = 'loading';
waiting++;
var fetchUrl=url;
if( fileBase!=url.substr(0,fileBase.length) && "http"!=url.substr(0,4) && "/"!=url.substr(0,1)) fetchUrl=fileBase+url;
var r = new XMLHttpRequest();
r.open("GET", fetchUrl, true);
if(self.options.ajaxCredentials) r.withCredentials=self.options.ajaxCredentials;
r.onreadystatechange = function () {
if (r.readyState != 4) return;
// Request succeeded
if(r.status === 200) {
var response;
try {
response = JSON.parse(r.responseText);
}
catch(e) {
window.console.log(e);
throw "Failed to parse external ref "+fetchUrl;
}
if(!response || typeof response !== "object") throw "External ref does not contain a valid schema - "+fetchUrl;
self.refs[url] = response;
self._loadExternalRefs(response,function() {
done++;
if(done >= waiting && !callback_fired) {
callback_fired = true;
callback();
}
}, self._getFileBaseFromFileLocation(fetchUrl));
}
// Request failed
else {
window.console.log(r);
throw "Failed to fetch ref via ajax- "+url;
}
};
r.send();
});
if(!waiting) {
callback();
}
},
expandRefs: function(schema) {
schema = $extend({},schema);
while (schema.$ref) {
var ref = schema.$ref;
delete schema.$ref;
if(!this.refs[ref]) ref = decodeURIComponent(ref);
schema = this.extendSchemas(schema,this.refs[ref]);
}
return schema;
},
expandSchema: function(schema) {
var self = this;
var extended = $extend({},schema);
var i;
// Version 3 `type`
if(typeof schema.type === 'object') {
// Array of types
if(Array.isArray(schema.type)) {
$each(schema.type, function(key,value) {
// Schema
if(typeof value === 'object') {
schema.type[key] = self.expandSchema(value);
}
});
}
// Schema
else {
schema.type = self.expandSchema(schema.type);
}
}
// Version 3 `disallow`
if(typeof schema.disallow === 'object') {
// Array of types
if(Array.isArray(schema.disallow)) {
$each(schema.disallow, function(key,value) {
// Schema
if(typeof value === 'object') {
schema.disallow[key] = self.expandSchema(value);
}
});
}
// Schema
else {
schema.disallow = self.expandSchema(schema.disallow);
}
}
// Version 4 `anyOf`
if(schema.anyOf) {
$each(schema.anyOf, function(key,value) {
schema.anyOf[key] = self.expandSchema(value);
});
}
// Version 4 `dependencies` (schema dependencies)
if(schema.dependencies) {
$each(schema.dependencies,function(key,value) {
if(typeof value === "object" && !(Array.isArray(value))) {
schema.dependencies[key] = self.expandSchema(value);
}
});
}
// Version 4 `not`
if(schema.not) {
schema.not = this.expandSchema(schema.not);
}
// allOf schemas should be merged into the parent
if(schema.allOf) {
for(i=0; i<schema.allOf.length; i++) {
extended = this.extendSchemas(extended,this.expandSchema(schema.allOf[i]));
}
delete extended.allOf;
}
// extends schemas should be merged into parent
if(schema["extends"]) {
// If extends is a schema
if(!(Array.isArray(schema["extends"]))) {
extended = this.extendSchemas(extended,this.expandSchema(schema["extends"]));
}
// If extends is an array of schemas
else {
for(i=0; i<schema["extends"].length; i++) {
extended = this.extendSchemas(extended,this.expandSchema(schema["extends"][i]));
}
}
delete extended["extends"];
}
// parent should be merged into oneOf schemas
if(schema.oneOf) {
var tmp = $extend({},extended);
delete tmp.oneOf;
for(i=0; i<schema.oneOf.length; i++) {
extended.oneOf[i] = this.extendSchemas(this.expandSchema(schema.oneOf[i]),tmp);
}
}
return this.expandRefs(extended);
},
extendSchemas: function(obj1, obj2) {
obj1 = $extend({},obj1);
obj2 = $extend({},obj2);
var self = this;
var extended = {};
$each(obj1, function(prop,val) {
// If this key is also defined in obj2, merge them
if(typeof obj2[prop] !== "undefined") {
// Required and defaultProperties arrays should be unioned together
if((prop === 'required'||prop === 'defaultProperties') && typeof val === "object" && Array.isArray(val)) {
// Union arrays and unique
extended[prop] = val.concat(obj2[prop]).reduce(function(p, c) {
if (p.indexOf(c) < 0) p.push(c);
return p;
}, []);
}
// Type should be intersected and is either an array or string
else if(prop === 'type' && (typeof val === "string" || Array.isArray(val))) {
// Make sure we're dealing with arrays
if(typeof val === "string") val = [val];
if(typeof obj2.type === "string") obj2.type = [obj2.type];
// If type is only defined in the first schema, keep it
if(!obj2.type || !obj2.type.length) {
extended.type = val;
}
// If type is defined in both schemas, do an intersect
else {
extended.type = val.filter(function(n) {
return obj2.type.indexOf(n) !== -1;
});
}
// If there's only 1 type and it's a primitive, use a string instead of array
if(extended.type.length === 1 && typeof extended.type[0] === "string") {
extended.type = extended.type[0];
}
// Remove the type property if it's empty
else if(extended.type.length === 0) {
delete extended.type;
}
}
// All other arrays should be intersected (enum, etc.)
else if(typeof val === "object" && Array.isArray(val)){
extended[prop] = val.filter(function(n) {
return obj2[prop].indexOf(n) !== -1;
});
}
// Objects should be recursively merged
else if(typeof val === "object" && val !== null) {
extended[prop] = self.extendSchemas(val,obj2[prop]);
}
// Otherwise, use the first value
else {
extended[prop] = val;
}
}
// Otherwise, just use the one in obj1
else {
extended[prop] = val;
}
});
// Properties in obj2 that aren't in obj1
$each(obj2, function(prop,val) {
if(typeof obj1[prop] === "undefined") {
extended[prop] = val;
}
});
return extended;
},
setCopyClipboardContents: function(value) {
this.copyClipboard = value;
},
getCopyClipboardContents: function() {
return this.copyClipboard;
}
};
JSONEditor.defaults = {
themes: {},
templates: {},
iconlibs: {},
editors: {},
languages: {},
resolvers: [],
custom_validators: []
};
|
AIWeightData = {
"weightSets": {
"test": {
"weights": {
"randomBias": 0.28458717884495854,
"upBias": 0.3640812458470464,
"downBias": -0.9047143049538136,
"leftBias": 0.3564878744073212,
"rightBias": -0.09058581106364727,
"emptyCells": 0.7221773574128747,
"hPairs": 0.42885784711688757,
"vPairs": 0.5457309461198747,
"maxVal": 0.2546499357558787,
"filledCols": -0.5565687231719494,
"filledRows": -0.02901927148923278,
"lockedCells": -0.19933633087202907
},
"rawFitness": 12303.2,
"fitness": 1427825897.9845643,
"fitnessMeasure": "score"
},
"lookahead_2": {
"weights": {
"randomBias": 0.02809830429032445,
"upBias": -0.9495922466740012,
"downBias": 0.8746085399761796,
"leftBias": 0.887634779792279,
"rightBias": 0.16475377837195992,
"emptyCells": 0.3643483077175915,
"hPairs": 0.8223549798130989,
"vPairs": 0.9044259455986321,
"maxVal": 0.5932102198712528,
"filledCols": 0.08707817969843745,
"filledRows": -0.5868596811778843,
"lockedCells": -0.17454146826639771
},
"rawFitness": 10117.6,
"fitness": 10117.6,
"fitnessMeasure": "score"
},
"lookahead_mv": {
"weights": {
"randomBias": 0.13527957862243056,
"upBias": 0.8872773167677224,
"downBias": -0.5815978674218059,
"leftBias": 0.5140415458008647,
"rightBias": -0.26215602504089475,
"emptyCells": 0.5967530817724764,
"hPairs": 0.28665489237755537,
"vPairs": 0.9960453785024583,
"maxVal": 0.872288198210299,
"filledCols": -0.5823901635594666,
"filledRows": -0.743896720930934,
"lockedCells": 0.5396598996594548
},
"rawFitness": 819.2,
"fitness": 6.129244227650333,
"fitnessMeasure": "maxval"
},
"test3": {
"weights": {
"randomBias": 0.14737190184075005,
"upBias": 0.12583319334475546,
"downBias": 0.3977331961455049,
"leftBias": 0.4149142177398355,
"rightBias": 0.25336763019215547,
"emptyCells": 0.597260765285013,
"hPairs": 0.6466984695282718,
"vPairs": 0.7597727150829141,
"maxVal": 0.044006366691239286,
"filledCols": -0.4794424804353543,
"filledRows": -0.3655225815869224,
"lockedCells": 0.20423370498569768
},
"rawFitness": 5641.466666666666,
"fitness": 91.77325393847399,
"fitnessMeasure": "score"
}
}
}
|
process.env.NODE_ENV = 'development';
var mongoose = require("./config/mongoose");
var express = require("./config/express");
var passport = require("./config/passport");
var db = mongoose();
var app = express();
var passport = passport();
app.listen(9000);
console.log("Sever listening at http://localhost:9000");
module.exports = app;
|
var assert = require('assert');
var logger = using('easynode.framework.Logger').forFile(__filename);
var GenericObject = using('easynode.GenericObject');
var S = require('string');
(function () {
/**
* 抽象类,定义了获取Action参数的函数 。
*
* @class easynode.framework.mvc.ActionRequestParameter
* @extends easynode.GenericObject
* @abstract
* @since 0.1.0
* @author zlbbq
* */
class ActionRequestParameter extends GenericObject {
/**
* 构造函数。
*
* @method 构造函数
* @since 0.1.0
* @author zlbbq
* */
constructor() {
super();
}
/**
* 获取HTTP请求参数。注意:EasyNode使用'first'模式取query string参数,参数名相同时,先出现的值有效。
*
* @method param
* @param {String} name 参数名
* @param {String} where 从哪里取参数,枚举,可以为"query"(query string),"body“(http body, POST时有效),
* "all"(body或query,body优先),默认”all“
* @return {String} 参数值
* @abstract
* @since 0.1.0
* @author zlbbq
* */
param (name, where='all', canNull=true) {
throw new Error('Abstract Method');
}
/**
* 是否传递了某个请求参数。
*
* @method hasParam
* @param {String} name 参数名
* @param {String} where 从哪里取参数,枚举,可以为"query"(query string),"body“(http body, POST时有效),
* "all"(body或query,body优先),默认”all“
* @return {boolean} 是否有此参数
* @abstract
* @since 0.1.0
* @author zlbbq
* */
hasParam(name, where='all') {
throw new Error('Abstract Method');
}
/**
* 获取HTTP请求参数名称。
*
* @method paramNames
* @param {String} where 从哪里取参数名,枚举,可以为"query"(query string),"body“(http body, POST时有效),
* "all"(body或query,body优先),默认”all“
* @return {Array} 参数名
* @abstract
* @since 0.1.0
* @author zlbbq
* */
paramNames (where='all') {
throw new Error('Abstract Method');
}
/**
* 获取上传的文件描述,POST且enctype="multipart-form-data"时有效。没有指定参数名的文件时,返回null。
*
* @method file
* @param {String} name 参数名(字段名)
* @return {object} 上传的文件描述。结构如下:
* {
* field : 'file1',
name : 'xx.jpg',
mime : 'image/jpeg',
path : '/tmp/adksl1234j123/xx.jpg'
* }
* @since 0.1.0
* @author zlbbq
* */
file (name) {
throw new Error('Abstract Method');
}
/**
* 保存文件到上传目录。
*
* @method saveFile
* @param {String} name 参数名(字段名)
* @return {object} 上传的文件描述。结构参考:file()函数。
* @async
* @since 0.1.0
* @author zlbbq
* */
saveFile (name) {
throw new Error('Abstract Method');
}
/**
* 枚举所有上传的文件参数名(字段名)。
*
* @method fileNames
* @param {String} name 参数名(字段名)
* @return {Array} 上传的所有文件参数名(字段名)
* @abstract
* @since 0.1.0
* @author zlbbq
* */
fileNames () {
throw new Error('Abstract Method');
}
/**
* 获取HTTP参数值,转成Number的整型。
*
* @method intParam
* @param {String} name 参数名
* @param {String} where query, body or both of two with 'all'
* @param {boolean} canNaN 是否允许NaN,如果是false, 当值为NaN时将被转成0
* @return {int}
* @since 0.1.0
* @author zlbbq
* */
intParam (name, where='all', canNaN=true) {
var val = parseInt(this.param(name, where));
if(canNaN !== true && isNaN(val)) {
return 0;
}
else {
return val;
}
}
/**
* 获取HTTP参数值,转成Number的整型。
*
* @method floatParam
* @param {String} name 参数名
* @param {String} where query, body or both of two with 'all'
* @param {boolean} canNaN 是否允许NaN,如果是false, 当值为NaN时将被转成0
* @return {float}
* @since 0.1.0
* @author zlbbq
* */
floatParam (name, where='all', canNaN=true) {
var val = parseFloat(this.param(name, where));
if(canNaN !== true && isNaN(val)) {
return 0;
}
return val;
}
/**
* 获取HTTP参数值,转成boolean型。
*
* @method booleanParam
* @param {String} name 参数名
* @param {String} where query, body or both of two with 'all'
* @return {boolean}
* @since 0.1.0
* @author zlbbq
* */
booleanParam (name, where='all') {
var v = this.param(name, where);
return (v == null || v == 'null' || v == 'false' || v == 'FALSE' || v =='False' || v === '0' || v == 0) ? false : true;
}
/**
* 获取HTTP参数值,转成数组型。
*
* @method booleanParam
* @param {String} name 参数名
* @param {String} type 数组中的元素实际类型,支持string, int, float, boolean, date, datetime, datetimeM
* @param {String} where query, body or both of two with 'all'
* @return {boolean}
* @since 0.1.0
* @author zlbbq
* */
arrayParam (name, type='string', where='all', delimiter=',') {
var val = this.param(name, where);
if(val) {
val = val.split(delimiter);
if(type != 'string') {
var idx = 0;
val.forEach(v => {
var rv = v;
switch (type) {
case 'int' :
{
rv = parseInt(v);
break;
}
case 'float':
{
rv = parseFloat(v);
break;
}
case 'boolean' :
{
rv = (v == null || v == 'null' || v == 'false' || v == 'FALSE' || v == 'False' || v === '0' || v == 0) ? false : true;
break;
}
case 'date':
{
v = v || '';
//if(v.match(/^\d{4}\-\d{2}\-\d{2}.*$/)) {
// v = v.substring(0, 10) + ' 00:00:00';
// rv = new Date(Date.parse(v));
//}
//else {
// rv = null;
//}
if(!v) {
rv = null;
}
else {
rv = new Date(Date.parse(v));
}
break;
}
case 'datetimeM':
{
v = v || '';
//if(v.match(/^\d{4}\-\d{2}\-\d{2}\s\d{2}:\d{2}.*$/)) {
// v = v.substring(0, 16) + ':00';
// rv = new Date(Date.parse(v));
//}
//else {
// rv = null;
//}
if(!v) {
rv = null;
}
else {
rv = new Date(Date.parse(v));
}
break;
}
case 'datetime':
{
//if(v.match(/^\d{4}\-\d{2}\-\d{2}\s\d{2}:\d{2}:\d{2}$/)) {
// v = v.substring(0, 16) + ':00';
// rv = new Date(Date.parse(v));
//}
//else {
// rv = null;
//}
if(!v) {
rv = null;
}
else {
rv = new Date(Date.parse(v));
}
break;
}
}
val[idx++] = rv;
});
}
}
return val;
}
/**
* 获取HTTP参数值,转成日期型。日期格式需要是:YYYY-MM-DD HH24:MI:SS, 例:2015-05-13 12:00:00,可只传日期部分。
* 日期格式请参考:date-utils模块。
*
* @method dateParam
* @param {String} name 参数名
* @param {String} where query, body or both of two with 'all'
* @return {Date} 格式错误时返回null。
* @since 0.1.0
* @author zlbbq
* */
dateParam (name, where='all') {
var val = this.param(name, where);
if(!val) {
return null;
}
//val = val || '';
//if(val.match(/^\d{4}\-\d{2}\-\d{2}$/)) {
// val = val + ' 00:00:00';
//}
//else if(val.match(/^\d{4}\-\d{2}\-\d{2}\s\d{2}:\d{2}:?\d{0,2}$/)) {
// val = val.substring(0, 10) + ' 00:00:00';
//}
//else {
// return null;
//}
//return new Date(Date.parse(val));
return new Date(Date.parse(val));
}
/**
* 获取HTTP参数值,转成日期时间型(精确到秒)。日期格式需要是:YYYY-MM-DD HH24:MI:SS, 例:2015-05-13 12:00:00,可只传日期部分。
* 日期格式请参考:date-utils模块。
*
* @method datetimeParam
* @param {String} name 参数名
* @param {String} where query, body or both of two with 'all'
* @return {Date} 格式错误时返回null。
* @since 0.1.0
* @author zlbbq
* */
datetimeParam (name, where='all') {
var val = this.param(name, where);
if(!val) {
return null;
}
//val = val || '';
//if(val.match(/^\d{4}\-\d{2}\-\d{2}$/)) {
// val = val + ' 00:00:00';
//}
//else if(val.match(/^\d{4}\-\d{2}\-\d{2}\s\d{2}:\d{2}:\d{2}$/)) {
// return new Date(Date.parse(val));
//}
//else {
// return null;
//}
return new Date(Date.parse(val));
}
/**
* 获取HTTP参数值,转成日期时间型(精确到分钟)。日期格式需要是:YYYY-MM-DD HH24:MI:SS, 例:2015-05-13 12:00:00,可只传日期部分。
* 日期格式请参考:date-utils模块。
*
* @method datetimeMParam
* @param {String} name 参数名
* @param {String} where query, body or both of two with 'all'
* @return {Date} 格式错误时返回null。
* @since 0.1.0
* @author zlbbq
* */
datetimeMParam (name, where='all') {
var val = this.param(name, where);
if(!val) {
return null;
}
//val = val || '';
//if(val.match(/^\d{4}\-\d{2}\-\d{2}$/)) {
// val = val + ' 00:00:00';
//}
//else if(val.match(/^\d{4}\-\d{2}\-\d{2}\s\d{2}:\d{2}$/)) {
// val = val + ':00';
//}
//else if(val.match(/^\d{4}\-\d{2}\-\d{2}\s\d{2}:\d{2}:\d{2}$/)) {
// val = val.substring(0, 16) + ':00';
//}
//else {
// return null;
//}
//return new Date(Date.parse(val));
return new Date(Date.parse(val));
}
/**
* 保存指定的文件,获取HTTP参数值,转成文件对象,语义化函数,同saveFile()函数。
*
* @method fileParam
* @param {String} name 参数名
* @return {Object} Notation参考file函数。
* @since 0.1.0
* @author zlbbq
* */
fileParam (name) {
return this.saveFile(name);
}
getClassName() {
return EasyNode.namespace(__filename);
}
}
module.exports = ActionRequestParameter;
})(); |
/**
* Dutch translation for bootstrap-datepicker
* Reinier Goltstein <mrgoltstein@gmail.com>
*/
;(function($){
$.fn.datepicker.dates['nl'] = {
days: ["Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag", "Zondag"],
daysShort: ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za", "Zo"],
daysMin: ["Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za", "Zo"],
months: ["Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"],
monthsShort: ["Jan", "Feb", "Mrt", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
today: "Vandaag"
};
}(jQuery)); |
var koa = require('koa')
var app = koa()
var router = require('../../router.js')
var Controller = require('../../controller.js')
app.use(router({
strictSlash: false
}))
router.get('/', function () {
this.body = 'Homepage'
})
router.all('/all', function () {
this.body = 'works'
})
;['get', 'post', 'put', 'delete'].forEach(function (method) {
router.set('/multiple-definitions', [method], function () {
this.body = method
})
})
function* getNestedGeneratorsContent () {
var body = yield getGeneratorBodyContent()
return body
}
function* getGeneratorBodyContent () {
return yield 'Nested Generators'
}
router.get('/nested-generators', function* () {
this.body = yield getNestedGeneratorsContent()
})
function getNestedPromisesContent () {
return Promise.resolve(getPromiseBodyContent())
}
function getPromiseBodyContent () {
return Promise.resolve('Nested Promises')
}
router.get('/nested-promises', function* () {
this.body = yield getNestedPromisesContent()
})
router.get('/primitive', function* () {
var prefix = yield 'Hello'
var suffix = yield 'World'
this.body = prefix + ' ' + suffix
})
router.get('/global-error-handler', function () {
this.throw(500)
})
router.get('/controller/normal-func', new Controller(function () {
this.body = 'done'
}))
router.get('/controller/generator', new Controller(function* (next) {
this.body = 'done'
yield next
}))
router.get('/controller/on', new Controller({
beforeAction: function () {
return true
},
defaultAction: function () {
},
on404: function () {
this.body = 'Nothing here'
this.status = 404
}
}))
router.get('/ba/not-ok', new Controller({
beforeAction: function () {
return true
},
defaultAction: function () {
this.body = 'Hello'
}
}))
router.get('/ba/ok', new Controller({
beforeAction: [function () {
return null
}, function* () {
function func () {
return
}
return yield func()
}],
defaultAction: function () {
this.body = 'Hello'
}
}))
router.get(/^\/hello\/(\w+)/i, function () {
this.body = 'Hello, ' + this.params[0]
})
function get () {
return Promise.resolve('works')
}
function* action () {
this.body = yield get()
}
function* gen () {
yield action.call(this)
}
router.get('/nested-generators-and-promises', function* () {
yield gen.call(this)
})
var ctrl = new Controller()
ctrl.addAction('addActionTest', function () {
this.body = 'works'
})
router.get('/ctrl/addAction', ctrl.addActionTest)
ctrl.addAction('notFound', function () {
})
ctrl.on('404', function () {
this.body = 'works'
this.status = 404
})
ctrl.on('405', function* () {
this.body = yield 'works'
this.status = 405
})
router.get('/ctrl/not-found', ctrl.notFound)
ctrl.on('401', function () {
throw Error('401 error')
})
ctrl.addAction('notAuth', function () {
this.status = 401
})
router.get('/ctrl/401', ctrl.notAuth)
router.get('/say/:name', function () {
this.body = this.params.name
})
router.on('500', function (next, error) {
this.body = error.message + '\nError Stack:' + error.stack
this.status = 500
})
app.listen(3456)
|
const enet = require('enet');
const crypto = require('crypto');
const base64 = require('./base64');
const FORWARDER_VERSION = 1;
const HEADER_LENGTH = 12;
const algorithm = "AES-128-CTR";
const originEncoding = 'utf8';
const ivSize = 16;
function unmakePacket(param) {
const packetData = param.data;
// console.log("data", data);
// console.log("data.length", data.length);
const header = packetData.slice(0, HEADER_LENGTH);
let data = packetData.slice(HEADER_LENGTH);
// console.log("header", header, 'len', header.length);
if (param.base64) {
const contentBase64 = base64.toByteArray(data.toString());
data = Buffer(contentBase64);
}
if (param.encrypt) {
const ivBuf = data.slice(0, ivSize);
console.log("ivBuf", ivBuf, 'len', ivBuf.length);
const key = param.encryptkey;
const decipher = crypto.createDecipheriv(algorithm, Buffer(key), ivBuf);
const plainChunks = [];
const encryptedContent = data.slice(ivSize);
console.log("encryptedContent", encryptedContent, 'len', encryptedContent.length);
plainChunks.push(decipher.update(encryptedContent));
plainChunks.push(decipher.final());
data = Buffer.concat(plainChunks);
console.log("origin", data, 'len', data.length);
}
const content = data.toString();
return {
header,
content,
};
}
function makePacket(param) {
if (!param.content) {
return null;
}
// small-endian
const arr = new Uint8Array(HEADER_LENGTH);
/*
uint8_t version;
uint8_t length;
uint8_t protocol;
uint8_t hash;
uint8_t subID;
uint8_t hostID;
uint16_t clientID;
*/
arr[0] = FORWARDER_VERSION;
arr[1] = HEADER_LENGTH;
arr[2] = param.protocol || 1;
arr[3] = 255; // hash
arr[4] = param.subID || 0; // subID
arr[5] = typeof(param.hostID) === "number" ? parseInt(param.hostID) : 0;
arr[6] = 0;
arr[7] = 0;
if (typeof(param.clientID) === "number") {
arr[6] = 0xff & param.clientID >> 8; // clientID
arr[7] = 0xff & param.clientID;
}
// Shares memory with `arr`
const headerBuf = new Buffer(arr.buffer);
let contentBuf;
if (param.encrypt) {
const key = param.encryptkey;
const ivBuf = crypto.randomBytes(ivSize);
// console.log("ivBuf", ivBuf, 'len', ivBuf.length);
const cipher = crypto.createCipheriv(algorithm, Buffer(key), ivBuf);
const cipherChunks = [ivBuf];
console.log("originBuf", Buffer(param.content), 'len', Buffer(param.content).length);
cipherChunks.push(cipher.update(param.content, originEncoding));
cipherChunks.push(cipher.final());
contentBuf = Buffer.concat(cipherChunks);
// console.log("contentBuf", contentBuf, 'len', contentBuf.length);
} else if (param.base64) {
contentBuf = new Buffer(param.content);
const contentBase64 = base64.fromByteArray(contentBuf);
contentBuf = new Buffer(contentBase64);
} else {
contentBuf = new Buffer(param.content);
}
const buf = Buffer.concat([headerBuf, contentBuf], headerBuf.length + contentBuf.length);
if (param.type === "enet") {
const packet = new enet.Packet(buf, enet.PACKET_FLAG.RELIABLE);
return packet;
} else {
return buf;
}
}
module.exports = {
makePacket,
unmakePacket,
}; |
var carController = {
rightDown: false,
leftDown: false,
controlCar: function(ev, car) {
switch (ev.keyCode) {
case 37:
// Left
// // configureAngularMotor(which, low_angle, high_angle, velocity, max_force)
car.wheel_fl_constraint.configureAngularMotor(1, -Math.PI / 4, Math.PI / 4, 3, 200);
car.wheel_fr_constraint.configureAngularMotor(1, -Math.PI / 4, Math.PI / 4, 3, 200);
car.wheel_fl_constraint.enableAngularMotor(1);
car.wheel_fr_constraint.enableAngularMotor(1);
carController.leftDown = true;
break;
case 39:
// Right
// MATH.PI /3 -> 60°;
// MATH.PI /2 -> 90°;
// MATH.PI /4 -> 45°;
car.wheel_fl_constraint.configureAngularMotor(1, -Math.PI / 4, Math.PI / 4, -3, 200);
car.wheel_fr_constraint.configureAngularMotor(1, -Math.PI / 4, Math.PI / 4, -3, 200);
car.wheel_fl_constraint.enableAngularMotor(1);
car.wheel_fr_constraint.enableAngularMotor(1);
carController.rightDown = true;
break;
case 38:
// Up
// configureAngularMotor(which, low_angle, high_angle, velocity, max_force)
car.wheel_bl_constraint.configureAngularMotor(2, 1, 0, velocity, 2000);
car.wheel_br_constraint.configureAngularMotor(2, 1, 0, velocity, 2000);
car.wheel_bl_constraint.enableAngularMotor(2);
car.wheel_br_constraint.enableAngularMotor(2);
break;
case 40:
// Down
car.wheel_bl_constraint.configureAngularMotor(2, 1, 0, -velocity, 2000);
car.wheel_br_constraint.configureAngularMotor(2, 1, 0, -velocity, 2000);
car.wheel_bl_constraint.enableAngularMotor(2);
car.wheel_br_constraint.enableAngularMotor(2);
break;
case 32:
//space
// createjs.Sound.stop("tuut");
createjs.Sound.play("tuut");
break;
case 67:
// c
switchCam();
break;
case 82:
// r
// init();
break;
}
},
controlCarWithPhone: function(direction, car) {
switch (direction) {
case 'left':
// Left
// // configureAngularMotor(which, low_angle, high_angle, velocity, max_force)
car.wheel_fl_constraint.configureAngularMotor(1, -Math.PI / 4, Math.PI / 4, 3, 200);
car.wheel_fr_constraint.configureAngularMotor(1, -Math.PI / 4, Math.PI / 4, 3, 200);
car.wheel_fl_constraint.enableAngularMotor(1);
car.wheel_fr_constraint.enableAngularMotor(1);
break;
case 'right':
// Right
// MATH.PI /3 -> 60°;
// MATH.PI /2 -> 90°;
// MATH.PI /4 -> 45°;
car.wheel_fl_constraint.configureAngularMotor(1, -Math.PI / 4, Math.PI / 4, -3, 200);
car.wheel_fr_constraint.configureAngularMotor(1, -Math.PI / 4, Math.PI / 4, -3, 200);
car.wheel_fl_constraint.enableAngularMotor(1);
car.wheel_fr_constraint.enableAngularMotor(1);
break;
case 'forward':
car.wheel_fl_constraint.configureAngularMotor(1, 0, 0, -3, 200);
car.wheel_fr_constraint.configureAngularMotor(1, 0, 0, -3, 200);
car.wheel_fl_constraint.enableAngularMotor(1);
car.wheel_fr_constraint.enableAngularMotor(1);
}
},
moveCar: function(car, direction) {
console.log(direction)
var multiplier = 1;
switch (direction) {
case 'forward':
multiplier = 1;
break;
case 'back':
multiplier = -1
break;
}
car.wheel_bl_constraint.configureAngularMotor(2, 1, 0, multiplier * velocity, 2000);
car.wheel_br_constraint.configureAngularMotor(2, 1, 0, multiplier * velocity, 2000);
car.wheel_bl_constraint.enableAngularMotor(2);
car.wheel_br_constraint.enableAngularMotor(2);
},
stopCar: function(car) {
car.wheel_bl_constraint.disableAngularMotor(2);
car.wheel_br_constraint.disableAngularMotor(2);
},
rotateCar: function(car, angle) {
if (angle < -8) {
// // configureAngularMotor(which, low_angle, high_angle, velocity, max_force)
car.wheel_fl_constraint.configureAngularMotor(1, -Math.PI / 6, Math.PI / 6, 3, 200);
car.wheel_fr_constraint.configureAngularMotor(1, -Math.PI / 6, Math.PI / 6, 3, 200);
car.wheel_fl_constraint.enableAngularMotor(1);
car.wheel_fr_constraint.enableAngularMotor(1);
} else if (angle > 8) {
car.wheel_fl_constraint.configureAngularMotor(1, -Math.PI / 6, Math.PI / 6, -3, 200);
car.wheel_fr_constraint.configureAngularMotor(1, -Math.PI / 6, Math.PI / 6, -3, 200);
car.wheel_fl_constraint.enableAngularMotor(1);
car.wheel_fr_constraint.enableAngularMotor(1);
} else {
car.wheel_fl_constraint.disableAngularMotor(1);
car.wheel_fr_constraint.disableAngularMotor(1);
}
},
stopCarAll: function(car) {
car.wheel_fl_constraint.disableAngularMotor(1);
car.wheel_fr_constraint.disableAngularMotor(1);
car.wheel_bl_constraint.disableAngularMotor(2);
car.wheel_br_constraint.disableAngularMotor(2);
},
stopCar: function(ev, car) {
switch (ev.keyCode) {
case 37:
// Left
car.wheel_fl_constraint.disableAngularMotor(1);
car.wheel_fr_constraint.disableAngularMotor(1);
carController.leftDown = false;
break;
case 39:
// Right
car.wheel_fl_constraint.disableAngularMotor(1);
car.wheel_fr_constraint.disableAngularMotor(1);
carController.rightDown = false;
break;
case 38:
// Up
car.wheel_bl_constraint.disableAngularMotor(2);
car.wheel_br_constraint.disableAngularMotor(2);
break;
case 40:
// Down
car.wheel_bl_constraint.disableAngularMotor(2);
car.wheel_br_constraint.disableAngularMotor(2);
break;
}
}
}
|
$('#photoSelect').click(function (e) {
e.preventDefault();
$("#Photo").click();
});
$('#Photo').change(function () {
if (this.files && this.files[0]) {
$('#formProfilePicture').submit();
}
}); |
'use strict';
var constants = require('../constants');
var oauthClient = require('../client/oauth');
var userClient = require('../client/user');
var loginCreatedUser = function(password, userData) {
var flux = this;
// User created, now log in
oauthClient.login(userData.email, password)
.then(function(tokenData) {
flux.dispatch(
constants.LOGIN_SUCCESSFUL,
{
tokenData : tokenData,
userData : userData
}
);
})
.fail(function() {
flux.dispatch(constants.LOGIN_FAILED);
});
};
var fetchLoggedInUser = function(tokenData)
{
var flux = this;
// Authenticated, but still need user data
userClient.setToken(tokenData);
userClient.getCurrentUser()
.then(function(userData) {
flux.dispatch(
constants.LOGIN_SUCCESSFUL,
{
tokenData : tokenData,
userData : userData
}
);
})
.fail(function() {
flux.dispatch(constants.LOGIN_FAILED);
});
};
module.exports = {
login : function(username, password)
{
var flux = this;
flux.dispatch(constants.LOGGING_IN);
oauthClient.login(username, password)
.then(fetchLoggedInUser.bind(flux))
.fail(function() {
flux.dispatch(constants.LOGIN_FAILED);
});
},
logout : function()
{
// Assume the logout worked, since it doesn't make a difference to the user
oauthClient.logout();
this.dispatch(constants.LOGOUT);
},
registerUser : function(email, password) {
var flux = this;
this.dispatch(constants.REGISTERING);
userClient.createUser(
{
email : email,
password : password
})
.then(loginCreatedUser.bind(flux, password))
.fail(function() {
flux.dispatch(constants.REGISTRATION_FAILED);
});
}
};
|
const FileSystem = require('fs'),
{ transform } = require('./transform');
function transformFile(fileName, _opts, callback) {
var opts = Object.assign({ fileName }, _opts || {});
if (arguments.length < 3) {
return new Promise((resolve, reject) => {
FileSystem.readFile(fileName, 'utf8', function(err, data) {
if (err)
return reject(err);
transform(data, opts, (err, token) => {
if (err)
return reject(err);
resolve(token);
});
});
});
}
if (typeof callback !== 'function')
throw new TypeError('transform: Third argument must be a `function`');
return FileSystem.readFile(fileName, 'utf8', function(err, data) {
if (err)
return callback(err, null);
transform(data, opts, callback);
});
}
module.exports = {
transformFile
};
|
var Suite = require('./suite')
, Bench = require('./bench');
module.exports = function (suite) {
var suites = [ suite ];
suite.on('pre-require', function (context) {
context.set = function (key, value) {
suites[0].setOption(key, value);
};
context.before = function (fn) {
suites[0].addBefore(fn);
};
context.after = function (fn) {
suites[0].addAfter(fn);
};
context.suite = function (title, fn) {
var suite = Suite.create(suites[0], title);
suites.unshift(suite);
fn();
suites.shift(suite);
};
context.bench = function (title, fn) {
suites[0].addBench(new Bench(title, fn));
};
});
};
|
const Command = require(`${process.cwd()}/base/Command.js`);
class Tag extends Command {
constructor(client) {
super(client, {
name: 'tag',
description: 'Show or modify tags.',
category: 'Support',
usage: 'tag <action> [tagname] <contents>.',
extended: `-add newTagName This is your new tag contents
-del tagName
-edit existingtagName This is new new edited contents
-list`,
aliases: ['t', 'tags']
});
this.init = client => {
this.db = new client.db(client, 'tags');
this.db.extendedHelp = this.help.extended;
client.tags = this.db;
};
}
async run(message, args, level) {
if (!args[0] && !message.flags.length) message.flags.push('list');
if (!message.flags.length) {
const [name, ...msg] = args;
if (!this.db.has(name)) return message.channel.send(`The tag \`${name}\` does not exist.`);
const tag = this.db.get(name).contents;
return message.channel.send(`${msg.join(' ')}${tag}`);
}
if (message.flags[0] === 'list') return message.channel.send(this.db.list());
if (level < 8) return;
const [name, ...extra] = args;
let data = null;
switch (message.flags[0]) {
case ('add') :
data = {contents: extra.join(' ')};
break;
default :
data = extra.join(' ');
}
try {
let response = await this.db[message.flags[0]](name, data);
response < 1 ? response = 'There appears to be no tags saved at this time.' : response;
message.channel.send(response);
} catch (error) {
this.client.logger.error(error);
}
}
}
module.exports = Tag; |
'use strict';
var gulp = require('gulp');
var gutil = require('gulp-util');
var del = require('del');
var path = require('path');
var bower = require('gulp-bower');
var autoprefixer = require('autoprefixer-core');
var cssnano = require('cssnano');
var postcss = require('gulp-postcss');
var rename = require('gulp-rename');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var merge = require('merge-stream');
var staticFiles = ['core/static/**'];
var buildDest = 'build_static/';
function copyBowerPackage(name, files) {
return gulp.src(path.join('bower_components/', name, files))
.pipe(gulp.dest(path.join(buildDest, 'dist/', name)));
}
gulp.task('clean', function (done) {
del(path.join(buildDest, '*'), done);
});
gulp.task('copyStatic', ['clean'], function () {
return gulp.src(staticFiles)
.pipe(gulp.dest(buildDest));
});
gulp.task('bower-install', ['clean'], function () {
return bower();
});
gulp.task('bower', ['bower-install'], function () {
return merge(
copyBowerPackage('bootstrap', 'dist/**'),
copyBowerPackage('jquery', 'dist/**'),
copyBowerPackage('js-cookie', 'src/**'),
copyBowerPackage('underscore', '*')
);
});
gulp.task('css', ['copyStatic'], function () {
var processors = [
autoprefixer({
browsers: 'last 2 versions'
}),
cssnano({
autoprefixer: false,
merge: false,
idents: false,
unused: false,
zindex: false
})
];
return gulp.src(path.join(buildDest, '*/*.css'))
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(postcss(processors))
.pipe(rename({extname: '.min.css'}))
.pipe(sourcemaps.write('.', {sourceRoot: '/static/'}))
.pipe(gulp.dest(buildDest));
});
gulp.task('uglify', ['copyStatic', 'bower'], function() {
return gulp.src([
path.join(buildDest, '*/*.js'),
path.join(buildDest, '*/js-cookie/*.js')
])
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(uglify())
.pipe(rename({extname: '.min.js'}))
.pipe(sourcemaps.write('.', {sourceRoot: '/static/'}))
.pipe(gulp.dest(buildDest));
});
gulp.task('build', ['copyStatic', 'bower', 'css', 'uglify']);
gulp.task('watch', function () {
gulp.watch([staticFiles, 'bower.json'], ['build']);
});
gulp.task('default', ['build']);
|
SleepyApp.controller('searchRetagController', [
'$scope',
'$state',
'retags',
'tagsFactory',
function ($scope, $state, retags, tagsFactory) {
$scope.doRetag = function(thread_list,retag) {
var search_query = ""
for (var i=0;i<thread_list.length;i++) {
var thread = thread_list[i];
if (thread.selected) {
if (search_query != "") {
search_query += " or ";
}
search_query += "thread:"+thread.id
}
}
if (search_query != "") {
tagsFactory.retag(search_query,retag.add,retag.remove)
.success(function(data) {
$state.go($state.current, {}, {reload: true});
});
}
}
$scope.retag_list = retags;
}
]);
|
describe('L.esri.Tasks.Query', function () {
function createMap(){
// create container
var container = document.createElement('div');
// give container a width/height
container.setAttribute('style', 'width:500px; height: 500px;');
// add contianer to body
document.body.appendChild(container);
return L.map(container).setView([45.51, -122.66], 16);
}
var map = createMap();
var server;
var task;
var bounds = L.latLngBounds([[45.5, -122.66],[ 45.51, -122.65]]);
var latlng = L.latLng(45.51, -122.66);
var rawLatlng = [45.51, -122.66];
var rawBounds = [[45.5, -122.66],[ 45.51, -122.65]];
var rawLatLng = [45.51, -122.66];
var rawGeoJsonPolygon = {
"type": "Polygon",
"coordinates": [[
[-97,39],[-97,41],[-94,41],[-94,39],[-97,39]
]]
};
var rawGeoJsonFeature = {"type": "Feature"}
rawGeoJsonFeature.geometry = rawGeoJsonPolygon;
var geoJsonPolygon = L.geoJson(rawGeoJsonPolygon);
var featureLayerUrl = 'http://services.arcgis.com/mock/arcgis/rest/services/MockFeatureService/FeatureServer/0/';
var mapServiceUrl = 'http://services.arcgis.com/mock/arcgis/rest/services/MockMapService/MapServer/';
var imageServiceUrl = 'http://services.arcgis.com/mock/arcgis/rest/services/MockImageService/ImageServer/';
var sampleImageServiceQueryResponse = {
'fieldAliases': {
'IMAGEID': 'IMAGEID',
'OWNER': 'OWNER'
},
'fields': [
{
'name': 'IMAGEID',
'type': 'esriFieldTypeOID',
'alias': 'IMAGEID'
},
{
'name': 'OWNER',
'type': 'esriFieldTypeString',
'alias': 'OWNER'
},
],
'features': [
{
'attributes': {
'IMAGEID': 1,
'OWNER': 'Joe Smith'
},
'geometry': {
'rings' : [
[ [-97.06138,32.837], [-97.06133,32.836], [-97.06124,32.834], [-97.06127,32.832], [-97.06138,32.837] ]
],
'spatialReference': {
'wkid': 4326
}
}
}
]
};
var sampleImageServiceCollection = {
'type': 'FeatureCollection',
'features': [{
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [
[ [-97.06138,32.837], [-97.06133,32.836], [-97.06124,32.834], [-97.06127,32.832], [-97.06138,32.837] ]
]
},
'properties': {
'IMAGEID': 1,
'OWNER': 'Joe Smith'
},
'id': 1
}]
};
var sampleMapServiceQueryResponse = {
'fieldAliases': {
'ObjectID': 'ObjectID',
'Name': 'Name'
},
'fields': [
{
'name': 'ObjectID',
'type': 'esriFieldTypeOID',
'alias': 'ObjectID'
},
{
'name': 'Name',
'type': 'esriFieldTypeString',
'alias': 'Name'
},
],
'features': [
{
'attributes': {
'ObjectID': 1,
'Name': 'Site'
},
'geometry': {
'x': -122.81,
'y': 45.48,
'spatialReference': {
'wkid': 4326
}
}
}
]
};
var sampleMapServiceCollection = {
'type': 'FeatureCollection',
'features': [{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [-122.81, 45.48]
},
'properties': {
'ObjectID': 1,
'Name': 'Site'
},
'id': 1
}]
};
var sampleQueryResponse = {
'objectIdFieldName': 'FID',
'fields': [{
'name': 'stop_desc',
'type': 'esriFieldTypeString',
'alias': 'stop_desc',
'sqlType': 'sqlTypeNVarchar',
'length': 256,
'domain': null,
'defaultValue': null
},{
'name': 'FID',
'type': 'esriFieldTypeInteger',
'alias': 'FID',
'sqlType': 'sqlTypeInteger',
'domain': null,
'defaultValue': null
}],
'features': [
{
'attributes': {
'FID': 1,
'Name': 'Site'
},
'geometry': {
'x': -122.81,
'y': 45.48,
'spatialReference': {
'wkid': 4326
}
}
}
]
};
var sampleExtentResponse = {
'extent': {
'xmin': -122.66,
'ymin': 45.5,
'xmax': -122.65,
'ymax': 45.51
}
};
var sampleCountResponse = {
'count': 1
};
var sampleFeatureCollection = {
'type': 'FeatureCollection',
'features': [{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [-122.81, 45.48]
},
'properties': {
'FID': 1,
'Name': 'Site'
},
'id': 1
}]
};
var sampleIdsResponse = {
'objectIdFieldName' : 'FID',
'objectIds' : [1, 2]
};
beforeEach(function(){
server = sinon.fakeServer.create();
task = L.esri.Tasks.query(featureLayerUrl);
});
afterEach(function(){
server.restore();
});
it('should query features', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&f=json', JSON.stringify(sampleQueryResponse));
var request = task.run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
expect(request).to.be.an.instanceof(XMLHttpRequest);
server.respond();
});
it('should query features within bounds', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&inSr=4326&geometry=%7B%22xmin%22%3A-122.66%2C%22ymin%22%3A45.5%2C%22xmax%22%3A-122.65%2C%22ymax%22%3A45.51%2C%22spatialReference%22%3A%7B%22wkid%22%3A4326%7D%7D&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelContains&f=json', JSON.stringify(sampleQueryResponse));
task.within(bounds).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query features within geojson geometry', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&inSr=4326&geometry=%7B%22rings%22%3A%5B%5B%5B-97%2C39%5D%2C%5B-97%2C41%5D%2C%5B-94%2C41%5D%2C%5B-94%2C39%5D%2C%5B-97%2C39%5D%5D%5D%2C%22spatialReference%22%3A%7B%22wkid%22%3A4326%7D%7D&geometryType=esriGeometryPolygon&spatialRel=esriSpatialRelContains&f=json', JSON.stringify(sampleQueryResponse));
task.within(rawGeoJsonPolygon).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query features within geojson feature', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&inSr=4326&geometry=%7B%22rings%22%3A%5B%5B%5B-97%2C39%5D%2C%5B-97%2C41%5D%2C%5B-94%2C41%5D%2C%5B-94%2C39%5D%2C%5B-97%2C39%5D%5D%5D%2C%22spatialReference%22%3A%7B%22wkid%22%3A4326%7D%7D&geometryType=esriGeometryPolygon&spatialRel=esriSpatialRelContains&f=json', JSON.stringify(sampleQueryResponse));
task.within(rawGeoJsonFeature).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query features within leaflet geojson object', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&inSr=4326&geometry=%7B%22rings%22%3A%5B%5B%5B-97%2C39%5D%2C%5B-97%2C41%5D%2C%5B-94%2C41%5D%2C%5B-94%2C39%5D%2C%5B-97%2C39%5D%5D%5D%2C%22spatialReference%22%3A%7B%22wkid%22%3A4326%7D%7D&geometryType=esriGeometryPolygon&spatialRel=esriSpatialRelContains&f=json', JSON.stringify(sampleQueryResponse));
task.within(geoJsonPolygon).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query features that intersect bounds', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&inSr=4326&geometry=%7B%22xmin%22%3A-122.66%2C%22ymin%22%3A45.5%2C%22xmax%22%3A-122.65%2C%22ymax%22%3A45.51%2C%22spatialReference%22%3A%7B%22wkid%22%3A4326%7D%7D&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelIntersects&f=json', JSON.stringify(sampleQueryResponse));
task.intersects(bounds).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query features that intersect geojson geometry', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&inSr=4326&geometry=%7B%22rings%22%3A%5B%5B%5B-97%2C39%5D%2C%5B-97%2C41%5D%2C%5B-94%2C41%5D%2C%5B-94%2C39%5D%2C%5B-97%2C39%5D%5D%5D%2C%22spatialReference%22%3A%7B%22wkid%22%3A4326%7D%7D&geometryType=esriGeometryPolygon&spatialRel=esriSpatialRelIntersects&f=json', JSON.stringify(sampleQueryResponse));
task.intersects(rawGeoJsonPolygon).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query features that intersect geojson feature', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&inSr=4326&geometry=%7B%22rings%22%3A%5B%5B%5B-97%2C39%5D%2C%5B-97%2C41%5D%2C%5B-94%2C41%5D%2C%5B-94%2C39%5D%2C%5B-97%2C39%5D%5D%5D%2C%22spatialReference%22%3A%7B%22wkid%22%3A4326%7D%7D&geometryType=esriGeometryPolygon&spatialRel=esriSpatialRelIntersects&f=json', JSON.stringify(sampleQueryResponse));
task.intersects(rawGeoJsonFeature).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query features that intersect leaflet geojson object', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&inSr=4326&geometry=%7B%22rings%22%3A%5B%5B%5B-97%2C39%5D%2C%5B-97%2C41%5D%2C%5B-94%2C41%5D%2C%5B-94%2C39%5D%2C%5B-97%2C39%5D%5D%5D%2C%22spatialReference%22%3A%7B%22wkid%22%3A4326%7D%7D&geometryType=esriGeometryPolygon&spatialRel=esriSpatialRelIntersects&f=json', JSON.stringify(sampleQueryResponse));
task.intersects(geoJsonPolygon).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query features that contain bounds', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&inSr=4326&geometry=%7B%22xmin%22%3A-122.66%2C%22ymin%22%3A45.5%2C%22xmax%22%3A-122.65%2C%22ymax%22%3A45.51%2C%22spatialReference%22%3A%7B%22wkid%22%3A4326%7D%7D&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelWithin&f=json', JSON.stringify(sampleQueryResponse));
task.contains(bounds).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query features that contain geojson geometry', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&inSr=4326&geometry=%7B%22rings%22%3A%5B%5B%5B-97%2C39%5D%2C%5B-97%2C41%5D%2C%5B-94%2C41%5D%2C%5B-94%2C39%5D%2C%5B-97%2C39%5D%5D%5D%2C%22spatialReference%22%3A%7B%22wkid%22%3A4326%7D%7D&geometryType=esriGeometryPolygon&spatialRel=esriSpatialRelWithin&f=json', JSON.stringify(sampleQueryResponse));
task.contains(rawGeoJsonPolygon).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query features that contain geojson feature', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&inSr=4326&geometry=%7B%22rings%22%3A%5B%5B%5B-97%2C39%5D%2C%5B-97%2C41%5D%2C%5B-94%2C41%5D%2C%5B-94%2C39%5D%2C%5B-97%2C39%5D%5D%5D%2C%22spatialReference%22%3A%7B%22wkid%22%3A4326%7D%7D&geometryType=esriGeometryPolygon&spatialRel=esriSpatialRelWithin&f=json', JSON.stringify(sampleQueryResponse));
task.contains(rawGeoJsonFeature).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query features that contain leaflet geojson object', function(done){
// query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&inSr=4326&geometry=%7B%22rings%22%3A%5B%5B%5B-97%2C39%5D%2C%5B-97%2C41%5D%2C%5B-94%2C41%5D%2C%5B-94%2C39%5D%2C%5B-97%2C39%5D%5D%5D%2C%22spatialReference%22%3A%7B%22wkid%22%3A4326%7D%7D&geometryType=esriGeometryPolygon&spatialRel=esriSpatialRelWithin&f=json
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&inSr=4326&geometry=%7B%22rings%22%3A%5B%5B%5B-97%2C39%5D%2C%5B-97%2C41%5D%2C%5B-94%2C41%5D%2C%5B-94%2C39%5D%2C%5B-97%2C39%5D%5D%5D%2C%22spatialReference%22%3A%7B%22wkid%22%3A4326%7D%7D&geometryType=esriGeometryPolygon&spatialRel=esriSpatialRelWithin&f=json', JSON.stringify(sampleQueryResponse));
task.contains(geoJsonPolygon).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query features that overlap bounds', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&inSr=4326&geometry=%7B%22xmin%22%3A-122.66%2C%22ymin%22%3A45.5%2C%22xmax%22%3A-122.65%2C%22ymax%22%3A45.51%2C%22spatialReference%22%3A%7B%22wkid%22%3A4326%7D%7D&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelOverlaps&f=json', JSON.stringify(sampleQueryResponse));
task.overlaps(bounds).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query features that overlap geojson geometry', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&inSr=4326&geometry=%7B%22rings%22%3A%5B%5B%5B-97%2C39%5D%2C%5B-97%2C41%5D%2C%5B-94%2C41%5D%2C%5B-94%2C39%5D%2C%5B-97%2C39%5D%5D%5D%2C%22spatialReference%22%3A%7B%22wkid%22%3A4326%7D%7D&geometryType=esriGeometryPolygon&spatialRel=esriSpatialRelOverlaps&f=json', JSON.stringify(sampleQueryResponse));
task.overlaps(rawGeoJsonPolygon).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query features that overlap geojson feature', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&inSr=4326&geometry=%7B%22rings%22%3A%5B%5B%5B-97%2C39%5D%2C%5B-97%2C41%5D%2C%5B-94%2C41%5D%2C%5B-94%2C39%5D%2C%5B-97%2C39%5D%5D%5D%2C%22spatialReference%22%3A%7B%22wkid%22%3A4326%7D%7D&geometryType=esriGeometryPolygon&spatialRel=esriSpatialRelOverlaps&f=json', JSON.stringify(sampleQueryResponse));
task.overlaps(rawGeoJsonFeature).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query features that overlap leaflet geojson object', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&inSr=4326&geometry=%7B%22rings%22%3A%5B%5B%5B-97%2C39%5D%2C%5B-97%2C41%5D%2C%5B-94%2C41%5D%2C%5B-94%2C39%5D%2C%5B-97%2C39%5D%5D%5D%2C%22spatialReference%22%3A%7B%22wkid%22%3A4326%7D%7D&geometryType=esriGeometryPolygon&spatialRel=esriSpatialRelOverlaps&f=json', JSON.stringify(sampleQueryResponse));
task.overlaps(geoJsonPolygon).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query features near a latlng', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&geometry=-122.66%2C45.51&geometryType=esriGeometryPoint&spatialRel=esriSpatialRelIntersects&units=esriSRUnit_Meter&distance=500&inSr=4326&f=json', JSON.stringify(sampleQueryResponse));
task.nearby(latlng, 500).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query features with a where option', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=NAME%3D\'Site\'&outSr=4326&outFields=*&f=json', JSON.stringify(sampleQueryResponse));
task.where('NAME="Site"').run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should limit queries for pagination', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&limit=10&f=json', JSON.stringify(sampleQueryResponse));
task.limit(10).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should offset queries for pagination', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&offset=10&f=json', JSON.stringify(sampleQueryResponse));
task.offset(10).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query features in a given time range', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&time=1357027200000%2C1388563200000&f=json', JSON.stringify(sampleQueryResponse));
var start = new Date('January 1 2013 GMT-0800');
var end = new Date('January 1 2014 GMT-0800');
task.between(start, end).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should set output fields for queries', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=Name%2CFID&f=json', JSON.stringify(sampleQueryResponse));
task.fields(['Name', 'FID']).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should limit geometry percision', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&geometryPrecision=4&f=json', JSON.stringify(sampleQueryResponse));
task.precision(4).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should identify features and simplify geometries', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&maxAllowableOffset=0.000010728836059556101&f=json', JSON.stringify(sampleQueryResponse));
task.simplify(map, 0.5).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should order query output ascending', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&orderByFields=Name%20ASC&f=json', JSON.stringify(sampleQueryResponse));
task.orderBy('Name').run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should order query output descending', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&orderByFields=Name%20DESC&f=json', JSON.stringify(sampleQueryResponse));
task.orderBy('Name', 'DESC').run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should order query output with multiple features', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&orderByFields=Name%20DESC%2CScore%20ASC&f=json', JSON.stringify(sampleQueryResponse));
task.orderBy('Name', 'DESC').orderBy('Score', 'ASC').run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should be able to query specific feature ids', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&objectIds=1%2C2&f=json', JSON.stringify(sampleQueryResponse));
task.featureIds([1,2]).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should be able to query token', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&token=foo&f=json', JSON.stringify(sampleQueryResponse));
task.token('foo').run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
server.respond();
});
it('should query bounds', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&returnExtentOnly=true&f=json', JSON.stringify(sampleExtentResponse));
var request = task.bounds(function(error, latlngbounds, raw){
expect(latlngbounds).to.deep.equal(bounds);
expect(raw).to.deep.equal(sampleExtentResponse);
done();
});
expect(request).to.be.an.instanceof(XMLHttpRequest);
server.respond();
});
it('should query count', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&returnCountOnly=true&f=json', JSON.stringify(sampleCountResponse));
var request = task.count(function(error, count, raw){
expect(count).to.equal(1);
expect(raw).to.deep.equal(sampleCountResponse);
done();
});
expect(request).to.be.an.instanceof(XMLHttpRequest);
server.respond();
});
it('should query ids', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&returnIdsOnly=true&f=json', JSON.stringify(sampleIdsResponse));
var request = task.ids(function(error, ids, raw){
expect(ids).to.deep.equal([1,2]);
expect(raw).to.deep.equal(sampleIdsResponse);
done();
});
expect(request).to.be.an.instanceof(XMLHttpRequest);
server.respond();
});
it('should use a feature layer service to query features', function(done){
server.respondWith('GET', featureLayerUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&f=json', JSON.stringify(sampleQueryResponse));
var service = new L.esri.Services.FeatureLayer(featureLayerUrl);
var request = service.query().run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleFeatureCollection);
expect(raw).to.deep.equal(sampleQueryResponse);
done();
});
expect(request).to.be.an.instanceof(XMLHttpRequest);
server.respond();
});
it('should use a map service to query features', function(done){
server.respondWith('GET', mapServiceUrl + '0/query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&f=json', JSON.stringify(sampleMapServiceQueryResponse));
var service = new L.esri.Services.MapService(mapServiceUrl);
service.query().layer(0).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleMapServiceCollection);
expect(raw).to.deep.equal(sampleMapServiceQueryResponse);
done();
});
server.respond();
});
it('should use a image service to query features', function(done){
server.respondWith('GET', imageServiceUrl + 'query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&pixelSize=1%2C1&f=json', JSON.stringify(sampleImageServiceQueryResponse));
var service = new L.esri.Services.MapService(imageServiceUrl);
var request = service.query().pixelSize([1, 1]).run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleImageServiceCollection);
expect(raw).to.deep.equal(sampleImageServiceQueryResponse);
done();
});
expect(request).to.be.an.instanceof(XMLHttpRequest);
server.respond();
});
it('should make GET queries with no service', function(done){
server.respondWith('GET', mapServiceUrl + '0/query?returnGeometry=true&where=1%3D1&outSr=4326&outFields=*&f=json', JSON.stringify(sampleMapServiceQueryResponse));
var queryTask = new L.esri.Tasks.Query(mapServiceUrl + '0');
var request = queryTask.where("1=1").run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleMapServiceCollection);
expect(raw).to.deep.equal(sampleMapServiceQueryResponse);
done();
});
server.respond();
});
it('query tasks without services should make GET requests w/ JSONP', function(done){
var queryTask = new L.esri.Tasks.Query(mapServiceUrl + '0');
queryTask.options.useCors = false;
var request = queryTask.where("1=1").run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleMapServiceCollection);
expect(raw).to.deep.equal(sampleMapServiceQueryResponse);
done();
});
window._EsriLeafletCallbacks[request.id](sampleMapServiceQueryResponse);
});
it('query tasks without services should make POST requests', function(done){
server.respondWith('POST', mapServiceUrl + '0/query', JSON.stringify(sampleMapServiceQueryResponse));
var queryTask = new L.esri.Tasks.Query(mapServiceUrl + '0');
var request = queryTask.where(
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters" +
"this is a dumb way to make sure the request is more than 2000 characters").
run(function(error, featureCollection, raw){
expect(featureCollection).to.deep.equal(sampleMapServiceCollection);
expect(raw).to.deep.equal(sampleMapServiceQueryResponse);
done();
});
server.respond();
});
}); |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Observable_1 = require("rxjs/Observable");
var ReplaySubject_1 = require("rxjs/ReplaySubject");
var normalize = function (x) { return Math.max(x, 0); };
/**
* @hidden
*/
var ScrollAction = (function () {
function ScrollAction(offset) {
this.offset = offset;
}
return ScrollAction;
}());
exports.ScrollAction = ScrollAction;
/**
* @hidden
*/
var PageAction = (function () {
function PageAction(skip) {
this.skip = skip;
}
return PageAction;
}());
exports.PageAction = PageAction;
/**
* @hidden
*/
var ScrollerService = (function () {
function ScrollerService(scrollObservable) {
this.scrollObservable = scrollObservable;
this.firstLoaded = 0;
this.bottomOffset = 0;
this.topOffset = 0;
}
ScrollerService.prototype.create = function (rowHeightService, skip, take, total, topOffset, bottomOffset) {
var _this = this;
if (topOffset === void 0) { topOffset = 0; }
if (bottomOffset === void 0) { bottomOffset = 0; }
this.rowHeightService = rowHeightService;
this.firstLoaded = skip;
this.lastLoaded = skip + take;
this.take = take;
this.total = total;
this.lastScrollTop = 0;
this.topOffset = topOffset;
this.bottomOffset = bottomOffset;
var subject = new ReplaySubject_1.ReplaySubject(2);
var offsetBufferRows = this.rowsForHeight(topOffset);
var skipWithOffset = normalize(skip - offsetBufferRows);
subject.next(new ScrollAction(this.rowOffset(skipWithOffset)));
if (offsetBufferRows) {
subject.next(new PageAction(skipWithOffset));
}
Observable_1.Observable.create(function (observer) {
_this.unsubscribe();
_this.scrollSubscription = _this.scrollObservable.subscribe(function (x) { return _this.onScroll(x, observer); });
}).subscribe(function (x) { return subject.next(x); });
return subject;
};
ScrollerService.prototype.destroy = function () {
this.unsubscribe();
};
ScrollerService.prototype.onScroll = function (_a, observer) {
var scrollTop = _a.scrollTop, offsetHeight = _a.offsetHeight;
if (this.lastScrollTop === scrollTop) {
return;
}
var up = this.lastScrollTop >= scrollTop;
this.lastScrollTop = scrollTop;
var firstItemIndex = this.rowHeightService.index(normalize(scrollTop - this.topOffset));
var lastItemIndex = this.rowHeightService.index(normalize(scrollTop + offsetHeight - this.bottomOffset));
if (!up && lastItemIndex >= this.lastLoaded && this.lastLoaded < this.total) {
this.firstLoaded = firstItemIndex;
observer.next(new ScrollAction(this.rowOffset(firstItemIndex)));
this.lastLoaded = Math.min(this.firstLoaded + this.take, this.total);
observer.next(new PageAction(this.firstLoaded));
}
if (up && firstItemIndex <= this.firstLoaded) {
var nonVisibleBuffer = Math.floor(this.take * 0.3);
this.firstLoaded = normalize(firstItemIndex - nonVisibleBuffer);
observer.next(new ScrollAction(this.rowOffset(this.firstLoaded)));
this.lastLoaded = Math.min(this.firstLoaded + this.take, this.total);
observer.next(new PageAction(this.firstLoaded));
}
};
ScrollerService.prototype.rowOffset = function (index) {
return this.rowHeightService.offset(index) + this.topOffset;
};
ScrollerService.prototype.rowsForHeight = function (height) {
return Math.ceil(height / this.rowHeightService.height(0));
};
ScrollerService.prototype.unsubscribe = function () {
if (this.scrollSubscription) {
this.scrollSubscription.unsubscribe();
this.scrollSubscription = undefined;
}
};
return ScrollerService;
}());
exports.ScrollerService = ScrollerService;
|
// All symbols in the Georgian block as per Unicode v3.2.0:
[
'\u10A0',
'\u10A1',
'\u10A2',
'\u10A3',
'\u10A4',
'\u10A5',
'\u10A6',
'\u10A7',
'\u10A8',
'\u10A9',
'\u10AA',
'\u10AB',
'\u10AC',
'\u10AD',
'\u10AE',
'\u10AF',
'\u10B0',
'\u10B1',
'\u10B2',
'\u10B3',
'\u10B4',
'\u10B5',
'\u10B6',
'\u10B7',
'\u10B8',
'\u10B9',
'\u10BA',
'\u10BB',
'\u10BC',
'\u10BD',
'\u10BE',
'\u10BF',
'\u10C0',
'\u10C1',
'\u10C2',
'\u10C3',
'\u10C4',
'\u10C5',
'\u10C6',
'\u10C7',
'\u10C8',
'\u10C9',
'\u10CA',
'\u10CB',
'\u10CC',
'\u10CD',
'\u10CE',
'\u10CF',
'\u10D0',
'\u10D1',
'\u10D2',
'\u10D3',
'\u10D4',
'\u10D5',
'\u10D6',
'\u10D7',
'\u10D8',
'\u10D9',
'\u10DA',
'\u10DB',
'\u10DC',
'\u10DD',
'\u10DE',
'\u10DF',
'\u10E0',
'\u10E1',
'\u10E2',
'\u10E3',
'\u10E4',
'\u10E5',
'\u10E6',
'\u10E7',
'\u10E8',
'\u10E9',
'\u10EA',
'\u10EB',
'\u10EC',
'\u10ED',
'\u10EE',
'\u10EF',
'\u10F0',
'\u10F1',
'\u10F2',
'\u10F3',
'\u10F4',
'\u10F5',
'\u10F6',
'\u10F7',
'\u10F8',
'\u10F9',
'\u10FA',
'\u10FB',
'\u10FC',
'\u10FD',
'\u10FE',
'\u10FF'
]; |
var positionAndSizeGrid = {
"1": [1, 1, 248, 123],
"2": [1, 251, 123, 123],
"3": [1, 376, 248, 248],
"4": [1, 626, 248, 123],
"5": [1, 876, 123, 123],
"6": [126, 1, 123, 248],
"7": [126, 126, 248, 248],
"8": [251, 376, 123, 123],
"9": [251, 501, 248, 248],
"10": [126, 626, 123, 123],
"11": [126, 751, 248, 248],
"12": [376, 1, 123, 123],
"13": [376, 126, 123, 123],
"14": [376, 251, 248, 123],
"15": [376, 751, 123, 123],
"16": [376, 876, 247, 123],
};
function addImageToGrid(num_box, num_grid, url_image, url_obra, titulo_obra, id_grid) {
var div_block = document.createElement("div");
var positionAndSize = positionAndSizeGrid["" + num_box];
// Dandole posicion
div_block.style.position = "absolute";
div_block.style.top = positionAndSize[0] + "px";
div_block.style.left = positionAndSize[1]+ "px";
// Dandole tamano
div_block.style.width = positionAndSize[2] + "px";
div_block.style.height = positionAndSize[3] + "px";
var img = new Image();
img.onload = function() {
// Se le da la clase al div
div_block.className = "catalogo-image";
// Se crea el div con la informacion
var div_info = document.createElement("div");
div_info.className = "info-image";
// Se crea y se agrega el texto (titulo)
var title_catalogoImage = document.createElement("h2");
title_catalogoImage.innerHTML = titulo_obra;
div_info.appendChild(title_catalogoImage);
// Se agrega los divs al block
div_block.appendChild(img);
div_block.appendChild(div_info);
// Se redimensiona dependiendo del tamano de la imagen
var img_width = 0;
var img_height = 0;
var scalarWidth = 0;
var scalarHeight = 0;
// Imagenes pequeñas
if(num_box == 2 || num_box == 5 || num_box == 8 || num_box == 10 || num_box == 12 ||
num_box == 13 || num_box == 15 || num_box == 16) {
img_width = img.width * 0.2;
img_height = img.height * 0.2;
$(img).css('width', '' + img_width);
$(img).css('height', '' + img_height);
$(div_info).css('top', '2%');
scalarWidth = 0.35;
scalarHeight = 0.35;
}
// Imagenes medianas-verticales
else if(num_box == 6) {
img_width = img.width * 0.4;
img_height = img.height * 0.45;
$(img).css('width', '' + img_width);
$(img).css('height', '' + img_height);
$(div_info).css('top', '15%');
scalarWidth = 0.4;
scalarHeight = 0.4;
}
// Imagenes medianas-horizontales
else if(num_box == 1 || num_box == 4 || num_box == 14) {
img_width = img.width * 0.2;
img_height = img.height * 0.2;
$(img).css('width', '' + img_width);
$(img).css('height', '' + img_height);
scalarWidth = 0.4;
scalarHeight = 0.4;
}
// Imagenes grandes
else if(num_box == 3 || num_box == 7 || num_box == 9 || num_box == 11) {
img_width = img.width * 0.35;
img_height = img.height * 0.4;
$(img).css('width', '' + img_width);
$(img).css('height', '' + img_height);
$(div_info).css('top', '50%');
scalarWidth = 0.2;
scalarHeight = 0.2;
}
// Se agrega la animacion
$(div_block).hover(function() {
$(this).find('img').animate({width: img_width * scalarWidth, height: img_height * scalarHeight, marginTop: 10, marginLeft: 10}, 500);
}, function() {
$(this).find('img').animate({width: img_width, height: img_height, marginTop: 0, marginLeft: 0}, 300);
});
// Se le linkea a su obra
$(div_block).click(function() {
$(location).attr("href", url_obra);
});
// Se agrega el div_block al grid
$(id_grid).append(div_block);
};
img.onerror = function () {
div_block.className = "catalogo-noImage";
$(id_grid).append(div_block);
};
img.src = url_image;
}
|
'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Club = mongoose.model('Club');
/**
* Globals
*/
var user,
club;
/**
* Unit tests
*/
describe('Club Model Unit Tests:', function () {
beforeEach(function (done) {
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: 'username',
password: 'M3@n.jsI$Aw3$0m3'
});
user.save(function () {
club = new Club({
title: 'Club Title',
content: 'Club Content',
user: user
});
done();
});
});
describe('Method Save', function () {
it('should be able to save without problems', function (done) {
this.timeout(10000);
club.save(function (err) {
should.not.exist(err);
return done();
});
});
it('should be able to show an error when try to save without title', function (done) {
club.title = '';
club.save(function (err) {
should.exist(err);
return done();
});
});
});
afterEach(function (done) {
Club.remove().exec(function () {
User.remove().exec(done);
});
});
});
|
var tape = require('tape')
var queue = require('../')
tape('pop sync', function (t) {
t.plan(2)
var q = queue()
var results = []
q.push(function (cb) {
results.push(1)
cb()
})
q.push(function (cb) {
results.push(2)
cb()
})
q.pop()
q.start(function (err) {
t.error(err)
t.deepEqual(results, [ 1 ])
})
})
tape('pop async', function (t) {
t.plan(2)
var q = queue({ concurrency: 1 })
var results = []
q.push(function (cb) {
results.push(1)
setTimeout(cb, 10)
})
q.push(function (cb) {
results.push(2)
cb()
})
q.start(function (err) {
t.error(err)
t.deepEqual(results, [ 1 ])
})
q.pop()
})
tape('shift sync', function (t) {
t.plan(2)
var q = queue()
var results = []
q.push(function (cb) {
results.push(1)
cb()
})
q.push(function (cb) {
results.push(2)
cb()
})
q.shift()
q.start(function (err) {
t.error(err)
t.deepEqual(results, [ 2 ])
})
})
tape('shift async', function (t) {
t.plan(2)
var q = queue({ concurrency: 1 })
var results = []
q.push(function (cb) {
results.push(1)
setTimeout(cb, 10)
})
q.push(function (cb) {
results.push(2)
cb()
})
q.start(function (err) {
t.error(err)
t.deepEqual(results, [ 1 ])
})
q.shift()
})
tape('slice sync', function (t) {
t.plan(3)
var q = queue()
var results = []
q.push(function (cb) {
results.push(1)
cb()
})
q.push(function (cb) {
results.push(2)
cb()
})
t.equal(q, q.slice(0, 1))
q.start(function (err) {
t.error(err)
t.deepEqual(results, [ 1 ])
})
})
tape('slice async', function (t) {
t.plan(3)
var q = queue({ concurrency: 1 })
var results = []
q.push(function (cb) {
results.push(1)
setTimeout(cb, 10)
})
q.push(function (cb) {
results.push(2)
cb()
})
q.start(function (err) {
t.error(err)
t.deepEqual(results, [ 1 ])
})
t.equal(q, q.slice(0, 0))
})
tape('reverse sync', function (t) {
t.plan(3)
var q = queue()
var results = []
q.push(function (cb) {
results.push(1)
cb()
})
q.push(function (cb) {
results.push(2)
cb()
})
t.equal(q, q.reverse())
q.start(function (err) {
t.error(err)
t.deepEqual(results, [ 2, 1 ])
})
})
tape('indexOf', function (t) {
t.plan(3)
var q = queue()
var results = []
q.push(job)
q.push(job)
t.equal(q.indexOf(job), 0)
q.start(function (err) {
t.error(err)
t.deepEqual(results, [ 1, 2 ])
})
function job (cb) {
results.push(results.length + 1)
cb()
}
})
tape('lastIndexOf', function (t) {
t.plan(3)
var q = queue()
var results = []
q.push(job)
q.push(job)
t.equal(q.lastIndexOf(job), 1)
q.start(function (err) {
t.error(err)
t.deepEqual(results, [ 1, 2 ])
})
function job (cb) {
results.push(results.length + 1)
cb()
}
})
|
var templates = loadTemplates();
var types = Type.getTypes();
var callback_tmp = null;
(function() {
if (localStorage[PREFIX + "noMoreTutrial"]) {
return;
}
localStorage[PREFIX + "noMoreTutrial"] = "true";
var sample = new Template();
sample.title = "sample";
sample.body = "----\ntitle: %{title}\nurl: %{url}\nI am %{author}, %{hoge}!\n----";
templates.push(sample);
saveTemplates();
setUserDefined('var result = {\n author: "yatemmma",\n hoge:"Hello benrychan"\n};\nreturn result;\n');
})();
function openOptionPage() {
chrome.tabs.create({
"url": chrome.extension.getURL(chrome.app.getDetails().options_page)
});
}
function saveTemplates() {
var jsonArray = templates.map(function(template) {
return template.json();
});
localStorage[PREFIX + "templates"] = JSON.stringify(jsonArray);
}
function loadTemplates() {
var jsonArray = JSON.parse(localStorage[PREFIX + "templates"] || "[]");
var templates = jsonArray.map(function(json) {
return Template.fromJson(JSON.parse(json));
});
return templates;
}
function addTemplate(template) {
templates.push(template);
saveTemplates();
}
function updateTemplate(template) {
var updated = templates.map(function(item) {
if (item.id == template.id) {
return template;
}
return item;
});
templates = updated;
saveTemplates();
}
function deleteTemplate(template) {
var deleted = templates.filter(function(item) {
return item != template;
});
templates = deleted;
saveTemplates();
}
function getTemplates() {
return templates;
}
function getTypes() {
return types;
}
function getUserDefined() {
return JSON.parse(localStorage[PREFIX + "userDefined"] || null);
}
function setUserDefined(text) {
localStorage[PREFIX + "userDefined"] = JSON.stringify(text);
types.user_defined.code = text; // TODO 汎用的にする
}
function executeTemplate(template, callback) {
callback_tmp = callback;
recursiveExecute(template, [].concat(template.types.reverse()), []);
}
function recursiveExecute(template, executeTypes, results) {
if (executeTypes.length == 0) {
executeCallback(template, results);
}
chrome.tabs.executeScript(null, { file: "jquery.2.0.3.js" }, function() {
chrome.tabs.executeScript(null, { code: getExecuteCode(executeTypes.shift()) }, function(result) {
if (typeof result[0] == 'string') {
callback_tmp(result[0]);
} else {
recursiveExecute(template, [].concat(executeTypes), results.concat(result[0]));
}
});
});
}
function getExecuteCode(type) {
var execute = (!type || !types[type]) ? "return {};" : types[type].code;
var code = "(function(){ try {" + execute + "} catch(e) { return e.stack; } })();";
return code;
}
function executeCallback(template, results) {
var text = template.body;
if (text) {
results.forEach(function(result) {
text = replaceText(text, result);
});
} else {
text = allParams(results);
}
callback_tmp(text);
callback_tmp = null;
}
function allParams(results) {
var allParamsText = "";
results.forEach(function(result) {
for (var key in result) {
allParamsText = key + ": " + result[key] + "\n" + allParamsText;
}
});
return allParamsText;
}
function replaceText(templateBody, params) {
if (!params) return templateBody;
for (var key in params) {
var reg = new RegExp("%{" + key + "}", "g");
templateBody = templateBody.replace(reg, params[key]);
}
return templateBody;
} |
import { resolve } from 'path'
import { app, BrowserWindow, Menu, ipcMain } from 'electron'
import windowState from 'electron-window-state'
import { initDebug, buildDevMenu } from './dev-utils'
import { LOG_REGISTER, LOG_OPTIONS } from './events'
import settings, { init as initSettings, KEY_LOGGER } from './settings'
import { initIpc } from './logger'
import menuHelper from './menu'
import registerFileOpenEvents from './files/open'
import registerXmlSwitcherEvents from './files/switcher'
const HTML_PATH = resolve(__dirname, '..', 'src/client/app.html')
const WIDTH = 1024
const HEIGHT = 728
let menu
let mainWindow = null
if (process.platform !== 'darwin') {
app.on('window-all-closed', () => app.quit())
}
async function onReady() {
await initDebug()
await initSettings()
const mainWindowState = windowState({ defaultWidth: WIDTH, defaultHeight: HEIGHT })
const { x, y, width, height } = mainWindowState
mainWindow = new BrowserWindow({ show: false, x, y, width, height })
mainWindow.loadURL(`file://${HTML_PATH}`)
mainWindow.on('closed', () => (mainWindow = null))
mainWindow.webContents.on('did-finish-load', () => {
mainWindow.show()
mainWindow.focus()
})
const loggerOptions = await settings.get(KEY_LOGGER)
const log = initIpc(mainWindow.webContents, 'Main', loggerOptions)
log.debug('Initialized the logger', loggerOptions)
ipcMain.on(LOG_REGISTER, (event) => {
log.debug('Sending logger options to render process')
event.sender.send(LOG_OPTIONS, loggerOptions)
})
// Register all events
// TODO add helper to do this, rename all functions to register()
registerFileOpenEvents()
registerXmlSwitcherEvents()
// Build menu
const template = menuHelper.build(mainWindow)
menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
// Dev mode menu
buildDevMenu(mainWindow)
// Manage window state
mainWindowState.manage(mainWindow)
}
app.on('ready', onReady)
|
var Event = require('compose-event')
var Notify = require('compose-notification')
// If a page has an element .form-flash, trigger a notification
//
Event.change(function(){
var flash = document.querySelector('.form-flash')
if (flash) {
var type = flash.dataset.type || 'error'
if (type == 'info') type = 'action'
Notify[type](flash.textContent.trim())
flash.classList.add('hidden')
}
})
|
var titles = [
'Mr', 'Mrs', 'Dr', 'Prof', 'Lord', 'Lady', 'Sir', 'Madam'
];
var firstNames = [
'Leanne', 'Edward', 'Haydee', 'Lyle', 'Shea', 'Curtis', 'Roselyn', 'Marcus', 'Lyn', 'Lloyd',
'Isabelle', 'Francis', 'Olivia', 'Roman', 'Myong', 'Jamie', 'Alexis', 'Vernon', 'Chloe', 'Max',
'Kirstie', 'Tyler', 'Katelin', 'Alejandro', 'Hannah', 'Gavin', 'Lynetta', 'Russell', 'Neida',
'Kurt', 'Dannielle', 'Aiden', 'Janett', 'Vaughn', 'Michelle', 'Brian', 'Maisha', 'Theo', 'Emma',
'Cedric', 'Jocelyn', 'Darrell', 'Grace', 'Ivan', 'Rikki', 'Erik', 'Madeleine', 'Rufus',
'Florance', 'Raymond', 'Jenette', 'Danny', 'Kathy', 'Michael', 'Layla', 'Rolf', 'Selma', 'Anton',
'Rosie', 'Craig', 'Victoria', 'Andy', 'Lorelei', 'Drew', 'Yuri', 'Miles', 'Raisa', 'Rico',
'Rosanne', 'Cory', 'Dori', 'Travis', 'Joslyn', 'Austin', 'Haley', 'Ian', 'Liza', 'Rickey',
'Susana', 'Stephen', 'Richelle', 'Lance', 'Jetta', 'Heath', 'Juliana', 'Rene', 'Madelyn', 'Stan',
'Eleanore', 'Jason', 'Alexa', 'Adam', 'Jenna', 'Warren', 'Cecilia', 'Benito', 'Elaine', 'Mitch',
'Raylene', 'Cyrus'
];
var lastNames = [
'Flinn', 'Bryd', 'Milligan', 'Keesee', 'Mercer', 'Chapman', 'Zobel', 'Carter', 'Pettey',
'Starck', 'Raymond', 'Pullman', 'Drolet', 'Higgins', 'Matzen', 'Tindel', 'Winter', 'Charley',
'Schaefer', 'Hancock', 'Dampier', 'Garling', 'Verde', 'Lenihan', 'Rhymer', 'Pleiman', 'Dunham',
'Seabury', 'Goudy', 'Latshaw', 'Whitson', 'Cumbie', 'Webster', 'Bourquin', 'Young', 'Rikard',
'Brier', 'Luck', 'Porras', 'Gilmore', 'Turner', 'Sprowl', 'Rohloff', 'Magby', 'Wallis', 'Mullens',
'Correa', 'Murphy', 'Connor', 'Gamble', 'Castleman', 'Pace', 'Durrett', 'Bourne', 'Hottle',
'Oldman', 'Paquette', 'Stine', 'Muldoon', 'Smit', 'Finn', 'Kilmer', 'Sager', 'White', 'Friedrich',
'Fennell', 'Miers', 'Carroll', 'Freeman', 'Hollis', 'Neal', 'Remus', 'Pickering', 'Woodrum',
'Bradbury', 'Caffey', 'Tuck', 'Jensen', 'Shelly', 'Hyder', 'Krumm', 'Hundt', 'Seal', 'Pendergast',
'Kelsey', 'Milling', 'Karst', 'Helland', 'Risley', 'Grieve', 'Paschall', 'Coolidge', 'Furlough',
'Brandt', 'Cadena', 'Rebelo', 'Leath', 'Backer', 'Bickers', 'Cappel'
];
var companies = [
'Unilogic', 'Solexis', 'Dalserve', 'Terrasys', 'Pancast', 'Tomiatech', 'Kancom', 'Iridimax',
'Proline', 'Qualcore', 'Thermatek', 'VTGrafix', 'Sunopia', 'WestGate', 'Chromaton', 'Tecomix',
'Galcom', 'Zatheon', 'OmniTouch', 'Hivemind', 'MultiServ', 'Citisys', 'Polygan', 'Dynaroc',
'Storex', 'Britech', 'Thermolock', 'Cryptonica', 'LoopSys', 'ForeTrust', 'TrueXT', 'LexiconLabs',
'Bellgate', 'Dynalab', 'Logico', 'Terralabs', 'CoreMax', 'Polycore', 'Infracom', 'Coolinga',
'MultiLingua', 'Conixco', 'QuadNet', 'FortyFour', 'TurboSystems', 'Optiplex', 'Nitrocam',
'CoreXTS', 'PeerSys', 'FastMart', 'Westercom', 'Templatek', 'Cirpria', 'FastFreight', 'Baramax',
'Superwire', 'Celmax', 'Connic', 'Forecore', 'SmartSystems', 'Ulogica', 'Seelogic', 'DynaAir',
'OpenServ', 'Maxcast', 'SixtySix', 'Protheon', 'SkyCenta', 'Eluxa', 'GrafixMedia', 'VenStrategy',
'Keycast', 'Opticast', 'Cameratek', 'CorpTek', 'Sealine', 'Playtech', 'Anaplex', 'Hypervision',
'Xenosys', 'Hassifix', 'Infratouch', 'Airconix', 'StrategyLine', 'Helixicon', 'MediaDime',
'NitroSystems', 'Viewtopia', 'Cryosoft', 'DuoServe', 'Acousticom', 'Freecast', 'CoreRobotics',
'Quadtek', 'Haltheon', 'TrioSys', 'Amsquare', 'Sophis', 'Keysoft', 'Creatonix'
];
var tlds = [
'com', 'org', 'net', 'info', 'edu', 'gov', 'co', 'biz', 'name', 'me', 'mobi', 'club', 'xyz', 'eu'
];
var streets = [
'Warner Street', 'Ceder Avenue', 'Glendale Road', 'Chester Square', 'Beechmont Parkway',
'Carter Street', 'Hinton Road', 'Pitman Street', 'Winston Road', 'Cottontail Road',
'Buckley Street', 'Concord Avenue', 'Clemont Street', 'Sleepy Lane', 'Bushey Crescent',
'Randolph Street', 'Radcliffe Road', 'Canal Street', 'Ridgewood Drive', 'Highland Drive',
'Orchard Road', 'Foster Walk', 'Walford Way', 'Harrington Crescent', 'Emmet Road',
'Berkeley Street', 'Clarendon Street', 'Sherman Road', 'Mount Street', 'Hunter Street',
'Pearl Street', 'Barret Street', 'Taylor Street', 'Shaftsbury Avenue', 'Paxton Street',
'Park Avenue', 'Seaside Drive', 'Tavistock Place', 'Prospect Place', 'Harvard Avenue',
'Elton Way', 'Green Street', 'Appleton Street', 'Banner Street', 'Piermont Drive', 'Brook Street',
'Main Street', 'Fairmont Avenue', 'Arlington Road', 'Rutherford Street', 'Windsor Avenue',
'Maple Street', 'Wandle Street', 'Grosvenor Square', 'Hunt Street', 'Haredale Road',
'Glenn Drive', 'Mulholland Drive', 'Baker Street', 'Fuller Road', 'Coleman Avenue', 'Wall Street',
'Robinson Street', 'Blakeley Street', 'Alexander Avenue', 'Gartland Street', 'Wooster Road',
'Brentwood Drive', 'Colwood Place', 'Rivington Street', 'Bramble Lane', 'Hartswood Road',
'Albion Place', 'Waverton Street', 'Sawmill Lane', 'Templeton Parkway', 'Hill Street',
'Marsham Street', 'Stockton Lane', 'Lake Drive', 'Elm Street', 'Winchester Drive',
'Crockett Street', 'High Street', 'Longford Crescent', 'Moreland Street', 'Sterling Street',
'Golden Lane', 'Mercer Street', 'Dunstable Street', 'Chestnut Walk', 'Rutland Drive',
'Buckfield Lane', 'Pembrooke Street', 'Tower Lane', 'Willow Avenue', 'Faraday Street',
'Springfield Street', 'Crawford Street', 'Hudson Street'
];
var cities = [
'Beaverton', 'Stanford', 'Baltimore', 'Newcastle', 'Halifax', 'Rockhampton', 'Coventry',
'Medford', 'Boulder', 'Dover', 'Waterbury', 'Christchurch', 'Manchester', 'Perth', 'Norwich',
'Redmond', 'Plymouth', 'Tacoma', 'Newport', 'Bradford', 'Aspen', 'Wellington', 'Oakland',
'Norfolk', 'Durham', 'Portsmouth', 'Detroit', 'Portland', 'Northampton', 'Dayton', 'Charleston',
'Irvine', 'Dallas', 'Albany', 'Petersburg', 'Melbourne', 'Southampton', 'Stafford', 'Bridgeport',
'Fairfield', 'Dundee', 'Spokane', 'Oakleigh', 'Bristol', 'Sacramento', 'Sheffield', 'Lewisburg',
'Miami', 'Brisbane', 'Denver', 'Kingston', 'Burwood', 'Rochester', 'Fresno', 'Cardiff',
'Auckland', 'Sudbury', 'Hastings', 'Reno', 'Hillboro', 'Palmerston', 'Oxford', 'Hobart',
'Atlanta', 'Wilmington', 'Vancouver', 'Youngstown', 'Hartford', 'London', 'Danbury', 'Birmingham',
'Columbia', 'Dublin', 'Chicago', 'Toronto', 'Orlando', 'Toledo', 'Pheonix', 'Bakersfield',
'Nottingham', 'Newark', 'Fargo', 'Walkerville', 'Exeter', 'Woodville', 'Greenville', 'Frankston',
'Bangor', 'Seattle', 'Canterbury', 'Colchester', 'Boston', 'York', 'Cambridge', 'Brighton',
'Lancaster', 'Adelaide', 'Cleveland', 'Telford', 'Richmond'
];
var countries = [
'Andorra', 'United Arab Emirates', 'Afghanistan', 'Antigua and Barbuda', 'Anguilla', 'Albania',
'Armenia', 'Angola', 'Antarctica', 'Argentina', 'American Samoa', 'Austria', 'Australia', 'Aruba',
'Åland Islands', 'Azerbaijan', 'Bosnia and Herzegovina', 'Barbados', 'Bangladesh', 'Belgium',
'Burkina Faso', 'Bulgaria', 'Bahrain', 'Burundi', 'Benin', 'Saint Barthélemy', 'Bermuda',
'Brunei Darussalam', 'Bolivia, Plurinational State of', 'Bonaire, Sint Eustatius and Saba',
'Brazil', 'Bahamas', 'Bhutan', 'Bouvet Island', 'Botswana', 'Belarus', 'Belize', 'Canada',
'Cocos (Keeling) Islands', 'Congo, the Democratic Republic of the', 'Central African Republic',
'Congo', 'Switzerland', 'Côte d\'Ivoire', 'Cook Islands', 'Chile', 'Cameroon', 'China',
'Colombia', 'Costa Rica', 'Cuba', 'Cabo Verde', 'Curaçao', 'Christmas Island', 'Cyprus',
'Czechia', 'Germany', 'Djibouti', 'Denmark', 'Dominica', 'Dominican Republic', 'Algeria',
'Ecuador', 'Estonia', 'Egypt', 'Western Sahara', 'Eritrea', 'Spain', 'Ethiopia', 'Finland',
'Fiji', 'Falkland Islands (Malvinas)', 'Micronesia, Federated States of', 'Faroe Islands',
'France', 'Gabon', 'United Kingdom of Great Britain and Northern Ireland', 'Grenada', 'Georgia',
'French Guiana', 'Guernsey', 'Ghana', 'Gibraltar', 'Greenland', 'Gambia', 'Guinea', 'Guadeloupe',
'Equatorial Guinea', 'Greece', 'South Georgia and the South Sandwich Islands', 'Guatemala',
'Guam', 'Guinea-Bissau', 'Guyana', 'Hong Kong', 'Heard Island and McDonald Islands', 'Honduras',
'Croatia', 'Haiti', 'Hungary', 'Indonesia', 'Ireland', 'Israel', 'Isle of Man', 'India',
'British Indian Ocean Territory', 'Iraq', 'Iran, Islamic Republic of', 'Iceland', 'Italy',
'Jersey', 'Jamaica', 'Jordan', 'Japan', 'Kenya', 'Kyrgyzstan', 'Cambodia', 'Kiribati', 'Comoros',
'Saint Kitts and Nevis', 'Korea, Democratic People\'s Republic of', 'Korea, Republic of',
'Kuwait', 'Cayman Islands', 'Kazakhstan', 'Lao People\'s Democratic Republic', 'Lebanon',
'Saint Lucia', 'Liechtenstein', 'Sri Lanka', 'Liberia', 'Lesotho', 'Lithuania', 'Luxembourg',
'Latvia', 'Libya', 'Morocco', 'Monaco', 'Moldova, Republic of', 'Montenegro',
'Saint Martin (French part)', 'Madagascar', 'Marshall Islands', 'North Macedonia', 'Mali',
'Myanmar', 'Mongolia', 'Macao', 'Northern Mariana Islands', 'Martinique', 'Mauritania',
'Montserrat', 'Malta', 'Mauritius', 'Maldives', 'Malawi', 'Mexico', 'Malaysia', 'Mozambique',
'Namibia', 'New Caledonia', 'Niger', 'Norfolk Island', 'Nigeria', 'Nicaragua', 'Netherlands',
'Norway', 'Nepal', 'Nauru', 'Niue', 'New Zealand', 'Oman', 'Panama', 'Peru', 'French Polynesia',
'Papua New Guinea', 'Philippines', 'Pakistan', 'Poland', 'Saint Pierre and Miquelon', 'Pitcairn',
'Puerto Rico', 'Palestine, State of', 'Portugal', 'Palau', 'Paraguay', 'Qatar', 'Réunion',
'Romania', 'Serbia', 'Russian Federation', 'Rwanda', 'Saudi Arabia', 'Solomon Islands',
'Seychelles', 'Sudan', 'Sweden', 'Singapore', 'Saint Helena, Ascension and Tristan da Cunha',
'Slovenia', 'Svalbard and Jan Mayen', 'Slovakia', 'Sierra Leone', 'San Marino', 'Senegal',
'Somalia', 'Suriname', 'South Sudan', 'Sao Tome and Principe', 'El Salvador',
'Sint Maarten (Dutch part)', 'Syrian Arab Republic', 'Eswatini', 'Turks and Caicos Islands',
'Chad', 'French Southern Territories', 'Togo', 'Thailand', 'Tajikistan', 'Tokelau', 'Timor-Leste',
'Turkmenistan', 'Tunisia', 'Tonga', 'Turkey', 'Trinidad and Tobago', 'Tuvalu',
'Taiwan, Province of China', 'Tanzania, United Republic of', 'Ukraine', 'Uganda',
'United States Minor Outlying Islands', 'United States of America', 'Uruguay', 'Uzbekistan',
'Holy See', 'Saint Vincent and the Grenadines', 'Venezuela, Bolivarian Republic of',
'Virgin Islands, British', 'Virgin Islands, U.S.', 'Viet Nam', 'Vanuatu', 'Wallis and Futuna',
'Samoa', 'Yemen', 'Mayotte', 'South Africa', 'Zambia', 'Zimbabwe'
];
var countryCodes = [
'AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AO', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AW', 'AX', 'AZ',
'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BL', 'BM', 'BN', 'BO', 'BQ', 'BR', 'BS',
'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN',
'CO', 'CR', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EE',
'EG', 'EH', 'ER', 'ES', 'ET', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF',
'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM',
'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', 'JM',
'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KP', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC',
'LI', 'LK', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'ME', 'MF', 'MG', 'MH', 'MK',
'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA',
'NC', 'NE', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG',
'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RS', 'RU', 'RW',
'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'SS',
'ST', 'SV', 'SX', 'SY', 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO',
'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UM', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI',
'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'ZA', 'ZM', 'ZW'
];
var colors = [
'aliceblue', 'antiquewhite', 'aqua', 'aquamarine', 'azure', 'beige', 'bisque', 'black',
'blanchedalmond', 'blue', 'blueviolet', 'brown', 'burlywood', 'cadetblue', 'chartreuse',
'chocolate', 'coral', 'cornflowerblue', 'cornsilk', 'crimson', 'cyan', 'darkblue', 'darkcyan',
'darkgoldenrod', 'darkgray', 'darkgreen', 'darkkhaki', 'darkmagenta', 'darkolivegreen',
'darkorange', 'darkorchid', 'darkred', 'darksalmon', 'darkseagreen', 'darkslateblue',
'darkslategray', 'darkturquoise', 'darkviolet', 'deeppink', 'deepskyblue', 'dimgray',
'dodgerblue', 'firebrick', 'floralwhite', 'forestgreen', 'fuchsia', 'gainsboro', 'ghostwhite',
'gold', 'goldenrod', 'gray', 'green', 'greenyellow', 'honeydew', 'hotpink', 'indianred', 'indigo',
'ivory', 'khaki', 'lavender', 'lavenderblush', 'lawngreen', 'lemonchiffon', 'lightblue',
'lightcoral', 'lightcyan', 'lightgoldenrodyellow', 'lightgray', 'lightgreen', 'lightpink',
'lightsalmon', 'lightseagreen', 'lightskyblue', 'lightslategray', 'lightsteelblue', 'lightyellow',
'lime', 'limegreen', 'linen', 'magenta', 'maroon', 'mediumaquamarine', 'mediumblue',
'mediumorchid', 'mediumpurple', 'mediumseagreen', 'mediumslateblue', 'mediumspringgreen',
'mediumturquoise', 'mediumvioletred', 'midnightblue', 'mintcream', 'mistyrose', 'moccasin',
'navajowhite', 'navy', 'oldlace', 'olive', 'olivedrab', 'orange', 'orangered', 'orchid',
'palegoldenrod', 'palegreen', 'paleturquoise', 'palevioletred', 'papayawhip', 'peachpuff', 'peru',
'pink', 'plum', 'powderblue', 'purple', 'rebeccapurple', 'red', 'rosybrown', 'royalblue',
'saddlebrown', 'salmon', 'sandybrown', 'seagreen', 'seashell', 'sienna', 'silver', 'skyblue',
'slateblue', 'slategray', 'snow', 'springgreen', 'steelblue', 'tan', 'teal', 'thistle', 'tomato',
'turquoise', 'violet', 'wheat', 'white', 'whitesmoke', 'yellow', 'yellowgreen'
];
var lorem = [
'lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipiscing', 'elit', 'morbi',
'vulputate', 'eros', 'ut', 'mi', 'laoreet', 'viverra', 'nunc', 'lacinia', 'non', 'condimentum',
'aenean', 'lacus', 'nisl', 'auctor', 'at', 'tortor', 'ac', 'fringilla', 'sodales', 'pretium',
'quis', 'iaculis', 'in', 'aliquam', 'ultrices', 'felis', 'accumsan', 'ornare', 'etiam',
'elementum', 'aliquet', 'finibus', 'maecenas', 'dignissim', 'vel', 'blandit', 'placerat', 'sed',
'tempor', 'ex', 'faucibus', 'velit', 'nam', 'erat', 'augue', 'quisque', 'nulla', 'maximus',
'vitae', 'e', 'lobortis', 'euismod', 'tristique', 'metus', 'vehicula', 'purus', 'diam', 'mollis',
'neque', 'eu', 'porttitor', 'mauris', 'a', 'risus', 'orci', 'tincidunt', 'scelerisque',
'vestibulum', 'dui', 'ante', 'posuere', 'turpis', 'enim', 'cras', 'massa', 'cursus', 'suscipit',
'tempus', 'facilisis', 'ultricies', 'i', 'eget', 'imperdiet', 'donec', 'arcu', 'ligula',
'sagittis', 'hendrerit', 'justo', 'pellentesque', 'mattis', 'lacinia', 'leo', 'est', 'magna',
'nibh', 'sem', 'natoque', 'consequat', 'proin', 'eti', 'commodo', 'rhoncus', 'dictum', 'id',
'pharetra', 'sapien', 'gravida', 'sollicitudin', 'curabitur', 'au', 'nisi', 'bibendum', 'lectus',
'et', 'pulvinar', 'it', 'o', 'cit', 'con', 'el', 'u', 'ali', 'dia', 'lum', 'tem', 'en'
];
module.exports = {
titles: titles,
firstNames: firstNames,
lastNames: lastNames,
companies: companies,
tlds: tlds,
streets: streets,
cities: cities,
countries: countries,
countryCodes: countryCodes,
colors: colors,
lorem: lorem
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.