code
stringlengths 2
1.05M
|
|---|
var methodAliases = require('./method-map');
module.exports = function getMethodName(categoryName, methodAlias) {
return methodAliases[categoryName] && methodAliases[categoryName][methodAlias];
};
|
define([
"utils/range"
],function(Range) {
"use strict";
function BoundingBox(position, width, height) {
this.position = position;
this.width = width;
this.height = height;
this.rangeX = new Range(position.x, position.x + width);
this.rangeY = new Range(position.y, position.y + width);
}
BoundingBox.prototype.setPosition = function(position) {
this.position = position;
return updateRanges(this);
};
BoundingBox.prototype.move = function(velocity) {
this.position.move(velocity);
return updateRanges(this);
};
BoundingBox.prototype.setWidth = function(width) {
this.width = width;
return updateRanges(this);
};
BoundingBox.prototype.setHeight = function(height) {
this.height = height;
return updateRanges(this);
};
/**
* Is this bounding box colliding with another?
*
* @param {BoundingBox} other
* @return bool
*/
BoundingBox.prototype.isColliding = function(other) {
var isCollidingX = this.rangeX.intersects(other.rangeX),
isCollidingY = this.rangeY.intersects(other.rangeY);
return isCollidingX && isCollidingY;
};
BoundingBox.prototype.toString = function() {
return "BoundingBox(rangeX = " + this.rangeX + ", rangeY = " + this.rangeY + ")";
};
function updateRanges(boundingBox) {
var pos = boundingBox.position;
boundingBox.rangeX.update(pos.x, pos.x + boundingBox.width);
boundingBox.rangeY.update(pos.y, pos.y + boundingBox.height);
return boundingBox;
}
return BoundingBox;
});
|
const chai = require('chai');
const { MongoClient } = require('mongodb');
const bson = require('bson');
chai.use(require('chai-as-promised'));
chai.use(require('chai-datetime'));
const expect = chai.expect;
const Model = require('../lib/model');
const cosaDb = require('../lib/db');
const { sleep, times } = require('omnibelt');
const getMongoClient = () => {
return MongoClient.connect(process.env.COSA_DB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
};
const cleanUpDb = async (client, db, close = true) => {
await Promise.all([ 'mocha_test', 'mocha_save_test', 'mocha_remove_test' ].map((cName) => {
const collection = db.collection(cName);
return collection.deleteMany();
}));
if (close) { await client.close(); }
};
after(async () => {
if (cosaDb._client) {
await cosaDb._client.close();
}
});
describe('Model', () => {
let _db, client;
beforeEach(async () => {
client = await getMongoClient();
_db = await client.db('test');
return cleanUpDb(client, _db, false);
});
afterEach(() => {
return cleanUpDb(client, _db);
});
const Immutable = require('../lib/immutable');
const FullTestModel = require('./support/full-test-model');
describe('.define()', () => {
it('should return a model definition', () => {
const ModelA = Model.define({
name: 'MyModelA',
collection: 'mocha_test',
properties: {
_type: { type: 'string', enum: ['A', 'B'], default: 'A' },
strA: { type: 'string' }
},
methods: {
blah: function() {
return 'blah';
}
}
});
expect(ModelA.create).to.be.a('function');
expect(ModelA.extend).to.be.a('function');
expect(ModelA.count).to.be.a('function');
expect(ModelA.find).to.be.a('function');
expect(ModelA.findOne).to.be.a('function');
expect(ModelA.remove).to.be.a('function');
expect(ModelA.__collectionName).to.equal('mocha_test');
expect(ModelA.__name).to.equal('MyModelA');
});
});
describe('.get()', () => {
it('should return a value at the given path', () => {
const model = FullTestModel.create({
str: 'foo',
obj: { deep: { blah: 'blah' } }
});
expect(model.get('str')).to.equal('foo');
expect(model.get('obj.deep.blah')).to.equal('blah');
});
});
describe('.set()', () => {
it('should except a path and value and return a new model', () => {
const model = FullTestModel.create({
str: 'foo',
obj: { deep: { blah: 'blah' } }
});
const model2 = model.set('obj.deep.blah', 'boo');
expect(FullTestModel.isA(model2)).to.equal(true);
expect(model.get('obj.deep.blah')).to.equal('blah');
expect(model2.get('obj.deep.blah')).to.equal('boo');
});
it('should except an object of values to assign and return a new model', () => {
const model = FullTestModel.create({});
const model2 = model.set({
str: 'foo',
obj: { deep: { blah: 'blah' } }
});
expect(FullTestModel.isA(model2)).to.equal(true);
expect(model2.fooString('str is set to {str}')).to.equal('str is set to foo');
expect(model.get('str')).to.be.oneOf([ null, undefined ]);
expect(model.get('obj.deep.blah')).to.be.oneOf([ null, undefined ]);
expect(model2.get('str')).to.equal('foo');
expect(model2.get('obj.deep.blah')).to.equal('blah');
});
});
describe('.del()', () => {
it('should delete the var at the given path and return a new model', () => {
const model = FullTestModel.create({
str: 'foo',
obj: { deep: { blah: 'blah' } }
});
const model2 = model.del('str');
const model3 = model.del('obj.deep.blah');
expect(FullTestModel.isA(model2)).to.equal(true);
expect(FullTestModel.isA(model3)).to.equal(true);
expect(model.get('str')).to.equal('foo');
expect(model2.get('str')).to.be.oneOf([ null, undefined ]);
expect(model.get('obj.deep.blah')).to.equal('blah');
expect(model3.get('obj.deep.blah')).to.be.oneOf([ null, undefined ]);
});
});
describe('.has()', () => {
it('should return true if the model contains a value at the given path', () => {
const model = FullTestModel.create({
str: 'foo',
obj: { deep: { blah: 'blah' } }
});
expect(model.has('str')).to.equal(true);
expect(model.has('obj.deep.blah')).to.equal(true);
});
});
describe('.is()', function() {
it('should return false if one object is null and the other is a model', () => {
const obj = null;
const modelA = Model.define({
name: 'ModelA',
collection: 'mocha_test',
properties: {
str: { type: 'string' }
}
}).create({ str: 'foo' });
expect(modelA.is(obj)).to.equal(false);
});
it('should return true if both objects reference the same doc', () => {
const modelA = Model.define({
name: 'ModelA',
collection: 'mocha_test',
properties: {
str: { type: 'string' }
}
}).create({ str: 'foo' });
let m = modelA;
expect(modelA.is(m)).to.equal(true);
m = modelA.set('str', 'blah');
expect(modelA.is(m)).to.equal(false);
});
it('should return false if the documents do not match, and should return true when the do', async () => {
const modelA = Model.define({
name: 'ModelA',
collection: 'mocha_test',
properties: {
str: { type: 'string' }
}
}).create({ str: 'foo' });
const modelB = Model.define({
name: 'ModelB',
collection: 'mocha_test',
properties: {
str: { type: 'string' }
}
}).create({ str: 'foo' });
expect(modelA.is(modelB)).to.equal(false);
const modelA2 = await modelA.save();
expect(modelA.is(modelA2)).to.equal(false);
const m2 = modelA2.set('str', 'bar');
expect(modelA2.is(m2)).to.equal(true);
});
});
describe('.equals()', function() {
it('should return true if both objects reference the same doc and version', async () => {
const modelA = Model.define({
name: 'ModelA',
collection: 'mocha_test',
properties: {
str: { type: 'string' }
}
}).create({ str: 'foo' });
const m = modelA.set('str', 'blah');
expect(modelA.equals(m)).to.equal(false);
const modelA2 = await modelA.save();
const m2 = modelA2.set('num', 10);
expect(modelA2.equals(m2)).to.equal(false);
});
});
describe('.isNew()', function() {
it('should return true if the model is new', async () => {
const model = FullTestModel.create({
str: 'foo'
});
expect(model.isNew()).to.equal(true);
const model2 = await model.save();
expect(model2.isNew()).to.equal(false);
});
});
describe('.saveWithId()', function() {
it('should save with a given ID', async () => {
const id = new bson.ObjectID('1234abcd103f8e485c9d2019');
const model = await FullTestModel.create({
str: 'foo'
}).saveWithId(id);
expect(model._id.toString()).to.equal('1234abcd103f8e485c9d2019');
});
it('should error when trying to update an object', async () => {
const id = new bson.ObjectID('1234abcd103f8e485c9d2019');
const newId = new bson.ObjectID('5678abcd103f8e485c9d9000');
const model = await FullTestModel.create({
str: 'foo'
}).saveWithId(id);
const error = await model.saveWithId(newId).catch((e) => { return e; });
expect(error.name).to.equal('Error');
expect(error.message).to.equal('saveWithId must receive a newly created object');
});
});
describe('.isModified()', () => {
it('should return true if the given path is modified', () => {
const model = FullTestModel.create({
str: 'foo',
obj: { deep: { blah: 'blah' } }
});
const m = model.set('arr', [1, 2, 3]);
expect(m.isModified('arr')).to.equal(true);
expect(m.isModified('str')).to.equal(false);
const m2 = model.set('obj.deep.blah', 'boo');
expect(m2.isModified('obj')).to.equal(true);
expect(m2.isModified('obj.deep')).to.equal(true);
expect(m2.isModified('obj.deep.blah')).to.equal(true);
});
it('should return true if no path is given and the object has been modified', () => {
const model = FullTestModel.create({
str: 'foo',
obj: { deep: { blah: 'blah' } }
});
expect(model.isModified()).to.equal(false);
const m = model.set('arr', [1, 2, 3]);
expect(m.isModified()).to.equal(true);
});
});
describe('.toJSON()', () => {
it('should return valid json', () => {
const DeepArrayModel = Model.define({
collection: 'mocha_test',
properties: {
arr: {
type: 'array',
items: {
type: 'object',
properties: {
oid: { type: 'objectid' }
}
}
},
nullVal: { type: '*' }
}
});
const model = DeepArrayModel.create({
arr: [
{ oid: bson.ObjectId('abdfabdfabdfabdfabdfabdf') },
{ oid: bson.ObjectId('abdfabdfabdfabdfabdfabdf') }
],
nullVal: null
});
expect(JSON.stringify(model.toJSON())).to.equal('{"arr":[{"oid":{"$oid":"abdfabdfabdfabdfabdfabdf"}},{"oid":{"$oid":"abdfabdfabdfabdfabdfabdf"}}],"nullVal":null}');
});
it('should except an extended option', () => {
const DeepArrayModel = Model.define({
collection: 'mocha_test',
properties: {
arr: {
type: 'array',
items: {
type: 'object',
properties: {
oid: { type: 'objectid' }
}
}
}
}
});
const model = DeepArrayModel.create({
arr: [
{ oid: bson.ObjectId('abdfabdfabdfabdfabdfabdf') },
{ oid: bson.ObjectId('abdfabdfabdfabdfabdfabdf') }
]
});
expect(JSON.stringify(model.toJSON({ extended: false }))).to.equal('{"arr":[{"oid":"abdfabdfabdfabdfabdfabdf"},{"oid":"abdfabdfabdfabdfabdfabdf"}]}');
});
it('should except an exclude option', () => {
const model = FullTestModel.create({
str: 'test string',
obj: { prop1: 'bar' }
});
const json = model.toJSON({ exclude: ['str', 'date'] });
expect(JSON.stringify(json)).to.equal('{"obj":{"prop1":"bar","propv":"bar.undefined"},"num":0,"bool":false,"virt":"test string.virtual"}');
});
it('should except an include option', () => {
const model = FullTestModel.create({
str: 'test string',
obj: { prop1: 'bar' }
});
const json = model.toJSON({ include: ['num', 'bool', 'virt'] });
expect(JSON.stringify(json)).to.equal('{"num":0,"bool":false,"virt":"test string.virtual"}');
});
it('should except a transform option', () => {
const model = FullTestModel.create({
str: 'test string'
});
const json = model.toJSON({
exclude: ['date'],
transform: function(obj) {
obj.str += ' TRANSFORMED!';
return obj;
}
});
expect(JSON.stringify(json)).to.equal('{"str":"test string TRANSFORMED!","num":0,"bool":false,"virt":"test string.virtual"}');
});
});
describe('.validate()', () => {
it('should reject promise if validation fails', async () => {
const model = FullTestModel.create({});
const error = await model.validate().catch((e) => { return e; });
expect(error.type).to.equal('Validation');
expect(error.name).to.equal('ValidationError');
expect(error.statusCode).to.equal(400);
expect(error.message).to.equal('"str" is required');
});
it('should resolve promise if validation succeeds', async () => {
const model = FullTestModel.create({ str: 'bar' });
const result = await model.validate();
expect(result).to.exist.and.to.be.an('object');
});
});
describe('db', function() {
const db = require('../lib/db');
it('should auto connect to db if connection lost', async () => {
const model = FullTestModel.create({
str: 'foo',
obj: { prop1: 'bar' }
});
const updatedModel = await model.save();
let count = await FullTestModel.count({ _id: updatedModel._id });
expect(count).to.equal(1);
await db._client.close();
count = await FullTestModel.count({ _id: updatedModel._id });
expect(count).to.equal(1);
});
});
describe('.save()', function() {
let model;
before(() => {
model = FullTestModel.create({
str: 'foo',
obj: { prop1: 'bar' }
});
});
it('should insert a new document', async () => {
const updatedModel = await model.save();
expect(updatedModel._id).to.be.a('object');
expect(updatedModel._etag).to.be.a('string');
const count = await FullTestModel.count({ _id: updatedModel._id });
expect(count).to.equal(1);
const collection = _db.collection('mocha_test');
const doc = await collection.findOne({ _id: updatedModel._id });
expect(updatedModel._etag).to.equal(doc._etag);
expect(updatedModel._id.toObject().toString()).to.equal(doc._id.toString());
expect(updatedModel.bool).to.equal(doc.bool);
expect(updatedModel.date).to.equalDate(doc.date);
expect(updatedModel.num).to.equal(doc.num);
expect(updatedModel.obj.toObject()).to.eql(doc.obj);
expect(updatedModel.str).to.equal(doc.str);
});
it('should update an existing document', async () => {
const newModel = await model.save();
const updatedModel = await newModel.set('str', 'test update').set('num', 2).save();
expect(updatedModel._id.toString()).to.equal(newModel._id.toString());
expect(updatedModel._etag).to.not.equal(newModel._etag);
const collection = _db.collection('mocha_test');
const doc = await collection.findOne({ _id: updatedModel._id });
expect(updatedModel._etag).to.equal(doc._etag);
expect(updatedModel._id.toObject().toString()).to.equal(doc._id.toString());
expect(updatedModel.bool).to.equal(doc.bool);
expect(updatedModel.date).to.equalDate(doc.date);
expect(updatedModel.num).to.equal(doc.num);
expect(updatedModel.obj.toObject()).to.eql(doc.obj);
expect(updatedModel.str).to.equal(doc.str);
});
it('should wait for the after save', async () => {
let afterSaveCalled = false;
const afterSaveModel = Model.define({
name: 'SaveTest',
collection: 'mocha_save_test',
properties: {
str: { type: 'string', required: true }
},
methods: {
afterSave: async function() {
await sleep(150);
afterSaveCalled = true;
}
}
});
await afterSaveModel.create({ str: 'hello' }).save({ waitAfterSave: true });
expect(afterSaveCalled).to.equal(true);
const collection = _db.collection('mocha_save_test');
const count = await collection.countDocuments();
expect(count).to.equal(1);
});
});
describe('.remove()', () => {
let model;
before(async () => {
model = FullTestModel.create({
str: 'test string',
obj: { prop1: 'bar' }
});
});
it('should remove the document', async () => {
const updatedModel = await model.save();
await updatedModel.remove();
const collection = _db.collection('mocha_test');
const count = await collection.countDocuments();
expect(count).to.equal(0);
});
it('should wait for the after remove', async () => {
let afterRemoveCalled = false;
const afterRemoveModel = Model.define({
name: 'RemoveTest',
collection: 'mocha_remove_test',
properties: {
str: { type: 'string', required: true }
},
methods: {
afterRemove: async function() {
await sleep(150);
afterRemoveCalled = true;
}
}
});
const testModel = await afterRemoveModel.create({ str: 'hello' }).save();
await testModel.remove({ waitAfterRemove: true });
expect(afterRemoveCalled).to.equal(true);
const collection = _db.collection('mocha_remove_test');
const count = await collection.countDocuments();
expect(count).to.equal(0);
});
});
describe('.reload', async () => {
it('should reload a model', async () => {
const model = FullTestModel.create({
str: 'test string',
obj: { prop1: 'bar' }
});
const updatedModel = await model.save();
const reloadedModel = await updatedModel.reload();
expect(reloadedModel.toObject()).to.deep.equal(updatedModel.toObject());
});
});
describe('.count()', () => {
let model;
before(async () => {
model = FullTestModel.create({
str: 'test string',
obj: { prop1: 'bar' }
});
});
it('should return the count of objects', async () => {
const updatedModel = await model.save();
const count = await FullTestModel.count({ _id: updatedModel._id });
expect(count).to.equal(1);
});
it('should return the count of objects with a skip or limit without a query', async () => {
await Promise.all([
FullTestModel.create({
str: 'test string',
obj: { prop1: 'bar' }
}).save(),
FullTestModel.create({
str: 'test string',
obj: { prop1: 'bar' }
}).save(),
FullTestModel.create({
str: 'test string',
obj: { prop1: 'bar' }
}).save(),
FullTestModel.create({
str: 'test string',
obj: { prop1: 'bar' }
}).save(),
FullTestModel.create({
str: 'test string',
obj: { prop1: 'bar' }
}).save()
]);
expect(await FullTestModel.count({}, { skip: 3 })).to.equal(2);
expect(await FullTestModel.count(undefined, { limit: 4 })).to.equal(4);
expect(await FullTestModel.count(null, { skip: 2, limit: 4 })).to.equal(3);
});
});
describe('.find()', () => {
let model;
before(async () => {
model = FullTestModel.create({
str: 'test string',
obj: { prop1: 'bar' }
});
});
it('should return a cursor to retrieve objects', async () => {
const updatedModel = await model.save();
const cursor = await FullTestModel.find({ _id: updatedModel._id });
const count = await cursor.count();
const obj = await cursor.next();
expect(count).to.equal(1);
expect(Immutable.isImmutableType(obj, 'FullTestModel')).to.equal(true);
});
it('should return an array if array option is given', async () => {
const updatedModel = await model.save();
const arr = await FullTestModel.find({ _id: updatedModel._id }, { array: true });
expect(Array.isArray(arr)).to.equal(true);
expect(arr.length).to.equal(1);
expect(Immutable.isImmutableType(arr[0], 'FullTestModel')).to.equal(true);
});
it('should perform reasonably on large finds', async () => {
const creations = [];
for (let i=0; i<1000; i++) {
creations.push(cosaDb.insert('mocha_test', {
aDate: new Date(Number(new Date('2019-03-11T04:55:00.000Z')) - i),
aString: 'a string',
aNumber: 1234,
anArray: ['a', {}, 2, true, [], bson.ObjectId(), new Date()],
aBoolean: true,
anObject: {
one: 1, two: false, three: {}, four: [], five: new Date(), six: bson.ObjectId(), seven: 'one two three four five six seven'
},
_etag: '"1e0-ilC0ScG/I4BHBDUJQZFa+TEv+B0"'
}));
}
await Promise.all(creations);
const PerfModel = Model.define({
name: 'PerfTest',
collection: 'mocha_test',
properties: {
aDate: { type: 'date' },
aString: { type: 'string' },
aNumber: { type: 'number' },
anArray: { type: 'array', items: { type: 'any' } },
aBoolean: { type: 'boolean' },
anObject: {
type: 'object',
properties: {
one: { type: 'number' },
two: { type: 'boolean' },
three: { type: 'object', properties: {} },
four: { type: 'array', items: { type: 'any' } },
five: { type: 'date' },
six: { type: 'objectid' },
seven: { type: 'string' }
}
}
}
});
let start = Date.now();
expect((await PerfModel.find({}, { array: true })).length).to.equal(1000);
const modelFindTime = Date.now() - start;
expect(modelFindTime).to.be.below(300); // generally below 200, but leaving some room
start = Date.now();
expect((await PerfModel.project({}, {}, { array: true })).length).to.equal(1000);
const projectFindTime = Date.now() - start;
expect(projectFindTime).to.be.below(200); // generally below 100 but leaving some room
});
});
describe('.findOne()', () => {
let model;
before(async () => {
model = FullTestModel.create({
str: 'test string',
obj: { prop1: 'bar' }
});
});
it('should return an object', async () => {
const updatedModel = await model.save();
const doc = await FullTestModel.findOne({ _id: updatedModel._id });
expect(doc).to.be.a('object');
expect(Immutable.isImmutableType(doc, 'FullTestModel'));
});
it('should return null if no document is found', async () => {
const doc = await FullTestModel.findOne({ _id: 'asdfasdfasdf' });
expect(doc).to.be.oneOf([ null, undefined ]);
});
});
describe('.update()', function() {
beforeEach(async () => {
await FullTestModel.create({ str: 'foo' }).save();
await FullTestModel.create({ str: 'bar' }).save();
return FullTestModel.create({ str: 'blah' }).save();
});
it('should partial update a single doc', async () => {
const result = await FullTestModel.update({}, { any: 'boo' });
expect(result.matchedCount).to.equal(1);
expect(result.modifiedCount).to.equal(1);
const doc = await FullTestModel.findOne({ str: 'foo' });
expect(doc.str).to.equal('foo');
expect(doc.any).to.equal('boo');
});
it('should partial update all docs', async () => {
const result = await FullTestModel.update({}, { any: 'any' }, { multiple: true });
expect(result.matchedCount).to.equal(3);
expect(result.modifiedCount).to.equal(3);
const docs = await FullTestModel.find({}, { sort: { str: 1 }, array: true });
expect(docs[0].str).to.equal('bar');
expect(docs[0].any).to.equal('any');
expect(docs[1].str).to.equal('blah');
expect(docs[1].any).to.equal('any');
expect(docs[2].str).to.equal('foo');
expect(docs[2].any).to.equal('any');
});
it('should replace single doc', async () => {
const result = await FullTestModel.update({}, { $set: { arr: ['a', 'b', 'c'] } }, { autoSet: false });
expect(result.matchedCount).to.equal(1);
expect(result.modifiedCount).to.equal(1);
const doc = await FullTestModel.find({ arr: ['a', 'b', 'c'] });
expect(doc.str).to.be.oneOf([ null, undefined ]);
});
});
describe('.distinct()', () => {
it('should return distinct key values', async () => {
const model = FullTestModel.create({
str: 'test string'
});
const model2 = FullTestModel.create({
str: 'another test string'
});
const model3 = FullTestModel.create({
str: 'test string'
});
await Promise.all([ model.save(), model2.save(), model3.save() ]);
const results = await FullTestModel.distinct('str');
expect(results).to.contain('test string', 'another test string');
});
});
describe('.aggregate()', () => {
it('should return results of aggregate pipeline', async () => {
const model = FullTestModel.create({
str: 'test string'
});
const model2 = FullTestModel.create({
str: 'another test string'
});
const model3 = FullTestModel.create({
str: 'test string'
});
await Promise.all([ model.save(), model2.save(), model3.save() ]);
const cursor = await FullTestModel.aggregate([
{ $group: { _id: '$str', count: { $sum: 1 } } }
]);
const results = await cursor.toArray();
expect(results.length).to.equal(2);
results.forEach(function(item) {
expect(item).to.contain.all.keys('_id', 'count');
expect(item).to.satisfy(function(val) {
return (val._id === 'test string' && val.count === 2) ||
(val._id === 'another test string' && val.count === 1);
});
});
});
});
describe('.remove() [static]', () => {
let model;
before(async () => {
model = FullTestModel.create({
str: 'test string',
obj: { prop1: 'bar' }
});
});
it('should remove a document', async () => {
const updatedModel = await model.save();
const id = updatedModel._id;
await FullTestModel.remove({ _id: updatedModel._id });
const collection = _db.collection('mocha_test');
const count = await collection.countDocuments({ _id: id });
expect(count).to.equal(0);
});
});
describe('.extend()', () => {
it('should allow extending of a model', () => {
const ModelA = Model.define({
name: 'ModelA',
abstract: true,
collection: 'mocha_test',
properties: {
_type: { type: 'string', enum: ['A', 'B'], default: 'A' },
strA: { type: 'string', default: 'A' }
},
methods: {
blah: function() {
return 'blah';
}
}
});
const ModelB = ModelA.extend({
name: 'ModelB',
where: { _type: 'B' },
properties: {
_type: { type: 'string', default: 'B', valid: 'B' },
strB: { type: 'string', default: 'B' }
}
});
const myModelA = ModelA.create({});
expect(myModelA.strA).to.equal('A');
expect(myModelA.strB).to.be.oneOf([ null, undefined ]);
const myModelB = ModelB.create({
strA: 'abc',
strB: '123'
});
expect(myModelB.strB).to.equal('123');
expect(myModelB.strA).to.equal('abc');
expect(myModelB.blah()).to.equal('blah');
});
});
describe('.beforeSave()', () => {
it('should execute before a model is saved', async () => {
let strToSave, options;
const HookedModel = Model.define({
name: 'HookedModel',
collection: 'mocha_test',
properties: {
str: { type: 'string' }
},
methods: {
beforeSave: function(opts) {
strToSave = this.str;
options = opts;
}
}
});
const model = HookedModel.create({ str: 'foo' });
expect(model.beforeSave).to.be.a('function');
await model.save({ randomOption: 'hello' });
expect(strToSave).to.equal('foo');
expect(options).to.deep.equal({ randomOption: 'hello', waitAfterSave: false });
});
it('should allow mutating model before saving', async () => {
const HookedModel = Model.define({
name: 'HookedModel',
collection: 'mocha_test',
properties: {
str: { type: 'string' }
},
methods: {
beforeSave: function() {
this.str += ' bar';
}
}
});
const model = HookedModel.create({ str: 'foo' });
expect(model.beforeSave).to.be.a('function');
const model2 = await model.save();
expect(model2.str).to.equal('foo bar');
});
});
describe('.afterSave()', () => {
it('should execute after a model is saved', async () => {
let strSaved = '';
let checkFunction;
const HookedModel = Model.define({
name: 'HookedModel',
collection: 'mocha_test',
properties: {
str: { type: 'string' }
},
methods: {
afterSave: function(...args) {
checkFunction(this, args);
strSaved = this.str;
}
}
});
const model = HookedModel.create({ str: 'foo' });
expect(model.afterSave).to.be.a('function');
let wasCalled = false;
checkFunction = function(instance, args) {
expect(instance.str).to.equal('foo');
expect(args[0]).to.equal(null);
expect(args[1]).to.deep.equal({ randomOption: 'hello', waitAfterSave: false });
wasCalled = true;
};
const m = await model.save({ randomOption: 'hello' });
expect(wasCalled).to.equal(true);
wasCalled = false;
checkFunction = function(instance, args) {
expect(instance.str).to.equal('bar');
expect(args[0].str).to.equal('foo');
expect(args[1]).to.deep.equal({ randomOption: 'goodbye', waitAfterSave: false });
wasCalled = true;
};
await m.set('str', 'bar').save({ randomOption: 'goodbye' });
expect(wasCalled).to.equal(true);
expect(strSaved).to.equal('bar');
});
});
describe('.beforeRemove()', () => {
it('should execute before a model is removed', async () => {
let strRemoved, options;
const HookedModel = Model.define({
name: 'HookedModel',
collection: 'mocha_test',
properties: {
str: { type: 'string' }
},
methods: {
beforeRemove: function(opts) {
strRemoved = this.str;
options = opts;
}
}
});
const model = HookedModel.create({ str: 'foo' });
expect(model.beforeRemove).to.be.a('function');
const m = await model.save();
await m.remove({ anotherOption: 'what' });
expect(strRemoved).to.equal('foo');
expect(options).to.deep.equal({ anotherOption: 'what', waitAfterRemove: false });
});
});
describe('.afterRemove()', () => {
it('should execute after a model is removed', async () => {
let strRemoved, options;
const HookedModel = Model.define({
name: 'HookedModel',
collection: 'mocha_test',
properties: {
str: { type: 'string' }
},
methods: {
afterRemove: function(opt) {
strRemoved = this.str;
options = opt;
}
}
});
const model = HookedModel.create({ str: 'foo' });
expect(model.afterRemove).to.be.a('function');
const m = await model.save();
await m.remove({ foo: 'bar' });
expect(strRemoved).to.equal('foo');
expect(options).to.deep.equal({ foo: 'bar', waitAfterRemove: false });
});
});
describe('.project()', () => {
it('should return cursor of projected values', async () => {
await FullTestModel.create({
str: 'test string',
obj: { prop1: 'bar' }
}).save();
const values = await FullTestModel.project({}, { str: 1 }, { array: 1 });
expect(values.length).to.equal(1);
expect(values[0].str).to.equal('test string');
});
});
describe('.forEachParallelLimitP', () => {
it('should iterate over a cursor in parallel', async () => {
await Promise.all(times(() => {
return FullTestModel.create({
str: 'test string',
obj: { prop1: 'bar' }
}).save();
}, 100));
const count = await FullTestModel.count();
const cursor = await FullTestModel.find();
let numOfTimesCalled = 0;
await cursor.forEachParallelLimitP(50, async (item) => {
expect(FullTestModel.isA(item)).to.equal(true);
await sleep(1);
numOfTimesCalled++;
});
expect(numOfTimesCalled).to.equal(count);
});
it('should iterate over a cursor in parallel', async () => {
await Promise.all(times(() => {
return FullTestModel.create({
str: 'test string',
obj: { prop1: 'bar' }
}).save();
}, 10));
const count = await FullTestModel.count();
const cursor = await FullTestModel.find();
let numOfTimesCalled = 0;
await cursor.forEachParallelLimitP(100, async (item) => {
expect(FullTestModel.isA(item)).to.equal(true);
await sleep(1);
numOfTimesCalled++;
});
expect(numOfTimesCalled).to.equal(count);
});
});
});
|
google.load("gdata", "1");
google.setOnLoadCallback(loadFeed);
var feedURL = "http://www.google.com/calendar/feeds/calendar%40ourladymotherchurch.com/public/full";
var calendarDiv = null;
var service = null;
function loadFeed() {
service = new google.gdata.calendar.CalendarService('OLMC');
var query = new google.gdata.calendar.CalendarEventQuery(feedURL);
query.setFutureEvents(true);
query.setOrderBy('starttime');
query.setSortOrder('ascending');
query.setMaxResults(5);
service.getEventsFeed(query, loadedFeed, handleError);
}
function handleError (error) {
console.log("Couldn't fetch events: " + error);
}
function loadedFeed (result) {
var entries = result.feed.getEntries();
if (!entries.length) {
var calendarDiv = getCalendar();
calendarDiv.innerHTML = "<p id=\"noEvents\">No upcoming events found</p>";
return;
}
var lastMonth = -1;
for (var n = 0; n < entries.length; n++) {
var entry = entries[n];
var title = entry.getTitle().getText();
var desc = entry.getContent().getText();
var times = entry.getTimes();
var firstTime = null;
if (times.length > 0) {
firstTime = times[0].getStartTime();
}
var date = firstTime.getDate();
var day = date.getDate();
var month = date.getMonth();
if (month != lastMonth) {
insertHeader(nameForMonth(month));
lastMonth = month;
}
var time = null;
if (!firstTime.isDateOnly()) {
time = formatShortTime(date);
}
addEvent(title, day, desc, time);
}
}
function insertHeader (month) {
var header = document.createElement("div");
header.className = "header";
header.innerHTML = '<p>' + month + '</p>';
getCalendar().appendChild(header);
}
function addEvent (title, day, desc, time) {
var event = document.createElement("div");
event.className = "event";
var month = document.createElement("div");
month.className = "month";
month.innerHTML = '<p>' + day + '</p>';
var info = document.createElement("div");
info.className = "info";
var clearFix = document.createElement("div");
clearFix.className = "clearFix";
var titleP = document.createElement("p");
titleP.className = "title";
titleP.innerHTML = title;
var subtitle = null;
if (desc) {
subtitle = desc;
if (time) {
subtitle += (" - " + time);
}
}
else if (time) {
subtitle = time;
}
var subtitleP = document.createElement("p");
subtitleP.className = "subtitle";
subtitleP.innerHTML = subtitle ? subtitle : "";
info.appendChild(titleP);
info.appendChild(subtitleP);
event.appendChild(month);
event.appendChild(info);
event.appendChild(clearFix);
getCalendar().appendChild(event);
}
/* Utility */
function getCalendar() {
if (!calendarDiv) {
calendarDiv = document.getElementById("calendar");
var throbber = document.getElementById("throbber");
calendarDiv.removeChild(throbber);
}
return calendarDiv;
}
function nameForMonth (month) {
if (month == 0) {
return "January";
}
else if (month == 1) {
return "February";
}
else if (month == 2) {
return "March";
}
else if (month == 3) {
return "April";
}
else if (month == 4) {
return "May";
}
else if (month == 5) {
return "June";
}
else if (month == 6) {
return "July";
}
else if (month == 7) {
return "August";
}
else if (month == 8) {
return "September";
}
else if (month == 9) {
return "October";
}
else if (month == 10) {
return "November";
}
return "December";
}
function formatShortTime (date) {
var rawHours = date.getHours();
var rawMinutes = date.getMinutes();
var hours = rawHours > 12 ? rawHours - 12 : rawHours;
var minutes = padNumber(rawMinutes);
var suffix = rawHours > 11 ? "PM" : "AM";
return hours + ":" + minutes + " " + suffix;
}
function padNumber (num) {
if (num <= 9)
return "0" + num;
return num;
}
|
/*
* Flush stats to InfluxDB (http://influxdb.org/)
*
* To enable this backend, include 'statsd-influxdb-backend' in the backends
* configuration array:
*
* backends: ['statsd-influxdb-backend']
*
* The backend will read the configuration options from the following
* 'influxdb' hash defined in the main statsd config file:
*
* influxdb: {
* host: '127.0.0.1', // InfluxDB host. (default 127.0.0.1)
* port: 8086, // InfluxDB port. (default 8086)
* ssl: false, // InfluxDB is hosted over SSL. (default false)
* database: 'dbname', // InfluxDB database instance. (required)
* username: 'user', // InfluxDB database username.
* password: 'pass', // InfluxDB database password.
* flush: {
* enable: true // Enable regular flush strategy. (default true)
* },
* proxy: {
* enable: false, // Enable the proxy strategy. (default false)
* suffix: 'raw', // Metric name suffix. (default 'raw')
* flushInterval: 1000 // Flush interval for the internal buffer.
* // (default 1000)
* },
* includeStatsdMetrics: false, // Send internal statsd metrics to InfluxDB. (default false)
* includeInfluxdbMetrics: false // Send internal backend metrics to InfluxDB. (default false)
* // Requires includeStatsdMetrics to be enabled.
* }
*
*/
var util = require('util'),
querystring = require('querystring'),
http = require('http'),
https = require('https');
function InfluxdbBackend(startupTime, config, events) {
var self = this;
self.debug = config.debug;
self.registry = {};
self.influxdbStats = {};
self.defaultHost = '127.0.0.1';
self.defaultPort = 8086;
self.defaultVersion = 0.8;
self.defaultFlushEnable = true;
self.defaultProxyEnable = false;
self.defaultProxySuffix = 'raw';
self.defaultProxyFlushInterval = 1000;
self.host = self.defaultHost;
self.port = self.defaultPort;
self.version = self.defaultVersion;
self.protocol = http;
self.flushEnable = self.defaultFlushEnable;
self.proxyEnable = self.defaultProxyEnable;
self.proxySuffix = self.defaultProxySuffix;
self.proxyFlushInterval = self.defaultProxyFlushInterval;
self.includeStatsdMetrics = false;
self.includeInfluxdbMetrics = false;
/* XXX Hardcoding default prefix here because it is not accessible otherwise. */
self.prefixStats = config.prefixStats !== undefined ? config.prefixStats : 'statsd';
if (config.influxdb) {
self.host = config.influxdb.host || self.defaultHost;
self.port = config.influxdb.port || self.defaultPort;
self.version = config.influxdb.version || self.defaultVersion;
self.user = config.influxdb.username;
self.pass = config.influxdb.password;
self.database = config.influxdb.database;
self.includeStatsdMetrics = config.influxdb.includeStatsdMetrics;
self.includeInfluxdbMetrics = config.influxdb.includeInfluxdbMetrics;
if (config.influxdb.ssl) {
self.protocol = https;
}
if (config.influxdb.flush) {
self.flushEnable = config.influxdb.flush.enable;
}
if (config.influxdb.proxy) {
self.proxyEnable = config.influxdb.proxy.enable || self.defaultProxyEnable;
self.proxySuffix = config.influxdb.proxy.suffix || self.defaultProxySuffix;
self.proxyFlushInterval = config.influxdb.proxy.flushInterval || self.defaultProxyFlushInterval;
}
}
if (self.version >= 0.9) {
self.assembleEvent = self.assembleEvent_v09;
self.httpPOST = self.httpPOST_v09;
} else {
self.assembleEvent = self.assembleEvent_v08;
self.httpPOST = self.httpPOST_v08;
}
if (self.proxyEnable) {
self.log('Starting the buffer flush interval. (every ' + self.proxyFlushInterval + 'ms)');
setInterval(function () {
self.flushQueue();
}, self.proxyFlushInterval);
events.on('packet', function (packet, rinfo) {
try {
self.processPacket(packet, rinfo);
} catch (e) {
self.log(e);
}
});
}
if (self.flushEnable) {
events.on('flush', function (timestamp, metrics) {
try {
self.processFlush(timestamp, metrics);
} catch (e) {
self.log(e);
}
});
}
events.on('status', function (writeCb) {
for (var stat in self.influxdbStats) {
writeCb(null, 'influxdb', stat, self.influxdbStats[stat]);
}
});
return true;
}
function millisecondsSince(start) {
diff = process.hrtime(start);
return diff[0] * 1000 + diff[1] / 1000000;
}
InfluxdbBackend.prototype.log = function (msg) {
util.log('[influxdb] ' + msg);
}
InfluxdbBackend.prototype.logDebug = function (msg) {
if (this.debug) {
var string;
if (msg instanceof Function) {
string = msg();
} else {
string = msg;
}
util.log('[influxdb] (DEBUG) ' + string);
}
}
/**
* Flush strategy handler
*
* @param {Number} timestamp
* @param {Object} stats metric
*/
InfluxdbBackend.prototype.processFlush = function (timestamp, metrics) {
var self = this,
counters = metrics.counters,
gauges = metrics.gauges,
timerData = metrics.timer_data,
statsdMetrics = metrics.statsd_metrics,
points = [],
sets = function (vals) {
var ret = {};
for (var val in vals) {
ret[val] = vals[val].values();
}
return ret;
}(metrics.sets),
startTime = process.hrtime(),
key, timerKey,
statsPrefixRegexp = new RegExp('^' + self.prefixStats + '\\.');
/* Convert timestamp from seconds to milliseconds. */
timestamp = (timestamp * 1000);
for (key in counters) {
/* Do not include statsd counters. */
if (!self.includeStatsdMetrics && key.match(statsPrefixRegexp)) { continue; }
var value = counters[key],
k = key + '.counter';
if (value) {
points.push(self.assembleEvent(k, [{value: value, time: timestamp}]));
}
}
for (set in sets) {
sets[set].map(function (v) {
points.push(self.assembleEvent(set, [{value: v, time: timestamp}]));
})
points.push(self.assembleEvent(set + "_count", [{value: sets[set].length, time: timestamp}]));
}
for (key in gauges) {
/* Do not include statsd gauges. */
if (!self.includeStatsdMetrics && key.match(statsPrefixRegexp)) { continue; }
var value = gauges[key],
k = key + '.gauge';
if (!isNaN(parseFloat(value)) && isFinite(value)) {
points.push(self.assembleEvent(k, [{value: value, time: timestamp}]));
}
}
for (key in timerData) {
var timerMetrics = timerData[key];
// Try to add histogram data, if it is there:
if (timerMetrics.histogram) {
var histoMetrics = timerMetrics.histogram
, histoKey;
for (histoKey in histoMetrics) {
var value = histoMetrics[histoKey],
k = key + '.timer.histogram.' + histoKey;
points.push(self.assembleEvent(k, [{value: value, time: timestamp}]));
}
// Delete here so it isn't iterated over later:
delete timerMetrics.histogram;
}
// Iterate over normal metrics:
for (timerKey in timerMetrics) {
var value = timerMetrics[timerKey],
k = key + '.timer' + '.' + timerKey;
points.push(self.assembleEvent(k, [{value: value, time: timestamp}]));
}
}
if (self.includeStatsdMetrics) {
// Include backend metrics for the previous flush
if (self.includeInfluxdbMetrics) {
statsdMetrics['influxdbStats.flush_time'] = self.influxdbStats.flushTime;
statsdMetrics['influxdbStats.http_response_time'] = self.influxdbStats.httpResponseTime;
statsdMetrics['influxdbStats.payload_size'] = self.influxdbStats.payloadSize;
statsdMetrics['influxdbStats.num_stats'] = self.influxdbStats.numStats;
}
for (key in statsdMetrics) {
var value = statsdMetrics[key],
k = self.prefixStats + '.' + key;
if (!isNaN(parseFloat(value)) && isFinite(value)) {
points.push(self.assembleEvent(k, [{value: value, time: timestamp}]));
}
}
}
self.httpPOST(points);
self.influxdbStats.flushTime = millisecondsSince(startTime);
}
InfluxdbBackend.prototype.processPacket = function (packet, rinfo) {
var self = this,
ts = (new Date()).valueOf();
/* Stolen from statsd's stats.js. */
var packet_data = packet.toString(),
metrics;
if (packet_data.indexOf("\n") > -1) {
metrics = packet_data.split("\n");
} else {
metrics = [packet_data];
}
for (var midx in metrics) {
if (metrics[midx].length === 0) {
continue;
}
var bits = metrics[midx].toString().split(':');
var key = bits.shift()
.replace(/\s+/g, '_')
.replace(/\//g, '-')
.replace(/[^a-zA-Z_\-0-9\.]/g, '');
if (bits.length === 0) {
bits.push("1");
}
for (var i = 0; i < bits.length; i++) {
var fields = bits[i].split("|");
if (fields[1] === undefined) {
self.log('Bad line: ' + fields + ' in msg "' + metrics[midx] +'"');
continue;
}
var metric_type = fields[1].trim();
/* Timer */
if (metric_type === "ms") {
self.enqueue('timer', ts, key, Number(fields[0] || 0));
/* Gauge */
} else if (metric_type === "g") {
if (fields[0].match(/^[-+]/)) {
self.logDebug('Sending gauges with +/- is not supported yet.');
} else {
self.enqueue('gauge', ts, key, Number(fields[0] || 0));
}
/* Set */
} else if (metric_type === "s") {
self.logDebug('Sets not supported yet.');
/* Counter */
} else {
/* XXX Handle sampling. */
self.enqueue('counter', ts, key, Number(fields[0] || 1));
}
}
}
}
InfluxdbBackend.prototype.enqueue = function (type, ts, key, value) {
var self = this;
key = key + '.' + type + '.' + self.proxySuffix;
if (!self.registry[key]) {
self.registry[key] = [];
}
self.registry[key].push({value: value, time: ts});
}
InfluxdbBackend.prototype.flushQueue = function () {
var self = this,
registry = self.clearRegistry(),
points = [];
for (var key in registry) {
var payload = self.assembleEvent(key, registry[key]);
self.logDebug(function () {
return 'Flush ' + registry[key].length + ' values for ' + key;
});
points.push(payload);
}
self.httpPOST(points);
self.logDebug('Queue flushed');
}
InfluxdbBackend.prototype.clearRegistry = function () {
var self = this,
registry = self.registry;
self.registry = {};
return registry;
}
InfluxdbBackend.prototype.assembleEvent_v08 = function (name, events) {
var self = this;
var payload = {
name: name,
columns: Object.keys(events[0]),
points: []
};
for (var idx in events) {
var event = events[idx],
points = [];
for (var cidx in payload.columns) {
var column = payload.columns[cidx];
points.push(event[column]);
}
payload.points.push(points);
}
return payload;
}
InfluxdbBackend.prototype.assembleEvent_v09 = function (name, events) {
var self = this;
var tag_symbol = "__t__";
var measurement_pieces = [];
var tags = {};
var pieces = name.split(".");
var i = 0;
while (i < pieces.length) {
if (pieces[i].substr(0,tag_symbol.length) == tag_symbol) {
var tag = pieces[i].substr(tag_symbol.length);
tags[tag] = pieces[i+1];
i += 2;
}
else {
measurement_pieces.push(pieces[i]);
i++;
}
}
var measurement = measurement_pieces.join(".");
var payload = {
measurement: measurement,
fields: { value: events[0]['value'] },
tags: tags
}
return payload;
}
InfluxdbBackend.prototype.httpPOST_v08 = function (points) {
/* Do not send if there are no points. */
if (!points.length) { return; }
var self = this,
query = {u: self.user, p: self.pass, time_precision: 'ms'},
protocolName = self.protocol == http ? 'HTTP' : 'HTTPS',
startTime;
self.logDebug(function () {
return 'Sending ' + points.length + ' different points via ' + protocolName;
});
self.influxdbStats.numStats = points.length;
var options = {
hostname: self.host,
port: self.port,
path: '/db/' + self.database + '/series?' + querystring.stringify(query),
method: 'POST',
agent: false // Is it okay to use "undefined" here? (keep-alive)
};
var req = self.protocol.request(options);
req.on('socket', function (res) {
startTime = process.hrtime();
});
req.on('response', function (res) {
var status = res.statusCode;
self.influxdbStats.httpResponseTime = millisecondsSince(startTime);
if (status !== 200) {
self.log(protocolName + ' Error: ' + status);
}
});
req.on('error', function (e, i) {
self.log(e);
});
var payload = JSON.stringify(points)
self.influxdbStats.payloadSize = Buffer.byteLength(payload);
self.logDebug(function () {
var size = (self.influxdbStats.payloadSize / 1024).toFixed(2);
return 'Payload size ' + size + ' KB';
});
req.write(payload);
req.end();
}
InfluxdbBackend.prototype.httpPOST_v09 = function (points) {
/* Do not send if there are no points. */
if (!points.length) { return; }
var self = this,
query = {u: self.user, p: self.pass},
protocolName = self.protocol == http ? 'HTTP' : 'HTTPS',
startTime;
self.logDebug(function () {
return 'Sending ' + points.length + ' different points via ' + protocolName;
});
self.influxdbStats.numStats = points.length;
var options = {
hostname: self.host,
port: self.port,
path: '/write?' + querystring.stringify(query),
method: 'POST',
agent: false // Is it okay to use "undefined" here? (keep-alive)
};
var req = self.protocol.request(options);
req.on('socket', function (res) {
startTime = process.hrtime();
});
req.on('response', function (res) {
var status = res.statusCode;
self.influxdbStats.httpResponseTime = millisecondsSince(startTime);
if (status >= 400) {
self.log(protocolName + ' Error: ' + status);
}
});
req.on('error', function (e, i) {
self.log(e);
});
var payload = JSON.stringify({
database: self.database,
points: points
});
self.influxdbStats.payloadSize = Buffer.byteLength(payload);
self.logDebug(function () {
var size = (self.influxdbStats.payloadSize / 1024).toFixed(2);
return 'Payload size ' + size + ' KB';
});
req.write(payload);
req.end();
}
InfluxdbBackend.prototype.configCheck = function () {
var self = this,
success = true;
/* Make sure the database name is configured. */
if (!self.database) {
self.log('Missing config option: database');
success = false;
}
return success;
}
exports.init = function (startupTime, config, events) {
var influxdb = new InfluxdbBackend(startupTime, config, events);
return influxdb.configCheck();
}
|
'use strict';
var test = require('prova'),
path = require('path'),
exec = require('child_process').exec;
function documentation(args, options, callback) {
if (!callback) {
callback = options;
options = {};
}
if (!options.cwd) {
options.cwd = __dirname;
}
args.unshift(path.join(__dirname, '../bin/documentation.js'));
exec(args.join(' '), options, function (err, stdout, stderr) {
if (err) return callback(err, stdout, stderr);
callback(err, JSON.parse(stdout), stderr);
});
}
test('documentation binary', function (t) {
documentation(['fixture/simple.input.js'], function (err, data) {
t.error(err);
t.equal(data.length, 1, 'simple has no dependencies');
t.end();
});
});
test('defaults to parsing package.json main', function (t) {
documentation([], { cwd: path.join(__dirname, '..') }, function (err, data) {
t.error(err);
t.ok(data.length, 'we document ourself');
t.end();
});
});
|
import { dispatch as d3_dispatch } from 'd3-dispatch';
import {
event as d3_event,
select as d3_select
} from 'd3-selection';
import { d3keybinding as d3_keybinding } from '../lib/d3.keybinding.js';
import { osmEntity } from '../osm/index';
import { utilRebind } from '../util/rebind';
/*
The hover behavior adds the `.hover` class on mouseover to all elements to which
the identical datum is bound, and removes it on mouseout.
The :hover pseudo-class is insufficient for iD's purposes because a datum's visual
representation may consist of several elements scattered throughout the DOM hierarchy.
Only one of these elements can have the :hover pseudo-class, but all of them will
have the .hover class.
*/
export function behaviorHover(context) {
var dispatch = d3_dispatch('hover'),
_selection = d3_select(null),
newId = null,
buttonDown,
altDisables,
target;
function keydown() {
if (altDisables && d3_event.keyCode === d3_keybinding.modifierCodes.alt) {
_selection.selectAll('.hover')
.classed('hover-suppressed', true)
.classed('hover', false);
_selection
.classed('hover-disabled', true);
dispatch.call('hover', this, null);
}
}
function keyup() {
if (altDisables && d3_event.keyCode === d3_keybinding.modifierCodes.alt) {
_selection.selectAll('.hover-suppressed')
.classed('hover-suppressed', false)
.classed('hover', true);
_selection
.classed('hover-disabled', false);
dispatch.call('hover', this, target ? target.id : null);
}
}
var hover = function(selection) {
_selection = selection;
newId = null;
_selection
.on('mouseover.hover', mouseover)
.on('mouseout.hover', mouseout)
.on('mousedown.hover', mousedown);
d3_select(window)
.on('keydown.hover', keydown)
.on('keyup.hover', keyup);
function mouseover() {
if (buttonDown) return;
var target = d3_event.target;
enter(target ? target.__data__ : null);
}
function mouseout() {
if (buttonDown) return;
var target = d3_event.relatedTarget;
enter(target ? target.__data__ : null);
}
function mousedown() {
buttonDown = true;
d3_select(window)
.on('mouseup.hover', mouseup, true);
}
function mouseup() {
buttonDown = false;
d3_select(window)
.on('mouseup.hover', null, true);
}
function enter(d) {
if (d === target) return;
target = d;
_selection.selectAll('.hover')
.classed('hover', false);
_selection.selectAll('.hover-suppressed')
.classed('hover-suppressed', false);
if (target instanceof osmEntity && target.id !== newId) {
// If drawing a way, don't hover on a node that was just placed. #3974
var mode = context.mode() && context.mode().id;
if ((mode === 'draw-line' || mode === 'draw-area') && !newId && target.type === 'node') {
newId = target.id;
return;
}
var selector = '.' + target.id;
if (target.type === 'relation') {
target.members.forEach(function(member) {
selector += ', .' + member.id;
});
}
var suppressed = altDisables && d3_event && d3_event.altKey;
_selection.selectAll(selector)
.classed(suppressed ? 'hover-suppressed' : 'hover', true);
dispatch.call('hover', this, !suppressed && target.id);
} else {
dispatch.call('hover', this, null);
}
}
};
hover.off = function(selection) {
selection.selectAll('.hover')
.classed('hover', false);
selection.selectAll('.hover-suppressed')
.classed('hover-suppressed', false);
selection
.classed('hover-disabled', false);
selection
.on('mouseover.hover', null)
.on('mouseout.hover', null)
.on('mousedown.hover', null);
d3_select(window)
.on('keydown.hover', null)
.on('keyup.hover', null);
};
hover.altDisables = function(_) {
if (!arguments.length) return altDisables;
altDisables = _;
return hover;
};
return utilRebind(hover, dispatch, 'on');
}
|
angular.module('square', [])
.factory('square', function() {
return function (num) {
return num * num;
};
});
|
function getEvents (cloudformation, argv, utils) {
const stackName = argv._[1]
if (!stackName) {
console.error('cirrus events <stackname>')
process.exit(1)
}
utils.fetchEvents(stackName, function (err, events) {
if (err) {
utils.checkExists(stackName, err)
throw new Error(err)
}
utils.logEvents(events)
})
}
export default {
name: 'events',
description: 'Returns events for a stack',
fn: getEvents
}
|
//(function() {
var markedRenderer = new marked.Renderer()
markedRenderer.image = function(src, title, alt) {
var renderedImage = "<img src=\"" + src + "\""
if (alt != null && alt != "") {
renderedImage += " alt=\"" + alt + "\""
}
if (title != null && title != "") {
if (title.indexOf("x") >= 0) {
var sizes = title.split("x")
if(sizes.length == 2 && !isNaN(sizes[0]) && !isNaN(sizes[1])) {
renderedImage += " width=\"" + sizes[0] + "\" height=\"" + sizes[1] + "\""
}
} else if (!isNaN(title)) {
renderedImage += " width=\"" + title + "\""
}
}
renderedImage += " />"
return renderedImage
}
markedRenderer.iframe = function(src) {
return "<div class=\"markdown-iframe\"><iframe frameborder=\"0\" allowfullscreen src=\"" + src + "\"></iframe></div>";
}
marked.setOptions({ renderer: markedRenderer, sanitize: true })
var app = angular.module("branch", ["ui.router", "ngResource", "ngConfirm", "ngNotifications", "ngComments", "ngModeration", "ngRating", "ngSubscribe", "ngSanitize", "vcRecaptcha" ]);
app.config(["$stateProvider","$urlRouterProvider", "confirmConfigProvider", "notificationConfigProvider", "commentsConfigProvider", "moderationConfigProvider", "ratingConfigProvider", "subscribeConfigProvider", "$locationProvider", function($stateProvider, $urlRouterProvider, confirmConfigProvider, notificationConfigProvider, commentsConfigProvider, moderationConfigProvider, ratingConfigProvider, subscribeConfigProvider, $locationProvider) {
$urlRouterProvider.otherwise(function($injector,$location) {
// if the url starts with "#%2F" it means that the url that
// was attempted was actually a "/#/" link (ie. /#/project). Since we converted
// from # to #! after releasing, we need to handle these links
// properly. Turns out $location.$$hash has that value we need
if ($location.$$url.substr(0,4) === "#%2F") {
return $location.$$hash;
}
return "/";
});
$stateProvider
//home page
.state("home", {
url: "/",
templateUrl: "/views/home/index.html",
controller: "homeController"
})
//TED page
.state("TED", {
url: "/TED",
templateUrl: "/views/ted/ted.html",
controller: "homeController"
})
//Terms & Conditions
.state("tnc", {
url: "/tnc",
templateUrl: "/views/tnc/index.html"
})
//no item page
.state("noitem", {
url: "/noitem",
templateUrl: "/views/noitem.html"
})
//no item page
.state("badbrowser", {
url: "/badbrowser",
templateUrl: "/views/badbrowser.html"
})
//login and signup page
.state("loginsignup", {
url: "/loginsignup?url",
templateUrl : "/views/loginsignup.html",
controller: "authController"
})
//login page
//used if a session has expired or user is not logged in and tries to navigate to a page that requires authentication
.state("login", {
url: "/login?url",
templateUrl : "/views/login.html",
controller: "authController"
})
//password reset page
//used if a session has expired or user is not logged in and tries to navigate to a page that requires authentication
.state("reset", {
url: "/reset",
templateUrl : "/views/reset/reset.html",
controller: "authController"
})
.state("reset.changepassword", {
url: "/:hash",
views:{
"@":{
templateUrl: "/views/reset/change-password.html",
controller: "authController",
}
}
})
//used to navigate to the admin console
.state("admin", {
url: "/shouldntbeabletoguessthisurl",
templateUrl: "/views/admin/index.html",
controller: "adminController"
})
//used to navigate to the moderator console
.state("moderator", {
url: "/moderator",
templateUrl: "/views/moderator/index.html",
controller: "moderatorController"
})
//used to navigate to the project list page
.state("projects", {
url: "/project?terms&page&sort",
templateUrl: "/views/projects/index.html",
controller: "projectController"
})
//used to navigate to a given project detail page
.state("projects.detail", {
url: "/:projectId?status",
views:{
"@":{
templateUrl: "/views/projects/detail.html",
controller: "projectController",
}
}
})
//used to navigate to a given project detail page
.state("projects.addedit", {
url: "/:projectId/edit",
views:{
"@":{
templateUrl: "/views/projects/addedit.html",
controller: "projectController",
}
}
})
//used to navigate to the publication list page
.state("publications", {
url: "/blog",
templateUrl: "/views/publications/index.html",
controller: "publicationController"
})
.state("publications.redirect", {
url: "/:publicationId?status",
views:{
"@":{
templateUrl: "/views/publications/index.html",
controller: "publicationController"
}
}
})
//used to navigate to the rc list page
.state("rc", {
url: "/knowledge",
templateUrl: "/views/resourcecenter/index.html",
controller: "resourceController"
})
//used to navigate to a given knowledge hub detail page
.state("rc.detail", {
url: "/:resourceId?status",
views:{
"@":{
templateUrl: "/views/resourcecenter/detail.html",
controller: "resourceController",
}
}
})
//used to navigate to the knowledge hub add/edit page
.state("rc.addedit", {
url: "/:resourceId/edit",
views:{
"@":{
templateUrl: "/views/resourcecenter/addedit.html",
controller: "resourceController",
}
}
})
//used to navigate to a user list page (not currently used)
.state("users", {
url: "/user?sort",
templateUrl: "/views/users/index.html",
controller: "userController"
})
//used to allow users to change their password
.state("users.changepassword", {
url: "/changepassword",
views:{
"@":{
templateUrl: "/views/users/changepassword.html",
controller: "userController",
}
}
})
//used to navigate to a given user detail page
.state("users.detail", {
url: "/:userId",
views:{
"@":{
templateUrl: "/views/users/detail.html",
controller: "userController",
}
}
})
//used to navigate to a given user add/edit page
.state("users.addedit", {
url: "/:userId/edit",
views:{
"@":{
templateUrl: "/views/users/addedit.html",
controller: "userController",
}
}
})
//used to navigate to a user list page (not currently used)
.state("userprofiles", {
url: "/userprofile?sort",
templateUrl: "/views/users/index.html",
controller: "userController"
})
//used to navigate to a given user add/edit page
.state("userprofiles.addedit", {
url: "/:userId/edit",
views:{
"@":{
templateUrl: "/views/users/addedit.html",
controller: "userController",
}
}
})
$locationProvider.hashPrefix('!');
}]);
//GA modification zhu
app.run(['$rootScope','$location', '$window',
function($rootScope,$location,$window) {
$window.ga('create', 'UA-87754759-1', 'auto');
$rootScope.$on('$stateChangeSuccess', function() {
$window.ga('send', 'pageview', $location.path());
document.body.scrollTop = document.documentElement.scrollTop = 0;
});
}]);
// app.run(['$rootScope',function($rootScope) {
// $rootScope.$on('$stateChangeSuccess', function() {
// document.body.scrollTop = document.documentElement.scrollTop = 0;
// });
// }]);
if (!window.WebSocket){
window.location = "#!badbrowser";
}
//directives
include "./directives/header.js"
include "./directives/footer.js"
include "./directives/branchtree.js"
include "./directives/confirm-dialog.js"
include "./directives/notification-dialog.js"
include "./directives/comments.js"
include "./directives/moderation.js"
include "./directives/rating.js"
include "./directives/subscribe.js"
include "./directives/search-input.js"
include "./directives/search-filter.js"
include "./directives/search-results.js"
//services
include "./services/user-manager.js"
include "./services/result-handler.js"
include "./services/search-exchange.js"
include "./services/picklists.js"
include "./services/lastError.js"
include "./services/publisher.js"
include "./services/templater.js"
//controllers
include "./controllers/admin.js"
include "./controllers/moderator.js"
include "./controllers/auth.js"
include "./controllers/home.js"
include "./controllers/project.js"
include "./controllers/publication.js"
include "./controllers/resource.js"
include "./controllers/comment.js"
include "./controllers/user.js"
include "./controllers/moderation.js"
//return app
//})();
|
'use strict';
var program = require('commander');
program
.version('0.0.1')
.option('-p, --peppers', 'Add peppers')
.option('-P, --pineapple', 'Add pineapple')
.option('-b, --bbq', 'Add bbq sauce')
.option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
.parse(process.argv);
console.log('you ordered a pizza with:');
if (program.peppers) console.log(' - peppers');
if (program.pineapple) console.log(' - pineapple');
if (program.bbq) console.log(' - bbq');
console.log(' - %s cheese', program.cheese);
|
// Imports
const fs = require('fs');
// Constants
const MASTER_KEY_ITERATIONS = 1000000;
const MASTER_KEY_MESSAGE_DIGEST = 'sha512';
const LEGACY_MASTER_KEY_ITERATIONS = 250000;
const LEGACY_MASTER_KEY_MESSAGE_DIGEST = 'sha512';
// Validator functions
function isFile(path) {
return fs.existsSync(path) && fs.statSync(path).isFile();
}
// Commands
const commands = {
SHARD_ARGS: [
{
name: 'key',
alias: 'k',
type: String,
required: true,
validator: isFile,
typeLabel: '{underline key file}',
description: 'The path to the shard key file'
},
{
name: 'input',
alias: 'i',
type: String,
required: true,
validator: isFile,
typeLabel: '{underline input file}',
description: 'The path to the file that is being sharded'
},
{
name: 'output',
alias: 'o',
multiple: true,
type: String,
required: true,
validator: (paths) => {
return paths.length >= 2
},
typeLabel: '{underline shard file} ...',
description: 'The paths to save each shard to'
},
{
name: 'expjunk',
alias: 'e',
type: Boolean,
defaultValue: false,
required: true,
typeLabel: '{underline exponential junk}',
description: 'Whether to use exponential junk boundaries (true), or fixed multiple boundaries (false)'
},
{
name: 'boundary',
alias: 'b',
type: Number,
defaultValue: 16384,
required: true,
validator: (boundary) => {
return Math.floor(boundary) === boundary && boundary > 1
},
typeLabel: '{underline boundary}',
description: 'The base to use when using exponential junk, or the boundary multiple when using fixed multiple junk'
}
],
RESHARD_ARGS: [
{
name: 'key',
alias: 'k',
type: String,
required: true,
validator: isFile,
typeLabel: '{underline key file}',
description: 'The path to the shard key file'
},
{
name: 'input',
alias: 'i',
type: String,
required: true,
validator: isFile,
typeLabel: '{underline shard file}',
description: 'The path to the shard file that is to be resharded'
},
{
name: 'output',
alias: 'o',
multiple: true,
type: String,
required: true,
validator: (paths) => {
return paths.length >= 2
},
typeLabel: '{underline shard file} ...',
description: 'The paths to save each new shard to'
}
],
MERGE_ARGS: [
{
name: 'key',
alias: 'k',
type: String,
required: true,
validator: isFile,
typeLabel: '{underline key file}',
description: 'The path to the shard key file'
},
{
name: 'input',
alias: 'i',
multiple: true,
type: String,
required: true,
validator: (paths) => {
return paths.every(isFile)
},
typeLabel: '{underline shard file} ...',
description: 'The paths to the shard files to merge'
},
{
name: 'output',
alias: 'o',
type: String,
required: true,
typeLabel: '{underline document path}',
description: 'The path to where the document will be saved'
}
],
GLUE_ARGS: [
{
name: 'key',
alias: 'k',
type: String,
required: true,
validator: isFile,
typeLabel: '{underline key file}',
description: 'The path to the shard key file'
},
{
name: 'input',
alias: 'i',
multiple: true,
type: String,
required: true,
validator: (paths) => {
return paths.every(isFile)
},
typeLabel: '{underline shard file} ...',
description: 'The paths to the shard files to glue together'
},
{
name: 'output',
alias: 'o',
type: String,
required: true,
typeLabel: '{underline shard file}',
description: 'The path to where the new shard will be saved'
}
],
CHPASS_ARGS: [
{
name: 'oldkey',
alias: 'k',
type: String,
required: true,
validator: isFile,
typeLabel: '{underline old key file}',
description: 'The path to the current shard key file'
},
{
name: 'newkey',
alias: 'o',
type: String,
required: true,
typeLabel: '{underline new key file}',
description: 'The path to where the new key file will be saved'
}
],
CHPARAM_ARGS: [
{
name: 'oldkey',
alias: 'k',
type: String,
required: true,
validator: isFile,
typeLabel: '{underline old key file}',
description: 'The path to the current shard key file'
},
{
name: 'newkey',
alias: 'o',
type: String,
required: true,
typeLabel: '{underline new key file}',
description: 'The path to where the new key file will be saved'
},
{
name: 'iterations',
alias: 'i',
type: Number,
defaultValue: MASTER_KEY_ITERATIONS,
required: true,
validator: (iterations) => {
return iterations > 0
},
typeLabel: '{underline PBKDF iterations}',
description: 'The number of iterations to do for PBKDF2'
},
{
name: 'algorithm',
alias: 'a',
type: String,
defaultValue: MASTER_KEY_MESSAGE_DIGEST,
required: true,
validator: (algorithm) => {
return ['md5', 'sha1', 'sha256', 'sha512'].includes(algorithm)
},
typeLabel: '{underline PBKDF algorithm}',
description: 'The hash algorithm to use for PBKDF2. Supported algorithms: {bold md5}, {bold sha1}, {bold sha256}, and {bold sha512}'
}
],
GENKEY_ARGS: [
{
name: 'output',
alias: 'o',
type: String,
required: true,
typeLabel: '{underline new key file}',
description: 'The path to where the newly generated key file will be saved'
},
{
name: 'iterations',
alias: 'i',
type: Number,
defaultValue: MASTER_KEY_ITERATIONS,
required: true,
validator: (iterations) => {
return iterations > 0
},
typeLabel: '{underline PBKDF iterations}',
description: 'The number of iterations to do for PBKDF2'
},
{
name: 'algorithm',
alias: 'a',
type: String,
defaultValue: MASTER_KEY_MESSAGE_DIGEST,
required: true,
validator: (algorithm) => {
return ['md5', 'sha1', 'sha256', 'sha512'].includes(algorithm)
},
typeLabel: '{underline PBKDF algorithm}',
description: 'The hash algorithm to use for PBKDF2. Supported algorithms: {bold md5}, {bold sha1}, {bold sha256}, and {bold sha512}'
}
],
VALID_COMMANDS: ['shard', 'reshard', 'merge', 'glue', 'chpass', 'genkey', 'help', null]
};
commands.SECTIONS = [
{
header: 'secsplit',
content: 'Protecting your documents with perfect encryption. Licensed under the ISC license.'
},
{
header: 'Synopsis',
content: '$ secsplit <command> <options>'
},
{
header: 'Command List',
content: [
{
name: 'shard',
summary: 'Initiate the sharding process for a {bold new} document, in order to split it into several pieces'
},
{
name: 'reshard',
summary: 'Split an {bold existing} shard into more shards'
},
{
name: 'merge',
summary: 'Merge {bold all} shards back into the original document'
},
{
name: 'glue',
summary: 'Merge {bold some} shards back into a single shard'
},
{
name: 'chpass',
summary: 'Change the password set during the key generation process used to protect the shard key'
},
{
name: 'chparam',
summary: 'Change the PBKDF2 arguments used for generating the key that protects the shard key, retaining the same password'
},
{
name: 'genkey',
summary: 'Generate a new shard key for all other commands, and protect it with a password'
},
{
name: 'help', summary: 'Display this help text'
}
]
},
{
header: 'Shard Options',
optionList: commands.SHARD_ARGS
},
{
header: 'Reshard Options',
optionList: commands.RESHARD_ARGS
},
{
header: 'Merge Options',
optionList: commands.MERGE_ARGS
},
{
header: 'Glue Options',
optionList: commands.GLUE_ARGS
},
{
header: 'Chpass Options',
optionList: commands.CHPASS_ARGS
},
{
header: 'Chparam Options',
optionList: commands.CHPARAM_ARGS
},
{
header: 'Genkey Options',
optionList: commands.GENKEY_ARGS
}
];
module.exports = {
commands,
fetchCommand: {
definition: [
{
name: 'command',
defaultOption: true
}
],
options: {
stopAtFirstUnknown: true
}
}
};
|
// jshint node: true, esversion: 6
'use strict';
const mailgun = require('mailgun-js')({ apiKey: process.env.MAILGUN_KEY, domain: 'lcssl.org' });
const mail = {
send: (recipient, subject, message, done) => {
var data = {
from: 'Civil Service Softball League <results@lcssl.org>',
cc: 'nick@mantonbradbury.com',
to: recipient,
subject: subject,
text: message
};
mailgun.messages().send(data).then(response => {
console.log('email sent', response); // move to winston
done(response);
}, err => {
console.error('not sent', err); // move to winston
done(err);
});
}
};
module.exports = mail;
|
'use strict';
var should = require('should'),
request = require('supertest'),
app = require('../../server'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Typing = mongoose.model('Typing'),
agent = request.agent(app);
/**
* Globals
*/
var credentials, user, typing;
/**
* Typing routes tests
*/
describe('Typing CRUD tests', function() {
beforeEach(function(done) {
// Create user credentials
credentials = {
username: 'username',
password: 'password'
};
// Create a new user
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: credentials.username,
password: credentials.password,
provider: 'local'
});
// Save a user to the test db and create new Typing
user.save(function() {
typing = {
name: 'Typing Name'
};
done();
});
});
it('should be able to save Typing instance if logged in', function(done) {
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Typing
agent.post('/typings')
.send(typing)
.expect(200)
.end(function(typingSaveErr, typingSaveRes) {
// Handle Typing save error
if (typingSaveErr) done(typingSaveErr);
// Get a list of Typings
agent.get('/typings')
.end(function(typingsGetErr, typingsGetRes) {
// Handle Typing save error
if (typingsGetErr) done(typingsGetErr);
// Get Typings list
var typings = typingsGetRes.body;
// Set assertions
(typings[0].user._id).should.equal(userId);
(typings[0].name).should.match('Typing Name');
// Call the assertion callback
done();
});
});
});
});
it('should not be able to save Typing instance if not logged in', function(done) {
agent.post('/typings')
.send(typing)
.expect(401)
.end(function(typingSaveErr, typingSaveRes) {
// Call the assertion callback
done(typingSaveErr);
});
});
it('should not be able to save Typing instance if no name is provided', function(done) {
// Invalidate name field
typing.name = '';
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Typing
agent.post('/typings')
.send(typing)
.expect(400)
.end(function(typingSaveErr, typingSaveRes) {
// Set message assertion
(typingSaveRes.body.message).should.match('Please fill Typing name');
// Handle Typing save error
done(typingSaveErr);
});
});
});
it('should be able to update Typing instance if signed in', function(done) {
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Typing
agent.post('/typings')
.send(typing)
.expect(200)
.end(function(typingSaveErr, typingSaveRes) {
// Handle Typing save error
if (typingSaveErr) done(typingSaveErr);
// Update Typing name
typing.name = 'WHY YOU GOTTA BE SO MEAN?';
// Update existing Typing
agent.put('/typings/' + typingSaveRes.body._id)
.send(typing)
.expect(200)
.end(function(typingUpdateErr, typingUpdateRes) {
// Handle Typing update error
if (typingUpdateErr) done(typingUpdateErr);
// Set assertions
(typingUpdateRes.body._id).should.equal(typingSaveRes.body._id);
(typingUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?');
// Call the assertion callback
done();
});
});
});
});
it('should be able to get a list of Typings if not signed in', function(done) {
// Create new Typing model instance
var typingObj = new Typing(typing);
// Save the Typing
typingObj.save(function() {
// Request Typings
request(app).get('/typings')
.end(function(req, res) {
// Set assertion
res.body.should.be.an.Array.with.lengthOf(1);
// Call the assertion callback
done();
});
});
});
it('should be able to get a single Typing if not signed in', function(done) {
// Create new Typing model instance
var typingObj = new Typing(typing);
// Save the Typing
typingObj.save(function() {
request(app).get('/typings/' + typingObj._id)
.end(function(req, res) {
// Set assertion
res.body.should.be.an.Object.with.property('name', typing.name);
// Call the assertion callback
done();
});
});
});
it('should be able to delete Typing instance if signed in', function(done) {
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Typing
agent.post('/typings')
.send(typing)
.expect(200)
.end(function(typingSaveErr, typingSaveRes) {
// Handle Typing save error
if (typingSaveErr) done(typingSaveErr);
// Delete existing Typing
agent.delete('/typings/' + typingSaveRes.body._id)
.send(typing)
.expect(200)
.end(function(typingDeleteErr, typingDeleteRes) {
// Handle Typing error error
if (typingDeleteErr) done(typingDeleteErr);
// Set assertions
(typingDeleteRes.body._id).should.equal(typingSaveRes.body._id);
// Call the assertion callback
done();
});
});
});
});
it('should not be able to delete Typing instance if not signed in', function(done) {
// Set Typing user
typing.user = user;
// Create new Typing model instance
var typingObj = new Typing(typing);
// Save the Typing
typingObj.save(function() {
// Try deleting Typing
request(app).delete('/typings/' + typingObj._id)
.expect(401)
.end(function(typingDeleteErr, typingDeleteRes) {
// Set message assertion
(typingDeleteRes.body.message).should.match('User is not logged in');
// Handle Typing error error
done(typingDeleteErr);
});
});
});
afterEach(function(done) {
User.remove().exec();
Typing.remove().exec();
done();
});
});
|
'use strict';
// ------------------------------------------------------
// TABLE OF CONTENTS
// ------------------------------------------------------
// 1 - GENERAL NOTES
// 2 - STEP BY STEP
// 3 - GENERAL GUIDE
// 4 - COMMON PROBLEMS
// ------------------------------------------------------
// ------------------------------------------------------
// GENERAL NOTES
// ------------------------------------------------------
// VALUES
// - Numbers
// - Strings
// - Boolean (true / false)
// - null
// - undefined
//
// VARIABLES
// - Declaration
// - Scope
// - Hoisting
//
// CONSTANTS
// ------------------------------------------------------
// STEP BY STEP
// ------------------------------------------------------
// VARIABLES
// ------------------------------------------------------
// DECLARATION
var surname;
var name;
var age;
// INITIALIZATION
var surname = 'Silva';
var name = 'Fabrício';
var age = 28;
// ASSIGNMENT
surname = 'Mendes';
name = 'Francisco';
age = 29;
// CONSTANTS
// ------------------------------------------------------
const dev = 'Fabrício Silva';
// VALUES
// ------------------------------------------------------
// NUMBERS
var number = 1;
var integer = 1;
var floatPointer = 1.0;
var notANumber = NaN;
// STRINGS
var string = "This is a String";
var name = "Fabrício Silva";
// BOOLEAN
var truthy = true;
var falsy = false;
// NULL
var notValue = null;
// UNDEFINED
var notDefinied;
// ------------------------------------------------------
// GENERAL GUIDE
// ------------------------------------------------------
// ------------------------------------------------------
// COMMON PROBLEMS
// ------------------------------------------------------
|
import EndOfGameEvent from "../events/EndOfGameEvent";
import ExitLevelEvent from "../events/ExitLevelEvent";
class CollisionDetector {
constructor(scoreMgr) {
this.scoreManager = scoreMgr;
}
detectAll(hero, level) {
var that = this;
var collided = false;
// Detects collisions with enemies
level.enemies.getChildren().forEach(function(enemy){
// There are two types of collisions with enemies:
// 1. If player is falling (hero.ySpeed > 0 [1.a]
// AND hero.getY() < enemy.getY() [1.b]),
// then the player kills the enemy
// 2. Else, the enemy kills the player
if(that.detectCollision(enemy, hero)
&& hero.ySpeed > 2 // 1.a
&& hero.getY() < enemy.getY()) { // 1.b
that.scoreManager.scoreEnemy();
enemy.remove();
} else if(that.detectCollision(enemy, hero)) { // 2
throw new EndOfGameEvent('Game Over!');
}
});
// Detects collisions with platforms
level.platforms.getChildren().forEach(function(platform){
// We're interested in collisions that:
// 1. Actually occurs (detectCollision(a, b) is true)
// 2. Player is over the platform (hero.getY() < platform.getY())
// 3. Player is falling over (hero.ySpeed > 0)
if(that.detectCollision(platform, hero) // 1
&& hero.getY() < platform.getY() // 2
&& hero.ySpeed >= 0) { // 3
hero.ySpeed *= hero.bounce;
hero.counter = 0;
hero.setY(platform.getY() - hero.getHeight());
}
});
// Detects collisions with coins
level.coins.getChildren().forEach(function(coin){
// Collisions with coins are straightforward:
// it they occur, score is rewarded and coin
// dissapears from stage.
if(that.detectCollision(coin, hero)) {
that.scoreManager.scoreCoin();
coin.remove();
}
});
// Detects collision with the exit door
// In order to advance to the next level,
// player MUST have collected the key.
if(that.detectCollision(level.door, hero) && level.key) {
throw new ExitLevelEvent();
}
}
detectCollision(a, b) {
var hit = false;
// Horizontal collisions
if(b.getX() + b.getWidth() >= a.getX() && b.getX() < a.getX() + a.getWidth()) {
// Vertical collisions
if(b.getY() + b.getHeight() >= a.getY() && b.getY() < a.getY() + a.getHeight()) {
hit = true;
}
}
// A gets inside B horizontally
if(b.getX() <= a.getX() && b.getX() + b.getWidth() >= a.getX() + a.getWidth()) {
// A is completely inside B
if(b.getY() <= a.getY() && b.getY() + b.getHeight() >= a.getY() + a.getHeight()) {
hit = true;
}
}
// B collides with A
if(a.getX() <= b.getX() && a.getX() + a.getWidth() >= b.getX() + b.getWidth()) {
if(a.getY() <= b.getY() && a.getY() + a.getHeight() >= b.getY() + b.getHeight()) {
hit = true;
}
}
return hit;
}
}
export default CollisionDetector;
|
version https://git-lfs.github.com/spec/v1
oid sha256:01d70387a0bf27d86a3b8d1aeefd71878327cc4827313de91b68e746a587783a
size 104603
|
import * as actionTypes from "./action-types";
import { fromJS } from "immutable"; // 将 JS 对象转换成 immutable 对象
import {
getBannerRequest,
getRecommendListRequest,
} from "../../../api/request";
export const changeBannerList = (data) => ({
type: actionTypes.CHANGE_BANNER,
data: fromJS(data),
});
export const changeRecommendList = (data) => ({
type: actionTypes.CHANGE_RECOMMEND_LIST,
data: fromJS(data),
});
export const changeEnterLoading = (data) => ({
type: actionTypes.CHANGE_ENTER_LOADING,
data,
});
export const getBannerList = () => {
return (dispatch) => {
getBannerRequest()
.then((data) => {
dispatch(changeBannerList(data.banners));
})
.catch(() => {
console.log("轮播图数据传输错误");
});
};
};
export const getRecommendList = () => {
return (dispatch) => {
getRecommendListRequest()
.then((data) => {
dispatch(changeRecommendList(data.result));
// 在获取推荐歌单后,应把 loading 状态改为 false
dispatch (changeEnterLoading (false));
})
.catch(() => {
console.log("推荐歌单数据传输错误");
});
};
};
|
var getNative = require('lodash/internal/getNative');
/** Native method references. */
var WeakMap = getNative(global, 'WeakMap');
/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;
module.exports = metaMap;
|
/**
* @jsx React.DOM
*/
/* not used but thats how you can use touch events
* */
//React.initializeTouchEvents(true);
/* not used but thats how you can use animation and other transition goodies
* */
var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;
/**
* we will use yes for true
* we will use no for false
*
* React has some built ins that rely on state being true/false like classSet()
* and these will not work with yes/no but can easily be modified / reproduced
*
* this single app uses the yes/no var so if you want you can switch back to true/false
*
* */
var yes = 'yes', no = 'no';
//var yes = true, no = false;
/* bootstrap components
* */
var Flash = ReactBootstrap.Alert;
var Btn = ReactBootstrap.Button;
var Modal = ReactBootstrap.Modal;
/* create the container object
* */
var snowUI = {
passthrough: {}, //special for passing functions between components
};
/* create flash message
* */
snowUI.SnowpiFlash = React.createClass({displayName: 'SnowpiFlash',
getInitialState: function() {
return {
isVisible: true
};
},
getDefaultProps: function() {
return ({showclass:'info'});
},
render: function() {
snowlog.log(this.props);
if(!this.state.isVisible)
return null;
var message = this.props.message ? this.props.message : this.props.children;
return (
Flash({bsStyle: this.props.showclass, onDismiss: this.dismissFlash},
React.DOM.p(null, message)
)
);
},
dismissFlash: function() {
this.setState({isVisible: false});
}
});
/* my little man component
* simple example
* */
snowUI.SnowpiMan = React.createClass({displayName: 'SnowpiMan',
getDefaultProps: function() {
return ({divstyle:{float:'right',}});
},
render: function() {
return this.transferPropsTo(
React.DOM.div({style: this.props.divstyle, dangerouslySetInnerHTML: {__html: snowtext.logoman}})
);
}
});
/**
* menu components
* */
//main
snowUI.leftMenu = React.createClass({displayName: 'leftMenu',
getInitialState: function() {
return ({
config:this.props.config || {section:snowPath.wallet,wallet:'all',moon:'overview'}
})
},
componentWillReceiveProps: function(nextProps) {
if(nextProps.config)this.setState({config:nextProps.config})
},
render: function() {
var showmenu
if(this.state.config.section === snowPath.wallet) {
if(this.state.config.wallet && this.state.config.wallet !== 'new')
showmenu = snowUI.walletMenu
else
showmenu = snowUI.defaultMenu
} else if(this.state.config.section === snowPath.receive || this.state.config.section === snowPath.settings) {
showmenu = snowUI.receiveMenu
} else {
showmenu = snowUI.defaultMenu
}
snowlog.log('main menu component',this.state.config)
return (
React.DOM.div(null, showmenu({config: this.state.config}), " ")
);
}
});
//wallet menu
snowUI.walletMenu = React.createClass({displayName: 'walletMenu',
getInitialState: function() {
return ({
config:this.props.config || {section:snowPath.wallet,wallet:false,moon:false}
})
},
componentWillReceiveProps: function(nextProps) {
if(nextProps.config)this.setState({config:nextProps.config})
},
componentDidUpdate: function() {
$('.dogemenulink').removeClass('active');
var moon = this.state.config.moon
if(!moon && this.state.config.wallet !== 'new')moon = 'dashboard'
$('.dogemenulink[data-snowmoon="'+moon+'"]').addClass('active');
},
componentDidMount: function() {
this.componentDidUpdate()
},
menuClick: function(e) {
e.preventDefault();
var moon = $(e.target).parent()[0].dataset.snowmoon;
if(moon !== undefined)
snowUI.methods.valueRoute(snowPath.wallet + '/' + this.state.config.wallet + '/' + moon);
else {
var moon = $(e.target)[0].dataset.snowmoon;
if(moon !== undefined) {
snowUI.methods.valueRoute(snowPath.wallet + '/' + this.state.config.wallet + '/' + moon);
} else {
snowmessage('error','Link error',1000)
}
}
return false
},
render: function() {
var testnet = this.state.config.testnet ? (React.DOM.div({id: "testnet-flash", title: "", 'data-toggle': "tooltip", 'data-placement': "right", 'data-container': "body", className: "dogemenulink", 'data-original-title': "This wallet is on the TESTNET!", style: {display:'block'}}, React.DOM.span({className: "glyphicon glyphicon-text-width"}), " TESTNET ")) : ''
snowlog.log('wallet menu component')
return (
React.DOM.div(null,
React.DOM.div({id: "menuwallet"},
testnet,
React.DOM.a({onClick: this.menuClick, 'data-snowmoon': "dashboard", id: "dogedash", 'data-container': "#menuspy", title: "", className: "dogemenulink ", 'data-original-title': "Dashboard"}, " ", React.DOM.span({className: "glyphicon glyphicon-th"}), " Dashboard"),
React.DOM.a({onClick: this.menuClick, 'data-snowmoon': "accounts", id: "dogeacc", 'data-container': "#menuspy", title: "", className: "dogemenulink", 'data-original-title': "manage wallet accounts"}, " ", React.DOM.span({className: "glyphicon glyphicon-list"}), " Accounts"),
React.DOM.a({onClick: this.menuClick, 'data-snowmoon': "send", id: "dogesend", 'data-container': "#menuspy", title: "", className: "dogemenulink", 'data-original-title': "send coins"}, " ", React.DOM.span({className: "glyphicon glyphicon-share"}), " Send"),
React.DOM.a({onClick: this.menuClick, 'data-snowmoon': "transactions", id: "dogetx", 'data-container': "#menuspy", title: "", className: "dogemenulink", 'data-original-title': "sortable transaction list"}, " ", React.DOM.span({className: "glyphicon glyphicon-list-alt"}), " Transactions"),
React.DOM.a({onClick: this.menuClick, 'data-snowmoon': "update", id: "dogeupdate", 'data-container': "#menuspy", title: "", className: "dogemenulink", 'data-original-title': "update wallet"}, React.DOM.span({className: "glyphicon glyphicon-pencil"}), " Update ", React.DOM.span({id: "updatecoinspan", style: {display:"none"}}))
),
"- ")
);
}
});
//main menu
snowUI.receiveMenu = React.createClass({displayName: 'receiveMenu',
getInitialState: function() {
return ({
config:this.props.config || {section:snowPath.wallet,wallet:'all',moon:'overview'}
})
},
componentWillReceiveProps: function(nextProps) {
if(nextProps.config)this.setState({config:nextProps.config})
},
componentDidUpdate: function() {
$('.dogedccmenulink').removeClass('active');
$('.dogedccmenulink[data-snowmoon="'+this.state.config.section+'"]').addClass('active');
},
menuClick: function(e) {
e.preventDefault();
//snowlog.log($(e.target).parent())
var moon = $(e.target).parent().attr('data-snowmoon');
if(moon !== undefined)
snowUI.methods.valueRoute(moon);
else {
snowmessage('error','Link error... Retrying now!',3000)
setTimeout(function() {
var moon = $(e.target).parent()[0].dataset.snowmoon;
if(moon !== undefined) snowUI.methods.valueRoute(moon);
}.bind(this),2000)
}
return false
},
render: function() {
snowlog.log('receive menu component')
return (
React.DOM.div(null,
React.DOM.div({id: "menudcc"},
React.DOM.a({onClick: this.menuClick, 'data-snowmoon': snowPath.wallet, id: "dogewallets", 'data-container': "#menuspy", title: "", className: "dogedccmenulink", 'data-original-title': "Digital Coin Wallets"}, " ", React.DOM.span({onClick: this.menuClick, 'data-snowmoon': snowPath.wallet, className: "glyphicon glyphicon-briefcase"}), " Wallets"),
React.DOM.a({onClick: this.menuClick, 'data-snowmoon': snowPath.receive, id: "dogedccsetup", 'data-container': "#menuspy", title: "", className: "dogedccmenulink", 'data-original-title': "Receive coins from strangers. (friends too)"}, " ", React.DOM.span({onClick: this.menuClick, 'data-snowmoon': snowPath.receive, className: "glyphicon glyphicon-tasks"}), " Receivers"),
React.DOM.a({onClick: this.menuClick, 'data-snowmoon': snowPath.settings, id: "dogedccsettings", 'data-container': "#menuspy", title: "", className: "dogedccmenulink", 'data-original-title': "Digital Coin Coordinator settings"}, " ", React.DOM.span({onClick: this.menuClick, 'data-snowmoon': snowPath.settings, className: "glyphicon glyphicon-cog"}), " Settings")
)
)
);
}
});
//default
snowUI.defaultMenu = snowUI.receiveMenu
//wallet select
snowUI.walletSelect = React.createClass({displayName: 'walletSelect',
componentDidMount: function() {
this.updateSelect();
},
componentDidUpdate: function() {
this.updateSelect();
},
componentWillUpdate: function() {
$("#walletselect").selectbox("detach");
},
updateSelect: function() {
var _this = this
$("#walletselect").selectbox({
onChange: function (val, inst) {
_this.props.route(val)
},
effect: "fade"
});
//snowlog.log('wallet select updated')
},
render: function() {
var wallets;
if(this.props.wally instanceof Array) {
var wallets = this.props.wally.map(function (w) {
return (
React.DOM.option({key: w.key, value: snowPath.wallet + '/' + w.key}, w.name)
);
});
}
if(this.props.section === snowPath.wallet) {
var _df = (this.props.wallet) ? snowPath.wallet + '/' + this.props.wallet : snowPath.wallet;
} else {
var _df = this.props.section;
}
//snowlog.log(_df)
return this.transferPropsTo(
React.DOM.div({className: "list"},
React.DOM.div({className: "walletmsg", style: {display:'none'}}),
React.DOM.select({onChange: this.props.route, id: "walletselect", value: _df},
wallets,
React.DOM.optgroup(null),
React.DOM.option({value: snowPath.wallet + '/new'}, snowtext.menu.plus.name),
React.DOM.option({value: snowPath.wallet}, snowtext.menu.list.name),
React.DOM.option({value: snowPath.receive}, snowtext.menu.receive.name),
React.DOM.option({value: snowPath.settings}, snowtext.menu.settings.name),
React.DOM.option({value: snowPath.inq}, snowtext.menu.inqueue.name)
)
)
);
}
});
var UI = React.createClass({displayName: 'UI',
getInitialState: function() {
/**
* initialize the app
* the plan is to keep only active references in root state.
* we should use props for the fill outs
* */
var _this = this
snowUI.methods = {
hrefRoute: _this.hrefRoute,
buttonRoute: _this.buttonRoute,
valueRoute: _this.valueRoute,
updateState: _this.updateState,
loaderStart: _this.loaderStart,
loaderStop: _this.loaderStop,
config: _this.config(),
/* statics dont have acccess to the UI Object unless binded with _this */
fadeOut: function () {
snowlog.log('fadeout')
$('#maindiv').css('opacity',0.01);
},
fadeIn: function () {
snowlog.log('fadein')
$('#maindiv').delay(500).fadeTo("slow",1.0);
},
ajax: {
call: function(url,data,callback) {
if(!snowUI.methods.ajax.running) {
//snowUI.methods.ajax.running = true
$.ajax({url: url,data:data})
.done(function( resp,status,xhr ) {
_csrf = xhr.getResponseHeader("x-snow-token");
snowUI.methods.ajax.running = false
snowlog.log('call method return')
callback(resp)
});
} else {
snowmessage('message','call in progress...' + url,1000)
}
},
post: function(url,data,callback) {
if(!snowUI.methods.ajax.running) {
//snowUI.methods.ajax.running = true
$.ajax({type:'POST',url:url,data:data})
.done(function( resp,status,xhr ) {
_csrf = xhr.getResponseHeader("x-snow-token");
snowUI.methods.ajax.running = false
snowlog.log('post method return')
callback(resp)
});
} else {
snowmessage('message','call in progress... ',1000)
}
},
callwaiting: function(url,data,callback) {
if(!snowUI.methods.ajax.running) {
//snowUI.methods.ajax.running = true
$.ajax({async:false,url: url,data:data})
.done(function( resp,status,xhr ) {
_csrf = xhr.getResponseHeader("x-snow-token");
snowUI.methods.ajax.running = false
snowlog.log('callwaiting method return')
callback(resp)
});
} else {
snowmessage('message','call in progress... ',1000)
}
},
running: false,
},/*end ajax*/
changelock: function(lock){
/* lockstatus -- 0=encrypted,1=unlocked until unlockeduntil,2=not encrypted */
if(lock==='off') {
this.setState({locked:false,unlocked:true}) //fake the lock out and turn it off
} else if(!this.state.wally || this.state.wally.coinapi!='rpc') {
this.setState({locked:false,unlocked:false,lockstatus:2})
} else if(lock===0 || lock==='Locked') {
this.setState({locked:true,unlocked:false,lockstatus:0})
}else if(lock>0) {
var usetime=lock;
var date = new Date(usetime);
snowlog.log(lock,usetime,new Date().getTime());
var hours = date.getHours(),minutes = date.getMinutes(),seconds = date.getSeconds();
var formattedTime = hours + ':' + minutes + ':' + seconds;
this.setState({locked:true,unlocked:true,lockstatus:1,lockeduntil:lock,lockedtimeformat:formattedTime})
//$('#wallet-unlocked').html('<span class="153567433"></span> secs').removeClass('hidden');
//snowcountdown('153567433',usetime);
} else {
this.setState({locked:false,unlocked:false,lockstatus:2})
}
}.bind(_this),/*end changelock - binded to snowUI React component*/
}
return {
section: this.props.section || 'wallet',
moon: this.props.moon || false,
wallet: this.props.wallet || false,
mywallets: [],
locatewallet: [],
mounted:false,
wally:false,
testnet: false,
isSSL: false,
locked: false,
unlocked: false,
lockstatus:2
};
},
//set up the config object
config: function() {
var _this = this
if(this.state) {
return {
section:_this.state.section,
wallet:_this.state.wallet,
moon:_this.state.moon,
mywallets: _this.state.mywallets,
locatewallet: _this.state.locatewallet,
wally: _this.state.wally,
testnet: _this.state.testnet,
isSSL: _this.state.isSSL,
locked: _this.state.locked,
unlocked: _this.state.unlocked,
lockstatus:_this.state.lockstatus
}
}
},
componentDidMount: function() {
if(!this.state.mounted) {
this.getWallets()
}
},
getWallets: function () {
//grab our initial data
var _this = this
snowlog.log('run on mount')
$.ajax({async:false,url: "/api/snowcoins/local/change-wallet"})
.done(function( resp,status,xhr ) {
_csrf = xhr.getResponseHeader("x-snow-token");
snowlog.log('wally',resp.wally, this.state.wallet)
//locater
var a = [];
var ix = resp.wally.length;
for(i=0;i<ix;i++) {
a[i]=resp.wally[i].key
}
if(this.state.wallet) {
var newWally = resp.wally[a.indexOf(this.state.wallet)];
this.setState({locatewallet:a,mounted:true,mywallets:resp.wally,wally: newWally });
} else {
this.setState({locatewallet:a,mounted:true,mywallets:resp.wally});
}
}.bind(this));
},
componentWillReceiveProps: function(nextProps) {
var update = {}
if(nextProps.section !== undefined)update.section = nextProps.section;
if(nextProps.moon !== undefined)update.moon = nextProps.moon;
if(nextProps.wallet !== undefined)update.wallet = nextProps.wallet;
//wallet list
if(nextProps.mywallets)update.mywallets = nextProps.mywallets;
//if(nextProps.section)this.loaderStart()
if(nextProps.wallet !== undefined) {
var newWally = this.state.mywallets[this.state.locatewallet.indexOf(nextProps.wallet)];
update.wally = newWally;
}
this.setState(update);
this.loaderStart()
return false
},
componentWillUpdate: function() {
return false
},
updateState: function(prop) {
if(typeof prop === 'object')
this.setState(prop);
snowlog.log('update state from function',prop)
return false
},
loaderStart: function() {
$('.loader').fadeIn();
return false
},
loaderStop: function() {
$('.loader').delay(500).fadeOut("slow");
return false
},
changeTheme: function() {
var mbody = $('body');
if(mbody.hasClass('themeable-snowcoinslight')==true) {
mbody.removeClass('themeable-snowcoinslight');
} else {
mbody.addClass('themeable-snowcoinslight');
}
return false
},
valueRoute: function(route) {
bone.router.navigate(snowPath.root + route, {trigger:true});
snowlog.log('value route',snowPath.root + route)
return false
},
hrefRoute: function(route) {
route.preventDefault();
bone.router.navigate(snowPath.root + $(route.target)[0].pathname, {trigger:true});
snowlog.log('href route',snowPath.root + $(route.target)[0].pathname)
return false
},
buttonRoute: function(route) {
route.preventDefault();
bone.router.navigate(snowPath.root + $(route.target)[0].dataset.snowmoon, {trigger:true});
snowlog.log('button route',snowPath.root + $(route.target)[0].pathname)
return false
},
eggy: function() {
eggy();
},
render: function() {
//set up our psuedo routes
var comp = {}
comp[snowPath.wallet]=snowUI.wallet;
comp[snowPath.receive]=snowUI.receive;
comp[snowPath.settings]=snowUI.settings;
comp[snowPath.inq]=snowUI.inq;
var mycomp = comp[this.state.section]
snowlog.log('check state UI',this.state.mounted);
if(this.state.mounted) {
var mountwallet = function() {
return (snowUI.walletSelect({route: this.valueRoute, section: this.state.section, wallet: this.state.wallet, wally: this.state.mywallets}))
}.bind(this)
var mountpages = function() {
return (mycomp({methods: snowUI.methods, config: this.config()}))
}.bind(this)
} else {
var mountwallet = function(){};
var mountpages = function(){};
}
var ssl = this.state.wallet && this.state.isSSL ? {display:'block'} : {display:'none'}
var lockedwallet = this.state.wallet && this.state.locked && !this.state.unlocked ? "" : "hidden"
var openwallet = !this.state.wallet || this.state.locked ? "hidden" : ""
var unlockedwallet = this.state.wallet && this.state.unlocked ? "" : "hidden"
var testnet = this.state.testnet ? 'testnet':''
snowlog.log('testnet',this.state.testnet)
//mount
return (
React.DOM.div({id: "snowpi-body"},
React.DOM.div({id: "walletbarspyhelper", style: {display:'block'}}),
React.DOM.div({id: "walletbar", className: "affix"},
React.DOM.div({className: "wallet"},
React.DOM.div({className: "button-group"},
Btn({bsStyle: "link", 'data-toggle': "dropdown", className: "dropdown-toggle"}, snowtext.menu.menu.name),
React.DOM.ul({className: "dropdown-menu", role: "menu"},
React.DOM.li({className: "nav-item-add"}, " ", React.DOM.a({onClick: this.hrefRoute, href: snowPath.wallet + '/new'}, snowtext.menu.plus.name)),
React.DOM.li({className: "nav-item-home"}, " ", React.DOM.a({onClick: this.hrefRoute, href: snowPath.wallet}, snowtext.menu.list.name)),
React.DOM.li({className: "nav-item-receive"}, React.DOM.a({onClick: this.hrefRoute, href: snowPath.receive}, snowtext.menu.receive.name)),
React.DOM.li({className: "nav-item-settings"}, React.DOM.a({onClick: this.hrefRoute, href: snowPath.settings}, snowtext.menu.settings.name)),
React.DOM.li({className: "divider"}),
React.DOM.li({className: "nav-item-snowcat"}),
React.DOM.li({className: "divider"}),
React.DOM.li(null,
React.DOM.div(null,
React.DOM.div({onClick: this.changeTheme, className: "walletmenuspan changetheme bstooltip", title: "Switch between the light and dark theme", 'data-toggle': "tooltip", 'data-placement': "bottom", 'data-container': "body"}, React.DOM.span({className: "glyphicon glyphicon-adjust"})),
React.DOM.div({className: "walletmenuspan bstooltip", title: "inquisive queue", 'data-toggle': "tooltip", 'data-placement': "bottom", 'data-container': "body"}, " ", React.DOM.a({onClick: this.hrefRoute, href: snowPath.inq, className: "nav-item-inq"})),
React.DOM.div({className: "walletmenuspan bstooltip", title: "Logout", 'data-toggle': "tooltip", 'data-placement': "right", 'data-container': "body"}, " ", React.DOM.a({href: "/signout"}, " ", React.DOM.span({className: "glyphicon glyphicon-log-out"}))),
React.DOM.div({className: "clearfix"})
)
)
)
)
),
mountwallet(),
React.DOM.div({style: ssl, id: "wallet-ssl", 'data-toggle': "tooltip", 'data-placement': "bottom", alt: "ssl connection", className: "", title: "SSL Connection to wallet"}, React.DOM.span({className: "glyphicon glyphicon-link"})),
React.DOM.div({className: lockedwallet, id: "wallet-lock", 'data-toggle': "tooltip", 'data-placement': "bottom", alt: "Wallet is encrypted", title: "Wallet is encrypted"}),
React.DOM.div({className: openwallet, id: "wallet-unlock", snowlink: "dashboard", 'data-toggle': "tooltip", 'data-placement': "bottom", title: "You should encrypt this wallet soon."}),
React.DOM.div({className: unlockedwallet, id: "wallet-unlocked"}),
React.DOM.div({className: "logo", onClick: this.eggy}, React.DOM.a({title: "inquisive.io snowcoins build info", 'data-container': "body", 'data-placement': "bottom", 'data-toggle': "tooltip", className: "walletbar-logo"}))
),
React.DOM.div({className: "container-fluid"},
React.DOM.div({id: "menuspy ", className: "affix dogemenu col-xs-1 col-md-2 " + testnet},
snowUI.leftMenu({config: this.config()})
),
React.DOM.div({className: "dogeboard col-xs-offset-1 col-xs-11 col-md-offset-2 col-md-10"},
snowUI.AppInfo(null),
React.DOM.div({className: "dogeboard-left col-xs-12 col-md-12"},
React.DOM.div({className: "content"}, " ", mountpages(), " ")
)
)
)
/* end snowpi-body */
)
)
}
});
//app info
snowUI.AppInfo = React.createClass({displayName: 'AppInfo',
render: function() {
return (
React.DOM.div({id: "easter-egg", style: {display:'none'}},
React.DOM.div(null,
React.DOM.div({className: "blocks col-xs-offset-1 col-xs-10 col-md-offset-1 col-md-5 col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"},
React.DOM.h4(null, "Get Snowcoins"),
React.DOM.div({className: "row"},
React.DOM.div({className: "col-sm-offset-1 col-sm-11"}, React.DOM.a({href: "https://github.com/inquisive/snowcoins", target: "_blank"}, "GitHub / Installation")),
React.DOM.div({className: "col-sm-offset-1 col-sm-11"}, " ", React.DOM.a({href: "https://github.com/inquisive/snowcoins/latest.zip", target: "_blank"}, "Download zip"), " | ", React.DOM.a({href: "https://github.com/inquisive/snowcoins/latest.tar.gz", target: "_blank"}, "Download gz"))
),
React.DOM.div({style: {borderBottom:'transparent 15px solid'}}),
React.DOM.h4(null, "Built With"),
React.DOM.div({className: "row"},
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://nodejs.org", target: "_blank"}, "nodejs")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://keystonejs.com", target: "_blank"}, "KeystoneJS")),
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://getbootstrap.com/", target: "_blank"}, "Bootstrap")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "https://github.com/countable/node-dogecoin", target: "_blank"}, "node-dogecoin")),
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://mongoosejs.com/", target: "_blank"}, "mongoose"))
)
),
React.DOM.div({className: "blocks col-xs-offset-1 col-xs-10 col-md-offset-1 col-md-5 col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"},
React.DOM.h4(null, "Donate"),
React.DOM.div({className: "row"},
React.DOM.div({title: "iq", className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, "iq: ", React.DOM.a({href: "https://inquisive.com/iq/snowkeeper", target: "_blank"}, "snowkeeper")),
React.DOM.div({title: "Dogecoin", className: "col-sm-6 col-md-4"}, React.DOM.a({href: "https://snow.snowpi.org/share/dogecoin", target: "_blank"}, "Ðogecoin")),
React.DOM.div({title: "Bitcoin", className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "https://snow.snowpi.org/share/bitcoin", target: "_blank"}, "Bitcoin")),
React.DOM.div({title: "Litecoin", className: "col-sm-6 col-md-4"}, React.DOM.a({href: "https://snow.snowpi.org/share/litecoin", target: "_blank"}, "Litecoin")),
React.DOM.div({title: "Darkcoin", className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "https://snow.snowpi.org/share/darkcoin", target: "_blank"}, "Darkcoin"))
),
React.DOM.div({style: {borderBottom:'transparent 15px solid'}}),
React.DOM.h4(null, "Digital Coin Wallets"),
React.DOM.div({className: "row"},
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://dogecoin.com", target: "_blank"}, "dogecoin")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://bitcoin.org", target: "_blank"}, "bitcoin")),
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://litecoin.org", target: "_blank"}, "litecoin")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://vertcoin.org", target: "_blank"}, "vertcoin")),
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://octocoin.org", target: "_blank"}, "888")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://auroracoin.org", target: "_blank"}, "auroracoin")),
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://blackcoin.co", target: "_blank"}, "blackcoin")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://digibyte.co", target: "_blank"}, "digibyte")),
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://digitalcoin.co", target: "_blank"}, "digitalcoin")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://darkcoin.io", target: "_blank"}, "darkcoin")),
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://maxcoin.co.uk", target: "_blank"}, "maxcoin")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://mintcoin.co", target: "_blank"}, "mintcoin")),
React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://einsteinium.org", target: "_blank"}, "einsteinium")),
React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://peercoin.net", target: "_blank"}, "peercoin "))
),
React.DOM.div({className: "row"}
)
),
React.DOM.div({className: "clearfix"})
)
)
);
}
});
|
/*
* lib/iterator.js
*
*/
var _ = require("lodash");
var fs = require("fs-extra");
var zlib = require("zlib");
var readline = require("readline");
var readChunk = require("read-chunk");
var fileType = require("file-type");
//==============================================================================
module.exports = function(fpath, handler, done) {
try {
var input = fs.createReadStream(fpath);
if (isGzip(fpath)) {
input = input.pipe(zlib.createGunzip());
}
var lineReader = readline.createInterface({ input: input });
} catch (e) {
//-- something went wrong!
return done(e);
}
//-- initialize
var lineNo = 0;
var processedLines = 0;
var doneReading = false;
var doneProcessing = false;
var paused = false;
var minDiff = 5;
var maxDiff = 10;
//-- trottling
function trottle() {
var diff = lineNo - processedLines;
if (paused) {
if (diff < minDiff) {
paused = false;
lineReader.resume();
}
} else {
if (diff > maxDiff) {
paused = true;
lineReader.pause();
}
}
}
//-- callback
function next() {
if (!doneProcessing && doneReading && processedLines >= lineNo) {
//-- done processing
doneProcessing = true;
done();
} else {
trottle();
}
}
//-- process line
lineReader.on("line", function(line) {
++lineNo;
handler(fpath, lineNo, _.trim(line), function(err) {
++processedLines;
next();
});
trottle();
});
//-- done reading file
lineReader.on("close", function() {
doneReading = true;
//-- this is important !!! :)
next();
});
};
//==============================================================================
function isGzip(fpath) {
var buffer = readChunk.sync(fpath, 0, 4100);
var ftype = fileType(buffer);
return (_.get(ftype, "mime") === "application/gzip");
}
//------------------------------------------------------------------------------
//==============================================================================
|
require('./lib/plato-repo-report')(
'your repo url here'
);
|
define([
"app/config"
], function (config) {
var obj = deepExtend({
baseUrl: './',
paths: {
app: './app',
nls: "./nls",
core: "./core",
service: "./core/loader/service",
controller: "./core/loader/controller",
directive: "./core/loader/directive",
//libs
text: "./lib/require/text",
i18n: "./lib/require/i18n",
angular: "./lib/angular/angular",
angularRoute: './lib/angular/angular-route',
angularSegment: './lib/angular/angular-route-segment',
angularView: './lib/angular/angular-view-segment',
angularMocks: './lib/angular/angular-mocks',
async: "./lib/async/async",
less: "./lib/require-less/less",
lessc: "./lib/require-less/lessc",
"less-builder": "./lib/require-less/less-builder",
normalize: "./lib/require-less/normalize",
jasmine: "./lib/jasmine-2.0.3/jasmine",
"jasmine-html": "./lib/jasmine-2.0.3/jasmine-html",
"jasmine-boot": "./lib/jasmine-2.0.3/boot"
},
shim: {
'angular': {
exports: 'angular'
},
'angularRoute': ['angular'],
'angularSegment': ['angular'],
'angularView': ['angular'],
'angularMocks':{
deps: ['angular'],
exports:'angular.mock'
},
'jasmine': {
exports: 'window.jasmineRequire'
},
'jasmine-html': {
deps: ['jasmine'],
exports: 'window.jasmineRequire'
},
'jasmine-boot': {
deps: ['jasmine', 'jasmine-html'],
exports: 'window.jasmineRequire'
}
},
less: {
env: "development"
}
}, config);
requirejs.config(obj);
return obj;
//we do not want load any frameworks with extend() function here (jquery, angular, ...). So we are providing
// some basic extend here, based on http://andrewdupont.net/2009/08/28/deep-extending-objects-in-javascript/
function deepExtend(destination, source) {
for (var property in source) {
if (source[property] && source[property].constructor &&
source[property].constructor === Object) {
destination[property] = destination[property] || {};
arguments.callee(destination[property], source[property]);
} else {
destination[property] = source[property];
}
}
return destination;
};
});
|
'use strict'
var express = require('express')
var expect = require('chai').expect
var request = require('supertest')
var bodyParser = require('body-parser')
var routes = require('../route/poiRoute')
var MongoClient = require('mongodb').MongoClient
var Types = require('../Types')
var db
MongoClient.connect(process.env.DB_URL, function(err, conn) {
db = conn
})
var app = express()
.set('types', new Types())
.use(bodyParser.json())
.use(bodyParser.urlencoded({extended: true}))
.use(routes)
function cleanAllDB(item) {
db.dropDatabase()
}
function insertData(poi) {
db.collection('poi').insertOne(poi)
}
describe('API controller tests', function () {
beforeEach(function() {
cleanAllDB()
})
describe('POIs operations', function() {
describe('GET ALL', function() {
beforeEach(function() {
insertData({x: 1, y: 2, name: 'TestData'})
})
it('Should return 200 and get the all POIs on data base', function (done) {
setTimeout(function() {
request(app)
.get('/poi')
.expect(200)
.expect(function(req) {
expect(req.body.length).to.equal(1)
expect(req.body[0].x).to.equal(1)
expect(req.body[0].y).to.equal(2)
expect(req.body[0].name).to.equal('TestData')
})
.end(done)
}, 500);
})
})
describe('GET BY PROXIMITY', function() {
beforeEach(function() {
insertData({x: 15, y: 15, name: 'TestData1'})
insertData({x: 30, y: 30, name: 'TestData2'})
insertData({x: 40, y: 40, name: 'TestData3'})
})
it('Should return 200 with two POI on range', function (done) {
setTimeout(function() {
request(app)
.get('/poi/proximity?x=35&y=35&range=10')
.expect(function(req) {
expect(req.body.length).to.equal(2)
expect(req.body[0].x).to.equal(30)
expect(req.body[0].name).to.equal('TestData2')
expect(req.body[1].x).to.equal(40)
expect(req.body[1].name).to.equal('TestData3')
})
.expect(200)
.end(done)
}, 500);
})
it('Should return 200 with empty array', function (done) {
request(app)
.get('/poi/proximity?x=1&y=4&range=10')
.expect(function(req) {
expect(req.body.length).to.equal(0)
})
.expect(200)
.end(done)
})
it('Should return 500 error if no querystring was informed', function (done) {
request(app)
.get('/poi/proximity')
.expect(/Coodinates parameter not informed or invalid on queryString/)
.expect(500)
.end(done)
})
it('Should return 500 error if the querystring is invalid', function (done) {
request(app)
.get('/poi/proximity?x=abc&y=1')
.expect(/Coodinates parameter not informed or invalid on queryString/)
.expect(500)
.end(done)
})
})
describe('POST', function() {
it('Should return error 400 when call post opperation with invalid body', function (done) {
request(app)
.post('/poi')
.send({z: 1, w: 2})
.expect(/Data validation failed/)
.expect(400)
.end(done)
})
it('Should return error 400 when call post opperation with negative coordinates', function (done) {
request(app)
.post('/poi')
.send({x: -100, y: -2, name: 'invalid'})
.expect(/Data validation failed/)
.expect(400)
.end(done)
})
it('Should return error 400 when call post opperation with non integer coordinates', function (done) {
request(app)
.post('/poi')
.send({x: 10.3, y: 2, name: 'invalid'})
.expect(/Data validation failed/)
.expect(400)
.end(done)
})
it('Should return error 200 and insert on data base', function (done) {
setTimeout(function() {
request(app)
.post('/poi')
.send({x: 5, y: 5, name: 'test'})
.expect(function(req) {
expect(req.body.x).to.equal(5)
expect(req.body.y).to.equal(5)
expect(req.body.name).to.equal('test')
})
.expect(201)
.end(done)
}, 500);
})
})
})
})
|
var app = angular.module('JukeTubeApp', []);
// Run
app.run(function () {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
});
// Config
app.config( function ($httpProvider) {
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
// Service
app.service('VideosService', ['$window', '$rootScope', '$log', function ($window, $rootScope, $log) {
var service = this;
var youtube = {
ready: false,
player: null,
playerId: null,
videoId: null,
videoTitle: null,
playerHeight: '480',
playerWidth: '640',
state: 'stopped'
};
var results = [];
var upcoming = [
{id: 'G6KuhTsiLVI', title: 'Alicia Keys - In Common (Black Coffee Remix) (Audio)'},
{id: 'lfEVLXu3NXs', title: 'David Zowie - House Every Weekend'},
{id: 'QNsPI6V4Iec', title: 'Tough Love - So Freakin Tight'},
{id: 'KDxJlW6cxRk', title: 'Duke Dumont - Ocean Drive'}
];
var history = [
{id: 'NYhxaZXXwsg', title: 'Imany – Dont be so shy (Filatov & Karas Remix)'}
];
$window.onYouTubeIframeAPIReady = function () {
$log.info('Youtube API is ready');
youtube.ready = true;
service.bindPlayer('placeholder');
service.loadPlayer();
$rootScope.$apply();
};
function onYoutubeReady (event) {
$log.info('YouTube Player is ready');
youtube.player.cueVideoById(history[0].id);
youtube.videoId = history[0].id;
youtube.videoTitle = history[0].title;
}
function onYoutubeStateChange (event) {
if (event.data == YT.PlayerState.PLAYING) {
youtube.state = 'playing';
} else if (event.data == YT.PlayerState.PAUSED) {
youtube.state = 'paused';
} else if (event.data == YT.PlayerState.ENDED) {
youtube.state = 'ended';
service.launchPlayer(upcoming[0].id, upcoming[0].title);
service.archiveVideo(upcoming[0].id, upcoming[0].title);
service.deleteVideo(upcoming, upcoming[0].id);
}
$rootScope.$apply();
}
this.bindPlayer = function (elementId) {
$log.info('Binding to ' + elementId);
youtube.playerId = elementId;
};
this.createPlayer = function () {
$log.info('Creating a new Youtube player for DOM id ' + youtube.playerId + ' and video ' + youtube.videoId);
return new YT.Player(youtube.playerId, {
height: youtube.playerHeight,
width: youtube.playerWidth,
playerVars: {
rel: 0,
showinfo: 0
},
events: {
'onReady': onYoutubeReady,
'onStateChange': onYoutubeStateChange
}
});
};
this.loadPlayer = function () {
if (youtube.ready && youtube.playerId) {
if (youtube.player) {
youtube.player.destroy();
}
youtube.player = service.createPlayer();
}
};
this.launchPlayer = function (id, title) {
youtube.player.loadVideoById(id);
youtube.videoId = id;
youtube.videoTitle = title;
return youtube;
}
this.listResults = function (data) {
results.length = 0;
for (var i = data.items.length - 1; i >= 0; i--) {
results.push({
id: data.items[i].id.videoId,
title: data.items[i].snippet.title,
description: data.items[i].snippet.description,
thumbnail: data.items[i].snippet.thumbnails.default.url,
author: data.items[i].snippet.channelTitle
});
}
return results;
}
this.queueVideo = function (id, title) {
upcoming.push({
id: id,
title: title
});
return upcoming;
};
this.archiveVideo = function (id, title) {
history.unshift({
id: id,
title: title
});
return history;
};
this.deleteVideo = function (list, id) {
for (var i = list.length - 1; i >= 0; i--) {
if (list[i].id === id) {
list.splice(i, 1);
break;
}
}
};
this.getYoutube = function () {
return youtube;
};
this.getResults = function () {
return results;
};
this.getUpcoming = function () {
return upcoming;
};
this.getHistory = function () {
return history;
};
}]);
// Controller
app.controller('VideosController', function ($scope, $http, $log, VideosService) {
init();
function init() {
$scope.youtube = VideosService.getYoutube();
$scope.results = VideosService.getResults();
$scope.upcoming = VideosService.getUpcoming();
$scope.history = VideosService.getHistory();
$scope.playlist = true;
}
$scope.launch = function (id, title) {
VideosService.launchPlayer(id, title);
VideosService.archiveVideo(id, title);
VideosService.deleteVideo($scope.upcoming, id);
$log.info('Launched id:' + id + ' and title:' + title);
};
$scope.queue = function (id, title) {
VideosService.queueVideo(id, title);
VideosService.deleteVideo($scope.history, id);
$log.info('Queued id:' + id + ' and title:' + title);
};
$scope.delete = function (list, id) {
VideosService.deleteVideo(list, id);
};
$scope.search = function () {
$http.get('https://www.googleapis.com/youtube/v3/search', {
params: {
key: 'AIzaSyBNdACA8nV5eYsAzD-fms8Z5Ld7WNEq6Gk',
type: 'video',
maxResults: '8',
part: 'id,snippet',
fields: 'items/id,items/snippet/title,items/snippet/description,items/snippet/thumbnails/default,items/snippet/channelTitle',
q: this.query
}
})
.success( function (data) {
VideosService.listResults(data);
$log.info(data);
})
.error( function () {
$log.info('Search error');
});
}
$scope.tabulate = function (state) {
$scope.playlist = state;
}
});
|
/*******************************************************************************
NAME MILLER CYLINDRICAL
PURPOSE: Transforms input longitude and latitude to Easting and
Northing for the Miller Cylindrical projection. The
longitude and latitude must be in radians. The Easting
and Northing values will be returned in meters.
PROGRAMMER DATE
---------- ----
T. Mittan March, 1993
This function was adapted from the Lambert Azimuthal Equal Area projection
code (FORTRAN) in the General Cartographic Transformation Package software
which is available from the U.S. Geological Survey National Mapping Division.
ALGORITHM REFERENCES
1. "New Equal-Area Map Projections for Noncircular Regions", John P. Snyder,
The American Cartographer, Vol 15, No. 4, October 1988, pp. 341-355.
2. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
3. "Software Documentation for GCTP General Cartographic Transformation
Package", U.S. Geological Survey National Mapping Division, May 1982.
*******************************************************************************/
Proj4js.Proj.mill = {
/* Initialize the Miller Cylindrical projection
-------------------------------------------*/
init: function() {
//no-op
},
/* Miller Cylindrical forward equations--mapping lat,long to x,y
------------------------------------------------------------*/
forward: function(p) {
var lon=p.x;
var lat=p.y;
/* Forward equations
-----------------*/
dlon = Proj4js.common.adjust_lon(lon -this.long0);
var x = this.x0 +this.R * dlon;
var y = this.y0 + this.R *Math.log(Math.tan((Proj4js.common.PI / 4.0) + (lat / 2.5))) * 1.25;
p.x=x;
p.y=y;
return p;
},//millFwd()
/* Miller Cylindrical inverse equations--mapping x,y to lat/long
------------------------------------------------------------*/
inverse: function(p) {
p. x -= this.x0;
p. y -= this.y0;
var lon = Proj4js.common.adjust_lon(this.long0 + p.x /this.R);
var lat = 2.5 * (Math.atan(Math.exp(p.y/ this.R / 1.25)) - Proj4js.common.PI / 4.0);
p.x=lon;
p.y=lat;
return p;
}//millInv()
};
|
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['test/**/spec.js']
};
|
'use strict';
var React = require('react/addons'),
TestUtils = React.addons.TestUtils,
_ = require('lodash'),
WordCloud = require('../wordcloud.js'),
WordCloudTable = require('../wordcloudtable.js'),
propsBase = require('./fixtures/propsBase.js'),
topics = require('./fixtures/topics.json.js');
describe('WordCloudTable rendering', function (){
var props = propsBase,
wordCloud = TestUtils.renderIntoDocument(<WordCloud {...props} />),
wordCloudTable,
node;
it('loads without error', function (){
should.exist(wordCloud);
wordCloudTable = TestUtils.findRenderedComponentWithType(wordCloud, WordCloudTable);
should.exist(wordCloudTable);
});
it('renders div', function (){
node = React.findDOMNode(wordCloudTable);
node.tagName.toLowerCase().should.be.equal('div');
node.getAttribute('class').should.be.equal('word-cloud-table');
});
it('renders table', function (){
var table = node.firstChild;
table.tagName.toLowerCase().should.be.equal('table');
});
it('renders table body', function (){
var tbody = node.firstChild.firstChild;
tbody.tagName.toLowerCase().should.be.equal('tbody');
});
it('renders rows and table divs', function (){
var rows = node.firstChild.firstChild.childNodes;
should.exist(rows);
rows.length.should.be.equal(5);
_.map(rows, function (row){
row.tagName.toLowerCase().should.be.equal('tr');
should.exist(row.childNodes);
row.childNodes.length.should.be.equal(2);
row.childNodes[0].tagName.toLowerCase().should.be.equal('td');
row.childNodes[1].tagName.toLowerCase().should.be.equal('td');
});
});
});
|
'use strict';
module.exports = function(app) {
var getRouterFor = require('../fake-backend.js').getRouterFor;
var contactsRouter = getRouterFor('contact', 'contacts');
app.use('/api/contacts', contactsRouter);
};
|
var login = new Object();
jQuery.extend(login, {
init: function(formulario) {
login.peticion(formulario);
},
peticion: function(formulario) {
jQuery.ajax({
url : "{{ RUTA_APP|e }}/Index/Index/autenticacion",
async : false,
data : jQuery(formulario).serialize(),
dataType : "json",
type : "POST",
cache : false,
error : function(error_mensaje) {
swal("Error!", "Se ha presentado un error, validar con el administrador del sistema", "error");
},
success : function(resultado) {
login.success(resultado);
}
});
},
success : function(info) {
if(info.status == true) {
location.href = info.data;
}
else {
swal("Error!", info.data, "error");
}
}
});
|
/**
* React Static Boilerplate
* https://github.com/koistya/react-static-boilerplate
* Copyright (c) Konstantin Tarkus (@koistya) | MIT license
*/
import 'babel/polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
import Location from './lib/Location';
import Layout from './components/Layout';
import WordStore from './lib/WordStore'
const routes = {}; // Auto-generated on build. See tools/lib/routes-loader.js
const route = async (path, callback) => {
const handler = routes[path] || routes['/404'];
const component = await handler();
await callback(<Layout>{React.createElement(component)}</Layout>);
};
function run() {
const container = document.getElementById('app');
Location.listen(location => {
route(location.pathname, async (component) => ReactDOM.render(component, container, () => {
// Track the page view event via Google Analytics
window.ga('send', 'pageview');
}));
});
}
if (canUseDOM) {
// Run the application when both DOM is ready
// and page content is loaded
if (window.addEventListener) {
window.addEventListener('DOMContentLoaded', run);
} else {
window.attachEvent('onload', run);
}
}
export default { route, routes };
|
import expect from 'expect'
import _ from 'lodash';
describe('multi', function() {
it('add new multi method', function() {
var multi = require('src/').default;
var area = multi(_.property('shape'));
expect(typeof area).toBe('function');
});
it('throw if no method and no default', function() {
var multi = require('src/').default;
var area = multi(_.property('shape'));
expect(() => area({shape: 'circle'})).toThrow();
});
it('use default no matter what value is passed', function() {
var multi = require('src/').default;
var area = multi(_.property('shape'));
area.defaultMethod(() => 42);
expect(area('stuff')).toBe(42);
expect(area({shape:'circle'})).toBe(42);
expect(area(undefined)).toBe(42);
expect(area(null)).toBe(42);
});
it('falls back to default', function() {
var multi = require('src/').default;
var area = multi(_.property('shape'));
area.method('circle', () => 43);
area.defaultMethod(() => 42);
expect(area('stuff')).toBe(42);
expect(area({shape:'circle'})).toBe(43);
});
it('differentiates between methods', function() {
var multi = require('src/').default;
var area = multi(_.property('shape'));
area.method('circle', () => 43);
area.method('square', () => 44);
area.defaultMethod(() => 42);
expect(area('stuff')).toBe(42);
expect(area({shape:'circle'})).toBe(43);
expect(area({shape:'square'})).toBe(44);
});
it('pass along the right variable', function() {
var multi = require('src/').default;
var area = multi(_.property('shape'));
area.method('circle', (s) => Math.PI * Math.pow(s.radius,2));
area.method('square', (s) => Math.pow(s.side, 2));
area.defaultMethod(() => 42);
expect(area('stuff')).toBe(42);
expect(area({shape:'circle', radius: 1})).toBe(Math.PI);
expect(area({shape:'square', side: 3})).toBe(9);
});
});
|
/*! @name videojs-playlist-ui @version 3.8.0 @license Apache-2.0 */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('global/document'), require('video.js')) :
typeof define === 'function' && define.amd ? define(['global/document', 'video.js'], factory) :
(global.videojsPlaylistUi = factory(global.document,global.videojs));
}(this, (function (document,videojs) { 'use strict';
document = document && document.hasOwnProperty('default') ? document['default'] : document;
videojs = videojs && videojs.hasOwnProperty('default') ? videojs['default'] : videojs;
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
var version = "3.8.0";
var dom = videojs.dom || videojs;
var registerPlugin = videojs.registerPlugin || videojs.plugin; // Array#indexOf analog for IE8
var indexOf = function indexOf(array, target) {
for (var i = 0, length = array.length; i < length; i++) {
if (array[i] === target) {
return i;
}
}
return -1;
}; // see https://github.com/Modernizr/Modernizr/blob/master/feature-detects/css/pointerevents.js
var supportsCssPointerEvents = function () {
var element = document.createElement('x');
element.style.cssText = 'pointer-events:auto';
return element.style.pointerEvents === 'auto';
}();
var defaults = {
className: 'vjs-playlist',
playOnSelect: false,
supportsCssPointerEvents: supportsCssPointerEvents
}; // we don't add `vjs-playlist-now-playing` in addSelectedClass
// so it won't conflict with `vjs-icon-play
// since it'll get added when we mouse out
var addSelectedClass = function addSelectedClass(el) {
el.addClass('vjs-selected');
};
var removeSelectedClass = function removeSelectedClass(el) {
el.removeClass('vjs-selected');
if (el.thumbnail) {
dom.removeClass(el.thumbnail, 'vjs-playlist-now-playing');
}
};
var upNext = function upNext(el) {
el.addClass('vjs-up-next');
};
var notUpNext = function notUpNext(el) {
el.removeClass('vjs-up-next');
};
var createThumbnail = function createThumbnail(thumbnail) {
if (!thumbnail) {
var placeholder = document.createElement('div');
placeholder.className = 'vjs-playlist-thumbnail vjs-playlist-thumbnail-placeholder';
return placeholder;
}
var picture = document.createElement('picture');
picture.className = 'vjs-playlist-thumbnail';
if (typeof thumbnail === 'string') {
// simple thumbnails
var img = document.createElement('img');
img.src = thumbnail;
img.alt = '';
picture.appendChild(img);
} else {
// responsive thumbnails
// additional variations of a <picture> are specified as
// <source> elements
for (var i = 0; i < thumbnail.length - 1; i++) {
var _variant = thumbnail[i];
var source = document.createElement('source'); // transfer the properties of each variant onto a <source>
for (var prop in _variant) {
source[prop] = _variant[prop];
}
picture.appendChild(source);
} // the default version of a <picture> is specified by an <img>
var variant = thumbnail[thumbnail.length - 1];
var _img = document.createElement('img');
_img.alt = '';
for (var _prop in variant) {
_img[_prop] = variant[_prop];
}
picture.appendChild(_img);
}
return picture;
};
var Component = videojs.getComponent('Component');
var PlaylistMenuItem =
/*#__PURE__*/
function (_Component) {
_inheritsLoose(PlaylistMenuItem, _Component);
function PlaylistMenuItem(player, playlistItem, settings) {
var _this;
if (!playlistItem.item) {
throw new Error('Cannot construct a PlaylistMenuItem without an item option');
}
playlistItem.showDescription = settings.showDescription;
_this = _Component.call(this, player, playlistItem) || this;
_this.item = playlistItem.item;
_this.playOnSelect = settings.playOnSelect;
_this.emitTapEvents();
_this.on(['click', 'tap'], _this.switchPlaylistItem_);
_this.on('keydown', _this.handleKeyDown_);
return _this;
}
var _proto = PlaylistMenuItem.prototype;
_proto.handleKeyDown_ = function handleKeyDown_(event) {
// keycode 13 is <Enter>
// keycode 32 is <Space>
if (event.which === 13 || event.which === 32) {
this.switchPlaylistItem_();
}
};
_proto.switchPlaylistItem_ = function switchPlaylistItem_(event) {
this.player_.playlist.currentItem(indexOf(this.player_.playlist(), this.item));
if (this.playOnSelect) {
this.player_.play();
}
};
_proto.createEl = function createEl() {
var li = document.createElement('li');
var item = this.options_.item;
var showDescription = this.options_.showDescription;
if (typeof item.data === 'object') {
var dataKeys = Object.keys(item.data);
dataKeys.forEach(function (key) {
var value = item.data[key];
li.dataset[key] = value;
});
}
li.className = 'vjs-playlist-item';
li.setAttribute('tabIndex', 0); // Thumbnail image
this.thumbnail = createThumbnail(item.thumbnail);
li.appendChild(this.thumbnail); // Duration
if (item.duration) {
var duration = document.createElement('time');
var time = videojs.formatTime(item.duration);
duration.className = 'vjs-playlist-duration';
duration.setAttribute('datetime', 'PT0H0M' + item.duration + 'S');
duration.appendChild(document.createTextNode(time));
li.appendChild(duration);
} // Now playing
var nowPlayingEl = document.createElement('span');
var nowPlayingText = this.localize('Now Playing');
nowPlayingEl.className = 'vjs-playlist-now-playing-text';
nowPlayingEl.appendChild(document.createTextNode(nowPlayingText));
nowPlayingEl.setAttribute('title', nowPlayingText);
this.thumbnail.appendChild(nowPlayingEl); // Title container contains title and "up next"
var titleContainerEl = document.createElement('div');
titleContainerEl.className = 'vjs-playlist-title-container';
this.thumbnail.appendChild(titleContainerEl); // Up next
var upNextEl = document.createElement('span');
var upNextText = this.localize('Up Next');
upNextEl.className = 'vjs-up-next-text';
upNextEl.appendChild(document.createTextNode(upNextText));
upNextEl.setAttribute('title', upNextText);
titleContainerEl.appendChild(upNextEl); // Video title
var titleEl = document.createElement('cite');
var titleText = item.name || this.localize('Untitled Video');
titleEl.className = 'vjs-playlist-name';
titleEl.appendChild(document.createTextNode(titleText));
titleEl.setAttribute('title', titleText);
titleContainerEl.appendChild(titleEl); // We add thumbnail video description only if specified in playlist options
if (showDescription) {
var descriptionEl = document.createElement('div');
var descriptionText = item.description || '';
descriptionEl.className = 'vjs-playlist-description';
descriptionEl.appendChild(document.createTextNode(descriptionText));
descriptionEl.setAttribute('title', descriptionText);
titleContainerEl.appendChild(descriptionEl);
}
return li;
};
return PlaylistMenuItem;
}(Component);
var PlaylistMenu =
/*#__PURE__*/
function (_Component2) {
_inheritsLoose(PlaylistMenu, _Component2);
function PlaylistMenu(player, options) {
var _this2;
if (!player.playlist) {
throw new Error('videojs-playlist is required for the playlist component');
}
_this2 = _Component2.call(this, player, options) || this;
_this2.items = [];
if (options.horizontal) {
_this2.addClass('vjs-playlist-horizontal');
} else {
_this2.addClass('vjs-playlist-vertical');
} // If CSS pointer events aren't supported, we have to prevent
// clicking on playlist items during ads with slightly more
// invasive techniques. Details in the stylesheet.
if (options.supportsCssPointerEvents) {
_this2.addClass('vjs-csspointerevents');
}
_this2.createPlaylist_();
if (!videojs.browser.TOUCH_ENABLED) {
_this2.addClass('vjs-mouse');
}
_this2.on(player, ['loadstart', 'playlistchange', 'playlistsorted'], function (event) {
_this2.update();
}); // Keep track of whether an ad is playing so that the menu
// appearance can be adapted appropriately
_this2.on(player, 'adstart', function () {
_this2.addClass('vjs-ad-playing');
});
_this2.on(player, 'adend', function () {
_this2.removeClass('vjs-ad-playing');
});
_this2.on('dispose', function () {
_this2.empty_();
player.playlistMenu = null;
});
_this2.on(player, 'dispose', function () {
_this2.dispose();
});
return _this2;
}
var _proto2 = PlaylistMenu.prototype;
_proto2.createEl = function createEl() {
return dom.createEl('div', {
className: this.options_.className
});
};
_proto2.empty_ = function empty_() {
if (this.items && this.items.length) {
this.items.forEach(function (i) {
return i.dispose();
});
this.items.length = 0;
}
};
_proto2.createPlaylist_ = function createPlaylist_() {
var playlist = this.player_.playlist() || [];
var list = this.el_.querySelector('.vjs-playlist-item-list');
var overlay = this.el_.querySelector('.vjs-playlist-ad-overlay');
if (!list) {
list = document.createElement('ol');
list.className = 'vjs-playlist-item-list';
this.el_.appendChild(list);
}
this.empty_(); // create new items
for (var i = 0; i < playlist.length; i++) {
var item = new PlaylistMenuItem(this.player_, {
item: playlist[i]
}, this.options_);
this.items.push(item);
list.appendChild(item.el_);
} // Inject the ad overlay. IE<11 doesn't support "pointer-events:
// none" so we use this element to block clicks during ad
// playback.
if (!overlay) {
overlay = document.createElement('li');
overlay.className = 'vjs-playlist-ad-overlay';
list.appendChild(overlay);
} else {
// Move overlay to end of list
list.appendChild(overlay);
} // select the current playlist item
var selectedIndex = this.player_.playlist.currentItem();
if (this.items.length && selectedIndex >= 0) {
addSelectedClass(this.items[selectedIndex]);
var thumbnail = this.items[selectedIndex].$('.vjs-playlist-thumbnail');
if (thumbnail) {
dom.addClass(thumbnail, 'vjs-playlist-now-playing');
}
}
};
_proto2.update = function update() {
// replace the playlist items being displayed, if necessary
var playlist = this.player_.playlist();
if (this.items.length !== playlist.length) {
// if the menu is currently empty or the state is obviously out
// of date, rebuild everything.
this.createPlaylist_();
return;
}
for (var i = 0; i < this.items.length; i++) {
if (this.items[i].item !== playlist[i]) {
// if any of the playlist items have changed, rebuild the
// entire playlist
this.createPlaylist_();
return;
}
} // the playlist itself is unchanged so just update the selection
var currentItem = this.player_.playlist.currentItem();
for (var _i = 0; _i < this.items.length; _i++) {
var item = this.items[_i];
if (_i === currentItem) {
addSelectedClass(item);
if (document.activeElement !== item.el()) {
dom.addClass(item.thumbnail, 'vjs-playlist-now-playing');
}
notUpNext(item);
} else if (_i === currentItem + 1) {
removeSelectedClass(item);
upNext(item);
} else {
removeSelectedClass(item);
notUpNext(item);
}
}
};
return PlaylistMenu;
}(Component);
/**
* Returns a boolean indicating whether an element has child elements.
*
* Note that this is distinct from whether it has child _nodes_.
*
* @param {HTMLElement} el
* A DOM element.
*
* @return {boolean}
* Whether the element has child elements.
*/
var hasChildEls = function hasChildEls(el) {
for (var i = 0; i < el.childNodes.length; i++) {
if (dom.isEl(el.childNodes[i])) {
return true;
}
}
return false;
};
/**
* Finds the first empty root element.
*
* @param {string} className
* An HTML class name to search for.
*
* @return {HTMLElement}
* A DOM element to use as the root for a playlist.
*/
var findRoot = function findRoot(className) {
var all = document.querySelectorAll('.' + className);
var el;
for (var i = 0; i < all.length; i++) {
if (!hasChildEls(all[i])) {
el = all[i];
break;
}
}
return el;
};
/**
* Initialize the plugin on a player.
*
* @param {Object} [options]
* An options object.
*
* @param {HTMLElement} [options.el]
* A DOM element to use as a root node for the playlist.
*
* @param {string} [options.className]
* An HTML class name to use to find a root node for the playlist.
*
* @param {boolean} [options.playOnSelect = false]
* If true, will attempt to begin playback upon selecting a new
* playlist item in the UI.
*/
var playlistUi = function playlistUi(options) {
var player = this;
if (!player.playlist) {
throw new Error('videojs-playlist plugin is required by the videojs-playlist-ui plugin');
}
if (dom.isEl(options)) {
videojs.log.warn('videojs-playlist-ui: Passing an element directly to playlistUi() is deprecated, use the "el" option instead!');
options = {
el: options
};
}
options = videojs.mergeOptions(defaults, options); // If the player is already using this plugin, remove the pre-existing
// PlaylistMenu, but retain the element and its location in the DOM because
// it will be re-used.
if (player.playlistMenu) {
var el = player.playlistMenu.el(); // Catch cases where the menu may have been disposed elsewhere or the
// element removed from the DOM.
if (el) {
var parentNode = el.parentNode;
var nextSibling = el.nextSibling; // Disposing the menu will remove `el` from the DOM, but we need to
// empty it ourselves to be sure.
player.playlistMenu.dispose();
dom.emptyEl(el); // Put the element back in its place.
if (nextSibling) {
parentNode.insertBefore(el, nextSibling);
} else {
parentNode.appendChild(el);
}
options.el = el;
}
}
if (!dom.isEl(options.el)) {
options.el = findRoot(options.className);
}
player.playlistMenu = new PlaylistMenu(player, options);
}; // register components
videojs.registerComponent('PlaylistMenu', PlaylistMenu);
videojs.registerComponent('PlaylistMenuItem', PlaylistMenuItem); // register the plugin
registerPlugin('playlistUi', playlistUi);
playlistUi.VERSION = version;
return playlistUi;
})));
|
/**
* Internal helper functions for parsing DICOM elements
*/
var dicomParser = (function (dicomParser)
{
"use strict";
if(dicomParser === undefined)
{
dicomParser = {};
}
function readDicomDataSetImplicitUndefinedLength(byteStream)
{
var elements = {};
while(byteStream.position < byteStream.byteArray.length)
{
var element = dicomParser.readDicomElementImplicit(byteStream);
elements[element.tag] = element;
// we hit an item delimiter tag, return the current offset to mark
// the end of this sequence item
if(element.tag === 'xfffee00d')
{
return new dicomParser.DataSet(byteStream.byteArrayParser, byteStream.byteArray, elements);
}
}
// eof encountered - log a warning and return what we have for the element
byteStream.warnings.push('eof encountered before finding sequence item delimiter in sequence item of undefined length');
return new dicomParser.DataSet(byteStream.byteArrayParser, byteStream.byteArray, elements);
}
function readSequenceItemImplicit(byteStream)
{
var item = dicomParser.readSequenceItem(byteStream);
if(item.length === 4294967295)
{
item.hadUndefinedLength = true;
item.dataSet = readDicomDataSetImplicitUndefinedLength(byteStream);
item.length = byteStream.position - item.dataOffset;
}
else
{
item.dataSet = new dicomParser.DataSet(byteStream.byteArrayParser, byteStream.byteArray, {});
dicomParser.parseDicomDataSetImplicit(item.dataSet, byteStream, byteStream.position + item.length);
}
return item;
}
function readSQElementUndefinedLengthImplicit(byteStream, element)
{
while(byteStream.position < byteStream.byteArray.length)
{
// end reading this sequence if the next tag is the sequence delimitation item
var nextTag = dicomParser.readTag(byteStream);
byteStream.seek(-4);
if (nextTag === 'xfffee0dd') {
// set the correct length
element.length = byteStream.position - element.dataOffset;
byteStream.seek(8);
return element;
}
var item = readSequenceItemImplicit(byteStream);
element.items.push(item);
}
element.length = byteStream.byteArray.length - element.dataOffset;
}
function readSQElementKnownLengthImplicit(byteStream, element)
{
var maxPosition = element.dataOffset + element.length;
while(byteStream.position < maxPosition)
{
var item = readSequenceItemImplicit(byteStream);
element.items.push(item);
}
}
/**
* Reads sequence items for an element in an implicit little endian byte stream
* @param byteStream the implicit little endian byte stream
* @param element the element to read the sequence items for
*/
dicomParser.readSequenceItemsImplicit = function(byteStream, element)
{
if(byteStream === undefined)
{
throw "dicomParser.readSequenceItemsImplicit: missing required parameter 'byteStream'";
}
if(element === undefined)
{
throw "dicomParser.readSequenceItemsImplicit: missing required parameter 'element'";
}
element.items = [];
if(element.length === 4294967295)
{
readSQElementUndefinedLengthImplicit(byteStream, element);
}
else
{
readSQElementKnownLengthImplicit(byteStream, element);
}
};
return dicomParser;
}(dicomParser));
|
import ScrollController from "properjs-scrollcontroller";
import * as core from "../../core";
import Controller from "properjs-controller";
/**
*
* @public
* @global
* @class AnimateController
* @param {Element} element The dom element to work with.
* @classdesc Handle scroll events for a DOMElement.
*
*/
class AnimateController {
constructor ( container, elements, delay ) {
this.container = container;
this.elements = elements;
this.delay = delay || 100;
}
noop () {
this.animate( this.elements );
}
/**
*
* @instance
* @description Initialize the animation frame
* @memberof AnimateController
* @method start
*
*/
start () {
this.scroller = new ScrollController();
this.scroller.on( "scroll", () => {
this.handle();
});
this.handle();
}
handle () {
this.elements = this.container.find( core.config.lazyAnimSelector ).not( "[data-animate='true']" );
if ( !this.elements.length ) {
this.scroller.stop();
this.scroller = null;
core.log( "[AnimateController] Done!" );
} else {
const visible = core.util.getElementsInView( this.elements );
if ( visible.length ) {
this.animate( visible );
}
}
}
animate ( elems ) {
elems.attr( "data-animate", "true" );
// Sequence the animation of the elements
const animator = new Controller();
let lastTime = Date.now();
let currElem = 0;
animator.go(() => {
const currTime = Date.now();
if ( currElem === elems.length ) {
animator.stop();
core.log( "[AnimateController] Animation Complete!" );
} else if ( (currTime - lastTime) >= this.delay ) {
lastTime = currTime;
elems[ currElem ].className += " is-animated";
currElem++;
}
});
}
/**
*
* @instance
* @description Stop the animation frame
* @memberof AnimateController
* @method destroy
*
*/
destroy () {
if ( this.scroller ) {
this.scroller.destroy();
this.scroller = null;
}
}
}
/******************************************************************************
* Export
*******************************************************************************/
export default AnimateController;
|
var Reflux = require('reflux');
var socket = require('../socket');
var channelActions = Reflux.createActions([
'join',
'part',
'invite',
'kick',
'addUser',
'removeUser',
'removeUserAll',
'renameUser',
'setUsers',
'setTopic',
'setMode',
'load'
]);
channelActions.join.preEmit = (channels, server) => {
socket.send('join', { server, channels });
};
channelActions.part.preEmit = (channels, server) => {
socket.send('part', { server, channels });
};
channelActions.invite.preEmit = (user, channel, server) => {
socket.send('invite', { server, channel, user });
};
channelActions.kick.preEmit = (user, channel, server) => {
socket.send('kick', { server, channel, user });
};
module.exports = channelActions;
|
'use strict';
angular.module('app.channels')
.directive('scrollToBottom', [
function() {
return {
restrict: "A",
link: function(scope, element, attrs) {
// We dont want to abuse on watch but here it is critical to determine if the parameter has changed.
scope.$watch(function() {
return element[0].scrollHeight;
}, function(newValue, oldValue) {
element[0].scrollTop = newValue;
});
}
};
}
]);
|
module.exports = (sequelize, DataTypes) => {
const Songs = sequelize.define('Songs', {
title: DataTypes.STRING,
artist: DataTypes.STRING,
genre: DataTypes.STRING,
album: DataTypes.STRING,
albumImage: DataTypes.STRING,
youtubId: DataTypes.STRING,
lyrics: DataTypes.STRING,
tab: DataTypes.STRING
})
return Songs
}
|
var express = require('express'),
app = express(),
router = express.Router(),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
morest = require('../src/morest').Morest;
//Connect to your mongoDB database
mongoose.connect('mongodb://127.0.0.1:27017/bears');
//Use bodyparser
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var port = 8000;
//Load all the controllers
var BearController = require('./app/controllers/bear'),
HoneypotController = require('./app/controllers/honeypot'),
CaveController = require('./app/controllers/cave');
//Let Morest generate the routes for the /api endpoint
app.use('/api', morest(router, mongoose, {
controllers: [
BearController,
HoneypotController,
CaveController
]
}));
//Remove all old data
mongoose.model('Bear').remove()
.then(function () {
return mongoose.model('Honeypot').remove();
})
.then(function () {
return mongoose.model('Cave').remove();
})
//Prepare some new data to use
.then(function () {
return HoneypotController.prepData();
})
.then(function () {
return CaveController.prepData()
})
.then(function () {
return BearController.prepData()
})
.then(function () {
app.listen(port);
});
|
var mongodb = require('./mongodb');
var Schema = mongodb.Schema;
var ColumnMetaSchema = new Schema({
columnName : String,
order : Number,
locked : Boolean,
visible : Boolean
});
var ColumnMeta = mongodb.model("ColumnMeta", ColumnMetaSchema);
var ColumnMetaDAO = function(){};
//±£´æÐÅÏ¢
ColumnMetaDAO.prototype.save = function(obj, callback) {
var instance = new ColumnMeta(obj);
instance.save(function(err){
callback(err);
});
};
//»ñÈ¡ÁбíÐÅÏ¢
ColumnMetaDAO.prototype.getColumnMetaList = function(query, callback) {
ColumnMeta.find(query, '-_id -__v', {}, callback);
};
//»ñÈ¡µ¥ÌõÐÅÏ¢
ColumnMetaDAO.prototype.getColumnMeta = function(query, callback) {
ColumnMeta.findOne(query, '-_id -__v', {}, callback);
};
module.exports = new ColumnMetaDAO();
|
(function () {
var cache = {};
window.Storage = {
Set: function (key, value) {
//chrome.storage.sync.set({[key]: value});
chrome.storage.local.set({[key]: value});
},
SetLocal: function (key, value) {
chrome.storage.local.set({[key]: value});
},
GetSync: function (key, sendResponse) {
chrome.storage.sync.get(key, function (response) {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
} else {
sendResponse(response);
}
});
},
Get: function (key, sendResponse) {
chrome.storage.local.get(key, function (response) {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
} else {
if (Object.keys(response).length === 0 && response.constructor === Object) {
Storage.GetSync(key, sendResponse);
}
else {
sendResponse(response);
}
}
});
},
GetMultipleSync: function (key, sendResponse) {
chrome.storage.sync.get(key, function (response) {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
} else {
for (var i = 0; i < key.length; i++) {
cache[key[i]] = response[key[i]];
Storage.Set(key[i], response[key[i]]);
}
sendResponse(response);
}
});
},
GetMultiple: function (key, sendResponse) {
chrome.storage.local.get(key, function (response) {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
} else {
for (var i = 0; i < key.length; i++) {
cache[key[i]] = response[key[i]];
}
if (Object.keys(response).length === 0 && response.constructor === Object) {
Storage.GetMultipleSync(key, sendResponse);
} else {
sendResponse(response);
}
}
});
}
}
})();
|
(function (dust) {
// Note: all error conditions are logged to console and failed silently
/* make a safe version of console if it is not available
* currently supporting:
* _console.log
* */
var _console = (typeof console !== 'undefined') ? console : {
log: function () {
/* a noop*/
}
};
function isSelect(context) {
var value = context.current();
return typeof value === "object" && value.isSelect === true;
}
// Utility method : toString() equivalent for functions
function jsonFilter(key, value) {
if (typeof value === "function") {
//to make sure all environments format functions the same way
return value.toString()
//remove all leading and trailing whitespace
.replace(/(^\s+|\s+$)/mg, '')
//remove new line characters
.replace(/\n/mg, '')
//replace , and 0 or more spaces with ", "
.replace(/,\s*/mg, ', ')
//insert space between ){
.replace(/\)\{/mg, ') {')
;
}
return value;
}
// Utility method: to invoke the given filter operation such as eq/gt etc
function filter(chunk, context, bodies, params, filterOp) {
params = params || {};
var body = bodies.block,
actualKey,
expectedValue,
filterOpType = params.filterOpType || '';
// when @eq, @lt etc are used as standalone helpers, key is required and hence check for defined
if (typeof params.key !== "undefined") {
actualKey = dust.helpers.tap(params.key, chunk, context);
}
else if (isSelect(context)) {
actualKey = context.current().selectKey;
// supports only one of the blocks in the select to be selected
if (context.current().isResolved) {
filterOp = function () { return false; };
}
}
else {
_console.log("No key specified for filter in:" + filterOpType + " helper ");
return chunk;
}
expectedValue = dust.helpers.tap(params.value, chunk, context);
// coerce both the actualKey and expectedValue to the same type for equality and non-equality compares
if (filterOp(coerce(expectedValue, params.type, context), coerce(actualKey, params.type, context))) {
if (isSelect(context)) {
context.current().isResolved = true;
}
// we want helpers without bodies to fail gracefully so check it first
if (body) {
return chunk.render(body, context);
}
else {
_console.log("Missing body block in the " + filterOpType + " helper ");
return chunk;
}
}
else if (bodies['else']) {
return chunk.render(bodies['else'], context);
}
return chunk;
}
function coerce(value, type, context) {
if (value) {
switch (type || typeof (value)) {
case 'number': return +value;
case 'string': return String(value);
case 'boolean': {
value = (value === 'false' ? false : value);
return Boolean(value);
}
case 'date': return new Date(value);
case 'context': return context.get(value);
}
}
return value;
}
var helpers = {
// Utility helping to resolve dust references in the given chunk
// uses the Chunk.render method to resolve value
/*
Reference resolution rules:
if value exists in JSON:
"" or '' will evaluate to false, boolean false, null, or undefined will evaluate to false,
numeric 0 evaluates to true, so does, string "0", string "null", string "undefined" and string "false".
Also note that empty array -> [] is evaluated to false and empty object -> {} and non-empty object are evaluated to true
The type of the return value is string ( since we concatenate to support interpolated references
if value does not exist in JSON and the input is a single reference: {x}
dust render emits empty string, and we then return false
if values does not exist in JSON and the input is interpolated references : {x} < {y}
dust render emits < and we return the partial output
*/
"tap": function (input, chunk, context) {
// return given input if there is no dust reference to resolve
var output = input;
// dust compiles a string/reference such as {foo} to function,
if (typeof input === "function") {
// just a plain function (a.k.a anonymous functions) in the context, not a dust `body` function created by the dust compiler
if (input.isFunction === true) {
output = input();
} else {
output = '';
chunk.tap(function (data) {
output += data;
return '';
}).render(input, context).untap();
if (output === '') {
output = false;
}
}
}
return output;
},
"sep": function (chunk, context, bodies) {
var body = bodies.block;
if (context.stack.index === context.stack.of - 1) {
return chunk;
}
if (body) {
return bodies.block(chunk, context);
}
else {
return chunk;
}
},
"idx": function (chunk, context, bodies) {
var body = bodies.block;
if (body) {
return bodies.block(chunk, context.push(context.stack.index));
}
else {
return chunk;
}
},
/**
* contextDump helper
* @param key specifies how much to dump.
* "current" dumps current context. "full" dumps the full context stack.
* @param to specifies where to write dump output.
* Values can be "console" or "output". Default is output.
*/
"contextDump": function (chunk, context, bodies, params) {
var p = params || {},
to = p.to || 'output',
key = p.key || 'current',
dump;
to = dust.helpers.tap(to, chunk, context),
key = dust.helpers.tap(key, chunk, context);
if (key === 'full') {
dump = JSON.stringify(context.stack, jsonFilter, 2);
}
else {
dump = JSON.stringify(context.stack.head, jsonFilter, 2);
}
if (to === 'console') {
_console.log(dump);
return chunk;
}
else {
return chunk.write(dump);
}
},
/**
if helper for complex evaluation complex logic expressions.
Note : #1 if helper fails gracefully when there is no body block nor else block
#2 Undefined values and false values in the JSON need to be handled specially with .length check
for e.g @if cond=" '{a}'.length && '{b}'.length" is advised when there are chances of the a and b been
undefined or false in the context
#3 Use only when the default ? and ^ dust operators and the select fall short in addressing the given logic,
since eval executes in the global scope
#4 All dust references are default escaped as they are resolved, hence eval will block malicious scripts in the context
Be mindful of evaluating a expression that is passed through the unescape filter -> |s
@param cond, either a string literal value or a dust reference
a string literal value, is enclosed in double quotes, e.g. cond="2>3"
a dust reference is also enclosed in double quotes, e.g. cond="'{val}'' > 3"
cond argument should evaluate to a valid javascript expression
**/
"if": function (chunk, context, bodies, params) {
var body = bodies.block,
skip = bodies['else'];
if (params && params.cond) {
var cond = params.cond;
cond = dust.helpers.tap(cond, chunk, context);
// eval expressions with given dust references
if (eval(cond)) {
if (body) {
return chunk.render(bodies.block, context);
}
else {
_console.log("Missing body block in the if helper!");
return chunk;
}
}
if (skip) {
return chunk.render(bodies['else'], context);
}
}
// no condition
else {
_console.log("No condition given in the if helper!");
}
return chunk;
},
/**
* math helper
* @param key is the value to perform math against
* @param method is the math method, is a valid string supported by math helper like mod, add, subtract
* @param operand is the second value needed for operations like mod, add, subtract, etc.
* @param round is a flag to assure that an integer is returned
*/
"math": function (chunk, context, bodies, params) {
//key and method are required for further processing
if (params && typeof params.key !== "undefined" && params.method) {
var key = params.key,
method = params.method,
// operand can be null for "abs", ceil and floor
operand = params.operand,
round = params.round,
mathOut = null,
operError = function () { _console.log("operand is required for this math method"); return null; };
key = dust.helpers.tap(key, chunk, context);
operand = dust.helpers.tap(operand, chunk, context);
// TODO: handle and tests for negatives and floats in all math operations
switch (method) {
case "mod":
if (operand === 0 || operand === -0) {
_console.log("operand for divide operation is 0/-0: expect Nan!");
}
mathOut = parseFloat(key) % parseFloat(operand);
break;
case "add":
mathOut = parseFloat(key) + parseFloat(operand);
break;
case "subtract":
mathOut = parseFloat(key) - parseFloat(operand);
break;
case "multiply":
mathOut = parseFloat(key) * parseFloat(operand);
break;
case "divide":
if (operand === 0 || operand === -0) {
_console.log("operand for divide operation is 0/-0: expect Nan/Infinity!");
}
mathOut = parseFloat(key) / parseFloat(operand);
break;
case "ceil":
mathOut = Math.ceil(parseFloat(key));
break;
case "floor":
mathOut = Math.floor(parseFloat(key));
break;
case "round":
mathOut = Math.round(parseFloat(key));
break;
case "abs":
mathOut = Math.abs(parseFloat(key));
break;
default:
_console.log("method passed is not supported");
}
if (mathOut !== null) {
if (round) {
mathOut = Math.round(mathOut);
}
if (bodies && bodies.block) {
// with bodies act like the select helper with mathOut as the key
// like the select helper bodies['else'] is meaningless and is ignored
return chunk.render(bodies.block, context.push({ isSelect: true, isResolved: false, selectKey: mathOut }));
} else {
// self closing math helper will return the calculated output
return chunk.write(mathOut);
}
} else {
return chunk;
}
}
// no key parameter and no method
else {
_console.log("Key is a required parameter for math helper along with method/operand!");
}
return chunk;
},
/**
select helper works with one of the eq/ne/gt/gte/lt/lte/default providing the functionality
of branching conditions
@param key, ( required ) either a string literal value or a dust reference
a string literal value, is enclosed in double quotes, e.g. key="foo"
a dust reference may or may not be enclosed in double quotes, e.g. key="{val}" and key=val are both valid
@param type (optional), supported types are number, boolean, string, date, context, defaults to string
**/
"select": function (chunk, context, bodies, params) {
var body = bodies.block;
// key is required for processing, hence check for defined
if (params && typeof params.key !== "undefined") {
// returns given input as output, if the input is not a dust reference, else does a context lookup
var key = dust.helpers.tap(params.key, chunk, context);
// bodies['else'] is meaningless and is ignored
if (body) {
return chunk.render(bodies.block, context.push({ isSelect: true, isResolved: false, selectKey: key }));
}
else {
_console.log("Missing body block in the select helper ");
return chunk;
}
}
// no key
else {
_console.log("No key given in the select helper!");
}
return chunk;
},
/**
eq helper compares the given key is same as the expected value
It can be used standalone or in conjunction with select for multiple branching
@param key, The actual key to be compared ( optional when helper used in conjunction with select)
either a string literal value or a dust reference
a string literal value, is enclosed in double quotes, e.g. key="foo"
a dust reference may or may not be enclosed in double quotes, e.g. key="{val}" and key=val are both valid
@param value, The expected value to compare to, when helper is used standalone or in conjunction with select
@param type (optional), supported types are number, boolean, string, date, context, defaults to string
Note : use type="number" when comparing numeric
**/
"eq": function (chunk, context, bodies, params) {
if (params) {
params.filterOpType = "eq";
}
return filter(chunk, context, bodies, params, function (expected, actual) { return actual === expected; });
},
/**
ne helper compares the given key is not the same as the expected value
It can be used standalone or in conjunction with select for multiple branching
@param key, The actual key to be compared ( optional when helper used in conjunction with select)
either a string literal value or a dust reference
a string literal value, is enclosed in double quotes, e.g. key="foo"
a dust reference may or may not be enclosed in double quotes, e.g. key="{val}" and key=val are both valid
@param value, The expected value to compare to, when helper is used standalone or in conjunction with select
@param type (optional), supported types are number, boolean, string, date, context, defaults to string
Note : use type="number" when comparing numeric
**/
"ne": function (chunk, context, bodies, params) {
if (params) {
params.filterOpType = "ne";
return filter(chunk, context, bodies, params, function (expected, actual) { return actual !== expected; });
}
return chunk;
},
/**
lt helper compares the given key is less than the expected value
It can be used standalone or in conjunction with select for multiple branching
@param key, The actual key to be compared ( optional when helper used in conjunction with select)
either a string literal value or a dust reference
a string literal value, is enclosed in double quotes, e.g. key="foo"
a dust reference may or may not be enclosed in double quotes, e.g. key="{val}" and key=val are both valid
@param value, The expected value to compare to, when helper is used standalone or in conjunction with select
@param type (optional), supported types are number, boolean, string, date, context, defaults to string
Note : use type="number" when comparing numeric
**/
"lt": function (chunk, context, bodies, params) {
if (params) {
params.filterOpType = "lt";
return filter(chunk, context, bodies, params, function (expected, actual) { return actual < expected; });
}
},
/**
lte helper compares the given key is less or equal to the expected value
It can be used standalone or in conjunction with select for multiple branching
@param key, The actual key to be compared ( optional when helper used in conjunction with select)
either a string literal value or a dust reference
a string literal value, is enclosed in double quotes, e.g. key="foo"
a dust reference may or may not be enclosed in double quotes, e.g. key="{val}" and key=val are both valid
@param value, The expected value to compare to, when helper is used standalone or in conjunction with select
@param type (optional), supported types are number, boolean, string, date, context, defaults to string
Note : use type="number" when comparing numeric
**/
"lte": function (chunk, context, bodies, params) {
if (params) {
params.filterOpType = "lte";
return filter(chunk, context, bodies, params, function (expected, actual) { return actual <= expected; });
}
return chunk;
},
/**
gt helper compares the given key is greater than the expected value
It can be used standalone or in conjunction with select for multiple branching
@param key, The actual key to be compared ( optional when helper used in conjunction with select)
either a string literal value or a dust reference
a string literal value, is enclosed in double quotes, e.g. key="foo"
a dust reference may or may not be enclosed in double quotes, e.g. key="{val}" and key=val are both valid
@param value, The expected value to compare to, when helper is used standalone or in conjunction with select
@param type (optional), supported types are number, boolean, string, date, context, defaults to string
Note : use type="number" when comparing numeric
**/
"gt": function (chunk, context, bodies, params) {
// if no params do no go further
if (params) {
params.filterOpType = "gt";
return filter(chunk, context, bodies, params, function (expected, actual) { return actual > expected; });
}
return chunk;
},
/**
gte helper, compares the given key is greater than or equal to the expected value
It can be used standalone or in conjunction with select for multiple branching
@param key, The actual key to be compared ( optional when helper used in conjunction with select)
either a string literal value or a dust reference
a string literal value, is enclosed in double quotes, e.g. key="foo"
a dust reference may or may not be enclosed in double quotes, e.g. key="{val}" and key=val are both valid
@param value, The expected value to compare to, when helper is used standalone or in conjunction with select
@param type (optional), supported types are number, boolean, string, date, context, defaults to string
Note : use type="number" when comparing numeric
**/
"gte": function (chunk, context, bodies, params) {
if (params) {
params.filterOpType = "gte";
return filter(chunk, context, bodies, params, function (expected, actual) { return actual >= expected; });
}
return chunk;
},
// to be used in conjunction with the select helper
// TODO: fix the helper to do nothing when used standalone
"default": function (chunk, context, bodies, params) {
// does not require any params
if (params) {
params.filterOpType = "default";
}
return filter(chunk, context, bodies, params, function (expected, actual) { return true; });
},
/**
* size helper prints the size of the given key
* Note : size helper is self closing and does not support bodies
* @param key, the element whose size is returned
*/
"size": function (chunk, context, bodies, params) {
var key, value = 0, nr, k;
params = params || {};
key = params.key;
if (!key || key === true) { //undefined, null, "", 0
value = 0;
}
else if (dust.isArray(key)) { //array
value = key.length;
}
else if (!isNaN(parseFloat(key)) && isFinite(key)) { //numeric values
value = key;
}
else if (typeof key === "object") { //object test
//objects, null and array all have typeof ojbect...
//null and array are already tested so typeof is sufficient http://jsperf.com/isobject-tests
nr = 0;
for (k in key) {
if (Object.hasOwnProperty.call(key, k)) {
nr++;
}
}
value = nr;
} else {
value = (key + '').length; //any other value (strings etc.)
}
return chunk.write(value);
}
};
dust.helpers = helpers;
})(typeof exports !== 'undefined' ? module.exports = require('dustjs-linkedin') : dust);
|
function save_options(){
var openInNewTab = document.getElementById('open-in-new-tab').checked;
chrome.storage.sync.set({
openInNewTab: openInNewTab
})
}
// Restores select box and checkbox state using the preferences
// stored in chrome.storage.
function restore_options() {
chrome.storage.sync.get({
openInNewTab: false
}, function(items) {
document.getElementById('open-in-new-tab').checked = items.openInNewTab;
});
}
document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click', function(){
save_options();
})
|
describe('Wheel.Utils.ObjectPath', function() {
describe('#write', function() {
it('builds the full path with object literals, if none are found in window', function() {
if (window.Foo) { window.Foo = undefined; }
Wheel.Utils.ObjectPath.write('Foo.Bar.Zardoz', 3);
expect(window.Foo).toEqual({Bar: {Zardoz: 3}});
});
it('does not overwrite existing objects', function() {
var func = function () {};
window.Bar = func;
Wheel.Utils.ObjectPath.write('Bar.Foo.Zardoz', 42);
expect(window.Bar).toBe(func);
expect(window.Bar.Foo).toEqual({Zardoz: 42});
});
it('works when the path is not an object path', function() {
Wheel.Utils.ObjectPath.write('Wazup', 42);
expect(window.Wazup).toBe(42);
});
it('return the full path', function() {
expect(Wheel.Utils.ObjectPath.write('Kiss.My.App', 13)).toBe(Kiss.My.App);
});
});
describe('#read', function() {
it('will get the value at a path', function() {
Wheel.Utils.ObjectPath.write('Kiss.My.App', 13);
expect(Wheel.Utils.ObjectPath.read('Kiss.My.App')).toBe(13);
});
it('will return null if the path does not exist', function() {
expect(Wheel.Utils.ObjectPath.read('Funk.The.Dunk')).toBe(null);
});
});
});
|
/*------------------------------------*\
navigation
\*------------------------------------*/
/**
* listeners for hovers and keyboard support for the menus
*/
/**
* TODO: Use event delegation instead of adding click events in for loops like some kind of animal...
* http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html
*/
vital.nav = (function(){
/**
* -private
*
* Mobile Menu
*
* Dropdown Menu
*
* Keyboard Focus
*
* -public
*
* init
*/
/**
* PRIVATE
*/
/*------------------------------------*\
Mobile Menu
\*------------------------------------*/
//menu is hidden with javascript at mobile sizes by the js--toggle-visuallyhidden class
//this is overwritten in css at larger screen sizes and also overwritten in noscript
//The mobile menu is animated as if it's another dropdown in this version.
//to use FLIP style animations the menu needs to be positioned absolutely, this version
//pushes all content down instead. For a FLIPped example see black jamm or look at:
//https://aerotwist.com/blog/flip-your-animations/
function _mobileTogglesMouseDown(e){
//called after mousedown event on anything with .menu-toggle class...
//click event for left clicks only! http://www.jacklmoore.com/notes/click-events
if (!(e.which > 1 || e.shiftKey || e.altKey || e.metaKey)) {
e.preventDefault();
e.stopImmediatePropagation();
var self = e.currentTarget;
var menu = document.getElementById( self.getAttribute('data-menu') );
if(menu){
if(apollo.hasClass(menu, 'active-dropdown')){
apollo.removeClass(self, 'menu-open');
_dropAnimate_hide(menu);
//apollo.removeClass(menu[i], 'expanded-mobile-menu');
//menu[i].style.height = null;
}else{
apollo.addClass(self, 'menu-open');
_dropAnimate_show(menu);
//_expandMobileMenu(menu[i]);
}
}
}//left clicks
}//_mobileTogglesMouseDown(e)
function _mobileMenuSetup(){
/**
* Because we also open these menus on focus putting the actions here on .click() does not work
* because the focus event (in most browsers) fires after mousedown but before mouseup
* so the .click() actions would immediately close the dropdowns
* (as they would have been opened by the focus event firing on mousedown)...
* by putting the logic on mousedown and preventing default we are able to circumvent this...
*/
//there could be more than one...
var menuToggles = document.getElementsByClassName('menu-toggle');
var i, l;
l = menuToggles.length;
if(l){
for ( i = l - 1; i >= 0; i--) {
menuToggles[i].addEventListener('mousedown', _mobileTogglesMouseDown, false);
menuToggles[i].addEventListener('click', vital.u_clickKiller.clickKiller, false);
}
}
}//_mobileMenuSetup
/*------------------------------------*\
Dropdown Menu
\*------------------------------------*/
/**
* TIDYING UP ANIMATIONS
*/
function _dropAnimate_tidy(e){
//get rid of this listener
e.currentTarget.removeEventListener('transitionend', _dropAnimate_tidy, false);
//remove inline height style now it's animated to
e.currentTarget.style.removeProperty('height');
//remove the animating-dropdown class which turns on transitions.
apollo.removeClass(e.currentTarget, 'animating-dropdown');
//inactive dropdowns should be visually hidden after transitioning
if(!apollo.hasClass(e.currentTarget, 'active-dropdown')){
apollo.addClass(e.currentTarget, 'js--toggle-visuallyhidden');
}
}//function _dropAnimate_tidy(e){
/**
* ANIMATE SHOWING MOBILE DROPDOWNS
*/
function _dropAnimate_show(dropdown, dropdownLink){
//make sure we're clean before starting this process...
_dropAnimate_tidy( { currentTarget: dropdown } );
//highlight the active link if it has been specified
if(dropdownLink !== undefined){
apollo.addClass(dropdownLink, 'active-dropdown-link');
}
//set this dropdown to it's 'active' state (actually does nothing but act as a js indicator)
apollo.addClass(dropdown, 'active-dropdown');
//remove the visuallyhidden class to get dropdown to full height:
apollo.removeClass(dropdown, 'js--toggle-visuallyhidden');
var mobSized = window.getComputedStyle( document.querySelector('.menu-toggle') ).getPropertyValue( 'display' ) === 'block';
//we only do the actual animation steps if we know transitionend event is supported
//they also only apply at mobile sizes - for desktop the active-dropdown class is enough!
if(vital.u_detect.transitionend && mobSized){
//grab the dimensions of the menu whilst it's expanded
var animateTo = dropdown.getBoundingClientRect();
//set height to 0 so we have something to transition from
dropdown.style.height = 1 + 'px';
// Wait for the next frame so we know all the style changes have taken hold.
requestAnimationFrame(function() {
//switch on animations.
//has to be done with class because the changes above need to be instant...
apollo.addClass(dropdown, 'animating-dropdown');
//listen for this animation to finish so we can clear up inline styles etc.
dropdown.addEventListener('transitionend', _dropAnimate_tidy, false);
//replace the 1px height with the full menu height for a smooth transition
dropdown.style.height = animateTo.height + 'px';
});//requestAnimationFrame(function() {
}//if(vital.u_detect.transitionend){
}//function _dropAnimate_show(dropdown, dropdownLink){
/**
* ANIMATE HIDING MOBIE DROPDOWNS
*/
function _dropAnimate_hide(dropdown, dropdownLink){
//make sure we're clean before starting this process...
_dropAnimate_tidy( { currentTarget: dropdown } );
//un-highlight the active link if it has been specified
if(dropdownLink !== undefined){
apollo.removeClass(dropdownLink, 'active-dropdown-link');
}
//remove the active state from this dropdown
apollo.removeClass(dropdown, 'active-dropdown');
var mobSized = window.getComputedStyle( document.querySelector('.menu-toggle') ).getPropertyValue( 'display' ) === 'block';
//we only do the actual animation steps if we know transitionend event is supported
//they also only apply at mobile sizes - for desktop the active-dropdown class is enough!
if(vital.u_detect.transitionend && mobSized){
//get current dropdown size - this is what we'll animate 'from'
var animateFrom = dropdown.getBoundingClientRect();
//set the dropdown to it's own height - purely for animation reasons!
dropdown.style.height = animateFrom.height + 'px';
// Wait for the next frame so we know all the style changes have taken hold.
requestAnimationFrame(function() {
//switch on animations.
//has to be done with class because the changes above need to be instant...
apollo.addClass(dropdown, 'animating-dropdown');
//listen for this animation to finish so we can clear up inline styles etc.
dropdown.addEventListener('transitionend', _dropAnimate_tidy, false);
//replace the full height with 1px to shrink the menu
dropdown.style.height = '1px';
});//requestAnimationFrame(function() {
}else{//if(vital.u_detect.transitionend){
//if we can't detect transitionend then just set it straight back to non visible
//rather than waiting for the animation to finish first
apollo.addClass(dropdown, 'js--toggle-visuallyhidden');
}//if(vital.u_detect.transitionend){
}//function _dropAnimate_hide(dropdown, dropdownLink){
/**
* EVENT HANDLERS
*/
function _dropdownTogglesMouseDown(e){
//called on touchstart or mousedown events on dropdown-toggle classed things
/**
* at mobile sizes all clicks (both touch and mouse) should expand the nav
* we only listen for mousedown rather than both here to avoid ghost clicks...
*/
var currentDropMenu = e.currentTarget.parentNode.getElementsByClassName('dropdown-menu')[0];
//var mobSized = window.getComputedStyle( e.currentTarget ).getPropertyValue( 'display' ) === 'block';
var mobSized = window.getComputedStyle( document.querySelector('.menu-toggle') ).getPropertyValue( 'display' ) === 'block';
//console.log('mobSized = '+mobSized);
if( mobSized && (e.type ==='mousedown') ){
if (!(e.which > 1 || e.shiftKey || e.altKey || e.metaKey)) {
e.stopPropagation();
e.preventDefault();
if(apollo.hasClass(currentDropMenu, 'active-dropdown')){
_dropAnimate_hide(currentDropMenu, e.currentTarget);
}else{
_dropAnimate_show(currentDropMenu, e.currentTarget);
}
}
}else if( !mobSized && (e.type === 'touchstart') ){
/**
* we're at sizes without the expanding menu so replicate hover but only for touch
*/
e.stopPropagation();
e.preventDefault();
if(apollo.hasClass(currentDropMenu, 'active-dropdown')){
//apollo.removeClass(currentDropMenu, 'active-dropdown');
//apollo.removeClass(e.currentTarget, 'active-dropdown-link');
_dropAnimate_hide(currentDropMenu, e.currentTarget);
}else{
//clear open dropdowns
_bodyDropClear(null);
_dropAnimate_show(currentDropMenu, e.currentTarget);
document.querySelector('body').addEventListener('touchstart', _bodyDropClear, false);
}
}//not mobiles && touch event
}//_dropdownTogglesMouseDown(e)
function _bodyDropClear(e){
//function to remove dropdown classes when body is touched...
document.querySelector('body').removeEventListener('touchstart', _bodyDropClear, false);
//removing all active dropdown links
var activeDrops = document.getElementsByClassName('active-dropdown-link');
/**
* Looping backwards because getElementsByClassName produces a LiveNodeList that gets
* shorter as elements are removed...
*/
var i, l;
l = activeDrops.length;
for (i = l - 1; i >= 0; i--) {
apollo.removeClass(activeDrops[i], 'active-dropdown-link');
}
//and the actual dropdowns
activeDrops = document.getElementsByClassName('active-dropdown');
/**
* Looping backwards because getElementsByClassName produces a LiveNodeList that gets
* shorter as elements are removed...
*/
l = activeDrops.length;
for (i = l - 1; i >= 0; i--) {
//apollo.removeClass(activeDrops[i], 'active-dropdown');
_dropAnimate_hide(activeDrops[i]);
}
}
function _dropdownsSetup(){
/**
Binding both touch and mouse and sorting out logic internally...
*/
var dropdownToggles = document.getElementsByClassName('dropdown-toggle');
var i, l;
l = dropdownToggles.length;
if(l){
for (i = l - 1; i >= 0; i--) {
dropdownToggles[i].addEventListener('touchstart', _dropdownTogglesMouseDown, false);
dropdownToggles[i].addEventListener('mousedown', _dropdownTogglesMouseDown, false);
/**
* kill standard click events at sizes where the drop menus don't have to expand on click...
*/
dropdownToggles[i].addEventListener('click', _mobileKillClick, false);//click listener
}//for
}//if(l)
}//_dropdownsSetup
function _mobileKillClick(e){
if( window.getComputedStyle( document.querySelector('.menu-toggle') ).getPropertyValue( 'display' ) === 'block' ){
vital.u_clickKiller.clickKiller(e);
}
}
/*------------------------------------*\
Menu Keyboard focus
\*------------------------------------*/
function _mainNavLinksFocus(){
//called when any of the main nav links (.main-navigation a) are focused
var theMenu = document.querySelectorAll('.main-navigation .menu')[0];
if(!apollo.hasClass(theMenu, 'active-dropdown')){
//_expandMobileMenu(theMenu);
_dropAnimate_show(theMenu);
apollo.addClass(document.getElementsByClassName('menu-toggle')[0], 'menu-open');
}
}
function _dropdownLinksFocus(e){
//called when '.dropdown-menu li a' is focused
var loopNode = e.currentTarget;
apollo.addClass(loopNode, 'currently-focused-link');
while( loopNode.parentNode.tagName.toLowerCase() !== 'nav' ){
var loopParent = loopNode.parentNode;
if( apollo.hasClass(loopParent, 'dropdown-menu') && !apollo.hasClass(loopParent, 'active-dropdown') ){
console.log('expanding a menu due to focus');
//if it isn't already, expand the menu that this link lives in
_dropAnimate_show(loopParent);
}
if( apollo.hasClass(loopParent, 'dropdown') ){
apollo.addClass(loopParent, 'focused');
}
loopNode = loopParent;
}
}
function _dropdownLinksBlur(e){
//called when '.dropdown-menu li a' is blurred
var loopNode = e.currentTarget;
apollo.removeClass(loopNode, 'currently-focused-link');
//put into rAF so that the focus event can add a currently-focused-class before this blur function runs!
requestAnimationFrame(function(){
while( loopNode.parentNode.tagName.toLowerCase() !== 'nav' ){
var loopParent = loopNode.parentNode;
if( apollo.hasClass(loopParent, 'dropdown-menu') && !loopParent.querySelector('.currently-focused-link') ){
console.log('closing a menu due to blur event');
//hide if there are no focused links anywhere under this parent
_dropAnimate_hide(loopParent);
}
if( apollo.hasClass(loopParent, 'dropdown') ){
apollo.removeClass(loopParent, 'focused');
}
loopNode = loopParent;
}//while( loopNode.parentNode.tagName.toLowerCase() !== 'nav' ){
});//requestAnimationFrame(function(){
}
function _menuKeyboardSetup(){
/**
* Keyboard focusing will open but not close the mobile nav
*/
var mainNavLinks = document.querySelectorAll('.main-navigation a');
var i, l;
l = mainNavLinks.length;
if(l){
for (i = l - 1; i >= 0; i--) {
mainNavLinks[i].addEventListener('focus', _mainNavLinksFocus, false);
}//for
}//if(l)
var dropdownLinks = document.querySelectorAll('.dropdown-menu li a');
l = dropdownLinks.length;
if(l){
for (i = l - 1; i >= 0; i--) {
dropdownLinks[i].addEventListener('focus', _dropdownLinksFocus, false);
dropdownLinks[i].addEventListener('blur', _dropdownLinksBlur, false);
}//for
}//if(l)
}//_menuKeyboardSetup()
/**
* PUBLIC
*/
function init(){
_mobileMenuSetup();
_dropdownsSetup();
_menuKeyboardSetup();
}
//revealing public methods
return {
init : init,
};
}()); //vital.nav
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2016
*/
/* eslint-disable max-len */
import LocalizedStrings from 'react-native-localization';
export const buttonStrings = new LocalizedStrings({
gb: {
add_batch: 'Add Batch',
add_master_list_items: 'Add Master List Items',
all_items_selected: 'All Items Selected',
create_automatic_order: 'Create Automatic Order',
current: 'Current',
done: 'Done',
hide_stockouts: 'Hide Stockouts',
manage_stocktake: 'Manage Stocktake',
new_invoice: 'New Invoice',
new_item: 'New Item',
new_line: 'New Line',
new_requisition: 'New Requisition',
new_stocktake: 'New Stocktake',
new_supplier_invoice: 'New Supplier Invoice',
past: 'Past',
use_suggested_quantities: 'Use Suggested Quantities',
use_requested_quantities: 'Use Requested Quantities',
},
fr: {
add_batch: 'Ajouter un lot',
add_master_list_items: "Ajouter une liste-Maître d'articles ?",
all_items_selected: 'Tout les articles sélectionnés',
create_automatic_order: 'Créer une commande automatiquement',
current: 'Actuel',
done: 'Terminé',
hide_stockouts: 'Cacher les ruptures de stocks',
manage_stocktake: "Gérer l'inventaire",
new_invoice: 'Nouvelle facture',
new_item: 'Nouvel Article',
new_line: 'Nouvelle ligne',
new_requisition: 'Nouvelle réquisition',
new_stocktake: 'Nouvel inventaire',
new_supplier_invoice: 'Nouvelle facture fournisseur',
past: 'Archives',
use_suggested_quantities: 'Utiliser les quantités suggérées',
use_requested_quantities: 'Utiliser les quantités demandées',
},
gil: { // TODO: add_batch
add_master_list_items: 'Rinea am list',
all_items_selected: 'Aikai nikabane',
create_automatic_order: 'Create Automatic Order',
current: 'Ai tibwa ngkai',
done: 'E a tia',
hide_stockouts: 'Tai kaoti ake a bane',
manage_stocktake: 'Manage Stocktake',
new_invoice: 'Am karao-oota\nae boou',
new_item: 'Karina am bwai\nn aoraki ae boou',
new_line: 'Te bwain aoraki\nae kainnanoaki',
new_requisition: 'Am oota\nae karina',
new_stocktake: 'Warebwai ae boou',
new_supplier_invoice: 'Bebwan am oota\nman pharmacy',
past: 'Are I mwaina',
use_requested_quantities: 'Kabongana maitina\nae kainnanoaki',
use_suggested_quantities: 'Kabongana te\nmwaiti are e katauaki',
},
tl: { // TODO: add_batch
add_master_list_items: 'Utiliza Lista Master',
all_items_selected: 'Hili Item Hotu',
create_automatic_order: 'Kria Orden Automátiku',
current: 'Atuál',
done: 'Hotu',
hide_stockouts: 'Hili item ho Qtd ejiste',
manage_stocktake: 'Maneja Ajustamentu',
new_invoice: 'Invoice Foun',
new_item: 'Item Foun',
new_line: 'Linha Foun',
new_requisition: 'Rekuizisaun Foun',
new_stocktake: 'Ajustamentu Foun',
new_supplier_invoice: 'Distribuidor nia Invoice Foun',
past: 'Pasadu',
use_suggested_quantities: 'Kuantidade Sujere',
use_requested_quantities: 'Kuantidade Ezije',
},
la: {
add_batch: 'ໃສ່ເລກຊຸດຜະລິດ',
add_master_list_items: 'ເພີ່ມລາຍການສິນຄ້າທັງໝົດທີ່ມີຢູ່',
all_items_selected: 'ລາຍການທັງໝົດຖືກເລືອກແລ້ວ',
create_automatic_order: 'ຄຳສັງແບບອັດຕະໂນມັດ',
current: 'ປັດຈຸບັນ',
done: 'ສໍາເລັດແລ້ວ',
hide_stockouts: 'ເຊື່ອງ ການຂາດສິນຄ້າໃສສາງ',
manage_stocktake: 'ເຮັດການຈັດການ ກວດກາສິນຄ້າໃນສາງ',
new_invoice: 'ເຮັດໃບເກັບເງິນໃໝ່',
new_item: 'ເຮັດລາຍການສິນຄ້າມາໃໝ່',
new_line: 'ເພີ່ມລາຍການໃໝ່',
new_requisition: 'ເຮັດການສະເໜີຂໍໃຫມ່',
new_stocktake: 'ເຮັດການກວດສາສາງໃໝ່',
new_supplier_invoice: 'ໃບຮັບສິນຄ້າໃໝ່',
past: 'ໃນທີ່ຜ່ານມາ',
use_suggested_quantities: 'ນຳໃຊ້ຈຳນວນທີ່ຖືກແນະນຳ',
use_requested_quantities: 'ນຳໃຊ້ຈຳນວນທີ່ສະເໜີຂໍ',
},
});
|
var React = require("react");
var PropTypes = require("prop-types");
var { requireNativeComponent } = require("react-native");
var NativeAutoComplete = requireNativeComponent("RCTAutoComplete", null);
class RCTAutoComplete extends React.Component {
constructor(props) {
super(props);
this.state = {
mostRecentEventCount: 0
};
this._getText = this._getText.bind(this);
this._onChange = this._onChange.bind(this);
this._onFocus = this._onFocus.bind(this);
this._onBlur = this._onBlur.bind(this);
}
_getText() {
return typeof this.props.value === "string"
? this.props.value
: this.props.defaultValue;
}
_onChange(event) {
var text = event.nativeEvent.text;
var eventCount = event.nativeEvent.eventCount;
this.props.onChange && this.props.onChange(event);
this.props.onChangeText && this.props.onChangeText(text);
this.setState({ mostRecentEventCount: eventCount }, () => {
// This is a controlled component, so make sure to force the native value
// to match. Most usage shouldn't need this, but if it does this will be
// more correct but might flicker a bit and/or cause the cursor to jump.
if (text !== this.props.value && typeof this.props.value === "string") {
this.refs.input &&
this.refs.input.setNativeProps({
text: this.props.value
});
}
});
event.nativeEvent.possibleCompletionsForString &&
this.props.onTyping &&
this.props.onTyping(event.nativeEvent.possibleCompletionsForString);
event.nativeEvent.didSelectAutoCompleteString &&
this.props.onSelect &&
this.props.onSelect(event.nativeEvent.didSelectAutoCompleteString);
}
_onFocus(event) {
if (this.props.onFocus) {
this.props.onFocus(event);
}
}
_onBlur(event) {
if (this.props.onBlur) {
this.props.onBlur(event);
}
}
render() {
var props = Object.assign({}, this.props);
return (
<NativeAutoComplete
ref="autocomplete"
{...props}
onChange={this._onChange}
onFocus={this._onFocus}
onBlur={this._onBlur}
onSelectionChangeShouldSetResponder={() => true}
text={this._getText()}
mostRecentEventCount={this.state.mostRecentEventCount}
/>
);
}
}
RCTAutoComplete.PropTypes = {
/**
* If false, disables auto-correct. The default value is true.
*/
autoCorrect: PropTypes.bool,
/**
* The string that will be rendered before text input has been entered
*/
placeholder: PropTypes.string,
/**
* When the clear button should appear on the right side of the text view
* @platform ios
*/
clearButtonMode: PropTypes.oneOf([
"never",
"while-editing",
"unless-editing",
"always"
]),
/**
* If true, clears the text field automatically when editing begins
* @platform ios
*/
clearTextOnFocus: PropTypes.bool,
/**
* Determines which keyboard to open, e.g.`numeric`.
*
* The following values work across platforms:
* - default
* - numeric
* - email-address
*/
keyboardType: PropTypes.oneOf([
// Cross-platform
"default",
"numeric",
"email-address",
// iOS-only
"ascii-capable",
"numbers-and-punctuation",
"url",
"number-pad",
"phone-pad",
"name-phone-pad",
"decimal-pad",
"twitter",
"web-search"
]),
/**
* Determines how the return key should look.
* @platform ios
*/
returnKeyType: PropTypes.oneOf([
"default",
"go",
"google",
"join",
"next",
"route",
"search",
"send",
"yahoo",
"done",
"emergency-call"
]),
/**
* If true, the keyboard disables the return key when there is no text and
* automatically enables it when there is text. The default value is false.
* @platform ios
*/
enablesReturnKeyAutomatically: PropTypes.bool,
/**
* Can tell TextInput to automatically capitalize certain characters.
*
* - characters: all characters,
* - words: first letter of each word
* - sentences: first letter of each sentence (default)
* - none: don't auto capitalize anything
*/
autoCapitalize: PropTypes.oneOf(["none", "sentences", "words", "characters"]),
/**
* Set the position of the cursor from where editing will begin.
* @platorm android
*/
textAlign: PropTypes.oneOf(["start", "center", "end"]),
cellComponent: PropTypes.string,
suggestions: PropTypes.array,
autoCompleteFetchRequestDelay: PropTypes.number,
maximumNumberOfAutoCompleteRows: PropTypes.number,
showTextFieldDropShadowWhenAutoCompleteTableIsOpen: PropTypes.bool,
autoCompleteTableViewHidden: PropTypes.bool,
autoCompleteTableBorderColor: PropTypes.string,
autoCompleteTableBorderWidth: PropTypes.number,
autoCompleteTableBackgroundColor: PropTypes.string,
autoCompleteTableCornerRadius: PropTypes.number,
autoCompleteTableTopOffset: PropTypes.number,
autoCompleteTableLeftOffset: PropTypes.number,
autoCompleteTableSizeOffset: PropTypes.number,
autoCompleteRowHeight: PropTypes.number,
autoCompleteFontSize: PropTypes.number,
autoCompleteRegularFontName: PropTypes.string,
autoCompleteBoldFontName: PropTypes.string,
autoCompleteTableCellTextColor: PropTypes.string,
autoCompleteTableCellBackgroundColor: PropTypes.string,
applyBoldEffectToAutoCompleteSuggestions: PropTypes.bool,
reverseAutoCompleteSuggestionsBoldEffect: PropTypes.bool,
disableAutoCompleteTableUserInteractionWhileFetching: PropTypes.bool
};
RCTAutoComplete.defaultProps = {
autoCorrect: false,
clearTextOnFocus: true,
showTextFieldDropShadowWhenAutoCompleteTableIsOpen: true,
reverseAutoCompleteSuggestionsBoldEffect: false,
autoCompleteTableViewHidden: false,
applyBoldEffectToAutoCompleteSuggestions: false,
enablesReturnKeyAutomatically: false,
disableAutoCompleteTableUserInteractionWhileFetching: false,
placeholder: "Search a name",
clearButtonMode: "while-editing",
returnKeyType: "go",
textAlign: "center",
autoCompleteTableTopOffset: 10,
autoCompleteTableLeftOffset: 20,
autoCompleteTableSizeOffset: 40,
autoCompleteTableBorderColor: "lightblue",
autoCompleteTableBackgroundColor: "azure",
autoCompleteTableCornerRadius: 8,
autoCompleteTableBorderWidth: 1,
autoCompleteFontSize: 18,
autoCompleteRegularFontName: "Helvetica Neue",
autoCompleteBoldFontName: "Helvetica Bold",
autoCompleteTableCellTextColor: "dimgray",
autoCompleteRowHeight: 40,
autoCompleteFetchRequestDelay: 100,
maximumNumberOfAutoCompleteRows: 6
};
module.exports = RCTAutoComplete;
|
import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as ViewActions from '../actions';
import Marker from '../components/Marker';
import Card from '../components/Card';
import SelectedWrapper from '../containers/SelectedWrapper';
import PictureWithFrame from '../components/PictureWithFrame';
import { MAINPAGE_STYLE, MAINPAGE_WRAPPER_STYLE } from '../constants/styles/Mainpage-Styles';
import { CARD_STYLE } from '../constants/styles/Card-Styles';
import { MARKER_STYLES } from '../constants/styles/Marker-Styles';
import Radium, { StyleRoot } from 'radium';
import { iconMappings } from '../constants/iconMappings';
import { fetchData } from '../actions/index';
import { getData } from '../data/dataFetcher';
@Radium
class MainpageContainer extends Component {
static fetchData() {
return getData('cards');
}
_renderCards() {
const selectedCardId = this._extractSelectedCard(this.props.views.items);
if (this._extractCardIds(this.props.views.items).indexOf(selectedCardId) > -1) {
return (<SelectedWrapper
actions={this.props.actions}
selectedTab={this.props.tab}
component={this.props.views.items[selectedCardId - 1]} />);
}
else {
return (<PictureWithFrame />);
}
}
_renderMarkers() {
return (this.props.views.items.map(item => <Marker key={item.id} markerId={item.id}
actions={this.props.actions}
selected={item.selected}
style={MARKER_STYLES[item.id]}
hoverIcon={this._generateHoverIcon(item.icon)} />));
}
_generateHoverIcon(iconKey) {
return iconMappings[iconKey];
}
_extractSelectedCard(cards) {
const selectedCard = cards.find(card => {
return card.selected === true;
});
return selectedCard ? selectedCard.id : 0;
}
_extractCardIds(cards) {
return cards.map(card => {
return card.id;
});
}
render() {
const markers = this._renderMarkers();
const cards = this._renderCards();
return (<StyleRoot><div style={MAINPAGE_STYLE}>
<div style={MAINPAGE_WRAPPER_STYLE}>
{markers}
{cards}
</div>
</div>
</StyleRoot>
);
}
}
MainpageContainer
.propTypes = {
views: PropTypes.object.isRequired,
actions: PropTypes.object.isRequired
}
function
mapStateToProps(state) {
return {
views: state.views,
tab: state.tab.selectedTab
}
}
function
mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(ViewActions, dispatch)
}
}
export default connect(mapStateToProps,
mapDispatchToProps)(MainpageContainer)
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Project = mongoose.model('Project'),
Task = mongoose.model('Task'),
User = mongoose.model('User'),
_ = require('lodash');
/**
* Create a Project
*/
exports.createProject = function(req, res) {
var project = new Project(req.body);
project.user = req.user;
User.findById(req.user._id).exec(function(err, userTimeline){
project.timeline = userTimeline.timeline;
project.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(project);
}
});
});
};
/**
* Show the current Project
*/
exports.readProject = function(req, res) {
res.jsonp(req.project);
};
/**
* Update a Project
*/
exports.updateProject = function(req, res) {
var project = req.project;
project = _.extend(project, req.body);
project.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
Task.findOne({projectId: project._id}).exec(function(err, task){
if(task){
task.projectName = project.name;
task.save();
}
});
res.jsonp(project);
}
});
};
/**
* Delete an Project
*/
exports.deleteProject = function(req, res) {
var project = req.project;
if(project.user._id !== req.user._id)
return res.status(403).send('User is not authorized');
project.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(project);
}
});
};
/**
* List of Projects
*/
exports.listProjects = function(req, res) {
Project.find({'timeline':req.user.timeline}).where(req.query).sort('-created').populate('user', 'username').populate('tasks', 'projectName personName group cohort startDate endDate').exec(function(err, projects) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(projects);
}
});
};
/**
* Project middleware
*/
exports.projectByID = function(req, res, next, id) {
Project.findById(id).populate('user', 'displayName').exec(function(err, project) {
if (err) return next(err);
if (!project) return next(new Error('Failed to load Project ' + id));
req.project = project;
next();
});
};
/**
* Project authorization middleware
*/
exports.hasAuthorization = function(req, res, next) {
if (req.project.timeline._id !== req.user.timeline._id) {
return res.status(403).send('User is not authorized');
}
next();
};
|
'use strict';
/**
* An Animation.
* @param frameRate {Number} The ideal number of frame changes per second for this animation.
* @constructor
*/
var Animation = function (frameRate) {
this.frameDeltaSum = 0;
this.targetFrameDelta = 1000 / (frameRate || 20);
this.frame = 0;
this.frames = [];
};
/**
* Manually add a draw function for a single frame.
* @param draw {Function} A draw function.
* @returns {Object} The Animation.
*/
Animation.prototype.addFrame = function (draw) {
if ('function' === typeof(draw)) {
this.frames.push(draw);
}
return this;
};
/**
* Add an image to an animation.
* @param image {String} The image key from the the ResourceLoader.
* @param width (optional) {Number} The width of each cell in a multi-cell image.
* @param height (optional) {Number} The height of each cell in a multi-cell image.
* @param rows (optional) {Number} The number of rows in a multi-cell image.
* @param columns (optional) {Number} The number of columns in a multi-cell image.
* @param x {Number} (optional) The x offset of the first cell in a multi-cell image.
* @param y {Number} (optional) The x offset of the first cell in a multi-cell image.
* @returns {Object} The Animation.
*/
Animation.prototype.addFrames = function (image, width, height, rows, columns, x, y) {
if (!image) {
throw new Error('Animation.addFrames requires an image argument.');
}
width = width || image.naturalWidth || 0;
height = height || image.naturalHeight || 0;
rows = rows || 1;
columns = columns || 1;
x = x || 0;
y = y || 0;
function getDrawFn(image, x, y, width, height) {
return function (context) {
context.drawImage(image, x, y, width, height, 0, 0, width, height);
}
}
for (var row = 0; row < rows; row++) {
for (var col = 0; col < columns; col++) {
var fn = getDrawFn(image, (col * width) + x, (row * height) + y, width, height);
this.addFrame(fn);
}
}
return this;
};
Animation.prototype.update = function (game) {
if (this.frameDeltaSum < this.targetFrameDelta) {
this.frameDeltaSum += game.frameDelta;
return;
}
this.frameDeltaSum = 0;
if (this.frame === this.frames.length - 1) {
this.frame = -1;
}
this.frame += 1;
};
Animation.prototype.draw = function () {
this.frames[this.frame].apply(this, arguments);
};
Animation.prototype.reset = function () {
this.frame = 0;
};
module.exports = Animation;
|
function displayMWError() {
kony.ui.Alert("Middleware Error ", null, "error", null, null);
};
function displaySessionError() {
kony.ui.Alert("Session Expired .. Please re-login", null, "error", null, null);
};
function displayError(code, msg) {
// Commented for SWA: kony.ui.Alert("Error Code: "..code .." Message: " ..msg,null,"error",null,null);
kony.ui.Alert(code + "- " + msg, null, "error", null, null);
};
var mergeHeaders = function(httpHeaders, globalHeaders) {
for (var attrName in globalHeaders) {
httpHeaders[attrName] = globalHeaders[attrName];
}
return httpHeaders;
};
function appmiddlewareinvoker(inputParam, isBlocking, indicator, datasetID) {
var url = appConfig.url;
var sessionIdKey = "cacheid";
inputParam.appID = appConfig.appId;
inputParam.appver = appConfig.appVersion;
inputParam["channel"] = "rc";
inputParam["platform"] = kony.os.deviceInfo().name;
if (indicator) {
inputParam["indicator"] = indicator;
};
if (datasetID) {
inputParam["datasetID"] = datasetID;
};
inputParam[sessionIdKey] = sessionID;
if (globalhttpheaders) {
if (inputParam["httpheaders"]) {
inputParam.httpheaders = mergeHeaders(inputParam.httpheaders, globalhttpheaders);
} else {
inputParam["httpheaders"] = globalhttpheaders;
};
};
var resulttable = _invokeServiceSyncForMF_(url, inputParam, isBlocking);
if (resulttable) {
if (resulttable[sessionIdKey]) {
sessionID = resulttable[sessionIdKey];
};
};
return resulttable;
};
function appmiddlewaresecureinvoker(inputParam, isBlocking, indicator, datasetID) {
var url = appConfig.secureurl;
var sessionIdKey = "cacheid";
inputParam.appID = appConfig.appId;
inputParam.appver = appConfig.appVersion;
inputParam["channel"] = "rc";
inputParam["platform"] = kony.os.deviceInfo().name;
if (indicator) {
inputParam["indicator"] = indicator;
};
if (datasetID) {
inputParam["datasetID"] = datasetID;
};
inputParam[sessionIdKey] = sessionID;
if (globalhttpheaders) {
if (inputParam["httpheaders"]) {
inputParam.httpheaders = mergeHeaders(inputParam.httpheaders, globalhttpheaders);
} else {
inputParam["httpheaders"] = globalhttpheaders;
};
};
var resulttable = _invokeServiceSyncForMF_(url, inputParam, isBlocking);
if (resulttable) {
if (resulttable[sessionIdKey]) {
sessionID = resulttable[sessionIdKey];
};
};
return resulttable;
};
function appmiddlewareinvokerasync(inputParam, callBack) {
var url = appConfig.url;
var sessionIdKey = "cacheid";
inputParam.appID = appConfig.appId;
inputParam.appver = appConfig.appVersion;
inputParam["channel"] = "rc";
inputParam["platform"] = kony.os.deviceInfo().name;
inputParam[sessionIdKey] = sessionID;
if (globalhttpheaders) {
if (inputParam["httpheaders"]) {
inputParam.httpheaders = mergeHeaders(inputParam.httpheaders, globalhttpheaders);
} else {
inputParam.httpheaders = globalhttpheaders;
};
};
var connHandle = _invokeServiceAsyncForMF_(url, inputParam, callBack);
return connHandle;
};
function appmiddlewaresecureinvokerasync(inputParam, callBack) {
var url = appConfig.secureurl;
var sessionIdKey = "cacheid";
inputParam.appID = appConfig.appId;
inputParam.appver = appConfig.appVersion;
inputParam["channel"] = "rc";
inputParam["platform"] = kony.os.deviceInfo().name;
inputParam[sessionIdKey] = sessionID;
if (globalhttpheaders) {
if (inputParam["httpheaders"]) {
inputParam.httpheaders = mergeHeaders(inputParam.httpheaders, globalhttpheaders);
} else {
inputParam["httpheaders"] = globalhttpheaders;
};
};
var connHandle = _invokeServiceAsyncForMF_(url, inputParam, callBack);
return connHandle;
};
function appmiddlewaresecureinvokerasyncForMBAAS(inputParam, serviceID, operationID, callBack) {
var url = appConfig.secureurl;
var sessionIdKey = "cacheid";
inputParam.appID = appConfig.appId;
inputParam.appver = appConfig.appVersion;
inputParam["channel"] = "rc";
inputParam["platform"] = kony.os.deviceInfo().name;
inputParam[sessionIdKey] = sessionID;
if (globalhttpheaders) {
if (inputParam["httpheaders"]) {
inputParam.httpheaders = mergeHeaders(inputParam.httpheaders, globalhttpheaders);
} else {
inputParam["httpheaders"] = mergeHeaders({}, globalhttpheaders);
};
};
kony.print("Async : Invoking service through mbaas with url : " + url + " service id : " + serviceID + " operationid : " + operationID + "\n input params" + JSON.stringify(inputParam));
if (kony.mbaas) {
kony.mbaas.invokeMbaasServiceFromKonyStudio(url, inputParam, serviceID, operationID, callBack);
} else {
alert("Unable to find the MBAAS SDK for KonyStudio. Please download the SDK from the Kony Cloud Console and add as module to the Kony Project.");
}
};
function appmiddlewaresecureinvokersyncForMBAAS(inputParam, serviceID, operationID) {
var url = appConfig.secureurl;
var sessionIdKey = "cacheid";
var resulttable;
inputParam.appID = appConfig.appId;
inputParam.appver = appConfig.appVersion;
inputParam["channel"] = "rc";
inputParam["platform"] = kony.os.deviceInfo().name;
inputParam[sessionIdKey] = sessionID;
if (globalhttpheaders) {
if (inputParam["httpheaders"]) {
inputParam.httpheaders = mergeHeaders(inputParam.httpheaders, globalhttpheaders);
} else {
inputParam["httpheaders"] = mergeHeaders({}, globalhttpheaders);
};
};
kony.print("Invoking service through mbaas with url : " + url + " service id : " + serviceID + " operationid : " + operationID + "\n input params" + JSON.stringify(inputParam));
if (kony.mbaas) {
resulttable = kony.mbaas.invokeMbaasServiceFromKonyStudioSync(url, inputParam, serviceID, operationID);
kony.print("Result table for service id : " + serviceID + " operationid : " + operationID + " : " + JSON.stringify(resulttable));
} else {
alert("Unable to find the MBAAS SDK for KonyStudio. Please download the SDK from the Kony Cloud Console and add as module to the Kony Project.");
}
return resulttable;
};
_invokeServiceAsyncForMF_ = function(url, inputParam, callBack) {
var operationID = inputParam["serviceID"];
if (!operationID) {
resulttable = kony.net.invokeServiceAsync(url, inputParam, callBack);
} else {
var _mfServicesMap_ = {};
kony.print("Getting serviceID for : " + operationID);
var serviceID = _mfServicesMap_[operationID] && _mfServicesMap_[operationID]["servicename"];
kony.print("Got serviceID for : " + operationID + " : " + serviceID);
kony.print("Async : Invoking service through mbaas with url : " + url + " service id : " + serviceID + " operationid : " + operationID + "\n input params" + JSON.stringify(inputParam));
if (serviceID && operationID) {
var url = appConfig.secureurl;
if (kony.mbaas) {
kony.mbaas.invokeMbaasServiceFromKonyStudio(url, inputParam, serviceID, operationID, callBack);
} else {
alert("Unable to find the MBAAS SDK for KonyStudio. Please download the SDK from the Kony Cloud Console and add as module to the Kony Project.");
}
} else {
resulttable = kony.net.invokeServiceAsync(url, inputParam, callBack);
}
}
};
_invokeServiceSyncForMF_ = function(url, inputParam, isBlocking) {
var resulttable;
var operationID = inputParam["serviceID"];
if (!operationID) {
resulttable = kony.net.invokeService(url, inputParam, isBlocking);
} else {
var _mfServicesMap_ = {};
kony.print("Getting serviceID for : " + operationID);
var serviceID = _mfServicesMap_[operationID] && _mfServicesMap_[operationID]["servicename"];
kony.print("Got serviceID for : " + operationID + " : " + serviceID);
kony.print("Invoking service through mbaas with url : " + url + " service id : " + serviceID + " operationid : " + operationID + "\n input params" + JSON.stringify(inputParam));
if (serviceID && operationID) {
var url = appConfig.secureurl;
if (kony.mbaas) {
resulttable = kony.mbaas.invokeMbaasServiceFromKonyStudioSync(url, inputParam, serviceID, operationID);
kony.print("Result table for service id : " + serviceID + " operationid : " + operationID + " : " + JSON.stringify(resulttable));
} else {
alert("Unable to find the MBAAS SDK for KonyStudio. Please download the SDK from the Kony Cloud Console and add as module to the Kony Project.");
}
} else {
resulttable = kony.net.invokeService(url, inputParam, isBlocking);
}
}
return resulttable;
};
function appmenuseq() {
frmHomeNew.show();
};
function callAppMenu() {
var appMenu = [
["appmenuitemid1", "Item 1", "option1.png", appmenuseq,
{}],
["appmenuitemid2", "Item 2", "option2.png", appmenuseq,
{}],
["appmenuitemid3", "Item 3", "option3.png", appmenuseq,
{}],
["appmenuitemid4", "Item 4", "option4.png", appmenuseq,
{}]
];
kony.application.createAppMenu("sampAppMenu", appMenu, "", "");
kony.application.setCurrentAppMenu("sampAppMenu");
};
function makeCall(eventobject) {
kony.phone.dial(eventobject.text);
};
function initializeGlobalVariables() {};
|
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
/**
Hide Sidebar by clicking submenu item.
@method actions.subMenuEl
*/
hideSidebar() {
Ember.$('.ui.sidebar').sidebar('hide');
},
/**
Expand menu items by click.
@method actions.subMenuEl
*/
subMenuEl(event) {
let $this = Ember.$(event.currentTarget).parent().find('.subMenu:first');
if ($this.hasClass('hidden')) {
$this.removeClass('hidden');
Ember.$(event.target).parent().find('.item-minus:first').removeClass('hidden');
Ember.$(event.target).parent().find('.item-plus:first').addClass('hidden');
} else {
$this.addClass('hidden');
Ember.$(event.target).parent().find('.item-minus:first').addClass('hidden');
Ember.$(event.target).parent().find('.item-plus:first').removeClass('hidden');
}
}
}
});
|
(function () {
'use strict';
angular
.module('app.layout')
.controller('Header', Header);
function Header($scope, authenticatedUser, $state, $timeout, $mdDialog, usersApi) {
$scope.logout = function () {
authenticatedUser.logout();
$timeout(function () {
$state.go('login');
}, 2000);
};
}
})();
|
import axios from 'axios';
import {
FETCH_USER,
FETCH_ITEMS,
FETCH_BACKPACK,
ADD_ITEM_TO_BACKPACK,
DEL_ITEM_FROM_BACKPACK,
REMOVE_ITEM_FROM_BACKPACK,
RECALCULATE_TOTAL_PRICE,
DISCARD_BACKPACK,
SAVE_BACKPACK,
CHECKOUT_BACKPACK,
BACKPACK_IS_LOADING,
BACKPACK_HAS_ERRORED,
FETCH_BACKPACK_SUCCESS
} from './types';
export const fetchItems = () => async dispatch => {
//console.log('_action_fetchItems_Getting Items');
//const res = await axios.get('/api/items');
//console.log('_action_fetchItems_Got Items', res.data);
//dispatch({ type: FETCH_ITEMS, payload: res.data });
//console.log('_action_fetchItems_state', getState());
dispatch(BackpackIsLoading(true));
const res = await axios.get('/api/items');
dispatch(BackpackIsLoading(false));
if (!res.data) {
dispatch(BackpackHasErrored(true));
}
//console.log('_action_fetchItems_Got items ', res.data);
dispatch(FetchBackpackSuccess(res.data));
};
export const fetchUser = () => async dispatch => {
//console.log('_action_fetchUser_Getting user');
const res = await axios.get('/api/current_user');
//console.log('_action_fetchUser_Got user', res.data);
dispatch({ type: FETCH_USER, payload: res.data });
};
export const fetchBackpack = () => async (dispatch, getState) => {
//console.log('_action_fetchBackpack_state', getState());
const state = getState();
const id = state.user._id;
dispatch(IsLoading(true));
const res = await axios.get(`/api/backpacks/user/${id}`);
dispatch(IsLoading(false));
if (!res.data.backpack) {
dispatch(HasErrored(true));
}
//console.log('_action_fetchBackpack_Got user backpack', res.data.backpack);
dispatch(FetchDataSuccess(res.data.backpack));
//dispatch({ type: FETCH_BACKPACK, payload: res.data.backpack });
};
// };
export const addItemToBackpack = id => dispatch => {
//console.log('_action_addItemToBackpack ', id);
dispatch({ type: ADD_ITEM_TO_BACKPACK, payload: id });
};
export const delItemFromBackpack = id => dispatch => {
//console.log('_action_delItemFromBackpack ', id);
dispatch({ type: DEL_ITEM_FROM_BACKPACK, payload: id });
};
export const removeItemFromBackpack = id => dispatch => {
//console.log('_action_removeItemFromBackpack ', id);
dispatch({ type: REMOVE_ITEM_FROM_BACKPACK, payload: id });
};
export const recalcutateTotalPrice = () => (dispatch, getState) => {
//console.log('_action_recalculateTotalPrice');
const state = getState();
const items = state.items;
dispatch({
type: RECALCULATE_TOTAL_PRICE,
items: items
});
};
export const discardBackpack = id => async dispatch => {
//console.log('_action_discardBackpack');
const res = await axios.get(`/api/backpacks/${id}/del`);
dispatch({ type: DISCARD_BACKPACK, payload: res });
};
export const saveBackpack = backpack => async dispatch => {
//console.log('_action_saveBackpack');
const res = await axios.post(
`/api/backpacks/${backpack._id}/update`,
backpack
);
dispatch({ type: SAVE_BACKPACK, payload: res });
};
export const checkoutBackpack = id => dispatch => {
//console.log('_action_checkoutBackpack');
const res = 'checked out';
dispatch({ type: CHECKOUT_BACKPACK, payload: res });
};
export function BackpackHasErrored(bool) {
return {
type: HAS_ERRORED,
hasErrored: bool
};
}
export function BackpackIsLoading(bool) {
return {
type: IS_LOADING,
isLoading: bool
};
}
export function FetchBackpackSuccess(backpack) {
return {
type: FETCH_BACKPACK_SUCCESS,
backpack
};
}
export function ItemsHasErrored(bool) {
return {
type: HAS_ERRORED,
hasErrored: bool
};
}
export function ItemsIsLoading(bool) {
return {
type: IS_LOADING,
isLoading: bool
};
}
export function FetchItemsSuccess(items) {
return {
type: FETCH_ITEMS_SUCCESS,
items
};
}
|
'use strict';
const Code = require('code');
const Lab = require('lab');
const Client = require('../lib/client');
const Manager = require('../lib/manager');
const lab = exports.lab = Lab.script();
const expect = Code.expect;
const describe = lab.describe;
const it = lab.it;
function createManager () {
const m = new Manager({ errors: { policy: 'throw' } });
m.error = (err) => {
m._err = err;
};
return m;
}
describe('Client', () => {
describe('constructor', () => {
it('creates a new Client object', (done) => {
const m = createManager();
const c = new Client(m);
expect(c).to.be.an.instanceof(Client);
expect(c._manager).to.shallow.equal(m);
expect(c._reporters).to.equal([]);
expect(c._commander).to.be.null();
done();
});
it('returns an instance of Client without new', (done) => {
const m = createManager();
const c = Client(m);
expect(c).to.be.an.instanceof(Client);
expect(c._manager).to.shallow.equal(m);
expect(c._reporters).to.equal([]);
expect(c._commander).to.be.null();
done();
});
});
describe('setCommander()', () => {
it('sets the commander object', (done) => {
const c = new Client();
const commander = { connect: () => {}, respond: () => {} };
expect(c._commander).to.be.null();
c.setCommander(commander);
expect(c._commander).to.shallow.equal(commander);
done();
});
it('errors on invalid commander', (done) => {
const m = createManager();
const c = new Client(m);
const errRe = /commander must be an object|invalid (connect|respond)\(\) method/;
function fail (commander) {
c.setCommander(commander);
expect(m._err).to.be.an.error(TypeError, errRe);
m._err = null;
}
fail(null);
fail(undefined);
fail('');
fail(0);
fail([]);
fail({});
fail({ connect: 1, respond: () => {} });
fail({ connect: () => {}, respond: 1 });
expect(c._commander).to.equal(null);
done();
});
});
describe('addReporter()', () => {
it('adds reporters to the reporters list', (done) => {
const c = new Client();
const reporter = { report: () => {} };
expect(c._reporters).to.equal([]);
c.addReporter(reporter);
expect(c._reporters).to.have.length(1);
expect(c._reporters[0]).to.shallow.equal(reporter);
done();
});
it('errors on invalid reporter', (done) => {
const m = createManager();
const c = new Client(m);
const errRe = /reporter must be an object|invalid report\(\) method/;
function fail (reporter) {
c.addReporter(reporter);
expect(m._err).to.be.an.error(TypeError, errRe);
m._err = null;
}
fail(null);
fail(undefined);
fail('');
fail(0);
fail([]);
fail({});
fail({ report: 1 });
expect(c._reporters).to.equal([]);
done();
});
});
describe('connect()', () => {
it('calls the _commanders connect method and executes the provided callback when done', (done) => {
const m = createManager();
const c = new Client(m);
const commander = {
connect (manager, callback) {
expect(manager).to.shallow.equal(m);
expect(callback).to.be.a.function();
callback();
},
respond () {}
};
c.setCommander(commander);
c.connect(done);
});
it('calls the _commanders connect method', (done) => {
const m = createManager();
const c = new Client(m);
const commander = {
connect (manager, callback) {
expect(manager).to.shallow.equal(m);
expect(callback).to.be.a.function();
done();
},
respond () {}
};
c.setCommander(commander);
c.connect();
});
it('errors if there is no commander', (done) => {
const c = new Client();
c.connect((err) => {
expect(err).to.be.an.error(Error, 'command interface not configured');
done();
});
});
});
describe('respond()', () => {
it('results in an error if there is no commander', (done) => {
const c = new Client();
c.respond(null, (err) => {
expect(err).to.be.an.error(Error, 'command interface not configured');
done();
});
});
it('results in an error if the message can not be stringify cleanly', (done) => {
const c = new Client();
const message = { foo: true };
message.bar = message;
c._commander = {};
c.respond(message, (err) => {
expect(err).to.be.an.error(Error, 'Converting circular structure to JSON: { foo: true, bar: [Circular] }');
done();
});
});
it('calls the respond() method of the commander object with a string message', (done) => {
const c = new Client();
c._commander = {
respond (message, callback) {
expect(message).to.equal('hello world');
expect(callback).to.be.a.function();
callback();
}
};
c.respond('hello world', done);
});
it('calls the respond() method of the commander object with an object message', (done) => {
const c = new Client();
c._commander = {
respond (message, callback) {
message = JSON.parse(message);
expect(message).to.equal({ foo: 'bar' });
expect(callback).to.be.a.function();
done();
}
};
c.respond({ foo: 'bar' });
});
});
describe('report()', () => {
it('results in an error if the message can not be stringify cleanly', (done) => {
const c = new Client();
const message = { foo: true };
message.bar = message;
c.report(message, (err) => {
expect(err).to.be.an.error(Error, 'Converting circular structure to JSON: { foo: true, bar: [Circular] }');
done();
});
});
it('calls the report() method of all the reporters', (done) => {
const c = new Client();
const one = {
report (message, callback) {
message = JSON.parse(message);
expect(message).to.equal({ foo: 'bar' });
callback();
}
};
const two = {
report (message, callback) {
message = JSON.parse(message);
expect(message).to.equal({ foo: 'bar' });
setImmediate(callback);
}
};
const three = {
report (message, callback) {
expect(message).to.equal('hello world');
callback();
}
};
c._reporters = [one, two];
c.report({ foo: 'bar' });
c._reporters = [three];
c.report('hello world', done);
});
});
});
|
/**
* array-some
* Array#some ponyfill for older browsers
* (Ponyfill: A polyfill that doesn't overwrite the native method)
*
* https://github.com/twada/array-some
*
* Copyright (c) 2015-2016 Takuto Wada
* Licensed under the MIT license.
* https://github.com/twada/array-some/blob/master/MIT-LICENSE
*/
'use strict';
module.exports = function some (ary, callback, thisArg) {
if (ary.some) {
return ary.some(callback, thisArg);
}
for (var i = 0; i < ary.length; i+=1) {
if (callback.call(thisArg, ary[i], i, ary)) {
return true;
}
}
return false;
};
|
'use strict';
var passport = require('passport');
var _ = require('underscore');
var formidable = require('formidable');
var md5 = require('md5');
var fs = require('fs');
var random = require('random-token');
var Models = require('../models/main');
var Additional = new (require('./additional'))();
var Mail = new (require('./mail'))();
var Orders = new (require('./orders'))();
var generate_code = random.create('0123456789');
class API {
// Auth and registration
registration(req, res, next) {
var user_data = {
mail: req.body.mail,
pass: md5(req.body.password),
first: req.body.first,
last: req.body.last,
code: generate_code(12)
};
if (!Additional.checkArguments(user_data)) {
return res.send(Additional.serialize(2, 'Required fields are empty'));
}
Models.users.findOne({
mail: user_data.mail
}).then(function (user) {
if (user) {
return res.send(Additional.serialize(3, 'User with this email are exists'));
}
var additional_user_data = {
status: 0,
success_tests: []
};
_.extend(user_data, additional_user_data);
return Models.users.create(user_data);
}).then(function (user) {
if (!user.mail) {
return false;
}
Mail.registration(user);
Mail.confirm(user);
return res.send(Additional.serialize(0));
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
login(req, res, next) {
passport.authenticate('local', function(err, user) {
if (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
}
else if (!user) {
return res.send(Additional.serialize(2, 'No user data'));
}
req.logIn(user, function(err) {
if (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
}
else {
res.cookie('dclog', user._id);
return res.send(Additional.serialize(0, user));
}
});
})(req, res, next);
}
logout(req, res, next) {
req.logout();
res.clearCookie('dclog');
return res.send(Additional.serialize(0));
}
checkStatus(req, res, next) {
var user_data = req.user;
if (!user_data) {
return res.send(Additional.serialize(1));
}
user_data._id = null;
user_data.pass = null;
return res.send(Additional.serialize(0, user_data));
}
confirmation(req, res, next) {
var confirmation_code = req.query.code;
if (!confirmation_code) {
return res.send(Additional.serialize(2, 'No code'));
}
Models.users.findOne({
code: confirmation_code,
status: 0
}).then(function (user) {
if (!user) {
return res.send(Additional.serialize(2, 'Incorrect code'));
}
return Models.users.update({
code: confirmation_code,
status: 0
}, {
status: 1
});
}).then(function () {
return res.send(Additional.serialize(0));
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
// Reports
report(req, res, next) {
var report_type = req.body.type;
var report_data = {
text: req.body.text,
question: req.body.question
};
if (!report_data.text || !report_type) {
return res.send(Additional.serialize(2, 'Incorrect data'));
}
var user = req.user ? req.user._id : null;
var additional_report_data = {
user: user,
addr: req.body.addr,
type: report_type,
date: new Date(),
solved: false
};
_.extend(report_data, additional_report_data);
Models.reports.create(report_data).then(function () {
return res.send(Additional.serialize(0));
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
solveReport(req, res, next) {
var report_num = req.body.report;
if (!report_num) {
return res.send(Additional.serialize(2, 'Incorrect data'));
}
Models.reports.update({
_id: report_num,
solved: false
}, {
solved: true
}).then(function (info) {
if (info.n) {
return res.send(Additional.serialize(0));
}
else {
return res.send(Additional.serialize(3, 'Incorrect report number'));
}
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
// Admin
createTest(req, res, next) {
var form = new formidable.IncomingForm({
uploadDir: "temp"
});
form.parse(req, function (err, field, files) {
if (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
}
var test_data = {
title: field.title,
description: field.description,
subjects: field.subjects,
easyCol: field.easyCol,
middleCol: field.middleCol,
hardCol: field.hardCol,
easyTime: field.easyTime,
middleTime: field.middleTime,
hardTime: field.hardTime,
img: Date.now() + '.png'
};
var image = files.img;
if (!Additional.checkArguments(test_data) || !image) {
return res.send(Additional.serialize(2, 'Required fields are empty'));
}
test_data.active = false;
fs.rename(image.path, 'client/source/images/uploaded/' + test_data.img, function(err) {
if (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
}
});
test_data.subjects = test_data.subjects.split('|');
Models.tests.create(test_data).then(function () {
return res.send(Additional.serialize(0));
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
});
}
editTest(req, res, next) {
var test_data = {
title: req.body.title,
description: req.body.description,
subjects: req.body.subjects,
easyCol: req.body.easyCol,
middleCol: req.body.middleCol,
hardCol: req.body.hardCol,
easyTime: req.body.easyTime,
middleTime: req.body.middleTime,
hardTime: req.body.hardTime
};
var test_num = req.body._id;
if (!Additional.checkArguments(test_data) || !test_num) {
return res.send(Additional.serialize(2, 'Required fields are empty'));
}
test_data.active = req.body.active;
test_data.subjects = test_data.subjects.split('|');
Models.tests.update({
_id: test_num
}, test_data).then(function (info) {
if (info.n) {
return res.send(Additional.serialize(0));
}
else {
return res.send(Additional.serialize(3, 'Incorrect test number'));
}
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
imageTest(req, res, next) {
var form = new formidable.IncomingForm({
uploadDir: "temp"
});
form.parse(req, function (err, fields, files) {
var data = {
num: fields.test,
img: files.img
};
if (!Additional.checkArguments(data)) {
return res.send(Additional.serialize(2, 'Required fields are empty'));
}
var filename = Date.now() + '.png';
fs.rename(data.img.path, 'client/source/images/uploaded/' + filename, function(err) {
if (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
}
});
Models.tests.update({
_id: data.num
}, {
img: filename
}).then(function (info) {
if (info.n) {
return res.send(Additional.serialize(0));
}
else {
return res.send(Additional.serialize(3, 'Incorrect test number'));
}
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
});
}
addQuestion(req, res, next) {
var question_data = {
text: req.body.text,
answer1: req.body.answer1,
answer2: req.body.answer2,
answer3: req.body.answer3,
answer4: req.body.answer4,
true_answer: req.body.true_answer,
complexity: req.body.complexity,
test: req.body.test
};
if (req.body.code) {
question_data.code = req.body.code;
}
if (!Additional.checkArguments(question_data)) {
return res.send(Additional.serialize(2, 'Required fields are empty'));
}
Models.questions.create(question_data).then(function () {
return res.send(Additional.serialize(0));
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
editQuestion(req, res, next) {
var question_data = {
text: req.body.text,
answer1: req.body.answer1,
answer2: req.body.answer2,
answer3: req.body.answer3,
answer4: req.body.answer4,
true_answer: req.body.true_answer,
complexity: req.body.complexity
};
var question_num = req.body._id;
if (!Additional.checkArguments(question_data) || !question_num) {
return res.send(Additional.serialize(2, 'Required fields are empty'));
}
question_data.code = req.body.code;
Models.questions.update({
_id: question_num
}, question_data).then(function () {
return res.send(Additional.serialize(0));
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
deleteQuestion(req, res, next) {
var question_num = req.body._id;
if (!question_num) {
return res.send(Additional.serialize(2, 'Required fields are empty'));
}
Models.questions.findOneAndRemove({
_id: question_num
}).then(function () {
return res.send(Additional.serialize(0));
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
getTest(req, res, next) {
var target_test = req.query.test;
Models.tests.findOne({
_id: target_test,
active: true
}).then(function (test) {
if (!test) {
return res.send(Additional.serialize(12, 'Not found'));
}
else {
return res.send(Additional.serialize(0, test));
}
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
getTests(req, res, next) {
var request_type = Number(req.query.type);
var user = req.user;
var query = {};
var target_tests;
Models.tests.find({
active: true
}).then(function (all_tests) {
switch (request_type) {
// only not solved
case 1:
target_tests = all_tests.filter(function (test) {
return !(user.success_tests.indexOf(test._id) > -1);
});
break;
// only solved
case 2:
target_tests = all_tests.filter(function (test) {
return user.success_tests.indexOf(test._id) > -1;
});
break;
default:
target_tests = all_tests;
}
return res.send(Additional.serialize(0, target_tests));
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
allTests(req, res, next) {
Models.tests.find().then(function (tests) {
return res.send(Additional.serialize(0, tests));
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
allQuestions(req, res, next) {
Models.questions.find().then(function (tests) {
return res.send(Additional.serialize(0, tests));
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
availableTest(req, res, next) {
var user = req.user;
var test = req.query.num;
Additional.checkAvailable(user, test).then(function (result) {
return res.send(Additional.serialize(0, result));
}).catch(function (err) {
return res.send(Additional.serialize(err));
});
}
startTesting(req, res, next) {
var user = req.user;
var test_num = req.body.num;
var test;
var all_question;
if (!test_num) {
return res.send(Additional.serialize(2, 'Required fields are empty'));
}
if (user.success_tests.indexOf(test_num) > -1) {
return res.send(Additional.serialize(3, 'You have already passed this test'));
}
Additional.checkAvailable(user, test_num).then(function (result) {
if (!result.available) {
return res.send(Additional.serialize(4, 'The recent failed attempt'));
}
return Models.tests.findOne({
_id: test_num,
active: true
});
}).then(function (target_test) {
test = target_test;
var question_search = [];
for (var i = 1; i <= 3; i++) {
question_search.push(Models.questions.find({
test: test_num,
complexity: i
}));
}
return Promise.all(question_search);
}).then(function (questions) {
var easy = _.sample(questions[0], test.easyCol);
var middle = _.sample(questions[1], test.middleCol);
var hard = _.sample(questions[2], test.hardCol);
easy = _.pluck(easy, '_id');
middle = _.pluck(middle, '_id');
hard = _.pluck(hard, '_id');
all_question = easy.concat(middle, hard);
return Models.solutions.create({
start: new Date(),
user: user._id,
test: test_num,
questions: all_question,
answers: [],
result: null
});
}).then(function (solution) {
return res.send(Additional.serialize(0, solution));
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
takeAnswer(req, res, next) {
var answer_data = {
user: req.user,
answer_num: req.body.answer_num,
question_num: req.body.question,
test_num: req.body.test,
solution_num: req.body.solution
};
if (!Additional.checkArguments(answer_data)) {
return res.send(Additional.serialize(2, 'Required fields are empty'));
}
var last_question = false;
var target_solution;
var search = [];
search.push(Models.solutions.findOne({
_id: answer_data.solution_num,
user: answer_data.user._id
}));
search.push(Models.questions.findOne({
_id: answer_data.question_num
}));
Promise.all(search).then(function (result) {
if (
!result[0] || !result[1] ||
result[0].questions.indexOf(answer_data.question_num) == -1 ||
result[1].test != answer_data.test_num
) {
return res.send(Additional.serialize(3, 'Incorrect data'));
}
target_solution = result[0];
var current_answers = result[0].answers;
current_answers.push(answer_data.answer_num);
if (current_answers.length >= result[0].questions.length) {
last_question = true;
}
else {
return Models.solutions.update({
_id: answer_data.solution_num
}, {
answers: current_answers
});
}
}).then(function () {
if (last_question) {
return Additional.finishTest(target_solution);
}
else {
return res.send(Additional.serialize(0));
}
}).then(function (result) {
if (!result.socket) {
return res.send(Additional.serialize(0, result));
}
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
getQuestion(req, res, next) {
var question_data = {
user: req.user,
question_num: req.body.question,
test_num: req.body.test,
solution_num: req.body.solution
};
if (!Additional.checkArguments(question_data)) {
return res.send(Additional.serialize(2, 'Required fields are empty'));
}
Models.solutions.findOne({
_id: question_data.solution_num,
user: question_data.user._id
}).then(function (solution) {
if (!solution || solution.questions.indexOf(question_data.question_num) == -1) {
return res.send(Additional.serialize(3, 'Incorrect data'));
}
return Models.questions.findOne({
_id: question_data.question_num,
test: question_data.test_num
});
}).then(function (question) {
if (!question) {
return res.send(Additional.serialize(12, 'Not Found'));
}
question.true_answer = null;
return res.send(Additional.serialize(0, question));
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
getQuestionsCol(req, res, next) {
Models.tests.find().then(function (tests) {
var question_requests = tests.map(function (test) {
var test_all_complexity = [];
var activity = test.active ? '' : ' (inactive)';
test_all_complexity.push(test.title + activity);
for (var i = 1; i <= 3; i++) {
test_all_complexity.push(Models.questions.count({
test: test._id,
complexity: i
}));
}
return Promise.all(test_all_complexity);
});
return Promise.all(question_requests);
}).then(function (questions) {
questions = questions.map(function (test) {
var total = test.reduce(function (sum, current) {
if (typeof current == 'number') {
return sum + current;
}
else {
return sum;
}
}, 0);
test.push(total);
return test;
});
return res.send(Additional.serialize(0, questions));
}).catch(function (err) {
return res.send(Additional.serialize(1, 'Server error'));
});
}
getTestStatus(req, res, next) {
var test_num = req.query.test;
var user = req.user;
if (!test_num) {
return res.send(Additional.serialize(2, 'Required fields are empty'));
}
if (!user) {
return res.send(Additional.serialize(3, 'You must be a user'));
}
if (user.success_tests.indexOf(test_num) > -1) {
return res.send(Additional.serialize(5, 'You already have this certificate'));
}
Models.tests.findOne({
_id: test_num,
active: true
}).then(function (test) {
if (!test) {
return res.send(Additional.serialize(12, 'Test not found'));
}
return Additional.checkAvailable(user, test_num);
}).then(function (status) {
if (status.error) {
throw status.error;
}
if (!status.available) {
return res.send(Additional.serialize(6, status));
}
return res.send(Additional.serialize(0, status));
}).catch(function (err) {
return res.send(Additional.serialize(1, 'Server error'));
});
}
getCategoryTests(req, res, next) {
var user = req.user;
if (!user) {
return res.send(Additional.serialize(2, 'Required fields are empty'));
}
var all_tests = {
all: {},
received: [],
unreceived: [],
available: [],
unavailable: []
};
var available_requests = [];
Models.tests.find({
active: true
}).then(function (tests) {
tests.forEach(function (test) {
all_tests.all[test._id] = test.title;
if (user.success_tests.indexOf(test._id) > -1) {
all_tests.received.push(test);
}
else {
all_tests.unreceived.push(test);
available_requests.push(Additional.checkAvailable(user, test._id));
}
});
return Promise.all(available_requests);
}).then(function (availability) {
availability.forEach(function (result, index) {
if (result.available) {
all_tests.available.push(all_tests.unreceived[index]);
}
else {
all_tests.unavailable.push(all_tests.unreceived[index]);
}
});
return res.send(Additional.serialize(0, all_tests));
}).catch(function (err) {
return res.send(Additional.serialize(1, 'Server error'));
});
}
getCertificates(req, res, next) {
var user = req.user;
if (!user) {
return res.send(Additional.serialize(2, 'Required fields are empty'));
}
Models.certificates.find({
user: user._id
}).then(function (result) {
return res.send(Additional.serialize(0, result));
}).catch(function (err) {
return res.send(Additional.serialize(1, 'Server error'));
});
}
getCertificate(req, res, next) {
var certificate = req.query.cert;
if (!certificate) {
return res.send(Additional.serialize(2, 'Required fields are empty'));
}
Models.certificates.findOne({
_id: certificate
}).then(function (result) {
if (!result) {
return res.send(Additional.serialize(12, 'Not found'));
}
return res.send(Additional.serialize(0, result));
}).catch(function (err) {
return res.send(Additional.serialize(1, 'Server error'));
});
}
getReports(req, res, next) {
var type = req.query.type || 0;
Models.reports.find({
solved: false,
type: type
}).then(function (reports) {
return res.send(Additional.serialize(0, reports));
}).catch(function (err) {
return res.send(Additional.serialize(1, 'Server error'));
});
}
getSolutions(req, res, next) {
var user = req.user;
Models.solutions.find({
user: user._id
}).then(function (solutions) {
return res.send(Additional.serialize(0, solutions));
}).catch(function (err) {
return res.send(Additional.serialize(1, 'Server error'));
});
}
createOrder(req, res, next) {
var user = req.user;
var order_data = {
certificate: req.body.certificate,
test: req.body.test
};
var addr_data = {
line1: req.body.line1,
city: req.body.city,
state: req.body.state,
postal_code: req.body.postal,
country_code: req.body.country
}
var telephone_data = {
country: req.body.t_country,
national: req.body.t_national
}
if (
!Additional.checkArguments(order_data) ||
!Additional.checkArguments(telephone_data) ||
!Additional.checkArguments(addr_data) ||
!user
) {
return res.send(Additional.serialize(2, 'Required fields are empty'));
}
order_data.addr = addr_data;
order_data.telephone = telephone_data;
order_data.user = user._id;
order_data.mail = user.mail;
Orders.create(order_data, user).then(function () {
return res.send(Additional.serialize(0));
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
getOrders(req, res, next) {
var user = req.user;
if (!user) {
return res.send(Additional.serialize(3, 'You must be a user'));
}
Models.orders.find({
user: user._id
}).then(function (orders) {
return res.send(Additional.serialize(0, orders));
}).catch(function (err) {
return res.send(Additional.serialize(1, 'Server error'));
});
}
getAllOrders(req, res, next) {
Models.orders.find({
paid: true
}).then(function (orders) {
return res.send(Additional.serialize(0, orders));
}).catch(function (err) {
return res.send(Additional.serialize(1, 'Server error'));
});
}
paymentData(req, res, next) {
var id = req.body.item_number;
Models.orders.update({
_id: id
}, {
payment: req.body
}).then(function (orders) {
if (req.body.payment_status == 'Completed') {
return Models.orders.update({
_id: id
}, {
status: 1,
paid: true
});
}
return res.send(Additional.serialize(0, orders));
}).then(function () {
return res.send(Additional.serialize(0, orders));
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
changePass(req, res, next) {
var user = req.user;
var pass_data = {
old: req.body.old,
new1: req.body.new1,
new2: req.body.new2
}
if (!Additional.checkArguments(pass_data) || !user) {
return res.send(Additional.serialize(2, 'Required fields are empty'));
}
if (pass_data.new1 != pass_data.new2) {
return res.send(Additional.serialize(4, 'Passwords are not equal'));
}
pass_data.old_hash = md5(pass_data.old);
Models.users.findOne({
_id: user._id
}).then(function (user) {
if (!user) {
return res.send(Additional.serialize(3, 'You must be a user'));
}
if (user.pass != pass_data.old_hash) {
return res.send(Additional.serialize(5, 'Incorrect old password'));
}
return Models.changes.create({
user: user._id,
pass: md5(pass_data.new1),
confirmed: false
});
}).then(function (change) {
if (change.user) {
Mail.pass_change(change);
return res.send(Additional.serialize(0));
}
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
changePassConfirm(req, res, next) {
var change_id = req.body.id;
if (!change_id) {
return res.send(Additional.serialize(2, 'Required fields are empty'));
}
Models.changes.findOne({
_id: change_id,
confirmed: false
}).then(function (change) {
if (!change) {
return res.send(Additional.serialize(3, 'Change not found'));
}
return Models.users.update({
_id: change.user
}, {
pass: change.pass
});
}).then(function () {
return Models.changes.update({
_id: change_id
}, {
confirmed: true
});
}).then(function () {
return res.send(Additional.serialize(0));
}).catch(function (err) {
console.log(err);
return res.send(Additional.serialize(1, 'Server error'));
});
}
incOrder(req, res, next) {
var order_id = req.body.id;
Models.orders.update({
_id: order_id
}, {
$inc: {
status: 1
}
}).then(function () {
return res.send(Additional.serialize(0));
}).catch(function (err) {
return res.send(Additional.serialize(1, 'Server error'));
});
}
decOrder(req, res, next) {
var order_id = req.body.id;
Models.orders.update({
_id: order_id
}, {
$inc: {
status: -1
}
}).then(function () {
return res.send(Additional.serialize(0));
}).catch(function (err) {
return res.send(Additional.serialize(1, 'Server error'));
});
}
downloadBackup(req, res, next) {
Additional.downloadBackup(res);
}
}
module.exports = API;
|
// DOM Manipulation Challenge
// I worked on this challenge with: Austin Dorff.
// Add your JavaScript calls to this page:
// Release 0:
// Set up
// Release 1:
var div_r_1 = document.getElementById("release-0");
div_r_1.className = "done";
// Release 2:
var div_r_2 = document.getElementById('release-1');
div_r_2.style.display = "none";
// Release 3:
var div_r_3 = document.getElementsByTagName('h1')[0];
div_r_3.innerHTML = "I completed release 2.";
// Release 4:
var div_r_4 = document.getElementById('release-3');
div_r_4.style.backgroundColor = "#955251";
// Release 5:
var div_r_5 = document.getElementsByClassName("release-4");
for (var i = 0; i < div_r_5.length; i++) {
div_r_5[i].style.fontSize = "2em";
}
// Release 6:
var template = document.getElementById('hidden');
document.body.appendChild(template.content.cloneNode(true));
|
$(document).ready(function() {
$("#calculator-body").draggable();
var total = "";
var currentNumber = "";
var operator;
var operatorChosen = false;
var decimalAlready = false;
$("#ac").on("click", function() {
total = "";
currentNumber = "";
operatorChosen = false;
operator = "";
$("#output").text(0);
});
$("#ce").on("click", function() {
currentNumber = "";
operatorChosen = false;
$("#output").text(0);
});
function resetOperator() {
if (operatorChosen) {
currentNumber = "";
}
};
$("#percent").on("click", function() {
resetOperator();
operator = "%";
operatorChosen = true;
$("#output").text("%");
});
$("#add").on("click", function() {
resetOperator();
operator = "+";
operatorChosen = true;
$("#output").text("+");
});
$("#subtract").on("click", function() {
resetOperator();
operator = "-";
operatorChosen = true;
$("#output").text("-");
});
$("#divide").on("click", function() {
resetOperator();
operator = "/";
operatorChosen = true;
$("#output").text("/");
});
$("#multiply").on("click", function() {
resetOperator();
operator = "*";
operatorChosen = true;
$("#output").text("*");
});
$("#decimal").on("click", function() {
if (operatorChosen && !decimalAlready) {
currentNumber += ".";
$("#output").text(currentNumber);
} else if (!decimalAlready) {
total += ".";
$("#output").text(total);
}
decimalAlready = true;
});
$("#equals").on("click", function() {
var truncatedTotal;
total = eval(total + operator + currentNumber);
var totalDigits = total.toString().length;
if (totalDigits > 12) {
truncatedTotal = total.toString().slice(0, 12);
} else {
truncatedTotal = total;
}
decimalAlready = false;
$("#output").text(truncatedTotal);
});
for (var i = 0; i < 10; i++) {
$("#" + i).on("click", function() {
if (total === "" && !operator) {
total = this.id;
$("#output").text(total);
} else if (total !== "" && !operator) {
total += this.id;
$("#output").text(total);
} else if (operator) {
currentNumber += this.id;
$("#output").text(currentNumber);
}
});
}
});
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z" />
, 'LensSharp');
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
'use strict';
var assert = require('chai').assert;
var Client = require('./client.js');
var ConnectionString = require('azure-iot-common').ConnectionString;
var Message = require('azure-iot-common').Message;
var Amqp = require('./amqp.js');
var AmqpWS = require('./amqp_ws.js');
var host = ConnectionString.parse(process.env.IOTHUB_CONNECTION_STRING).HostName;
var deviceId = process.env.IOTHUB_DEVICE_ID;
var key = process.env.IOTHUB_DEVICE_KEY;
var connectionString = 'HostName=' + host + ';DeviceId=' + deviceId + ';SharedAccessKey=' + key;
var badConnStrings = [
'HostName=bad;DeviceId=' + deviceId + ';SharedAccessKey=' + key,
'HostName=' + host + ';DeviceId=bad;SharedAccessKey=' + key,
'HostName=' + host + ';DeviceId=' + deviceId + ';SharedAccessKey=bad;'
];
function badConfigTests(opName, badConnStrings, Transport, requestFn) {
function makeRequestWith(connectionString, test, done) {
var client = Client.fromConnectionString(connectionString, Transport);
requestFn(client, function (err, res) {
test(err, res);
done();
});
}
function expectNotFoundError(err) {
assert.include(err.message, 'getaddrinfo ENOTFOUND bad');
}
function expectTimeout(err) {
assert.isNotNull(err);
assert.include(err.message, "ETIMEDOUT");
}
var tests = [
{ name: 'hostname is malformed', expect: expectNotFoundError },
{ name: 'device is not registered', expect: expectTimeout },
{ name: 'password is wrong', expect: expectTimeout }
];
/*Tests_SRS_NODE_DEVICE_CLIENT_05_016: [When a Client method encounters an error in the transport, the callback function (indicated by the done argument) shall be invoked with the following arguments:
err - the standard JavaScript Error object, with a response property that points to a transport-specific response object, and a responseBody property that contains the body of the transport response.]*/
badConnStrings.forEach(function (test, index) {
it.skip('fails to ' + opName + ' when the ' + tests[index].name, function (done) {
this.timeout(30000);
makeRequestWith(test, tests[index].expect, done);
});
});
}
function runAmqpTests(Transport, goodConnectionString, badConnectionStrings) {
describe('Client', function () {
describe('#sendEvent', function () {
/*Tests_SRS_NODE_DEVICE_CLIENT_05_007: [The sendEvent method shall send the event indicated by the message argument via the transport associated with the Client instance.]*/
/*Tests_SRS_NODE_DEVICE_CLIENT_05_017: [With the exception of receive, when a Client method completes successfully, the callback function (indicated by the done argument) shall be invoked with the following arguments:
err - null
response - a transport-specific response object]*/
/*Tests_SRS_NODE_DEVICE_AMQP_16_002: [The sendEvent method shall construct an AMQP request using the message passed in argument as the body of the message.] */
/*Tests_SRS_NODE_DEVICE_AMQP_16_003: [The sendEvent method shall call the done() callback with no arguments when the message has been successfully sent.] */
/*Tests_SRS_NODE_DEVICE_AMQP_16_004: [If sendEvent encounters an error before it can send the request, it shall invoke the done callback function and pass the standard JavaScript Error object with a text description of the error (err.message). ] */
it('sends the event', function (done) {
this.timeout(15000);
var client = Client.fromConnectionString(goodConnectionString, Transport);
var message = new Message('hello');
client.sendEvent(message, function (err, res) {
assert.isNull(err);
assert.isNotNull(res);
done();
});
});
badConfigTests('send an event', badConnectionStrings, Transport, function (client, done) {
client.sendEvent(new Message(''), done);
});
});
/*Tests_SRS_NODE_DEVICE_AMQP_16_006: [If a receiver for this endpoint has already been created, the getReceiver method should call the done() method with the existing instance as an argument.]*/
/*Tests_SRS_NODE_DEVICE_AMQP_16_007: [If a receiver for this endpoint doesn’t exist, the getReceiver method should create a new AmqpReceiver object and then call the done() method with the object that was just created as an argument.]*/
describe('#getReceiver', function() {
it('returns the same receiver instance if called multiple times', function(done) {
this.timeout(15000);
var client = Client.fromConnectionString(goodConnectionString, Transport);
client.getReceiver(function(err1, receiver1) {
client.getReceiver(function(err2, receiver2) {
assert.isNotNull(receiver1);
assert.isNotNull(receiver2);
assert.equal(receiver1, receiver2);
done();
});
});
});
});
});
}
function makeConnectionString(host, device, key) {
return 'HostName='+host+';DeviceId='+device+';SharedAccessKey='+key;
}
var badConnStrings = [
makeConnectionString('bad', 'device', 'key'),
makeConnectionString('host', 'bad', 'key'),
makeConnectionString('host', 'device', 'bad')
];
describe('Over AMQPS', function () {
runAmqpTests(Amqp, connectionString, badConnStrings);
});
describe('Over AMQP/WS', function () {
runAmqpTests(AmqpWS, connectionString, badConnStrings);
});
module.exports = runAmqpTests;
|
/*
* Author: Eddy Huang
* Date: 2015-07-29
* File: api
*/
|
var toEncoding = require("./toEncoding")
module.exports = toValueEncoding
function toValueEncoding(data, options) {
return toEncoding(data && data.value
, options.valueEncoding || options.encoding)
}
|
import React from 'react';
import PropTypes from 'prop-types';
import { Provider } from 'react-redux';
import IntlProvider from './IntlProvider';
function Provide({ store, children }) {
return (
<Provider store={store}>
<IntlProvider>{children}</IntlProvider>
</Provider>
);
}
Provide.propTypes = {
store: PropTypes.shape({
subscribe: PropTypes.func.isRequired,
dispatch: PropTypes.func.isRequired,
getState: PropTypes.func.isRequired,
}).isRequired,
children: PropTypes.element.isRequired,
};
export default Provide;
|
/**
* CustomEmailSettings Schema
*/
Core.Schemas.CustomEmailSettings = new SimpleSchema({
username: {
type: String,
optional: true
},
password: {
type: String,
optional: true
},
host: {
type: String,
optional: true
},
port: {
type: Number,
allowedValues: [25, 587, 465, 475, 2525],
optional: true
}
});
/**
* Metafield Schema
*/
Core.Schemas.Metafield = new SimpleSchema({
_id: {
type: String,
autoValue: Core.schemaIdAutoValue,
optional: true
},
key: {
type: String,
max: 30,
optional: true
},
namespace: {
type: String,
max: 20,
optional: true
},
scope: {
type: String,
optional: true
},
value: {
type: String,
optional: true
},
valueType: {
type: String,
optional: true
},
description: {
type: String,
optional: true
}
});
/**
* Locale Schema
*/
Core.Schemas.Locale = new SimpleSchema({
continents: {
type: Object,
blackbox: true
},
countries: {
type: Object,
blackbox: true
}
});
/**
* Tenants Schema
*/
Core.Schemas.Tenant = new SimpleSchema({
"_id": {
type: String,
optional: true
},
"status": {
type: String,
defaultValue: "active",
optional: true
},
"name": {
type: String,
index: 1,
unique: true
},
"description": {
type: String,
optional: true
},
"keywords": {
type: String,
optional: true
},
"addressBook": {
type: Array,
optional: true
},
"addressBook.$": {
type: Object,
optional: true
},
"addressBook.$.address1": {
type: String,
optional: true
},
"industry": {
type: String,
optional: true
},
"domains": {
type: [String],
unique: true,
index: 1,
optional: true
//autoValue: function(){return [this.field('name')]}
},
"emails": {
type: [Core.Schemas.Email],
optional: true
},
"country": {
type: String
},
"baseCurrency": {
label: "Base Currency",
optional: true,
type: Object,
autoValue: function () {
if (this.isInsert && Meteor.isServer) {
let country = this.field('country');
if (!this.isSet && country.isSet) {
let locales = EJSON.parse(Assets.getText("settings/locales.json"));
let currency = {};
if (locales.countries[country.value]) {
currency.iso = locales.countries[country.value].currency;
let currencies = EJSON.parse(Assets.getText("settings/currencies.json"));
currency.symbol = currencies[currency.iso] ? currencies[currency.iso].symbol : '';
return currency;
}
}
}
}
},
"baseCurrency.iso": {
type: String,
optional: true
},
"baseCurrency.symbol": {
type: String,
optional: true
},
"currencies": {
type: [String],
optional: true
},
"locale": {
type: String,
defaultValue: "en",
optional: true
},
"public": {
type: String,
optional: true
},
"timezone": {
type: String,
optional: true
},
"baseUOM": {
type: String,
optional: true,
defaultValue: "OZ",
label: "Base Unit of Measure"
},
"metafields": {
type: [Core.Schemas.Metafield],
optional: true
},
"defaultRoles": {
type: [String],
defaultValue: ["business/manage", "employee/view"],
optional: true
},
"layout": {
type: [Object],
optional: true
},
"layout.$.layout": {
type: String,
defaultValue: "ApplicationLayout",
optional: true
},
"layout.$.theme": {
type: String,
defaultValue: "default",
optional: true
},
"layout.$.workflow": {
type: String,
optional: true
},
"layout.$.collection": {
type: String,
optional: true
},
"layout.$.enabled": {
type: Boolean,
defaultValue: true,
optional: true
},
"settings": {
type: Object,
optional: true
},
"settings.rounding": {
type: Object,
optional: true,
blackbox: true
},
"adminEmail": {
type: String,
regEx: SimpleSchema.RegEx.Email,
optional: true
},
"createdAt": {
type: Date,
autoValue: function () {
if (this.isInsert) {
return new Date;
} else if (this.isUpsert) {
return {
$setOnInsert: new Date
};
}
},
denyUpdate: true,
optional: true
},
"updatedAt": {
type: Date,
autoValue: function () {
if (this.isUpdate) {
return new Date;
}
},
optional: true
}
});
|
'use strict';
const url = require('url');
const _ = {
map: require('lodash/map'),
trimStart: require('lodash/trimStart'),
sortBy: require('lodash/sortBy'),
isString: require('lodash/isString'),
forEach: require('lodash/forEach'),
remove: require('lodash/remove'),
has: require('lodash/has'),
groupBy: require('lodash/groupBy'),
split: require('lodash/split'),
findIndex: require('lodash/findIndex'),
join: require('lodash/join')
};
exports.treefy = treefy;
exports.domain = domain;
exports.treefyByPathname = treefyByPathname;
exports.linkDirectories = linkDirectories;
function treefy(urls){
let domains = exports.domain(urls);
return _.map(domains, function(domain){
return exports.treefyByPathname(domain);
});
};
function domain(links){
links = _.map(links, parse);
let domains = _.groupBy(links, function(link){
return _.trimStart(link.hostname, 'www.');
});
domains = _.sortBy(domains, function(node){
return -node.length;
});
return domains;
};
function parse(link){
if(_.isString(link)){
return url.parse(link);
}
return url.parse(link.url);
};
function treefyByPathname(urls){
let host = urls[0].host;
let tree = {
branch: []
};
_.forEach(urls, function(urlObj){
let pathparts = _.split(urlObj.pathname, '/');
_.remove(pathparts, function(name) {
return name === '';
});
pathparts.unshift(host);
let node = tree;
_.forEach(pathparts, function(name){
node = expandTree(node, name);
});
});
return tree.branch[0];
};
function expandTree(node, name){
if(_.has(node, 'branch') === false){
node.branch = [];
}
let index = _.findIndex(node.branch, function(o) { return o.name === name; });
if(index === -1){
index = node.branch.push({
name: name,
count: 0
}) - 1;
}
let branchNode = node.branch[index];
branchNode.count += 1;
return branchNode;
};
function linkDirectories(urls){
let treeList = treefy(urls);
_.forEach(treeList, linkDirectory);
return treeList;
};
function linkDirectory(node){
if(node.branch && node.branch.length === 1){
let child = node.branch[0];
node.name = _.join([node.name, child.name], '/');
node.branch = child.branch;
linkDirectory(node);
}
};
|
var HomeController = require("./Base"),
View = require("../views/Base"),
Service = require("../domain/concrete/services/HomeService.js");
module.exports = HomeController.extend({
name: "Home",
// index action for home
index: function(req, res, next) {
var view = new View(res, 'home');
view.render({
title: 'Home'
});
},
users: function(req, res, next) {
var self = this;
var view = new View(res, 'home');
var service = new Service();
var result = null;
view.render({
title: 'Home Sweet Home + Users'
});
}
});
|
let point = require('./gis/protobuf/point_pb');
module.exports.Point2D = point.Point2D;
module.exports.Point3D = point.Point3D;
module.exports.MultiPoint2D = point.MultiPoint2D;
module.exports.MultiPoint3D = point.MultiPoint3D;
let linestring = require('./gis/protobuf/linestring_pb');
module.exports.LineString2D = linestring.LineString2D;
module.exports.LineString3D = linestring.LineString3D;
module.exports.MultiLineString2D = linestring.MultiLineString2D;
module.exports.MultiLineString3D = linestring.MultiLineString3D;
let polygon = require('./gis/protobuf/polygon_pb');
module.exports.Polygon2D = polygon.Polygon2D;
module.exports.Polygon3D = polygon.Polygon3D;
module.exports.MultiPolygon2D = polygon.MultiPolygon2D;
module.exports.MultiPolygon3D = polygon.MultiPolygon3D;
|
'use strict';
import React from "react";
var RefreshButton = React.createClass({
render: function() {
return (
<button type="button" className="refresh-button btn btn-info navbar-btn" title="Sync" onClick={this.props.onRefreshClick}>
<span className={"fa fa-refresh" + (this.props.isSyncing ? " fa-spin" : "")}></span>
</button>
);
}
});
export default RefreshButton;
|
var is = require('annois');
module.exports = function(op, y, x) {
return is.number(op(y, x));
};
|
'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var BookSchema = new Schema({
name: {type: String, required: true},
info: String,
author: {type: String, required: true},
user: {type: Schema.Types.ObjectId, ref: 'User', required: true},
bookcase: {type: Schema.Types.ObjectId, ref: 'Bookcase', required: true},
shelf: {type: Number, required: true},
line: {type: Number, required: true},
active: Boolean
});
module.exports = mongoose.model('Book', BookSchema);
|
'use strict';
const _ = require('lodash');
const Script = require('smooch-bot').Script;
const scriptRules = require('./script.json');
module.exports = new Script({
processing: {
//prompt: (bot) => bot.say('Beep boop...'),
receive: () => 'processing'
},
start: {
receive: (bot) => {
return bot.say('So you want to know more about MikeBot? Just say BOT to wake me up :) %[BOT](postback:bot)')
.then(() => 'speak');
}
},
speak: {
receive: (bot, message) => {
let upperText = message.text.trim().toUpperCase();
function updateSilent() {
switch (upperText) {
case "CONTACT TO MIKE":
return bot.setProp("silent", false);
case "MIKEBOT BACK":
return bot.setProp("silent", false);
default:
return Promise.resolve();
}
}
function getSilent() {
return bot.getProp("silent");
}
function processMessage(isSilent) {
if (isSilent) {
return Promise.resolve("speak");
}
if (!_.has(scriptRules, upperText)) {
return bot.say(`So, I'm good at structured conversations but some stickers, emoji and sentences still confuse me :'(\nSay GOT IT to chat about something else.%[Got it](postback:got_it)`).then(() => 'speak');
}
var response = scriptRules[upperText];
var lines = response.split('\n');
var p = Promise.resolve();
_.each(lines, function(line) {
line = line.trim();
p = p.then(function() {
console.log(line);
return bot.say(line);
});
})
return p.then(() => 'speak');
}
return updateSilent()
.then(getSilent)
.then(processMessage);
}
}
});
|
/*
* @title Bump
* @description A task to bump the bower and package version numbers
* @summary Allowed bump types: major, minor, patch
* @default patch
* @example (cli) env BUMP_TYPE=major gulp bump
*/
/*********************************************************************************
1. DEPENDENCIES
*********************************************************************************/
var bump = require('gulp-bump');
var gulp = require('gulp');
/*********************************************************************************
2. TASK
*********************************************************************************/
gulp.task('bump', function () {
return gulp
.src(['./bower.json', './package.json'])
.pipe(bump({
type: process.env.BUMP_TYPE
}))
.pipe(gulp.dest('./'));
});
|
import jwt from 'jsonwebtoken';
import ErrorConstants from '../constants/ErrorConstants';
import { User } from '../models';
import Constants from '../constants/Constants';
const {
userDeleteUnauthorizedError,
voidUserDeleteError,
} = ErrorConstants;
/**
* @description allows users to delete only his account.
* Allows admin to delete all accounts
*
* @param {Request} request Http request object from express
* @param {Response} response HTTP response object from express
* @param {function} next next function provided by the express.
* it passes control to the next middleware
*
* @returns {Promise | void} Promise from express HTTP response
*/
const deleteUserAuthorization = (request, response, next) => {
let token = request.headers.authorization;
token = token.split(' ')[1];
const user = jwt.decode(token).data;
let statusCode = 400;
const idToBeDeleted = request.params.id;
User.findById(idToBeDeleted)
.then((queryResult) => {
const error = new Error();
if (!queryResult) {
statusCode = 404;
error.message = voidUserDeleteError;
throw error;
}
const expectedUserId = queryResult.dataValues.id;
if (expectedUserId !== user.id && user.roleId !== Constants.adminRole) {
error.message = userDeleteUnauthorizedError;
statusCode = 403;
throw error;
}
next();
})
.catch(error => response
.status(statusCode)
.json({ error: error.message })
);
};
export default deleteUserAuthorization;
|
'use strict';
//region Imports
const configuration = require( './../system/configuration-reader.js' );
const Argument = require( '../system/argument-check.js' );
const ModelError = require( './model-error.js' );
const PropertyInfo = require( './property-info.js' );
//endregion
//region Private variables
const _getValue = new WeakMap();
const _setValue = new WeakMap();
const _isDirty = new WeakMap();
const _connection = new WeakMap();
const _fulfill = new WeakMap();
const _reject = new WeakMap();
//endregion
//region Helper methods
function getByName( properties, name ) {
for (let i = 0; i < properties.length; i++) {
if (properties[ i ].name === name)
return properties[ i ];
}
throw new ModelError( 'noProperty', properties.name, name );
}
//endregion
/**
* Provides the context for custom data portal actions.
*
* @memberof bo.common
*/
class DataPortalContext {
//region Constructor
/**
* Creates a new data context object.
* </br></br>
* <i><b>Warning:</b> Data portal context objects are created in models internally.
* They are intended only to make publicly available the context
* for custom data portal actions.</i>
*
* @param {object} dao - The data access object of the current model.
* @param {Array.<bo.common.PropertyInfo>} properties - An array of property definitions.
* @param {internal~getValue} [getValue] - A function that returns the current value of a property.
* @param {internal~setValue} [setValue] - A function that changes the current value of a property.
*
* @throws {@link bo.system.ArgumentError Argument error}: The dao argument must be an object.
* @throws {@link bo.system.ArgumentError Argument error}: The properties must be an array
* of PropertyInfo objects, or a single PropertyInfo object or null.
* @throws {@link bo.system.ArgumentError Argument error}: The getValue argument must be a function.
* @throws {@link bo.system.ArgumentError Argument error}: The setValue argument must be a function.
*/
constructor( dao, properties, getValue, setValue ) {
const check = Argument.inConstructor( DataPortalContext.name );
/**
* The data access object of the current model.
* @member {object} bo.common.DataPortalContext#dao
* @readonly
*/
this.dao = check( dao || {} ).forMandatory( 'dao' ).asObject();
/**
* Array of property definitions that may appear on the data transfer object.
* @member {Array.<bo.common.PropertyInfo>} bo.common.DataPortalContext#properties
* @readonly
*/
this.properties = check( properties ).forOptional( 'properties' ).asArray( PropertyInfo );
_getValue.set( this, check( getValue ).forOptional( 'getValue' ).asFunction() );
_setValue.set( this, check( setValue ).forOptional( 'setValue' ).asFunction() );
_isDirty.set( this, false );
_connection.set( this, null );
_fulfill.set( this, null );
_reject.set( this, null );
// Immutable object.
Object.freeze( this );
}
//endregion
//region Properties
/**
* The current user.
* @member {bo.system.UserInfo} bo.common.DataPortalContext#user
* @readonly
*/
get user() {
return configuration.getUser();
}
/**
* The current locale.
* @member {string} bo.common.DataPortalContext#locale
* @readonly
*/
get locale() {
return configuration.getLocale();
}
/**
* The connection object for the data source.
* @member {object} bo.common.DataPortalContext#connection
* @readonly
*/
get connection() {
return _connection.get( this );
}
/**
* Indicates whether the current model itself has been changed.
* @member {boolean} bo.common.DataPortalContext#isSelfDirty
* @readonly
*/
get isSelfDirty() {
return _isDirty.get( this );
}
/**
* The fulfilling function of the promise when extension manager
* calls a custom data portal method.
* @member {function} bo.common.DataPortalContext#fulfill
* @readonly
*/
get fulfill() {
return _fulfill.get( this );
}
/**
* The rejecting function of the promise when extension manager
* calls a custom data portal method.
* @member {function} bo.common.DataPortalContext#reject
* @readonly
*/
get reject() {
return _reject.get( this );
}
//endregion
//region Methods
/**
* Sets the current state of the model.
*
* @param {object} [connection] - The current connection for the data store.
* @param {boolean} [isSelfDirty] - Indicates whether the current model itself has been changed.
* @returns {bo.common.DataPortalContext} The data context object itself.
*/
setState( connection, isSelfDirty ) {
_connection.set( this, connection || null );
_isDirty.set( this, isSelfDirty === true );
return this;
}
/**
* Sets the state setting functions of the promise when
* extension manager calls a custom data portal method.
*
* @param {function} fulfill - The fulfill argument of the promise factory.
* @param {function} reject - The reject argument of the promise factory.
*/
setPromise( fulfill, reject ) {
_fulfill.set( this, typeof fulfill === 'function' ? fulfill : null );
_reject.set( this, typeof reject === 'function' ? reject : null );
}
/**
* Gets the current value of a model property.
*
* @param {string} propertyName - The name of the property.
* @returns {*} The value of the model property.
*
* @throws {@link bo.system.ArgumentError Argument error}: The name must be a non-empty string.
* @throws {@link bo.system.ArgumentError Argument error}: The model has no property with the given name.
* @throws {@link bo.common.ModelError Model error}: Cannot read the properties of a collection.
*/
getValue( propertyName ) {
propertyName = Argument.inMethod( DataPortalContext.name, 'getValue' )
.check( propertyName ).forMandatory( 'propertyName' ).asString();
const getValue = _getValue.get( this );
if (getValue)
return getValue( getByName( this.properties, propertyName ) );
else
throw new ModelError( 'readCollection', this.properties.name, propertyName );
}
/**
* Sets the current value of a model property.
*
* @param {string} propertyName - The name of the property.
* @param {*} value - The new value of the property.
*
* @throws {@link bo.system.ArgumentError Argument error}: The name must be a non-empty string.
* @throws {@link bo.system.ArgumentError Argument error}: The model has no property with the given name.
* @throws {@link bo.common.ModelError Model error}: Cannot write the properties of a collection.
*/
setValue( propertyName, value ) {
propertyName = Argument.inMethod( DataPortalContext.name, 'setValue' )
.check( propertyName ).forMandatory( 'propertyName' ).asString();
const setValue = _setValue.get( this );
if (setValue) {
if (value !== undefined) {
setValue( getByName( this.properties, propertyName ), value );
}
} else
throw new ModelError( 'writeCollection', this.properties.name, propertyName );
}
//endregion
//region Call DAO methods
/**
* Calls a method on the data access object with current context.
* The method is a shorthand for `dpContext.dao.$runMethod( methodName, dpContext.connection, methodArg )`.
*
* @param {string} methodName - The name of the method to call.
* @param {*} methodArg - Additional argument of the method to call.
* @returns {Promise.<*>} Returns a promise to the result of the method.
*/
call( methodName, methodArg ) {
return this.dao.$runMethod( methodName, this.connection, methodArg );
}
/**
* Calls the create method on the data access object with current context.
* The method is a shorthand for `dpContext.dao.$runMethod( 'create', dpContext.connection )`.
*
* @returns {Promise.<*>} Returns a promise to the result of the create method.
*/
create() {
return this.dao.$runMethod( 'create', this.connection );
}
/**
* Calls the fetch method on the data access object with current context.
* The method is a shorthand for `dpContext.dao.$runMethod( 'fetch', dpContext.connection, filter )`.
*
* @param {*} filter - The search conditions of the retrieval.
* @returns {Promise.<*>} Returns a promise to the result of the fetch method.
*/
fetch( filter ) {
return this.dao.$runMethod( 'fetch', this.connection, filter );
}
/**
* Calls the insert method on the data access object with current context.
* The method is a shorthand for `dpContext.dao.$runMethod( 'insert', dpContext.connection, data )`.
*
* @param {*} data - The data transfer object.
* @returns {Promise.<*>} Returns a promise to the result of the insert method.
*/
insert( data ) {
return this.dao.$runMethod( 'insert', this.connection, data );
}
/**
* Calls the update method on the data access object with current context.
* The method is a shorthand for `dpContext.dao.$runMethod( 'update', dpContext.connection, data )`.
*
* @param {*} data - The data transfer object.
* @returns {Promise.<*>} Returns a promise to the result of the update method.
*/
update( data ) {
return this.dao.$runMethod( 'update', this.connection, data );
}
/**
* Calls the remove method on the data access object with current context.
* The method is a shorthand for `dpContext.dao.$runMethod( 'remove', dpContext.connection, filter )`.
*
* @param {*} filter - The search conditions of the removal.
* @returns {Promise.<null>} Returns a promise to the result of the remove method, i.e. to a null.
*/
remove( filter ) {
return this.dao.$runMethod( 'remove', this.connection, filter );
}
/**
* Calls the execute method on the data access object with current context.
* The method is a shorthand for `dpContext.dao.$runMethod( 'execute', dpContext.connection, data )`.
*
* @param {*} data - The data transfer object.
* @returns {Promise.<*>} Returns a promise to the result of the execute method.
*/
execute( data ) {
return this.dao.$runMethod( 'execute', this.connection, data );
}
//endregion
}
module.exports = DataPortalContext;
|
/*
* Copyright (c) 2017. MIT-license for Jari Van Melckebeke
* Note that there was a lot of educational work in this project,
* this project was (or is) used for an assignment from Realdolmen in Belgium.
* Please just don't abuse my work
*/
define(function (require) {
'use strict';
var zrUtil = require('zrender/core/util');
var graphic = require('../../util/graphic');
var AxisBuilder = require('./AxisBuilder');
var axisBuilderAttrs = [
'axisLine', 'axisLabel', 'axisTick', 'axisName'
];
var selfBuilderAttrs = [
'splitLine', 'splitArea'
];
require('../../echarts').extendComponentView({
type: 'radiusAxis',
render: function (radiusAxisModel, ecModel) {
this.group.removeAll();
if (!radiusAxisModel.get('show')) {
return;
}
var polarModel = ecModel.getComponent('polar', radiusAxisModel.get('polarIndex'));
var angleAxis = polarModel.coordinateSystem.getAngleAxis();
var radiusAxis = radiusAxisModel.axis;
var polar = polarModel.coordinateSystem;
var ticksCoords = radiusAxis.getTicksCoords();
var axisAngle = angleAxis.getExtent()[0];
var radiusExtent = radiusAxis.getExtent();
var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
zrUtil.each(axisBuilderAttrs, axisBuilder.add, axisBuilder);
this.group.add(axisBuilder.getGroup());
zrUtil.each(selfBuilderAttrs, function (name) {
if (radiusAxisModel.get(name +'.show')) {
this['_' + name](radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords);
}
}, this);
},
/**
* @private
*/
_splitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
var splitLineModel = radiusAxisModel.getModel('splitLine');
var lineStyleModel = splitLineModel.getModel('lineStyle');
var lineColors = lineStyleModel.get('color');
var lineCount = 0;
lineColors = lineColors instanceof Array ? lineColors : [lineColors];
var splitLines = [];
for (var i = 0; i < ticksCoords.length; i++) {
var colorIndex = (lineCount++) % lineColors.length;
splitLines[colorIndex] = splitLines[colorIndex] || [];
splitLines[colorIndex].push(new graphic.Circle({
shape: {
cx: polar.cx,
cy: polar.cy,
r: ticksCoords[i]
},
silent: true
}));
}
// Simple optimization
// Batching the lines if color are the same
for (var i = 0; i < splitLines.length; i++) {
this.group.add(graphic.mergePath(splitLines[i], {
style: zrUtil.defaults({
stroke: lineColors[i % lineColors.length],
fill: null
}, lineStyleModel.getLineStyle()),
silent: true
}));
}
},
/**
* @private
*/
_splitArea: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
var splitAreaModel = radiusAxisModel.getModel('splitArea');
var areaStyleModel = splitAreaModel.getModel('areaStyle');
var areaColors = areaStyleModel.get('color');
var lineCount = 0;
areaColors = areaColors instanceof Array ? areaColors : [areaColors];
var splitAreas = [];
var prevRadius = ticksCoords[0];
for (var i = 1; i < ticksCoords.length; i++) {
var colorIndex = (lineCount++) % areaColors.length;
splitAreas[colorIndex] = splitAreas[colorIndex] || [];
splitAreas[colorIndex].push(new graphic.Sector({
shape: {
cx: polar.cx,
cy: polar.cy,
r0: prevRadius,
r: ticksCoords[i],
startAngle: 0,
endAngle: Math.PI * 2
},
silent: true
}));
prevRadius = ticksCoords[i];
}
// Simple optimization
// Batching the lines if color are the same
for (var i = 0; i < splitAreas.length; i++) {
this.group.add(graphic.mergePath(splitAreas[i], {
style: zrUtil.defaults({
fill: areaColors[i % areaColors.length]
}, areaStyleModel.getAreaStyle()),
silent: true
}));
}
}
});
/**
* @inner
*/
function layoutAxis(polar, radiusAxisModel, axisAngle) {
return {
position: [polar.cx, polar.cy],
rotation: axisAngle / 180 * Math.PI,
labelDirection: -1,
tickDirection: -1,
nameDirection: 1,
labelRotation: radiusAxisModel.getModel('axisLabel').get('rotate'),
// Over splitLine and splitArea
z2: 1
};
}
});
|
define(["jquery","Velocity","easing"], function ($,velocity) {
$.fn.collapsible = function(options) {
var defaults = { accordion: undefined };
options = $.extend(defaults, options);
return this.each(function() {
var $this = $(this), $panel_headers = $(this).find('> li > .collapsible-header'), collapsible_type = $this.data("collapsible");
$this.off('click.collapse', '.collapsible-header');
$panel_headers.off('click.collapse');
function accordionOpen(object) {
$panel_headers = $this.find('> li > .collapsible-header');
if (object.hasClass('active')) object.parent().addClass('active'); else object.parent().removeClass('active');
if (object.parent().hasClass('active')) object.siblings('.collapsible-body').stop(true,false).slideDown({ duration: 350, easing: "easeOutQuart", queue: false, complete: function() {$(this).css('height', '');}});
else object.siblings('.collapsible-body').stop(true,false).slideUp({ duration: 350, easing: "easeOutQuart", queue: false, complete: function() {$(this).css('height', '');}});
$panel_headers.not(object).removeClass('active').parent().removeClass('active');
$panel_headers.not(object).parent().children('.collapsible-body').stop(true,false).slideUp({ duration: 350,easing: "easeOutQuart",queue: false, complete: function() {
$(this).css('height', '');
}});
}
function expandableOpen(object) {
if (object.hasClass('active')) object.parent().addClass('active'); else object.parent().removeClass('active');
if (object.parent().hasClass('active')) object.siblings('.collapsible-body').stop(true,false).slideDown({ duration: 350, easing: "easeOutQuart", queue: false, complete: function() {$(this).css('height', '');}});
else object.siblings('.collapsible-body').stop(true,false).slideUp({ duration: 350, easing: "easeOutQuart", queue: false, complete: function() {$(this).css('height', '');}});
}
function isChildrenOfPanelHeader(object) {
var panelHeader = getPanelHeader(object);
return panelHeader.length > 0;
}
function getPanelHeader(object) {
return object.closest('li > .collapsible-header');
}
if (options.accordion || collapsible_type === "accordion" || collapsible_type === undefined) { // Handle Accordion
$panel_headers = $this.find('> li > .collapsible-header');
$panel_headers.on('click.collapse', function (e) {
var element = $(e.target);
if (isChildrenOfPanelHeader(element)) element = getPanelHeader(element);
element.toggleClass('active');
accordionOpen(element);
});
accordionOpen($panel_headers.filter('.active').first());
} else { // Handle Expandables
$panel_headers.each(function () {
$(this).on('click.collapse', function (e) {
var element = $(e.target);
if (isChildrenOfPanelHeader(element)) element = getPanelHeader(element);
element.toggleClass('active');
expandableOpen(element);
});
if ($(this).hasClass('active')) expandableOpen($(this));
});
}
});
};
});
|
fetch('https://foo.com/form-data')
.then((response) => response.formData())
.then((formData) => console.log(formData.get('foo'));
// bar
BodyFormDataExample02.js
|
import Joi from 'joi';
import pluck from 'lodash/map';
import dates from '../lib/dates';
import validate from '../lib/validate';
import payoutMethods from '../ui/payout_methods';
import i18n from '../lib/i18n';
/**
* New expense schema
*/
const schema = Joi.object().keys({
attachment: Joi.string().uri()
.label('Photo')
.allow(null),
name: Joi.string().required()
.label('Name'),
email: Joi.string().email().required()
.label('Email'),
description: Joi.string().required()
.label('Description'),
amount: Joi.number().integer().min(1).required()
.label('Amount'),
// TODO add currency
vat: Joi.number().precision(2).min(0).allow(null)
.label('VAT'),
incurredAt: Joi.date().max(dates().tomorrow).required()
.raw() // doesn't convert date into Date object
.label('IncurredAt'),
category: Joi.string().required()
.label('Category'),
payoutMethod: Joi.string().valid(pluck(payoutMethods(i18n('en')), 'value')) // i18n.getString not used here
.label('Reimbursement method'),
paypalEmail: Joi.string().email()
.label('PayPal email')
.allow(null),
notes: Joi.string()
.label('Notes')
.allow(null)
});
export default (obj) => validate(obj, schema);
|
$(function(){
// set-up the favs_people table if it doesn't exist
$(document).ready(function(){
db.transaction(
function(transaction) {
transaction.executeSql(
'CREATE TABLE IF NOT EXISTS favs_people '+
' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, givenname TEXT NOT NULL, surname TEXT NOT NULL);'
);
}
);
});
// after loading the main people view load the number of favs out of the local database
$('#people').live('pageAnimationEnd', function(event, info){
if (info.direction == 'out') {
$(this).removeClass('active');
} else {
// get number of favorites
db.transaction(
function(transaction) {
transaction.executeSql(
'SELECT * FROM favs_people ORDER BY surname;',
[],
function(transaction,results) {
$(".pfavscount").html('<small id="pfavscount" class="counter">'+results.rows.length+'</small>');
},
sqlError
);
}
);
$('#people-favorites').remove();
}
});
// when animating into the people detail see if this item is a favorite or not
$('#people-detail').live('pageAnimationStart', function(event, info){
if (info.direction == 'in') {
checkPeopleFav();
}
});
// draw the list of people favorites, use a hidden li item w/ id of #fav-ppl-clone to clone items
$('#people-favorites').live('pageAnimationStart', function(event, info){
if (info.direction == 'in') {
db.transaction(
function(transaction) {
transaction.executeSql(
'SELECT * FROM favs_people ORDER BY surname;',
[],
function(transaction,results) {
var string_sep = 'A';
var string_sep_check = false;
(results.rows.length > 0) ? $('#fav-ppl-info').hide() : $('#fav-ppl-info').show();
for (var i=0; i < results.rows.length; i++) {
var row = results.rows.item(i);
if ((string_sep_check == false) && (row.surname.substr(0,1) == 'A')) {
// duplicate an entry for a separator
var newSepRow = $('#fav-ppl-clone').clone();
newSepRow.removeAttr('id');
newSepRow.removeAttr('style');
newSepRow.addClass('sep');
newSepRow.addClass('fav-ppl-sep');
newSepRow.appendTo('#fav-ppl-list');
newSepRow.html(row.surname.substr(0,1));
string_sep_check = true;
} else if (string_sep != row.surname.substr(0,1)) {
// duplicate an entry for a separator
var newSepRow = $('#fav-ppl-clone').clone();
newSepRow.removeAttr('id');
newSepRow.removeAttr('style');
newSepRow.addClass('sep');
newSepRow.addClass('fav-ppl-sep');
newSepRow.appendTo('#fav-ppl-list');
newSepRow.html(row.surname.substr(0,1));
string_sep = row.surname.substr(0,1);
}
// duplicate an entry for a person
var newFavRow = $('#fav-ppl-clone').clone();
newFavRow.removeAttr('id');
newFavRow.removeAttr('style');
newFavRow.data('entryId',row.id);
newFavRow.addClass('fav-ppl-entry');
newFavRow.appendTo('#fav-ppl-list');
newFavRow.html("<a href=\"/people/?username="+row.username+"\"><span class='thin'>"+row.givenname+"</span> "+row.surname+"</a>");
}
},
sqlError
);
}
);
}
});
// when unloading the people details delete the div holding the old detail so divs with that ID load properly in future
// also delete the sessionStorage data so the options can be re-populated cleanly in the future
$('.people-list').live('pageAnimationEnd', function(event, info){
if (info.direction == 'in') {
$('#people-detail').remove();
peopleFavSelected = false;
delete sessionStorage.givenName;
delete sessionStorage.surname;
delete sessionStorage.username;
} else {
$('.fav-ppl-entry').remove();
$('.fav-ppl-sep').remove();
}
});
// toggle fav graphic on and off when tapped as well as add and remove data from db
$('#people-favorite-detail').live('tap',function(){ peopleFav(); });
});
var peopleFavSelected = false;
// mark or unmark the item as a favorite
function peopleFav() {
if (peopleFavSelected == true) {
db.transaction(
function(transaction) {
transaction.executeSql(
'DELETE FROM favs_people WHERE username = ?;',
[sessionStorage.username],
function() {
peopleFavSelected = false;
$('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_unselected.png');
},
sqlError
);
}
);
} else if (peopleFavSelected == false) {
db.transaction(
function(transaction) {
transaction.executeSql(
'INSERT INTO favs_people (username, givenname, surname) VALUES (?,?,?);',
[sessionStorage.username, sessionStorage.givenName, sessionStorage.surname],
function() {
peopleFavSelected = true;
$('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_selected.png');
},
sqlError
);
}
);
}
}
// the actual function that checks if there is a favorite for the directory entry
function checkPeopleFav() {
db.transaction(
function(transaction) {
transaction.executeSql(
'SELECT id FROM favs_people WHERE username = ?;',
[sessionStorage.username],
function(transaction,results) {
if (results.rows.length > 0) {
$('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_selected.png');
peopleFavSelected = true;
} else {
$('#people-favorite-detail-img').attr('src','/themes/'+theme+'/webkit/images/favorite_unselected.png');
peopleFavSelected = false;
}
},
sqlError
);
}
);
}
|
var machina = require('machina');
var request = require('request');
var lagarto = require('./devices');
var data = require('./data');
// Global Variables to the experiment
var currentBlock = [];
var currentNumOfTrials = 0;
var currentTrialNum = 0;
var timeOutLeadsToFail = false;
var timeoutValue = 0;
var delayValue = 0;
var currentBirdID = "";
var currentStage = null;
var currentPerchDelay = 5;
var initialTrialID = 1;
// Call backs for the data functions below
function setLagartoToDevice(result) {
console.log("lagartoToDevice", result);
lagartoToDevice = result;
}
function setExpNodeToDeviceName(result) {
console.log("expNodeToDeviceName", result);
expNodeToDeviceName = result;
}
function setDeviceNameToExpNode(result) {
console.log("deviceNameToExpNode", result);
deviceNameToExpNode = result;
}
function setExpToDevice(result) {
console.log("expToDevice", result);
expToDevice = result;
}
// Mappings between Experiment Nodes, Device ID's, and Lagarto ID's
onlineDeviceList = {};
data.getDeviceToLagartoMapping(setLagartoToDevice);
data.getExpNodeToDeviceName(setExpNodeToDeviceName);
data.getDeviceNameToExpNode(setDeviceNameToExpNode);
data.getDeviceMapping(setExpToDevice);
// Map these onto the data functions
// get the online list
// tie this to the UI event, so it has given enough time to get a handle on what is currently online
// add the mapping to that online list (get the device mapping)
// reset all values
var resetAllValues = function() {
currentBirdID = 0;
currentStage = null;
currentNumOfTrials = 0;
currentBlock = [];
currentTrialNum = 0;
timeoutValue = 0;
timeOutLeadsToFail = false;
delayValue = 0;
currentPerchDelay = 5;
}
function generateNextTrialIDInAdvance(newID){
console.log("generate ID", newID);
initialTrialID = newID;
}
var trialGenerator = function() {
// Filled from the stage object
stageID = currentStage.name;
timeoutValue = currentStage.autoEndTime * 1000;
delayValue = currentStage.delay * 1000;
timeOutLeadsToFail = currentStage.autoEnd;
birdID = currentBirdID;
numOfTrials = currentNumOfTrials;
availableFeeders = [];
// take only the selected feeders to add to the bucket
function fillBucket() {
// Old method - kept for bug checking
//for (var i=1;i<=numOfAvailableFeeders;i++) {
// availableFeeders.push(i);
//}
for (var i=0; i <= currentStage.feederArrangement.length; i++) {
if (currentStage.feederArrangement[i] == true) {
availableFeeders.push(i+1);
}
}
numOfAvailableFeeders = availableFeeders.length;
}
// Will be replaced with recopying the initital stage.feeders
fillBucket();
//Sample without replacement
function getRandomFromBucket() {
var randomIndex = Math.floor(Math.random()*availableFeeders.length);
return availableFeeders.splice(randomIndex, 1)[0];
}
// Generate Trials
var block = [];
for (id=initialTrialID; id < initialTrialID + numOfTrials; id++) {
block.push({'trialID': id, 'bird': birdID, 'stage': stageID,
'intended': getRandomFromBucket(), 'actual': '', 'success': null,
'startTime': '', 'endTime': '', 'totalTime': '', 'videoFilePath': '', 'notes': ''});
//console.log((id - initialTrialID + 1) % (numOfAvailableFeeders) == 0);
if ((id - initialTrialID + 1) % (numOfAvailableFeeders) == 0) {
//console.log(availableFeeders.length);
fillBucket();
//console.log(availableFeeders.length);
}
}
// requires additional check to see if there is enough meat to support this session!
return block;
}
var experiment = new machina.Fsm( {
// the initialize method is called right after the FSM
// instance is constructed, giving you a place for any
// setup behavior, etc. It receives the same arguments
// (options) as the constructor function.
initialize: function( options ) {
// your setup code goes here...
},
namespace: "controller",
// The initial State the FSM will be started in
initialState: "uninitialized",
// Experimental States
states: {
uninitialized: {
_onEnter: function() {
},
"*": function() {
},
_onExit: function() {
},
initialize: function() {
this.transition( "freeForm" );
}
},
freeForm: {
_onEnter: function() {
console.log("entered freeform mode")
},
"*": function() {
},
_onExit: function() {
},
dropMeat: function(feederID) {
console.log(feederID);
// Transform experimental Feeder ID into the actual device Name
deviceNameID = expNodeToDeviceName[feederID];
// DEVICEMAPPING
lagarto.dropMeat(deviceNameID);
},
lightOn: function(lightID) {
//Hardwired for Node 1, TO-DO make general case
console.log("turn light on: ", lightID);
// DEVICEMAPPING
lagarto.turnLightOn(lightID);
},
lightOff: function(lightID) {
console.log("turn lights off");
// DEVICEMAPPING
lagarto.turnLightOff(lightID);
},
startExperiment: function(birdID, stage) {
currentBirdID = birdID;
currentStage = stage;
console.log("before create next trial ID");
data.getNextTrialID(birdID, stage.name, generateNextTrialIDInAdvance);
this.transition( "experiment" );
},
reInitialize: function(){
// Reset the feeder mappings
this.transition( "uninitialized" );
},
perchEvent: function(perchID) {
console.log("perch event occured inside freeForm", perchID);
}
},
experiment: {
_onEnter: function() {
},
"*": function() {
console.log("caught event inside experiment");
},
_onExit: function() {
},
startSession: function(numOfTrials, perchDelay) {
currentNumOfTrials = numOfTrials;
currentPerchDelay = perchDelay * 1000;
currentBlock = trialGenerator();
this.transition( "session" );
},
cancelExperiment: function() {
// reset all values
resetAllValues();
this.transition("freeForm");
},
},
session: {
_onEnter: function() {
console.log("In session");
// Are there still trials remaining to be run?
if (currentTrialNum < currentBlock.length) {
// Delay before running next trial
console.log("Delaying Trial Start by:", delayValue);
currentBlock[currentTrialNum].totalTime = "[Delaying by " + (delayValue/1000) + "sec ...]";
this.timer = setTimeout( function() {
this.handle( "delayEnded" );
}.bind( this ), delayValue );
} else {
this.transition("endedSession");
}
},
delayEnded: function() {
console.log("delayed ended, trial starting");
currentBlock[currentTrialNum].totalTime = "[running...]";
this.transition( "trial" );
},
"*": function() {
},
_onExit: function() {
},
endSession: function() {
this.transition("endedSession");
},
},
trial: {
_onEnter: function(randomNumber) {
console.log("In trial ", currentTrialNum);
currentBlock[currentTrialNum].startTime = new Date().getTime();
// DEVICEMAPPING
lagarto.turnLightOn(currentBlock[currentTrialNum].intended-1);
this.timer = setTimeout( function() {
this.handle( "timeout" );
}.bind( this ), timeoutValue );
},
timeout: function() {
currentBlock[currentTrialNum].endTime = new Date().getTime();
currentBlock[currentTrialNum].totalTime = currentBlock[currentTrialNum].endTime - currentBlock[currentTrialNum].startTime
currentBlock[currentTrialNum].actual = 'timeout';
currentBlock[currentTrialNum].success = false;
// DEVICEMAPPING
lagarto.turnLightOff(currentBlock[currentTrialNum].intended-1);
console.log(currentBlock[currentTrialNum]);
if (timeOutLeadsToFail) {
this.transition( "failedSession" );
} else {
// Carry on with the block
// If finished, go to ended session, not session
if (currentTrialNum+1 >= currentBlock.length) {
this.transition('endedSession');
}
//else
// Log the trial outcome
data.logTrial(currentBlock[currentTrialNum]);
currentTrialNum = currentTrialNum + 1;
this.transition('session');
}
},
"*": function() {
},
_onExit: function() {
},
perchEvent: function(perchID) {
clearTimeout( this.timer );
console.log("Perch event inside trial", perchID);
currentBlock[currentTrialNum].endTime = new Date().getTime();
currentBlock[currentTrialNum].totalTime = currentBlock[currentTrialNum].endTime - currentBlock[currentTrialNum].startTime
// Mapping from device ID to experimental ID required
currentBlock[currentTrialNum].actual = perchID;
// DEVICEMAPPING
// Moved to after a delay
//lagarto.turnLightOff(currentBlock[currentTrialNum].intended-1);
if (currentBlock[currentTrialNum].intended == currentBlock[currentTrialNum].actual) {
currentBlock[currentTrialNum].success = true;
console.log(currentBlock[currentTrialNum]);
// Time to reward the bird for sending the dropMeat Command to the revlant feeder
// feederID is the same as the perchID, as they are the same device
// Transform experimental Feeder ID into the actual device Name
deviceNameID = expNodeToDeviceName[currentBlock[currentTrialNum].intended];
// Drop the Meat
// DEVICEMAPPING
lagarto.dropMeat(deviceNameID);
// If finished, go to ended session, not session
if (currentTrialNum+1 >= currentBlock.length) {
// Place the delay in lowering the flag
this.timer = setTimeout( function() {
this.handle( "endedSessionFlagTimeout" );
}.bind( this ), currentPerchDelay );
//this.transition('endedSession');
} else {
// Log the trial outcome
data.logTrial(currentBlock[currentTrialNum]);
currentTrialNum = currentTrialNum + 1;
// place the delay in lowering the flag
this.timer = setTimeout( function() {
this.handle( "sessionFlagTimeout" );
}.bind( this ), currentPerchDelay );
//this.transition('session');
}
} else {
currentBlock[currentTrialNum].success = false;
console.log(currentBlock[currentTrialNum]);
// If finished, go to ended session, not session
if (currentTrialNum+1 >= currentBlock.length) {
// Place the delay in lowering the flag
this.timer = setTimeout( function() {
this.handle( "endedSessionFlagTimeout" );
}.bind( this ), currentPerchDelay );
//this.transition('endedSession');
} else {
// Log the trial outcome
data.logTrial(currentBlock[currentTrialNum]);
currentTrialNum = currentTrialNum + 1;
// place the delay in lowering the flag
this.timer = setTimeout( function() {
this.handle( "sessionFlagTimeout" );
}.bind( this ), currentPerchDelay );
//this.transition('session');
}
}
},
endSession: function() {
clearTimeout( this.timer );
// deal with the current trial
this.transition("endedSession");
},
sessionFlagTimeout: function() {
console.log("insider sesson flag timeout", currentPerchDelay);
lagarto.turnLightOff(currentBlock[currentTrialNum-1].intended-1);
this.transition('session');
},
endedSessionFlagTimeout: function() {
console.log("insider ended sesson flag timeout", currentPerchDelay);
lagarto.turnLightOff(currentBlock[currentTrialNum].intended-1);
this.transition( "endedSession" );
},
},
failedSession: {
_onEnter: function() {
console.log("failed session!");
},
wrapUpSession: function (note) {
console.log(currentBlock);
// Log the trial with the related note
currentBlock[currentTrialNum].notes = note;
data.logTrial(currentBlock[currentTrialNum]);
resetAllValues();
this.transition('freeForm');
},
"*": function() {
},
_onExit: function() {
},
},
endedSession: {
_onEnter: function() {
console.log("Inside ended session");
},
wrapUpSession: function (note) {
console.log(currentBlock);
// Log the trial with the related note
currentBlock[currentTrialNum].notes = note;
data.logTrial(currentBlock[currentTrialNum]);
resetAllValues();
this.transition('freeForm');
},
"*": function() {
},
_onExit: function() {
},
},
},
// External Facing API
initializeDevices: function(newDeviceMapping) {
console.log("initialize API");
experiment.setDeviceMapping(newDeviceMapping);
this.handle( "initialize" );
},
startExperiment: function(birdID, stage) {
console.log("startExperiment API", birdID, stage);
this.handle("startExperiment", birdID, stage);
},
cancelExperiment: function() {
console.log("cancelExperiment API");
this.handle( "cancelExperiment" );
},
startSession: function(numOfTrials, perchDelay) {
console.log("startSession API", numOfTrials, perchDelay);
this.handle("startSession", numOfTrials, perchDelay);
},
endSession: function() {
console.log("endSession API");
this.handle( "endSession" );
},
wrapUpSession: function(note) {
console.log("wrapUpSession API");
this.handle( "wrapUpSession", note);
},
ackIndicator: function() {
lagarto.ackIndicator();
},
// FreeForm Action Methods
dropMeat: function(feederID) {
console.log("dropMeat API", feederID);
this.handle("dropMeat", feederID);
//lagarto.sendMessage();
},
lightOn: function(lightID) {
console.log("lightOn API", lightID);
this.handle("lightOn", lightID);
},
lightOff: function(lightID) {
console.log("lightOff API");
this.handle( "lightOff", lightID);
},
perchEvent: function(perchID) {
console.log("perchEvent API");
this.handle("perchEvent", perchID);
},
// Experimental Methods
meatDropped: function(feederID) {
console.log("meatDropped API");
this.handle("meatDroppedEvent", feederID);
},
lightChanged: function(lightID) {
console.log("perchEvent API");
this.handle("lightChangedEvent", lightID);
},
// Feeder Stages Methods
stopFeeder: function(feederID) {
console.log("stopFeeder API", feederID);
// Transform experimental Feeder ID into the actual device Name
deviceNameID = expNodeToDeviceName[feederID];
lagarto.stopFeeder(deviceNameID);
// Consider the interaction with the state machine later
//this.handle("stopFeeder", feederID);
},
resetFeeder: function(feederID) {
console.log("resetFeeder API", feederID);
// Transform experimental Feeder ID into the actual device Name
deviceNameID = expNodeToDeviceName[feederID];
lagarto.resetFeeder(deviceNameID);
// Consider the interaction with the state machine later
//this.handle("resetFeeder", feederID);
},
primeFeeder: function(feederID) {
console.log("primeFeeder API", feederID);
// Transform experimental Feeder ID into the actual device Name
deviceNameID = expNodeToDeviceName[feederID];
lagarto.primeFeeder(deviceNameID);
// Consider the interaction with the state machine later
//this.handle("primeFeeder", feederID);
},
// End Experimental Methods
addNewBird: function(newBird, res) {
console.log("addNewBird API", newBird);
data.newBird(newBird, res, experiment.getBirds);
//return data.getBirds();
},
addNewStage: function(newStage, res) {
console.log("addNewStage API", newStage);
data.newStage(newStage,res, experiment.getStages);
//return data.getStages()
},
// Data Methods
getCurrentSessionProgress: function() {
// accept row value
// filer the 'currentBlock' by that value onwards
// return that block of data
return currentBlock;
},
getBirds: function(res) {
data.getBirds(res);
},
getStages: function(res) {
data.getStages(res);
},
deleteBird: function(bird, res) {
//console.log("inside controller: ", bird);
data.deleteBird(bird, res);
},
deleteStage: function(stage, res) {
//console.log("inside controller: ", stage);
data.deleteStage(stage, res);
},
getOnlineDeviceListFreeform: function() {
// But should I also change the current state?
this.handle( "reInitialize" );
return experiment.getOnlineDeviceList();
},
getOnlineDeviceListFreeformNoReIt: function() {
// But should I also change the current state?
console.log("did it enter the controller?");
return experiment.getOnlineDeviceList();
},
getOnlineDeviceList: function() {
console.log("Insider getDevicesList in controller");
onlineDeviceList = lagarto.getOnlineDeviceList();
console.log(expToDevice);
console.log(onlineDeviceList);
console.log(lagartoToDevice);
console.log("Retrived values from devices in controller");
// reverse list
feeders = {'feederList': [
{'id': 1, 'mappedTo': expToDevice[0].deviceID,
'batteryLevel': onlineDeviceList[lagartoToDevice[expToDevice[0].deviceID]].batteryLevel,
'meatRemaining': onlineDeviceList[lagartoToDevice[expToDevice[0].deviceID]].meatRemaining,
'state': onlineDeviceList[lagartoToDevice[expToDevice[0].deviceID]].state,
'connected': onlineDeviceList[lagartoToDevice[expToDevice[0].deviceID]].online,
'colour': 'red', 'perch-colour': 'black' },
{'id': 2, 'mappedTo': expToDevice[1].deviceID,
'batteryLevel': onlineDeviceList[lagartoToDevice[expToDevice[1].deviceID]].batteryLevel,
'meatRemaining': onlineDeviceList[lagartoToDevice[expToDevice[1].deviceID]].meatRemaining,
'state': onlineDeviceList[lagartoToDevice[expToDevice[1].deviceID]].state,
'connected': onlineDeviceList[lagartoToDevice[expToDevice[1].deviceID]].online,
'colour': 'red', 'perch-colour': 'black' },
{'id': 3, 'mappedTo': expToDevice[2].deviceID,
'batteryLevel': onlineDeviceList[lagartoToDevice[expToDevice[2].deviceID]].batteryLevel,
'meatRemaining': onlineDeviceList[lagartoToDevice[expToDevice[2].deviceID]].meatRemaining,
'state': onlineDeviceList[lagartoToDevice[expToDevice[2].deviceID]].state,
'connected': onlineDeviceList[lagartoToDevice[expToDevice[2].deviceID]].online,
'colour': 'red', 'perch-colour': 'black' },
{'id': 4, 'mappedTo': expToDevice[3].deviceID,
'batteryLevel': onlineDeviceList[lagartoToDevice[expToDevice[3].deviceID]].batteryLevel,
'meatRemaining': onlineDeviceList[lagartoToDevice[expToDevice[3].deviceID]].meatRemaining,
'state': onlineDeviceList[lagartoToDevice[expToDevice[3].deviceID]].state,
'connected': onlineDeviceList[lagartoToDevice[expToDevice[3].deviceID]].online,
'colour': 'red', 'perch-colour': 'black' },
{'id': 5, 'mappedTo': expToDevice[4].deviceID,
'batteryLevel': onlineDeviceList[lagartoToDevice[expToDevice[4].deviceID]].batteryLevel,
'meatRemaining': onlineDeviceList[lagartoToDevice[expToDevice[4].deviceID]].meatRemaining,
'state': onlineDeviceList[lagartoToDevice[expToDevice[4].deviceID]].state,
'connected': onlineDeviceList[lagartoToDevice[expToDevice[4].deviceID]].online,
'colour': 'red', 'perch-colour': 'black' },
{'id': 6, 'mappedTo': expToDevice[5].deviceID,
'batteryLevel': onlineDeviceList[lagartoToDevice[expToDevice[5].deviceID]].batteryLevel,
'meatRemaining': onlineDeviceList[lagartoToDevice[expToDevice[5].deviceID]].meatRemaining,
'state': onlineDeviceList[lagartoToDevice[expToDevice[5].deviceID]].state,
'connected': onlineDeviceList[lagartoToDevice[expToDevice[5].deviceID]].online,
'colour': 'red', 'perch-colour': 'black' },
{'id': 7, 'mappedTo': expToDevice[6].deviceID,
'batteryLevel': onlineDeviceList[lagartoToDevice[expToDevice[6].deviceID]].batteryLevel,
'meatRemaining': onlineDeviceList[lagartoToDevice[expToDevice[6].deviceID]].meatRemaining,
'state': onlineDeviceList[lagartoToDevice[expToDevice[6].deviceID]].state,
'connected': onlineDeviceList[lagartoToDevice[expToDevice[6].deviceID]].online,
'colour': 'red', 'perch-colour': 'black' },
{'id': 8, 'mappedTo': expToDevice[7].deviceID,
'batteryLevel': onlineDeviceList[lagartoToDevice[expToDevice[7].deviceID]].batteryLevel,
'meatRemaining': onlineDeviceList[lagartoToDevice[expToDevice[7].deviceID]].meatRemaining,
'state': onlineDeviceList[lagartoToDevice[expToDevice[7].deviceID]].state,
'connected': onlineDeviceList[lagartoToDevice[expToDevice[7].deviceID]].online,
'colour': 'red', 'perch-colour': 'black' },
{'id': 9, 'mappedTo': expToDevice[8].deviceID,
'batteryLevel': onlineDeviceList[lagartoToDevice[expToDevice[8].deviceID]].batteryLevel,
'meatRemaining': onlineDeviceList[lagartoToDevice[expToDevice[8].deviceID]].meatRemaining,
'state': onlineDeviceList[lagartoToDevice[expToDevice[8].deviceID]].state,
'connected': onlineDeviceList[lagartoToDevice[expToDevice[8].deviceID]].online,
'colour': 'red', 'perch-colour': 'black' },
{'id': 10, 'mappedTo': expToDevice[9].deviceID,
'batteryLevel': onlineDeviceList[lagartoToDevice[expToDevice[9].deviceID]].batteryLevel,
'meatRemaining': onlineDeviceList[lagartoToDevice[expToDevice[9].deviceID]].meatRemaining,
'state': onlineDeviceList[lagartoToDevice[expToDevice[9].deviceID]].state,
'connected': onlineDeviceList[lagartoToDevice[expToDevice[9].deviceID]].online,
'colour': 'red', 'perch-colour': 'black'}],
'onlineList': [
{'id': 'a', 'connected': onlineDeviceList[lagartoToDevice[expToDevice[0].deviceID]].online},
{'id': 'b', 'connected': onlineDeviceList[lagartoToDevice[expToDevice[1].deviceID]].online},
{'id': 'c', 'connected': onlineDeviceList[lagartoToDevice[expToDevice[2].deviceID]].online},
{'id': 'd', 'connected': onlineDeviceList[lagartoToDevice[expToDevice[3].deviceID]].online},
{'id': 'e', 'connected': onlineDeviceList[lagartoToDevice[expToDevice[4].deviceID]].online},
{'id': 'f', 'connected': onlineDeviceList[lagartoToDevice[expToDevice[5].deviceID]].online},
{'id': 'g', 'connected': onlineDeviceList[lagartoToDevice[expToDevice[6].deviceID]].online},
{'id': 'h', 'connected': onlineDeviceList[lagartoToDevice[expToDevice[7].deviceID]].online},
{'id': 'i', 'connected': onlineDeviceList[lagartoToDevice[expToDevice[8].deviceID]].online},
{'id': 'j', 'connected': onlineDeviceList[lagartoToDevice[expToDevice[9].deviceID]].online},
]};
for (var i=0; i<10; i++) {
if (feeders['feederList'][i].connected == true){
feeders['feederList'][i].colour = 'green';
}
}
console.log(feeders);
return feeders;
},
getDeviceMapping: function() {
return expNodeToDeviceName;
},
setDeviceMapping: function(newDeviceMapping) {
// Take what is passed through to update the data.setDeviceMapping
// and also whatever temp variable that is required during the course of this session
// This is what is returned, turn this into
deviceNameToExpNode1 = {'a': '1',
'b': '2',
'c': '3',
'd': '4',
'e': '5',
'f': '6',
'g': '7',
'h': '8',
'i': '9',
'j': '10'};
expNodeToDeviceName1 = {'1': 'a',
'2': 'b',
'3': 'c',
'4': 'd',
'5': 'e',
'6': 'f',
'7': 'g',
'8': 'h',
'9': 'i',
'10': 'j'};
/*
deviceMapping = [{nodeID: 1, deviceID: 'a'},
{nodeID: 2, deviceID: 'b'},
{nodeID: 3, deviceID: 'c'},
{nodeID: 4, deviceID: 'd'},
{nodeID: 5, deviceID: 'e'},
{nodeID: 6, deviceID: 'f'},
{nodeID: 7, deviceID: 'g'},
{nodeID: 8, deviceID: 'h'},
{nodeID: 9, deviceID: 'i'},
{nodeID: 10, deviceID: 'j'}];
*/
for (var i=0; i<10; i++) {
deviceNameToExpNode1[newDeviceMapping[i].deviceID] = newDeviceMapping[i].nodeID;
expNodeToDeviceName1[i+1] = newDeviceMapping[i].deviceID;
}
deviceNameToExpNode = deviceNameToExpNode1;
expNodeToDeviceName = expNodeToDeviceName1;
expToDevice = newDeviceMapping;
console.log("deviceNameToExpNode: ",deviceNameToExpNode);
console.log("expNodeToDeviceName: ", expNodeToDeviceName)
data.setDeviceMapping(newDeviceMapping);
},
getLeaderBoard: function() {
return data.getLeaderBoard();
},
getTrialsOfBirdInStage: function(birdID, stageID, res) {
data.getTrialsOfBirdInStage(birdID, stageID, res);
},
getCurrentBatteryLife: function() {
return lagarto.getCurrentBatteryLife();
},
} );
// Logging for any handeler event and state change
experiment.on("*", function (eventName, data){
// uncomment to see all the stage changes printed to console
//console.log("this thing happened:", eventName, data);
});
// create an instance of the Meerkat class
var meerkat = new lagarto.Meerkat();
// add an 'perch' event listener
meerkat.on('perchEvent', function(perchID) {
console.log('perch event listenter: "%s"', perchID);
// Parse deviceID to experimental nodeID
expNode = deviceNameToExpNode[perchID];
console.log(expNode);
experiment.perchEvent(expNode);
});
// add a 'meatDropped' event listener
meerkat.on('meatDropped', function(feederID) {
console.log('meatDropped event listenter: "%s"', feederID);
// Parse deviceID to experimental nodeID
experiment.meatDropped(feederID);
});
// add a 'lightChange' event listener
meerkat.on('lightChanged', function(lightID) {
console.log('lightChanged event listenter: "%s"', lightID);
// Parse deviceID to experimental nodeID
experiment.lightChanged(lightID);
});
// add a 'device offline' event listener
meerkat.on('feederOfline', function(feederID) {
console.log('Feeder went offline: "%s"', feederID);
// Parse deviceID to experimental nodeID
//experiment.perchEvent(perchID);
});
// add a 'feeder online' event listener
meerkat.on('feederOnline', function(feederID) {
console.log('Feeder went online: "%s"', feederID);
// Parse deviceID to experimental nodeID
//experiment.perchEvent(perchID);
});
// add a 'meat levels updated' event listener - - - this could be combine with meat dropped perhaps
meerkat.on('meatUpdate', function(feederID, meatLeft) {
console.log('Meat levels changed: "%s %s"', feederID, meatleft);
// Parse deviceID to experimental nodeID
//experiment.perchEvent(perchID);
});
// add a 'lightChange' event listener
meerkat.on('dunno', function(ID) {
console.log('[dunno] unknown event: "%s"', ID);
// Parse deviceID to experimental nodeID
//experiment.perchEvent(perchID);
});
// What other actions should be listened for
// Meat levels changed
// Battery levels changed
// devices going online / offline
// Start with: get all available devices (called from when a state changes, prompted by UI)
// Then subscribe to updates after that
// get state
// battery lists
// meat left lists
// device on list
// devices can be stateless, controller keeps it all up-to-date
// setup phases loads in the list
// calls devices to get the initial list
// - what is on, what the battery levels are, how much meat is left, what the deviceID's are
// devices doesnt really care what the experimental nodes are, or what is being used, its just an interface
module.exports.experiment = experiment;
|
import { assert, JSData } from '../../_setup'
import { productSchema } from './_productSchema'
describe('Schema.pick', function () {
it('has the right exports', function () {
assert.isFunction(JSData.Schema.prototype.pick)
})
it('Copies a value based on the properties defined in the schema', function () {
const schema = new JSData.Schema(productSchema)
const data = {
id: 1,
foo: 'bar',
dimensions: {
length: 1234,
beep: 'boop'
}
}
const copy = schema.pick(data)
assert.deepEqual(copy, {
id: 1,
dimensions: {
height: undefined,
length: 1234,
width: undefined
},
name: undefined,
price: undefined,
tags: undefined,
warehouseLocation: undefined
})
})
it('Copies a value based on the items defined in the schema allowing extra properties', function () {
const schema = new JSData.Schema({
type: 'object',
properties: {
id: {
type: 'number'
},
tags: {
type: 'array',
items: {
type: 'object',
properties: {
name: {
type: 'string'
},
id: {
type: 'number'
}
},
additionalProperties: true
}
}
},
additionalProperties: true
})
const data = {
id: 1,
foo: 'bar',
tags: [
{
name: 'foo',
beep: 'boop'
}
]
}
const copy = schema.pick(data)
assert.deepEqual(copy, {
id: 1,
foo: 'bar',
tags: [
{
name: 'foo',
id: undefined,
beep: 'boop'
}
]
})
})
it('Copies a value based on the items defined in the schema disallowing extra properties', function () {
const schema = new JSData.Schema({
type: 'object',
properties: {
id: {
type: 'number'
},
tags: {
type: 'array',
items: {
type: 'object',
properties: {
name: {
type: 'string'
},
id: {
type: 'number'
}
}
}
}
}
})
const data = {
id: 1,
foo: 'bar',
tags: [
{
name: 'foo',
beep: 'boop'
}
]
}
const copy = schema.pick(data, { strict: true })
assert.deepEqual(copy, {
id: 1,
// foo was stripped
tags: [
{
name: 'foo',
id: undefined
// beep was stripped
}
]
})
})
it('Copies a value based on the parent schema', function () {
const schema = new JSData.Schema({
type: 'object',
extends: productSchema,
properties: {
id: {
type: 'number'
},
roles: {
type: 'array',
items: {
type: 'object',
properties: {
name: {
type: 'string'
},
id: {
type: 'number'
}
}
}
}
}
})
const data = {
id: 1,
foo: 'bar',
roles: [
{
name: 'foo',
beep: 'boop'
}
],
dimensions: {}
}
const copy = schema.pick(data)
assert.deepEqual(copy, {
id: 1,
dimensions: {
height: undefined,
length: undefined,
width: undefined
},
price: undefined,
name: undefined,
tags: undefined,
roles: [
{
name: 'foo',
id: undefined
}
],
warehouseLocation: undefined
})
})
it('should ignore undefined properties', function () {
const store = new JSData.DataStore()
const countrySchema = new JSData.Schema({
type: 'object',
properties: {
code: {
type: 'string',
indexed: true
}
}
})
store.defineMapper('country', {
schema: countrySchema
})
store.add('country', [
{
code: 'foo'
},
{
code: 'bar'
}
])
const addressSchema = new JSData.Schema({
type: 'object',
properties: {
uid: { type: 'string' },
tag: { type: ['string', 'null'] },
country: {
type: 'object',
extends: countrySchema,
get () {
return store.getAll('country', this.tag, { index: 'code' })[0]
}
}
}
})
store.defineMapper('address', {
schema: addressSchema
})
const address = store.createRecord('address', { uid: '123', tag: 'foo' })
const address2 = store.createRecord('address', { uid: '789', tag: 'beep' })
assert.deepEqual(address.toJSON(), {
uid: '123',
tag: 'foo',
country: {
code: 'foo'
}
})
assert.deepEqual(address2.toJSON(), {
uid: '789',
tag: 'beep',
country: undefined
})
})
})
|
var puremvc = window.puremvc;
var TodoProxy = require('../../model/proxy/TodoProxy');
class PrepModelCommand extends puremvc.SimpleCommand {
execute() {
this.facade.registerProxy(new TodoProxy());
}
}
module.exports = PrepModelCommand;
|
import Shader from "./shader/shader-program";
import { degToRad, makePerspective } from "./utility";
import PerformanceCounter from "./performance-counter";
import TextureManager from "./texture-manager";
import Planet from "./planet";
import config from "./config";
/**
* Resizes the given canvas element to fit the whole screen.
* @param {DOMElement} canvas The canvas element to resize
*/
function resizeToFullscreen(canvas, glContext, uiCanvas, uiContext) {
const width = document.body.clientWidth;
const height = document.body.clientHeight;
canvas.width = width;
canvas.height = height;
glContext.viewportWidth = width;
glContext.viewportHeight = height;
uiCanvas.width = width;
uiCanvas.height = height;
uiContext.viewportWidth = width;
uiContext.viewportHeight = height;
}
/**
* Reference to the projection matrix.
*/
let pMatrix;
/**
* Reference to the model view matrix.
*/
let mvMatrix;
export default class SolarApp {
/**
* Prepares all necessary elements to execute and draw SolarApp.
* @param {DOMElement} canvas The canvas element to draw to
*/
constructor(canvas, uiCanvas) {
this.lastTime = new Date().getTime();
this.canvas = canvas;
this.uiCanvas = uiCanvas;
this.gl = this.initializeContext(this.canvas, "webgl");
this.uiContext = this.initializeContext(this.uiCanvas, "2d");
this.shader = new Shader(this.gl);
this.yaw = 0;
this.pitch = 0;
this.mouseFactor = 1.5;
this.mousePosition = { x: 0, y: 0 };
this.cameraPosition = [0, 0, -50];
this.isMouseDown = false;
this.perfCounter = new PerformanceCounter();
this.textureManager = new TextureManager(this.gl, config.textures);
resizeToFullscreen(this.canvas, this.gl, this.uiCanvas, this.uiContext);
this.gl.clearColor(0.0, 0.0, 0.0, 1.0);
this.gl.enable(this.gl.DEPTH_TEST);
// Bind this to callbacks
this.onResize = this.onResize.bind(this);
this.onMouseScroll = this.onMouseScroll.bind(this);
this.onMouseDown = this.onMouseDown.bind(this);
this.onMouseUp = this.onMouseUp.bind(this);
this.onMouseMove = this.onMouseMove.bind(this);
}
async initialize() {
await this.textureManager.initialize();
this.solarSystem = this.setupSolarSystem(config.system);
}
/**
* Tries to initialize the webgl context for the given canvas.
* @param {DOMElement} canvas The canvas to get the context for.
*/
initializeContext(canvas, type) {
try {
let glContext = canvas.getContext(type);
glContext.viewportWidth = canvas.width;
glContext.viewportHeight = canvas.height;
return glContext;
} catch (e) {
this.onError(e);
return null;
}
}
setupSolarSystem(systemConfig) {
const planets = [];
systemConfig.planets.forEach((planetConfig) => {
let p = new Planet({ position: [ planetConfig.distance * config.globalScale, 0, 0 ] , radius: planetConfig.radius * config.globalScale, texture: this.textureManager.getTexture(planetConfig.texture), speed: planetConfig.speed, rotationSpeed: planetConfig.rotationSpeed, orbitalInclination: planetConfig.orbitalInclination });
p.create(this.gl);
planetConfig.moons.forEach((moonConfig) => {
let m = new Planet({ position: [ (planetConfig.distance + moonConfig.distance) * config.globalScale, 0, 0 ], radius: moonConfig.radius * config.globalScale, texture: this.textureManager.getTexture(moonConfig.texture), speed: moonConfig.speed, rotationSpeed: moonConfig.rotationSpeed });
m.create(this.gl);
p.addChild(m);
});
planets.push(p);
});
return planets;
}
/**
* Error Callback
*/
onError(err) {
console.dir(err);
}
/**
* Resize Callback
*/
onResize() {
// TODO: Throttle number of calls.
resizeToFullscreen(this.canvas, this.gl, this.uiCanvas, this.uiContext);
}
/**
* Mouse Scroll Callback
*/
onMouseScroll(e) {
const zoomDir = Math.max(-1, Math.min(1, e.deltaY));
this.cameraPosition[2] += zoomDir * config.zoomSpeed;
}
/**
* Mouse Down Callback
*/
onMouseDown() {
this.isMouseDown = true;
}
/**
* Mouse Up Callback
*/
onMouseUp() {
this.isMouseDown = false;
}
/**
* Mouse Move Callback
*/
onMouseMove({ clientX, clientY }) {
if (this.isMouseDown) {
const { x:lastX , y:lastY } = this.mousePosition;
const dX = clientX - lastX;
const dY = clientY - lastY;
this.cameraPosition[0] += -1 * dX * config.moveSpeed;
this.cameraPosition[1] += dY * config.moveSpeed;
}
this.mousePosition.x = clientX;
this.mousePosition.y = clientY;
}
doAction() {
try {
this.update();
this.render();
this.renderUI();
} catch (err) {
this.onError(err);
}
}
/**
* Update function of the SolarApp
*/
update() {
const now = new Date().getTime();
const elapsed = now - this.lastTime;
this.perfCounter.update(elapsed);
this.solarSystem.forEach(p => p.update(elapsed));
this.lastTime = now;
}
/**
* Render function of the SolarApp
*/
render() {
this.gl.viewport(0, 0, this.gl.viewportWidth, this.gl.viewportHeight);
this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);
pMatrix = makePerspective(45, this.gl.viewportWidth/this.gl.viewportHeight, config.camera.zNear, config.camera.zFar);
mvMatrix = Matrix.I(4)
// Move Camera
.x(Matrix.Translation($V(this.cameraPosition)).ensure4x4())
// Rotate around y-axis (vertical)
.x(Matrix.Rotation(degToRad(this.yaw), $V([0, 1, 0])).ensure4x4())
// Rotate around x-axis (horizontal)
.x(Matrix.Rotation(degToRad(this.pitch), $V([1, 0, 0])).ensure4x4());
this.shader.setLight(this.gl);
this.solarSystem.forEach(p => p.draw(this.gl, this.shader, pMatrix, mvMatrix));
}
renderUI() {
this.uiContext.clearRect(0, 0, this.uiCanvas.width, this.uiCanvas.height);
const labelWidth = 100;
const labelHeight = 30;
const labelPosX = this.uiCanvas.width - labelWidth;
const labelPosY = this.uiCanvas.height - labelHeight;
this.uiContext.fillStyle = "white";
this.uiContext.fillRect(labelPosX, labelPosY, labelWidth, labelHeight);
this.uiContext.fillStyle = "black";
this.uiContext.fillText(`AVG: ${this.perfCounter.average.toFixed(2)}ms`, labelPosX + 5, labelPosY + 12);
this.uiContext.fillText(`FPS: ${this.perfCounter.fps.toFixed(1)}`, labelPosX + 5, labelPosY + 25);
}
}
|
import Enzyme, { mount } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
Enzyme.configure({ adapter: new Adapter() })
import { Line } from './Line'
describe('<Line />', () => {
let wrapper
beforeEach(() => {
wrapper = mount(<Line />)
})
test('Should renderer', () => {
expect(wrapper).toBeDefined()
})
})
|
var gulp = require('gulp');
var ts = require('gulp-typescript');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var ddescribeIit = require('gulp-ddescribe-iit');
var shell = require('gulp-shell');
var ghPages = require('gulp-gh-pages');
var del = require('del');
var merge = require('merge2');
var clangFormat = require('clang-format');
var gulpFormat = require('gulp-clang-format');
var runSequence = require('run-sequence');
var webpack = require('webpack');
var webpackDemoConfig = require('./webpack.demo.js');
var PATHS = {src: 'src/**/*.ts', specs: 'src/**/*.spec.ts', demo: 'demo/**/*.ts', demoDist: 'demo/dist/**/*'};
// Transpiling & Building
var buildProject = ts.createProject('tsconfig.json', {declaration: true});
gulp.task('clean:build', function() { return del('dist/'); });
gulp.task('cjs', function() {
var tsResult = gulp.src([PATHS.src, '!' + PATHS.specs]).pipe(ts(buildProject));
return merge([tsResult.dts.pipe(gulp.dest('dist/cjs')), tsResult.js.pipe(gulp.dest('dist/cjs'))]);
});
gulp.task('umd', function(cb) {
webpack(
{
entry: './dist/cjs/core.js',
output: {filename: 'dist/global/ng-bootstrap.js', library: 'ngb', libraryTarget: 'umd'},
externals: {
'angular2/angular2':
{root: 'ng', commonjs: 'angular2/angular2', commonjs2: 'angular2/angular2', amd: 'angular2/angular2'}
}
},
function(err, stats) {
if (err) throw new gutil.PluginError('webpack', err);
gutil.log("[webpack]", stats.toString());
cb();
});
});
// Testing
var testProject = ts.createProject('tsconfig.json');
function startKarmaServer(isTddMode, done) {
var karmaServer = require('karma').Server;
var travis = process.env.TRAVIS;
var config = {configFile: __dirname + '/karma.conf.js', singleRun: !isTddMode, autoWatch: isTddMode};
if (travis) {
config['reporters'] = ['dots'];
config['browsers'] = ['Firefox'];
}
new karmaServer(config, done).start();
}
gulp.task('clean:tests', function() { return del('temp/'); });
gulp.task('build:tests', function() {
var tsResult = gulp.src(PATHS.src).pipe(sourcemaps.init()).pipe(ts(testProject));
return tsResult.js.pipe(sourcemaps.write('.')).pipe(gulp.dest('temp'));
});
gulp.task('clean:build-tests', function(done) { runSequence('clean:tests', 'build:tests', done); });
gulp.task(
'ddescribe-iit', function() { return gulp.src(PATHS.specs).pipe(ddescribeIit({allowDisabledTests: false})); });
gulp.task('test', ['clean:build-tests'], function(done) { startKarmaServer(false, done); });
gulp.task('tdd', ['clean:build-tests'], function(done) {
startKarmaServer(true, function(err) {
done(err);
process.exit(1);
});
gulp.watch(PATHS.src, ['build:tests']);
});
// Formatting
gulp.task('check-format', function() {
return doCheckFormat().on(
'warning', function(e) { console.log("NOTE: this will be promoted to an ERROR in the continuous build"); });
});
gulp.task('enforce-format', function() {
return doCheckFormat().on('warning', function(e) {
console.log("ERROR: You forgot to run clang-format on your change.");
console.log("See https://github.com/ng-bootstrap/core/blob/master/DEVELOPER.md#clang-format");
process.exit(1);
});
});
function doCheckFormat() {
return gulp.src(['gulpfile.js', 'karma-test-shim.js', PATHS.src, PATHS.demo])
.pipe(gulpFormat.checkFormat('file', clangFormat));
}
// Demo
gulp.task('clean:demo', function() { return del('demo/dist'); });
gulp.task('clean:demo-cache', function() { return del('.publish/'); });
gulp.task('copy:polyfills-demo', function() {
gulp.src('./node_modules/angular2/bundles/angular2-polyfills.js').pipe(gulp.dest('./demo/dist/lib/'));
});
gulp.task(
'demo-server', ['copy:polyfills-demo'],
shell.task(['webpack-dev-server --config webpack.demo.js --inline --progress']));
gulp.task('build:demo', function(done) {
var config = Object.create(webpackDemoConfig);
config.plugins = config.plugins.concat(new webpack.optimize.UglifyJsPlugin());
webpack(config, function(err, stats) {
if (err) throw new gutil.PluginError('build:demo', err);
gutil.log('[build:demo]', stats.toString({colors: true}));
done();
});
});
gulp.task('demo-push', function() { return gulp.src(PATHS.demoDist).pipe(ghPages()); });
// Public Tasks
gulp.task('build', function(done) {
runSequence('enforce-format', 'ddescribe-iit', 'test', 'clean:build', 'cjs', 'umd', done);
});
gulp.task('deploy-demo', function(done) {
runSequence('clean:demo', 'copy:polyfills-demo', 'build:demo', 'demo-push', 'clean:demo-cache', done);
});
gulp.task('default', function(done) { runSequence('enforce-format', 'ddescribe-iit', 'test', done); });
|
/**
* @license
* Copyright (c) 2016 Nicholas Nelson
*
* 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.
*/
import GameTimer from './GameTimer';
import SceneHandler from './SceneHandler';
import ViewRenderer from './ViewRenderer';
/**
* The Engine class, manages all aspects of the game
*/
class Engine {
/**
* Constructor for the game engine
* @param {Element} canvas The HTML canvas to render on
*/
constructor(canvas) {
this.timer = new GameTimer();
this.sceneHandler = new SceneHandler();
this.sceneHandler.init();
this.renderer = new ViewRenderer({
canvas: canvas,
scene: this.sceneHandler.scene,
world: this.sceneHandler.world});
}
/**
* Run one game tick, normally will be called by requestUpdateFrame
* from app.js
*/
tick() {
this.timer.update();
this.sceneHandler.update(this.timer.deltaTime);
this.renderer.update();
this.renderer.render(this.sceneHandler);
}
}
export { Engine as default };
|
import Ember from "ember-metal/core";
import run from "ember-metal/run_loop";
import EmberObject from "ember-runtime/system/object";
import RSVP from "ember-runtime/ext/rsvp";
import EmberView from "ember-views/views/view";
import jQuery from "ember-views/system/jquery";
import Test from "ember-testing/test";
import "ember-testing/helpers"; // ensure that the helpers are loaded
import "ember-testing/initializers"; // ensure the initializer is setup
import setupForTesting from "ember-testing/setup_for_testing";
import EmberRouter from "ember-routing/system/router";
import EmberRoute from "ember-routing/system/route";
import EmberApplication from "ember-application/system/application";
import EmberHandlebars from "ember-handlebars";
import htmlbarsCompile from "ember-htmlbars/system/compile";
var App, originalAdapter = Test.adapter;
var compile;
if (Ember.FEATURES.isEnabled('ember-htmlbars')) {
compile = htmlbarsCompile;
} else {
compile = EmberHandlebars.compile;
}
function cleanup(){
// Teardown setupForTesting
Test.adapter = originalAdapter;
run(function(){
jQuery(document).off('ajaxSend');
jQuery(document).off('ajaxComplete');
});
Test.pendingAjaxRequests = null;
// Other cleanup
if (App) {
run(App, App.destroy);
App.removeTestHelpers();
App = null;
}
Ember.TEMPLATES = {};
}
function assertHelpers(application, helperContainer, expected){
if (!helperContainer) { helperContainer = window; }
if (expected === undefined) { expected = true; }
function checkHelperPresent(helper, expected){
var presentInHelperContainer = !!helperContainer[helper];
var presentInTestHelpers = !!application.testHelpers[helper];
ok(presentInHelperContainer === expected, "Expected '" + helper + "' to be present in the helper container (defaults to window).");
ok(presentInTestHelpers === expected, "Expected '" + helper + "' to be present in App.testHelpers.");
}
checkHelperPresent('visit', expected);
checkHelperPresent('click', expected);
checkHelperPresent('keyEvent', expected);
checkHelperPresent('fillIn', expected);
checkHelperPresent('wait', expected);
checkHelperPresent('triggerEvent', expected);
}
function assertNoHelpers(application, helperContainer) {
assertHelpers(application, helperContainer, false);
}
function currentRouteName(app){
return app.testHelpers.currentRouteName();
}
function currentPath(app){
return app.testHelpers.currentPath();
}
function currentURL(app){
return app.testHelpers.currentURL();
}
QUnit.module("ember-testing Helpers", {
setup: function(){ cleanup(); },
teardown: function() { cleanup(); }
});
test("Ember.Application#injectTestHelpers/#removeTestHelpers", function() {
App = run(EmberApplication, EmberApplication.create);
assertNoHelpers(App);
App.injectTestHelpers();
assertHelpers(App);
App.removeTestHelpers();
assertNoHelpers(App);
});
test("Ember.Application#setupForTesting", function() {
run(function() {
App = EmberApplication.create();
App.setupForTesting();
});
equal(App.__container__.lookup('router:main').location.implementation, 'none');
});
test("Ember.Application.setupForTesting sets the application to `testing`.", function(){
run(function() {
App = EmberApplication.create();
App.setupForTesting();
});
equal(App.testing, true, "Application instance is set to testing.");
});
test("Ember.Application.setupForTesting leaves the system in a deferred state.", function(){
run(function() {
App = EmberApplication.create();
App.setupForTesting();
});
equal(App._readinessDeferrals, 1, "App is in deferred state after setupForTesting.");
});
test("App.reset() after Application.setupForTesting leaves the system in a deferred state.", function(){
run(function() {
App = EmberApplication.create();
App.setupForTesting();
});
equal(App._readinessDeferrals, 1, "App is in deferred state after setupForTesting.");
App.reset();
equal(App._readinessDeferrals, 1, "App is in deferred state after setupForTesting.");
});
test("`visit` advances readiness.", function(){
expect(2);
run(function() {
App = EmberApplication.create();
App.setupForTesting();
App.injectTestHelpers();
});
equal(App._readinessDeferrals, 1, "App is in deferred state after setupForTesting.");
App.testHelpers.visit('/').then(function(){
equal(App._readinessDeferrals, 0, "App's readiness was advanced by visit.");
});
});
test("`wait` helper can be passed a resolution value", function() {
expect(4);
var promise, wait;
promise = new RSVP.Promise(function(resolve) {
run(null, resolve, 'promise');
});
run(function() {
App = EmberApplication.create();
App.setupForTesting();
});
App.injectTestHelpers();
run(App, App.advanceReadiness);
wait = App.testHelpers.wait;
wait('text').then(function(val) {
equal(val, 'text', 'can resolve to a string');
return wait(1);
}).then(function(val) {
equal(val, 1, 'can resolve to an integer');
return wait({ age: 10 });
}).then(function(val) {
deepEqual(val, { age: 10 }, 'can resolve to an object');
return wait(promise);
}).then(function(val) {
equal(val, 'promise', 'can resolve to a promise resolution value');
});
});
test("`click` triggers appropriate events in order", function() {
expect(4);
var click, wait, events;
run(function() {
App = EmberApplication.create();
App.setupForTesting();
});
App.IndexView = EmberView.extend({
classNames: 'index-view',
didInsertElement: function() {
this.$().on('mousedown focusin mouseup click', function(e) {
events.push(e.type);
});
},
Checkbox: Ember.Checkbox.extend({
click: function() {
events.push('click:' + this.get('checked'));
},
change: function() {
events.push('change:' + this.get('checked'));
}
})
});
Ember.TEMPLATES.index = compile('{{input type="text"}} {{view view.Checkbox}} {{textarea}}');
App.injectTestHelpers();
run(App, App.advanceReadiness);
click = App.testHelpers.click;
wait = App.testHelpers.wait;
wait().then(function() {
events = [];
return click('.index-view');
}).then(function() {
deepEqual(events,
['mousedown', 'mouseup', 'click'],
'fires events in order');
}).then(function() {
events = [];
return click('.index-view input[type=text]');
}).then(function() {
deepEqual(events,
['mousedown', 'focusin', 'mouseup', 'click'],
'fires focus events on inputs');
}).then(function() {
events = [];
return click('.index-view textarea');
}).then(function() {
deepEqual(events,
['mousedown', 'focusin', 'mouseup', 'click'],
'fires focus events on textareas');
}).then(function() {
// In IE (< 8), the change event only fires when the value changes before element focused.
jQuery('.index-view input[type=checkbox]').focus();
events = [];
return click('.index-view input[type=checkbox]');
}).then(function() {
// i.e. mousedown, mouseup, change:true, click, click:true
// Firefox differs so we can't assert the exact ordering here.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=843554.
equal(events.length, 5, 'fires click and change on checkboxes');
});
});
test("Ember.Application#setupForTesting attaches ajax listeners", function() {
var documentEvents;
documentEvents = jQuery._data(document, 'events');
if (!documentEvents) {
documentEvents = {};
}
ok(documentEvents['ajaxSend'] === undefined, 'there are no ajaxSend listers setup prior to calling injectTestHelpers');
ok(documentEvents['ajaxComplete'] === undefined, 'there are no ajaxComplete listers setup prior to calling injectTestHelpers');
run(function() {
setupForTesting();
});
documentEvents = jQuery._data(document, 'events');
equal(documentEvents['ajaxSend'].length, 1, 'calling injectTestHelpers registers an ajaxSend handler');
equal(documentEvents['ajaxComplete'].length, 1, 'calling injectTestHelpers registers an ajaxComplete handler');
});
test("Ember.Application#setupForTesting attaches ajax listeners only once", function() {
var documentEvents;
documentEvents = jQuery._data(document, 'events');
if (!documentEvents) {
documentEvents = {};
}
ok(documentEvents['ajaxSend'] === undefined, 'there are no ajaxSend listers setup prior to calling injectTestHelpers');
ok(documentEvents['ajaxComplete'] === undefined, 'there are no ajaxComplete listers setup prior to calling injectTestHelpers');
run(function() {
setupForTesting();
});
run(function() {
setupForTesting();
});
documentEvents = jQuery._data(document, 'events');
equal(documentEvents['ajaxSend'].length, 1, 'calling injectTestHelpers registers an ajaxSend handler');
equal(documentEvents['ajaxComplete'].length, 1, 'calling injectTestHelpers registers an ajaxComplete handler');
});
test("Ember.Application#injectTestHelpers calls callbacks registered with onInjectHelpers", function(){
var injected = 0;
Test.onInjectHelpers(function(){
injected++;
});
run(function() {
App = EmberApplication.create();
App.setupForTesting();
});
equal(injected, 0, 'onInjectHelpers are not called before injectTestHelpers');
App.injectTestHelpers();
equal(injected, 1, 'onInjectHelpers are called after injectTestHelpers');
});
test("Ember.Application#injectTestHelpers adds helpers to provided object.", function(){
var helpers = {};
run(function() {
App = EmberApplication.create();
App.setupForTesting();
});
App.injectTestHelpers(helpers);
assertHelpers(App, helpers);
App.removeTestHelpers();
assertNoHelpers(App, helpers);
});
test("Ember.Application#removeTestHelpers resets the helperContainer's original values", function(){
var helpers = {visit: 'snazzleflabber'};
run(function() {
App = EmberApplication.create();
App.setupForTesting();
});
App.injectTestHelpers(helpers);
ok(helpers.visit !== 'snazzleflabber', "helper added to container");
App.removeTestHelpers();
ok(helpers.visit === 'snazzleflabber', "original value added back to container");
});
test("`wait` respects registerWaiters", function() {
expect(2);
var counter=0;
function waiter() {
return ++counter > 2;
}
run(function() {
App = EmberApplication.create();
App.setupForTesting();
});
App.injectTestHelpers();
run(App, App.advanceReadiness);
Test.registerWaiter(waiter);
App.testHelpers.wait().then(function() {
equal(waiter(), true, 'should not resolve until our waiter is ready');
Test.unregisterWaiter(waiter);
equal(Test.waiters.length, 0, 'should not leave a waiter registered');
});
});
test("`wait` waits for outstanding timers", function() {
expect(1);
var wait_done = false;
run(function() {
App = EmberApplication.create();
App.setupForTesting();
});
App.injectTestHelpers();
run(App, App.advanceReadiness);
run.later(this, function() {
wait_done = true;
}, 500);
App.testHelpers.wait().then(function() {
equal(wait_done, true, 'should wait for the timer to be fired.');
});
});
test("`wait` respects registerWaiters with optional context", function() {
expect(2);
var obj = {
counter: 0,
ready: function() {
return ++this.counter > 2;
}
};
run(function() {
App = EmberApplication.create();
App.setupForTesting();
});
App.injectTestHelpers();
run(App, App.advanceReadiness);
Test.registerWaiter(obj, obj.ready);
App.testHelpers.wait().then(function() {
equal(obj.ready(), true, 'should not resolve until our waiter is ready');
Test.unregisterWaiter(obj, obj.ready);
equal(Test.waiters.length, 0, 'should not leave a waiter registered');
});
});
if (Ember.FEATURES.isEnabled("ember-testing-pause-test")) {
QUnit.module("ember-testing debugging helpers", {
setup: function(){
cleanup();
run(function() {
App = EmberApplication.create();
App.Router = EmberRouter.extend({
location: 'none'
});
App.setupForTesting();
});
App.injectTestHelpers();
run(App, 'advanceReadiness');
},
teardown: function(){
cleanup();
}
});
test("pauseTest pauses", function() {
expect(1);
function fakeAdapterAsyncStart() {
ok(true, 'Async start should be called');
}
Test.adapter.asyncStart = fakeAdapterAsyncStart;
App.testHelpers.pauseTest();
});
}
QUnit.module("ember-testing routing helpers", {
setup: function(){
cleanup();
run(function() {
App = EmberApplication.create();
App.Router = EmberRouter.extend({
location: 'none'
});
App.Router.map(function() {
this.resource("posts", function() {
this.route("new");
});
});
App.setupForTesting();
});
App.injectTestHelpers();
run(App, 'advanceReadiness');
},
teardown: function(){
cleanup();
}
});
test("currentRouteName for '/'", function(){
expect(3);
App.testHelpers.visit('/').then(function(){
equal(App.testHelpers.currentRouteName(), 'index', "should equal 'index'.");
equal(App.testHelpers.currentPath(), 'index', "should equal 'index'.");
equal(App.testHelpers.currentURL(), '/', "should equal '/'.");
});
});
test("currentRouteName for '/posts'", function(){
expect(3);
App.testHelpers.visit('/posts').then(function(){
equal(App.testHelpers.currentRouteName(), 'posts.index', "should equal 'posts.index'.");
equal(App.testHelpers.currentPath(), 'posts.index', "should equal 'posts.index'.");
equal(App.testHelpers.currentURL(), '/posts', "should equal '/posts'.");
});
});
test("currentRouteName for '/posts/new'", function(){
expect(3);
App.testHelpers.visit('/posts/new').then(function(){
equal(App.testHelpers.currentRouteName(), 'posts.new', "should equal 'posts.new'.");
equal(App.testHelpers.currentPath(), 'posts.new', "should equal 'posts.new'.");
equal(App.testHelpers.currentURL(), '/posts/new', "should equal '/posts/new'.");
});
});
QUnit.module("ember-testing pendingAjaxRequests", {
setup: function(){
cleanup();
run(function() {
App = EmberApplication.create();
App.setupForTesting();
});
App.injectTestHelpers();
},
teardown: function() { cleanup(); }
});
test("pendingAjaxRequests is maintained for ajaxSend and ajaxComplete events", function() {
equal(Test.pendingAjaxRequests, 0);
var xhr = {some: 'xhr'};
jQuery(document).trigger('ajaxSend', xhr);
equal(Test.pendingAjaxRequests, 1, 'Ember.Test.pendingAjaxRequests was incremented');
jQuery(document).trigger('ajaxComplete', xhr);
equal(Test.pendingAjaxRequests, 0, 'Ember.Test.pendingAjaxRequests was decremented');
});
test("pendingAjaxRequests is ignores ajaxComplete events from past setupForTesting calls", function() {
equal(Test.pendingAjaxRequests, 0);
var xhr = {some: 'xhr'};
jQuery(document).trigger('ajaxSend', xhr);
equal(Test.pendingAjaxRequests, 1, 'Ember.Test.pendingAjaxRequests was incremented');
Ember.run(function(){
setupForTesting();
});
equal(Test.pendingAjaxRequests, 0, 'Ember.Test.pendingAjaxRequests was reset');
var altXhr = {some: 'more xhr'};
jQuery(document).trigger('ajaxSend', altXhr);
equal(Test.pendingAjaxRequests, 1, 'Ember.Test.pendingAjaxRequests was incremented');
jQuery(document).trigger('ajaxComplete', xhr);
equal(Test.pendingAjaxRequests, 1, 'Ember.Test.pendingAjaxRequests is not impressed with your unexpected complete');
});
test("pendingAjaxRequests is reset by setupForTesting", function() {
Test.pendingAjaxRequests = 1;
Ember.run(function(){
setupForTesting();
});
equal(Test.pendingAjaxRequests, 0, 'pendingAjaxRequests is reset');
});
test("`triggerEvent accepts an optional options hash and context", function(){
expect(3);
var triggerEvent, wait, event;
run(function() {
App = EmberApplication.create();
App.setupForTesting();
});
App.IndexView = EmberView.extend({
template: compile('{{input type="text" id="outside-scope" class="input"}}<div id="limited">{{input type="text" id="inside-scope" class="input"}}</div>'),
didInsertElement: function() {
this.$('.input').on('blur change', function(e) {
event = e;
});
}
});
App.injectTestHelpers();
run(App, App.advanceReadiness);
triggerEvent = App.testHelpers.triggerEvent;
wait = App.testHelpers.wait;
wait().then(function() {
return triggerEvent('.input', '#limited', 'blur', { keyCode: 13 });
}).then(function() {
equal(event.keyCode, 13, 'options were passed');
equal(event.type, 'blur', 'correct event was triggered');
equal(event.target.getAttribute('id'), 'inside-scope', 'triggered on the correct element');
});
});
test("`triggerEvent accepts an optional options hash without context", function(){
expect(3);
var triggerEvent, wait, event;
run(function() {
App = EmberApplication.create();
App.setupForTesting();
});
App.IndexView = EmberView.extend({
template: compile('{{input type="text" id="scope" class="input"}}'),
didInsertElement: function() {
this.$('.input').on('blur change', function(e) {
event = e;
});
}
});
App.injectTestHelpers();
run(App, App.advanceReadiness);
triggerEvent = App.testHelpers.triggerEvent;
wait = App.testHelpers.wait;
wait().then(function() {
return triggerEvent('.input', 'blur', { keyCode: 13 });
}).then(function() {
equal(event.keyCode, 13, 'options were passed');
equal(event.type, 'blur', 'correct event was triggered');
equal(event.target.getAttribute('id'), 'scope', 'triggered on the correct element');
});
});
test("`triggerEvent can limit searching for a selector to a scope", function(){
expect(2);
var triggerEvent, wait, event;
run(function() {
App = EmberApplication.create();
App.setupForTesting();
});
App.IndexView = EmberView.extend({
template: compile('{{input type="text" id="outside-scope" class="input"}}<div id="limited">{{input type="text" id="inside-scope" class="input"}}</div>'),
didInsertElement: function() {
this.$('.input').on('blur change', function(e) {
event = e;
});
}
});
App.injectTestHelpers();
run(App, App.advanceReadiness);
triggerEvent = App.testHelpers.triggerEvent;
wait = App.testHelpers.wait;
wait().then(function() {
return triggerEvent('.input', '#limited', 'blur');
}).then(function() {
equal(event.type, 'blur', 'correct event was triggered');
equal(event.target.getAttribute('id'), 'inside-scope', 'triggered on the correct element');
});
});
test("`triggerEvent` can be used to trigger arbitrary events", function() {
expect(2);
var triggerEvent, wait, event;
run(function() {
App = EmberApplication.create();
App.setupForTesting();
});
App.IndexView = EmberView.extend({
template: compile('{{input type="text" id="foo"}}'),
didInsertElement: function() {
this.$('#foo').on('blur change', function(e) {
event = e;
});
}
});
App.injectTestHelpers();
run(App, App.advanceReadiness);
triggerEvent = App.testHelpers.triggerEvent;
wait = App.testHelpers.wait;
wait().then(function() {
return triggerEvent('#foo', 'blur');
}).then(function() {
equal(event.type, 'blur', 'correct event was triggered');
equal(event.target.getAttribute('id'), 'foo', 'triggered on the correct element');
});
});
test("`fillIn` takes context into consideration", function() {
expect(2);
var fillIn, find, visit, andThen;
run(function() {
App = EmberApplication.create();
App.setupForTesting();
});
App.IndexView = EmberView.extend({
template: compile('<div id="parent">{{input type="text" id="first" class="current"}}</div>{{input type="text" id="second" class="current"}}')
});
App.injectTestHelpers();
run(App, App.advanceReadiness);
fillIn = App.testHelpers.fillIn;
find = App.testHelpers.find;
visit = App.testHelpers.visit;
andThen = App.testHelpers.andThen;
visit('/');
fillIn('.current', '#parent', 'current value');
andThen(function() {
equal(find('#first').val(), 'current value');
equal(find('#second').val(), '');
});
});
QUnit.module("ember-testing async router", {
setup: function(){
cleanup();
run(function() {
App = EmberApplication.create();
App.Router = EmberRouter.extend({
location: 'none'
});
App.Router.map(function() {
this.resource("user", function() {
this.route("profile");
this.route("edit");
});
});
App.UserRoute = EmberRoute.extend({
model: function() {
return resolveLater();
}
});
App.UserProfileRoute = EmberRoute.extend({
beforeModel: function() {
var self = this;
return resolveLater().then(function() {
self.transitionTo('user.edit');
});
}
});
// Emulates a long-running unscheduled async operation.
function resolveLater() {
var promise;
run(function() {
promise = new RSVP.Promise(function(resolve) {
// The wait() helper has a 10ms tick. We should resolve() after at least one tick
// to test whether wait() held off while the async router was still loading. 20ms
// should be enough.
setTimeout(function() {
run(function() {
resolve(EmberObject.create({firstName: 'Tom'}));
});
}, 20);
});
});
return promise;
}
App.setupForTesting();
});
App.injectTestHelpers();
run(App, 'advanceReadiness');
},
teardown: function(){
cleanup();
}
});
test("currentRouteName for '/user'", function(){
expect(4);
App.testHelpers.visit('/user').then(function(){
equal(currentRouteName(App), 'user.index', "should equal 'user.index'.");
equal(currentPath(App), 'user.index', "should equal 'user.index'.");
equal(currentURL(App), '/user', "should equal '/user'.");
equal(App.__container__.lookup('route:user').get('controller.model.firstName'), 'Tom', "should equal 'Tom'.");
});
});
test("currentRouteName for '/user/profile'", function(){
expect(4);
App.testHelpers.visit('/user/profile').then(function(){
equal(currentRouteName(App), 'user.edit', "should equal 'user.edit'.");
equal(currentPath(App), 'user.edit', "should equal 'user.edit'.");
equal(currentURL(App), '/user/edit', "should equal '/user/edit'.");
equal(App.__container__.lookup('route:user').get('controller.model.firstName'), 'Tom', "should equal 'Tom'.");
});
});
var originalVisitHelper, originalFindHelper, originalWaitHelper;
QUnit.module('can override built-in helpers', {
setup: function(){
originalVisitHelper = Test._helpers.visit;
originalFindHelper = Test._helpers.find;
originalWaitHelper = Test._helpers.wait;
jQuery('<style>#ember-testing-container { position: absolute; background: white; bottom: 0; right: 0; width: 640px; height: 384px; overflow: auto; z-index: 9999; border: 1px solid #ccc; } #ember-testing { zoom: 50%; }</style>').appendTo('head');
jQuery('<div id="ember-testing-container"><div id="ember-testing"></div></div>').appendTo('body');
run(function() {
App = Ember.Application.create({
rootElement: '#ember-testing'
});
App.setupForTesting();
});
},
teardown: function(){
App.removeTestHelpers();
jQuery('#ember-testing-container, #ember-testing').remove();
run(App, App.destroy);
App = null;
Test._helpers.visit = originalVisitHelper;
Test._helpers.find = originalFindHelper;
Test._helpers.wait = originalWaitHelper;
}
});
test("can override visit helper", function(){
expect(1);
Test.registerHelper('visit', function(){
ok(true, 'custom visit helper was called');
});
App.injectTestHelpers();
App.testHelpers.visit();
});
test("can override find helper", function(){
expect(1);
Test.registerHelper('find', function(){
ok(true, 'custom find helper was called');
return ['not empty array'];
});
App.injectTestHelpers();
App.testHelpers.findWithAssert('.who-cares');
});
|
var router = require('express').Router();
var Q = require('q');
var KEY = require('./key');
var User = require('../models/user.js');
var Comm = require('../comm');
var ERR = Comm.ERR;
var FailProcess = Comm.FailProcess;
/*
* get: 注册页面
* post: 提交注册
*/
router.route('/')
.get(function(req, res){
return res.render('register', {
title: 'Register',
key: KEY.REGISTER
});
})
.post(function(req, res){
var name = Comm.clearSpace(req.body.username);
var nick = Comm.clearSpace(req.body.nick);
var password = req.body.password;
var vcode = Comm.clearSpace(req.body.vcode);
var school = Comm.clearSpace(req.body.school);
var email = Comm.clearSpace(req.body.email);
var sig = Comm.clearSpace(req.body.signature);
var ret = ERR.SYS;
Q.fcall(function(){
if (!name || !nick || !Comm.isString(password) || !password || !vcode || school.length > 50 ||
email.length > 50 || sig.length > 200 || !Comm.isUsername(name)) {
ret = ERR.ARGS;
throw new Error('invalid args.');
}
if (vcode.toLowerCase() !== req.session.verifycode) {
ret = ERR.ARGS;
throw new Error('wrong verify code.');
}
return User.watch(name);
})
.then(function(user){
if (user) {
ret = ERR.ARGS;
throw new Error('the user name has already been registered.');
}
return (new User({
name: name,
password: Comm.MD5(password),
regTime: (new Date()).getTime(),
nick: nick,
school: school,
email: email,
signature: sig
})).save();
})
.then(function(user){
req.session.user = user;
req.session.msg = 'Welcome, '+name+'. :)';
res.send({ret: ERR.OK});
})
.fail(function(err){
FailProcess(err, res, ret);
})
.done();
});
module.exports = router;
|
angular.module('demoApp').config([function() {
}]);
|
/* */
var _curry1 = require('./internal/_curry1');
var curryN = require('./curryN');
module.exports = _curry1(function curry(fn) {
return curryN(fn.length, fn);
});
|
var GoogleMalwareList = require('./GoogleMalwareList');
var GooglePhishingList = require('./GooglePhishingList');
var DefaultLists = [
GoogleMalwareList,
GooglePhishingList
];
module.exports = DefaultLists;
|
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
app = angular.module('suca', ['ionic', 'ionic-material'])
.run([ '$rootScope', '$window', '$ionicPlatform', function($rootScope, $window, $ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
$rootScope.user = {};
}])
.config([ '$stateProvider','$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'views/login/login.html',
controller: 'LoginCtrl'
})
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'views/menu/menu.html',
controller: 'MenuCtrl'
})
.state('app.search', {
url: '/search',
views: {
//The menuContent works with Ionic widget
'menuContent': {
templateUrl: 'views/search/search.html',
controller: 'SearchCtrl'
}
}
})
.state('app.photo', {
url: '/photo',
views: {
'menuContent': {
templateUrl: 'views/photo/photo.html',
controller: 'PhotoCtrl'
}
}
})
.state('app.challenge', {
url: '/challenge',
views: {
'menuContent': {
templateUrl: 'views/challenge/challenge.html',
controller: 'ChallengeCtrl'
}
}
})
.state('app.restaurant', {
url: '/restaurant',
views: {
'menuContent': {
templateUrl: 'views/restaurant/restaurant.html',
controller: 'RestaurantCtrl'
}
}
})
.state('app.picture', {
url: '/picture',
views: {
'menuContent': {
templateUrl: 'views/pictures/pictures.html',
controller: 'PicturesCtrl'
}
}
})
.state('app.settings', {
url: '/settings',
views: {
'menuContent': {
templateUrl: 'views/settings/settings.html',
controller: 'SettingsCtrl'
}
}
});
/*.state('app.single', {
url: '/playlists/:playlistId',
views: {
'menuContent': {
templateUrl: 'views/playlist.html',
controller: 'PlaylistCtrl'
}
}
});*/
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/login');
}]);
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M17 6H3v8h14V6zm-7 7c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3z" opacity=".3" /><path d="M17 4H3c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zM3 14V6h14v8H3z" /><path d="M10 7c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3zm13 0v11c0 1.1-.9 2-2 2H4v-2h17V7h2z" /></React.Fragment>
, 'PaymentsTwoTone');
|
// let info = {
// user: 'X',
// comp: 'O'
// };
// const settings = (state = info, action) => {
// switch (action.type) {
// case 'SET_USER_MARKER':
// return {
// user: action.marker,
// comp: action.marker === 'X' ? 'O' : 'X'
// };
// default:
// return state;
// }
// };
// export default settings;
|
console.log (`
// ""--.._
|| (_) _ "-._
|| _ (_) '-.
|| (_) __..-'
\\__..--""
`);
|
const assert = require('assert');
const is = require('is_js');
function StringBuilder() {
const chars = [];
//appends a value to the string
function append(value) {
assert.equal(is.not.object(value), true);
value + '';
for (let i = 0; i < value.length; i++) {
chars.push(value[i]);
}
}
// removes any instance of the value from within the string
function remove(value) {
assert.equal(is.not.object(value), true);
let j = 0;
let strs = [];
for (let i = 0; i < chars.length; i++) {
if (chars[i] == value[j]) {
let str = chars.slice(i, i + value.length);
let matches = true;
for (let k = 0; k < str.length; k++) {
if (str[k] != value[j]) {
matches = false;
break;
}
j++;
}
if (matches) {
chars.splice(i, value.length);
}
i = j;
j = 0;
}
}
}
// returns the string
let toString = function toString() {
return chars.reduce((x, char) => {
return x + char;
});
}
return {
append: append,
remove: remove,
toString: toString,
};
}
module.exports = StringBuilder;
|
/* eslint-env node */
const GetterRegex = /^(?:chronology|dayOf(?:Month|Week|Year)|hashCode|hour|instant|millis|minute|month|monthValue|name|nano|lengthOf(?:Month|Year)|offset|ordinal|second|value|year)$/;
module.exports = function({ types: t }) {
const idEmber = t.identifier('Ember');
const idEmberObject = t.identifier('EmberObject');
const idGet = t.identifier('get');
const ComparableMixin = t.memberExpression(
idEmber,
t.identifier('Comparable')
);
const assert = t.memberExpression(idEmber, t.identifier('assert'));
return {
visitor: {
Program(path) {
path.unshiftContainer(
'body',
t.importDeclaration(
[
t.importDefaultSpecifier(idEmberObject),
t.importSpecifier(idGet, idGet)
],
t.stringLiteral('@ember/object')
),
t.importDeclaration(
[t.importDefaultSpecifier(idEmber)],
t.stringLiteral('ember')
)
);
},
ClassDeclaration(path) {
let didExtend = false;
if (!path.node.superClass) {
if (
![
'OffsetIdPrinterParser',
'ValueRange',
'DateTimeFormatter',
'FractionPrinterParser'
].includes(path.node.id.name) // FIXME: this is stupid
) {
// extend leaf super classes from EmberObject
path.node.superClass = idEmberObject;
didExtend = true;
}
}
for (const methodPath of path.get('body.body')) {
if (
methodPath.node.type === 'ClassMethod' &&
!methodPath.node.static
) {
if (didExtend && methodPath.node.kind === 'constructor') {
// insert missing super call
methodPath
.get('body')
.unshiftContainer('body', t.callExpression(t.super(), []));
} else if (methodPath.node.kind == 'method') {
if (methodPath.node.key.name === 'compareTo') {
// add compare method
const a = t.identifier('a');
const b = t.identifier('b');
methodPath.insertAfter(
t.classMethod(
'method',
t.identifier('compare'),
[a, b],
t.blockStatement([
t.expressionStatement(
t.callExpression(assert, [
t.stringLiteral(
'ember-joda: a must be equal to the object you are comparing on (this).'
),
t.binaryExpression('===', t.thisExpression(), a)
])
),
t.returnStatement(
t.callExpression(
t.memberExpression(
t.thisExpression(),
methodPath.node.key
),
[b]
)
)
])
)
);
// mixin Comparable mixin for comparable classes
path
.getStatementParent()
.insertAfter(
t.expressionStatement(
t.callExpression(
t.memberExpression(
path.node.id,
t.identifier('reopen')
),
[ComparableMixin]
)
)
);
} else if (methodPath.node.key.name === 'get') {
// re-wrap Ember get method
const bodyPath = methodPath.get('body');
bodyPath.replaceWith(
t.blockStatement([
t.ifStatement(
t.binaryExpression(
'===',
t.unaryExpression('typeof', methodPath.node.params[0]),
t.stringLiteral('string')
),
t.blockStatement([
t.returnStatement(
t.callExpression(idGet, [
t.thisExpression(),
methodPath.node.params[0]
])
)
]),
bodyPath.node
)
])
);
} else if (
methodPath.node.params.length === 0 &&
GetterRegex.test(methodPath.node.key.name)
) {
// turn all getter methods into real getters
methodPath.node.kind = 'get';
}
}
}
}
},
CallExpression(path) {
// turn all getter call expressions into member expressions
if (
path.node.arguments.length === 0 &&
t.isMemberExpression(path.node.callee) &&
t.isIdentifier(path.node.callee.property) &&
GetterRegex.test(path.node.callee.property.name)
) {
path.replaceWith(path.node.callee);
}
}
}
};
};
module.exports.baseDir = function() {
return __dirname;
};
|
describe("About Expects", function() {
//We shall contemplate truth by testing reality, via spec expectations.
it("should expect true", function() {
expect(true).toBeTruthy(); //This should be true
});
//To understand reality, we must compare our expectations against reality.
it("should expect equality", function () {
var expectedValue = 2;
var actualValue = 1 + 1;
expect(actualValue === expectedValue).toBeTruthy();
});
//Some ways of asserting equality are better than others.
it("should assert equality a better way", function () {
var expectedValue = 3-1;
var actualValue = 1 + 1;
// toEqual() compares using common sense equality.
expect(actualValue).toEqual(expectedValue);
});
//Sometimes you need to be really exact about what you "type".
it("should assert equality with ===", function () {
var expectedValue = "2";
var actualValue = (1 + 1).toString();
// toBe() will always use === to compare.
expect(actualValue).toBe(expectedValue);
});
//Sometimes we will ask you to fill in the values.
it("should have filled in values", function () {
expect(1 + 1).toEqual(2);
});
});
|
import React from 'react';
import {
Link
} from 'react-router';
class Navbar extends React.Component {
constructor(props) {
super(props);
this.url = location.href.split('#')[0];
this.updateContent = props.updateContent || function(){};
}
componentDidMount() {
this.initEvent();
}
componentDidUpdate(prevProps) {
}
updateMenu(){
let urlparams = location.href.split('#/');
if(!!urlparams && urlparams.length>1){
let urlparam = urlparams[1].split("?_k=")[0];
if(!!urlparam){
$(".nav .active").removeClass("active");
$(".nav .nav_"+urlparam.replace("/","_")).addClass("active");
}
}
}
initEvent(){
//var that = this;
//$('.menu_li').click(function (e) {
//e.preventDefault()
//$(".active").removeClass("active");
//$(this).tab('show')
//console.log('click:')
//that.updateContent();
//})
/*
<li className="menu_li nav_author nav_author_calligraphy"><Link to='/author/calligraphy'>美术字</Link></li>
<li className="menu_li nav_author nav_author_self-portrait"><Link to='/author/self-portrait'>自画像</Link></li>
<li className="menu_li nav_author nav_author_cloudscape"><Link to='/author/cloudscape'>云景</Link></li>
<li className="menu_li nav_author nav_author_sculpture"><Link to='/author/sculpture'>雕刻</Link></li>
*/
}
render() {
return (
<div className="nav" id='nav'>
<li className="nav_title" title="作品">作品</li>
<li className="menu_li nav_art_all active"><Link to='/art/all'>全部</Link></li>
<li className="nav_title" title="作者">作者</li>
<li className="menu_li nav_author nav_author_all"><Link to='/author/all'>全部</Link></li>
<li className="menu_li nav_author nav_author_abstract"><Link to='/author/abstract'>抽象概念</Link></li>
<li className="menu_li nav_author nav_author_cityscape"><Link to='/author/cityscape'>城市景观</Link></li>
<li className="menu_li nav_author nav_author_design"><Link to='/author/design'>结构</Link></li>
<li className="menu_li nav_author nav_author_photo"><Link to='/author/photo'>照片</Link></li>
<li className="menu_li nav_author nav_author_portrait"><Link to='/author/portrait'>人物描写</Link></li>
<li className="menu_li nav_author nav_author_miniature"><Link to='/author/miniature'>微型画</Link></li>
<li className="menu_li nav_author nav_author_illustration"><Link to='/author/illustration'>插图</Link></li>
<li className="menu_li nav_author nav_author_painting"><Link to='/author/painting'>油画</Link></li>
<li className="menu_li nav_author nav_author_landscape"><Link to='/author/landscape'>乡村风景画</Link></li>
</div>
);
}
}
export default Navbar;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.