code stringlengths 2 1.05M |
|---|
(function () {
'use strict';
var IDriver = require('../utils/idriver'),
DriverError = require('../utils/drivererror'),
// XXX new logging infrastructure not landed yet
// logger = require('../logger'),
util = require('util');
try {
var SubDriver = require('node-etcd');
} catch (e) {
// XXX new logging infrastructure not landed yet
// logger.error('IDriver', 'You must use `npm install node-etcd` if you want to use this adapter');
return;
}
var Etcd = function () {
// Provides slave and master url properties
IDriver.apply(this, arguments);
this.slave = this.drivers.shift();
this.master = this.drivers.pop();
var client = new SubDriver(
this.slave.hostname || '127.0.0.1',
this.slave.port || 4001
);
var prefix = '/hipache/';
if (this.slave.hash) {
prefix = this.slave.hash.substr(1);
}
// XXX new logging infrastructure not landed yet
// if (this.slave.path && this.slave.path !== '/') {
// logger.warn('Etcd', 'You specified a path while this driver doesn\'t support databases');
// }
// if (this.slave.auth) {
// logger.error('Etcd', 'This driver doesn\'t support authentication!!!');
// }
// client.on('error', function (err) {
// this.emit('error', err);
// }.bind(this));
// client.on('ready', function (err) {
// clientReady = true;
// if (!this.master || clientWriteReady) {
// this.emit('ready', err);
// }
// }.bind(this));
// The optional master
// var clientWriteReady = false;
var clientWrite;
if (this.master) {
clientWrite = new SubDriver(
this.master.hostname || '127.0.0.1',
this.master.port || 4001
);
// XXX new logging infrastructure not landed yet
// if (this.master.auth) {
// logger.error('Etcd', 'This driver doesn\'t support authentication!!!');
// }
// clientWrite.on('error', function (err) {
// this.emit('error', err);
// }.bind(this));
// clientWrite.on('ready', function (err) {
// clientWriteReady = true;
// if (clientReady) {
// this.emit('ready', err);
// }
// }.bind(this));
}
var connected = false;
Object.defineProperty(this, 'connected', {
get: function () {
// XXX implement me!
return true;
}
});
var sayErr = function (err) {
connected = false;
this.emit(this.ERROR, new DriverError(DriverError.UNSPECIFIED, err));
}.bind(this);
this.read = function (hosts, callback) {
var result = [];
var first = hosts[0];
hosts = hosts.map(function (host) {
return prefix + 'frontend:' + host;
});
hosts.push(prefix + 'dead:' + first);
var lookup = function () {
var host = hosts.shift();
if (!host) {
callback(null, result);
return;
}
client.get(host, { sorted: true }, function (err, data) {
if (err && err.errorCode !== 100) {
sayErr(err);
callback(err);
return;
}
if (!data.node || !data.node.dir || !data.node.nodes) {
result.push([ ]);
return lookup();
}
var backend = [ 'stub' ];
data.node.nodes.forEach(function (node) {
backend.push(node.value);
});
result.push(backend);
lookup();
});
};
lookup();
};
this.create = function (host, vhost, callback) {
client.set(
prefix + 'frontend:' + host,
JSON.stringify([vhost]),
function (err, data) {
callback(err, JSON.parse(data ? data.node.value : '[]'));
}
);
};
this.add = function (host, backend, callback) {
client.get(
prefix + 'frontend:' + host,
function (err, data) {
data = JSON.parse(data.node.value);
data.push(backend);
client.set(prefix + 'frontend:' + host, JSON.stringify(data), function (err, data) {
callback(err, JSON.parse(data ? data.node.value : '[]'));
});
}
);
};
this.mark = function (frontend, id, url, len, ttl, callback) {
var cl = (clientWrite ? clientWrite : client);
client.get(
prefix + 'dead:' + frontend,
function (err, data) {
data = JSON.parse(data ? data.node.value : '[]');
data.push(id);
cl.set(
prefix + 'dead:' + frontend,
JSON.stringify(data),
{ttl: ttl},
callback
);
}
);
};
// XXX implement this
this.destructor = function () {
};
};
util.inherits(Etcd, IDriver);
module.exports = Etcd;
})();
|
/**
* Module dependencies.
*/
var start = require('./common')
, mongoose = start.mongoose
, assert = require('assert')
, Schema = mongoose.Schema
, ObjectId = Schema.ObjectId
, Document = require('../lib/document')
, EmbeddedDocument = require('../lib/types/embedded')
, DocumentObjectId = mongoose.Types.ObjectId;
/**
* Test Document constructor.
*/
function TestDocument () {
Document.apply(this, arguments);
};
/**
* Inherits from Document.
*/
TestDocument.prototype.__proto__ = Document.prototype;
/**
* Set a dummy schema to simulate compilation.
*/
var em = new Schema({ title: String, body: String });
em.virtual('works').get(function () {
return 'em virtual works'
});
var schema = new Schema({
test : String
, oids : [ObjectId]
, numbers : [Number]
, nested : {
age : Number
, cool : ObjectId
, deep : { x: String }
, path : String
, setr : String
}
, nested2 : {
nested: String
, yup : {
nested : Boolean
, yup : String
, age : Number
}
}
, em: [em]
});
TestDocument.prototype.$__setSchema(schema);
schema.virtual('nested.agePlus2').get(function (v) {
return this.nested.age + 2;
});
schema.virtual('nested.setAge').set(function (v) {
this.nested.age = v;
});
schema.path('nested.path').get(function (v) {
return this.nested.age + (v ? v : '');
});
schema.path('nested.setr').set(function (v) {
return v + ' setter';
});
/**
* Method subject to hooks. Simply fires the callback once the hooks are
* executed.
*/
TestDocument.prototype.hooksTest = function(fn){
fn(null, arguments);
};
describe('document: hooks:', function () {
it('step order', function(done){
var doc = new TestDocument()
, steps = 0
, awaiting = 0
, called = false;
// serial
doc.pre('hooksTest', function(next){
steps++;
setTimeout(function(){
// make sure next step hasn't executed yet
assert.equal(1, steps);
next();
}, 50);
});
doc.pre('hooksTest', function(next){
steps++;
next();
});
// parallel
doc.pre('hooksTest', true, function(next, done){
steps++;
assert.equal(3, steps);
setTimeout(function(){
assert.equal(4, steps);
}, 10);
setTimeout(function(){
steps++;
done();
}, 110);
next();
});
doc.pre('hooksTest', true, function(next, done){
steps++;
setTimeout(function(){
assert.equal(4, steps);
}, 10);
setTimeout(function(){
steps++;
done();
}, 110);
next();
});
doc.hooksTest(function(err){
assert.ifError(err);
assert.equal(6, steps);
done();
});
});
it('calling next twice does not break', function(done){
var doc = new TestDocument()
, steps = 0
, called = false;
doc.pre('hooksTest', function(next){
steps++;
next();
next();
});
doc.pre('hooksTest', function(next){
steps++;
next();
});
doc.hooksTest(function(err){
assert.ifError(err);
assert.equal(2, steps);
done();
});
});
it('calling done twice does not break', function(done){
var doc = new TestDocument()
, steps = 0
doc.pre('hooksTest', true, function(next, done){
steps++;
next();
done();
done();
});
doc.pre('hooksTest', true, function(next, done){
steps++;
next();
done();
done();
});
doc.hooksTest(function(err){
assert.ifError(err);
assert.equal(2, steps);
done();
});
});
it('errors from a serial hook', function(done){
var doc = new TestDocument()
, steps = 0
, called = false;
doc.pre('hooksTest', function(next){
steps++;
next();
});
doc.pre('hooksTest', function(next){
steps++;
next(new Error);
});
doc.pre('hooksTest', function(next){
steps++;
});
doc.hooksTest(function(err){
assert.ok(err instanceof Error);
assert.equal(2, steps);
done();
});
});
it('errors from last serial hook', function(done){
var doc = new TestDocument()
, called = false;
doc.pre('hooksTest', function(next){
next(new Error);
});
doc.hooksTest(function(err){
assert.ok(err instanceof Error);
done();
});
});
it('mutating incoming args via middleware', function(done){
var doc = new TestDocument();
doc.pre('set', function(next, path, val){
next(path, 'altered-' + val);
});
doc.set('test', 'me');
assert.equal('altered-me', doc.test);
done();
});
it('test hooks system errors from a parallel hook', function(done){
var doc = new TestDocument()
, steps = 0
, called = false;
doc.pre('hooksTest', true, function(next, done){
steps++;
next();
done();
});
doc.pre('hooksTest', true, function(next, done){
steps++;
next();
done();
});
doc.pre('hooksTest', true, function(next, done){
steps++;
next();
done(new Error);
});
doc.hooksTest(function(err){
assert.ok(err instanceof Error);
assert.equal(3, steps);
done();
});
});
it('passing two arguments to a method subject to hooks and return value', function(done){
var doc = new TestDocument()
, called = false;
doc.pre('hooksTest', function (next) {
next();
});
doc.hooksTest(function (err, args) {
assert.equal(2, args.length);
assert.equal(args[1], 'test');
done();
}, 'test')
});
it('hooking set works with document arrays (gh-746)', function(done){
var db = start();
var child = new Schema({ text: String });
child.pre('set', function (next, path, value, type) {
next(path, value, type);
});
var schema = new Schema({
name: String
, e: [child]
});
var S = db.model('docArrayWithHookedSet', schema);
var s = new S({ name: "test" });
s.e = [{ text: 'hi' }];
s.save(function (err) {
assert.ifError(err);
S.findById(s.id, function (err ,s) {
assert.ifError(err);
s.e = [{ text: 'bye' }];
s.save(function (err) {
assert.ifError(err);
S.findById(s.id, function (err, s) {
db.close();
assert.ifError(err);
assert.equal('bye', s.e[0].text);
done();
})
})
})
});
});
it('pre save hooks on sub-docs should not exec after validation errors', function(done){
var db = start();
var presave = false;
var child = new Schema({ text: { type: String, required: true }});
child.pre('save', function (next) {
presave = true;
next();
});
var schema = new Schema({
name: String
, e: [child]
});
var S = db.model('docArrayWithHookedSave', schema);
var s = new S({ name: 'hi', e: [{}] });
s.save(function (err) {
assert.ok(err);
assert.ok(err.errors['e.0.text']);
assert.equal(false, presave);
done();
});
});
it('post remove hooks on subdocuments work', function(done) {
var db = start();
var sub = Schema({ _id: Number });
var called = { pre: 0, post: 0 };
sub.pre('remove', function (next) {
called.pre++;
next();
});
sub.post('remove', function (doc) {
called.post++;
assert.ok(doc instanceof Document);
});
var par = Schema({ sub: [sub], name: String });
var M = db.model('post-remove-hooks-sub', par);
var m = new M({ sub: [{ _id: 1 }, { _id: 2 }] });
m.save(function (err) {
assert.ifError(err);
assert.equal(0, called.pre);
assert.equal(0, called.post);
M.findById(m, function(err, doc) {
assert.ifError(err);
doc.sub.id(1).remove();
doc.save(function (err) {
assert.ifError(err);
assert.equal(1, called.pre);
assert.equal(1, called.post);
// does not get called when not removed
doc.name = 'changed1';
doc.save(function (err) {
assert.ifError(err);
assert.equal(1, called.pre);
assert.equal(1, called.post);
doc.sub.id(2).remove();
doc.remove(function (err) {
assert.ifError(err);
assert.equal(2, called.pre);
assert.equal(2, called.post);
// does not get called twice
doc.remove(function (err) {
assert.ifError(err);
assert.equal(2, called.pre);
assert.equal(2, called.post);
done();
});
});
});
});
});
});
});
it('post save hooks on subdocuments work (gh-915)', function(done) {
var doneCalled = false;
var _done = function(e) {
if (!doneCalled) {
doneCalled = true;
done(e);
}
};
var db = start();
var called = { post: 0 };
var subSchema = new Schema({
name: String
});
subSchema.post('save', function(doc) {
called.post++;
try {
assert.ok(doc instanceof EmbeddedDocument);
}
catch (e) {
_done(e);
}
});
var postSaveHooks = new Schema({
subs: [subSchema]
});
var M = db.model('post-save-hooks-sub', postSaveHooks);
var m = new M({ subs: [
{ name: 'mee' },
{ name: 'moo' }
] });
m.save(function(err) {
assert.ifError(err);
assert.equal(2, called.post);
called.post = 0;
M.findById(m, function(err, doc) {
assert.ifError(err);
doc.subs.push({ name: 'maa' });
doc.save(function(err) {
assert.ifError(err);
assert.equal(3, called.post);
_done();
});
});
});
});
it("pre save hooks should run in parallel", function (done) {
// we set the time out to be double that of the validator - 1 (so that running in serial will be greater then that)
this.timeout(1000);
var db = start(),
count = 0
var SchemaWithPreSaveHook = new Schema ({
preference: String
});
SchemaWithPreSaveHook.pre('save', true, function hook (next, done) {
setTimeout(function () {
count++;
next();
if (count == 3) {
done(new Error("gaga"));
} else {
done();
}
}, 500);
});
var MWPSH = db.model('mwpsh', new Schema({subs: [SchemaWithPreSaveHook]}));
var m = new MWPSH({
subs: [
{
preference: "xx"
}
,
{
preference: "yy"
}
,
{
preference: "1"
}
,
{
preference: "2"
}
]
});
m.save(function (err) {
assert.equal(err.message, "gaga");
assert.equal(count, 4);
done();
});
})
});
|
'use strict';
class RoleHelper {
constructor(client) {
this.client = client;
}
hasUserRoleInServer(user, role, server) {
if (user.id === this.client.admin.id) return true;
if (!server || !server.roles) return false;
role = server.roles.get('name', role);
if (!role) return false;
return this.client.memberHasRole(user, role);
}
}
module.exports = RoleHelper; |
'use strict';
//global variables
var hours = ['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm', 'Total'];
var stores = [];
var total = [];
var tableElement;
var rowData;
//global functions
function hourHeader() { //print the hours of operation
var tableEl = document.getElementById('table');
var newRow = document.createElement('tr');
var storeName = document.createElement('th');
storeName.textContent = 'Stores';
newRow.setAttribute('id', 'tableFormat');
newRow.appendChild(storeName);
for (var i = 0; i < hours.length; i ++) {
var rowData = document.createElement('th');
rowData.textContent = hours[i];
newRow.appendChild(rowData);
}
tableEl.appendChild(newRow);
};
function getHourTotal() { //sum the amount of cookies sold each hour
total = [];
for (var i = 0; i < hours.length; i ++){
var hour = 0;
for (var j = 0; j < stores.length; j++){
var storeCount = stores[j].location[i];
hour = hour + storeCount;
}
total.push(hour);
}
};
function footerHeader() { //print the total cookies sold each hour
tableElement = document.getElementById('table');
var newRow = document.createElement('tr');
var blankHead = document.createElement('th');
newRow.setAttribute('id', 'tableTotal');
newRow.setAttribute('class', 'tableFormat');
blankHead.textContent = 'Totals';
newRow.appendChild(blankHead);
for (var i = 0; i < total.length; i ++) {
rowData = document.createElement('td');
rowData.textContent = total[i];
newRow.appendChild(rowData);
}
tableElement.appendChild(newRow);
};
function removeRow() {
var oldTableEl = document.getElementById('table');
var oldRowEl = document.getElementById('tableTotal');
var remove = oldTableEl.removeChild(oldRowEl);
remove;
}
//In progress. Looking to add an animation event to the index.html site
// function fadeOut(element) {
// var mouseMove = document.getElementById('footer');
//
// }
//Store object
function Store(minHourlyCust, maxHourlyCust, avgCookies, name){
this.minHourlyCust = parseInt(minHourlyCust);
this.maxHourlyCust = parseInt(maxHourlyCust);
this.avgCookies = avgCookies;
this.location = [];
this.name = name;
};
//methods
Store.prototype.cookiesPerHour = function() { //calculate the amount of cookies sold per hour
for (var i = 0; i < hours.length - 1; i++) {
var people = Math.round(Math.random() * (this.maxHourlyCust - this.minHourlyCust) + this.minHourlyCust);
var amount = Math.round(people * this.avgCookies);
this.location.push(amount);
}
};
Store.prototype.amount = function() { //add the total amount of cookies sold
var sum = 0;
for(var i = 0; i < this.location.length; i ++){
sum += this.location[i];
}
this.location.push(sum);
// console.log(this.location);
};
Store.prototype.cookieTotals = function() { //print the information into a table on the sales.html page
var arr = this.location;
var tableEl2 = document.getElementById('table');
var newRow = document.createElement('tr');
newRow.setAttribute('id', 'rowInfo');
var nameEl = document.createElement('th');
nameEl.textContent = this.name;
newRow.appendChild(nameEl);
for (var i = 0; i < arr.length; i ++) {
var rowData = document.createElement('td');
rowData.textContent = arr[i];
newRow.appendChild(rowData);
// console.log('Inside cookie totals: ' + arr[i]);
}
tableEl2.appendChild(newRow);
};
Store.prototype.print = function() { //call the methods in proper order
this.cookiesPerHour();
this.amount();
this.cookieTotals();
};
//event listeners
var formEl = document.getElementById('store-info'); //When form is submitted, populate table with new info
formEl.addEventListener('submit', function(event){
event.preventDefault();
event.stopPropagation();
var location = event.target.location.value;
var minCustomer = event.target.minCust.value;
var maxCustomer = event.target.maxCust.value;
var avgSold = event.target.avgSold.value;
var newStore = new Store(minCustomer, maxCustomer, avgSold, location);
stores.push(newStore);
removeRow();
newStore.print();
getHourTotal();
footerHeader();
console.log(stores);
}, false);
// Inprogress. Working on adding an animation element to index.html
// window.addEventListener('scroll', fadeOut, false);
//created stores
var firstAndPike = new Store(23, 65, 6.3, 'First and Pike');
stores.push(firstAndPike);
var seatac = new Store(2, 23, 1.2, 'Seatac');
stores.push(seatac);
var seattleCenter = new Store(11, 38, 3.7, 'Seattle Center');
stores.push(seattleCenter);
var capitalHill = new Store(20, 38, 2.3, 'Capital Hill');
stores.push(capitalHill);
var alki = new Store(2, 16, 4.6, 'Alki');
stores.push(alki);
//call the stores to print
hourHeader();
firstAndPike.print();
seatac.print();
seattleCenter.print();
capitalHill.print();
alki.print();
getHourTotal();
footerHeader();
|
'use strict';
angular.module('mean.ddb').factory('Group', ['$http',
function ($http) {
var dao = {};
dao.getGroup = function (id) {
return $http({
url: '/api/group/' + id,
method: 'GET'
});
};
dao.createGroup = function (group) {
return $http({
url: '/api/group',
method: 'POST',
data: group
});
};
dao.leaveGroup = function (groupId) {
return $http({
url: '/api/group/' + groupId + '/member',
method: 'DELETE'
});
};
dao.listGroups = function () {
return $http({
url: '/api/group',
method: 'GET'
});
};
dao.listInvitations = function () {
return $http({
url: '/api/invitation',
method: 'GET'
});
};
dao.acceptInvitation = function (groupId) {
return $http({
url: '/api/group/' + groupId + '/member',
method: 'POST'
});
};
dao.rejectInvitation = function (groupId) {
return $http({
url: '/api/group/' + groupId + '/member',
method: 'DELETE'
});
};
dao.addInvitation = function (groupId, userId) {
return $http({
url: '/api/group/' + groupId + '/invitation/' + userId,
method: 'POST'
});
};
dao.removeInvitation = function (groupId, userId) {
return $http({
url: '/api/group/' + groupId + '/invitation/' + userId,
method: 'DELETE'
});
};
dao.getRanking = function (id) {
return $http({
url: '/api/group/' + id + '/ranking',
method: 'GET'
});
};
dao.getMonthlyRanking = function (id, date) {
return $http({
url: '/api/group/' + id + '/ranking/monthly/' + date,
method: 'GET'
});
};
return dao;
}
]);
|
var renderOrderSort = function(a, b) {
return a.renderOrder < b.renderOrder;
};
var updateOrderSort = function(a, b) {
return a.updateOrder < b.updateOrder;
};
var StateManager = function() {
this.states = {};
this.renderOrder = [];
this.updateOrder = [];
this._preventEvent = false;
};
StateManager.prototype.add = function(name, state) {
this.states[name] = this._newStateHolder(name, state);
this.refreshOrder();
return state;
};
StateManager.prototype.enable = function(name) {
var holder = this.getHolder(name);
if (holder) {
if (!holder.enabled) {
if (holder.state.enable) {
holder.state.enable();
}
holder.enabled = true;
holder.changed = true;
if (holder.paused) {
this.unpause(name);
}
}
}
};
StateManager.prototype.disable = function(name) {
var holder = this.getHolder(name);
if (holder) {
if (holder.enabled) {
if (holder.state.disable) {
holder.state.disable();
}
holder.changed = true;
holder.enabled = false;
}
}
};
StateManager.prototype.hide = function(name) {
var holder = this.getHolder(name);
if (holder) {
if (holder.enabled) {
holder.changed = true;
holder.render = false;
}
}
};
StateManager.prototype.show = function(name) {
var holder = this.getHolder(name);
if (holder) {
if (holder.enabled) {
holder.changed = true;
holder.render = true;
}
}
};
StateManager.prototype.pause = function(name) {
var holder = this.getHolder(name);
if (holder) {
if (holder.state.pause) {
holder.state.pause();
}
holder.changed = true;
holder.paused = true;
}
};
StateManager.prototype.unpause = function(name) {
var holder = this.getHolder(name);
if (holder) {
if (holder.state.unpause) {
holder.state.unpause();
}
holder.changed = true;
holder.paused = false;
}
};
StateManager.prototype.protect = function(name) {
var holder = this.getHolder(name);
if (holder) {
holder.protect = true;
}
};
StateManager.prototype.unprotect = function(name) {
var holder = this.getHolder(name);
if (holder) {
holder.protect = false;
}
};
StateManager.prototype.refreshOrder = function() {
this.renderOrder.length = 0;
this.updateOrder.length = 0;
for (var name in this.states) {
var holder = this.states[name];
if (holder) {
this.renderOrder.push(holder);
this.updateOrder.push(holder);
}
}
this.renderOrder.sort(renderOrderSort);
this.updateOrder.sort(updateOrderSort);
};
StateManager.prototype._newStateHolder = function(name, state) {
var holder = {};
holder.name = name;
holder.state = state;
holder.protect = false;
holder.enabled = true;
holder.paused = false;
holder.render = true;
holder.initialized = false;
holder.updated = false;
holder.changed = true;
holder.updateOrder = 0;
holder.renderOrder = 0;
return holder;
};
StateManager.prototype.setUpdateOrder = function(name, order) {
var holder = this.getHolder(name);
if (holder) {
holder.updateOrder = order;
this.refreshOrder();
}
};
StateManager.prototype.setRenderOrder = function(name, order) {
var holder = this.getHolder(name);
if (holder) {
holder.renderOrder = order;
this.refreshOrder();
}
};
StateManager.prototype.destroy = function(name) {
var state = this.getHolder(name);
if (state && !state.protect) {
if (state.state.close) {
state.state.close();
}
delete this.states[name];
this.refreshOrder();
}
};
StateManager.prototype.destroyAll = function() {
for (var i=0, len=this.updateOrder.length; i<len; i++) {
var state = this.updateOrder[i];
if (!state.protect) {
if (state.state.close) {
state.state.close();
}
delete this.states[state.name];
}
}
this.refreshOrder();
};
StateManager.prototype.getHolder = function(name) {
return this.states[name];
};
StateManager.prototype.get = function(name) {
return this.states[name].state;
};
StateManager.prototype.update = function(time) {
for (var i=0, len=this.updateOrder.length; i<len; i++) {
var state = this.updateOrder[i];
if (state) {
state.changed = false;
if (state.enabled) {
if (!state.initialized && state.state.init) {
state.initialized = true;
state.state.init();
}
if (state.state.update && !state.paused) {
state.state.update(time);
state.updated = true;
}
}
}
}
};
StateManager.prototype.exitUpdate = function(time) {
for (var i=0, len=this.updateOrder.length; i<len; i++) {
var state = this.updateOrder[i];
if (state && state.enabled && state.state.exitUpdate && !state.paused) {
state.state.exitUpdate(time);
}
}
};
StateManager.prototype.render = function() {
for (var i=0, len=this.renderOrder.length; i<len; i++) {
var state = this.renderOrder[i];
if (state && state.enabled && (state.updated || !state.state.update) && state.render && state.state.render) {
state.state.render();
}
}
};
StateManager.prototype.mousemove = function(value) {
this._preventEvent = false;
for (var i=0, len=this.updateOrder.length; i<len; i++) {
var state = this.updateOrder[i];
if (state && state.enabled && !state.changed && state.state.mousemove && !state.paused) {
state.state.mousemove(value);
}
if (this._preventEvent) { break; }
}
};
StateManager.prototype.mouseup = function(value) {
this._preventEvent = false;
for (var i=0, len=this.updateOrder.length; i<len; i++) {
var state = this.updateOrder[i];
if (state && state.enabled && !state.changed && state.state.mouseup && !state.paused) {
state.state.mouseup(value);
}
if (this._preventEvent) { break; }
}
};
StateManager.prototype.mousedown = function(value) {
this._preventEvent = false;
for (var i=0, len=this.updateOrder.length; i<len; i++) {
var state = this.updateOrder[i];
if (state && state.enabled && !state.changed && state.state.mousedown && !state.paused) {
state.state.mousedown(value);
}
if (this._preventEvent) { break; }
}
};
StateManager.prototype.keyup = function(value) {
this._preventEvent = false;
for (var i=0, len=this.updateOrder.length; i<len; i++) {
var state = this.updateOrder[i];
if (state && state.enabled && !state.changed && state.state.keyup && !state.paused) {
state.state.keyup(value);
}
if (this._preventEvent) { break; }
}
};
StateManager.prototype.keydown = function(value) {
this._preventEvent = false;
for (var i=0, len=this.updateOrder.length; i<len; i++) {
var state = this.updateOrder[i];
if (state && state.enabled && !state.changed && state.state.keydown && !state.paused) {
state.state.keydown(value);
}
if (this._preventEvent) { break; }
}
};
StateManager.prototype.resize = function() {
for (var i=0, len=this.updateOrder.length; i<len; i++) {
var state = this.updateOrder[i];
if (state && state.enabled && state.state.resize) {
state.state.resize();
}
}
};
module.exports = StateManager;
|
// @flow
/**
* React Flip Move | propConverter
* (c) 2016-present Joshua Comeau
*
* Abstracted away a bunch of the messy business with props.
* - props flow types and defaultProps
* - Type conversion (We accept 'string' and 'number' values for duration,
* delay, and other fields, but we actually need them to be ints.)
* - Children conversion (we need the children to be an array. May not always
* be, if a single child is passed in.)
* - Resolving animation presets into their base CSS styles
*/
/* eslint-disable block-scoped-var */
import React, { Component, Children } from 'react';
// eslint-disable-next-line no-duplicate-imports
import type { ComponentType, Element } from 'react';
import {
statelessFunctionalComponentSupplied,
primitiveNodeSupplied,
invalidTypeForTimingProp,
invalidEnterLeavePreset,
} from './error-messages';
import {
appearPresets,
enterPresets,
leavePresets,
defaultPreset,
disablePreset,
} from './enter-leave-presets';
import { isElementAnSFC, omit } from './helpers';
import type {
Animation,
AnimationProp,
Presets,
FlipMoveProps,
ConvertedProps,
DelegatedProps,
} from './typings';
declare var process: {
env: {
NODE_ENV: 'production' | 'development',
},
};
function propConverter(
ComposedComponent: ComponentType<ConvertedProps>,
): ComponentType<FlipMoveProps> {
return class FlipMovePropConverter extends Component<FlipMoveProps> {
static defaultProps = {
easing: 'ease-in-out',
duration: 350,
delay: 0,
staggerDurationBy: 0,
staggerDelayBy: 0,
typeName: 'div',
enterAnimation: defaultPreset,
leaveAnimation: defaultPreset,
disableAllAnimations: false,
getPosition: (node: HTMLElement) => node.getBoundingClientRect(),
maintainContainerHeight: false,
verticalAlignment: 'top',
};
// eslint-disable-next-line class-methods-use-this
checkChildren(children) {
// Skip all console warnings in production.
// Bail early, to avoid unnecessary work.
if (process.env.NODE_ENV === 'production') {
return;
}
// same as React.Node, but without fragments, see https://github.com/facebook/flow/issues/4781
type Child = void | null | boolean | number | string | Element<*>;
// FlipMove does not support stateless functional components.
// Check to see if any supplied components won't work.
// If the child doesn't have a key, it means we aren't animating it.
// It's allowed to be an SFC, since we ignore it.
Children.forEach(children, (child: Child) => {
// null, undefined, and booleans will be filtered out by Children.toArray
if (child == null || typeof child === 'boolean') {
return;
}
if (typeof child !== 'object') {
primitiveNodeSupplied();
return;
}
if (isElementAnSFC(child) && child.key != null) {
statelessFunctionalComponentSupplied();
}
});
}
convertProps(props: FlipMoveProps): ConvertedProps {
const workingProps: ConvertedProps = {
// explicitly bypass the props that don't need conversion
children: props.children,
easing: props.easing,
onStart: props.onStart,
onFinish: props.onFinish,
onStartAll: props.onStartAll,
onFinishAll: props.onFinishAll,
typeName: props.typeName,
disableAllAnimations: props.disableAllAnimations,
getPosition: props.getPosition,
maintainContainerHeight: props.maintainContainerHeight,
verticalAlignment: props.verticalAlignment,
// Do string-to-int conversion for all timing-related props
duration: this.convertTimingProp('duration'),
delay: this.convertTimingProp('delay'),
staggerDurationBy: this.convertTimingProp('staggerDurationBy'),
staggerDelayBy: this.convertTimingProp('staggerDelayBy'),
// Our enter/leave animations can be specified as boolean (default or
// disabled), string (preset name), or object (actual animation values).
// Let's standardize this so that they're always objects
appearAnimation: this.convertAnimationProp(
props.appearAnimation,
appearPresets,
),
enterAnimation: this.convertAnimationProp(
props.enterAnimation,
enterPresets,
),
leaveAnimation: this.convertAnimationProp(
props.leaveAnimation,
leavePresets,
),
delegated: {},
};
this.checkChildren(workingProps.children);
// Gather any additional props;
// they will be delegated to the ReactElement created.
const primaryPropKeys = Object.keys(workingProps);
const delegatedProps: DelegatedProps = omit(this.props, primaryPropKeys);
// The FlipMove container element needs to have a non-static position.
// We use `relative` by default, but it can be overridden by the user.
// Now that we're delegating props, we need to merge this in.
delegatedProps.style = {
position: 'relative',
...delegatedProps.style,
};
workingProps.delegated = delegatedProps;
return workingProps;
}
convertTimingProp(prop: string): number {
const rawValue: string | number = this.props[prop];
const value =
typeof rawValue === 'number' ? rawValue : parseInt(rawValue, 10);
if (isNaN(value)) {
const defaultValue: number = FlipMovePropConverter.defaultProps[prop];
if (process.env.NODE_ENV !== 'production') {
invalidTypeForTimingProp({
prop,
value: rawValue,
defaultValue,
});
}
return defaultValue;
}
return value;
}
// eslint-disable-next-line class-methods-use-this
convertAnimationProp(
animation: ?AnimationProp,
presets: Presets,
): ?Animation {
switch (typeof animation) {
case 'boolean': {
// If it's true, we want to use the default preset.
// If it's false, we want to use the 'none' preset.
return presets[animation ? defaultPreset : disablePreset];
}
case 'string': {
const presetKeys = Object.keys(presets);
if (presetKeys.indexOf(animation) === -1) {
if (process.env.NODE_ENV !== 'production') {
invalidEnterLeavePreset({
value: animation,
acceptableValues: presetKeys.join(', '),
defaultValue: defaultPreset,
});
}
return presets[defaultPreset];
}
return presets[animation];
}
default: {
return animation;
}
}
}
render() {
return <ComposedComponent {...this.convertProps(this.props)} />;
}
};
}
export default propConverter;
|
var GraphQL = require('../index').GraphQL;
var GraphQLFilter = require('../index').GraphQLFilter;
module.exports.testBasic = function (test) {
var filtered;
var obj = {
users: [
{
id: 'user1',
name: 'User One',
age: 123,
friends: [
{name: 'User Two', duration: '1 hour'}
]
},
{
id: 'user2',
name: 'User Two',
age: 234,
friends: [
{name: 'User One', duration: '1 hour'}
]
}
]
};
filtered = GraphQLFilter.filter(obj, GraphQL.parse('Object{users{age}}'));
test.deepEqual(filtered, {
users:[
{
age:obj.users[0].age
},
{
age:obj.users[1].age
}
]
});
filtered = GraphQLFilter.filter(obj, GraphQL.parse('Object{users.id(user2){name}}'));
test.deepEqual(filtered, {
users:[
{
name:obj.users[1].name
}
]
});
test.done();
};
|
import {defaultsDeep} from 'lodash/fp';
import pgConnectionString from 'pg-connection-string';
let pg;
try {
require('pg-native');
pg = require('pg').native;
} catch (e) {
pg = require('pg');
}
const createPool = async function (options, globals) {
try {
const {
url: connectionUrl,
connectionName,
connection: connectionOptions
} = options;
const {openPools} = globals.state;
if (!openPools[connectionName]) {
const urlConfig = pgConnectionString.parse(connectionUrl);
const poolConfig = defaultsDeep(urlConfig, connectionOptions);
openPools[connectionName] = new pg.Pool(poolConfig);
}
return openPools[connectionName];
} catch (error) {
throw error;
}
};
export default createPool;
|
// All code points in the `New_Tai_Lue` script as per Unicode v5.1.0:
[
0x1980,
0x1981,
0x1982,
0x1983,
0x1984,
0x1985,
0x1986,
0x1987,
0x1988,
0x1989,
0x198A,
0x198B,
0x198C,
0x198D,
0x198E,
0x198F,
0x1990,
0x1991,
0x1992,
0x1993,
0x1994,
0x1995,
0x1996,
0x1997,
0x1998,
0x1999,
0x199A,
0x199B,
0x199C,
0x199D,
0x199E,
0x199F,
0x19A0,
0x19A1,
0x19A2,
0x19A3,
0x19A4,
0x19A5,
0x19A6,
0x19A7,
0x19A8,
0x19A9,
0x19B0,
0x19B1,
0x19B2,
0x19B3,
0x19B4,
0x19B5,
0x19B6,
0x19B7,
0x19B8,
0x19B9,
0x19BA,
0x19BB,
0x19BC,
0x19BD,
0x19BE,
0x19BF,
0x19C0,
0x19C1,
0x19C2,
0x19C3,
0x19C4,
0x19C5,
0x19C6,
0x19C7,
0x19C8,
0x19C9,
0x19D0,
0x19D1,
0x19D2,
0x19D3,
0x19D4,
0x19D5,
0x19D6,
0x19D7,
0x19D8,
0x19D9,
0x19DE,
0x19DF
]; |
module.exports = function(){
return require("fortune")({
adapter: "mongodb",
connectionString: process.env.USERS_DB_CONNECTION_STRING ||
"mongodb://localhost/fortune-client-test-users"
}).resource("user",{
name: String,
email: String,
address: {ref: "address"},
instruments: [{ref: "instrument"}],
lover: {ref: 'user', type: String},
band: {ref: 'band', external: true},
bababand: {ref: 'band', external: true},
nanananas: [{ref: 'na-na-na-na', inverse: 'users'}]
}, {
model: {
pk: "email"
},
actions: {
"first-action": {
name: 'first-action',
method: 'POST',
init: function(){
return function(req, res){
console.log("users --> firstAction");
};
}
},
"second-action": {
name: 'second-action',
method: 'POST',
init: function(){
return function(req, res){
console.log("users --> secondAction");
};
}
}
}
}).resource("address",{
houseNumber: Number,
street: String,
postcode: String,
inhabitants: [{ref: "user", type: String}]
}).resource("instrument",{
name: String,
genre: {ref: 'genre', external: true},
owner: {ref: 'user', type: String}
}).resource("na-na-na-na",{
batman: String,
users: [{ref: 'user', inverse: 'nanananas', type: String}]
});
};
|
import express from 'express';
import Schema from '../../app/data/schema';
import GraphQLHTTP from 'express-graphql';
import {MongoClient} from 'mongodb';
import fs from 'fs';
import {graphql} from 'graphql';
import {introspectionQuery} from 'graphql/utilities';
let app = express();
app.use(express.static(__dirname + '/../../public'));
// let db;
(async ()=> {
try{
let db = await MongoClient.connect(process.env.MONGO_URL);
let schema = Schema(db);
app.use('/graphql', GraphQLHTTP({
schema,
graphiql: true
}));
app.listen(3000, () => console.log("listening on port 3000"));
let json = await graphql(schema, introspectionQuery);
fs.writeFile('./app/data/schema.json', JSON.stringify(json, null, 2), err => {
if (err) throw err;
console.log("created JSON schema");
})
} catch(e) {
console.log(e);
}
})();
// MongoClient.connect(process.env.MONGO_URL, (err, database) => {
// if (err) {
// throw err;
// }
// db = database;
//
// app.use('/graphql', GraphQLHTTP({
// schema: schema(db),
// //schema,
// graphiql: true
// }));
//
//
// app.listen(3000, () => console.log("listening on port 3000"));
// });
// app.get("/data/links", (req, res) => {
// db.collection("links").find({}).toArray((err, links) => {
// if (err) {
// throw err;
// }
// res.json(links);
// });
// })
|
var Unit = require('./unit');
var SAT = require('sat');
function Player(){
this.position = new SAT.Vector(0, 0);
}
Player.prototype = new Unit();
Player.prototype.constructor = Player;
module.exports = Player;
|
module.exports = {
conditions: [''],
name: 'ClassBody',
rules: [
'ClassElementList',
],
handlers: [
'$$ = $1',
],
subRules: [
require('./ClassElementList'),
],
};
|
'use strict';
module.exports = require('test-y-fish-J');
|
// Of the form: {keyCode: active}, e.g. {34: true, 32: false}
// meaning key 34 is pressed, key 32 is not
var keyStates = {};
(function() {
var Input = function() {
// Of the form: {keyCode: behaviour}, e.g. {34: 'left', 32: 'jump'}
// meaning key 34 is configured to move the player to the left, 32 to let it jump
this.keyMap = {};
inputs.push (this);
return this;
}
// Configure keys
Input.prototype.mapKeys = function(keys) {
Five.Utils.merge (this.keyMap, keys);
return this;
}
Input.prototype.updateKeys = function() {
for(keyCode in this.keyMap) {
this[this.keyMap[keyCode]] = !!keyStates[keyCode];
}
return this;
}
var handlerDown = function(e) {
keyStates[e.keyCode] = true;
updateInputs ();
}
var handlerUp = function(e) {
keyStates[e.keyCode] = false;
updateInputs ();
}
var updateInputs = function() {
for(var i = 0, len = inputs.length; i < len; i++) {
inputs[i].updateKeys ();
}
}
document.addEventListener ("keyup", handlerUp);
document.addEventListener ("keyDown", handlerDown);
var inputs = [];
var Plugin = {
name: "Input",
"Input": {
construct: function(game) {
return new Input ();
}
}
}
Five.plugins.push (Plugin);
}()) |
// Javascript Document
(() => {
return {
props: ['source'],
data(){
return {
type: false,
items: []
}
},
watch: {
type(newVal){
if ( newVal ){
this.post(this.source.root + 'session', {
type: newVal
}, (d) => {
if ( d.data ){
this.items = d.data;
this.$nextTick(() => {
this.getRef('tree').updateData(true)
})
}
})
}
}
}
};
})(); |
Oskari.registerLocalization({
"lang": "pl",
"key": "Toolbar",
"value": {
"buttons": {
"link": {
"tooltip": "Link",
"ok": "Ok",
"title": "Link do widoku mapy"
},
"print": {
"tooltip": "Drukuj"
},
"history": {
"reset": "Powrót do domyślnego widoku",
"back": "Cofnij",
"next": "Następny"
},
"pan": "NOT TRANSLATED",
"zoom": "Przybliż",
"measure": {
"line": "Pomiar odległości",
"area": "Pomiar powierzchni"
}
},
"measure": {
"title": "Pomiary",
"close": "Anuluj",
"guidance": {
"measureline": "Zmierz linię na mapie. Podwójne kliknięcie wstrzymuje pomiar.",
"measurearea": "Zmierz powierzchnię mapy.Podwójne kliknięcie wstrzymuje pomiar."
}
}
}
});
|
'use strict';
// Use applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('competitions',['youtube-embed','ngFileUpload']);
|
// This is a very simple test framework that leverages the tap framework
// to run tests and output tap-parseable results.
module.exports = Test
var assert = require("./tap-assert")
, inherits = require("inherits")
, Results = require("./tap-results")
, Harness = require("./tap-harness")
// tests are also test harnesses
inherits(Test, Harness)
function Test (harness, name, conf) {
//console.error("test ctor")
if (!(this instanceof Test)) return new Test(harness, name, conf)
Harness.call(this, Test)
conf.name = name || conf.name || "(anonymous)"
this.conf = conf
this.harness = harness
this.harness.add(this)
}
// it's taking too long!
Test.prototype.timeout = function () {
// detect false alarms
if (this._ended) return
this.fail("Timeout!")
this.end()
}
Test.prototype.clear = function () {
this._started = false
this._ended = false
this._plan = null
this._bailedOut = false
this._testCount = 0
this.results = new Results()
}
// this gets called if a test throws ever
Test.prototype.threw = function (ex) {
//console.error("threw!", ex.stack)
this.fail(ex.name + ": " + ex.message, { error: ex, thrown: true })
// may emit further failing tests if the plan is not completed
//console.error("end, because it threw")
if (!this._ended) this.end()
}
Test.prototype.comment = function (m) {
if (typeof m !== "string") {
return this.fail("Test.comment argument must be a string")
}
this.result("\n" + m.trim())
}
Test.prototype.result = function (res) {
this.results.add(res)
this._testCount ++
this.emit("result", res)
if (this._plan === this._testCount) {
// plan has been met
this.emit("fulfill")
process.nextTick(this._endNice.bind(this))
}
}
Test.prototype._endNice = function () {
if (!this._ended) this.end()
}
// parasitic
// Who says you can't do multiple inheritance in js?
Object.getOwnPropertyNames(assert).forEach(function (k) {
if (k === "prototype" || k === "name") return
var d = Object.getOwnPropertyDescriptor(assert, k)
, v = d.value
if (!v) return
d.value = assertParasite(v)
Object.defineProperty(Test.prototype, k, d)
})
function assertParasite (fn) { return function _testAssert () {
//console.error("_testAssert", fn.name, arguments)
if (this._bailedOut) return
var res = fn.apply(assert, arguments)
this.result(res)
return res
}}
// a few tweaks on the EE emit function, because
// we want to catch all thrown errors and bubble up "bailout"
Test.prototype.emit = (function (em) { return function (t) {
// bailouts bubble until handled
if (t === "bailout" &&
this.listeners(t).length === 0 &&
this.harness) {
return this.harness.bailout(arguments[1])
}
if (t === "error") return em.apply(this, arguments)
try {
em.apply(this, arguments)
} catch (ex) {
// any exceptions in a test are a failure
//console.error("caught!", ex.stack)
this.threw(ex)
}
}})(Harness.prototype.emit)
|
(function () {
"use strict";
angular.module('demoApp.header', [
'ngAnimate',
'ngAria',
'ngMessages',
'ngResource',
'ui.router',
'demoApp.constants',
'demoApp.templates'
]);
})();
|
angular.module('pigeon.fileController', [
'pigeon.fileService',
'fileread'
])
.controller('FileController', ['$scope', '$routeParams', '$location', 'fileService',
function ($scope, $routeParams, $location, fileService) {
$scope.alerts.length = 0;
$scope.file = {};
$scope.files = fileService.getAll();
if (angular.isDefined($routeParams.fileIndex)) {
$scope.file = angular.copy(fileService.get($routeParams.fileIndex));
}
this.editorOptions = {
lineWrapping: true,
lineNumbers: true,
mode: 'javascript',
theme: 'elegant'
};
this.save = function () {
if (angular.isDefined($routeParams.fileIndex)) {
fileService.edit($scope.file, $routeParams.fileIndex);
} else {
fileService.add($scope.file);
}
$location.path('/files');
};
this.remove = function (file) {
fileService.remove(file);
};
}
])
;
|
var postcss = require('postcss'),
parser = require('./parser').parser,
unitconvert = require('css-unit-converter'),
color = require('css-color-converter');
var convertNodes = function (left, right) {
var converted = {
left: left,
right: right,
operators: ['!=', '==']
};
if (typeof left === 'boolean') {
if (typeof right !== 'boolean')
converted.right = Boolean(converted.right.value);
return converted;
}
switch (left.type) {
case 'ColorValue':
converted.left = { type: left.type, value: color(left.value).toHexString() };
switch (right.type) {
case 'Value':
converted.right = { type: left.type, value: color().fromRgb([right.value, right.value, right.value]).toHexString() };
case left.type:
converted.operators = converted.operators.concat(['+', '-', '*', '/']);
break;
}
break;
case 'LengthValue':
case 'AngleValue':
case 'TimeValue':
case 'FrequencyValue':
case 'ResolutionValue':
switch (right.type) {
case left.type:
converted.right.value = unitconvert(right.value, right.unit, left.unit);
case 'Value':
converted.right = { type: left.type, value: right.value, unit: left.unit };
converted.operators = converted.operators.concat(['>=', '>', '<=', '<', '+', '-', '*', '/']);
break;
}
break;
case 'EmValue':
case 'ExValue':
case 'ChValue':
case 'RemValue':
case 'VhValue':
case 'VwValue':
case 'VminValue':
case 'VmaxValue':
case 'PercentageValue':
switch (right.type) {
case left.type:
case 'Value':
converted.right = { type: left.type, value: right.value, unit: left.unit };
converted.operators = converted.operators.concat(['>=', '>', '<=', '<', '+', '-', '*', '/']);
break;
}
break;
case 'String':
break;
case 'Value':
switch (right.type) {
case 'ColorValue':
converted.left = { type: right.type, value: color().fromRgb([left.value, left.value, left.value]).toHexString() };
converted.operators = converted.operators.concat(['+', '-', '*', '/']);
break;
case 'LengthValue':
case 'AngleValue':
case 'TimeValue':
case 'FrequencyValue':
case 'ResolutionValue':
converted.left = { type: right.type, value: left.value, unit: right.unit };
converted.operators = converted.operators.concat(['>=', '>', '<=', '<', '+', '-', '*', '/']);
break;
case 'EmValue':
case 'ExValue':
case 'ChValue':
case 'RemValue':
case 'VhValue':
case 'VwValue':
case 'VminValue':
case 'VmaxValue':
case 'PercentageValue':
converted.left = { type: right.type, value: left.value };
case 'Value':
converted.operators = converted.operators.concat(['>=', '>', '<=', '<', '+', '-', '*', '/']);
break;
}
}
return converted;
};
var cmp = function (val1, val2) {
return val1 === val2 ? 0 : val1 > val2 ? 1 : -1;
};
var evalParseTree = function (tree) {
var parseBinaryExpression = function (left, right, operator) {
var converted = convertNodes(left, right);
left = converted.left;
right = converted.right;
var comparison;
if (typeof left === 'boolean') comparison = cmp(left, right);
else comparison = cmp(left.value, right.value);
if (converted.operators.indexOf(operator) < 0) {
throw new Error("Invalid operands for operator '" + operator+ "'");
}
switch (operator) {
case '==':
if (left.type !== right.type) return false;
return comparison === 0;
case '!=':
if (left.type !== right.type) return true;
return comparison !== 0;
case '>=':
return comparison >= 0;
case '>':
return comparison > 0;
case '<=':
return comparison <= 0;
case '<':
return comparison < 0;
}
};
var parseMathExpression = function (left, right, operator) {
var converted = convertNodes(left, right);
left = converted.left;
right = converted.right;
if (converted.operators.indexOf(operator) < 0) {
throw new Error("Invalid operands for operator '" + operator+ "'");
}
if (left.type == 'ColorValue') {
var val1 = color(left.value).toRgbaArray(),
val2 = color(right.value).toRgbaArray();
if (val1[3] !== val2[3]) {
throw new Error('Alpha channels must be equal');
}
switch (operator) {
case '+':
val1[0] = Math.min(val1[0] + val2[0], 255);
val1[1] = Math.min(val1[1] + val2[1], 255);
val1[2] = Math.min(val1[2] + val2[2], 255);
break;
case '-':
val1[0] = Math.max(val1[0] - val2[0], 0);
val1[1] = Math.max(val1[1] - val2[1], 0);
val1[2] = Math.max(val1[2] - val2[2], 0);
break;
case '*':
val1[0] = Math.min(val1[0] * val2[0], 255);
val1[1] = Math.min(val1[1] * val2[1], 255);
val1[2] = Math.min(val1[2] * val2[2], 255);
break;
case '/':
val1[0] = Math.max(val1[0] / val2[0], 0);
val1[1] = Math.max(val1[1] / val2[1], 0);
val1[2] = Math.max(val1[2] / val2[2], 0);
break;
}
left.value = color().fromRgba(val1).toHexString();
return left;
}
switch (operator) {
case '+':
left.value = left.value + right.value;
break;
case '-':
left.value = left.value - right.value;
break;
case '*':
left.value = left.value * right.value;
break;
case '/':
left.value = left.value / right.value;
break;
}
return left;
};
var parseTree = function (subtree) {
switch (subtree.type) {
case 'LogicalExpression':
return subtree.operator === 'AND'
? evalParseTree(subtree.left) && evalParseTree(subtree.right)
: evalParseTree(subtree.left) || evalParseTree(subtree.right);
case 'BinaryExpression':
return parseBinaryExpression(parseTree(subtree.left), parseTree(subtree.right), subtree.operator);
case 'MathematicalExpression':
return parseMathExpression(parseTree(subtree.left), parseTree(subtree.right), subtree.operator);
case 'UnaryExpression':
return !parseTree(subtree.argument);
case 'BooleanValue':
return subtree.value;
case 'ColorValue':
subtree.value = color(subtree.value).toHexString();
return subtree;
case 'String':
return subtree;
default:
subtree.value = parseFloat(subtree.value);
return subtree;
}
};
var result = parseTree(tree);
if (typeof result !== 'boolean') result = Boolean(result.value);
return result;
};
var parseElseStatement = function (rule, prevPassed) {
if (!prevPassed)
rule.parent.insertBefore(rule, rule.nodes);
rule.remove();
};
var parseIfStatement = function(rule, input) {
processRule(rule);
if (!input)
throw rule.error('Missing condition', { plugin: 'postcss-conditionals' });
var previousPassed = arguments[2] || false;
var passed = false;
try {
passed = evalParseTree(parser.parse(input));
}
catch (err) {
throw rule.error('Failed to parse expression', { plugin: 'postcss-conditionals' });
}
if (!previousPassed && passed)
rule.parent.insertBefore(rule, rule.nodes);
var next = rule.next();
if (typeof next !== 'undefined' && next.type === 'atrule' && next.name === 'else') {
if (next.params.substr(0, 2) === 'if')
parseIfStatement(next, next.params.substr(3), passed || previousPassed);
else
parseElseStatement(next, passed || previousPassed);
}
rule.remove();
};
function processRule(css) {
css.walkAtRules('if', function (rule) {
parseIfStatement(rule, rule.params);
});
}
module.exports = postcss.plugin('postcss-conditionals', function (opts) {
opts = opts || {};
return processRule;
});
|
/*'use strict';
angular.module('myApp.myportfolio', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/myportfolio', {
templateUrl: 'myportfolio/my-portfolio.html',
controller: 'MyPortfolioCtrl'
});
}])
.controller('MyPortfolioCtrl', [function() {
}]);*/ |
function alertIfMozilla() {
var currentWindow = window,
browserName = currentWindow.navigator.appCodeName,
isMozilla = (browserName === "Mozilla");
if (isMozilla) {
alert("Yes");
} else {
alert("No");
}
} |
/*! loglevel - v0.6.0 - https://github.com/pimterry/loglevel - (c) 2014 Tim Perry - licensed MIT */
;(function (undefined) {
var undefinedType = "undefined";
(function (name, definition) {
if (typeof module !== 'undefined') {
module.exports = definition();
} else if (typeof define === 'function' && typeof define.amd === 'object') {
define(definition);
} else {
this[name] = definition();
}
}('log', function () {
var self = {};
var noop = function() {};
function realMethod(methodName) {
if (typeof console === undefinedType) {
return noop;
} else if (console[methodName] === undefined) {
if (console.log !== undefined) {
return boundToConsole(console, 'log');
} else {
return noop;
}
} else {
return boundToConsole(console, methodName);
}
}
function boundToConsole(console, methodName) {
var method = console[methodName];
if (method.bind === undefined) {
if (Function.prototype.bind === undefined) {
return functionBindingWrapper(method, console);
} else {
try {
return Function.prototype.bind.call(console[methodName], console);
} catch (e) {
// In IE8 + Modernizr, the bind shim will reject the above, so we fall back to wrapping
return functionBindingWrapper(method, console);
}
}
} else {
return console[methodName].bind(console);
}
}
function functionBindingWrapper(f, context) {
return function() {
Function.prototype.apply.apply(f, [context, arguments]);
};
}
var logMethods = [
"trace",
"debug",
"info",
"warn",
"error"
];
function replaceLoggingMethods(methodFactory) {
for (var ii = 0; ii < logMethods.length; ii++) {
self[logMethods[ii]] = methodFactory(logMethods[ii]);
}
}
function cookiesAvailable() {
return (typeof window !== undefinedType &&
window.document !== undefined &&
window.document.cookie !== undefined);
}
function localStorageAvailable() {
try {
return (typeof window !== undefinedType &&
window.localStorage !== undefined);
} catch (e) {
return false;
}
}
function persistLevelIfPossible(levelNum) {
var localStorageFail = false,
levelName;
for (var key in self.levels) {
if (self.levels.hasOwnProperty(key) && self.levels[key] === levelNum) {
levelName = key;
break;
}
}
if (localStorageAvailable()) {
/*
* Setting localStorage can create a DOM 22 Exception if running in Private mode
* in Safari, so even if it is available we need to catch any errors when trying
* to write to it
*/
try {
window.localStorage['loglevel'] = levelName;
} catch (e) {
localStorageFail = true;
}
} else {
localStorageFail = true;
}
if (localStorageFail && cookiesAvailable()) {
window.document.cookie = "loglevel=" + levelName + ";";
}
}
var cookieRegex = /loglevel=([^;]+)/;
function loadPersistedLevel() {
var storedLevel;
if (localStorageAvailable()) {
storedLevel = window.localStorage['loglevel'];
}
if (storedLevel === undefined && cookiesAvailable()) {
var cookieMatch = cookieRegex.exec(window.document.cookie) || [];
storedLevel = cookieMatch[1];
}
if (self.levels[storedLevel] === undefined) {
storedLevel = "WARN";
}
self.setLevel(self.levels[storedLevel]);
}
/*
*
* Public API
*
*/
self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3,
"ERROR": 4, "SILENT": 5};
self.setLevel = function (level) {
if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
persistLevelIfPossible(level);
if (level === self.levels.SILENT) {
replaceLoggingMethods(function () {
return noop;
});
return;
} else if (typeof console === undefinedType) {
replaceLoggingMethods(function (methodName) {
return function () {
if (typeof console !== undefinedType) {
self.setLevel(level);
self[methodName].apply(self, arguments);
}
};
});
return "No console available for logging";
} else {
replaceLoggingMethods(function (methodName) {
if (level <= self.levels[methodName.toUpperCase()]) {
return realMethod(methodName);
} else {
return noop;
}
});
}
} else if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
self.setLevel(self.levels[level.toUpperCase()]);
} else {
throw "log.setLevel() called with invalid level: " + level;
}
};
self.enableAll = function() {
self.setLevel(self.levels.TRACE);
};
self.disableAll = function() {
self.setLevel(self.levels.SILENT);
};
loadPersistedLevel();
return self;
}));
})();
|
const _ = require('lodash')
module.exports = function (problem, sliceSizes) {
return _.map(sliceSizes, ([height, width]) => {
const xs = _.range(0, problem.ncolumns - width + 1, width)
const ys = _.range(0, problem.nrows - height + 1, height)
return _.flatMap(xs, x => _.map(ys, y => ({r1: y, r2: y + height - 1, c1: x, c2: x + width - 1})))
})
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (service) {
describe('Service base tests', function () {
it('.find', function (done) {
service.find().then(function (todos) {
return _assert2.default.deepEqual(todos, [{
text: 'some todo',
complete: false,
id: 0
}]);
}).then(function () {
return done();
}).catch(done);
});
it('.get and params passing', function (done) {
var query = {
some: 'thing',
other: ['one', 'two'],
nested: { a: { b: 'object' } }
};
service.get(0, { query: query }).then(function (todo) {
return _assert2.default.deepEqual(todo, {
id: 0,
text: 'some todo',
complete: false,
query: query
});
}).then(function () {
return done();
}).catch(done);
});
it('.create and created event', function (done) {
service.once('created', function (data) {
_assert2.default.equal(data.text, 'created todo');
_assert2.default.ok(data.complete);
done();
});
service.create({ text: 'created todo', complete: true });
});
it('.update and updated event', function (done) {
service.once('updated', function (data) {
_assert2.default.equal(data.text, 'updated todo');
_assert2.default.ok(data.complete);
done();
});
service.create({ text: 'todo to update', complete: false }).then(function (todo) {
return service.update(todo.id, {
text: 'updated todo',
complete: true
});
});
});
it('.patch and patched event', function (done) {
service.once('patched', function (data) {
_assert2.default.equal(data.text, 'todo to patch');
_assert2.default.ok(data.complete);
done();
});
service.create({ text: 'todo to patch', complete: false }).then(function (todo) {
return service.patch(todo.id, { complete: true });
});
});
it('.remove and removed event', function (done) {
service.once('removed', function (data) {
_assert2.default.equal(data.text, 'todo to remove');
_assert2.default.equal(data.complete, false);
done();
});
service.create({ text: 'todo to remove', complete: false }).then(function (todo) {
return service.remove(todo.id);
}).catch(done);
});
it('.get with error', function (done) {
var query = { error: true };
service.get(0, { query: query }).then(done, function (error) {
_assert2.default.ok(error && error.message);
done();
});
});
});
};
var _assert = require('assert');
var _assert2 = _interopRequireDefault(_assert);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = exports['default']; |
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var MetaTile = (function (_super) {
__extends(MetaTile, _super);
function MetaTile(tile, x, y, value) {
_super.call(this, tile.texture, tile.walkable);
this.FVal = 0;
this.GVal = 0;
this.HVal = 0;
this.value = value;
this.x = x;
this.y = y;
this.xd = 0;
this.yd = 0;
}
return MetaTile;
})(VTile);
var Level = (function () {
function Level(map) {
if (map === void 0) { map = new TileMap(Dm.from(25, 25), Pt.from(8, 32)); }
this.eSpawns = [];
this.AIPath = [];
this.map = map;
this.map.setTileSet(Level.defaultTileSet);
do {
this.eSpawns = [];
this.generateLevel();
this.AIPath = this.generatePath(1, 23, 23, 1);
} while (this.AIPath.length < 50);
this.setSpawns();
this.entities = [];
}
Level.prototype.getNbr = function (px, py, x, y, val) {
var tile = this.map.getTile(x, y);
if (tile && tile.value === val) {
tile.xd = (x - px);
tile.yd = (y - py);
return tile;
}
return undefined;
};
Level.prototype.getNbrs = function (x, y, val) {
var result = [];
var t1 = this.getNbr(x, y, x, y - 1, val);
if (t1)
result.push(t1);
var t2 = this.getNbr(x, y, x, y + 1, val);
if (t2)
result.push(t2);
var t3 = this.getNbr(x, y, x - 1, y, val);
if (t3)
result.push(t3);
var t4 = this.getNbr(x, y, x + 1, y, val);
if (t4)
result.push(t4);
return result;
};
Level.prototype.generateLevel = function () {
for (var i = 0; i < (this.map.size.width * this.map.size.height); i++) {
this.map.tiles[i] = 1;
}
for (var i = 0; i < this.map.size.width; i++) {
this.map.tiles[i] = this.map.tiles[this.map.tiles.length - 1 - i] = 2;
}
for (var i = 1; i < this.map.size.height - 1; i++) {
this.map.tiles[this.map.size.width * i] = this.map.tiles[(this.map.size.width * (i + 1)) - 1] = 2;
}
var seed = Pt.from(getRandomInt(1, 23), getRandomInt(1, 23));
if (seed.x % 2 == 0)
seed.x -= 1;
if (seed.y % 2 == 0)
seed.y -= 1;
var currentTile = this.map.getTile(seed.x, seed.y);
currentTile.value = 0;
this.map.setTile(currentTile.x, currentTile.y, 0);
var walls = [];
do {
if (currentTile)
walls = walls.concat(this.getNbrs(currentTile.x, currentTile.y, 1));
var wallIndex = getRandomInt(0, walls.length - 1);
var tileToCheck = walls[wallIndex];
var nextTile = this.map.getTile(tileToCheck.x + tileToCheck.xd, tileToCheck.y + tileToCheck.yd);
if (nextTile && (nextTile.value === 1)) {
nextTile.value = 0;
this.map.setTile(nextTile.x, nextTile.y, 0);
tileToCheck.value = 0;
this.map.setTile(tileToCheck.x, tileToCheck.y, 0);
currentTile = this.map.getTile(nextTile.x, nextTile.y);
}
else {
tileToCheck.value = 3;
this.map.setTile(tileToCheck.x, tileToCheck.y, 3);
currentTile = undefined;
}
walls = walls.filter(function (obj, index, array) { return (obj.value === 1); });
} while (walls.length != 0);
};
Level.prototype.generatePath = function (startX, startY, goalX, goalY) {
var path = [];
var openList = [], closedList = [], nbrs = [];
var current, ctile, parent;
;
openList.push(this.map.getTile(startX, startY));
do {
current = openList.pop();
closedList.push(current);
if (current.x === goalX && current.y === goalY) {
ctile = current;
break;
}
nbrs = this.getNbrs(current.x, current.y, 0);
for (var _i = 0; _i < nbrs.length; _i++) {
var nbr = nbrs[_i];
if (this.tileInSet(nbr.x, nbr.y, closedList))
continue;
var tile = this.getTileInSet(nbr.x, nbr.y, openList);
if (tile === undefined) {
nbr.parent = current;
nbr.HVal = (Math.abs(goalX - nbr.x) + Math.abs(goalY - nbr.y));
nbr.GVal = current.GVal + 10;
nbr.FVal = nbr.HVal + nbr.GVal;
openList.push(nbr);
}
else {
var tempG = current.GVal + 10;
if (tempG < tile.GVal) {
tile.parent = current;
tile.GVal = current.GVal + 10;
tile.FVal = tile.HVal + tile.GVal;
}
}
}
if (openList.length === 0)
break;
openList.sort(function (tileA, tileB) { return tileB.FVal - tileA.FVal; });
} while (true);
do {
parent = ctile.parent;
path.push(Pt.from(ctile.x - parent.x, ctile.y - parent.y));
ctile = parent;
if (ctile.x != startX && ctile.y != startY)
this.eSpawns.push(Pt.from(ctile.x, ctile.y));
} while (ctile.parent !== undefined);
return path;
};
Level.prototype.getTileInSet = function (x, y, arr) {
var result = undefined;
for (var _i = 0; _i < arr.length; _i++) {
var tile = arr[_i];
if (tile.x === x && tile.y === y) {
result = tile;
break;
}
}
return result;
};
Level.prototype.tileInSet = function (x, y, arr) {
var result = false;
for (var _i = 0; _i < arr.length; _i++) {
var tile = arr[_i];
result = result || (tile.x === x && tile.y === y);
if (result === true)
break;
}
return result;
};
Level.prototype.setSpawns = function () {
for (var y = 2; y <= 22; y++) {
for (var x = 2; x <= 22; x++) {
var tile = this.map.getTile(x, y);
if (tile.value === 0) {
}
}
}
};
return Level;
})();
|
import {combineReducers} from 'redux';
import {routerReducer} from 'router-redux';
const rootReducer = combineReducers({
routing: routerReducer
});
export default rootReducer;
|
var Router = require('../../lib')
var router = module.exports = new Router({
viewPath: 'views'
})
var a = router.get('/a', function*(cont) {
yield cont
})
a.get('/b', function*(cont) {
yield cont
})
var w = a.get('/w', function*(cont) {
yield cont
})
w.get('/v', function*(cont) {
yield cont
})
var u = w.get('/u', function*(cont) {
yield cont
})
u.get('/c', function*(cont) {
yield cont
})
u.get('/d', function*(cont) {
yield cont
})
var e = router.get('/:e', function*(cont) {
yield cont
})
e.get('/k', function*(cont) {
yield cont
})
var f = e.get('/:f', function*(cont) {
yield cont
})
f.get('/g', function*(cont) {
yield cont
})
var h = f.get('/:h', function*(cont) {
yield cont
})
h.get('/i', function*(cont) {
yield cont
})
h.get('/j', function*(cont) {
yield cont
}) |
import React from 'react'
import { Button } from 'stardust'
const ButtonLoadingExample = () => (
<div>
<Button loading>Loading</Button>
<Button basic loading>Loading</Button>
<Button loading primary>Loading</Button>
<Button loading secondary>Loading</Button>
</div>
)
export default ButtonLoadingExample
|
/**
* Reducer. It takes the current state and an action and returns the next state.
*
* @param {string} state State.
* @param {Object} action Action.
*
* @return {string}
*/
export default function message(state = "", action = {}) {
//scroll users to top of the page
scroll(0,0);
switch (action.type) {
case 'SHOW_MESSAGE':
return action.messageType;
case 'HIDE_MESSAGE':
return action.messageType;
case 'GENERATE_MESSAGE':
return action.message;
default:
return state;
}
};
|
function rgbToHexColor(red, green, blue) {
if (!Number.isInteger(red) || (red < 0) || (red > 255))
return undefined; // Red value is invalid
if (!Number.isInteger(green) || (green < 0) || (green > 255))
return undefined; // Green value is invalid
if (!Number.isInteger(blue) || (blue < 0) || (blue > 255))
return undefined; // Blue value is invalid
return "#" +
("0" + red.toString(16).toUpperCase()).slice(-2) +
("0" + green.toString(16).toUpperCase()).slice(-2) +
("0" + blue.toString(16).toUpperCase()).slice(-2);
}
module.exports = {rgbToHexColor};
|
define(function() {
var parseFunctionCall = function(tokens,index) {
};
var parseStatement = function(tokens, index) {
};
var parseForLoop = function(tokens, index) {
};
var parseExpression = function(tokens, index) {
};
var parseVariableDeclaration = function() {
};
//starts on leading {
var parseFunctionBody = function(tokens, index) {
while (tokens[current].token !== 'T_CLOSE_BRACE') {
}
};
var parseFunction = function(tokens, index) {
var returnType = tokens[index];
var id = tokens[index+1];
var current = index+3;
var parameters = [];
while (tokens[current].token !== 'T_CLOSE_BRACKETS') {
var paramType = tokens[current];
var paramId = tokens[current+1];
parameters.push({ type: paramType, id: paramId });
current += 2;
}
var body = parseFunctionBody(tokens, current);
};
var parseTopLevelDeclaration = function(tokens, index) {
var lookAhead = tokens[index+2];
if (lookAhead == null)
return { error: ""};
if (lookAhead.token === 'T_OPEN_BRACKETS') {
return parseFunction(tokens, index);
}
};
return function(tokens) {
var parseStack = [];
var state = 'start';
var index = 0;
parseStack.push('start');
for (var i = 0; i < tokens.length; i++) {
var lookAhead = tokens[i];
var entry = stateTransitions[state][lookAhead.token];
state = entry(lookAhead, parseStack);
}
};
}); |
(function(){
'use strict'
angular
.module('triviaQuiz', [
'ngAnimate',
'ngSanitize',
'ui.router',
'ui.router.state.events'
]);
})();
(function(){
'use strict';
angular
.module('triviaQuiz')
.constant('API_URL','https://opentdb.com/')
.config(AppConfig);
//Config
function AppConfig($locationProvider, $compileProvider) {
"ngInject";
$locationProvider.html5Mode(true); //for clean urls
$compileProvider.debugInfoEnabled(false); //disable debug info
}
})();
(function(){
'use strict';
angular
.module('triviaQuiz')
.config(AppRouter);
function AppRouter ($stateProvider, $urlRouterProvider) {
"ngInject";
var ver = '1.0.0';
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: "/",
templateUrl: "app/views/home.html?ver="+ver,
controller: "homeCtrl",
controllerAs: "ctrl"
})
.state('quiz', {
url: "/quiz",
templateUrl: "app/views/quiz.html?ver="+ver,
controller: "quizCtrl",
controllerAs: "ctrl"
});
}
})();
(function(){
"use strict";
angular
.module("triviaQuiz")
.controller('homeCtrl', homeCtrl);
//Home controller
function homeCtrl ($state,quiz) {
"ngInject";
var vm = this;
vm.isLoading = true;
vm.categories = [];
vm.quizDetail = {};
vm.step = 1;
vm.user = {};
vm.pageTitle = "Select Category";
vm.cardColors = ['#009688','#ef4438','#4caf50','#38a4dd','#ffc107','#8e76b6','#ec407a'];
vm.game = quiz.getScore() || {};
vm.setCategory = setCategory;
vm.setLevel = setLevel;
vm.setUserInfo = setUserInfo;
vm.changeStep = changeStep;
//get category listing
quiz
.getCategoryList()
.then(function(res){
if(res.status == 200) {
angular.forEach(res.data.trivia_categories,function(item){
item.name = (item.name.search(':') != -1)?item.name.split(":")[1].trim():item.name;
});
vm.categories = res.data.trivia_categories;
}
})
.catch(function(err){
console.log("get category error",err);
})
.finally(function(){
vm.isLoading = false;
});
//set category
function setCategory (category) {
vm.quizDetail.category = category;
vm.step = 2;
vm.changeStep(vm.step);
}
//set level
function setLevel (level) {
vm.quizDetail.difficulty = level;
vm.step = 3;
vm.changeStep(vm.step);
}
//set level
function setUserInfo (user) {
vm.quizDetail.user = user;
quiz.setDetails(vm.quizDetail);
$state.go("quiz");
}
//change title on step change
function changeStep(step) {
switch(step) {
case 1:
vm.pageTitle = 'Select Categories';
break;
case 2:
vm.pageTitle = 'Select Level';
break;
case 3:
vm.pageTitle = 'Enter Personal Details';
break;
}
}
}
})();
(function(){
"use strict";
angular
.module("triviaQuiz")
.controller('quizCtrl', quizCtrl);
//Home controller
function quizCtrl ($state, $interval, quiz) {
"ngInject";
var vm = this;
var timer = null;
vm.quizDetail = {};
vm.timeCount = 60;
vm.hideQuizBlock = true;
vm.showQuizResult = false;
vm.currentQuestion = 0;
vm.questions = [];
vm.answers = [];
vm.initTimer = initTimer;
vm.next = next;
//get quizinfo & question list
quiz
.getDetails()
.then(function(res){
vm.quizDetail = res;
return res;
})
.then(function(quizDetail){
quiz
.getQuestionList(quizDetail.category.id,quizDetail.difficulty,20)
.then(function(res){
if(res.data.results.length) {
angular.forEach(res.data.results,function(item){
item.answers = angular.copy(item.incorrect_answers);
item.answers.push(item.correct_answer);
item.answers = quiz.shuffleArray(item.answers);
});
vm.questions = res.data.results;
vm.hideQuizBlock = false;
initTimer();
} else {
alert("Sorry, No data :( ....... Please Try different category or level");
$state.go("home");
}
});
})
.catch(function(err){
console.log(err);
$state.go("home");
});
function next() {
$interval.cancel(vm.timer);
timer = null;
if(vm.questions.length === vm.currentQuestion+1) {
vm.hideQuizBlock = true;
vm.quizDetail.score = 0;
vm.quizDetail.totalScore = vm.questions.length;
angular.forEach(vm.answers,function(ans,key){
if(ans === vm.questions[key].correct_answer) {
vm.quizDetail.score += 1;
}
});
vm.showQuizResult = true;
quiz.setScore(vm.quizDetail.totalScore,vm.quizDetail.score);
} else {
vm.currentQuestion++;
vm.initTimer();
}
}
//timer
function initTimer() {
vm.timeCount = 60;
if(!timer) {
vm.timer = $interval(function(){
vm.timeCount--;
if(vm.timeCount == 0) {
vm.next();
}
},1000);
}
}
}
})();
(function() {
"use strict";
angular
.module('triviaQuiz')
.factory('quiz',quiz);
function quiz($http, $q, $timeout, API_URL) {
"ngInject";
var obj = {};
var _quizDetails = {};
obj.getCategoryList = getCategoryList;
obj.getQuestionList = getQuestionList;
obj.setDetails = setDetails;
obj.getDetails = getDetails;
obj.shuffleArray = shuffleArray;
obj.getScore = getScore;
obj.setScore = setScore;
obj.resetScore = resetScore;
function getCategoryList () {
return $http.get(API_URL+'api_category.php');
}
function getQuestionList (category,difficulty,amount) {
//default values
amount = amount || 20;
category = category || 1;
difficulty = difficulty || 'medium';
return $http.get(API_URL+'api.php?amount='+amount+'&category='+category+'&difficulty='+difficulty);
}
function setDetails (quizDetails) {
_quizDetails = quizDetails;
}
function getDetails () {
var deferred = $q.defer();
if(!_quizDetails.hasOwnProperty('user')) {
deferred.reject("no quiz data");
} else {
deferred.resolve(_quizDetails);
}
return deferred.promise;
}
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function resetScore(totalScore, score) {
localStorage.setItem('totalScore', 0);
localStorage.setItem('score', 0);
}
function setScore(totalScore, score) {
localStorage.setItem('totalScore', parseInt(localStorage.getItem('totalScore') || 0)+totalScore);
localStorage.setItem('score', parseInt(localStorage.getItem('score') || 0)+score);
}
function getScore() {
return {score:parseInt(localStorage.getItem('score')),totalScore:parseInt(localStorage.getItem('totalScore'))};
}
return obj;
}
})();
|
'use strict';
var INDEX_PATH = require('./index-path');
function resetRequireCache() {
var resolved = require.resolve(INDEX_PATH);
delete require.cache[resolved];
}
module.exports = resetRequireCache;
|
const program = require('commander');
const path = require('path');
const pkg = require('../package.json');
const promfiler = require('..');
const sanitizeArgv = (cmd, argv) =>
argv.filter( (arg, i) => argv.indexOf(cmd) === -1 || i >= argv.indexOf(cmd) || i === 0 );
const runApp = (cmd) => {
return (uri) => {
process.argv = sanitizeArgv(cmd, process.argv);
const appModule = path.resolve(path.join(cmd));
console.info("\n");
console.info("*********************************************");
console.info('***** Profiler listening on %s', uri);
console.info("***** Executing: %s", process.argv.slice(1).join(' '));
console.info("*********************************************");
console.info("\n");
require(appModule);
};
};
const runProfiling = (cmd, opts) => {
return promfiler.startServer({
hostname: opts.hostname,
port: opts.port,
path: opts.path,
}).then( (_) => {
promfiler.startProfiling({
samplingInterval: opts.samplingInterval,
});
return _;
});
};
program
.version(pkg.version)
.option('-h, --hostname <hostname>', 'Address to listen for metric interface.')
.option('-p, --port <port>', 'Port to listen for metric interface.')
.option('-P, --path <path>', 'Path under which to expose metrics.')
.option('-s, --sampling-interval <sampling interval>', 'Changes default CPU profiler sampling interval to the specified number of microseconds.')
.arguments('<app> [argv...]')
.action((app, argv, options) => {
runProfiling(app, options).then(runApp(app));
});
program.on('--help', () => {
console.log('');
console.log(' Examples:');
console.log('');
console.log(' $ promfiler ./app.js');
console.log(' $ promfiler ./app.js foo bar');
console.log(' $ promfiler --port 9090 ./app.js foo bar');
console.log('');
});
program.parse(process.argv);
if (!program.args.length)
program.help();
|
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
desktop = false,
mobile = false;
app.listen(8001);
console.log('Server started');
function handler (req, res) {
res.writeHead(200);
res.end("Hello world!");
}
function sendEvent(socketID, eventName, data) {
data = typeof data !== 'undefined' ? data : '';
io.to(socketID).emit(eventName, data);
}
io.sockets.on('connection', function (socket) {
if (socket.handshake.query.type === 'mobile') {
mobile = socket.id;
console.log('Mobile connected');
} else {
desktop = socket.id;
console.log('Desktop connected');
}
if (desktop && mobile) {
sendEvent(mobile, 'desktopConnected', desktop);
sendEvent(desktop, 'mobileConnected', mobile);
}
socket.on('disconnect', function() {
if (socket.id === desktop) {
console.log('Desktop disconnected');
desktop = false;
if (mobile) sendEvent(mobile, 'desktopDisconnected');
} else if (socket.id === mobile) {
console.log('Mobile disconnected');
mobile = false;
if (desktop) sendEvent(desktop, 'mobileDisconnected');
}
});
socket.on('sendCommand', function(command) {
console.log('Saw command: ' + command.event);
console.log(command.target);
console.log(command.data);
io.sockets.to(command.target).emit(command.event, command.data);
});
}); |
import Component from '@ember/component'
import { computed } from '@ember/object'
import moment from 'moment'
export default Component.extend({
classNames: 'date-field',
inputFormat: 'YYYY-MM-DD',
value: computed('inputFormat', {
set(prop, value) {
return this.set('selected', moment(value, this.inputFormat))
},
}),
selected: computed(function() {
return moment()
}),
center: computed(function() {
return this.selected
}),
change() {},
})
|
'use strict';
// santa ssr package
module.exports = {
"extends": ["./santa-es6.js"],
"rules": {
"santa/no-module-state": 0,
"santa/no-experiment-in-component": 0,
"no-restricted-syntax": [
"error",
{
"selector": "CallExpression[callee.type='MemberExpression'][callee.object.name='experiment'][callee.property.name='isOpen'][arguments.length<1]",
"message": "isOpen must always be invoked with at least one argument."
}
],
}
};
|
angular.module('just.service')
.factory('authHttpResponseInterceptor', ['$q', '$location', '$injector', 'justRoutes',
function($q, $location, $injector, routes) {
function redirectToLogin() {
var authService = $injector.get('authService');
var userService = $injector.get('userService');
authService.logout();
userService.clearUserModel();
$location.path(routes.user.signin.url);
}
return {
response: function(response) {
if (response.status === 401) {
redirectToLogin();
return response;
}
return response || $q.when(response);
},
responseError: function(rejection) {
if (rejection.status === 401) {
redirectToLogin();
}
return $q.reject(rejection);
}
};
}]);
|
'use strict';
/**
* @ngdoc service
* @name waxeApp.Files
* @description
* # Files
* Service in the waxeApp.
*/
angular.module('waxeApp')
.factory('FS', function() {
var FS = function(data) {
this.init(data);
};
FS.prototype.init = function(data) {
this.status = false; // Versioning status
this.selected = false; // If it is selected by checkbox
for (var key in data) {
if (data.hasOwnProperty(key)) {
this[key] = data[key];
}
}
};
FS.prototype._editUrl = function() {
throw new Error('NotImplemented');
};
Object.defineProperty(FS.prototype, 'editUrl', {
get: function editUrlProperty() {
return this._editUrl();
}
});
return FS;
})
.factory('Folder', ['FS', 'UrlFactory', function(FS, UrlFactory) {
var Folder = function(data){
this.init(data);
this.iClass = 'fa fa-folder-o';
};
Folder.prototype = new FS();
Folder.prototype._editUrl = function() {
return UrlFactory.userUrl('', {path: this.path});
};
return Folder;
}])
.factory('File', ['FS', 'UrlFactory', 'AccountProfile', function(FS, UrlFactory, AccountProfile) {
var File = function(data){
this.init(data);
this.iClass = 'fa fa-file-excel-o';
};
File.prototype = new FS();
File.prototype._editUrl = function(data) {
var url = this.editor + '/edit';
data = data || {};
data.path = this.path;
if (angular.isDefined(this.user) && this.user) {
// On opened and commited file it can be a link to another account.
return UrlFactory.url(this.user, url, data);
}
return UrlFactory.userUrl(url,data);
};
File.prototype.init = function(data) {
FS.prototype.init.call(this, data);
if (! angular.isDefined(this.name)) {
this.name = this.path.substring(this.path.lastIndexOf('/')+1, this.path.length);
}
this.extension = this.name.substring(this.name.lastIndexOf('.'), this.name.length).toLowerCase();
this.editor = AccountProfile.editors[this.extension];
this.renderer = AccountProfile.renderers[this.extension];
};
Object.defineProperty(File.prototype, 'newUrl', {
get: function newUrlProperty() {
var url = this.editor + '/new';
return UrlFactory.userUrl(url, {path: this.path});
}
});
Object.defineProperty(File.prototype, 'viewUrl', {
get: function viewUrlProperty() {
var url = this.renderer + '/view';
return UrlFactory.jsonAPIUserUrl(url, {path: this.path});
}
});
File.loadFromPath = function(path) {
var data = {
'name': path.substring(path.lastIndexOf('/')+1, path.length),
'path': path,
};
return new File(data);
};
return File;
}])
.service('Files', ['$http', '$q', 'UrlFactory', 'MessageService', 'Session', 'Folder', 'File', function ($http, $q, UrlFactory, MessageService, Session, Folder, File) {
var that = this;
var getPaths = function(files) {
var filenames = [];
for(var i=0,len=files.length; i < len; i++) {
filenames.push(files[i].path);
}
return filenames;
};
var httpRequest = function(method, url, path) {
return $http[method](url, {params: {path: path}})
.then(function(res) {
if (!angular.isDefined(res) || ! angular.isDefined(res.data)) {
return $q.reject(res);
}
return that.dataToObjs(res.data);
});
};
this.dataToObjs = function(data) {
return data.map(function(value) {
if(value.type === 'folder') {
return new Folder(value);
}
else {
return new File(value);
}
});
};
this.query = function(path) {
var url = UrlFactory.jsonAPIUserUrl('explore');
return httpRequest('get', url, path);
};
this.move = function(files, newpath) {
var url = UrlFactory.jsonAPIUserUrl('files/move');
// TODO: the task can failed, it's possible some elements have been
// moved, so we should reload files
return $http.post(url, {paths: getPaths(files), newpath: newpath}).then(function() {
angular.forEach(files, function(file) {
var index = Session.files.indexOf(file);
Session.files.splice(index, 1);
});
Session.unSelectFiles();
MessageService.set('success', 'Files moved!');
});
};
this.delete = function(files) {
var paths = getPaths(files);
var url = UrlFactory.jsonAPIUserUrl('files', {paths: paths});
// TODO: the task can failed, it's possible some elements have been
// deleted, so we should reload files
return $http
.delete(url)
.then(function() {
angular.forEach(files, function(file) {
var index = Session.files.indexOf(file);
Session.files.splice(index, 1);
});
Session.unSelectFiles();
MessageService.set('success', 'Files deleted!');
});
};
}]);
|
QUnit.module("Various Others", function() {
var imperView = null;
function SomeView(vm) {
return function() {
return el("div", [
el("div", [
el("strong", [
vw(SomeView2)
]),
!!imperView && iv(imperView),
])
]);
};
}
function SomeView2(vm) {
return function() {
return el("em", "yay!");
};
}
var vm;
QUnit.test('Init sub-view buried in plain nodes', function(assert) {
var expcHtml = '<div><div><strong><em>yay!</em></strong></div></div>';
instr.start();
vm = domvm.createView(SomeView).mount(testyDiv);
var callCounts = instr.end();
evalOut(assert, vm.node.el, vm.html(), expcHtml, callCounts, { createElement: 4, insertBefore: 4, textContent: 1 });
});
QUnit.test('html() renders subviews without explicit mount()', function(assert) {
imperView = domvm.createView(SomeView2);
instr.start();
vm = domvm.createView(SomeView);
var callCounts = instr.end();
var expcHtml = '<div><div><strong><em>yay!</em></strong><em>yay!</em></div></div>';
assert.equal(vm.html(), expcHtml);
});
QUnit.test('Inserted nodes should not be matched up to sibling views with same root tags', function(assert) {
var nulls = false;
function ViewX() {
return function() {
return el("div", [
nulls ? null : el("div"),
vw(ViewY),
nulls ? null : el("div"),
]);
}
}
function ViewY() {
return function() {
return el("div", "foo");
};
}
instr.start();
vm = domvm.createView(ViewX).mount(testyDiv);
var callCounts = instr.end();
var expcHtml = '<div><div></div><div>foo</div><div></div></div>';
evalOut(assert, vm.node.el, vm.html(), expcHtml, callCounts, { createElement: 4, insertBefore: 4, textContent: 1 });
nulls = true;
instr.start();
vm.redraw();
var callCounts = instr.end();
var expcHtml = '<div><div>foo</div></div>';
evalOut(assert, vm.node.el, vm.html(), expcHtml, callCounts, { removeChild: 2 });
nulls = false;
instr.start();
vm.redraw();
var callCounts = instr.end();
var expcHtml = '<div><div></div><div>foo</div><div></div></div>';
evalOut(assert, vm.node.el, vm.html(), expcHtml, callCounts, { createElement: 2, insertBefore: 2 });
});
function FlattenView(vm) {
return function() {
return el("div", [
el("br"),
tx("hello kitteh"),
[
el("em", "foo"),
el("em", "bar"),
vw(SomeView2),
tx("woohoo!"),
[
vw(SomeView2),
el("i", "another thing"),
]
],
tx("the end"),
]);
};
}
QUnit.test('Flatten child sub-arrays', function(assert) {
var expcHtml = '<div><br>hello kitteh<em>foo</em><em>bar</em><em>yay!</em>woohoo!<em>yay!</em><i>another thing</i>the end</div>';
instr.start();
vm = domvm.createView(FlattenView).mount(testyDiv);
var callCounts = instr.end();
evalOut(assert, vm.node.el, vm.html(), expcHtml, callCounts, { createElement: 7, createTextNode: 3, insertBefore: 10, textContent: 5 });
});
function SomeView3() {
return function() {
return el("em", {style: {width: 30, zIndex: 5}}, "test");
};
}
QUnit.test('"px" appended only to proper numeric style attrs', function(assert) {
var expcHtml = '<em style="width: 30px; z-index: 5;">test</em>';
instr.start();
vm = domvm.createView(SomeView3).mount(testyDiv);
var callCounts = instr.end();
evalOut(assert, vm.node.el, vm.html(), expcHtml, callCounts, { createElement: 1, textContent: 1, insertBefore: 1 });
});
// TODO: how to test mounting to body without blowing away test?
QUnit.test('Mount to existing element instead of append into', function(assert) {
var em = document.createElement("em");
em.textContent = "abc";
testyDiv.appendChild(em);
var expcHtml = '<em style="width: 30px; z-index: 5;">test</em>';
instr.start();
vm = domvm.createView(SomeView3).mount(em, true);
var callCounts = instr.end();
evalOut(assert, em, vm.html(), expcHtml, callCounts, { textContent: 2, insertBefore: 1 });
});
QUnit.test('Raw HTML as body', function(assert) {
function View5(vm) {
return function() {
return el("div", {".innerHTML": '<p class="foo">bar</p> baz'}); // .html()
};
}
var expcHtml = '<div><p class="foo">bar</p> baz</div>';
instr.start();
vm = domvm.createView(View5).mount(testyDiv);
var callCounts = instr.end();
evalOut(assert, vm.node.el, vm.html(), expcHtml, callCounts, { createElement: 1, innerHTML: 1, insertBefore: 1 });
var tab = 1;
function View51() {
return function() {
return el('div', [
tab === 2 && el('span', 'foo'),
el('span', {".innerHTML": 'bar <b>baz</b>'})
]);
};
}
var expcHtml = '<div><span>bar <b>baz</b></span></div>';
instr.start();
vm = domvm.createView(View51).mount(testyDiv);
var callCounts = instr.end();
evalOut(assert, vm.node.el, vm.html(), expcHtml, callCounts, { createElement: 2, innerHTML: 1, insertBefore: 2 });
tab = 2;
var expcHtml = '<div><span>foo</span><span>bar <b>baz</b></span></div>';
instr.start();
vm.redraw();
var callCounts = instr.end();
evalOut(assert, vm.node.el, vm.html(), expcHtml, callCounts, { createElement: 1, textContent: 1, innerHTML: 2, insertBefore: 1 });
});
QUnit.test('Existing DOM element as child', function(assert) {
var el2 = document.createElement("strong");
el2.textContent = "cow";
var body = [
ie(el2),
tx("abc"),
];
function View6(vm) {
return function() {
return el("div", body);
};
}
var expcHtml = '<div><strong>cow</strong>abc</div>';
instr.start();
vm = domvm.createView(View6).mount(testyDiv);
var callCounts = instr.end();
evalOut(assert, vm.node.el, vm.html(), expcHtml, callCounts, { createElement: 1, createTextNode: 1, insertBefore: 3 });
// TODO: ensure injected elems get matched exactly during findDonor
var body = [
tx("abc"),
ie(el2),
];
var expcHtml = '<div>abc<strong>cow</strong></div>';
instr.start();
vm.redraw();
var callCounts = instr.end();
evalOut(assert, vm.node.el, vm.html(), expcHtml, callCounts, { insertBefore: 1 });
});
QUnit.test('Externally inserted element', function(assert) {
var ins = false;
function View6(vm) {
return function() {
return el("div", [
el("span", "a"),
ins ? el("i", "me") : null,
el("em", "b"),
]);
};
}
var expcHtml = '<div><span>a</span><em>b</em></div>';
instr.start();
vm = domvm.createView(View6).mount(testyDiv);
var callCounts = instr.end();
evalOut(assert, vm.node.el, vm.html(), expcHtml, callCounts, { createElement: 3, textContent: 2, insertBefore: 3 });
var el2 = document.createElement("strong");
el2.textContent = "cow";
vm.node.el.insertBefore(el2, vm.node.el.lastChild);
var expcHtml = '<div><span>a</span><strong>cow</strong><em>b</em></div>';
instr.start();
vm.redraw();
var callCounts = instr.end();
evalOut(assert, vm.node.el, vm.html().replace("</span><em>","</span><strong>cow</strong><em>"), expcHtml, callCounts, { });
ins = true;
var expcHtml = "<div><span>a</span><strong>cow</strong><i>me</i><em>b</em></div>";
instr.start();
vm.redraw();
var callCounts = instr.end();
evalOut(assert, vm.node.el, vm.html().replace("</span><i>","</span><strong>cow</strong><i>"), expcHtml, callCounts, { createElement: 1, textContent: 1, insertBefore: 1});
});
QUnit.test('Remove/clean child of sub-view', function(assert) {
var data = ["a"];
var data2 = ["b", "c"];
function View6(vm) {
return function() {
return el("div", [
el("p", data[0]),
vw(View7, data2),
]);
};
}
function View7(vm, data2) {
return function() {
return el("ul", data2.map(function(v) {
return el("li", v);
}));
};
}
instr.start();
vm = domvm.createView(View6).mount(testyDiv);
var callCounts = instr.end();
var expcHtml = '<div><p>a</p><ul><li>b</li><li>c</li></ul></div>';
evalOut(assert, vm.node.el, vm.html(), expcHtml, callCounts, { createElement: 5, textContent: 3, insertBefore: 5 });
data2.shift();
instr.start();
vm.redraw();
var callCounts = instr.end();
var expcHtml = '<div><p>a</p><ul><li>c</li></ul></div>';
evalOut(assert, vm.node.el, vm.html(), expcHtml, callCounts, { removeChild: 1, nodeValue: 1 });
});
QUnit.test('vm.root()', function(assert) {
var vmA, vmB, vmC;
function ViewA(vm) {
vmA = vm;
return function() {
return el("#a", [
vw(ViewB)
]);
}
}
function ViewB(vm) {
vmB = vm;
return function() {
return el("#b", [
vw(ViewC)
]);
};
}
function ViewC(vm) {
vmC = vm;
return function() {
return el("#c", "Hi!");
};
}
domvm.createView(ViewA).mount(testyDiv);
assert.equal(vmC.root(), vmA);
assert.equal(vmB.root(), vmA);
assert.equal(vmA.root(), vmA);
});
QUnit.test('defineElementSpread', function(assert) {
var el2 = domvm.defineElementSpread;
function ViewA(vm) {
return function() {
return el2("#a", vw(ViewB));
}
}
function ViewB(vm) {
return function() {
return el2("#b", "b");
}
}
function ViewC(vm) {
return function() {
return el2("#c", {class: "foo"}, "c");
}
}
function ViewD(vm) {
return function() {
return el2("#d", "d", "dog");
}
}
function ViewE(vm) {
return function() {
return el2("#e");
}
}
instr.start();
var vmA = domvm.createView(ViewA).mount(testyDiv);
var callCounts = instr.end();
var expcHtml = '<div id="a"><div id="b">b</div></div>';
evalOut(assert, vmA.node.el, vmA.html(), expcHtml, callCounts, { createElement: 2, id: 2, insertBefore: 2, textContent: 1 });
instr.start();
var vmC = domvm.createView(ViewC).mount(testyDiv);
var callCounts = instr.end();
var expcHtml = '<div class="foo" id="c">c</div>';
evalOut(assert, vmC.node.el, vmC.html(), expcHtml, callCounts, { createElement: 1, id: 1, className: 1, insertBefore: 1, textContent: 1 });
instr.start();
var vmD = domvm.createView(ViewD).mount(testyDiv);
var callCounts = instr.end();
var expcHtml = '<div id="d">ddog</div>';
evalOut(assert, vmD.node.el, vmD.html(), expcHtml, callCounts, { createElement: 1, id: 1, createTextNode: 1, insertBefore: 2 });
instr.start();
var vmE = domvm.createView(ViewE).mount(testyDiv);
var callCounts = instr.end();
var expcHtml = '<div id="e"></div>';
evalOut(assert, vmE.node.el, vmE.html(), expcHtml, callCounts, { createElement: 1, id: 1, insertBefore: 1 });
});
QUnit.test('defineElementSpread', function(assert) {
function ViewA(vm) {
return function() {
return el("#a", [
vw(ViewB),
el("div", [
vw(ViewB)
])
]);
}
}
var vmBs = [];
function ViewB(vm) {
vmBs.push(vm);
return function() {
return el("#b", "b");
}
}
instr.start();
var vmA = domvm.createView(ViewA).mount(testyDiv);
var callCounts = instr.end();
var expcHtml = '<div id="a"><div id="b">b</div><div><div id="b">b</div></div></div>';
evalOut(assert, vmA.node.el, vmA.html(), expcHtml, callCounts, { createElement: 4, id: 3, insertBefore: 4, textContent: 2 });
var vmbody = vmA.body();
assert.equal(vmbody.length, 2);
assert.equal(vmbody[0], vmBs[0]);
assert.equal(vmbody[1], vmBs[1]);
assert.deepEqual(vmbody[0].body(), []);
});
// mostly for code coverage
QUnit.test('spl prop -> null', function(assert) {
var tpl = null;
function ViewA(vm) {
return function() {
return tpl;
}
}
tpl = el("div", {_data: {}});
instr.start();
var vmA = domvm.createView(ViewA).mount(testyDiv);
var callCounts = instr.end();
var expcHtml = '<div></div>';
evalOut(assert, vmA.node.el, vmA.html(), expcHtml, callCounts, { createElement: 1, insertBefore: 1 });
tpl = el("div");
instr.start();
vmA.redraw();
var callCounts = instr.end();
var expcHtml = '<div></div>';
evalOut(assert, vmA.node.el, vmA.html(), expcHtml, callCounts, { });
});
}); |
module.exports = {
LruCache: require('./lru-cache'),
withCache: require('./cache'),
};
|
const randomString = require('./randomString');
const Parse = require('parse').Parse;
var clientConfig = {}; // eslint-disable-line no-var
// Load client config. Async.
module.exports.configLoad = (store, feathersServices) =>
store.dispatch(feathersServices.config.get())
.then(res => {
if (!localStorage.deviceId) {
localStorage.deviceId = randomString(30);
}
clientConfig = res.action.payload;
if (!clientConfig.agent) { // just being careful
clientConfig.agent = {};
}
clientConfig.agent.deviceId = localStorage.deviceId;
clientConfig.agent.clientBuiltFor =
__processEnvNODE_ENV__; // eslint-disable-line no-undef, camelcase
Parse.serverURL = clientConfig.parseClient.url;
Parse.initialize(clientConfig.parseClient.appId);
console.log(clientConfig);
Object.freeze(clientConfig);
return clientConfig;
})
.catch(error => {
// We cannot use the logger as it requires a loaded config. Log directly to the server.
store.dispatch(feathersServices.logs.create({
level: 'error',
msg: 'Client config get fail',
payload: { deviceId: localStorage.deviceId, error },
}))
.catch(err => console.log( // eslint-disable-line no-console
'Client config.js unexpected error:', err.message
));
});
// Return current value of clientConfig. We cannot do this with ES6 as far as I can tell.
// This code depends on how Babel transpiles import { config } from './config';
Object.defineProperty(module.exports, 'config', {
get() {
return clientConfig;
},
});
|
'use strict';
// Module dependencies
var Q = require('q');
// function to get detailled informations about movie (currently only themoviedb api support)
var info = function(mdb) {
return function(res){
var deferred = Q.defer();
mdb.movieInfo({id: res.results[0].id}, deferred.makeNodeResolver());
return deferred.promise;
};
};
// video search function (currently only themoviedb api support)
var search = function(name,mdb) {
var deferred = Q.defer();
mdb.searchMovie({query: name }, deferred.makeNodeResolver());
return deferred.promise;
};
// the moviedb dedicated init function
var themoviedb = function (infos,config) {
var mdb = require('moviedb')(config.key);
var name = '';
if (infos.movie_name) {
console.log('movie name by encoder');
name = infos.movie_name;
}
else {
console.log('name by path file');
name = infos.complete_name.substring(infos.complete_name.lastIndexOf('/')+1, infos.complete_name.lastIndexOf('.'));
}
console.log(name);
return search(name,mdb).then(info(mdb));
};
// startpoint (currentl only themoviedb api support)
exports.getDetails = function(infos,config) {
if(config.name === 'themoviedb') {
return themoviedb(infos,config);
}
};
|
function intersection (...arrays) {
const result = []
const array = arrays[0]
for (let i = 0; i < array.length; i++) {
const item = array[i]
if (result.includes(item)) continue
let j = 1
for (j; j < arrays.length; j++) {
if (!arrays[j].includes(item)) break
}
if (j === arrays.length) result.push(item)
}
return result
}
module.exports = intersection
|
import serialize from 'serialize-javascript';
import Helmet from 'react-helmet';
import ReactDOM from 'react-dom/server';
import React, {Component, PropTypes} from 'react';
/**
* Wrapper component containing HTML metadata and boilerplate tags.
* Used in server-side code only to wrap the string output of the
* rendered route component.
*
* The only thing this component doesn't (and can't) include is the
* HTML doctype declaration, which is added to the rendered output
* by the server.js file.
*/
export default class Html extends Component {
static propTypes = {
assets: PropTypes.object,
component: PropTypes.node,
store: PropTypes.object
};
render() {
const {assets, component, store} = this.props;
const content = component
? ReactDOM.renderToString(component)
: '';
const head = Helmet.rewind();
return (
<html lang="en-us">
<head>
{head
.base
.toComponent()}
{head
.title
.toComponent()}
{head
.meta
.toComponent()}
{head
.link
.toComponent()}
{head
.script
.toComponent()}
<link rel="shortcut icon" href="/favicon.ico"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
{/* styles (will be present only in production with webpack extract text plugin) */}
{Object
.keys(assets.styles)
.map((style, key) => <link
href={assets.styles[style]}
key={key}
media="screen, projection"
rel="stylesheet"
type="text/css"
charSet="UTF-8"/>)}
{/* (will be present only in development mode) */}
{/* can smoothen the initial style flash (flicker) on page load in development mode. */}
{/* ideally one could also include here the style for the current page (Home.scss, About.scss, etc) */}
{Object
.keys(assets.styles)
.length === 0
? <style
dangerouslySetInnerHTML={{
__html: require('../containers/App/App.scss')._style
}}/>
: null}
</head>
<body>
<div
id="content"
dangerouslySetInnerHTML={{
__html: content
}}/>
<script
dangerouslySetInnerHTML={{
__html: `window.__data=${serialize(store.getState())};`
}}
charSet="UTF-8"/>
<script src={assets.javascript.main} charSet="UTF-8"/>
</body>
</html>
);
}
}
|
(function($) {
$.fn.draggable = function(o) {
return this.each(function() {
new $.ui.draggable(this, o);
});
}
$.fn.undraggable = function() {
}
$.ui.ddmanager = {
current: null,
droppables: [],
prepareOffsets: function(t) {
var dropTop = $.ui.ddmanager.dropTop = [];
var dropLeft = $.ui.ddmanager.dropLeft;
var m = $.ui.ddmanager.droppables;
for (var i = 0; i < m.length; i++) {
m[i].offset = $(m[i].item.element).offset({ border: false });
if (t && m[i].item.options.accept(t.element)) //Activate the droppable if used directly from draggables
m[i].item.activate.call(m[i].item);
}
},
fire: function(oDrag) {
var oDrops = $.ui.ddmanager.droppables;
var oOvers = $.grep(oDrops, function(oDrop) {
if ($.ui.intersect(oDrag, oDrop, oDrop.item.options.tolerance))
oDrop.item.drop.call(oDrop.item);
});
$.each(oDrops, function(i, oDrop) {
if (oDrop.item.options.accept(oDrag.element)) {
oDrop.out = 1; oDrop.over = 0;
oDrop.item.deactivate.call(oDrop.item);
}
});
},
update: function(oDrag) {
if(oDrag.options.refreshPositions) $.ui.ddmanager.prepareOffsets();
var oDrops = $.ui.ddmanager.droppables;
var oOvers = $.grep(oDrops, function(oDrop) {
var isOver = $.ui.intersect(oDrag, oDrop, oDrop.item.options.tolerance)
if (!isOver && oDrop.over == 1) {
oDrop.out = 1; oDrop.over = 0;
oDrop.item.out.call(oDrop.item);
}
return isOver;
});
$.each(oOvers, function(i, oOver) {
if (oOver.over == 0) {
oOver.out = 0; oOver.over = 1;
oOver.item.over.call(oOver.item);
}
});
}
};
$.ui.draggable = function(el, o) {
var options = {};
$.extend(options, o);
$.extend(options, {
_start: function(h, p, c, t, e) {
self.start.apply(t, [self, e]); // Trigger the start callback
},
_beforeStop: function(h, p, c, t, e) {
self.stop.apply(t, [self, e]); // Trigger the start callback
},
_drag: function(h, p, c, t, e) {
self.drag.apply(t, [self, e]); // Trigger the start callback
}
});
var self = this;
if (options.ghosting == true) options.helper = 'clone'; //legacy option check
this.interaction = new $.ui.mouseInteraction(el, options);
}
$.extend($.ui.draggable.prototype, {
plugins: {},
currentTarget: null,
lastTarget: null,
prepareCallbackObj: function(self) {
return {
helper: self.helper,
position: { left: self.pos[0], top: self.pos[1] },
offset: self.options.cursorAt,
draggable: self,
options: self.options
}
},
start: function(that, e) {
var o = this.options;
$.ui.ddmanager.current = this;
$.ui.plugin.call(that, 'start', [e, that.prepareCallbackObj(this)]);
$(this.element).triggerHandler("dragstart", [e, that.prepareCallbackObj(this)], o.start);
if (this.slowMode && $.ui.droppable && !o.dropBehaviour)
$.ui.ddmanager.prepareOffsets(this);
return false;
},
stop: function(that, e) {
var o = this.options;
$.ui.plugin.call(that, 'stop', [e, that.prepareCallbackObj(this)]);
$(this.element).triggerHandler("dragstop", [e, that.prepareCallbackObj(this)], o.stop);
if (this.slowMode && $.ui.droppable && !o.dropBehaviour) //If cursorAt is within the helper, we must use our drop manager
$.ui.ddmanager.fire(this);
$.ui.ddmanager.current = null;
$.ui.ddmanager.last = this;
return false;
},
drag: function(that, e) {
var o = this.options;
$.ui.ddmanager.update(this);
this.pos = [this.pos[0]-o.cursorAt.left, this.pos[1]-o.cursorAt.top];
$.ui.plugin.call(that, 'drag', [e, that.prepareCallbackObj(this)]);
var nv = $(this.element).triggerHandler("drag", [e, that.prepareCallbackObj(this)], o.drag);
var nl = (nv && nv.left) ? nv.left : this.pos[0];
var nt = (nv && nv.top) ? nv.top : this.pos[1];
$(this.helper).css('left', nl+'px').css('top', nt+'px'); // Stick the helper to the cursor
return false;
}
});
})($);
|
const express = require('express');
const { groupBy, sumBy } = require('lodash');
const APIError = require('../../errors/APIError');
const { isUUID } = require('../../lib/idParser');
const dbCatch = require('../../lib/dbCatch');
const router = new express.Router();
router.get('/services/treasury/purchases', (req, res, next) => {
const models = req.app.locals.models;
let initialQuery = models.Purchase;
let price = 'price';
let pricePeriod = 'price.period';
if (req.query.dateIn && req.query.dateOut) {
const dateIn = new Date(req.query.dateIn);
const dateOut = new Date(req.query.dateOut);
if (!Number.isNaN(dateIn.getTime()) && !Number.isNaN(dateOut.getTime())) {
initialQuery = initialQuery
.where('created_at', '>=', dateIn)
.where('created_at', '<=', dateOut);
} else {
return next(new APIError(module, 400, 'Invalid dates'));
}
}
if (req.query.event) {
pricePeriod = {
'price.period': q => q.where({ event_id: req.query.event })
};
}
if (req.query.point) {
initialQuery = initialQuery.where({ point_id: req.query.point });
}
if (req.query.fundation) {
price = {
price: q => q.where({ fundation_id: req.query.fundation })
};
}
initialQuery = initialQuery
.fetchAll({
withRelated: [
price,
pricePeriod,
'price.article',
'price.promotion'
],
withDeleted: true
});
initialQuery
.then((results) => {
// Remove deleted purchases, transform price relation to an outer join
const purchases = results
.toJSON()
.filter(p => !p.deleted_at && p.price.id && p.price.period && p.price.period.id);
const groupedPurchases = groupBy(purchases, 'price_id');
const mappedPurchases = Object.values(groupedPurchases)
.map(p => ({
price : p[0].price.amount,
id : p[0].price.id,
totalTI : sumBy(p, 'price.amount'),
totalVAT: sumBy(p, 'vat'),
count : p.length,
name : (p[0].price.article) ? p[0].price.article.name : p[0].price.promotion.name
}))
.sort((a, b) => a.name.localeCompare(b.name));
res.status(200).json(mappedPurchases).end();
})
.catch(err => dbCatch(module, err, next));
});
router.get('/services/treasury/reloads', (req, res, next) => {
const models = req.app.locals.models;
let initialQuery = models.Reload;
if (req.query.point) {
if (isUUID(req.query.point)) {
initialQuery = initialQuery.where({ point_id: req.query.point });
}
}
if (req.query.dateIn && req.query.dateOut) {
const dateIn = new Date(req.query.dateIn);
const dateOut = new Date(req.query.dateOut);
if (!Number.isNaN(dateIn.getTime()) && !Number.isNaN(dateOut.getTime())) {
initialQuery = initialQuery
.where('created_at', '>=', dateIn)
.where('created_at', '<=', dateOut);
} else {
return next(new APIError(module, 400, 'Invalid dates'));
}
}
initialQuery = initialQuery
.query(q => q
.select('type')
.sum('credit as credit')
.groupBy('type'))
.fetchAll();
initialQuery
.then((credits) => {
res
.status(200)
.json(credits.toJSON())
.end();
})
.catch(err => dbCatch(module, err, next));
});
router.get('/services/treasury/refunds', (req, res, next) => {
const models = req.app.locals.models;
let initialQuery = models.Refund;
if (req.query.dateIn && req.query.dateOut) {
const dateIn = new Date(req.query.dateIn);
const dateOut = new Date(req.query.dateOut);
if (!Number.isNaN(dateIn.getTime()) && !Number.isNaN(dateOut.getTime())) {
initialQuery = initialQuery
.where('created_at', '>=', dateIn)
.where('created_at', '<=', dateOut);
} else {
return next(new APIError(module, 400, 'Invalid dates'));
}
}
initialQuery = initialQuery
.query(q => q
.select('type')
.sum('amount as amount')
.groupBy('type'))
.fetchAll();
initialQuery
.then((amounts) => {
res
.status(200)
.json(amounts.toJSON())
.end();
})
.catch(err => dbCatch(module, err, next));
});
module.exports = router;
|
/* jshint esnext:true */
import {abs, conjugate, copy, divide, evaluate, hypot, inverse, is, isEqual, isOne, isReal, isZero, minus, plus, sign, times, times, toContentMathML, toLaTeX, toMathML, toString, type} from 'Functn';
import {toContentMathML, toLaTeX, toMathML, toString} from 'meta';
import {Circle} from 'Circle';
import {EvaluationError} from 'EvaluationError';
import {Expression} from 'Expression';
import {Permutation} from 'Permutation';
import {Point} from 'Point';
import {Vector} from 'Vector';
/**
* The matrix implementation of MathLib makes calculations with matrices of
* arbitrary size possible. The entries of a matrix can be numbers and complex
* numbers.
*
* It is as easy as
* ```
* new Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
* ```
* to create the following matrix:
* ⎛ 1 2 3 ⎞
* ⎜ 4 5 6 ⎟
* ⎝ 7 8 9 ⎠
*
* @class
* @this {Matrix}
*/
var Matrix = (function () {
function Matrix(matrix) {
var _this = this;
this.type = 'matrix';
if (typeof matrix === 'string') {
// If there is a < in the string we assume it's MathML
if (matrix.indexOf('<') > -1) {
return Expression.parseContentMathML(matrix).evaluate();
} else {
matrix = matrix.trim().replace(/;?\n/g, '],[');
matrix = JSON.parse('[[' + matrix + ']]');
}
}
matrix.forEach(function (x, i) {
_this[i] = x;
});
this.length = matrix.length;
this.cols = matrix[0].length;
this.rows = matrix.length;
}
/**
* Calculates the LU decomposition of a matrix
* The result is cached.
*
* @return {Matrix}
*/
Matrix.prototype.LU = function () {
var i, j, k, t, p, LU = this.toArray(), m = this.rows, n = this.cols, permutation = [];
for (k = 0; k < n; k++) {
// Find the pivot
p = k;
for (i = k + 1; i < m; i++) {
if (Math.abs(LU[i][k]) > Math.abs(LU[p][k])) {
p = i;
}
}
// Exchange if necessary
if (p !== k) {
permutation.unshift([p, k]);
t = LU[p];
LU[p] = LU[k];
LU[k] = t;
}
// The elimination
if (LU[k][k] !== 0) {
for (i = k + 1; i < m; i++) {
LU[i][k] = divide(LU[i][k], LU[k][k]);
for (j = k + 1; j < n; j++) {
LU[i][j] = minus(LU[i][j], times(LU[i][k], LU[k][j]));
}
}
}
}
LU = new Matrix(LU);
this.LU = function () {
return LU;
};
this.LUpermutation = new Permutation(permutation);
return LU;
};
/**
* Calculates the adjoint matrix
*
* @return {Matrix}
*/
Matrix.prototype.adjoint = function () {
return this.map(function (entry) {
return conjugate(entry);
}).transpose();
};
/**
* Calculates the adjugate matrix
*
* @return {Matrix}
*/
Matrix.prototype.adjugate = function () {
return this.map(function (x, r, c, m) {
return times(m.remove(c, r).determinant(), 1 - ((r + c) % 2) * 2);
});
};
/**
* The cholesky decomposition of a matrix
* using the Cholesky–Banachiewicz algorithm.
* Does not change the current matrix, but returns a new one.
* The result is cached.
*
* @return {Matrix}
*/
Matrix.prototype.cholesky = function () {
var i, ii, j, jj, k, kk, sum, choleskyMatrix, cholesky = [];
for (i = 0, ii = this.rows; i < ii; i++) {
cholesky.push([]);
}
for (i = 0, ii = this.rows; i < ii; i++) {
for (j = 0; j < i; j++) {
sum = 0;
for (k = 0, kk = j; k < kk; k++) {
sum = plus(sum, times(cholesky[i][k], cholesky[j][k]));
}
cholesky[i][j] = (this[i][j] - sum) / cholesky[j][j];
}
sum = 0;
for (k = 0, kk = j; k < kk; k++) {
sum = plus(sum, times(cholesky[i][k], cholesky[i][k]));
}
cholesky[i][j] = Math.sqrt(this[j][j] - sum);
for (j++, jj = this.cols; j < jj; j++) {
cholesky[i][j] = 0;
}
}
choleskyMatrix = new Matrix(cholesky);
this.cholesky = function () {
return choleskyMatrix;
};
return choleskyMatrix;
};
/**
* Compares the matrix to an other matrix.
*
* @param {Matrix} m The matrix to compare.
* @return {number}
*/
Matrix.prototype.compare = function (m) {
var i, ii, j, jj;
if (this.rows !== m.rows) {
return sign(this.rows - m.rows);
}
if (this.cols !== m.cols) {
return sign(this.cols - m.cols);
}
for (i = 0, ii = this.rows; i < ii; i++) {
for (j = 0, jj = this.cols; j < jj; j++) {
if (this[i][j] - m[i][j]) {
return sign(this[i][j] - m[i][j]);
}
}
}
return 0;
};
/**
* Copies the matrix
*
* @return {Matrix}
*/
Matrix.prototype.copy = function () {
return this.map(function (entry) {
return copy(entry);
});
};
/**
* Calculates the determinant of the matrix via the LU decomposition.
* The result is cached.
*
* @return {number|Complex}
*/
Matrix.prototype.determinant = function () {
var LU, determinant;
if (!this.isSquare()) {
throw new EvaluationError('Determinant of non square matrix', {
method: 'Matrix.prototype.determinant'
});
}
if (this.rank() < this.rows) {
determinant = 0;
} else {
LU = this.LU();
determinant = times(this.LUpermutation.sgn(), times.apply(null, LU.diag()));
}
this.determinant = function () {
return determinant;
};
return determinant;
};
/**
* Returns the entries on the diagonal in an array
*
* @return {array}
*/
Matrix.prototype.diag = function () {
var diagonal = [], i, ii;
for (i = 0, ii = Math.min(this.rows, this.cols); i < ii; i++) {
diagonal.push(this[i][i]);
}
return diagonal;
};
/**
* Multiplies the matrix by the inverse of a number or a matrix
*
* @return {Matrix|number} n The number or Matrix to be inverted and multiplied
*/
Matrix.prototype.divide = function (n) {
return this.times(inverse(n));
};
/**
* Evaluates the entries of the matrix
*
* @return {Matrix}
*/
Matrix.prototype.evaluate = function () {
return this.map(evaluate);
};
/**
* This function works like the Array.prototype.every function.
* The matrix is processed row by row.
* The function is called with the following arguments:
* the entry at the current position, the number of the row,
* the number of the column and the complete matrix
*
* @param {function} f The function which is called on every argument
* @return {boolean}
*/
Matrix.prototype.every = function (f) {
return Array.prototype.every.call(this, function (x, i) {
return Array.prototype.every.call(x, function (y, j) {
return f(y, i, j, this);
});
});
};
/**
* This function works like the Array.prototype.forEach function.
* The matrix is processed row by row.
* The function is called with the following arguments:
* the entry at the current position, the number of the row,
* the number of the column and the complete matrix
*
* @param {function} f The function which is called on every argument
*/
Matrix.prototype.forEach = function (f) {
Array.prototype.forEach.call(this, function (x, i) {
return Array.prototype.forEach.call(x, function (y, j) {
return f(y, i, j, this);
});
});
};
/**
* Returns the Gershgorin circles of the matrix.
*
* @return {array} Returns an array of circles
*/
Matrix.prototype.gershgorin = function () {
var c = [], rc = [], rr = [], circles = [], i, ii;
for (i = 0, ii = this.rows; i < ii; i++) {
rc.push(0);
rr.push(0);
}
this.forEach(function (x, i, j) {
if (i === j) {
if (is(x, 'complex')) {
c.push(x.toPoint());
} else {
c.push(new Point([x, 0, 1]));
}
} else {
rc[j] += abs(x);
rr[i] += abs(x);
}
});
for (i = 0, ii = this.rows; i < ii; i++) {
circles.push(new Circle(c[i], Math.min(rc[i], rr[i])));
}
return circles;
};
/**
* QR decomposition with the givens method.
*
* @return {[Matrix, Matrix]}
*/
Matrix.prototype.givens = function () {
var rows = this.rows, cols = this.cols, R = this.copy(), Q = Matrix.identity(rows), c, s, rho, i, j, k, ri, rj, qi, qj;
for (i = 0; i < cols; i++) {
for (j = i + 1; j < rows; j++) {
if (!isZero(R[j][i])) {
// We can't use the sign function here, because we want the factor
// to be 1 if A[i][i] is zero.
rho = (R[i][i] < 0 ? -1 : 1) * hypot(R[i][i], R[j][i]);
c = R[i][i] / rho;
s = R[j][i] / rho;
// Apply the rotation
ri = [];
rj = [];
qi = [];
qj = [];
for (k = 0; k < cols; k++) {
ri.push(R[i][k]);
rj.push(R[j][k]);
}
for (k = 0; k < cols; k++) {
R[i][k] = rj[k] * s + ri[k] * c;
R[j][k] = rj[k] * c - ri[k] * s;
}
for (k = 0; k < rows; k++) {
qi.push(Q[k][i]);
qj.push(Q[k][j]);
}
for (k = 0; k < rows; k++) {
Q[k][i] = qi[k] * c + qj[k] * s;
Q[k][j] = -qi[k] * s + qj[k] * c;
}
}
}
}
return [Q, R];
};
/**
* Calculates the inverse matrix.
*
* @return {Matrix}
*/
Matrix.prototype.inverse = function () {
var i, ii, res, inverse, col = [], matrix = [], n = this.rows;
if (!this.isSquare()) {
throw EvaluationError('Inverse of non square matrix', { method: 'Matrix.prototype.inverse' });
}
for (i = 0, ii = n - 1; i < ii; i++) {
matrix.push([]);
col.push(0);
}
matrix.push([]);
col.push(1);
col = col.concat(col).slice(0, -1);
for (i = 0, ii = n; i < ii; i++) {
res = this.solve(col.slice(n - i - 1, 2 * n - i - 1));
if (res === undefined) {
return;
}
res.forEach(function (x, i) {
matrix[i].push(x);
});
}
inverse = new Matrix(matrix);
this.inverse = function () {
return inverse;
};
return inverse;
};
/**
* Determines if the matrix is a band matrix.
*
* @param {number} l The wished lower bandwidth
* @param {number} u The wished upper bandwidth
* @return {boolean}
*/
Matrix.prototype.isBandMatrix = function (l, u) {
// var i, j, ii, jj;
if (arguments.length === 1) {
u = l;
}
return this.every(function (x, i, j) {
return (i - l <= j && i + u >= j) || isZero(x);
});
// for (i = 0, ii = this.rows; i < ii; i++) {
// for (j = 0, jj = this.cols; j < jj; j++) {
// if (i - j < l && this[i][j] !== 0) {
// return false;
// }
// }
// }
// return true;
};
/**
* Determines if the matrix is a diagonal matrix.
*
* @return {boolean}
*/
Matrix.prototype.isDiag = function () {
var i, j, ii, jj;
if (Number(this.hasOwnProperty('isUpper') && this.isUpper()) + Number(this.hasOwnProperty('isLower') && this.isLower()) + Number(this.hasOwnProperty('isSymmetric') && this.isSymmetric()) > 1) {
return true;
}
for (i = 0, ii = this.rows; i < ii; i++) {
for (j = 0, jj = this.cols; j < jj; j++) {
if (i !== j && !isZero(this[i][j])) {
return false;
}
}
}
return true;
};
/**
* Determines if the matrix is equal to an other matrix.
*
* @param {Matrix} matrix The matrix to compare with
* @return {boolean}
*/
Matrix.prototype.isEqual = function (matrix) {
var i, j, ii, jj;
if (this === matrix) {
return true;
}
if (this.rows === matrix.rows && this.cols === matrix.cols) {
for (i = 0, ii = this.rows; i < ii; i++) {
for (j = 0, jj = this.cols; j < jj; j++) {
if (!isEqual(this[i][j], matrix[i][j])) {
return false;
}
}
}
return true;
}
return false;
};
/**
* Determines if the matrix is a identity matrix.
*
* @return {boolean}
*/
Matrix.prototype.isIdentity = function () {
if (!this.isSquare()) {
return false;
}
var isIdentity = this.every(function (x, r, c) {
return r === c ? isOne(x) : isZero(x);
});
this.isIdentity = function () {
return isIdentity;
};
return isIdentity;
};
/**
* Determines if the matrix is invertible.
*
* @return {boolean}
*/
Matrix.prototype.isInvertible = function () {
return this.isSquare() && this.rank() === this.rows;
};
/**
* Determines if the matrix is a lower triangular matrix.
*
* @return {boolean}
*/
Matrix.prototype.isLower = function () {
return this.slice(0, -1).every(function (x, i) {
return x.slice(i + 1).every(isZero);
});
};
/**
* Determines if the matrix is negative definite
*
* @return {boolean}
*/
Matrix.prototype.isNegDefinite = function () {
if (!this.isSquare()) {
return;
}
if (this.rows === 1) {
return this[0][0] < 0;
}
// Sylvester's criterion
if (this.rows % 2 === 0) {
return this.determinant() > 0 && this.remove(this.rows - 1, this.cols - 1).isNegDefinite();
} else {
return this.determinant() < 0 && this.remove(this.rows - 1, this.cols - 1).isNegDefinite();
}
};
/**
* Determines if the matrix is a orthogonal.
*
* @return {boolean}
*/
Matrix.prototype.isOrthogonal = function () {
return this.transpose().times(this).isIdentity();
};
/**
* Determines if the matrix is a permutation matrix
*
* @return {boolean}
*/
Matrix.prototype.isPermutation = function () {
var rows = [], cols = [];
return this.every(function (x, r, c) {
if (isOne(x)) {
if (rows[r] || cols[c]) {
return false;
} else {
rows[r] = true;
cols[c] = true;
return true;
}
} else if (isZero(x)) {
return true;
}
return false;
}) && rows.length === this.rows && cols.length === this.cols;
};
/**
* Determines if the matrix is positive definite
*
* @return {boolean}
*/
Matrix.prototype.isPosDefinite = function () {
if (!this.isSquare()) {
return;
}
if (this.rows === 1) {
return this[0][0] > 0;
}
// Sylvester's criterion
return this.determinant() > 0 && this.remove(this.rows - 1, this.cols - 1).isPosDefinite();
};
/**
* Determines if the matrix has only real entries
*
* @return {boolean}
*/
Matrix.prototype.isReal = function () {
return this.every(isReal);
};
/**
* Determines if the matrix is a scalar matrix
* (that is a multiple of the identity matrix)
*
* @return {boolean}
*/
Matrix.prototype.isScalar = function () {
var i, ii, diag = this.diag;
if (this.hasOwnProperty('isIdentity') && this.hasOwnProperty('isZero')) {
if (this.isIdentity() || this.isZero()) {
return true;
} else {
return false;
}
}
if (this.isDiag()) {
for (i = 1, ii = this.rows; i < ii; i++) {
if (!isEqual(diag[0], diag[i])) {
return false;
}
}
return true;
}
return false;
};
/**
* Determines if the matrix is a square matrix
*
* @return {boolean}
*/
Matrix.prototype.isSquare = function () {
return this.cols === this.rows;
};
/**
* Determines if the matrix is symmetric
*
* @return {boolean}
*/
Matrix.prototype.isSymmetric = function () {
var i, ii, j, jj, isSymmetric = true;
if (!this.isSquare()) {
isSymmetric = false;
} else {
lp:
for (i = 0, ii = this.rows; i < ii; i++) {
for (j = i + 1, jj = this.cols; j < jj; j++) {
if (!isEqual(this[i][j], this[j][i])) {
isSymmetric = false;
break lp;
}
}
}
}
this.isSymmetric = function () {
return isSymmetric;
};
return isSymmetric;
};
/**
* Determines if the matrix is a upper triangular matrix
*
* @return {boolean}
*/
Matrix.prototype.isUpper = function () {
return this.slice(1).every(function (x, i) {
return x.slice(0, i + 1).every(isZero);
});
};
/**
* Determines if the matrix is a vector
* (only one row or one column)
*
* @return {boolean}
*/
Matrix.prototype.isVector = function () {
return (this.rows === 1) || (this.cols === 1);
};
/**
* Determines if the matrix the zero matrix
* The result is cached.
*
* @return {boolean}
*/
Matrix.prototype.isZero = function () {
var isZero = this.every(isZero);
this.isZero = function () {
return isZero;
};
return isZero;
};
/**
* This function works like the Array.prototype.map function.
* The matrix is processed row by row.
* The function is called with the following arguments:
* the entry at the current position, the number of the row,
* the number of the column and the complete matrix
*
* @param {function} f The function which is called on every argument
* @return {Matrix}
*/
Matrix.prototype.map = function (f) {
var m = this;
return new Matrix(Array.prototype.map.call(this, function (x, i) {
return Array.prototype.map.call(x, function (y, j) {
return f(y, i, j, m);
});
}));
};
/**
* Calculates a minor
*
* @param {number} r The row to be removed.
* @param {number} c The column to be removed.
* @return {Matrix}
*/
Matrix.prototype.minor = function (r, c) {
return this.remove(r, c).determinant();
};
/**
* Calculates the difference of two matrices
*
* @param {Matrix} subtrahend The matrix to be subtracted.
* @return {Matrix}
*/
Matrix.prototype.minus = function (subtrahend) {
if (this.rows === subtrahend.rows && this.cols === subtrahend.cols) {
return this.plus(subtrahend.negative());
} else {
throw EvaluationError('Matrix sizes not matching', { method: 'Matrix.prototype.minus' });
}
};
/**
* Returns the negative matrix
*
* @return {Matrix}
*/
Matrix.prototype.negative = function () {
var i, ii, negative = [];
for (i = 0, ii = this.rows; i < ii; i++) {
negative.push(this[i].map(function (entry) {
return negative(entry);
}));
}
return new Matrix(negative);
};
/**
* This function adds a matrix to the current matrix
* and returns the result as a new matrix.
*
* @param {Matrix} summand The matrix to be added.
* @return {Matrix}
*/
Matrix.prototype.plus = function (summand) {
var i, ii, j, jj, sum = [];
if (this.rows === summand.rows && this.cols === summand.cols) {
for (i = 0, ii = this.rows; i < ii; i++) {
sum[i] = [];
for (j = 0, jj = this.cols; j < jj; j++) {
sum[i][j] = plus(this[i][j], summand[i][j]);
}
}
return new Matrix(sum);
} else {
throw EvaluationError('Matrix sizes not matching', { method: 'Matrix.prototype.plus' });
}
};
/**
* Determines the rank of the matrix
*
* @return {number}
*/
Matrix.prototype.rank = function () {
var i, j, rank = 0, mat = this.rref();
rankloop:
for (i = Math.min(this.rows, this.cols) - 1; i >= 0; i--) {
for (j = this.cols - 1; j >= i; j--) {
if (!isZero(mat[i][j])) {
rank = i + 1;
break rankloop;
}
}
}
this.rank = function () {
return rank;
};
return rank;
};
/**
* This function works like the Array.prototype.reduce function.
*
* @return {any}
*/
Matrix.prototype.reduce = function () {
var args = [];
for (var _i = 0; _i < (arguments.length - 0); _i++) {
args[_i] = arguments[_i + 0];
}
return Array.prototype.reduce.apply(this, args);
};
/**
* This function removes the specified rows and/or columns for the matrix.
*
* @param {number|array} row The row(s) to be removed.
* @param {number|array} col The column(s) to be removed.
* @return {Matrix}
*/
Matrix.prototype.remove = function (row, col) {
var rest = this.toArray();
if (row || row === 0) {
if (typeof row === 'number') {
row = [row];
}
rest = rest.filter(function (x, i) {
return row.indexOf(i) === -1;
});
}
if (col || col === 0) {
if (typeof col === 'number') {
col = [col];
}
col = col.sort().reverse();
col.forEach(function (n) {
rest = rest.map(function (x) {
x.splice(n, 1);
return x;
});
});
}
return new Matrix(rest);
};
/**
* Calculate the reduced row echelon form (rref) of a matrix.
*
* @return {Matrix}
*/
Matrix.prototype.rref = function () {
var i, ii, j, jj, k, kk, pivot, factor, swap, lead = 0, rref = this.toArray();
for (i = 0, ii = this.rows; i < ii; i++) {
if (this.cols <= lead) {
return new Matrix(rref);
}
// Find the row with the biggest pivot element
j = i;
while (rref[j][lead] === 0) {
j++;
if (this.rows === j) {
j = i;
lead++;
if (this.cols === lead) {
return new Matrix(rref);
}
}
}
// Swap the pivot row to the top
if (i !== j) {
swap = rref[j];
rref[j] = rref[i];
rref[i] = swap;
}
pivot = rref[i][lead];
for (j = lead, jj = this.cols; j < jj; j++) {
rref[i][j] /= pivot;
}
for (j = 0, jj = this.rows; j < jj; j++) {
if (j === i) {
continue;
}
factor = rref[j][lead];
for (k = 0, kk = this.cols; k < kk; k++) {
rref[j][k] = minus(rref[j][k], times(factor, rref[i][k]));
}
}
lead++;
}
return new Matrix(rref);
};
/**
* This function works like the Array.prototype.slice function.
*
* @return {array}
*/
Matrix.prototype.slice = function () {
var args = [];
for (var _i = 0; _i < (arguments.length - 0); _i++) {
args[_i] = arguments[_i + 0];
}
return Array.prototype.slice.apply(this, args);
};
/**
* Solves the system of linear equations Ax = b
* given by the matrix A and a vector or point b.
*
* @param {Vector} b The b in Ax = b
* @return {Vector}
*/
Matrix.prototype.solve = function (b) {
// Ax = b -> LUx = b. Then y is defined to be Ux
var LU = this.LU(), i, j, n = b.length, x = [], y = [];
// Permutate b according to the LU decomposition
b = this.LUpermutation.applyTo(b);
for (i = 0; i < n; i++) {
y[i] = b[i];
for (j = 0; j < i; j++) {
y[i] = minus(y[i], times(LU[i][j], y[j]));
}
}
for (i = n - 1; i >= 0; i--) {
x[i] = y[i];
for (j = i + 1; j < n; j++) {
x[i] = minus(x[i], times(LU[i][j], x[j]));
}
if (LU[i][i] === 0) {
if (x[i] !== 0) {
return undefined;
} else {
x[i] = x[i];
}
} else {
x[i] = divide(x[i], LU[i][i]);
}
}
if (type(b) === 'array') {
return x;
} else {
return new b.constructor(x);
}
};
/**
* This function works like the Array.prototype.some function.
* The matrix is processed row by row.
* The function is called with the following arguments:
* the entry at the current position, the number of the row,
* the number of the column and the complete matrix
*
* @param {function} f The function which is called on every argument
* @return {boolean}
*/
Matrix.prototype.some = function (f) {
return Array.prototype.some.call(this, function (x, i) {
return Array.prototype.some.call(x, function (y, j) {
return f(y, i, j, this);
});
});
};
/**
* Multiplies the current matrix with a number, a matrix, a point or a vector.
*
* @param {number|Matrix|Point|Rational|Vector} a The object to multiply to the current matrix
* @return {Matrix|Point|Vector}
*/
Matrix.prototype.times = function (a) {
var i, ii, j, jj, k, kk, product = [], entry;
if (a.type === 'rational') {
a = a.coerceTo('number');
}
if (typeof a === 'number' || a.type === 'complex') {
return this.map(function (x) {
return times(x, a);
});
} else if (a.type === 'matrix') {
if (this.cols === a.rows) {
for (i = 0, ii = this.rows; i < ii; i++) {
product[i] = [];
for (j = 0, jj = a.cols; j < jj; j++) {
entry = 0;
for (k = 0, kk = this.cols; k < kk; k++) {
entry = plus(entry, times(this[i][k], a[k][j]));
}
product[i][j] = entry;
}
}
return new Matrix(product);
} else {
throw EvaluationError('Matrix sizes not matching', { method: 'Matrix#times' });
}
} else if (a.type === 'point' || a.type === 'vector') {
if (this.cols === a.length) {
for (i = 0, ii = this.rows; i < ii; i++) {
entry = 0;
for (j = 0, jj = this.cols; j < jj; j++) {
entry = plus(entry, times(this[i][j], a[j]));
}
product.push(entry);
}
return new a.constructor(product);
}
}
};
/**
* Converts the matrix to a two-dimensional array
*
* @return {array}
*/
Matrix.prototype.toArray = function () {
return Array.prototype.map.call(this, function (x) {
return Array.prototype.map.call(x, function (y) {
return copy(y);
});
});
};
/**
* Converts the columns of the matrix to vectors
*
* @return {array}
*/
Matrix.prototype.toColVectors = function () {
return this.transpose().toRowVectors();
};
/**
* converting the matrix to content MathML
*
* @param {object} [options] - Optional options to style the output
* @return {string}
*/
Matrix.prototype.toContentMathML = function (options) {
if (typeof options === "undefined") { options = {}; }
if (options.strict) {
return this.reduce(function (str, x) {
return str + '<apply><csymbol cd="linalg2">matrixrow</csymbol>' + x.map(function (entry) {
return toContentMathML(entry, options);
}).join('') + '</apply>';
}, '<apply><csymbol cd="linalg2">matrix</csymbol>') + '</apply>';
} else {
return this.reduce(function (str, x) {
return str + '<matrixrow>' + x.map(function (entry) {
return toContentMathML(entry, options);
}).join('') + '</matrixrow>';
}, '<matrix>') + '</matrix>';
}
};
/**
* Converting the matrix to LaTeX
*
* @param {object} [options] - Optional options to style the output
* @return {string}
*/
Matrix.prototype.toLaTeX = function (options) {
if (typeof options === "undefined") { options = {}; }
var passOptions = { base: options.base, baseSubscript: options.baseSubscript };
return '\\begin{pmatrix}\n' + this.reduce(function (str, x) {
return str + x.map(function (entry) {
return toLaTeX(entry, passOptions);
}).join(' & ') + '\\\n';
}, '').slice(0, -2) + '\n\\end{pmatrix}';
};
/**
* converting the matrix to (presentation) MathML
*
* @param {object} [options] - Optional options to style the output
* @return {string}
*/
Matrix.prototype.toMathML = function (options) {
if (typeof options === "undefined") { options = {}; }
var passOptions = { base: options.base, baseSubscript: options.baseSubscript };
return this.reduce(function (str, x) {
return str + '<mtr><mtd>' + x.map(function (entry) {
return toMathML(entry, passOptions);
}).join('</mtd><mtd>') + '</mtd></mtr>';
}, '<mrow><mo> ( </mo><mtable>') + '</mtable><mo> ) </mo></mrow>';
};
/**
* Converts the rows of the matrix to vectors
*
* @return {array}
*/
Matrix.prototype.toRowVectors = function () {
return this.toArray().map(function (v) {
return new Vector(v);
});
};
/**
* Creating a custom .toString() function
*
* @param {object} [options] - Optional options to style the output
* @return {string}
*/
Matrix.prototype.toString = function (options) {
if (typeof options === "undefined") { options = {}; }
var passOptions = { base: options.base, baseSubscript: options.baseSubscript };
return this.reduce(function (str, x) {
return str + x.map(function (entry) {
return toString(entry, passOptions);
}).join('\t') + '\n';
}, '').slice(0, -1);
};
/**
* Calculating the trace of the matrix
*
* @return {number|Complex}
*/
Matrix.prototype.trace = function () {
var trace = plus.apply(null, this.diag());
this.trace = function () {
return trace;
};
return trace;
};
/**
* Calculating the transpose of the matrix
* The result is cached.
*
* @return {Matrix}
*/
Matrix.prototype.transpose = function () {
var transposedMatrix, row, i, j, ii, jj, transpose = [];
for (i = 0, ii = this.cols; i < ii; i++) {
row = [];
for (j = 0, jj = this.rows; j < jj; j++) {
row.push(this[j][i]);
}
transpose.push(row);
}
transposedMatrix = new Matrix(transpose);
this.transpose = function () {
return transposedMatrix;
};
return transposedMatrix;
};
Matrix.givensMatrix = function (n, i, k, phi) {
var givens = Matrix.identity(n);
givens[k][k] = givens[i][i] = Math.cos(phi);
givens[i][k] = Math.sin(phi);
givens[k][i] = -givens[i][k];
return givens;
};
Matrix.identity = function (n) {
var row = [], matrix = [], i, ii;
n = n || 1;
for (i = 0, ii = n - 1; i < ii; i++) {
row.push(0);
}
row.push(1);
row = row.concat(row);
row = row.slice(0, -1);
for (i = 0, ii = n; i < ii; i++) {
matrix.push(row.slice(n - i - 1, 2 * n - i - 1));
}
return new Matrix(matrix);
};
Matrix.numbers = function (n, r, c) {
var i, ii, row = [], matrix = [];
for (i = 0, ii = c || r || 1; i < ii; i++) {
row.push(n);
}
for (i = 0, ii = r || 1; i < ii; i++) {
matrix.push(row.slice(0));
}
return new Matrix(matrix);
};
Matrix.one = function (r, c) {
if (typeof r === "undefined") { r = 1; }
if (typeof c === "undefined") { c = r; }
return Matrix.numbers(1, r, c);
};
Matrix.random = function (r, c) {
var row, matrix = [], i, j, ii, jj;
for (i = 0, ii = r || 1; i < ii; i++) {
row = [];
for (j = 0, jj = c || r || 1; j < jj; j++) {
row.push(Math.random());
}
matrix.push(row);
}
return new Matrix(matrix);
};
Matrix.zero = function (r, c) {
if (typeof r === "undefined") { r = 1; }
if (typeof c === "undefined") { c = r; }
return Matrix.numbers(0, r, c);
};
return Matrix;
})();
export default Matrix;
|
/* jshint node: true */
/* global it, before, describe */
/*jshint strict: true*/
var assert = require("assert");
var core = new (require("ebus"))();
var threader = require("./threader.js");
var gen = require("../lib/generate.js");
var config = require('./../server-config.js');
var guid = gen.uid;
var names = gen.names;
var message = {
id:guid(),
text: "values : " + Math.random(),
from : "guest-" + names(6),
to: "avesty",
type: 'text',
time: new Date().getTime(),
tags: [],
thread: "asdfasdf",
room: {
id: "avesty",
params: {
threader: {
enabled: true
}
}
}
};
function copyMsg() { "use strict"; return JSON.parse(JSON.stringify(message)); }
function isEmpty(str) {
"use strict";
return (!str || 0 === str.length);
}
describe('threader', function() {
"use strict";
before( function(done) {
this.timeout(10000);
threader(core, config.threader);
setTimeout(function(){
done();
}, 9000);
});
it('should have a thread of type "string"', function(done) {
var msg = copyMsg();
core.emit("text", msg, function(/*err, msg*/) {
console.log("message= ", msg);
var m = (msg.thread && typeof msg.thread === 'string')? true : false;
assert.equal(m, true, "Unable to get a thread for message OR typeof thread is not a string.");
done();
});
//done();
});
/*it('should get a thread with lables', function(done) {
var msg = copyMsg();
core.emit("text", msg, function(err, msg) {
console.log("message= ", msg);
var m = (msg.labels && msg.labels.normal && msg.labels.nonsense && msg.labels.spam) ? true : false;
assert.equal(m, true, "Unable to get a labels");
done();
});
});*/
it('should not take more then 1 sec', function(done) {
this.timeout(1100);
var msg = copyMsg();
msg.threads = [];
core.emit("text", msg, function(/*err, data*/) {
console.log(msg);
done();
});
});
it('should get threads if threader params is not defined', function(done) {
var msg = copyMsg();
delete msg.room.params.threader;
core.emit("text", msg, function(/*err, data*/) {
console.log("msg=", msg);
var m = (msg.thread)? true : false;
assert.equal(m, true, "No thread added to array");
done();
});
});
it('should not get threads if disabled', function(done) {
var msg = copyMsg();
msg.room.params.threader.enabled = false;
core.emit("text", msg, function(/*err, data*/) {
console.log("msg=", msg);
assert.equal(isEmpty(msg.thread), true, "Got a thread on disable");
done();
});
});
it('Invalid threader params', function(done) {
var msg = copyMsg();
var room = msg.room;
room.params.threader = "hello"; // invalid value
core.emit("room", {room: room}, function(err/* data*/) {
console.log("msg=", room, err);
assert.equal(!!err, true, "Should throw error");
done();
});
});
it('valid threader params', function(done) {
var msg = copyMsg();
var room = msg.room;
core.emit("room", {room : room}, function(err/*, data*/) {
console.log("msg=", room, err);
assert.equal(!err, true, "Should throw error");
done();
});
});
});
|
var searchData=
[
['bit_20by_20bit',['bit by bit',['../d0/d30/md_README.html',1,'']]]
];
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('helix')) :
typeof define === 'function' && define.amd ? define('HX_IO', ['exports', 'helix'], factory) :
(factory((global.HX_IO = {}),global.HX));
}(this, (function (exports,HX) { 'use strict';
/**
* Exporter forms a base class for exporters.
*
* @property onComplete A Signal called when exporting is finished. A Blob is passed as the payload.
* @property onProgress A Signal called when exporting makes progress. A float ratio between 0 - 1 is passed as the payload.
*/
function Exporter()
{
this.onComplete = new Signal(/*Blob*/);
this.onProgress = new Signal(/*ratio*/);
}
Exporter.prototype = {
/**
* Exports the object. When done.
*/
export: function(object)
{
}
};
/**
* ASH is an exporter for SphericalHarmonicsRGB objects (L2 spherical harmonics).
*/
function ASH()
{
Exporter.call(this);
}
ASH.prototype = Object.create(Exporter.prototype);
/**
* Exports a SphericalHarmonicsRGB object.
*/
Exporter.prototype.export = function(sphericalHarmonics)
{
var str = "# Generated with Helix\n";
var sh = sphericalHarmonics._coefficients;
var n = 0;
for (var l = 0; l < 3; ++l) {
str += "\nl=" + l + ":\n" ;
for (var m = -l; m <= l; ++m) {
str += "m=" + m + ": ";
str += sh[n].r + " " + sh[n].g + " " + sh[n].b + "\n";
++n;
}
}
this.onComplete.dispatch(new Blob([str], {type: "text/plain;charset=utf-8"}));
};
// https://www.khronos.org/files/gltf20-reference-guide.pdf
/**
* GLTFData contains all the info loaded
* @constructor
*/
function GLTFData()
{
/**
* The default scene to show first, as defined by GLTF.
*/
this.defaultScene = new HX.Scene();
/**
* The loaded scenes.
*/
this.scenes = {};
}
function readFloat(dataView, offset)
{
return dataView.getFloat32(offset, true);
}
function readFloat3(dataView, offset)
{
var f = new HX.Float4();
f.x = dataView.getFloat32(offset, true);
f.y = dataView.getFloat32(offset + 4, true);
f.z = dataView.getFloat32(offset + 8, true);
return f;
}
function readMatrix4x4(dataView, offset)
{
var m = [];
for (var j = 0; j < 16; ++j) {
m[j] = dataView.getFloat32(offset, true);
offset += 4;
}
return new HX.Matrix4x4(m);
}
function readQuat(dataView, offset)
{
var q = new HX.Quaternion();
q.x = dataView.getFloat32(offset, true);
q.y = dataView.getFloat32(offset + 4, true);
q.z = dataView.getFloat32(offset + 8, true);
q.w = dataView.getFloat32(offset + 12, true);
return q;
}
/**
* GLTF is an importer for glTF files. When loading, GLTF will immediately return a GLTFAsset containing the default
* scene (empty scene if not specified in the glTF file), and will populate this object as it's being loaded.
*
* @constructor
*
* @see {@link https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#introduction}
*
* @author derschmale <http://www.derschmale.com>
*/
function GLTF()
{
// not sure if we're importing a scene?
HX.Importer.call(this);
this._numComponentLookUp = {
SCALAR: 1,
VEC2: 2,
VEC3: 3,
VEC4: 4,
MAT4: 16
};
this._flipCoord = new HX.Matrix4x4();
this._flipCoord.setColumn(0, new HX.Float4(-1, 0, 0, 0));
this._flipCoord.setColumn(1, new HX.Float4(0, 0, 1, 0));
this._flipCoord.setColumn(2, new HX.Float4(0, 1, 0, 0));
}
GLTF.prototype = Object.create(HX.Importer.prototype);
GLTF.prototype.parse = function(file, target)
{
this._defaultSceneIndex = undefined;
this._gltf = JSON.parse(file);
var asset = this._gltf.asset;
this._target = target || new GLTFData();
// maps the animation targets to their closest scene graph objects (the targets can be the scene graph entity
// itself, a MorphAnimation, a SkeletonJointPose)
this._animationTargetNodes = {};
this._animations = [];
if (asset.hasOwnProperty("minVersion")){
var minVersion = asset.minVersion.split(".");
// TODO: check minVersion support
}
if (asset.hasOwnProperty("version")) {
var version = asset.version.split(".");
if (version[0] !== "2") {
this._notifyFailure("Unsupported glTF version!");
return;
}
}
this._assetLibrary = new HX.AssetLibrary();
this._binFileCheck = {};
// queue all assets for loading first
this._queueImages();
this._queueBuffers();
// load dependencies first
this._assetLibrary.onComplete.bind(function() { this._continueParsing(); }, this);
this._assetLibrary.onProgress.bind(function(ratio) { this._notifyProgress(.8 * ratio); }, this);
this._assetLibrary.load();
};
// todo: add some timeouts
GLTF.prototype._continueParsing = function()
{
var gltf = this._gltf;
if (gltf.hasOwnProperty("scene"))
this._defaultSceneIndex = gltf.scene;
var queue = new HX.AsyncTaskQueue();
queue.queue(this._parseMaterials.bind(this));
queue.queue(this._parseMeshes.bind(this));
queue.queue(this._parseNodes.bind(this));
queue.queue(this._parseScenes.bind(this));
queue.queue(this._parseAnimations.bind(this));
queue.queue(this._assignAnimations.bind(this));
queue.onComplete.bind(this._finalize.bind(this));
queue.onProgress.bind((function(ratio) {
this._notifyProgress(.8 + .2 * ratio);
}).bind(this));
queue.execute();
};
GLTF.prototype._finalize = function()
{
var queue = new HX.AsyncTaskQueue();
// this just initializes materials trying not to freeze up the browser
// otherwise it'd all happen on first render
for (var i = 0, len = this._materials.length; i < len; ++i) {
var material = this._materials[i];
queue.queue(material.init.bind(material));
}
queue.onComplete.bind((function() {
this._notifyComplete(this._target);
}).bind(this));
queue.execute();
};
GLTF.prototype._getAccessor = function(index)
{
var accessorDef = this._gltf.accessors[index];
var bufferView;
if (accessorDef.bufferView !== undefined)
bufferView = this._getBufferView(accessorDef.bufferView);
var f = {
dataType: accessorDef.componentType,
numComponents: this._numComponentLookUp[accessorDef.type],
type: accessorDef.type,
data: bufferView? bufferView.data : null,
min: accessorDef.min,
max: accessorDef.max,
byteOffset: bufferView.byteOffset + (accessorDef.byteOffset || 0),
byteStride: bufferView.byteStride,
count: accessorDef.count,
isSparse: false
};
if (accessorDef.sparse) {
f.isSparse = true;
f.sparseCount = accessorDef.sparse.count;
f.sparseOffsets = [];
var indexBufferView = this._getBufferView(accessorDef.sparse.indices.bufferView);
var valuesBufferView = this._getBufferView(accessorDef.sparse.values.bufferView);
f.sparseIndices = {
data: indexBufferView.data,
byteOffset: accessorDef.sparse.indices.byteOffset,
dataType: accessorDef.componentType
};
f.sparseValues = {
data: valuesBufferView.data,
byteOffset: accessorDef.values.indices.byteOffset
};
}
return f;
};
GLTF.prototype._getBufferView = function(index)
{
var bufferView = this._gltf.bufferViews[index];
var buffer = this._buffers[bufferView.buffer];
var byteOffset = buffer.byteOffset + (bufferView.byteOffset || 0);
// HX.Debug.assert(byteOffset + bufferView.byteLength < buffer.byteOffset + buffer.byteLength, "bufferView out of bounds of buffer!");
return {
data: this._assetLibrary.get(buffer.assetID),
byteOffset: byteOffset,
byteLength: bufferView.byteLength,
byteStride: bufferView.byteStride
};
};
GLTF.prototype._queueImages = function()
{
var imageDefs = this._gltf.images;
if (!imageDefs) return;
for (var i = 0; i < imageDefs.length; ++i) {
var image = imageDefs[i];
this._assetLibrary.queueAsset("hx_image_" + i, this._correctURL(image.uri), HX.AssetLibrary.Type.ASSET, HX.JPG);
}
};
GLTF.prototype._queueBuffers = function()
{
var bufferDefs = this._gltf.buffers;
if (!bufferDefs) return;
this._buffers = [];
for (var i = 0; i < bufferDefs.length; ++i) {
var buffer = bufferDefs[i];
if (!this._binFileCheck[buffer.uri]) {
var assetID = "hx_bin_" + i;
this._assetLibrary.queueAsset(assetID, this._correctURL(buffer.uri), HX.AssetLibrary.Type.RAW_BINARY);
this._binFileCheck[buffer.uri] = true;
this._buffers[i] = {
assetID: assetID,
byteOffset: buffer.byteOffset || 0,
byteLength: buffer.byteLength
};
}
}
};
GLTF.prototype._parseMaterials = function()
{
var materialDefs = this._gltf.materials;
if (!materialDefs) return;
this._materials = [];
for (var i = 0; i < materialDefs.length; ++i) {
var matDef = materialDefs[i];
var mat = new HX.BasicMaterial();
mat.name = matDef.name;
mat.specularMapMode = HX.BasicMaterial.SPECULAR_MAP_METALLIC_ROUGHNESS;
mat.normalMap = this._getTexture(matDef.normalTexture);
mat.occlusionMap = this._getTexture(matDef.occlusionTexture);
mat.emissionMap = this._getTexture(matDef.emissiveTexture);
if (matDef.doubleSided) {
mat.cullMode = HX.CullMode.NONE;
}
if (matDef.emissiveFactor) {
var emission = new HX.Color(matDef.emissiveFactor[0], matDef.emissiveFactor[1], matDef.emissiveFactor[2], 1.0);
mat.emissiveColor = emission.linearToGamma(); // BasicMaterial expects gamma values
}
else if (mat.emissionMap)
mat.emissiveColor = HX.Color.WHITE;
var pbr = matDef.pbrMetallicRoughness;
if (pbr) {
mat.colorMap = this._getTexture(pbr.baseColorTexture);
mat.specularMap = this._getTexture(pbr.metallicRoughnessTexture);
if (pbr.baseColorFactor) {
var color = new HX.Color(pbr.baseColorFactor[0], pbr.baseColorFactor[1], pbr.baseColorFactor[2], pbr.baseColorFactor[3]);
mat.color = color.linearToGamma(); // BasicMaterial expects gamma values
}
mat.metallicness = pbr.metallicFactor === undefined ? 1.0 : pbr.metallicFactor;
mat.roughness = pbr.roughnessFactor === undefined? 1.0 : pbr.roughnessFactor;
mat.normalSpecularReflectance = 0.04; // the default specified by GLTF spec
if (mat.specularMap) {
mat.roughness *= .5;
mat.roughnessRange = -mat.roughness;
}
// TODO: There can also be a texCoord property with the textures, but secondary uvs are not supported yet in the default material
}
this._materials[i] = mat;
}
};
GLTF.prototype._getTexture = function(textureDef)
{
return textureDef? this._assetLibrary.get("hx_image_" + this._gltf.textures[textureDef.index].source) : null;
};
GLTF.prototype._parseMeshes = function()
{
var meshDefs = this._gltf.meshes;
if (!meshDefs) return;
// locally stored by index, using gltf nomenclature (actually contains model instances)
this._entities = [];
for (var i = 0, numMeshes = meshDefs.length; i < numMeshes; ++i) {
var meshDef = meshDefs[i];
var entity = new HX.Entity();
entity.name = meshDef.name;
for (var j = 0, numPrims = meshDef.primitives.length; j < numPrims; ++j) {
var primDef = meshDef.primitives[j];
this._parsePrimitive(primDef, entity);
if (meshDef.weights) {
this._parseMorphWeights(meshDef.weights, entity);
}
}
this._entities[i] = entity;
}
};
GLTF.prototype._parseMorphWeights = function(morphWeights, entity)
{
var morphComponent = new HX.MorphAnimation();
if (morphWeights) {
for (var i = 0, len = morphWeights.length; i < len; ++i) {
morphComponent.setWeight("morphTarget_" + i, morphWeights[i]);
}
}
entity.addComponent(morphComponent);
this._animationTargetNodes[morphComponent.name] = entity;
};
GLTF.prototype._parseMorphTargets = function(targetDefs, mesh)
{
for (var i = 0; i < targetDefs.length; ++i) {
var attribs = targetDefs[i];
var morphTarget = new HX.MorphTarget();
morphTarget.name = "morphTarget_" + i;
var positionAcc = this._getAccessor(attribs.POSITION);
var normalAcc = attribs.NORMAL !== undefined? this._getAccessor(attribs.NORMAL) : null;
// tangent morphing not supported in Helix!
// var tangentAcc = attribs.TANGENT !== undefined? this._getAccessor(attribs.TANGENT) : null;
var positionData = new Float32Array(positionAcc.count * 3);
this._readVertexData(positionData, 0, positionAcc, 3, 3, true);
morphTarget.setPositionData(positionData);
if (normalAcc) {
var normalData = new Float32Array(normalAcc.count * 3);
this._readVertexData(normalData, 0, normalAcc, 3, 3, true);
morphTarget.setNormalData(normalData);
}
mesh.addMorphTarget(morphTarget);
}
};
GLTF.prototype._parsePrimitive = function(primDef, entity)
{
var mesh = HX.Mesh.createDefaultEmpty();
var attribs = primDef.attributes;
var positionAcc = this._getAccessor(attribs.POSITION);
var normalAcc = attribs.NORMAL !== undefined? this._getAccessor(attribs.NORMAL) : null;
var tangentAcc = attribs.TANGENT !== undefined? this._getAccessor(attribs.TANGENT) : null;
var texCoordAcc = attribs.TEXCOORD_0 !== undefined? this._getAccessor(attribs.TEXCOORD_0) : null;
var jointIndexAcc = attribs.JOINTS_0 !== undefined? this._getAccessor(attribs.JOINTS_0) : null;
var jointWeightsAcc = attribs.WEIGHTS_0 !== undefined? this._getAccessor(attribs.WEIGHTS_0) : null;
var normalGenMode = 0;
var stride = mesh.getVertexStride(0);
var vertexData = new Float32Array(positionAcc.count * stride);
this._readVertexData(vertexData, 0, positionAcc, 3, stride, true);
if (normalAcc)
this._readVertexData(vertexData, 3, normalAcc, 3, stride, true);
else
normalGenMode = HX.NormalTangentGenerator.MODE_NORMALS;
if (tangentAcc)
this._readVertexData(vertexData, 6, tangentAcc, 4, stride, true);
else if (texCoordAcc)
normalGenMode = normalGenMode | HX.NormalTangentGenerator.MODE_TANGENTS;
if (texCoordAcc)
this._readUVData(vertexData, 10, texCoordAcc, stride);
mesh.setVertexData(vertexData, 0);
if (primDef.hasOwnProperty("mode"))
mesh.elementType = primDef.mode;
var indexAcc = this._getAccessor(primDef.indices);
mesh.setIndexData(this._readIndices(indexAcc));
if (normalGenMode) {
var normalGen = new HX.NormalTangentGenerator();
normalGen.generate(mesh, normalGenMode);
}
if (jointIndexAcc) {
mesh.addVertexAttribute("hx_jointIndices", 4, 1);
mesh.addVertexAttribute("hx_jointWeights", 4, 1);
stride = mesh.getVertexStride(1);
var jointData = new Float32Array(jointIndexAcc.count * stride);
this._readVertexData(jointData, 0, jointIndexAcc, 4, stride);
this._readVertexData(jointData, 4, jointWeightsAcc, 4, stride);
mesh.setVertexData(jointData, 1);
}
entity.addComponent(new HX.MeshInstance(mesh, this._materials[primDef.material]));
if (primDef.targets && primDef.targets.length > 0)
this._parseMorphTargets(primDef.targets, mesh);
};
GLTF.prototype._readVertexData = function(target, offset, accessor, numComponents, stride, flipCoords)
{
var p = offset;
var o = accessor.byteOffset;
var i;
var len = accessor.count;
var src = accessor.data;
var srcStride = accessor.byteStride || 0;
var readFnc;
var elmSize;
if (src) {
if (accessor.dataType === HX.DataType.FLOAT) {
readFnc = src.getFloat32;
elmSize = 4;
}
else if (accessor.dataType === HX.DataType.UNSIGNED_SHORT) {
readFnc = src.getUint16;
elmSize = 2;
}
else if (accessor.dataType === HX.DataType.UNSIGNED_INT) {
readFnc = src.getUint32;
elmSize = 4;
}
else if (accessor.dataType === HX.DataType.UNSIGNED_BYTE) {
readFnc = src.getUint8;
elmSize = 1;
}
else {
this._notifyFailure("Unknown data type " + accessor.dataType);
return;
}
for (i = 0; i < len; ++i) {
var or = o;
for (var j = 0; j < numComponents; ++j) {
target[p + j] = readFnc.call(src, o, true);
o += elmSize;
}
p += stride;
if (srcStride)
o = or + srcStride;
}
}
else {
for (i = 0; i < len; ++i) {
for (j = 0; j < numComponents; ++j) {
target[p + j] = 0.0;
}
}
p += stride;
}
if (accessor.isSparse)
this._applySparseAccessor(target, accessor, numComponents, stride, readFnc, elmSize);
if (flipCoords) {
p = offset;
for (i = 0; i < len; ++i) {
var tmp = target[p + 1];
target[p] = -target[p];
target[p + 1] = target[p + 2];
target[p + 2] = tmp;
p += stride;
}
}
};
GLTF.prototype._applySparseAccessor = function(target, accessor, numComponents, stride, valueReadFunc, valueElmSize)
{
var len = accessor.sparseCount;
var indexData = accessor.sparseIndices.data;
var valueData = accessor.sparseValues.data;
var id = accessor.sparseIndices.byteOffset;
var o = accessor.sparseValues.byteOffset;
var readIndexFnc, idSize;
if (accessor.dataType === HX.DataType.UNSIGNED_SHORT) {
readIndexFnc = indexData.getUint16;
idSize = 2;
}
else if (accessor.dataType === HX.DataType.UNSIGNED_INT) {
readIndexFnc = indexData.getUint32;
idSize = 4;
}
for (var i = 0; i < len; ++i) {
var index = readIndexFnc.call(indexData, id) * stride;
for (var j = 0; j < numComponents; ++j) {
var value = valueReadFunc.call(valueData, o, true);
o += valueElmSize;
target[index + j] = value;
}
id += idSize;
}
};
GLTF.prototype._readUVData = function(target, offset, accessor, stride)
{
var p = offset;
var o = accessor.byteOffset;
var len = accessor.count;
var src = accessor.data;
for (var i = 0; i < len; ++i) {
target[p] = src.getFloat32(o, true);
target[p + 1] = src.getFloat32(o + 4, true);
o += 8;
p += stride;
}
};
GLTF.prototype._readIndices = function(accessor)
{
var o = accessor.byteOffset;
var src = accessor.data;
var len = accessor.count;
if (accessor.dataType === HX.DataType.UNSIGNED_SHORT) {
return new Uint16Array(src.buffer, o, len);
}
else if (accessor.dataType === HX.DataType.UNSIGNED_INT) {
return new Uint32Array(src.buffer, o, len);
}
else {
this._notifyFailure("Unknown data type for indices!");
return;
}
};
GLTF.prototype._parseSkin = function(nodeDef, target)
{
var skinIndex = nodeDef.skin;
var skinDef = this._gltf.skins[skinIndex];
skinDef.name = skinDef.name || "skin ";
var invBinAcc = this._getAccessor(skinDef.inverseBindMatrices);
var src = invBinAcc.data;
var o = invBinAcc.byteOffset;
var skeleton = new HX.Skeleton();
var pose = new HX.SkeletonPose();
var skelNode = this._nodes[skinDef.skeleton];
// no need for it to end up in the scene graph
if (skelNode.parent) skelNode.parent.detach(skelNode);
for (var i = 0; i < skinDef.joints.length; ++i) {
var nodeIndex = skinDef.joints[i];
var joint = new HX.SkeletonJoint();
joint.inverseBindPose = readMatrix4x4(src, o);
o += 64;
joint.inverseBindPose.prepend(this._flipCoord);
joint.inverseBindPose.append(this._flipCoord);
skeleton.joints.push(joint);
var node = this._nodes[nodeIndex];
if (node._jointIndex !== undefined) {
this._notifyFailure("Adding one node to multiple skeletons!");
return;
}
// we use this to keep a mapping when assigning target animations
node._jointIndex = i;
node._skeletonPose = pose;
node._skeleton = skeleton;
if (skinDef.name)
joint.name = skinDef.name + "_joint_" + i;
var jointPose = new HX.SkeletonJointPose();
jointPose.position.copyFrom(node.position);
jointPose.rotation.copyFrom(node.rotation);
jointPose.scale.copyFrom(node.scale);
pose.setJointPose(i, jointPose);
this._animationTargetNodes[joint.name] = target;
}
for (i = 0; i < skinDef.joints.length; ++i) {
nodeIndex = skinDef.joints[i];
node = this._nodes[nodeIndex];
joint = skeleton.joints[i];
joint.parentIndex = node !== skelNode && node.parent? node.parent._jointIndex : -1;
}
var instances = target.components.meshInstance;
for (i = 0; i < instances.length; ++i) {
var instance = instances[i];
instance.skeleton = skeleton;
instance.skeletonPose = pose;
}
};
// TODO: The whole nodes 6 animation parsing thing is messy. Clean up
GLTF.prototype._parseNodes = function()
{
var nodeDefs = this._gltf.nodes;
if (!nodeDefs) return;
var m = new HX.Matrix4x4();
this._nodes = [];
// these may also be skeleton joints, will be determined when parsing skeleton
for (var i = 0; i < nodeDefs.length; ++i) {
var nodeDef = nodeDefs[i];
var node;
if (nodeDef.hasOwnProperty("mesh")) {
node = this._entities[nodeDef.mesh];
// if the node has a specific name, use that.
if (nodeDef.name)
node.name = nodeDef.name;
}
else {
node = new HX.SceneNode();
}
this._animationTargetNodes[node.name] = node;
if (nodeDef.rotation) {
node.rotation.set(nodeDef.rotation[0], nodeDef.rotation[1], nodeDef.rotation[2], nodeDef.rotation[3]);
m.fromQuaternion(node.rotation);
m.prepend(this._flipCoord);
m.append(this._flipCoord);
node.rotation.fromMatrix(m);
}
if (nodeDef.translation)
node.position.set(-nodeDef.translation[0], nodeDef.translation[2], nodeDef.translation[1], 1.0);
if (nodeDef.scale) {
m.fromScale(nodeDef.scale[0], nodeDef.scale[1], nodeDef.scale[2]);
m.prepend(this._flipCoord);
m.append(this._flipCoord);
node.scale.set(m.getColumn(0).length, m.getColumn(1).length, m.getColumn(2).length);
}
if (nodeDef.matrix) {
node.matrix = new HX.Matrix4x4(nodeDef.matrix);
node.matrix.prepend(this._flipCoord);
node.matrix.append(this._flipCoord);
}
this._nodes[i] = node;
}
// all parsed, now we can attach them together
for (i = 0; i < nodeDefs.length; ++i) {
nodeDef = nodeDefs[i];
node = this._nodes[i];
if (nodeDef.children) {
for (var j = 0; j < nodeDef.children.length; ++j) {
var childIndex = nodeDef.children[j];
node.attach(this._nodes[childIndex]);
}
}
}
for (i = 0; i < nodeDefs.length; ++i) {
nodeDef = nodeDefs[i];
node = this._nodes[i];
if (nodeDef.hasOwnProperty("skin"))
this._parseSkin(nodeDef, node);
}
};
GLTF.prototype._parseScenes = function()
{
var sceneDefs = this._gltf.scenes;
if (!sceneDefs) return;
for (var i = 0; i < sceneDefs.length; ++i) {
var sceneDef = sceneDefs[i];
var scene;
// this because a scene was already created for immediate access
if (i === this._defaultSceneIndex)
scene = this._target.defaultScene;
else {
scene = new HX.Scene();
this._target.scenes.push(scene);
}
var childNodes = sceneDef.nodes;
for (var j = 0; j < childNodes.length; ++j) {
var nodeIndex = childNodes[j];
scene.attach(this._nodes[nodeIndex]);
}
}
};
GLTF.prototype._parseAnimationSampler = function(samplerDef, flipCoords, duration)
{
var timesAcc = this._getAccessor(samplerDef.input);
var valuesAcc = this._getAccessor(samplerDef.output);
var timeSrc = timesAcc.data;
var valueSrc = valuesAcc.data;
var t = timesAcc.byteOffset;
var v = valuesAcc.byteOffset;
var m = new HX.Matrix4x4();
// in the case of weights
var elmCount = valuesAcc.count / timesAcc.count;
var clips = [];
if (elmCount === 1) {
var clip = clips[0] = new HX.AnimationClip();
clip.duration = duration;
}
else {
for (var i = 0; i < elmCount; ++i) {
clips[i] = new HX.AnimationClip();
clips[i].duration = duration;
}
}
// valuesAcc can be a multiple of timesAcc, if it contains more weights
for (var k = 0; k < timesAcc.count; ++k) {
var value;
switch(valuesAcc.numComponents) {
case 1:
value = [];
for (i = 0; i < elmCount; ++i)
value[i] = readFloat(valueSrc, v + i * 4);
break;
case 3:
value = readFloat3(valueSrc, v);
if (flipCoords) {
value.x = -value.x;
var tmp = value.y;
value.y = value.z;
value.z = tmp;
}
break;
case 4:
value = readQuat(valueSrc, v);
if (flipCoords) {
m.fromQuaternion(value);
m.prepend(this._flipCoord);
m.append(this._flipCoord);
value.fromMatrix(m);
}
break;
default:
this._notifyFailure("Unsupported animation sampler type");
return;
}
var time = readFloat(timeSrc, t) * 1000.0;
var keyFrame;
if (elmCount === 1) {
keyFrame = new HX.KeyFrame(time, value);
clip.addKeyFrame(keyFrame);
}
else {
for (i = 0; i < elmCount; ++i) {
keyFrame = new HX.KeyFrame(time, value[i]);
clips[i].addKeyFrame(keyFrame);
}
}
v += valuesAcc.numComponents * elmCount * 4;
t += 4;
}
return clips;
};
GLTF.prototype._parseAnimations = function()
{
var animDefs = this._gltf.animations;
if (!animDefs) return;
for (var i = 0; i < animDefs.length; ++i) {
var animDef = animDefs[i];
var animation = new HX.LayeredAnimation();
var duration = 0;
for (var j = 0; j < animDef.samplers.length; ++j) {
var max = this._gltf.accessors[animDef.samplers[j].input].max[0];
duration = Math.max(duration, max);
}
// milliseconds
duration *= 1000;
for (j = 0; j < animDef.channels.length; ++j) {
var layers = this._parseAnimationChannel(animDef.channels[j], animDef.samplers, duration);
for (var k = 0; k < layers.length; ++k)
animation.addLayer(layers[k]);
}
animation.name = animDef.name || "animation_" + i;
this._animations.push(animation);
}
};
GLTF.prototype._parseAnimationChannel = function(channelDef, samplers, duration)
{
var target = this._nodes[channelDef.target.node];
var targetName;
var layers = [];
// gltf targets a node, but we need to target the joint pose
if (target._jointIndex !== undefined) {
targetName = target._skeleton.joints[target._jointIndex].name;
target = target._skeletonPose._jointPoses[target._jointIndex];
}
else {
targetName = target.name;
}
switch (channelDef.target.path) {
case "translation":
var clips = this._parseAnimationSampler(samplers[channelDef.sampler], true, duration);
layers = [ new HX.AnimationLayerFloat4(targetName, "position", clips[0]) ];
break;
case "rotation":
clips = this._parseAnimationSampler(samplers[channelDef.sampler], true, duration);
layers = [ new HX.AnimationLayerQuat(targetName, "rotation", clips[0]) ] ;
break;
case "scale":
clips = this._parseAnimationSampler(samplers[channelDef.sampler], false, duration);
layers = [ new HX.AnimationLayerFloat4(targetName, "scale", clips[0]) ];
break;
case "weights":
clips = this._parseAnimationSampler(samplers[channelDef.sampler], false, duration);
layers = [];
for (var i = 0; i < clips.length; ++i)
layers.push(new HX.AnimationLayerMorphTarget(target.components.morphAnimation[0].name, "morphTarget_" + i, clips[i]));
break;
default:
this._notifyFailure("Unknown channel path!");
return;
}
return layers;
};
GLTF.prototype._assignAnimations = function()
{
var anims = this._animations;
for (var i = 0, len = anims.length; i < len; ++i) {
var anim = anims[i];
// this expects separate animations to target separate scenes:
var entity = this._animationTargetNodes[anim._layers[0]._targetName];
var rootNode = entity._scene.rootNode;
rootNode.addComponent(anim);
}
};
/**
* @classdesc
* <p>Signal provides an implementation of the Observer pattern. Functions can be bound to the Signal, and they will be
* called when the Signal is dispatched. This implementation allows for keeping scope.</p>
* <p>When dispatch has an object passed to it, this is called the "payload" and will be passed as a parameter to the
* listener functions</p>
*
* @constructor
*
* @author derschmale <http://www.derschmale.com>
*/
function Signal$1()
{
this._listeners = [];
this._lookUp = {};
}
/**
* Signals keep "this" of the caller, because having this refer to the signal itself would be silly
*/
Signal$1.prototype =
{
/**
* Binds a function as a listener to the Signal
* @param {function(*):void} listener A function to be called when the function is dispatched.
* @param {Object} [thisRef] If provided, the object that will become "this" in the function. Used in a class as such:
*
* @example
* signal.bind(this.methodFunction, this);
*/
bind: function(listener, thisRef)
{
// param is an optional extra parameter for some internal functionality
this._lookUp[listener] = this._listeners.length;
var callback = thisRef? listener.bind(thisRef) : listener;
this._listeners.push(callback);
},
/**
* Removes a function as a listener.
*/
unbind: function(listener)
{
var index = this._lookUp[listener];
if (index !== undefined) {
this._listeners.splice(index, 1);
delete this._lookUp[listener];
}
},
/**
* Unbinds all bound functions.
*/
unbindAll: function()
{
this._listeners = [];
this._lookUp = {};
},
/**
* Dispatches the signal, causing all the listening functions to be called.
*
* @param [payload] An optional amount of arguments to be passed in as a parameter to the listening functions. Can be used to provide data.
*/
dispatch: function(payload)
{
var len = this._listeners.length;
for (var i = 0; i < len; ++i)
this._listeners[i].apply(null, arguments);
},
/**
* Returns whether there are any functions bound to the Signal or not.
*/
get hasListeners()
{
return this._listeners.length > 0;
}
};
/**
* AsyncTaskQueue allows queueing a bunch of functions which are executed "whenever", in order.
*
* @classdesc
*
* @constructor
*
* @author derschmale <http://www.derschmale.com>
*/
function AsyncTaskQueue()
{
this.onComplete = new Signal$1();
this.onProgress = new Signal$1();
this._queue = [];
this._childQueues = [];
this._currentIndex = 0;
this._isRunning = false;
this._timeout = undefined;
}
AsyncTaskQueue.prototype = {
/**
* Indicates whether the queue is currently running or not.
*/
get isRunning() { return this._isRunning },
/**
* Adds a function to execute. Provide the parameters for the function as parameters after the function.
*/
queue: function(func, rest)
{
// V8 engine doesn't perform well if not copying the array first before slicing
var args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments));
this._queue.push({
func: func,
args: args.slice(1)
});
},
/**
* Adds a child queue to execute. This can be done by queued tasks while this queue is already running.
*/
addChildQueue: function(queue)
{
this._childQueues.push(queue);
},
/**
* Starts execution of the tasks in the queue.
*/
execute: function()
{
if (this._isRunning)
throw new Error("Already running!");
this._isRunning = true;
this._currentIndex = 0;
this._executeTask();
},
/**
* Cancels execution of the queue.
*/
cancel: function()
{
if (!this._isRunning) return;
if (this._timeout !== undefined)
clearTimeout(this._timeout);
this._isRunning = false;
this._timeout = undefined;
},
/**
* @ignore
* @private
*/
_executeTask: function()
{
this._timeout = setTimeout(this._executeImpl.bind(this));
},
/**
* @ignore
* @private
*/
_executeImpl: function()
{
// cancelled
if (!this._isRunning) return;
this.onProgress.dispatch(this._currentIndex / this._queue.length);
if (this._childQueues.length > 0) {
var queue = this._childQueues.shift();
queue.onComplete.bind(this._executeImpl, this);
queue.execute();
}
else if (this._queue.length === this._currentIndex) {
this._isRunning = false;
this.onComplete.dispatch();
}
else {
var elm = this._queue[this._currentIndex];
elm.func.apply(this, elm.args);
++this._currentIndex;
this._executeTask();
}
}
};
/**
* MTL is an importer for .mtl files accompanying .obj files. Rarely needed by itself.
* @constructor
*
* @author derschmale <http://www.derschmale.com>
*/
function MTL()
{
HX.Importer.call(this, HX.URLLoader.DATA_TEXT);
this._textures = [];
this._texturesToLoad = [];
this._activeMaterial = null;
}
MTL.prototype = Object.create(HX.Importer.prototype);
MTL.prototype.parse = function(data, target)
{
target = target || {};
var lines = data.split("\n");
var numLines = lines.length;
for (var i = 0; i < numLines; ++i) {
var line = lines[i].replace(/^\s+|\s+$/g, "");
this._parseLine(line, target);
}
this._loadTextures(target);
};
MTL.prototype._parseLine = function(line, target)
{
// skip line
if (line.length === 0 || line.charAt(0) === "#") return;
var tokens = line.split(/\s+/);
switch (tokens[0].toLowerCase()) {
case "newmtl":
this._activeMaterial = new HX.BasicMaterial();
this._activeMaterial.name = tokens[1];
target[tokens[1]] = this._activeMaterial;
break;
case "ns":
var specularPower = parseFloat(tokens[1]);
this._activeMaterial.roughness = HX.BasicMaterial.roughnessFromShininess(specularPower);
this._activeMaterial.roughnessRange = this._activeMaterial.roughness;
break;
case "kd":
this._activeMaterial.color = new HX.Color(parseFloat(tokens[1]), parseFloat(tokens[2]), parseFloat(tokens[3]));
break;
case "map_kd":
this._activeMaterial.colorMap = this._getTexture(tokens[1]);
break;
case "map_d":
this._activeMaterial.maskMap = this._getTexture(tokens[1]);
this._activeMaterial.alphaThreshold = .5;
break;
case "map_ns":
this._activeMaterial.specularMap = this._getTexture(tokens[1]);
break;
case "map_bump":
case "bump":
this._activeMaterial.normalMap = this._getTexture(tokens[1]);
break;
default:
//console.log("MTL tag ignored or unsupported: " + tokens[0]);
}
};
MTL.prototype._getTexture = function(url)
{
if (!this._textures[url]) {
var tex = new HX.Texture2D();
this._textures[url] = tex;
this._texturesToLoad.push({
file: this._correctURL(url),
importer: HX.JPG,
target: tex
});
}
return this._textures[url];
};
MTL.prototype._loadTextures = function(lib)
{
var library = new HX.AssetLibrary(null, this.options.crossOrigin);
library.fileMap = this.fileMap;
var files = this._texturesToLoad;
var len = files.length;
if (len === 0) {
this._notifyComplete(lib);
return;
}
for (var i = 0; i < files.length; ++i) {
library.queueAsset(files[i].file, files[i].file, HX.AssetLibrary.Type.ASSET, files[i].importer, this.options, files[i].target);
}
library.onComplete.bind(function() {
this._notifyComplete(lib);
}, this);
library.onProgress.bind(function(ratio) {
this._notifyProgress(ratio);
}, this);
library.load(files);
};
/**
* @classdesc
* OBJ is an importer for the Wavefront OBJ format.
* The options property supports the following settings:
* <ul>
* <li>groupsAsObjects: Specifies whether group tags should be treated as separate scene graph objects (true) or as separate MeshInstance components (false). Defaults to true.</li>
* </ul>
*
* @constructor
*
* @author derschmale <http://www.derschmale.com>
*/
function OBJ()
{
HX.Importer.call(this);
this._objects = [];
this._vertices = [];
this._normals = [];
this._uvs = [];
this._hasNormals = false;
this._defaultMaterial = new HX.BasicMaterial();
this._target = null;
this._mtlLibFile = null;
}
OBJ.prototype = Object.create(HX.Importer.prototype);
OBJ.prototype.parse = function(data, target)
{
this._groupsAsObjects = this.options.groupsAsObjects === undefined? true : this._groupsAsObjects;
this._target = target || new HX.Entity();
var lines = data.split("\n");
var numLines = lines.length;
this._pushNewObject("hx_default");
for (var i = 0; i < numLines; ++i) {
var line = lines[i].replace(/^\s+|\s+$/g, "");
this._parseLine(line);
}
if (this._mtlLibFile)
this._loadMTLLib(this._mtlLibFile);
else
this._finish(null);
};
OBJ.prototype._finish = function(mtlLib)
{
var queue = new AsyncTaskQueue();
var numObjects = this._objects.length;
for (var i = 0; i < numObjects; ++i) {
queue.queue(this._translateObject.bind(this), i, mtlLib);
}
for (var m in mtlLib) {
// init all materials while we're in the async queue, otherwise it will all happen on first render
if (mtlLib.hasOwnProperty(m)) {
var material = mtlLib[m];
queue.queue(material.init.bind(material));
}
}
queue.onComplete.bind(this._onComplete, this);
queue.execute();
};
OBJ.prototype._onComplete = function()
{
this._notifyComplete(this._target);
};
OBJ.prototype._loadMTLLib = function(filename)
{
var loader = new HX.AssetLoader(MTL);
var self = this;
loader.onComplete = function (asset)
{
self._finish(asset);
};
loader.onProgress = function(ratio)
{
self._notifyProgress(ratio * .8);
};
loader.onFail = function (message)
{
self._notifyFailure(message);
};
loader.load(filename);
};
OBJ.prototype._parseLine = function(line)
{
// skip line
if (line.length === 0 || line.charAt(0) === "#") return;
var tokens = line.split(/\s+/);
switch (tokens[0].toLowerCase()) {
case "mtllib":
this._mtlLibFile = this._correctURL(tokens[1]);
break;
case "usemtl":
this._setActiveSubGroup(tokens[1]);
break;
case "v":
this._vertices.push(parseFloat(tokens[1]), parseFloat(tokens[3]), parseFloat(tokens[2]));
break;
case "vt":
this._uvs.push(parseFloat(tokens[1]), 1.0 - parseFloat(tokens[2]));
break;
case "vn":
this._normals.push(parseFloat(tokens[1]), parseFloat(tokens[3]), parseFloat(tokens[2]));
break;
case "o":
this._pushNewObject(tokens[1]);
break;
case "g":
if (this._groupsAsObjects)
this._pushNewObject(tokens[1]);
else
this._pushNewGroup(tokens[1]);
break;
case "f":
this._parseFaceData(tokens);
break;
default:
// ignore following tags:
// s
//console.log("OBJ tag ignored or unsupported: " + tokens[0]);
}
};
OBJ.prototype._pushNewObject = function(name)
{
this._activeObject = new OBJ._ObjectData();
this._activeObject.name = name;
this._objects.push(this._activeObject);
this._pushNewGroup("hx_default");
};
OBJ.prototype._pushNewGroup = function(name)
{
this._activeGroup = new OBJ._GroupData();
this._activeGroup.name = name || "Group" + this._activeGroup.length;
this._activeObject.groups.push(this._activeGroup);
this._setActiveSubGroup("hx_default");
};
OBJ.prototype._setActiveSubGroup = function(name)
{
this._activeGroup.subgroups[name] = this._activeGroup.subgroups[name] || new OBJ._SubGroupData();
this._activeSubGroup = this._activeGroup.subgroups[name];
};
OBJ.prototype._parseFaceData = function(tokens)
{
var face = new OBJ._FaceData();
var numTokens = tokens.length;
for (var i = 1; i < numTokens; ++i) {
var faceVertexData = new OBJ._FaceVertexData();
face.vertices.push(faceVertexData);
var indices = tokens[i].split("/");
var index = (indices[0] - 1) * 3;
faceVertexData.posX = this._vertices[index];
faceVertexData.posY = this._vertices[index + 1];
faceVertexData.posZ = this._vertices[index + 2];
if(indices.length > 1) {
index = (indices[1] - 1) * 2;
faceVertexData.uvU = this._uvs[index];
faceVertexData.uvV = this._uvs[index + 1];
if (indices.length > 2) {
index = (indices[2] - 1) * 3;
this._hasNormals = true;
faceVertexData.normalX = this._normals[index];
faceVertexData.normalY = this._normals[index + 1];
faceVertexData.normalZ = this._normals[index + 2];
}
}
}
this._activeSubGroup.faces.push(face);
this._activeSubGroup.numIndices += tokens.length === 4 ? 3 : 6;
};
OBJ.prototype._translateObject = function(objectIndex, mtlLib)
{
var object = this._objects[objectIndex];
var numGroups = object.groups.length;
if (numGroups === 0) return;
var entity = new HX.Entity();
for (var i = 0; i < numGroups; ++i) {
var group = object.groups[i];
for (var key in group.subgroups)
{
if (group.subgroups.hasOwnProperty(key)) {
var subgroup = group.subgroups[key];
if (subgroup.numIndices === 0) continue;
var material = mtlLib? mtlLib[key] : null;
material = material || this._defaultMaterial;
var mesh = this._translateMesh(subgroup);
var meshInstance = new HX.MeshInstance(mesh, material);
entity.addComponent(meshInstance);
}
}
}
if (object.name)
entity.name = object.name;
this._target.attach(entity);
this._notifyProgress(.8 + (objectIndex + 1) / this._objects.length * .2);
};
OBJ.prototype._translateMesh = function(group)
{
var mesh = HX.Mesh.createDefaultEmpty();
var realIndices = [];
var indices = new Array(group.numIndices);
var numVertices = 0;
var currentIndex = 0;
if (group.name)
mesh.name = group.name;
var faces = group.faces;
var numFaces = faces.length;
for (var i = 0; i < numFaces; ++i) {
var face = faces[i];
var faceVerts = face.vertices;
var numVerts = faceVerts.length;
for (var j = 0; j < numVerts; ++j) {
var vert = faceVerts[j];
var hash = vert.getHash();
if (!realIndices.hasOwnProperty(hash))
realIndices[hash] = {index: numVertices++, vertex: vert};
}
indices[currentIndex] = realIndices[faceVerts[0].getHash()].index;
indices[currentIndex+1] = realIndices[faceVerts[2].getHash()].index;
indices[currentIndex+2] = realIndices[faceVerts[1].getHash()].index;
currentIndex += 3;
if (numVerts === 4) {
indices[currentIndex] = realIndices[faceVerts[0].getHash()].index;
indices[currentIndex+1] = realIndices[faceVerts[3].getHash()].index;
indices[currentIndex+2] = realIndices[faceVerts[2].getHash()].index;
currentIndex += 3;
}
}
var vertices = new Array(numVertices * HX.Mesh.DEFAULT_VERTEX_SIZE);
for (hash in realIndices) {
if (!realIndices.hasOwnProperty(hash)) continue;
var data = realIndices[hash];
var vertex = data.vertex;
var index = data.index * HX.Mesh.DEFAULT_VERTEX_SIZE;
vertices[index] = vertex.posX;
vertices[index+1] = vertex.posY;
vertices[index+2] = vertex.posZ;
vertices[index+3] = vertex.normalX;
vertices[index+4] = vertex.normalY;
vertices[index+5] = vertex.normalZ;
vertices[index+6] = 0;
vertices[index+7] = 0;
vertices[index+8] = 0;
vertices[index+9] = 1;
vertices[index+10] = vertex.uvU;
vertices[index+11] = vertex.uvV;
}
mesh.setVertexData(vertices, 0);
mesh.setIndexData(indices);
var mode = HX.NormalTangentGenerator.MODE_TANGENTS;
if (!this._hasNormals) mode = mode | HX.NormalTangentGenerator.MODE_NORMALS;
var generator = new HX.NormalTangentGenerator();
generator.generate(mesh, mode, true);
return mesh;
};
OBJ._FaceVertexData = function()
{
this.posX = 0;
this.posY = 0;
this.posZ = 0;
this.uvU = 0;
this.uvV = 0;
this.normalX = 0;
this.normalY = 0;
this.normalZ = 0;
this._hash = "";
};
OBJ._FaceVertexData.prototype =
{
// instead of actually using the values, we should use the indices as keys
getHash: function()
{
if (!this._hash)
this._hash = this.posX + "/" + this.posY + "/" + this.posZ + "/" + this.uvU + "/" + this.uvV + "/" + this.normalX + "/" + this.normalY + "/" + this.normalZ + "/";
return this._hash;
}
};
OBJ._FaceData = function()
{
this.vertices = []; // <FaceVertexData>
};
OBJ._SubGroupData = function()
{
this.numIndices = 0;
this.faces = []; // <FaceData>
};
OBJ._GroupData = function()
{
this.subgroups = [];
this.name = null;
this._activeMaterial = null;
};
OBJ._ObjectData = function()
{
this.name = null;
this.groups = [];
this._activeGroup = null;
};
/**
* @classdesc
*
* BufferGeometryJSON loads three.js' JSON BufferGeometry format.
*
* @constructor
*
* @author derschmale <http://www.derschmale.com>
*/
function THREEBufferGeometry()
{
HX.Importer.call(this);
}
THREEBufferGeometry.prototype = Object.create(HX.Importer.prototype);
THREEBufferGeometry.prototype.parse = function(data, target)
{
target = target || new HX.Mesh();
var json = JSON.parse(data);
if (json.type !== "BufferGeometry") {
this._notifyFailure("JSON does not contain correct BufferGeometry data! (type property is not BufferGeometry)");
return;
}
HX.Mesh.createDefaultEmpty(target);
this.parseAttributes(json.data.attributes, target);
this.parseIndices(json.data.index, target);
var flags = json.data.attributes.normal? HX.NormalTangentGenerator.MODE_NORMALS : 0;
flags |= json.data.attributes.tangent? HX.NormalTangentGenerator.MODE_TANGENTS : 0;
if (flags) {
var gen = new HX.NormalTangentGenerator();
gen.generate(target, flags);
}
this._notifyComplete(target);
};
THREEBufferGeometry.prototype.parseAttributes = function(attributes, mesh)
{
var map = {
"position": "hx_position",
"normal": "hx_normal",
"tangent": "hx_tangent",
"uv": "hx_texCoord"
};
// assume position is always present
var numVertices = attributes.position.array.length / attributes.position.itemSize;
for (var name in attributes) {
if (!attributes.hasOwnProperty(name)) continue;
if (!map.hasOwnProperty(name)) {
mesh.addVertexAttribute(name, attributes[name].itemSize);
if (attributes[name].type !== "Float32Array") {
this._notifyFailure("Unsupported vertex attribute data type!");
}
}
}
var stride = mesh.getVertexStride(0);
var data = new Float32Array(numVertices * stride);
for (name in attributes) {
if (!attributes.hasOwnProperty(name)) continue;
var attrib = attributes[name];
var mappedName = map[name] || name;
var def = mesh.getVertexAttributeByName(mappedName);
var itemSize = attrib.itemSize;
var j = 0;
var len = attrib.array.length;
var offset = def.offset;
var flip = false;
if (name === "position" || name === "normal" || name === "tangent") {
flip = true;
}
while (j < len) {
for (var i = 0; i < itemSize; ++i)
data[offset + i] = attrib.array[j++];
if (flip) {
var z = data[offset + 1];
var y = data[offset + 2];
data[offset + 1] = y;
data[offset + 2] = z;
}
offset += stride;
}
}
mesh.setVertexData(data, 0);
};
THREEBufferGeometry.prototype.parseIndices = function(indexData, mesh)
{
var indices;
switch (indexData.type) {
case "Uint16Array":
indices = new Uint16Array(indexData.array);
break;
case "Uint32Array":
indices = new Uint32Array(indexData.array);
break;
default:
this._notifyFailure("Unsupported index type " + indexData.type);
}
mesh.setIndexData(indices);
};
// could we make things switchable based on a config file, so people can generate a file with only the importers they
exports.ASH = ASH;
exports.GLTF = GLTF;
exports.GLTFData = GLTFData;
exports.OBJ = OBJ;
exports.MTL = MTL;
exports.THREEBufferGeometry = THREEBufferGeometry;
Object.defineProperty(exports, '__esModule', { value: true });
})));
|
import { expect } from 'chai';
import request from '../src/fetch-request';
/* eslint func-names: 0 */
/* eslint prefer-arrow-callback: 0 */
describe('fetch-request', function () {
it('(server) should accept json response', function () {
this.timeout(10000);
const test = request({ url: 'https://o.hahoo.cn/test.json' })
.then(function (res) {
expect(res.body).to.eql({ foo: 'bar' });
});
return test;
});
});
|
/**
* @tag controllers, home
* Displays a table of files. Lets the user
* ["filesController.prototype.form submit" create],
* ["filesController.prototype..edit click" edit],
* or ["filesController.prototype..destroy click" destroy] files.
*/
jQuery.Controller.extend('editorController',
/* @Static */
{
onDocument: true,
Helpers: {
}
},
/* @Prototype */
{
editor: null,
aceUrl: "/~js/resources/ace/production.js",
url: null,
fileName: null,
data: null,
'open.text.* subscribe': function (event, data) {
this.data = {
url: $(data).attr('href'),
mime: $(data).attr('mime')
}
if (!$('#editor').length) {
$('#files-content').html(
$(document.createElement('div')).attr('id','editor')
);
}
if(!window['ace']) {
Loader.script(this.aceUrl, this.callback('loadFile'),
{'data-ace-base': '/~js/resources/ace'}
);
}
else {
this.loadFile()
}
},
loadFile: function() {
$.ajax({
url: this.data['url'],
success: this.callback(function(data){
$('#editor').text(data)
this.showEditor()
})
});
},
showEditor: function() {
this.editor = ace.edit('editor')
// Based on the Mime-Type decide what mode to set
var mode = null;
var extension = files.extension(this.data['url'])
switch(extension.toLowerCase()) {
case 'c':
case 'cpp':
mode = "ace/mode/c_cpp"
break;
case 'css':
mode = "ace/mode/css"
break;
case 'htm':
case 'html':
mode = "ace/mode/html"
break;
case 'js':
mode = "ace/mode/javascript"
break;
case 'java':
mode = "ace/mode/java"
break;
case 'php3':
case 'phtml':
case 'php':
mode = "ace/mode/php"
break;
case 'py':
mode = "ace/mode/python"
break;
case 'sh':
mode = "ace/mode/sh"
break;
case 'sql':
mode = "ace/mode/sql"
break;
case 'xml':
mode = "ace/mode/xml"
break;
default:
break;
}
if (mode) {
var Mode = require(mode).Mode;
this.editor.getSession().setMode(new Mode());
}
this.fileName = $('.breadcrumb .current').text();
this.editor.getSession().on('change', this.callback(function() {
$('.breadcrumb .current').text('* '+this.fileName)
}))
var commands = this.editor.commands;
commands.addCommand({
name: "save",
bindKey: {
win: "Ctrl-S",
mac: "Command-S",
sender: "editor"
},
exec: this.callback('save')
});
// Fake-Print with custom lookup-sender-match function.
commands.addCommand({
name: "print",
bindKey: {
win: "Ctrl-P",
mac: "Command-P",
sender: function(env, sender, hashId, keyString) {
if (sender == "editor") {
return true;
} else {
alert("Sorry, can only print from the editor");
}
}
},
exec: this.callback('print')
});
},
save: function(event) {
var self = this
var data = this.editor.getSession().getValue();
$('#loader').show();
files.create(this.data['url'], data, true,
function() {
$('#loader').hide();
$('.breadcrumb .current').text(self.fileName)
},
function(xhr, text) {
$('#loader').hide();
alert('Saving Failed! Error: '+xhr.statusText)
});
},
print: function(event, data) {
// @todo: print the data
alert('print')
}
}); |
import React, { Component } from 'react';
import colorPicker from 'utility/colorPicker';
export default class Status extends Component {
render() {
const {status, showBall=true, showText=true} = this.props;
const color = colorPicker.getColorWithStatus(status);
return (
<div className="status">
{
(showBall) && <div className="ball" style={ { borderColor: color } }></div>
}
{
(showText) && <div className="text" style={ { color } }>{ status }</div>
}
</div>
)
}
} |
var cant_fotos = 0;
var cant_razones = 0;
var cant_acciones_recomendaciones = 0;
var cant_compromisos = 0;
var cant_asistentes = 0;
function VerificarCant()
{
if (cant_fotos == 0)
jQuery('#remover_imagen').hide();
if (cant_fotos > 0)
jQuery('#remover_imagen').show();
if (cant_razones == 0)
jQuery('#remover_razon').hide();
if (cant_razones > 0)
jQuery('#remover_razon').show();
if (cant_acciones_recomendaciones == 0)
{
jQuery('#remover_acciones').hide();
jQuery('#agregar_acciones').show();
}
if (cant_acciones_recomendaciones > 0)
{
jQuery('#remover_acciones').show();
jQuery('#agregar_acciones').hide();
}
if (cant_compromisos == 0)
jQuery('#remover_compromiso').hide();
if (cant_compromisos > 0)
jQuery('#remover_compromiso').show();
if (cant_asistentes == 0)
jQuery('#remover_asistente').hide();
if (cant_asistentes > 0)
jQuery('#remover_asistente').show();
}
function Agregar(en, data, cant_respon)
{
if (en == 'imagen')
{
campo = '<div id="imagen_agregada">\n\
<input type="text" class="span5" name="titulo_foto' + cant_fotos + '" placeholder="Indique el titulo" required /><br>\n\
<input type="text" class="span6" name="sub_titulo_foto' + cant_fotos + '" placeholder="Indique el sub-titulo" /><br>\n\
<input type="file" name="foto' + cant_fotos + '" accept="image/png, image/gif, image/jpeg, image/jpg" required>\n\
</div>';
jQuery('#imagenes').append(campo);
}
if (en == 'razon')
{
campo = '<div id="razon_agregada">\n\
<input type="text" class="span3" name="razon' + cant_razones + '" data-provide="typeahead" data-items="3" data-source=[' + data + '] autocomplete="off" placeholder="Indique razón" required />\n\
<input type="number" class="span1" name="mva_razon' + cant_razones + '" placeholder="Cant" required/> MVAmin\n\
</div>';
jQuery('#razones').append(campo);
}
if (en == 'acciones')
{
campo = '<div id="accion_agregada">\n\
<textarea name="acciones" class="input-block-level" rows="3" placeholder="Indique las acciones y recomendaciones" required></textarea>\n\
</div>';
jQuery('#acciones').append(campo);
}
if (en == 'compromiso')
{
var select = ' ';
for (var i = 1; i <= cant_respon; i++)
{
select = select + '<select class="span3" name="responsable_compromiso' + cant_compromisos + i + '" required><option></option>' + data + '</select> ';
}
campo = '<div id="compromiso_agregado">\n\
<small><b>Duración estimada del compromiso:</b></small>\n\
<br><input name="f_duracion_estimada_comp' + cant_compromisos + '" type="datetime-local" required />\n\
<textarea name="compromiso' + cant_compromisos + '" class="input-block-level" rows="3" placeholder="Indique el compromiso y luego los responsables" required></textarea> '
+ select +
'</div>';
jQuery('#compromisos').append(campo);
}
if (en == 'asistente')
{
campo = '<div id="asistente_agregado">\n\
<input type="number" class="span2" name="ci_personal' + cant_asistentes + '" data-provide="typeahead" data-items="4" data-source=[' + data + '] autocomplete="off" placeholder="Indique Cédula ' + cant_asistentes + '" required />\n\
</div>';
jQuery('#asistentes').append(campo);
}
}
jQuery('document').ready(function()
{
cant_fotos = jQuery('#cant_fotos').val();
cant_razones = jQuery('#cant_razones').val();
cant_acciones_recomendaciones = jQuery('#cant_acciones').val();
cant_compromisos = jQuery('#cant_compromisos').val();
cant_asistentes = jQuery('#cant_asistentes').val();
VerificarCant();
jQuery('#agregar_imagen').click(function()
{
cant_fotos++;
Agregar('imagen');
VerificarCant();
return false;
});
jQuery('#remover_imagen').click(function()
{
cant_fotos--;
jQuery('#imagen_agregada:last-child').remove();
VerificarCant();
return false;
});
jQuery('#agregar_razon').click(function()
{
$.ajax({
type: "POST",
url: "../../../razones_mvamin",
data: {},
success: function(respuesta) {
if (respuesta)
{
cant_razones++;
Agregar('razon', respuesta);
VerificarCant();
}
}
});
return false;
});
jQuery('#remover_razon').click(function()
{
cant_razones--;
jQuery('#razon_agregada:last-child').remove();
VerificarCant();
return false;
});
jQuery('#agregar_acciones').click(function()
{
Agregar('acciones');
jQuery('#agregar_acciones').hide();
jQuery('#remover_acciones').show();
return false;
});
jQuery('#remover_acciones').click(function()
{
jQuery('#accion_agregada:last-child').remove();
jQuery('#agregar_acciones').show();
jQuery('#remover_acciones').hide();
return false;
});
jQuery('#agregar_compromiso').click(function()
{
var cant = prompt('Ingrese la cantidad de responsables para el compromiso:', 1);
if (!isNaN(cant) && cant != null && cant > 0)
{
$.ajax({
type: "POST",
url: "../../../unidad_equipo",
data: {},
success: function(respuesta) {
if (respuesta)
{
cant_compromisos++;
Agregar('compromiso', respuesta, cant);
VerificarCant();
}
}
});
}
else if (isNaN(cant))
alert('Error:: No introdujo un valor númerico');
else if (cant == 0)
alert('Error:: Debe introducir al menos un responsable');
return false;
});
jQuery('#remover_compromiso').click(function()
{
cant_compromisos--;
jQuery('#compromiso_agregado:last-child').remove();
VerificarCant();
return false;
});
jQuery('#agregar_asistente').click(function()
{
$.ajax({
type: "POST",
url: "../personal",
data: {},
success: function(respuesta) {
if (respuesta)
{
cant_asistentes++;
Agregar('asistente', respuesta);
VerificarCant();
}
}
});
return false;
});
jQuery('#remover_asistente').click(function()
{
cant_asistentes--;
jQuery('#asistente_agregado:last-child').remove();
VerificarCant();
return false;
});
jQuery('#guardar_desarrollo_evento').submit(function()
{
if (confirm("¿Desea continuar con el proceso de guardado?")) {
return true;
}
return false;
});
jQuery('#cancelar_proceso').click(function()
{
if (confirm("¿Desea CANCELAR el proceso de desarrollo?")) {
return true;
}
return false;
});
jQuery('#guardar_minuta').submit(function()
{
if (cant_asistentes > 0)
{
if (confirm("¿Desea continuar con el proceso de guardado?"))
return true;
}
else
alert('Error:: No agregó ningún asistente.');
return false;
});
jQuery('#terminar_minuta').click(function()
{
if (confirm("Al aceptar se terminará con el proceso de edición de la minuta. ¿Desea continuar?"))
return true;
return false;
})
});
|
import test from 'ava';
import promisify from './';
import Firebase from 'firebase';
Firebase.goOffline();
promisify(Firebase.prototype, true);
function baseRef() {
return new Firebase('https://test.firebaseio.test');
}
test('async methods', async t => {
t.plan(15);
var ref = baseRef();
ref.set(null);
ref.child('a').setWithPriority('b', 3);
t.ok(await ref.child('a').exists() === true);
t.ok(await ref.child('b').exists() === false);
t.same(await ref.val(), {a: 'b'});
t.ok(await ref.child('a').val() === 'b');
t.ok(await ref.hasChild('a') === true);
t.ok(await ref.hasChild('b') === false);
t.ok(await ref.hasChildren() === true);
t.ok(await ref.child('a').hasChildren() === false);
t.ok(await ref.numChildren() === 1);
t.ok(await ref.child('a').numChildren() === 0);
t.ok(await ref.getPriority() === null);
t.ok(await ref.child('a').getPriority() === 3);
t.same(await ref.exportVal(), {a: {'.value': 'b', '.priority': 3}});
t.same((await ref.snap()).exportVal(), {a: {'.value': 'b', '.priority': 3}});
t.same(await ref.child('a').exportVal(), {'.value': 'b', '.priority': 3});
});
test('sync methods', t => {
t.plan(15);
var ref = baseRef();
ref.set(null);
ref.child('a').setWithPriority('b', 3);
t.ok(ref.child('a').existsSync() === true);
t.ok(ref.child('b').existsSync() === false);
t.same(ref.valSync(), {a: 'b'});
t.ok(ref.child('a').valSync() === 'b');
t.ok(ref.hasChildSync('a') === true);
t.ok(ref.hasChildSync('b') === false);
t.ok(ref.hasChildrenSync() === true);
t.ok(ref.child('a').hasChildrenSync() === false);
t.ok(ref.numChildrenSync() === 1);
t.ok(ref.child('a').numChildrenSync() === 0);
t.ok(ref.getPrioritySync() === null);
t.ok(ref.child('a').getPrioritySync() === 3);
t.same(ref.exportValSync(), {a: {'.value': 'b', '.priority': 3}});
t.same(ref.snapSync().exportVal(), {a: {'.value': 'b', '.priority': 3}});
t.same(ref.child('a').exportValSync(), {'.value': 'b', '.priority': 3});
});
|
/*******************************
* 名称:首页
* 作者:rubbish.boy@163.com
*******************************
*/
//获取应用实例
var app = getApp()
var config={
//页面的初始数据
data: {
title: '台州速腾网络小程序',
userInfo: {},
session_id:'',
requestlock:true,
inputShowed: false,
inputVal: "",
domainName:app.globalData.domainName,
imagePath:app.globalData.imagePath,
totals : 0,
totals_title :"总数",
first_page :1,//首页
prev_page :1,//上一页
current_page :1,//当前页
next_page :1,//下一页
last_page :1,//尾页
listdata :{},//列表数据
page :1
},
//生命周期函数--监听页面加载
onLoad: function () {
//调用应用实例的方法获取全局数据
/**/
var that = this
app.getUserInfo(function(userInfo){
that.setData({
userInfo:userInfo
})
//异步获取缓存session_id
wx.getStorage({
key: 'session_id',
success: function(res) {
that.setData({
session_id:res.data
})
that.get_list()
}
})
})
},
//生命周期函数--监听页面初次渲染完成
onReady: function() {
// Do something when page ready.
},
//生命周期函数--监听页面显示
onShow: function() {
// Do something when page show.
if(this.data.requestlock==false)
{
this.get_list()
}
else
{
this.setData({
requestlock:false
})
}
},
//生命周期函数--监听页面隐藏
onHide: function() {
// Do something when page hide.
},
//生命周期函数--监听页面卸载
onUnload: function() {
// Do something when page close.
},
//页面相关事件处理函数--监听用户下拉动作
onPullDownRefresh: function() {
// Do something when pull down.
this.get_list('onPullDownRefresh')
},
//页面上拉触底事件的处理函数
onReachBottom: function() {
// Do something when page reach bottom.
},
//导航处理函数
bindNavigateTo: function(action)
{
app.bindNavigateTo(action.target.dataset.action,action.target.dataset.params)
},
//页面打开导航处理函数
bindRedirectTo: function(action)
{
app.bindRedirectTo(action.target.dataset.action,action.target.dataset.params)
},
//跳转到 tabBar 页面
bindSwitchTo: function(action)
{
app.bindSwitchTo(action.target.dataset.action)
},
get_list: function(actionway="")
{
var that = this
var post_data={token:app.globalData.token,session_id:that.data.session_id,search_keyword:that.data.inputVal,page:that.data.page}
app.action_loading()
app.func.http_request_action(app.globalData.domainName+app.globalData.api.api_product,post_data,function(resback){
if(resback.status==1)
{
app.action_loading_hidden()
let totals=Math.ceil(resback.resource.total/resback.resource.per_page)
let current_page=resback.resource.current_page
let totals_title=resback.resource.total+'条'
let last_page=resback.resource.last_page
that.setData({
listdata:resback.resource.data,
current_page:current_page,
totals_title:totals_title,
last_page:last_page
})
//分页限制3组
if(totals<=3)
{
that.setData({
totals:totals
})
}
else
{
that.setData({
totals:[current_page+1,current_page,current_page+1]
})
}
//下一页数据
if(current_page==totals)
{
that.setData({
next_page:totals
})
}
else
{
that.setData({
next_page:resback.resource.current_page+1
})
}
//上一页数据
if(current_page==1)
{
that.setData({
prev_page:1
})
}
else
{
that.setData({
prev_page:current_page-1
})
}
if(actionway=="onPullDownRefresh")
{
setTimeout(function(){
wx.stopPullDownRefresh()
},800)
}
}
else
{
app.action_loading_hidden()
var msgdata=new Object
msgdata.totype=3
msgdata.msg=resback.info
app.func.showToast_default(msgdata)
//console.log('获取用户登录态失败!' + resback.info);
}
})
},
//点击页码获取列表数据
btnClick: function(action)
{
if(action.target.dataset.page != this.current_page)
{
this.setData({
page:action.target.dataset.page
})
this.get_list();
}
console.log(action.target.dataset.page);
},
//搜索条相关动作函数
showInput: function () {
this.setData({
inputShowed: true
});
},
hideInput: function () {
this.setData({
inputVal: "",
inputShowed: false
});
this.get_list();
},
clearInput: function () {
this.setData({
inputVal: ""
});
this.get_list();
},
inputTyping: function (e) {
this.setData({
inputVal: e.detail.value,
page:1
});
},
//单个添加购物车
shopping_cart_add:function(arr)
{
var that = this
var post_data={token:app.globalData.token,session_id:that.data.session_id,formdata:arr.target.dataset}
app.func.http_request_action(app.globalData.domainName+app.globalData.api.api_shoppingcart_add,post_data,function(resback){
if(resback.status==1)
{
var msgdata=new Object
msgdata.totype=1
msgdata.msg=resback.info
app.func.showToast_success(msgdata)
}
else
{
var msgdata=new Object
msgdata.totype=1
msgdata.msg=resback.info
app.func.showToast_default(msgdata)
}
})
},
}
Page(config)
|
function runTests (tests) {
var testGroups = [
'general',
'hyphens',
'punctuation',
'quotes',
'subtitles',
'technical',
'versus',
'miscellaneous'
]
testGroups.forEach(function (groupName) {
tests[groupName].forEach(function (test) {
QUnit.test(groupName, function (assert) {
assert.equal(test.input.toTitleCase(), test.expect)
})
})
})
}
/* Distinguish between browser and node */
if (typeof window === 'undefined') {
require('../to-title-case.js')
var QUnit = require('qunit')
var tests = require('./tests.json')
runTests(tests)
} else {
/* globals jQuery */
jQuery.getJSON('tests.json').done(runTests)
}
|
function PrimeCheck(args){
var n = args[0];
var isPrime = true;
if (n < 0) {
console.log(false);
}
else{
for (var i = 2; i <= n/2; i++) {
if (n % i === 0) {
isPrime = false;
break;
}
}
console.log(isPrime);
}
}
PrimeCheck([1]);
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.8/esri/copyright.txt for details.
//>>built
define(["require","exports","../../webgl-engine/lib/Util"],function(p,m,n){Object.defineProperty(m,"__esModule",{value:!0});m.computeSignedDistancefieldCicle=function(a,d){var g=new Uint8Array(4*a*a),h=a/2-.5;d/=2;for(var e=0;e<a;e++)for(var f=0;f<a;f++){var c=f+a*e,b=f-h,l=e-h,b=Math.sqrt(b*b+l*l)-d,b=b/a+.5;n.packFloatRGBA(b,g,4*c)}return g};m.computeSignedDistancefieldSquare=function(a,d,g){g&&(d/=Math.SQRT2);for(var h=new Uint8Array(4*a*a),e=0;e<a;e++)for(var f=0;f<a;f++){var c=f-.5*(a-.5),b=
e-.5*(a-.5),l=e*a+f;if(g)var k=(c+b)/Math.SQRT2,b=(b-c)/Math.SQRT2,c=k;c=Math.max(Math.abs(c),Math.abs(b))-.5*d;c=c/a+.5;n.packFloatRGBA(c,h,4*l)}return h};m.computeSignedDistancefieldCrossAndX=function(a,d,g){g&&(d*=Math.SQRT2);d*=.5;for(var h=new Uint8Array(4*a*a),e=0;e<a;e++)for(var f=0;f<a;f++){var c=f-.5*a,b=e-.5*a,l=e*a+f;if(g)var k=(c+b)/Math.SQRT2,b=(b-c)/Math.SQRT2,c=k;k=void 0;c=Math.abs(c);b=Math.abs(b);k=c>b?c>d?Math.sqrt((c-d)*(c-d)+b*b):b:b>d?Math.sqrt(c*c+(b-d)*(b-d)):c;k=k/a+.5;n.packFloatRGBA(k,
h,4*l)}return h}}); |
// http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
(function () {
'use strict';
var lastTime = 0;
(['webkit', 'moz']).forEach(function (key) {
window.requestAnimationFrame = window.requestAnimationFrame || window[key + 'RequestAnimationFrame'] || null;
window.cancelAnimationFrame = window.cancelAnimationFrame || window[key + 'CancelAnimationFrame'] || null;
});
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function (callback) {
var currTime = Date.now(),
timeToCall = Math.max(0, 16 - (currTime - lastTime)),
id = window.setTimeout(function () { callback(currTime + timeToCall); }, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function (id) {
window.clearTimeout(id);
};
}
}()); |
/* @flow */
import type { IncomingMessageType, OutgoingMessageType } from "wild-yak/dist/types";
export type HttpContext<TBody> = { query: { [key: string]: string }, body: TBody, session: Object }
|
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import {
GET_REPOSITORY_CONTENTS,
GET_REPOSITORY_FILE,
GET_REPOSITORY_COMMITS,
GET_COMMIT,
GET_COMMIT_DIFF,
GET_REPOSITORY_README,
GET_REPOSITORY_LABELS,
} from 'repository/repository.type';
import {
getContents,
getRepositoryFile,
getCommits,
getCommitFromUrl,
getCommitDiffFromUrl,
getReadMe,
getLabels,
getCommitDetails,
} from 'repository/repository.action';
import { fetchDiff, fetchReadMe, v3 } from 'api';
jest.mock('api', () => ({
v3: {
getJson: jest.fn(),
getRaw: jest.fn(),
},
fetchDiff: jest.fn(),
fetchReadMe: jest.fn(),
}));
const store = configureStore([thunk])({ auth: { accessToken: 'ABCXYZ' } });
beforeEach(() => {
jest.clearAllMocks();
});
afterEach(() => {
store.clearActions();
});
describe('getContents()', () => {
it('should return a success response', async () => {
const level = 'some-level';
const expectedData = { key: 'value ' };
v3.getJson.mockResolvedValue(expectedData);
await store.dispatch(getContents('', level));
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_CONTENTS.PENDING,
});
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_CONTENTS.SUCCESS,
results: expectedData,
level,
});
expect(store.getActions()).not.toContainEqual(
expect.objectContaining({
type: GET_REPOSITORY_CONTENTS.ERROR,
})
);
});
it('should return an error response', async () => {
const expectedData = 'ERROR';
v3.getJson.mockRejectedValue(expectedData);
await store.dispatch(getContents());
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_CONTENTS.PENDING,
});
expect(store.getActions()).not.toContainEqual(
expect.objectContaining({
type: GET_REPOSITORY_CONTENTS.SUCCESS,
})
);
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_CONTENTS.ERROR,
payload: expectedData,
});
});
});
describe('getRepositoryFile()', () => {
it('should return a success response', async () => {
const expectedData = { key: 'value ' };
v3.getRaw.mockResolvedValue(expectedData);
await store.dispatch(getRepositoryFile(''));
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_FILE.PENDING,
});
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_FILE.SUCCESS,
payload: expectedData,
});
expect(store.getActions()).not.toContainEqual(
expect.objectContaining({
type: GET_REPOSITORY_FILE.ERROR,
})
);
});
it('should return an error response', async () => {
const expectedData = 'ERROR';
v3.getRaw.mockRejectedValue(expectedData);
await store.dispatch(getRepositoryFile());
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_FILE.PENDING,
});
expect(store.getActions()).not.toContainEqual(
expect.objectContaining({
type: GET_REPOSITORY_FILE.SUCCESS,
})
);
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_FILE.ERROR,
payload: expectedData,
});
});
});
describe('getCommits()', () => {
it('should return a success response', async () => {
const expectedData = { key: 'value ' };
v3.getJson.mockResolvedValue(expectedData);
await store.dispatch(getCommits(''));
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_COMMITS.PENDING,
});
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_COMMITS.SUCCESS,
payload: expectedData,
});
expect(store.getActions()).not.toContainEqual(
expect.objectContaining({
type: GET_REPOSITORY_COMMITS.ERROR,
})
);
});
it('should return an error response', async () => {
const expectedData = 'ERROR';
v3.getJson.mockRejectedValue(expectedData);
await store.dispatch(getCommits());
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_COMMITS.PENDING,
});
expect(store.getActions()).not.toContainEqual(
expect.objectContaining({
type: GET_REPOSITORY_COMMITS.SUCCESS,
})
);
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_COMMITS.ERROR,
payload: expectedData,
});
});
});
describe('getCommitFromUrl()', () => {
it('should return a success response', async () => {
const expectedData = { key: 'value ' };
v3.getJson.mockResolvedValue(expectedData);
await store.dispatch(getCommitFromUrl(''));
expect(store.getActions()).toContainEqual({
type: GET_COMMIT.PENDING,
});
expect(store.getActions()).toContainEqual({
type: GET_COMMIT.SUCCESS,
payload: expectedData,
});
expect(store.getActions()).not.toContainEqual(
expect.objectContaining({
type: GET_COMMIT.ERROR,
})
);
});
it('should return an error response', async () => {
const expectedData = 'ERROR';
v3.getJson.mockRejectedValue(expectedData);
await store.dispatch(getCommitFromUrl());
expect(store.getActions()).toContainEqual({
type: GET_COMMIT.PENDING,
});
expect(store.getActions()).not.toContainEqual(
expect.objectContaining({
type: GET_COMMIT.SUCCESS,
})
);
expect(store.getActions()).toContainEqual({
type: GET_COMMIT.ERROR,
payload: expectedData,
});
});
});
describe('getCommitDiffFromUrl()', () => {
it('should return a success response', async () => {
const expectedData = { key: 'value ' };
fetchDiff.mockResolvedValue(expectedData);
await store.dispatch(getCommitDiffFromUrl(''));
expect(store.getActions()).toContainEqual({
type: GET_COMMIT_DIFF.PENDING,
});
expect(store.getActions()).toContainEqual({
type: GET_COMMIT_DIFF.SUCCESS,
payload: expectedData,
});
expect(store.getActions()).not.toContainEqual(
expect.objectContaining({
type: GET_COMMIT_DIFF.ERROR,
})
);
});
it('should return an error response', async () => {
const expectedData = 'ERROR';
fetchDiff.mockRejectedValue(expectedData);
await store.dispatch(getCommitDiffFromUrl());
expect(store.getActions()).toContainEqual({
type: GET_COMMIT_DIFF.PENDING,
});
expect(store.getActions()).not.toContainEqual(
expect.objectContaining({
type: GET_COMMIT_DIFF.SUCCESS,
})
);
expect(store.getActions()).toContainEqual({
type: GET_COMMIT_DIFF.ERROR,
payload: expectedData,
});
});
});
describe('getReadMe()', () => {
it('should return a success response', async () => {
const expectedData = { key: 'value ' };
fetchReadMe.mockResolvedValue(expectedData);
await store.dispatch(getReadMe(''));
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_README.PENDING,
});
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_README.SUCCESS,
payload: expectedData,
});
expect(store.getActions()).not.toContainEqual(
expect.objectContaining({
type: GET_REPOSITORY_README.ERROR,
})
);
});
it('should return an error response', async () => {
const expectedData = 'ERROR';
fetchReadMe.mockRejectedValue(expectedData);
await store.dispatch(getReadMe());
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_README.PENDING,
});
expect(store.getActions()).not.toContainEqual(
expect.objectContaining({
type: GET_REPOSITORY_README.SUCCESS,
})
);
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_README.ERROR,
payload: expectedData,
});
});
});
describe('getLabels()', () => {
it('should return a success response', async () => {
const expectedData = { key: 'value ' };
v3.getJson.mockResolvedValue(expectedData);
await store.dispatch(getLabels(''));
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_LABELS.PENDING,
});
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_LABELS.SUCCESS,
payload: expectedData,
});
expect(store.getActions()).not.toContainEqual(
expect.objectContaining({
type: GET_REPOSITORY_LABELS.ERROR,
})
);
});
it('should return an error response', async () => {
const expectedData = 'ERROR';
v3.getJson.mockRejectedValue(expectedData);
await store.dispatch(getLabels());
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_LABELS.PENDING,
});
expect(store.getActions()).not.toContainEqual(
expect.objectContaining({
type: GET_REPOSITORY_LABELS.SUCCESS,
})
);
expect(store.getActions()).toContainEqual({
type: GET_REPOSITORY_LABELS.ERROR,
payload: expectedData,
});
});
});
describe('getCommitDetails()', () => {
it('should get commit and commit diff', async () => {
const commit = { url: 'url.com' };
v3.getJson.mockResolvedValue({});
await store.dispatch(getCommitDetails(commit));
expect(v3.getJson).toHaveBeenCalledWith(commit.url, expect.any(String));
expect(fetchDiff).toHaveBeenCalledWith(commit.url, expect.any(String));
});
it('should get commit and commit diff when commit has nested commit', async () => {
const nestedCommit = { commit: { url: 'nestedUrl.dev' } };
v3.getJson.mockResolvedValue({});
await store.dispatch(getCommitDetails(nestedCommit));
expect(v3.getJson).toHaveBeenCalledWith(nestedCommit.commit.url, expect.any(String));
expect(fetchDiff).toHaveBeenCalledWith(nestedCommit.commit.url, expect.any(String));
});
}); |
var cal_timezone = ""
//=============OAtuh 2.0=============
function handleClientLoad() {
gapi.client.setApiKey(apiKey);
window.setTimeout(checkAuth, 1);
}
function checkAuth() {
gapi.auth.authorize({
client_id: clientId,
scope: scopes,
immediate: true
}, handleAuthResult);
}
function handleAuthResult(authResult) {
var authorizeButton = document.getElementById('authorize-button');
var new_event = document.getElementById('new_event')
if (authResult && !authResult.error) {
authorizeButton.style.visibility = 'hidden';
new_event.style.visibility = ''
$('#auth-dialog').modal('hide');
makeApiCall();
} else {
authorizeButton.style.visibility = '';
authorizeButton.onclick = handleAuthClick;
new_event.style.visibility = 'hidden'
$('#auth-dialog').modal('show');
}
}
function handleAuthClick(event) {
gapi.auth.authorize({
client_id: clientId,
scope: scopes,
immediate: false
}, handleAuthResult);
return false;
}
//=============OAtuh 2.0=============
//=============執行 Api 呼叫=============
function makeApiCall() {
gapi.client.load('calendar', 'v3', function () {
var request = gapi.client.calendar.events.list({
"calendarId": calendarId,
"maxResults": maxResults,
"orderBy": "startTime",
"singleEvents": "true",
"timeZone": "UTC"
});
request.execute(function (resp) {
$("#name")
.text(resp.summary);
$("#title")
.text(resp.summary);
$("#timezone")
.text(resp.timeZone);
cal_timezone = resp.timeZone
var cal_out = ""
for (var i = resp.items.length - 1; i >= 0; i--) {
var allday = "0"
if (resp.items[i].start.date) {
allday = "1"
var sto = resp.items[i].start.date
var st = new Date(resp.items[i].start.date + "T00:00:00" + moment().tz(resp.timeZone).format('Z'));
var starttime = st.getFullYear() + "-" + (st.getMonth() + 1) + "-" + st.getDate() + " " + st.getHours() + ":" + st.getMinutes()
var eto = resp.items[i].end.date
var et = new Date(resp.items[i].end.date + "T00:00:00" + moment().tz(resp.timeZone).format('Z'));
var endtime = et.getFullYear() + "-" + (et.getMonth() + 1) + "-" + et.getDate() + " " + et.getHours() + ":" + et.getMinutes()
} else {
var sto = resp.items[i].start.dateTime
var st = new Date(resp.items[i].start.dateTime);
var starttime = st.getFullYear() + "-" + (st.getMonth() + 1) + "-" + st.getDate() + " " + st.getHours() + ":" + st.getMinutes()
var eto = resp.items[i].end.dateTime
var et = new Date(resp.items[i].end.dateTime);
var endtime = et.getFullYear() + "-" + (et.getMonth() + 1) + "-" + et.getDate() + " " + et.getHours() + ":" + et.getMinutes()
}
cal_out = cal_out + "<tr>"
cal_out = cal_out + "<td>" + resp.items[i].id + "</td>"
cal_out = cal_out + "<td>" + resp.items[i].description + "</td>"
cal_out = cal_out + "<td>" + allday + "</td>"
cal_out = cal_out + "<td>" + starttime + "</td>"
cal_out = cal_out + "<td>" + sto + "</td>"
cal_out = cal_out + "<td>" + endtime + "</td>"
cal_out = cal_out + "<td>" + eto + "</td>"
cal_out = cal_out + "<td>" + diffTime(st, et) + "</td>"
cal_out = cal_out + "<td>" + diffTime(new Date(), st) + "</td>"
if (resp.items[i].description != undefined){
cal_out = cal_out + '<td><a onclick="detailshow(\'' + encodeURI(newline_en(resp.items[i].description)) + '\')">' + resp.items[i].summary + '</a></td>'
}else{
cal_out = cal_out + '<td>' + resp.items[i].summary + '</td>'
}
cal_out = cal_out + "<td>" + '<a onclick="edit_event(' + (resp.items.length - i) + ')"><span class="glyphicon glyphicon-pencil"></span></a>' + " " + '<a onclick="del_event(\'' + resp.items[i].id + '\')"><span class="glyphicon glyphicon-trash"></span></a>' + "</td>"
cal_out = cal_out + "</tr>"
}
$('#caltable')
.append(cal_out)
$('#caltable tr td:nth-child(1)').css('display','none');
$('#caltable tr td:nth-child(2)').css('display','none');
$('#caltable tr td:nth-child(3)').css('display','none');
$('#caltable tr td:nth-child(5)').css('display','none');
$('#caltable tr td:nth-child(7)').css('display','none');
switchLang(lang)
});
});
}
//=============執行 Api 呼叫=============
function add_new_event(){
$('#ned-cancel')[0].disabled="disabled"
$('#ned-submit')[0].disabled="disabled"
var summary = $('#ned-summary').val()
var allday = $("#ned-allday")[0].checked
var start_date = $('#ned-SD').val()
var start_time = $('#ned-ST').val()
var end_date = $('#ned-ED').val()
var end_time = $('#ned-ET').val()
var detail = $('#ned-detail').val()
var start_datetime = ""
var end_datetime = ""
var needretrun = 0
if (!allday){
start_datetime = start_date + "T" + start_time + ":00" + moment().tz(cal_timezone).format('Z')
end_datetime = end_date + "T" + end_time + ":00" + moment().tz(cal_timezone).format('Z')
if (diffTime(start_datetime,end_datetime)=="Over"){
needretrun = 1
}
}
if (summary==""){
needretrun = 1
}
if (start_date==""){
needretrun = 1
}
if (end_date==""){
needretrun = 1
}
if (!allday && start_time==""){
needretrun = 1
}
if (!allday && end_time==""){
needretrun = 1
}
if (diffTime(start_date,end_date)=="Over"){
needretrun = 1
}
if (needretrun){
$('#ned-cancel')[0].disabled=""
$('#ned-submit')[0].disabled=""
return false
}else{
if (allday){
var req_body = {
'start': {
'date': start_date
},
'end': {
'date': end_date
},
'summary': summary,
'description': detail
}
}else{
var req_body = {
'start': {
'dateTime': start_datetime
},
'end': {
'dateTime': end_datetime
},
'summary': summary,
'description': detail
}
}
gapi.client.load('calendar', 'v3', function () {
var request = gapi.client.calendar.events.insert({
'calendarId': calendarId,
'resource': req_body
});
request.execute(function (resp) {
$('#new_event-dialog').modal('hide');
update_table()
});
});
}
}
function edit_event(row){
var eventid = $('#caltable tr td:nth-child(1)')[(row - 1)].innerHTML
var detail = $('#caltable tr td:nth-child(2)')[(row - 1)].innerHTML
if (detail == "undefined"){
detail = ""
}
var allday = Number($('#caltable tr td:nth-child(3)')[(row - 1)].innerHTML)
var start_datetime = $('#caltable tr td:nth-child(5)')[(row - 1)].innerHTML
var end_datetime = $('#caltable tr td:nth-child(7)')[(row - 1)].innerHTML
var summary = $('#caltable tr td:nth-child(10)')[(row - 1)].innerHTML
start_datetime_as_date = new Date(start_datetime)
end_datetime_as_date = new Date(end_datetime)
$('#editd-summary')[0].value = summary
$('#editd-allday')[0].checked = allday
$('#editd-SD')[0].value = moment(start_datetime_as_date).format('YYYY-MM-DD');
$('#editd-ED')[0].value = moment(end_datetime_as_date).format('YYYY-MM-DD');
if (allday){
$('#editd-ST')[0].style.visibility = "hidden";
$('#editd-ET')[0].style.visibility = "hidden";
}else{
$('#editd-ST')[0].value = moment(start_datetime_as_date).format('hh:mm:ss');
$('#editd-ET')[0].value = moment(end_datetime_as_date).format('hh:mm:ss');
$('#editd-ST')[0].style.visibility = "";
$('#editd-ET')[0].style.visibility = "";
}
$('#editd-detail')[0].value = detail
$('#editd-submit').attr("onclick", 'real_edit_event("' + eventid + '")')
$('#editd-cancel')[0].disabled=""
$('#editd-submit')[0].disabled=""
$('#edit-dialog').modal('show')
}
function real_edit_event(id){
$('#editd-cancel')[0].disabled="disabled"
$('#editd-submit')[0].disabled="disabled"
var summary = $('#editd-summary').val()
var allday = $("#editd-allday")[0].checked
var start_date = $('#editd-SD').val()
var start_time = $('#editd-ST').val()
var end_date = $('#editd-ED').val()
var end_time = $('#editd-ET').val()
var detail = $('#editd-detail').val()
var start_datetime = ""
var end_datetime = ""
var needretrun = 0
if (!allday){
start_datetime = start_date + "T" + (start_time.split(':').length == 2 ? start_time + ":00" : start_time) + moment().tz(cal_timezone).format('Z')
end_datetime = end_date + "T" + (end_time.split(':').length == 2 ? end_time + ":00" : end_time) + moment().tz(cal_timezone).format('Z')
if (diffTime(start_datetime,end_datetime)=="Over"){
needretrun = 1
}
}
if (summary==""){
needretrun = 1
}
if (start_date==""){
needretrun = 1
}
if (end_date==""){
needretrun = 1
}
if (!allday && start_time==""){
needretrun = 1
}
if (!allday && end_time==""){
needretrun = 1
}
if (diffTime(start_date,end_date)=="Over"){
needretrun = 1
}
if (needretrun){
$('#editd-cancel')[0].disabled=""
$('#editd-submit')[0].disabled=""
return false
}else{
if (allday){
var req_body = {
'start': {
'date': start_date
},
'end': {
'date': end_date
},
'summary': summary,
'description': detail
}
}else{
var req_body = {
'start': {
'dateTime': start_datetime
},
'end': {
'dateTime': end_datetime
},
'summary': summary,
'description': detail
}
}
gapi.client.load('calendar', 'v3', function () {
var request = gapi.client.calendar.events.update({
'calendarId': calendarId,
'eventId': id,
'resource': req_body
});
request.execute(function (resp) {
$('#edit-dialog').modal('hide');
update_table()
});
});
}
}
function del_event(id){
$('#delete-dialog-delete').attr("onclick", 'real_del_event("' + id + '")')
$('#delete-dialog').modal('show')
}
function real_del_event(id){
gapi.client.load('calendar', 'v3', function () {
var request = gapi.client.calendar.events.delete({
'calendarId': calendarId,
'eventId': id
});
request.execute(function (resp) {
$('#delete-dialog').modal('hide')
update_table()
});
});
}
function update_table(){
$("#caltable tr").remove();
makeApiCall()
}
$('#new_event-dialog').on('shown.bs.modal', function () {
$('#new_event-form')[0].reset()
$('#ned-summary').focus()
$('#ned-ST')[0].style.visibility="";
$('#ned-ET')[0].style.visibility="";
})
$('#ned-fullday').click(function() {
if ($("#ned-fullday")[0].checked){
$('#ned-ST')[0].style.visibility="hidden";
$('#ned-ET')[0].style.visibility="hidden";
}else{
$('#ned-ST')[0].style.visibility="";
$('#ned-ET')[0].style.visibility="";
}
})
$('#editd-allday').click(function() {
if ($("#editd-allday")[0].checked){
$('#editd-ST')[0].style.visibility="hidden";
$('#editd-ET')[0].style.visibility="hidden";
}else{
$('#editd-ST')[0].style.visibility="";
$('#editd-ET')[0].style.visibility="";
}
})
|
function Block(){
this.number=0;
this.position=function(x,y){
this.x=x;
this.y=y;
this.block.style.marginLeft=x*(this.width+this.offset)+"px";
this.block.style.marginTop=y*(this.height+this.offset)+"px";
};
this.create=function(x,y,stage){
var nwBlock=document.createElement("div");
nwBlock.className="block";
this.block=nwBlock;
this.width=this.height=100;
this.x=x;
this.y=y;
this.offset=7;
this.position(x,y);
stage.appendChild(nwBlock);
};
this.setNumber=function(num){
this.number=num;
this.block.innerHTML=num;
switch(parseInt(this.number)){
case 2:this.block.style.backgroundColor="#3399cc";
this.block.style.color="white";
break;
case 4:this.block.style.backgroundColor="#ff9900";
this.block.style.color="white";
break;
case 8:this.block.style.backgroundColor="#ffcc33";
this.block.style.color="white";
break;
case 16:this.block.style.backgroundColor="#ff6600";
this.block.style.color="white";
break;
case 32:this.block.style.backgroundColor="#009966";
this.block.style.color="white";
break;
case 64:this.block.style.backgroundColor="#33cc99";
this.block.style.color="white";
break;
case 128:this.block.style.backgroundColor="#cc6600";
this.block.style.color="white";
break;
case 256:this.block.style.backgroundColor="#cccc33";
this.block.style.color="white";
break;
case 512:this.block.style.backgroundColor="#663399";
this.block.style.color="white";
break;
case 1024:this.block.style.backgroundColor="#ff6666";
this.block.style.color="white";
break;
case 2048:this.block.style.backgroundColor="#333399";
this.block.style.color="white";
break;
case 4096:this.block.style.backgroundColor="#cc3366";
this.block.style.color="white";
break;
case 8192:this.block.style.backgroundColor="#666666";
this.block.style.color="white";
break;
case 16384:this.block.style.backgroundColor="#996600";
this.block.style.color="white";
break;
case 32768:this.block.style.backgroundColor="#003300";
this.block.style.color="white";
break;
case 65536:this.block.style.backgroundColor="#ccccff";
this.block.style.color="white";
break;
case 131072:this.block.style.backgroundColor="#336666";
this.block.style.color="white";
break;
case 262144:this.block.style.backgroundColor="#cc9966";
this.block.style.color="white";
break;
case 524288:this.block.style.backgroundColor="#996633";
this.block.style.color="white";
break;
}
};
}
module.exports=Block; |
(function () {
'use strict';
var XP = require('expandjs'),
fileParser = require('lol-file-parser');
module.exports = fileParser({
name: 'CacFile',
parse: function (parser, cb) {
cb(null, parser.stringView().join(''));
},
read: function (data, cb) {
var lines = data.split(/\r\n|\n/);
// Remove comments
lines = XP.filter(lines, function (line) {
return !line.match(/^\s*\/\//);
});
lines = lines.join('');
cb(null, JSON.parse(lines));
}
});
}());
|
/*
* d-messaging
* http://github.com/Fxrialab/d-messaging
*
* Copyright (c) 2014 Minh Tran
* Licensed under the MIT license.
*/
'use strict';
exports.awesome = function() {
return 'awesome';
};
|
/**
* Created by Jeng on 2016/1/8.
*/
define(function () {
return ["$scope", "CouponAPI","$modal", "$ugDialog","$stateParams", function($scope, CouponAPI,$modal, $ugDialog,$stateParams){
$scope.readOldCard = function(){
if($scope.pick.couponNo && $scope.pick.password){
//查找卡信息
CouponAPI.readCard({
couponNo:$scope.pick.couponNo,
password:$scope.pick.password
}, function (data) {
if(data.userName == null || data.userName == undefined){
$ugDialog.warn("卡号或者密码错误!");
$scope.pick.couponNo = "";
$scope.pick.password = "";
$("#couponNo").focus();
$("#couponNo").select();
return;
};
$scope.pick.userName = data.userName;
$scope.pick.phoneNumber = data.phoneNumber;
$scope.pick.couponNo = data.couponNo;
$scope.pick.couponPrice = data.couponPrice;
}, function (data) {
$ugDialog.warn(data.data.error);
})
}
}
$scope.readCard = function(){
var strls = "";
var errorno = "";
var BLOCK0_EN = 0x01;//读第一块的(16个字节)
var BLOCK1_EN = 0x02;//读第二块的(16个字节)
var BLOCK2_EN = 0x04;//读第四块的(16个字节)
var EXTERNKEY = 0x10;//用明码认证密码,产品开发完成后,建议把密码放到设备的只写区,然后用该区的密码后台认证,这样谁都不知道密码是多少,需要这方面支持请联系
//指定控制字
var myctrlword=BLOCK0_EN + BLOCK1_EN + BLOCK2_EN + EXTERNKEY;
//指定区号
var myareano = 8; //指定为第8区
//批定密码模式
var authmode = 1; //大于0表示用A密码认证,推荐用A密码认证
//指定序列号,未知卡序列号时可指定为8个0
var mypiccserial="00000000";
//指定密码,以下密码为厂家出厂密码
var mypicckey = "ffffffffffff";
strls=IcCardReader.piccreadex(myctrlword, mypiccserial,myareano,authmode,mypicckey);
errorno = strls.substr(0,4);
switch(errorno)
{
case "ER08":
alert("寻不到卡");
break;
case "ER09":
alert("寻不到卡");
break;
case "ER10":
alert("寻不到卡");
break;
case "ER11":
$ugDialog.alert("密码认证错误");
break;
case "ER12":
$ugDialog.alert("密码认证错误");
break;
case "ER13":
$ugDialog.alert("读卡错误");
break;
case "ER14":
$ugDialog.alert("写卡错误");
break;
case "ER21":
$ugDialog.alert("没找到动态库");
break;
case "ER22":
$ugDialog.alert("动态库或驱动程序异常");
break;
case "ER23":
$ugDialog.alert("读卡器未插上或动态库或驱动程序异常");
break;
case "ER24":
$ugDialog.alert("操作超时,一般是动态库没有反应");
break;
case "ER25":
$ugDialog.alert("发送字数不够");
break;
case "ER26":
$ugDialog.alert("发送的CRC错");
break;
case "ER27":
$ugDialog.alert("接收的字数不够");
break;
case "ER28":
$ugDialog.alert("接收的CRC错");
break;
case "ER29":
$ugDialog.alert("函数输入参数格式错误,请仔细查看" );
break;
default :
//读卡成功,其中ER00表示完全成功,ER01表示完全没读到卡数据,ER02表示仅读该卡的第一块成功,,ER02表示仅读该卡的第一二块成功,这是刷卡太快原因
var e=new RegExp("F","g");
$scope.pick.newCouponNo = strls.substr(14,32).replace(e,"");
$scope.pick.newPassword = strls.substr(46,32).replace(e,"");
IcCardReader.pcdbeep(200);//100表示响100毫秒
break;
}
}
$scope.pickForm = {};
$scope.exchangeCard = function(){
if($scope.pick.couponNo == "" || $scope.pick.couponNo == null || $scope.pick.couponNo == undefined || $scope.pick.newCouponNo == "" || $scope.pick.newCouponNo == null || $scope.pick.newCouponNo == undefined){
$ugDialog.alert("请刷卡");
return;
}
CouponAPI.exchangeCard({
oldCouponNo:$scope.pick.couponNo,
oldPassword:$scope.pick.password,
newCouponNo:$scope.pick.newCouponNo,
newPassword:$scope.pick.newPassword
},function(){
$ugDialog.alert("换卡成功");
$scope.pick = {}
}, function(data){
IcCardReader.pcdbeep(200);//100表示响100毫秒
$ugDialog.warn(data.data.error);
})
}
var initialize = function(){
$scope.pick = {};
$("#couponNo").focus();
$("#couponNo").select();
}
initialize();
}];
}); |
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'flash', 'ms', {
access: 'Script Access', // MISSING
accessAlways: 'Always', // MISSING
accessNever: 'Never', // MISSING
accessSameDomain: 'Same domain', // MISSING
alignAbsBottom: 'Bawah Mutlak',
alignAbsMiddle: 'Pertengahan Mutlak',
alignBaseline: 'Garis Dasar',
alignTextTop: 'Atas Text',
bgcolor: 'Warna Latarbelakang',
chkFull: 'Allow Fullscreen', // MISSING
chkLoop: 'Loop', // MISSING
chkMenu: 'Enable Flash Menu', // MISSING
chkPlay: 'Auto Play', // MISSING
flashvars: 'Variables for Flash', // MISSING
hSpace: 'Ruang Melintang',
properties: 'Flash Properties', // MISSING
propertiesTab: 'Properties', // MISSING
quality: 'Quality', // MISSING
qualityAutoHigh: 'Auto High', // MISSING
qualityAutoLow: 'Auto Low', // MISSING
qualityBest: 'Best', // MISSING
qualityHigh: 'High', // MISSING
qualityLow: 'Low', // MISSING
qualityMedium: 'Medium', // MISSING
scale: 'Scale', // MISSING
scaleAll: 'Show all', // MISSING
scaleFit: 'Exact Fit', // MISSING
scaleNoBorder: 'No Border', // MISSING
title: 'Flash Properties', // MISSING
vSpace: 'Ruang Menegak',
validateHSpace: 'HSpace must be a number.', // MISSING
validateSrc: 'Sila taip sambungan URL',
validateVSpace: 'VSpace must be a number.', // MISSING
windowMode: 'Window mode', // MISSING
windowModeOpaque: 'Opaque', // MISSING
windowModeTransparent: 'Transparent', // MISSING
windowModeWindow: 'Window' // MISSING
} );
|
/*! gm-google-map - v0.0.13 - 2017-07-02
* https://github.com/srizzo/gm-google-map
* Copyright (c) 2017 Samuel Rizzo; Licensed MIT */
angular.module('gm-google-map', [])
/**
* @description
*
* Shared map context. Publishes $scope.$setMap(map) and $scope.$getMap().
*
*/
.directive('gmMapContext', function() {
return {
scope: true,
restrict: 'EA',
controller: ["$scope", function ($scope) {
var _map;
$scope.$setMap = function (map) {
_map = map
}
$scope.$getMap = function () {
return _map
}
}]
}
})
/**
* @description
*
* Map Canvas. Publishes $scope.$setMap(map) and $scope.$getMap().
*
*/
.directive('gmMapCanvas', function() {
return {
scope: true,
restrict: 'EA',
require: '^?gmMapContext',
link: {
pre: function (scope, element, attrs) {
var disableDefaultUI = false
var styles = [
{
featureType: 'poi',
elementType: 'all',
stylers: [{ visibility: 'off' }]
}
]
if (attrs.disableDefaultUi)
disableDefaultUI = scope.$eval(attrs.disableDefaultUi)
if (attrs.styles)
styles = scope.$eval(attrs.styles)
var _map = new google.maps.Map(element[0], {
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: disableDefaultUI,
styles: styles
})
if (!scope.$setMap) {
scope.$setMap = function (map) {
_map = map
}
scope.$getMap = function () {
return _map
}
}
scope.$setMap(_map)
if (attrs.zoom) {
scope.$watch(attrs.zoom, function(current) {
_map.setZoom(current)
})
}
if (attrs.center) {
scope.$watch(attrs.center, function(current) {
if (current == null) {
return
}
_map.setCenter(new google.maps.LatLng(current.lat, current.lng))
}, true)
}
scope.safeApply = function(fn) {
var phase = scope.$root.$$phase
if(phase == '$apply' || phase == '$digest') {
if(fn && (typeof(fn) === 'function')) {
fn()
}
} else {
scope.$apply(fn)
}
}
angular.forEach(scope.$eval(attrs.listeners), function (listener, key) {
google.maps.event.addListener(_map, key, function () {
scope.safeApply(function () {
listener()
})
})
})
angular.forEach(scope.$eval(attrs.listenersOnce), function (listener, key) {
google.maps.event.addListenerOnce(_map, key, function () {
scope.safeApply(function () {
listener()
})
})
})
}
}
}
})
/**
* @description
*
* The sole purpose of the gmAddOns directive is to group gm-* directives / dom elements into a hidden element, preventing them from being displayed outside the map canvas
*
*/
.directive('gmAddOns', function() {
return {
scope: true,
restrict: 'EA',
compile: function (element) {
element.css("display", "none")
}
}
})
.directive('gmControl', function() {
return {
scope: true,
compile: function(element, attrs) {
if (typeof attrs.visible === 'undefined')
attrs.visible = "true"
return {
pre: function(scope, element, attrs) {
var domElement = element[0]
var map = scope.$getMap()
var position = attrs.position || "LEFT_TOP"
scope.$hide = function() {
var index = map.controls[google.maps.ControlPosition[position]].indexOf(domElement)
if (index > -1)
map.controls[google.maps.ControlPosition[position]].removeAt(index)
}
scope.$show = function() {
var index = map.controls[google.maps.ControlPosition[position]].indexOf(domElement)
if (index < 0)
map.controls[google.maps.ControlPosition[position]].push(domElement)
}
if (attrs.visible) {
scope.$watch(attrs.visible, function(current) {
if (current === true)
scope.$show()
else
scope.$hide()
})
}
}
}
}
}
})
/**
* @description
*
* InfoWindow. Expects $scope.$getMap() and $scope.$getMarker() to be available. Publishes $scope.$openInfoWindow() and $scope.$closeInfoWindow().
*
*/
.directive('gmInfoWindow', function() {
return {
scope: true,
compile: function() {
return {
pre: function(scope, element, attrs) {
var domElement = element[0]
var infoWindow = new google.maps.InfoWindow()
infoWindow.setContent(domElement)
if (attrs.closeclick) {
infoWindow.addListener('closeclick', function() {
scope.$apply(function() {
scope.$eval(attrs.closeclick)
})
})
}
scope.$openInfoWindow = function() {
infoWindow.open(scope.$getMap(), scope.$getMarker())
}
scope.$closeInfoWindow = function() {
infoWindow.close()
}
}
}
}
}
})
/**
* @description
*
* Overlapping Marker Spiderfier. Expects $scope.$getMap() to be available. Publishes $scope.$getOverlappingMarkerSpiderfier(). Triggers gm_oms_click google maps event when a marker is clicked.
*
* Requires https://cdn.rawgit.com/srizzo/OverlappingMarkerSpiderfier/0.3.3/dist/oms.min.js
*
*/
.directive('gmOverlappingMarkerSpiderfier', function() {
return {
restrict: 'AE',
scope: true,
compile: function () {
return {
pre: function(scope, element) {
element.css("display", "none")
var oms = new OverlappingMarkerSpiderfier(scope.$getMap(), {
keepSpiderfied: true
})
scope.$getOverlappingMarkerSpiderfier = function () {
return oms
}
scope.$on("gm_marker_created", function (event, marker) {
oms.addMarker(marker)
})
scope.$on("gm_marker_destroyed", function (event, marker) {
oms.removeMarker(marker)
})
oms.addListener('click', function(marker, event) {
scope.$apply(function() {
google.maps.event.trigger(marker, "gm_oms_click", event)
})
})
}
}
}
}
})
/**
* @description
*
* Marker. Expects $scope.$getMap() to be available. Publishes $scope.$getMarker(). Emits gm_marker_created and gm_marker_destroyed angularjs events.
*
*/
.directive('gmMarker', function() {
return {
restrict: 'AE',
scope: true,
compile: function() {
return {
pre: function(scope, element, attrs) {
var marker = new google.maps.Marker({
map: scope.$getMap(),
data: scope.$eval(attrs.data),
title: scope.$eval(attrs.title),
optimized: scope.$eval(attrs.optimized),
position: new google.maps.LatLng(scope.$eval(attrs.position).lat, scope.$eval(attrs.position).lng)
})
scope.$getMarker = function () {
return marker
}
if (attrs.position) {
var unbindPositionWatch = scope.$watch(attrs.position, function(current) {
marker.setPosition(new google.maps.LatLng(current.lat, current.lng))
})
}
if (attrs.icon) {
var unbindIconWatch = scope.$watch(attrs.icon, function(current) {
marker.setIcon(current)
})
}
scope.$emit("gm_marker_created", marker)
scope.$on("$destroy", function() {
unbindPositionWatch()
unbindIconWatch()
marker.setMap(null)
scope.$emit("gm_marker_destroyed", marker)
})
scope.safeApply = function(fn) {
var phase = scope.$root.$$phase
if(phase == '$apply' || phase == '$digest') {
if(fn && (typeof(fn) === 'function')) {
fn()
}
} else {
scope.$apply(fn)
}
}
angular.forEach(scope.$eval(attrs.listeners), function (listener, key) {
google.maps.event.addListener(marker, key, function () {
scope.safeApply(function () {
listener()
})
})
})
angular.forEach(scope.$eval(attrs.listenersOnce), function (listener, key) {
google.maps.event.addListenerOnce(marker, key, function () {
scope.safeApply(function () {
listener()
})
})
})
}
}
}
}
})
/**
* @description
*
* Polyline. Expects $scope.$getMap() to be available. Publishes $scope.$getPolyline(). Emits gm_polyline_created and gm_polyline_destroyed angularjs events.
*
*/
.directive('gmPolyline', function() {
return {
restrict: 'AE',
scope: true,
compile: function() {
return {
pre: function(scope, element, attrs) {
var polyline = new google.maps.Polyline({
map: scope.$getMap(),
data: scope.$eval(attrs.data),
path: scope.$eval(attrs.path),
geodesic: scope.$eval(attrs.geodesic),
strokeColor: scope.$eval(attrs.strokeColor),
strokeOpacity: scope.$eval(attrs.strokeOpacity),
strokeWeight: scope.$eval(attrs.strokeWeight)
})
scope.$getPolyline = function () {
return polyline
}
if (attrs.icon) {
var unbindIconWatch = scope.$watch(attrs.icon, function(current) {
polyline.setIcon(current)
})
}
scope.$emit("gm_polyline_created", polyline)
scope.$on("$destroy", function() {
unbindIconWatch()
polyline.setMap(null)
scope.$emit("gm_polyline_destroyed", polyline)
})
scope.safeApply = function(fn) {
var phase = scope.$root.$$phase
if(phase == '$apply' || phase == '$digest') {
if(fn && (typeof(fn) === 'function')) {
fn()
}
} else {
scope.$apply(fn)
}
}
angular.forEach(scope.$eval(attrs.listeners), function (listener, key) {
google.maps.event.addListener(polyline, key, function () {
scope.safeApply(function () {
listener()
})
})
})
angular.forEach(scope.$eval(attrs.listenersOnce), function (listener, key) {
google.maps.event.addListenerOnce(polyline, key, function () {
scope.safeApply(function () {
listener()
})
})
})
}
}
}
}
})
/**
* @description
*
* Adds listeners to google maps objects.
*
*/
.directive('gmAddListeners', function() {
return {
scope: true,
restrict: 'EA',
link: {
pre: function (scope, element, attrs) {
scope.safeApply = function(fn) {
var phase = scope.$root.$$phase
if(phase == '$apply' || phase == '$digest') {
if(fn && (typeof(fn) === 'function')) {
fn()
}
} else {
scope.$apply(fn)
}
}
var to = scope.$eval(attrs.to)
angular.forEach(scope.$eval(attrs.listeners), function (callback, key) {
google.maps.event.addListener(to, key, function () {
scope.safeApply(function () {
scope.$eval(callback)
})
})
})
angular.forEach(scope.$eval(attrs.listenersOnce), function (callback, key) {
google.maps.event.addListenerOnce(to, key, function () {
scope.safeApply(function () {
scope.$eval(callback)
})
})
})
}
}
}
})
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Richard Backhouse
*
* 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.
*/
module.exports = function(RED) {
function BLEDevice(config) {
var BLEManager = require("../../lib/BLEManager");
RED.nodes.createNode(this, config);
this.name = config.name;
this.uuid = config.uuid;
this.readType;
var node = this;
var theDevice;
var cmds = [];
BLEManager.waitFor(node.uuid, function(device) {
theDevice = device;
node.log(node.name+":"+node.uuid+" created ");
device.on("connected", function() {
node.log(device.name+":"+device.id+" connected");
node.status({fill:"red",shape:"ring",text:"connected"});
cmds.forEach(function(cmd) {
node.log("sending cmd : "+cmd+" to "+device.name+":"+device.id);
BLEManager.sendCommand(device.id, cmd, function() {});
});
cmds = [];
});
device.on("disconnected", function() {
node.log(device.name+":"+device.id+" disconnected");
node.status({fill:"red",shape:"dot",text:"disconnected"});
});
device.on("read", function(type, data) {
if (node.readType === type) {
node.log("read type : "+type+" data : "+JSON.stringify(data)+" from "+device.name+":"+device.id);
var readMsg = {
id: device.id,
name: device.name,
type: type,
data: data
};
node.send({payload: readMsg});
}
});
device.on("error", function(err) {
node.log("error on "+device.name+":"+device.id+" : "+err);
});
}.bind(this));
this.on('input', function(msg) {
if (theDevice) {
node.readType = msg.payload.readType;
node.log("input with msg : "+JSON.stringify(msg)+" on "+theDevice.name+":"+theDevice.id);
if (theDevice.isConnected()) {
node.log("sending cmd : "+msg.payload.cmd+" to "+theDevice.name+":"+theDevice.id);
BLEManager.sendCommand(theDevice.id, msg.payload.cmd, function() {});
} else {
cmds.push(msg.payload.cmd);
BLEManager.connectToDevice(theDevice.id);
}
}
});
this.on('close', function() {
node.log(node.name+":"+node.uuid+" closed");
if (theDevice) {
BLEManager.disconnectFromDevice(theDevice.id);
}
});
}
RED.nodes.registerType("BLEDevice", BLEDevice);
} |
// Build 35
$(document).ready(function () {
socket.on('newMessage', function (message) {
var entry = '<li data-userID="' + message.userID + '"><div class="content"><p class="message">' + linkURLs(message.message) + '</p><h4 class="name">- ' + message.name + '</h4><time data-time="' + message.time + '"></time></div></li>';
$('#messages').append(entry);
setTime();
// for iOS, shows the time when tapping onto a message
if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) $('html, body').animate({scrollTop: $(document).height()}, 0);
else $('#messages').animate({ scrollTop: document.getElementById('messages').scrollHeight }, 0);
// functions:
function linkURLs(text) {
var url = '', www = '', mail = '';
url = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim; // URLs starting with http://, https://, or ftp://
www = /(^|[^\/])(www\.[\S]+(\b|$))/gim; // URLs starting with "www." (without // before it, or it'd re-link the ones done above).
mail = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim; // Change email addresses to mailto:: links.
return String(text).replace(url, '<a href="$1" target="_blank">$1</a>').replace(www, '$1<a href="http://$2" target="_blank">$2</a>').replace(mail, '<a href="mailto:$1">$1</a>');
}
});
socket.on('updatedUsers', function (users) {
var html='';
var watching = 0;
for (var userID in users) {
if (users[userID].name != false) html += '<li data-userID="' + userID + '">' + users[userID].name + '</li>';
else watching++;
}
if (watching == 1) html += '<li>' + watching + ' person watching</li>';
if (watching >= 2) html += '<li>' + watching + ' people watching</li>';
$('#users li').each(function(index) { // for each, do:
$(this).addClass('disappear');
});
setTimeout(function () {
$('#users').html(html);
}, 200);
});
setInterval(setTime, 10*1000);
function setTime() { // adds relative timestamps to every entry
$('#messages li time').each(function(index) { // for each, do
if ($(this).attr('data-time')) { // if this element has 'data-time' attribute
var time;
time = moment('"' + $(this).attr('data-time') + '"', "YYYY-MM-DDTHH:mm:ssZ"); // cretates moment() with the content of the data-time attribute
time = time.from(moment().utc()); // coverts it to realtive timestamps
$(this).html(time); // add's the relative timestamp into the element
}
});
}
}); // document.ready |
/**
* @desc: build-clean
*/
const _del = require('del');
const _dirs = require('../config/dir-vars').dirs;
_del.sync(_dirs.build);
|
/*jslint node:true */
/*jslint nomen: true */
var db = require('mongoose');
var Schema = db.Schema;
var ObjectId = Schema.ObjectId;
//Note Schema
var NoteSchema = new Schema({
name: String,
date: Date,
amount: Number,
devise: String,
user: String,
status: String,
commentary: String,
id: ObjectId
}, { collection: 'notes' });
var Note = db.model('Note', NoteSchema);
module.exports = Note; |
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import CtlBase from '../ctl.base'
import { localPro, drawCtls, makeStyles, makeValueAndState } from '../ctl.utils'
export default class CtlLayout extends CtlBase {
constructor(props) {
super(props);
debugger;
let [ ctlStyle ] = [ {} ];
const a = this;
const { local , styles } = a.profile.props;
const { coms = [], stack = 0, direct = 0, perz = 0, lazy: lazyLoad = 1 } = local || {};
a.lazyLoad = lazyLoad;
a.coms = coms;
a.stack = stack;
a.direct = direct;
a.perz = perz;
a._loaded = false;
a.defaultDisplay = 'block';
// 行内样式(公众)
if (styles)
ctlStyle = makeStyles(a, styles);
// state默认设置
this.state = {
ctlStyle,
loadable: !a.lazyLoad,
childrenCtl: this.profile.ctls || [],
widgetDisabled: false
};
makeValueAndState(this);
}
componentDidMount() {
console.log('[ CtlLayout.componentDidMount ]', new Date().toISOString());
super.componentDidMount();
this.runtime.instance.sqlexec(this.runtime);
}
render() {
console.log('[ CtlLayout.redner ]', new Date().toISOString());
const { type, id, path } = this;
const { ctlStyle, childrenCtl } = this.state;
return (
<div
ref={box => this.box = $(box)}
data-type={type}
data-id={id}
data-path={path}
className={'panel'}
style={ctlStyle}
>
{this.load()}
</div>
);
}
load() {
const a = this;
let itemComponents = null;
if (a.state.loadable) {
a._loaded = true;
a.perzArr = [];
$F.dataService('SystemDo2', {
data: {
token: a.runtime.project.token,
dbPool: '',
sqls: [{
key: 'Dyn.layout.read',
params: {
C1: $E.staff.epidSql,
C2: $E.staff.id,
C3: a.path
}
}, {
key: 'Dyn.layout.read',
params: {
C1: $E.staff.epidSql,
C2: '_DEFT_',
C3: a.path
}
}]
},
async: false,
success: function(data) {
debugger;
if (data.code > 0) {
//console.log(data);
if (data.value[0].count < 0) {
$F.err('Ctls - CtlLayout', 'Sql execute failed: ' + data.value[0].key);
return;
}
a.perzArr = $F.makeJsonArray(data.value[0]);
if (a.perzArr.length == 0) {
// 当前账号无数据,从系统读入默认配置
if (data.value[1].count < 0) {
$F.err('Ctls - CtlLayout', 'Sql execute failed: ' + data.value[1].key);
return;
}
a.perzArr = $F.makeJsonArray(data.value[1]);
}
} else
$F.err('Ctls - layoutBox', data.message);
}
})
console.info('获取容器组件列表[' + a.path + ']: ', a.coms);
const visualCtl = [];
if (!a.perzArr.length && a.stack > 0) {
for(let key in a.coms) {
if (a.coms.hasOwnProperty(key)) {
const com = a.coms[key];
com.props.extend = com.props.extend || {};
//console.log(com.props.extend)
if (com.props.extend.hide)
continue; // 组件默认隐藏状态
a.perzArr.push({
STAFFID: $E.staff.id,
COMKEY: com.id2,
COMID: com.id,
COMPNAME: com.name,
X: 1,
Y: 1,
COLSPAN: 1,
ROWSPAN: 1,
TABINDEX: com.props.extend.index || 0
})
}
}
}
a.perzArr.sort((a, b) => {
return a.TABINDEX > b.TABINDEX;
})
console.log('获取容器自定义数据:' + a.path, a.perzArr);
const comStructNeedLoaded = [];
// 手机默认陈列式容器
a.perzArr.forEach((perz, i) => {
debugger;
if (perz.COMKEY == 'CONTAINER' || ! a.coms[perz.COMKEY])
return;
const vc = {
id : a.id + '.' + perz.COMKEY,
name : 'component'
}
vc.props = a.coms[perz.COMKEY].props;
vc.props.local = vc.props.local || {};
vc.props.local.com = a.coms[perz.COMKEY].id;
vc.props.styles = vc.props.styles || {};
if (a.direct) {
// 纵向陈列
vc.props.styles.display = 'block';
if (i > 0 && localPro(a, 'sep')) {
vc.props.styles.customStyles = vc.props.styles.customStyles || {};
vc.props.styles.customStyles.styles += ';margin-top:' + localPro(a, 'sep') + 'px';
}
} else {
// 横向陈列
vc.props.styles.display = 'inline-block';
if (i > 0 && localPro(a, 'sep')) {
vc.props.styles.customStyles = vc.props.styles.customStyles || {};
vc.props.styles.customStyles.styles += ';margin-left:' + localPro(a, 'sep') + 'px';
}
}
if (!$D.structs[a.runtime.project.id][vc.props.local.com]) {
comStructNeedLoaded.push(vc.props.local.com);
}
visualCtl.push(vc);
});
if (comStructNeedLoaded.length > 0)
a.loadComponentsStruct(comStructNeedLoaded);
if (visualCtl.length > 0)
itemComponents = drawCtls(visualCtl, a.box, a, a.runtime, a.xData, a.xRow);
}
return itemComponents;
}
loadComponentsStruct(ids) {
const project = this.runtime.project;
// for dyn2
const dataRequest = {
token: project.token,
dbPool: project.getParam('CFGDBP'),
sqls: []
}
ids.forEach((id, i) => {
dataRequest.sqls.push({
key: 'dyn2.get',
params: { C1: id }
},
{
key: 'dyn2.page.findAll',
params: { C1: id }
});
});
$F.dataService('SystemDo2', {
data: dataRequest,
digest: project.digest,
async : false,
success: function(data) {
if (data.code < 0)
return $F.err('Dyn - loadComponents', data.message);
// console.group('Dyn - loadComponents', '组件结构批量加载完成', data);
// console.log(data.value);
if (ids.length * 2 !== data.value.length)
return $F.err('Dyn - loadComponents', '组件结构获取接口发生异常', data);
$.each(ids, function(i, id) {
var bean = $F.makeJsonBean(data.value[i*2]), content = JSON.parse(bean.CONTENT), property, prop;
var struct = {
id: bean.DYNID2,
guid: bean.DYNID,
stateful: bean.STATEFUL,
theme: bean.THEME,
trackablity: bean.TRACKABLITY,
cmds: content.cmds,
flows: content.flows,
pages: content.pages,
styles: content.styles || {},
props: {
pub: {},
local: {}
},
version: 'DYN2',
mode: content.mode
};
for(var key in content.properties) {
for(var name in content.properties[key]) {
prop = content.properties[key][name];
property = {
ns: key,
field: name,
t: prop.t
};
if (prop.v !== undefined)
property.v = prop.v;
if (key == 'var' || key == 'tabc') {
struct.props.local[key + '.' + name] = property
} else {
struct.props.pub[key + '.' + name] = property
}
}
}
// 合并所有子页面在主结构中
try {
$.each(data.value[i*2 + 1].fields, function(i, row) {
// console.log(row)
var page = struct.pages[row[0]];
if (page) {
$.extend(page, JSON.parse(row[1]))
} else
$F.err('Ctls - loadComponents', '组件结构中未发现子页面: ' + row[0])
})
} catch(e) {
$F.err('Ctls - loadComponents', e)
}
debugger;
$D.structs[project.id][struct.guid] = struct;
$F.log('Dyn - loadComponents', '获取组件结构:' + struct.id, struct);
});
}
});
}
initStateWidgetState(e) {
const a = this;
a.widgetState = e;
if (e == 1) {
this.state.ctlStyle.disable = 'none';
} else {
this.state.ctlStyle.disable = this.defaultDisplay;
if (a.lazyLoad && !a._loaded) // 懒加载模式,且未绘制
this.state.loadable = true;
this.state.widgetDisabled = (e == 2);
}
}
states(e) {
const a = this;
if (e == 1) {
this.setState({ctlStyle: {...this.state.ctlStyle, display: 'none'}});
} else {
this.setState({ctlStyle: {...this.state.ctlStyle, display: this.state.ctlStyle.display || this.defaultDisplay}});
if (a.lazyLoad && !a._loaded) // 懒加载模式,且未绘制
this.setState({loadable: true});
a.disable(e == 2);
}
}
disable (e, byParent) {
const a = this, fakeState = byParent ? (e || a.widgetDisabled) : e;
Object.keys(a.controls).forEach(ctlId => {
a.controls[ctlId].disable(fakeState, true);
});
}
} |
export const ic_table_chart_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M20 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h15c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 2v3H5V5h15zm-5 14h-5v-9h5v9zM5 10h3v9H5v-9zm12 9v-9h3v9h-3z"},"children":[]}]}; |
{
if (n(i) && e(t.parent)) t.parent.data.pendingInsert = r;
else for (var o = 0; o < r.length; ++o) r[o].data.hook.insert(r[o]);
}
|
(function () {
'use strict';
angular.module('demo.person.directive', [])
.directive('person', PersonDirective);
PersonDirective.$inject = ['loggingService'];
function PersonDirective(loggingService) {
return {
restrict: 'E',
require: 'ngModel',
scope: {
ngModel: '='
},
templateUrl: 'person/templates/person-edit.html',
link: link
};
function link(scope, element, attr) {
var vm = scope,
logger = loggingService.logger('person Directive $Id ' + vm.$id),
personCopy;
// validate and update model on change
// This example is a bit contrived, but imagine third party control here
function update() {
try {
// implements model change event
vm.ngModel.onChange();
// create a copy of the model for rollback if required
personCopy = vm.ngModel.copy();
logger.debug('updating', vm.ngModel);
} catch (ex) {
// throw non-fatal error
logger.error('updating', vm.ngModel, ex, false);
// rollback
vm.ngModel = personCopy;
logger.debug('rolling back', vm.ngModel);
}
}
// directive activation
(function () {
vm.update = update;
personCopy = vm.ngModel.copy();
logger.debug('activated', vm);
})();
}
}
})(); |
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;
|
/**
* angular-ui-utils - Swiss-Army-Knife of AngularJS tools (with no external dependencies!)
* @version v0.0.4 - 2013-07-24
* @link http://angular-ui.github.com
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
!function(){var a=(window.ieShivDebug||!1,["ngInclude","ngPluralize","ngView","ngSwitch","uiCurrency","uiCodemirror","uiDate","uiEvent","uiKeypress","uiKeyup","uiKeydown","uiMask","uiMapInfoWindow","uiMapMarker","uiMapPolyline","uiMapPolygon","uiMapRectangle","uiMapCircle","uiMapGroundOverlay","uiModal","uiReset","uiScrollfix","uiSelect2","uiShow","uiHide","uiToggle","uiSortable","uiTinymce"]);window.myCustomTags=window.myCustomTags||[],a.push.apply(a,window.myCustomTags);for(var b=function(a){var b=[],c=a.replace(/([A-Z])/g,function(a){return" "+a.toLowerCase()}),d=c.split(" ");if(1===d.length){var e=d[0];b.push(e),b.push("x-"+e),b.push("data-"+e)}else{var f=d[0],g=d.slice(1).join("-");b.push(f+":"+g),b.push(f+"-"+g),b.push("x-"+f+"-"+g),b.push("data-"+f+"-"+g)}return b},c=0,d=a.length;d>c;c++)for(var e=b(a[c]),f=0,g=e.length;g>f;f++){var h=e[f];document.createElement(h)}}(window); |
function agenda (titulo, inic) {
var _titulo = titulo;
var _contenido = inic;
return {
titulo: function() { return _titulo; },
meter: function(nombre, tf) { _contenido[nombre]=tf; },
tf: function(nombre) { return _contenido[nombre]; },
borrar: function(nombre) { delete _contenido[nombre]; },
listar: function() { for (var i in _contenido) { console.log(i + ", " + _contenido[i])}},
toJSON: function() { return JSON.stringify(_contenido);}
}
}
var amigos = agenda ("Amigos",
{ Pepe: 113278561,
José: 157845123,
Jesús: 178512355
});
amigos.listar();
|
import {Actions} from 'flummox';
import {queryLocation} from '../api/instagram';
class InstagramApiActions extends Actions {
async queryLocation(location) {
try {
let response = await queryLocation(location);
return {
data: response.data
};
} catch (error) {
}
}
}
export default InstagramApiActions; |
initSidebarItems({"mod":[["v1","The first version of the prelude of the standard library."]]}); |
'use strict';
const Vue = require('vue');
const page = require('../router.js');
Vue.component('v-setup', {
el () {
return document.createElement('div');
},
template: require('../templates/v-setup.vue'),
data () {
return {
date: null,
title: ''
};
},
methods: {
create () {
page.show(`/countdown?date=${this.date}&title=${this.title}`);
}
}
});
|
// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2014-09-30 using
// generator-karma 0.8.3
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// base path, that will be used to resolve files and exclude
basePath: '../../',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
// 'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-cookies/angular-cookies.js',
// 'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-ui-router/release/angular-ui-router.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-touch/angular-touch.js',
'app/scripts/**/*.js',
'test/unit/spec/**/*.js'
],
// list of files / patterns to exclude
exclude: [
'app/scripts/ecg-quicktest-ngmodule/services/*.js'
],
// web server port
port: 8080,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
'PhantomJS'
],
// Which plugins to enable
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine'
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_DEBUG
// Uncomment the following lines if you are using grunt's server to run the tests
// proxies: {
// '/': 'http://localhost:9000/'
// },
// URL root prevent conflicts with the site root
// urlRoot: '_karma_'
});
};
|
'use strict';
const {run} = require('madrun');
module.exports = {
'test': () => 'tape test/*.js',
'watcher': () => 'nodemon -w test -w lib --exec',
'watch:test': () => run('watcher', 'npm test'),
'lint': () => 'putout lib test .madrun.js *.md',
'fix:lint': () => run('lint', '--fix'),
'coverage': () => 'nyc npm test',
'report': () => 'nyc report --reporter=text-lcov | coveralls',
};
|
var fixtures = require('./fixtures');
describe('Place relationships', function () {
before(fixtures.fakeserver.init);
after(fixtures.fakeserver.deinit);
beforeEach(fixtures.testData.createPlaceTestData);
beforeEach(fixtures.testData.setPlaceIds);
});
|
import './Debug-91f604ee.js';
import 'redux';
import { _ as _createClass, w as _classCallCheck, x as _inherits, y as _defineProperty, z as _possibleConstructorReturn, B as _getPrototypeOf, C as _assertThisInitialized, D as _toConsumableArray } from './turn-order-dce10a02.js';
import 'immer';
import './reducer-b11048c2.js';
import 'flatted';
import { M as MCTSBot } from './ai-9b435d0e.js';
import './initialize-63a95034.js';
import { C as Client$1 } from './client-ef3f3b30.js';
import React from 'react';
import PropTypes from 'prop-types';
import Cookies from 'react-cookies';
import './base-c99f5be2.js';
import { S as SocketIO, L as Local } from './socketio-043d62b9.js';
import './master-6720c47b.js';
import 'socket.io-client';
/*
* Copyright 2017 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Client
*
* boardgame.io React client.
*
* @param {...object} game - The return value of `Game`.
* @param {...object} numPlayers - The number of players.
* @param {...object} board - The React component for the game.
* @param {...object} loading - (optional) The React component for the loading state.
* @param {...object} multiplayer - Set to a falsy value or a transportFactory, e.g., SocketIO()
* @param {...object} debug - Enables the Debug UI.
* @param {...object} enhancer - Optional enhancer to send to the Redux store
*
* Returns:
* A React component that wraps board and provides an
* API through props for it to interact with the framework
* and dispatch actions such as MAKE_MOVE, GAME_EVENT, RESET,
* UNDO and REDO.
*/
function Client(opts) {
var _a;
let { game, numPlayers, loading, board, multiplayer, enhancer, debug } = opts;
// Component that is displayed before the client has synced
// with the game master.
if (loading === undefined) {
const Loading = () => React.createElement("div", { className: "bgio-loading" }, "connecting...");
loading = Loading;
}
/*
* WrappedBoard
*
* The main React component that wraps the passed in
* board component and adds the API to its props.
*/
return _a = class WrappedBoard extends React.Component {
constructor(props) {
super(props);
if (debug === undefined) {
debug = props.debug;
}
this.client = Client$1({
game,
debug,
numPlayers,
multiplayer,
gameID: props.gameID,
playerID: props.playerID,
credentials: props.credentials,
enhancer,
});
}
componentDidMount() {
this.unsubscribe = this.client.subscribe(() => this.forceUpdate());
this.client.start();
}
componentWillUnmount() {
this.client.stop();
this.unsubscribe();
}
componentDidUpdate(prevProps) {
if (this.props.gameID != prevProps.gameID) {
this.client.updateGameID(this.props.gameID);
}
if (this.props.playerID != prevProps.playerID) {
this.client.updatePlayerID(this.props.playerID);
}
if (this.props.credentials != prevProps.credentials) {
this.client.updateCredentials(this.props.credentials);
}
}
render() {
const state = this.client.getState();
if (state === null) {
return React.createElement(loading);
}
let _board = null;
if (board) {
_board = React.createElement(board, {
...state,
...this.props,
isMultiplayer: !!multiplayer,
moves: this.client.moves,
events: this.client.events,
gameID: this.client.gameID,
playerID: this.client.playerID,
reset: this.client.reset,
undo: this.client.undo,
redo: this.client.redo,
log: this.client.log,
gameMetadata: this.client.gameMetadata,
});
}
return React.createElement("div", { className: "bgio-client" }, _board);
}
},
_a.propTypes = {
// The ID of a game to connect to.
// Only relevant in multiplayer.
gameID: PropTypes.string,
// The ID of the player associated with this client.
// Only relevant in multiplayer.
playerID: PropTypes.string,
// This client's authentication credentials.
// Only relevant in multiplayer.
credentials: PropTypes.string,
// Enable / disable the Debug UI.
debug: PropTypes.any,
},
_a.defaultProps = {
gameID: 'default',
playerID: null,
credentials: null,
debug: true,
},
_a;
}
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
var _LobbyConnectionImpl =
/*#__PURE__*/
function () {
function _LobbyConnectionImpl(_ref) {
var server = _ref.server,
gameComponents = _ref.gameComponents,
playerName = _ref.playerName,
playerCredentials = _ref.playerCredentials;
_classCallCheck(this, _LobbyConnectionImpl);
this.gameComponents = gameComponents;
this.playerName = playerName || 'Visitor';
this.playerCredentials = playerCredentials;
this.server = server;
this.rooms = [];
}
_createClass(_LobbyConnectionImpl, [{
key: "_baseUrl",
value: function _baseUrl() {
return "".concat(this.server || '', "/games");
}
}, {
key: "refresh",
value: async function refresh() {
try {
this.rooms.length = 0;
var resp = await fetch(this._baseUrl());
if (resp.status !== 200) {
throw new Error('HTTP status ' + resp.status);
}
var json = await resp.json();
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = json[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var gameName = _step.value;
if (!this._getGameComponents(gameName)) continue;
var gameResp = await fetch(this._baseUrl() + '/' + gameName);
var gameJson = await gameResp.json();
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = gameJson.rooms[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var inst = _step2.value;
inst.gameName = gameName;
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) {
_iterator2["return"]();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
this.rooms = this.rooms.concat(gameJson.rooms);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator["return"] != null) {
_iterator["return"]();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
} catch (error) {
throw new Error('failed to retrieve list of games (' + error + ')');
}
}
}, {
key: "_getGameInstance",
value: function _getGameInstance(gameID) {
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = this.rooms[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var inst = _step3.value;
if (inst['gameID'] === gameID) return inst;
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) {
_iterator3["return"]();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
}
}, {
key: "_getGameComponents",
value: function _getGameComponents(gameName) {
var _iteratorNormalCompletion4 = true;
var _didIteratorError4 = false;
var _iteratorError4 = undefined;
try {
for (var _iterator4 = this.gameComponents[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
var comp = _step4.value;
if (comp.game.name === gameName) return comp;
}
} catch (err) {
_didIteratorError4 = true;
_iteratorError4 = err;
} finally {
try {
if (!_iteratorNormalCompletion4 && _iterator4["return"] != null) {
_iterator4["return"]();
}
} finally {
if (_didIteratorError4) {
throw _iteratorError4;
}
}
}
}
}, {
key: "_findPlayer",
value: function _findPlayer(playerName) {
var _iteratorNormalCompletion5 = true;
var _didIteratorError5 = false;
var _iteratorError5 = undefined;
try {
for (var _iterator5 = this.rooms[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
var inst = _step5.value;
if (inst.players.some(function (player) {
return player.name === playerName;
})) return inst;
}
} catch (err) {
_didIteratorError5 = true;
_iteratorError5 = err;
} finally {
try {
if (!_iteratorNormalCompletion5 && _iterator5["return"] != null) {
_iterator5["return"]();
}
} finally {
if (_didIteratorError5) {
throw _iteratorError5;
}
}
}
}
}, {
key: "join",
value: async function join(gameName, gameID, playerID) {
try {
var inst = this._findPlayer(this.playerName);
if (inst) {
throw new Error('player has already joined ' + inst.gameID);
}
inst = this._getGameInstance(gameID);
if (!inst) {
throw new Error('game instance ' + gameID + ' not found');
}
var resp = await fetch(this._baseUrl() + '/' + gameName + '/' + gameID + '/join', {
method: 'POST',
body: JSON.stringify({
playerID: playerID,
playerName: this.playerName
}),
headers: {
'Content-Type': 'application/json'
}
});
if (resp.status !== 200) throw new Error('HTTP status ' + resp.status);
var json = await resp.json();
inst.players[Number.parseInt(playerID)].name = this.playerName;
this.playerCredentials = json.playerCredentials;
} catch (error) {
throw new Error('failed to join room ' + gameID + ' (' + error + ')');
}
}
}, {
key: "leave",
value: async function leave(gameName, gameID) {
try {
var inst = this._getGameInstance(gameID);
if (!inst) throw new Error('game instance not found');
var _iteratorNormalCompletion6 = true;
var _didIteratorError6 = false;
var _iteratorError6 = undefined;
try {
for (var _iterator6 = inst.players[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
var player = _step6.value;
if (player.name === this.playerName) {
var resp = await fetch(this._baseUrl() + '/' + gameName + '/' + gameID + '/leave', {
method: 'POST',
body: JSON.stringify({
playerID: player.id,
credentials: this.playerCredentials
}),
headers: {
'Content-Type': 'application/json'
}
});
if (resp.status !== 200) {
throw new Error('HTTP status ' + resp.status);
}
delete player.name;
delete this.playerCredentials;
return;
}
}
} catch (err) {
_didIteratorError6 = true;
_iteratorError6 = err;
} finally {
try {
if (!_iteratorNormalCompletion6 && _iterator6["return"] != null) {
_iterator6["return"]();
}
} finally {
if (_didIteratorError6) {
throw _iteratorError6;
}
}
}
throw new Error('player not found in room');
} catch (error) {
throw new Error('failed to leave room ' + gameID + ' (' + error + ')');
}
}
}, {
key: "disconnect",
value: async function disconnect() {
var inst = this._findPlayer(this.playerName);
if (inst) {
await this.leave(inst.gameName, inst.gameID);
}
this.rooms = [];
this.playerName = 'Visitor';
}
}, {
key: "create",
value: async function create(gameName, numPlayers) {
try {
var comp = this._getGameComponents(gameName);
if (!comp) throw new Error('game not found');
if (numPlayers < comp.game.minPlayers || numPlayers > comp.game.maxPlayers) throw new Error('invalid number of players ' + numPlayers);
var resp = await fetch(this._baseUrl() + '/' + gameName + '/create', {
method: 'POST',
body: JSON.stringify({
numPlayers: numPlayers
}),
headers: {
'Content-Type': 'application/json'
}
});
if (resp.status !== 200) throw new Error('HTTP status ' + resp.status);
} catch (error) {
throw new Error('failed to create room for ' + gameName + ' (' + error + ')');
}
}
}]);
return _LobbyConnectionImpl;
}();
/**
* LobbyConnection
*
* Lobby model.
*
* @param {string} server - '<host>:<port>' of the server.
* @param {Array} gameComponents - A map of Board and Game objects for the supported games.
* @param {string} playerName - The name of the player.
* @param {string} playerCredentials - The credentials currently used by the player, if any.
*
* Returns:
* A JS object that synchronizes the list of running game instances with the server and provides an API to create/join/start instances.
*/
function LobbyConnection(opts) {
return new _LobbyConnectionImpl(opts);
}
var LobbyLoginForm =
/*#__PURE__*/
function (_React$Component) {
_inherits(LobbyLoginForm, _React$Component);
function LobbyLoginForm() {
var _getPrototypeOf2;
var _this;
_classCallCheck(this, LobbyLoginForm);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(LobbyLoginForm)).call.apply(_getPrototypeOf2, [this].concat(args)));
_defineProperty(_assertThisInitialized(_this), "state", {
playerName: _this.props.playerName,
nameErrorMsg: ''
});
_defineProperty(_assertThisInitialized(_this), "onClickEnter", function () {
if (_this.state.playerName === '') return;
_this.props.onEnter(_this.state.playerName);
});
_defineProperty(_assertThisInitialized(_this), "onKeyPress", function (event) {
if (event.key === 'Enter') {
_this.onClickEnter();
}
});
_defineProperty(_assertThisInitialized(_this), "onChangePlayerName", function (event) {
var name = event.target.value.trim();
_this.setState({
playerName: name,
nameErrorMsg: name.length > 0 ? '' : 'empty player name'
});
});
return _this;
}
_createClass(LobbyLoginForm, [{
key: "render",
value: function render() {
return React.createElement("div", null, React.createElement("p", {
className: "phase-title"
}, "Choose a player name:"), React.createElement("input", {
type: "text",
value: this.state.playerName,
onChange: this.onChangePlayerName,
onKeyPress: this.onKeyPress
}), React.createElement("span", {
className: "buttons"
}, React.createElement("button", {
className: "buttons",
onClick: this.onClickEnter
}, "Enter")), React.createElement("br", null), React.createElement("span", {
className: "error-msg"
}, this.state.nameErrorMsg, React.createElement("br", null)));
}
}]);
return LobbyLoginForm;
}(React.Component);
_defineProperty(LobbyLoginForm, "propTypes", {
playerName: PropTypes.string,
onEnter: PropTypes.func.isRequired
});
_defineProperty(LobbyLoginForm, "defaultProps", {
playerName: ''
});
var LobbyRoomInstance =
/*#__PURE__*/
function (_React$Component) {
_inherits(LobbyRoomInstance, _React$Component);
function LobbyRoomInstance() {
var _getPrototypeOf2;
var _this;
_classCallCheck(this, LobbyRoomInstance);
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(LobbyRoomInstance)).call.apply(_getPrototypeOf2, [this].concat(args)));
_defineProperty(_assertThisInitialized(_this), "_createSeat", function (player) {
return player.name || '[free]';
});
_defineProperty(_assertThisInitialized(_this), "_createButtonJoin", function (inst, seatId) {
return React.createElement("button", {
key: 'button-join-' + inst.gameID,
onClick: function onClick() {
return _this.props.onClickJoin(inst.gameName, inst.gameID, '' + seatId);
}
}, "Join");
});
_defineProperty(_assertThisInitialized(_this), "_createButtonLeave", function (inst) {
return React.createElement("button", {
key: 'button-leave-' + inst.gameID,
onClick: function onClick() {
return _this.props.onClickLeave(inst.gameName, inst.gameID);
}
}, "Leave");
});
_defineProperty(_assertThisInitialized(_this), "_createButtonPlay", function (inst, seatId) {
return React.createElement("button", {
key: 'button-play-' + inst.gameID,
onClick: function onClick() {
return _this.props.onClickPlay(inst.gameName, {
gameID: inst.gameID,
playerID: '' + seatId,
numPlayers: inst.players.length
});
}
}, "Play");
});
_defineProperty(_assertThisInitialized(_this), "_createButtonSpectate", function (inst) {
return React.createElement("button", {
key: 'button-spectate-' + inst.gameID,
onClick: function onClick() {
return _this.props.onClickPlay(inst.gameName, {
gameID: inst.gameID,
numPlayers: inst.players.length
});
}
}, "Spectate");
});
_defineProperty(_assertThisInitialized(_this), "_createInstanceButtons", function (inst) {
var playerSeat = inst.players.find(function (player) {
return player.name === _this.props.playerName;
});
var freeSeat = inst.players.find(function (player) {
return !player.name;
});
if (playerSeat && freeSeat) {
// already seated: waiting for game to start
return _this._createButtonLeave(inst);
}
if (freeSeat) {
// at least 1 seat is available
return _this._createButtonJoin(inst, freeSeat.id);
} // room is full
if (playerSeat) {
return React.createElement("div", null, [_this._createButtonPlay(inst, playerSeat.id), _this._createButtonLeave(inst)]);
} // allow spectating
return _this._createButtonSpectate(inst);
});
return _this;
}
_createClass(LobbyRoomInstance, [{
key: "render",
value: function render() {
var room = this.props.room;
var status = 'OPEN';
if (!room.players.find(function (player) {
return !player.name;
})) {
status = 'RUNNING';
}
return React.createElement("tr", {
key: 'line-' + room.gameID
}, React.createElement("td", {
key: 'cell-name-' + room.gameID
}, room.gameName), React.createElement("td", {
key: 'cell-status-' + room.gameID
}, status), React.createElement("td", {
key: 'cell-seats-' + room.gameID
}, room.players.map(this._createSeat).join(', ')), React.createElement("td", {
key: 'cell-buttons-' + room.gameID
}, this._createInstanceButtons(room)));
}
}]);
return LobbyRoomInstance;
}(React.Component);
_defineProperty(LobbyRoomInstance, "propTypes", {
room: PropTypes.shape({
gameName: PropTypes.string.isRequired,
gameID: PropTypes.string.isRequired,
players: PropTypes.array.isRequired
}),
playerName: PropTypes.string.isRequired,
onClickJoin: PropTypes.func.isRequired,
onClickLeave: PropTypes.func.isRequired,
onClickPlay: PropTypes.func.isRequired
});
var LobbyCreateRoomForm =
/*#__PURE__*/
function (_React$Component) {
_inherits(LobbyCreateRoomForm, _React$Component);
function LobbyCreateRoomForm(props) {
var _this;
_classCallCheck(this, LobbyCreateRoomForm);
_this = _possibleConstructorReturn(this, _getPrototypeOf(LobbyCreateRoomForm).call(this, props));
/* fix min and max number of players */
_defineProperty(_assertThisInitialized(_this), "state", {
selectedGame: 0,
numPlayers: 2
});
_defineProperty(_assertThisInitialized(_this), "_createGameNameOption", function (game, idx) {
return React.createElement("option", {
key: 'name-option-' + idx,
value: idx
}, game.game.name);
});
_defineProperty(_assertThisInitialized(_this), "_createNumPlayersOption", function (idx) {
return React.createElement("option", {
key: 'num-option-' + idx,
value: idx
}, idx);
});
_defineProperty(_assertThisInitialized(_this), "_createNumPlayersRange", function (game) {
return _toConsumableArray(new Array(game.maxPlayers + 1).keys()).slice(game.minPlayers);
});
_defineProperty(_assertThisInitialized(_this), "onChangeNumPlayers", function (event) {
_this.setState({
numPlayers: Number.parseInt(event.target.value)
});
});
_defineProperty(_assertThisInitialized(_this), "onChangeSelectedGame", function (event) {
var idx = Number.parseInt(event.target.value);
_this.setState({
selectedGame: idx,
numPlayers: _this.props.games[idx].game.minPlayers
});
});
_defineProperty(_assertThisInitialized(_this), "onClickCreate", function () {
_this.props.createGame(_this.props.games[_this.state.selectedGame].game.name, _this.state.numPlayers);
});
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = props.games[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var game = _step.value;
var game_details = game.game;
if (!game_details.minPlayers) {
game_details.minPlayers = 1;
}
if (!game_details.maxPlayers) {
game_details.maxPlayers = 4;
}
console.assert(game_details.maxPlayers >= game_details.minPlayers);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator["return"] != null) {
_iterator["return"]();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
_this.state = {
selectedGame: 0,
numPlayers: props.games[0].game.minPlayers
};
return _this;
}
_createClass(LobbyCreateRoomForm, [{
key: "render",
value: function render() {
var _this2 = this;
return React.createElement("div", null, React.createElement("select", {
value: this.state.selectedGame,
onChange: function onChange(evt) {
return _this2.onChangeSelectedGame(evt);
}
}, this.props.games.map(this._createGameNameOption)), React.createElement("span", null, "Players:"), React.createElement("select", {
value: this.state.numPlayers,
onChange: this.onChangeNumPlayers
}, this._createNumPlayersRange(this.props.games[this.state.selectedGame].game).map(this._createNumPlayersOption)), React.createElement("span", {
className: "buttons"
}, React.createElement("button", {
onClick: this.onClickCreate
}, "Create")));
}
}]);
return LobbyCreateRoomForm;
}(React.Component);
_defineProperty(LobbyCreateRoomForm, "propTypes", {
games: PropTypes.array.isRequired,
createGame: PropTypes.func.isRequired
});
var LobbyPhases = {
ENTER: 'enter',
PLAY: 'play',
LIST: 'list'
};
/**
* Lobby
*
* React lobby component.
*
* @param {Array} gameComponents - An array of Board and Game objects for the supported games.
* @param {string} lobbyServer - Address of the lobby server (for example 'localhost:8000').
* If not set, defaults to the server that served the page.
* @param {string} gameServer - Address of the game server (for example 'localhost:8001').
* If not set, defaults to the server that served the page.
* @param {function} clientFactory - Function that is used to create the game clients.
* @param {number} refreshInterval - Interval between server updates (default: 2000ms).
* @param {bool} debug - Enable debug information (default: false).
*
* Returns:
* A React component that provides a UI to create, list, join, leave, play or spectate game instances.
*/
var Lobby =
/*#__PURE__*/
function (_React$Component) {
_inherits(Lobby, _React$Component);
function Lobby(_props) {
var _this;
_classCallCheck(this, Lobby);
_this = _possibleConstructorReturn(this, _getPrototypeOf(Lobby).call(this, _props));
_defineProperty(_assertThisInitialized(_this), "state", {
phase: LobbyPhases.ENTER,
playerName: 'Visitor',
runningGame: null,
errorMsg: '',
credentialStore: {}
});
_defineProperty(_assertThisInitialized(_this), "_createConnection", function (props) {
var name = _this.state.playerName;
_this.connection = LobbyConnection({
server: props.lobbyServer,
gameComponents: props.gameComponents,
playerName: name,
playerCredentials: _this.state.credentialStore[name]
});
});
_defineProperty(_assertThisInitialized(_this), "_updateCredentials", function (playerName, credentials) {
_this.setState(function (prevState) {
// clone store or componentDidUpdate will not be triggered
var store = Object.assign({}, prevState.credentialStore);
store[[playerName]] = credentials;
return {
credentialStore: store
};
});
});
_defineProperty(_assertThisInitialized(_this), "_updateConnection", async function () {
await _this.connection.refresh();
_this.forceUpdate();
});
_defineProperty(_assertThisInitialized(_this), "_enterLobby", function (playerName) {
_this.setState({
playerName: playerName,
phase: LobbyPhases.LIST
});
});
_defineProperty(_assertThisInitialized(_this), "_exitLobby", async function () {
await _this.connection.disconnect();
_this.setState({
phase: LobbyPhases.ENTER,
errorMsg: ''
});
});
_defineProperty(_assertThisInitialized(_this), "_createRoom", async function (gameName, numPlayers) {
try {
await _this.connection.create(gameName, numPlayers);
await _this.connection.refresh(); // rerender
_this.setState({});
} catch (error) {
_this.setState({
errorMsg: error.message
});
}
});
_defineProperty(_assertThisInitialized(_this), "_joinRoom", async function (gameName, gameID, playerID) {
try {
await _this.connection.join(gameName, gameID, playerID);
await _this.connection.refresh();
_this._updateCredentials(_this.connection.playerName, _this.connection.playerCredentials);
} catch (error) {
_this.setState({
errorMsg: error.message
});
}
});
_defineProperty(_assertThisInitialized(_this), "_leaveRoom", async function (gameName, gameID) {
try {
await _this.connection.leave(gameName, gameID);
await _this.connection.refresh();
_this._updateCredentials(_this.connection.playerName, _this.connection.playerCredentials);
} catch (error) {
_this.setState({
errorMsg: error.message
});
}
});
_defineProperty(_assertThisInitialized(_this), "_startGame", function (gameName, gameOpts) {
var gameCode = _this.connection._getGameComponents(gameName);
if (!gameCode) {
_this.setState({
errorMsg: 'game ' + gameName + ' not supported'
});
return;
}
var multiplayer = undefined;
if (gameOpts.numPlayers > 1) {
if (_this.props.gameServer) {
multiplayer = SocketIO({
server: _this.props.gameServer
});
} else {
multiplayer = SocketIO();
}
}
if (gameOpts.numPlayers == 1) {
var maxPlayers = gameCode.game.maxPlayers;
var bots = {};
for (var i = 1; i < maxPlayers; i++) {
bots[i + ''] = MCTSBot;
}
multiplayer = Local({
bots: bots
});
}
var app = _this.props.clientFactory({
game: gameCode.game,
board: gameCode.board,
debug: _this.props.debug,
multiplayer: multiplayer
});
var game = {
app: app,
gameID: gameOpts.gameID,
playerID: gameOpts.numPlayers > 1 ? gameOpts.playerID : '0',
credentials: _this.connection.playerCredentials
};
_this.setState({
phase: LobbyPhases.PLAY,
runningGame: game
});
});
_defineProperty(_assertThisInitialized(_this), "_exitRoom", function () {
_this.setState({
phase: LobbyPhases.LIST,
runningGame: null
});
});
_defineProperty(_assertThisInitialized(_this), "_getPhaseVisibility", function (phase) {
return _this.state.phase !== phase ? 'hidden' : 'phase';
});
_defineProperty(_assertThisInitialized(_this), "renderRooms", function (rooms, playerName) {
return rooms.map(function (room) {
var gameID = room.gameID,
gameName = room.gameName,
players = room.players;
return React.createElement(LobbyRoomInstance, {
key: 'instance-' + gameID,
room: {
gameID: gameID,
gameName: gameName,
players: Object.values(players)
},
playerName: playerName,
onClickJoin: _this._joinRoom,
onClickLeave: _this._leaveRoom,
onClickPlay: _this._startGame
});
});
});
_this._createConnection(_this.props);
setInterval(_this._updateConnection, _this.props.refreshInterval);
return _this;
}
_createClass(Lobby, [{
key: "componentDidMount",
value: function componentDidMount() {
var cookie = Cookies.load('lobbyState') || {};
if (cookie.phase && cookie.phase === LobbyPhases.PLAY) {
cookie.phase = LobbyPhases.LIST;
}
this.setState({
phase: cookie.phase || LobbyPhases.ENTER,
playerName: cookie.playerName || 'Visitor',
credentialStore: cookie.credentialStore || {}
});
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps, prevState) {
var name = this.state.playerName;
var creds = this.state.credentialStore[name];
if (prevState.phase !== this.state.phase || prevState.credentialStore[name] !== creds || prevState.playerName !== name) {
this._createConnection(this.props);
this._updateConnection();
var cookie = {
phase: this.state.phase,
playerName: name,
credentialStore: this.state.credentialStore
};
Cookies.save('lobbyState', cookie, {
path: '/'
});
}
}
}, {
key: "render",
value: function render() {
var _this$props = this.props,
gameComponents = _this$props.gameComponents,
renderer = _this$props.renderer;
var _this$state = this.state,
errorMsg = _this$state.errorMsg,
playerName = _this$state.playerName,
phase = _this$state.phase,
runningGame = _this$state.runningGame;
if (renderer) {
return renderer({
errorMsg: errorMsg,
gameComponents: gameComponents,
rooms: this.connection.rooms,
phase: phase,
playerName: playerName,
runningGame: runningGame,
handleEnterLobby: this._enterLobby,
handleExitLobby: this._exitLobby,
handleCreateRoom: this._createRoom,
handleJoinRoom: this._joinRoom,
handleLeaveRoom: this._leaveRoom,
handleExitRoom: this._exitRoom,
handleRefreshRooms: this._updateConnection,
handleStartGame: this._startGame
});
}
return React.createElement("div", {
id: "lobby-view",
style: {
padding: 50
}
}, React.createElement("div", {
className: this._getPhaseVisibility(LobbyPhases.ENTER)
}, React.createElement(LobbyLoginForm, {
key: playerName,
playerName: playerName,
onEnter: this._enterLobby
})), React.createElement("div", {
className: this._getPhaseVisibility(LobbyPhases.LIST)
}, React.createElement("p", null, "Welcome, ", playerName), React.createElement("div", {
className: "phase-title",
id: "game-creation"
}, React.createElement("span", null, "Create a room:"), React.createElement(LobbyCreateRoomForm, {
games: gameComponents,
createGame: this._createRoom
})), React.createElement("p", {
className: "phase-title"
}, "Join a room:"), React.createElement("div", {
id: "instances"
}, React.createElement("table", null, React.createElement("tbody", null, this.renderRooms(this.connection.rooms, playerName))), React.createElement("span", {
className: "error-msg"
}, errorMsg, React.createElement("br", null))), React.createElement("p", {
className: "phase-title"
}, "Rooms that become empty are automatically deleted.")), React.createElement("div", {
className: this._getPhaseVisibility(LobbyPhases.PLAY)
}, runningGame && React.createElement(runningGame.app, {
gameID: runningGame.gameID,
playerID: runningGame.playerID,
credentials: runningGame.credentials
}), React.createElement("div", {
className: "buttons",
id: "game-exit"
}, React.createElement("button", {
onClick: this._exitRoom
}, "Exit game"))), React.createElement("div", {
className: "buttons",
id: "lobby-exit"
}, React.createElement("button", {
onClick: this._exitLobby
}, "Exit lobby")));
}
}]);
return Lobby;
}(React.Component);
_defineProperty(Lobby, "propTypes", {
gameComponents: PropTypes.array.isRequired,
lobbyServer: PropTypes.string,
gameServer: PropTypes.string,
debug: PropTypes.bool,
clientFactory: PropTypes.func,
refreshInterval: PropTypes.number
});
_defineProperty(Lobby, "defaultProps", {
debug: false,
clientFactory: Client,
refreshInterval: 2000
});
export { Client, Lobby };
|
Resourceful.BelongsToObject = Ember.ObjectProxy.extend({
primaryResourceClass: null,
foreignResource: null,
primaryKey: 'id',
foreignKey: null,
init: function() {
this.set('content', {});
this._super();
this.addObserver('_primaryResourceArray.@each.' + this.get('primaryKey'), this._updateContent);
this.addObserver('foreignResource.' + this.get('foreignKey'), this._updateContent);
this._updateContent();
},
_updateContent: function() {
var primaryKey, foreignKeyValue, primaryResource, _this = this;
primaryKey = this.get('primaryKey');
foreignKeyValue = this._foreignKeyValue();
primaryResource = this.get('_primaryResourceArray').findProperty(primaryKey, foreignKeyValue);
this.set('content', primaryResource);
},
_primaryResourceArray: function() {
return Resourceful.collectionFor(this.get('primaryResourceClass'));
}.property('primaryResourceClass'),
_foreignKeyValue: function() {
return this.get('foreignResource.' + this.get('foreignKey'));
}
});
|
'use strict';
// Load modules
const Hoek = require('hoek');
const Decoder = require('./decoder');
const Encoder = require('./encoder');
exports.decode = Decoder.decode;
exports.encode = Encoder.encode;
exports.Decoder = Decoder.Decoder;
exports.Encoder = Encoder.Encoder;
// Base64url (RFC 4648) encode
exports.base64urlEncode = function (value, encoding) {
Hoek.assert(typeof value === 'string' || Buffer.isBuffer(value), 'value must be string or buffer');
const buf = (Buffer.isBuffer(value) ? value : Buffer.from(value, encoding || 'binary'));
return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
};
// Base64url (RFC 4648) decode
exports.base64urlDecode = function (value, encoding) {
if (typeof value !== 'string') {
throw new Error('Value not a string');
}
if (!/^[\w\-]*$/.test(value)) {
throw new Error('Invalid character');
}
const buf = Buffer.from(value, 'base64');
return (encoding === 'buffer' ? buf : buf.toString(encoding || 'binary'));
};
|
module.exports = {
"selector": "//MemberExpression",
"version": "3",
"en": {
"name": "MemberExpression"
}
}; |
var express = require('express');
var app = express();
var router = express.Router();
var auth = require('../lib/api/auth');
router.use('/auth', auth);
module.exports = router;
|
var app = new Vue({
el:'#app',
data:{
indexUpdate: -1,
isActive: false,
newTipoProduto:{
id:'',
descricao:''
},
tiposProduto:[]
},
mounted:function(){
this.findAll();
},
methods: {
findAll: function () {
this.$http.get("http://localhost:8080/tipoProduto/private/")
.then(function (res) {
this.tiposProduto = res.body;
}, function (res) {
console.log(res);
});
},
updateTipoProduto: function () {
this.$http.put("http://localhost:8080/tipoProduto/private/edit", this.newTipoProduto)
.then(function(res) {
this.findAll();
}, function (res){
window.alert(res.body.mensagem);
});
},
save:function(){
if(this.newTipoProduto.remoteId==""){
this.add();
}else {
this.updateTipoProduto();
}
this.clear();
},
add: function () {
this.$http.post("http://localhost:8080/tipoProduto/private/savenofile", this.newTipoProduto)
.then(function(res) {
this.findAll();
}, function (res){
window.alert(res.body.mensagem);
});
},
deleteTipoProduto: function (i) {
this.$http.delete("http://localhost:8080/tipoProduto/private/" + (i))
.then(function (res) {
this.findAll();
}, function (res) {
console.log(res);
});
},
prepareUpdate :function(i){
this.newTipoProduto= Vue.util.extend({},this.tiposProduto[i]);
},
clear: function () {
this.newTipoProduto = {
id:'',
descricao:''
}
}
}
}) |
/*
* Copyright (c) Maximilian Antoni <max@javascript.studio>
*/
'use strict';
const request = require('./request');
const BUILD_STATUS = {
CREATED: 'Build pending',
ANALYZING: 'Analyzing',
ERROR: 'Build error',
FAILED: 'Build completed with issues',
SUCCESS: 'Build completed. No issues found.'
};
const STATUS_TIMEOUTS = {
CREATED: 35000,
ANALYZING: 35000
};
const FINAL = {
ERROR: true,
FAILED: true,
SUCCESS: true
};
const SYMBOLS = {
ERROR: '🚨 ',
FAILED: '⚠️ ',
SUCCESS: '✅ '
};
module.exports = function (config, report_number, argv, spinner, callback) {
const start = Date.now();
let delay = 250;
let path = `/uploads/${report_number}`;
if (argv.exceptions) {
path += '?exceptions=1';
}
function load_report() {
request(config, {
path,
timeout: 10000,
expect: 200
}, null, (err, json) => {
if (err) {
callback(err);
return;
}
let status = BUILD_STATUS[json.status];
if (!status) {
callback(new Error(`Unknown build status "${json.status}"`));
return;
}
if (json.message) {
status = `${status} - ${json.message}`;
}
spinner.text = status;
if (FINAL[json.status]) {
spinner.stopAndPersist({
symbol: SYMBOLS[json.status]
});
callback(null, json);
} else if (Date.now() - start > STATUS_TIMEOUTS[json.status]) {
callback(new Error('Timeout'));
} else {
delay = Math.min(delay * 2, 4000);
setTimeout(load_report, delay);
}
});
}
setTimeout(load_report, delay);
};
|
const {module, test} = QUnit;
import PostNodeBuilder from 'content-kit-editor/models/post-node-builder';
import SectionParser from 'content-kit-editor/parsers/section';
import Helpers from '../../test-helpers';
let builder, parser;
module('Unit: Parser: SectionParser', {
beforeEach() {
builder = new PostNodeBuilder();
parser = new SectionParser(builder);
},
afterEach() {
builder = null;
parser = null;
}
});
test('#parse parses simple dom', (assert) => {
let element = Helpers.dom.makeDOM(t =>
t('p', {}, [
t.text('hello there'),
t('b', {}, [
t.text('i am bold')
])
])
);
const section = parser.parse(element);
assert.equal(section.tagName, 'p');
assert.equal(section.markers.length, 2, 'has 2 markers');
const [m1, m2] = section.markers.toArray();
assert.equal(m1.value, 'hello there');
assert.equal(m2.value, 'i am bold');
assert.ok(m2.hasMarkup('b'), 'm2 is bold');
});
test('#parse parses nested markups', (assert) => {
let element = Helpers.dom.makeDOM(t =>
t('p', {}, [
t('b', {}, [
t.text('i am bold'),
t('i', {}, [
t.text('i am bold and italic')
]),
t.text('i am bold again')
])
])
);
const section = parser.parse(element);
assert.equal(section.markers.length, 3, 'has 3 markers');
const [m1, m2, m3] = section.markers.toArray();
assert.equal(m1.value, 'i am bold');
assert.equal(m2.value, 'i am bold and italic');
assert.equal(m3.value, 'i am bold again');
assert.ok(m1.hasMarkup('b'), 'm1 is bold');
assert.ok(m2.hasMarkup('b') && m2.hasMarkup('i'), 'm2 is bold and i');
assert.ok(m3.hasMarkup('b'), 'm3 is bold');
assert.ok(!m1.hasMarkup('i') && !m3.hasMarkup('i'), 'm1 and m3 are not i');
});
test('#parse ignores non-markup elements like spans', (assert) => {
let element = Helpers.dom.makeDOM(t =>
t('p', {}, [
t('span', {}, [
t.text('i was in span')
])
])
);
const section = parser.parse(element);
assert.equal(section.tagName, 'p');
assert.equal(section.markers.length, 1, 'has 1 markers');
const [m1] = section.markers.toArray();
assert.equal(m1.value, 'i was in span');
});
test('#parse reads attributes', (assert) => {
let element = Helpers.dom.makeDOM(t =>
t('p', {}, [
t('a', {href: 'google.com'}, [
t.text('i am a link')
])
])
);
const section = parser.parse(element);
assert.equal(section.markers.length, 1, 'has 1 markers');
const [m1] = section.markers.toArray();
assert.equal(m1.value, 'i am a link');
assert.ok(m1.hasMarkup('a'), 'has "a" markup');
assert.equal(m1.getMarkup('a').attributes.href, 'google.com');
});
test('#parse joins contiguous text nodes separated by non-markup elements', (assert) => {
let element = Helpers.dom.makeDOM(t =>
t('p', {}, [
t('span', {}, [
t.text('span 1')
]),
t('span', {}, [
t.text('span 2')
])
])
);
const section = parser.parse(element);
assert.equal(section.tagName, 'p');
assert.equal(section.markers.length, 1, 'has 1 markers');
const [m1] = section.markers.toArray();
assert.equal(m1.value, 'span 1span 2');
});
// test: a section can parse dom
// test: a section can clear a range:
// * truncating the markers on the boundaries
// * removing the intermediate markers
// * connecting (but not joining) the truncated boundary markers
|
test('.linearEccentricity()', 10, function () {
var c1 = new MathLib.Conic([[1, 0, 0], [0, 1, 0], [0, 0, -1]]),
c2 = new MathLib.Conic([[2, 0, 0], [0, 2, 0], [0, 0, -2]]),
e1 = new MathLib.Conic([[4, 0, 0], [0, 3, 0], [0, 0, -1]]),
e2 = new MathLib.Conic([[8, 0, 0], [0, 6, 0], [0, 0, -2]]),
p1 = new MathLib.Conic([[1, 0, 0], [0, 0, -0.5], [0, -0.5, 0]]),
p2 = new MathLib.Conic([[2, 0, 0], [0, 0, -1], [0, -1, 0]]),
h1 = new MathLib.Conic([[4, 0, 0], [0, -3, 0], [0, 0, -1]]),
h2 = new MathLib.Conic([[8, 0, 0], [0, -6, 0], [0, 0, -2]]),
deg1 = new MathLib.Conic([[1, 1, 0], [1, 1, 0], [0, 0, -1]]),
deg2 = new MathLib.Conic([[1, 1, 0], [1, 2, 0], [0, 0, 0]]);
equal(c1.linearEccentricity(), 0, 'circle.linearEccentricity()');
equal(c2.linearEccentricity(), 0, 'circle.linearEccentricity()');
equal(e1.linearEccentricity(), 0.28867513459481287, 'ellipse.linearEccentricity()');
equal(e2.linearEccentricity(), 0.28867513459481287, 'ellipse.linearEccentricity()');
equal(p1.linearEccentricity(), 1 / 4, 'parabola.linearEccentricity()');
equal(p2.linearEccentricity(), 1 / 4, 'parabola.linearEccentricity()');
equal(h1.linearEccentricity(), Math.sqrt(1 / 3 + 1 / 4), 'hyperbola.linearEccentricity()');
equal(h2.linearEccentricity(), Math.sqrt(1 / 3 + 1 / 4), 'hyperbola.linearEccentricity()');
equal(deg1.linearEccentricity(), undefined, 'degeneratedConic.linearEccentricity() = undefined');
equal(deg2.linearEccentricity(), undefined, 'degeneratedConic.linearEccentricity() = undefined');
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.