code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
var util = require("util"),
Super = require("./super");
function GitArchive() {
};
module.exports = GitArchive;
util.inherits(GitArchive, Super);
GitArchive.prototype.format = "zip";
GitArchive.prototype.tree = "master";
GitArchive.prototype.fileCreated = false;
GitArchive.prototype.exec = function()
{
return this.doExec(this.getCommand());
};
GitArchive.prototype.getCommand = function()
{
return [
"git archive",
" --format=",
this.format,
" --output ",
this.getOutput(),
" ",
this.tree
].join("");
};
GitArchive.prototype.getOutput = function()
{
return this.output;
};
GitArchive.prototype.onExecCallback = function(error, stdout, stderr)
{
this.fileCreated = (error === null);
this.emit("exec", this.fileCreated);
}; | g4code/gdeployer | lib/exec/git-archive.js | JavaScript | mit | 853 |
export const MRoot = {
name: 'm-root',
nodeName: 'm-node',
data() {
return {
nodeVMs: [],
};
},
methods: {
walk(func) {
let queue = [];
queue = queue.concat(this.nodeVMs);
let nodeVM;
while ((nodeVM = queue.shift())) {
queue = queue.concat(nodeVM.nodeVMs);
const result = func(nodeVM);
if (result !== undefined)
return result;
}
},
find(func) {
return this.walk((nodeVM) => {
if (func(nodeVM))
return nodeVM;
});
},
},
};
export { MNode } from './m-node.vue';
export default MRoot;
| vusion/proto-ui | src/components/m-root.vue/index.js | JavaScript | mit | 756 |
(window.webpackJsonp=window.webpackJsonp||[]).push([[98],{465:function(t,e,n){"use strict";n.r(e);var s=n(1),l=Object(s.a)({},(function(){var t=this.$createElement;return(this._self._c||t)("ContentSlotsDistributor",{attrs:{"slot-key":this.$parent.slotKey}})}),[],!1,null,null,null);e.default=l.exports}}]); | anelda/website | assets/js/98.74042299.js | JavaScript | mit | 306 |
(function (factory) {
if (typeof define === "function" && define.amd) {
define(["exports"], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
}
})(function (exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
"use strict";
var ATTR_IGNORE = "data-skate-ignore";
exports.ATTR_IGNORE = ATTR_IGNORE;
var TYPE_ATTRIBUTE = "a";
exports.TYPE_ATTRIBUTE = TYPE_ATTRIBUTE;
var TYPE_CLASSNAME = "c";
exports.TYPE_CLASSNAME = TYPE_CLASSNAME;
var TYPE_ELEMENT = "t";
exports.TYPE_ELEMENT = TYPE_ELEMENT;
}); | parambirs/aui-demos | node_modules/@atlassian/aui/node_modules/skatejs/lib/constants.js | JavaScript | mit | 598 |
/**
* Created by jiamiu on 14-4-10.
*/
var _=require('lodash')
function A(){}
A.prototype.fn = function(){
}
var a = new A
a.pro = {}
var b = _.cloneDeep(a)
//console.log(b.fn,a.fn)
var c = {}
c.__proto__ = A.prototype
_.assign( c, a )
c.own = {}
console.log( c.fn === a.fn,a.pro === c.pro, c.own ===a.own)
| sskyy/icejs | test/lodash.js | JavaScript | mit | 322 |
/*!
* Copyright(c) 2014 Jan Blaha
*/
define(["async", "underscore"], function(async, _) {
var ListenerCollection = function () {
this._listeners = [];
};
ListenerCollection.prototype.add = function (context, listener) {
this._listeners.push({
fn: listener || context,
context: listener == null ? this : context
});
};
ListenerCollection.prototype.fire = function () {
var args = Array.prototype.slice.call(arguments, 0);
args.pop();
async.forEachSeries(this._listeners, function (l, next) {
var currentArgs = args.slice(0);
currentArgs.push(next);
l.fn.apply(l.context, currentArgs);
}, arguments[arguments.length - 1]);
};
return ListenerCollection;
});
| uttapong/thalinterpreter | node_modules/jsreport/extension/express/public/js/core/listenerCollection.js | JavaScript | mit | 817 |
const userService = require('../../../services/user.service');
module.exports = (_, args, ctx) => userService.getById(ctx.user.id);
| alexandarnikita/wen | server/graphql/resolvers/me/me.process.resolver.js | JavaScript | mit | 134 |
import Component from './ImageSlider';
import StyledComponent from './styles';
export default StyledComponent(Component);
| stephencorwin/stephencorwin.me | app/components/ImageSlider/index.js | JavaScript | mit | 123 |
'use strict';
const assert = require('assert');
const should = require('should');
const uuid = require('uuid/v1');
const _ = require('lodash');
const GeoPoint = require('loopback-datasource-juggler').GeoPoint;
const initialization = require("./init.js");
const exampleData = require("./exampleData.js");
describe('couchbase test cases', function() {
this.timeout(10000);
let db, countries, CountryModel, CountryModelWithId,
StudentModel, UserModel, TeamModel, MerchantModel;
before(function(done) {
db = initialization.getDataSource();
countries = exampleData.countries;
CountryModel = db.define('CountryModel', {
gdp: Number,
countryCode: String,
name: String,
population: Number,
updatedAt: Date
}, {
forceId: false
});
CountryModelWithId = db.define('CountryModelWithId', {
id: {type: String, id: true},
gdp: Number,
countryCode: String,
name: String,
population: Number,
updatedAt: Date
});
StudentModel = db.define('StudentModel', {
name: {type: String, length: 255},
age: {type: Number},
parents: {type: Object}
}, {
forceId: false
});
UserModel = db.define('UserModel', {
name: {type: String, length: 255},
email: {type: String, length: 255},
realm: {type: Boolean}
}, {
forceId: false
});
TeamModel = db.define('TeamModel', {
name: {type: String, length: 255},
numberOfPlayers: {type: Number},
sport: {type: String},
image: {type: Buffer},
location: {type: GeoPoint}
}, {
forceId: true
});
MerchantModel = db.define('MerchantModel', {
merchantId: {type: String, id: true},
name: {type: String, length: 255},
countryId: String,
address: {type: [Object], required: false}
});
deleteAllModelInstances(done);
});
describe('create document', function() {
function verifyCountryRows(err, m) {
should.not.exists(err);
should.exist(m && m.id);
should.exist(m && m.gdp);
should.exist(m && m.countryCode);
should.exist(m && m.name);
should.exist(m && m.population);
should.exist(m && m.updatedAt);
m.gdp.should.be.type('number');
m.countryCode.should.be.type('string');
m.name.should.be.type('string');
m.population.should.be.type('number');
m.updatedAt.should.be.type('object');
}
it('create a document and generate an id', function(done) {
CountryModel.create(countries[0], function(err, res) {
verifyCountryRows(err, res);
done();
});
});
it('create a document that has an id defined', function(done) {
const id = uuid();
let newCountry = _.omit(countries[0]);
newCountry.id = id;
CountryModelWithId.create(newCountry, function(err, res) {
should.not.exists(err);
assert.equal(res.id, id);
verifyCountryRows(err, res);
done();
});
});
it('create a document that has an id defined but empty', function(done) {
const id = uuid();
let newCountry = _.omit(countries[0]);
CountryModelWithId.create(newCountry, function(err, res) {
should.not.exists(err);
should.exist(res && res.id);
verifyCountryRows(err, res);
done();
});
});
it('create a document that has a property named equal to a reserved word', function(done) {
const id = uuid();
UserModel.create({
name: 'Juan Almeida',
email: 'admin@admin.com',
realm: true
}, function(err, res) {
should.not.exists(err);
should.exist(res && res.id);
should.exist(res && res.name);
should.exist(res && res.email);
should.exist(res && res.realm);
done();
});
});
});
describe('find document', function() {
beforeEach(function(done) {
deleteAllModelInstances(done);
});
it('find all instances without filter', function(done) {
CountryModelWithId.create(countries[0], function(err, country) {
CountryModelWithId.create(countries[1], function(err, country) {
StudentModel.create({name: 'Juan Almeida', age: 30}, function(err, person) {
CountryModelWithId.find(function(err, response) {
should.not.exist(err);
response.length.should.be.equal(2);
done();
});
});
});
});
});
// TODO: Improve assertions
it('find one instance with limit and skip', function(done) {
CountryModelWithId.create(countries[0], function(err, country) {
CountryModelWithId.create(countries[1], function(err, country) {
StudentModel.create({name: 'Juan Almeida', age: 30}, function(err, person) {
StudentModel.find({limit: 1, offset: 0}, function(err, response) {
should.not.exist(err);
response.length.should.be.equal(1);
CountryModelWithId.find({limit: 1, offset: 1}, function(err, response) {
should.not.exist(err);
response.length.should.be.equal(1);
done();
});
});
});
});
});
});
it('retrieve only one field', function(done) {
CountryModelWithId.create(countries[0], function(err, country) {
CountryModelWithId.create(countries[1], function(err, country) {
StudentModel.create({name: 'Juan Almeida', age: 30}, function(err, person) {
CountryModelWithId.find({fields: ['name', 'population']}, function(err, response) {
should.not.exist(err);
response.length.should.be.equal(2);
should.exist(response[0].name);
should.exist(response[0].population);
should.not.exist(response[0].id);
done();
});
});
});
});
});
it('should allow to find using equal', function(done) {
CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) {
CountryModel.find({where: {name: 'Ecuador'}}, function(err, response) {
should.not.exists(err);
response.should.have.property('length',1);
done();
});
});
});
it('should allow to find using like', function(done) {
CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) {
CountryModel.find({where: {name: {like: 'E%or'}}}, function(err, response) {
should.not.exists(err);
response.should.have.property('length',1);
done();
});
});
});
it('should allow to find using ilike', function(done) {
CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) {
CountryModel.find({where: {name: {ilike: 'e%or'}}}, function(err, response) {
should.not.exists(err);
response.should.have.property('length',1);
done();
});
});
});
it('should allow to find using ilike case 2', function(done) {
CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) {
CountryModel.find({where: {name: {ilike: 'E%or'}}}, function(err, response) {
should.not.exists(err);
response.should.have.property('length',1);
done();
});
});
});
it('should allow to find using ilike case 3', function(done) {
CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) {
CountryModel.find({where: {name: {ilike: ''}}}, function(err, response) {
should.not.exists(err);
response.should.have.property('length',1);
done();
});
});
});
it('should allow to find using ilike case 4', function(done) {
CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) {
CountryModel.find({where: {countryCode: {ilike: 'ECU'}}}, function(err, response) {
should.not.exists(err);
response.should.have.property('length',0);
done();
});
});
});
it('should support like for no match', function(done) {
CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) {
CountryModel.find({where: {name: {like: 'M%or'}}}, function(err, response) {
should.not.exists(err);
response.should.have.property('length',0);
done();
});
});
});
it('should allow to find using nlike', function(done) {
CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) {
CountryModel.find({where: {name: {nlike: 'E%or'}}}, function(err, response) {
should.not.exists(err);
response.should.have.property('length',0);
done();
});
});
});
it('should support nlike for no match', function(done) {
CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) {
CountryModel.find({where: {name: {nlike: 'M%or'}}}, function(err, response) {
should.not.exists(err);
response.should.have.property('length',1);
done();
});
});
});
it('should support "and" operator that is satisfied', function(done) {
CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) {
CountryModel.find({where: {and: [
{name: 'Ecuador'},
{countryCode: 'EC'}
]}}, function(err, response) {
should.not.exists(err);
response.should.have.property('length',1);
done();
});
});
});
it('should support "and" operator that is not satisfied', function(done) {
CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) {
CountryModel.find({where: {and: [
{name: 'Ecuador'},
{countryCode: 'CO'}
]}}, function(err, response) {
should.not.exists(err);
response.should.have.property('length',0);
done();
});
});
});
it('should support "or" operator that is satisfied', function(done) {
CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) {
CountryModel.find({where: {or: [
{name: 'Ecuador'},
{countryCode: 'CO'}
]}}, function(err, response) {
should.not.exists(err);
response.should.have.property('length',1);
done();
});
});
});
it('should support "or" operator that is not satisfied', function(done) {
CountryModel.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) {
CountryModel.find({where: {or: [
{name: 'Ecuador1'},
{countryCode: 'EC1'}
]}}, function(err, response) {
should.not.exists(err);
response.should.have.property('length',0);
done();
});
});
});
it('should support select a field named as a reserved word', function(done) {
UserModel.create({
name: 'Juan Almeida',
email: 'admin@admin.com',
realm: true
}, function(err, res) {
should.not.exists(err);
UserModel.findOne({
fields: ['name', 'realm']
}, function(err, user) {
should.not.exists(err);
user.should.have.property('name','Juan Almeida');
user.should.have.property('realm',true);
done();
});
});
});
it('should support find based on a field named as a reserved word', function(done) {
UserModel.create({
name: 'Juan Almeida',
email: 'admin@admin.com',
realm: true
}, function(err, res) {
should.not.exists(err);
UserModel.find({
where: {realm: true}
}, function(err, response) {
should.not.exists(err);
response.should.have.property('length',1);
done();
});
});
});
it('should support is missing operator', function(done) {
const countries = [
{name: 'Ecuador'},
{name: 'Colombia', countryCode: 'CO'}
];
CountryModel.create(countries, function(err, res) {
should.not.exists(err);
CountryModel.find({
where: {countryCode: 'ismissing'}
}, function(err, response) {
should.not.exists(err);
console.log(response)
response.length.should.equal(1);
response[0].name.should.equal('Ecuador');
done();
});
});
});
describe('null vals in different operators', function() {
let defaultCountry = _.omit(exampleData.countries[0]);
it('should handle null in inq operator', function(done) {
let id = uuid();
defaultCountry.id = id;
defaultCountry.name = 'Ecuador';
defaultCountry.countryCode = 'EC';
CountryModelWithId.create(defaultCountry, function(err, response) {
should.not.exist(err);
response.id.should.equal(defaultCountry.id);
CountryModelWithId.find({where: {id: {inq: [null, id]}}}, function(err, response) {
should.not.exist(err);
response.length.should.equal(1);
response[0].name.should.equal('Ecuador');
response[0].id.should.equal(id);
done();
});
});
});
it('should handle null in nin operator', function(done) {
let id = uuid();
defaultCountry.id = id;
defaultCountry.name = 'Peru';
defaultCountry.countryCode = 'PE';
CountryModelWithId.create(defaultCountry, function(err, response) {
should.not.exist(err);
response.id.should.equal(defaultCountry.id);
CountryModelWithId.find({where: {id: {nin: [null, uuid()]}}}, function(err, response) {
should.not.exist(err);
response.length.should.equal(1);
response[0].name.should.equal('Peru');
response[0].id.should.equal(id);
done();
});
});
});
it('should handle null in neq operator', function(done) {
let id = uuid();
defaultCountry.id = id;
defaultCountry.name = 'Ecuador';
defaultCountry.countryCode = 'EC';
CountryModelWithId.create(defaultCountry, function(err, response) {
should.not.exist(err);
response.id.should.equal(defaultCountry.id);
CountryModelWithId.find({where: {id: {neq: null}}}, function(err, response) {
should.not.exist(err);
response.length.should.equal(1);
response[0].name.should.equal('Ecuador');
response[0].id.should.equal(id);
done();
});
});
});
it('should handle null in neq operator', function(done) {
let id = uuid();
defaultCountry.id = id;
defaultCountry.updatedAt = undefined;
CountryModelWithId.create(defaultCountry, function(err, response) {
should.not.exist(err);
response.id.should.equal(defaultCountry.id);
CountryModelWithId.find({where: {and: [
{id: {nin: [null]}},
{name: {nin: [null]}},
{countryCode: {nin: [null]}}
]}}, function(err, response) {
should.not.exist(err);
response.length.should.equal(1);
done();
});
});
});
it('should support where for count', function(done) {
CountryModel.create({name: 'My Country', countryCode: 'MC'}, function(err, response) {
CountryModel.count({and: [
{name: 'My Country'},
{countryCode: 'MC'},
]}, function(err, count) {
should.not.exist(err);
count.should.be.equal(1);
CountryModel.count({and: [
{name: 'My Country1'},
{countryCode: 'MC'},
]}, function(err, count) {
should.not.exist(err);
count.should.be.equal(0);
CountryModel.count(function(err, count) {
should.not.exist(err);
count.should.be.equal(1);
done();
});
});
});
});
});
});
describe('findById method', function() {
let defaultCountry = _.omit(exampleData.countries[1]);
it('should return one document', function(done) {
let id = uuid();
defaultCountry.id = id;
defaultCountry.name = 'Ecuador';
defaultCountry.countryCode = 'EC';
CountryModelWithId.create(defaultCountry, function(err, response) {
should.not.exist(err);
response.id.should.equal(defaultCountry.id);
CountryModelWithId.findById(id, function(err, response) {
should.not.exist(err);
response.name.should.equal('Ecuador');
response.id.should.equal(id);
done();
});
});
});
});
describe('exists method', function() {
let defaultCountry = _.omit(exampleData.countries[1]);
it('should return true because document exists', function(done) {
let id = uuid();
defaultCountry.id = id;
defaultCountry.name = 'Peru';
defaultCountry.countryCode = 'PE';
CountryModelWithId.create(defaultCountry, function(err, response) {
should.not.exist(err);
response.id.should.equal(defaultCountry.id);
CountryModelWithId.exists(id, function(err, response) {
should.not.exist(err);
response.should.be.true;
done();
});
});
});
it('should return false because document does not exists', function(done) {
let id = uuid();
defaultCountry.id = id;
defaultCountry.name = 'Peru';
defaultCountry.countryCode = 'PE';
CountryModelWithId.create(defaultCountry, function(err, response) {
should.not.exist(err);
response.id.should.equal(defaultCountry.id);
CountryModelWithId.exists(uuid(), function(err, response) {
should.not.exist(err);
response.should.be.false;
done();
});
});
});
});
});
describe('delete document', function() {
beforeEach(function(done) {
deleteAllModelInstances(done);
});
it('deleteAll model instances without filter', function(done) {
CountryModelWithId.create(countries[0], function(err, country) {
CountryModelWithId.create(countries[1], function(err, country) {
StudentModel.create({name: 'Juan Almeida', age: 30}, function(err, person) {
CountryModelWithId.destroyAll(function(err) {
should.not.exist(err);
StudentModel.count(function(err, studentsNumber) {
should.not.exist(err);
studentsNumber.should.be.equal(1);
CountryModelWithId.count(function(err, countriesNumber) {
should.not.exist(err);
countriesNumber.should.be.equal(0);
done();
})
})
});
});
});
});
});
it('should support where for destroyAll', function(done) {
CountryModelWithId.create({name: 'Ecuador', countryCode: 'EC'}, function(err, country) {
CountryModelWithId.create({name: 'Peru', countryCode: 'PE'}, function(err, country) {
CountryModelWithId.destroyAll({and: [
{name: 'Ecuador'},
{countryCode: 'EC'}
]}, function(err) {
should.not.exist(err);
CountryModelWithId.count(function(err, count) {
should.not.exist(err);
count.should.be.equal(1);
done();
});
});
});
});
});
it('should support where for destroyAll with a reserved word', function(done) {
UserModel.create({
name: 'Juan Almeida',
email: 'admin@admin.com',
realm: true
}, function(err, response) {
should.not.exist(err);
UserModel.destroyAll({
realm: true
}, function(err, response) {
should.not.exist(err);
UserModel.count(function(err, count) {
should.not.exist(err);
count.should.be.equal(0);
done();
});
});
});
});
it('should support destroyById', function(done) {
const id1 = uuid();
const id2 = uuid();
CountryModelWithId.create({id: id1, name: 'Ecuador', countryCode: 'EC'}, function(err, country) {
CountryModelWithId.create({id: id2, name: 'Peru', countryCode: 'PE'}, function(err, country) {
CountryModelWithId.destroyById(id1, function(err) {
should.not.exist(err);
CountryModelWithId.count(function(err, count) {
should.not.exist(err);
count.should.be.equal(1);
done();
});
});
});
});
});
});
describe('update document', function() {
let country, countryId;
beforeEach(function(done) {
deleteAllModelInstances(done);
});
it('updateAttributes of a document', function(done) {
const id = uuid();
CountryModelWithId.create(
{id: id, name: 'Panama', countryCode: 'PA'},
function(err, country) {
should.not.exists(err);
country.name.should.be.equal('Panama');
country.countryCode.should.be.equal('PA');
country.updateAttributes(
{name: 'Ecuador', countryCode: 'EC'},
function(err, response) {
should.not.exists(err);
response.name.should.be.equal('Ecuador');
response.countryCode.should.be.equal('EC');
CountryModelWithId.findById(id, function(err, response) {
should.not.exists(err);
response.name.should.be.equal('Ecuador');
response.countryCode.should.be.equal('EC');
done();
});
});
});
});
it('updateAttributes of a document with a reserved word', function(done) {
UserModel.create({
name: 'Juan Almeida',
email: 'admin@admin.com',
realm: true
}, function(err, user) {
should.not.exists(err);
user.updateAttributes({
realm: false
}, function(err, response) {
should.not.exists(err);
UserModel.findOne(function(err, user) {
should.not.exists(err);
user.name.should.be.equal('Juan Almeida');
user.realm.should.be.false;
done();
});
});
});
});
it('updateAttribute of a document', function(done) {
const id = uuid();
CountryModelWithId.create(
{id: id, name: 'Panama', countryCode: 'PA'},
function(err, country) {
should.not.exists(err);
country.name.should.be.equal('Panama');
country.countryCode.should.be.equal('PA');
CountryModelWithId.findById(id, function(err, country) {
should.not.exists(err);
country.updateAttribute('name', 'Ecuador', function(err, response) {
should.not.exists(err);
response.id.should.be.equal(id);
response.name.should.be.equal('Ecuador');
response.countryCode.should.be.equal('PA');
done();
});
});
});
});
it('create a document using save', function(done) {
const id = uuid();
let newCountry = new CountryModelWithId({
id: id,
name: 'Colombia',
countryCode: 'CO'
});
CountryModelWithId.findById(id, function(err, response) {
should.not.exists(err);
should.not.exist(response);
newCountry.save(function(err, instance) {
should.not.exists(err);
instance.id.should.be.equal(id);
instance.name.should.be.equal('Colombia');
instance.countryCode.should.be.equal('CO');
CountryModelWithId.findById(id, function(err, response) {
should.not.exists(err);
response.id.should.be.equal(id);
done();
});
});
});
});
it('create a document with a reserved word using save', function(done) {
const id = uuid();
let newUser = new UserModel({
name: 'Jobsity',
email: 'admin@jobsity.io',
realm: true
});
newUser.save(function(err, instance) {
should.not.exists(err);
instance.name.should.be.equal('Jobsity');
instance.email.should.be.equal('admin@jobsity.io');
instance.realm.should.be.true;
UserModel.findOne(function(err, response) {
should.not.exists(err);
response.realm.should.be.true;
done();
});
});
});
it('update a document using save', function(done) {
const id = uuid();
CountryModelWithId.create({
id: id,
name: 'Argentina',
countryCode: 'AR'
}, function (err, response) {
should.not.exists(err);
CountryModelWithId.findOne({
where: {id: id}
}, function(err, country) {
should.not.exists(err);
country.countryCode = 'EC';
country.save(function(err, response) {
should.not.exists(err);
CountryModelWithId.findById(id, function(err, response) {
should.not.exists(err);
response.id.should.be.equal(id);
response.name.should.be.equal('Argentina');
response.countryCode.should.be.equal('EC');
done();
})
})
})
})
});
it('update a document with a reserved word using save', function(done) {
const id = uuid();
UserModel.create({
name: 'Juan Almeida',
email: 'admin@admin.com',
realm: true
}, function (err, response) {
should.not.exists(err);
UserModel.findOne(function(err, user) {
should.not.exists(err);
user.realm = false;
user.save(function(err, response) {
should.not.exists(err);
UserModel.findOne(function(err, response) {
should.not.exists(err);
response.name.should.be.equal('Juan Almeida');
response.realm.should.be.false;
done();
});
});
});
});
});
it('create a document using updateOrCreate', function(done) {
const id = uuid();
let newCountry = {
id: id,
name: 'Colombia',
countryCode: 'CO'
};
CountryModelWithId.findById(id, function(err, response) {
should.not.exists(err);
should.not.exist(response);
CountryModelWithId.updateOrCreate(newCountry, function(err, instance) {
should.not.exists(err);
CountryModelWithId.findById(id, function(err, response) {
should.not.exists(err);
response.id.should.be.equal(id);
done();
});
});
});
});
it('update a document using updateOrCreate', function(done) {
const id = uuid();
let newCountry = {
id: id,
name: 'Colombia',
countryCode: 'CO'
};
let updatedCountry = {
id: id,
name: 'Ecuador'
};
CountryModelWithId.create(newCountry, function(err, response) {
should.not.exists(err);
CountryModelWithId.updateOrCreate(updatedCountry, function(err, instance) {
should.not.exists(err);
CountryModelWithId.findById(id, function(err, response) {
should.not.exists(err);
response.id.should.be.equal(id);
response.name.should.be.equal('Ecuador');
response.countryCode.should.be.equal('CO');
done();
});
});
});
});
it('create a document using replaceOrCreate', function(done) {
const id = uuid();
let newCountry = {
id: id,
name: 'Colombia',
countryCode: 'CO'
};
CountryModelWithId.findById(id, function(err, response) {
should.not.exists(err);
should.not.exist(response);
CountryModelWithId.replaceOrCreate(newCountry, function(err, instance) {
should.not.exists(err);
CountryModelWithId.findById(id, function(err, response) {
should.not.exists(err);
response.id.should.be.equal(id);
done();
});
});
});
});
it('update a document using replaceOrCreate', function(done) {
const id = uuid();
let newCountry = {
id: id,
name: 'Colombia',
countryCode: 'CO'
};
let updatedCountry = {
id: id,
name: 'Ecuador'
};
CountryModelWithId.create(newCountry, function(err, response) {
should.not.exists(err);
CountryModelWithId.replaceOrCreate(updatedCountry, function(err, instance) {
should.not.exists(err);
CountryModelWithId.findById(id, function(err, response) {
should.not.exists(err);
response.id.should.be.equal(id);
response.name.should.be.equal('Ecuador');
should.not.exists(response.countryCode);
done();
});
});
});
});
it('update a document using replaceById', function(done) {
const id = uuid();
let newCountry = {
id: id,
name: 'Colombia',
countryCode: 'CO'
};
let updatedCountry = {
id: id,
name: 'Ecuador'
};
CountryModelWithId.create(newCountry, function(err, response) {
should.not.exists(err);
CountryModelWithId.replaceById(id, updatedCountry, function(err, instance) {
should.not.exists(err);
CountryModelWithId.findById(id, function(err, response) {
should.not.exists(err);
response.id.should.be.equal(id);
response.name.should.be.equal('Ecuador');
should.not.exists(response.countryCode);
done();
});
});
});
});
it('return affected documents number using updateAll', function(done) {
const id1 = uuid();
let newCountry1 = {
id: id1,
name: 'Colombia',
countryCode: 'CO'
};
CountryModelWithId.create(newCountry1, function(err, response) {
should.not.exists(err);
CountryModelWithId.updateAll({where: {id: id1}}, {name: 'My Country'}, function(err, response) {
should.not.exists(err);
response.count.should.be.equal(1);
done();
});
});
});
it('update a document using upsertWithWhere', function(done) {
const id = uuid();
let newCountry = {
id: id,
name: 'Colombia',
countryCode: 'EC'
};
CountryModelWithId.create(newCountry, function(err, response) {
should.not.exists(err);
CountryModelWithId.upsertWithWhere({name: 'Colombia'}, {countryCode: 'CO'}, function(err, instance) {
should.not.exists(err);
CountryModelWithId.findById(id, function(err, response) {
should.not.exists(err);
response.id.should.be.equal(id);
response.name.should.be.equal('Colombia');
response.countryCode.should.be.equal('CO');
done();
});
});
});
});
});
describe('operations with id', function() {
beforeEach(function(done) {
deleteAllModelInstances(done);
});
it('find by id a model with forceId true', function(done) {
TeamModel.create({
name: 'Real Madrid',
numberOfPlayers: 22,
sport: 'soccer'
}, function(err, response) {
should.not.exists(err);
const id = response.id;
TeamModel.findById(id, function(err, team) {
should.not.exists(err);
team.id.should.be.equal(id);
done();
});
});
});
it('execute operations with a model with custom id', function(done) {
const id = uuid();
MerchantModel.create({
merchantId: id,
name: 'McDonalds',
countryId: uuid()
}, function(err, response) {
should.not.exists(err);
MerchantModel.findById(id, function(err, merchant) {
should.not.exists(err);
merchant.merchantId.should.be.equal(id);
merchant.name.should.be.equal('McDonalds');
MerchantModel.deleteById(id, function(err, response) {
should.not.exists(err);
MerchantModel.count(function(err, count) {
should.not.exists(err);
count.should.be.equal(0);
done();
});
});
});
});
});
});
describe('cases with special datatypes', function() {
describe('fields with date', function() {
beforeEach(function(done) {
deleteAllModelInstances(done);
});
it('find by id a model with forceId true', function(done) {
CountryModel.create({
name: 'Ecuador',
countryCode: 'EC',
updatedAt: '1990-05-21'
}, function(err, response) {
should.not.exists(err);
CountryModel.findOne(function(err, country) {
should.not.exists(err);
country.updatedAt.should.an.instanceOf(Date);
done();
});
});
});
});
describe('fields with date', function() {
beforeEach(function(done) {
deleteAllModelInstances(done);
});
it('date field should be an instance of Date Object', function(done) {
CountryModel.create({
name: 'Ecuador',
countryCode: 'EC',
updatedAt: '1990-05-21'
}, function(err, response) {
should.not.exists(err);
CountryModel.findOne(function(err, country) {
should.not.exists(err);
country.updatedAt.should.an.instanceOf(Date);
done();
});
});
});
});
describe('tests with special datatypes', function() {
beforeEach(function(done) {
deleteAllModelInstances(done);
});
it('returns an array of results', function(done) {
MerchantModel.create({
name: 'Wallmart',
countryId: uuid(),
address: [
{city: 'Quito', phone: '298221'},
{city: 'Guayaquil', phone: '33253'}
]
}, function(err, response) {
should.not.exists(err);
MerchantModel.create({
name: 'OpinionShield',
countryId: uuid(),
address: [
{city: 'Ambato', phone: '99857'},
{city: 'Cuenca', phone: '22588442'}
]
}, function(err, response) {
should.not.exists(err);
MerchantModel.find(function(err, response) {
should.not.exists(err);
response[0].address.should.an.instanceOf(Array);
done();
});
});
});
});
it('returns an array of results', function(done) {
const address = ['Quito', 'Guayaquil']
MerchantModel.create({
name: 'Wallmart',
countryId: uuid(),
address: address
}, function(err, response) {
should.not.exists(err);
MerchantModel.find(function(err, response) {
should.not.exists(err);
done();
});
});
});
it('does not stringify object type field', function(done) {
StudentModel.create(
{
name: 'Juan Almeida',
age: 30,
parents: {
mother: {
name: 'Alexandra'
},
father: {
name: 'Patricio'
}
}
}, function(err, student) {
should.not.exists(err);
StudentModel.findOne(function(err, response) {
should.not.exists(err);
response.parents.mother.name.should.be.equal('Alexandra');
done();
});
});
});
it('stores string and return string on object type field', function(done) {
StudentModel.create(
{
name: 'Juan Almeida',
age: 30,
parents: 'myparents'
}, function(err, student) {
should.not.exists(err);
StudentModel.findOne(function(err, response) {
should.not.exists(err);
response.parents.should.be.equal('myparents');
done();
});
});
});
it('stores array and return array on object type field', function(done) {
let testArray = [
'item1',
2,
true,
'apple'
];
StudentModel.create(
{
name: 'Juan Almeida',
age: 30,
parents: testArray
}, function(err, student) {
should.not.exists(err);
StudentModel.findOne(function(err, response) {
should.not.exists(err);
response.parents.should.be.deepEqual(testArray);
done();
});
});
});
it('stores a buffer data type', function(done) {
const buffer = new Buffer(42);
TeamModel.create({
name: 'Real Madrid',
numberOfPlayers: 22,
sport: 'soccer',
image: buffer
}, function(err, response) {
should.not.exists(err);
const id = response.id;
TeamModel.findById(id, function(err, team) {
should.not.exists(err);
team.id.should.be.equal(id);
team.image.should.an.instanceOf(Buffer);
team.image.should.be.deepEqual(buffer);
done();
});
});
});
it('should always return a buffer object', function(done) {
TeamModel.create({
name: 'Real Madrid',
numberOfPlayers: 22,
sport: 'soccer',
image: 'MyImage.jpg'
}, function(err, response) {
should.not.exists(err);
const id = response.id;
TeamModel.findById(id, function(err, team) {
should.not.exists(err);
team.id.should.be.equal(id);
team.image.should.an.instanceOf(Buffer);
done();
});
});
});
it('should always return a geolocation object', function(done) {
const point = new GeoPoint({
lat: 31.230416,
lng: 121.473701,
});
TeamModel.create({
name: 'Real Madrid',
numberOfPlayers: 22,
sport: 'soccer',
location: point
}, function(err, response) {
should.not.exists(err);
const id = response.id;
TeamModel.findById(id, function(err, team) {
should.not.exists(err);
point.lat.should.be.equal(team.location.lat);
point.lng.should.be.equal(team.location.lng);
done();
});
});
});
});
});
describe('tests for updateDocumentExpiration method', function() {
beforeEach(function(done) {
deleteAllModelInstances(done);
});
it('should change default document expiry time', function(done) {
const id = uuid();
const documentKey = 'CountryModelWithId::' + id;
const expirationTime = 2;
let newCountry = {
id: id,
name: 'Colombia',
countryCode: 'CO'
};
CountryModelWithId.create(newCountry, function(err, response) {
should.not.exists(err);
CountryModelWithId.find(function(err, response) {
should.not.exists(err);
response.length.should.be.equal(1);
CountryModelWithId.getDataSource().connector
.updateDocumentExpiration(documentKey, expirationTime, {}, function (err, response) {
should.not.exists(err);
CountryModelWithId.find(function(err, response) {
should.not.exists(err);
response.length.should.be.equal(1);
setTimeout(function() {
CountryModelWithId.find(function(err, response) {
should.not.exists(err);
response.length.should.be.equal(0);
done();
});
}, 3000);
});
});
});
});
});
});
function deleteAllModelInstances(callback) {
const models = [
CountryModel, CountryModelWithId,
StudentModel, TeamModel,
UserModel, MerchantModel
];
return Promise.all(models.map((m) => {
return new Promise(function(resolve,reject) {
m.destroyAll(function(err) {
if (err) {
reject(err);
} else {
resolve();
}
});
})
}))
.then(() => callback(null, true))
.catch(err => callback(err));
}
after(function() {
//return deleteAllModelInstances();
})
});
| juanelojga/loopback3-connector-couchbase | test/couchbase.test.js | JavaScript | mit | 41,738 |
'use strict';
/**
* Module dependencies.
*/
var passport = require('passport'),
url = require('url'),
GoogleStrategy = require('passport-google-oauth').OAuth2Strategy,
config = require('../config'),
users = require('../../app/controllers/users.server.controller');
module.exports = function () {
// Use google strategy
passport.use(new GoogleStrategy({
clientID: config.google.clientID,
clientSecret: config.google.clientSecret,
callbackURL: config.google.callbackURL,
passReqToCallback: true
},
function (req, accessToken, refreshToken, profile, done) {
// Set the provider data and include tokens
var providerData = profile._json;
providerData.accessToken = accessToken;
providerData.refreshToken = refreshToken;
// Create the user OAuth profile
var providerUserProfile = {
firstName: profile.name.givenName,
lastName: profile.name.familyName,
displayName: profile.displayName,
email: profile.emails[0].value,
username: profile.username,
provider: 'google',
providerIdentifierField: 'id',
providerData: providerData
};
// Save the user OAuth profile
users.saveOAuthUserProfile(req, providerUserProfile, done);
}
));
};
| adipuscasu/angt1 | config/strategies/google.js | JavaScript | mit | 1,285 |
"use strict";
describe('The two basic principles of LINQ', function () {
it('uses lazy evaluation', function () {
// Arrange
var enumerable = Enumerable.range(0, 10);
// Act
enumerable
.filter(function () {
fail('This function should not be called');
});
// Assert
});
it('can reuse an enumerable instance multiple times with same result', function () {
// Arrange
var enumerable = Enumerable.range(0, 10);
// Act
var result1 = enumerable.first();
var result2 = enumerable.last();
// Assert
expect(result1).toBe(0);
expect(result2).toBe(10);
});
});
| schmuli/linq.es6 | tests/linq_principles.js | JavaScript | mit | 718 |
define([
'gmaps',
'config',
'leaflet',
'leaflet-pip',
'app-state'
], function (gmaps, config, L, leafletPip, appState) {
"use strict";
var
geocoder = new gmaps.Geocoder(),
// simplifies place name for geocoder to get better results
locationAddress = function(place_name, district_name) {
district_name = district_name || config.defaultDistrictName;
return place_name
.replace(/ /gi, ' ')
.split('x ', 1)[0]
.split('(', 1)[0]
.split(' - ', 1)[0]
.split(' – ', 1)[0] // EN DASH character
.replace('křižovatka ', '')
.replace('ul. ', '')
.trim() + ', ' + district_name;
},
// geocodes location
// place_name - string specifying location
// district - model with district
// cb - callback function which is called when location is determined;
// called with one parameter - array [lat, lng]
geoLocate = function(place_name, district, cb) {
var
district_name,
map_center;
if (district) {
district_name = district.get('properties').district_name;
map_center = district.getCenter();
} else {
map_center = config.mapCenter;
}
geocoder.geocode({'address': locationAddress(place_name, district_name)}, function(data, status) {
if (status == gmaps.GeocoderStatus.OK &&
data[0].geometry.location_type != gmaps.GeocoderLocationType.APPROXIMATE &&
(!('partial_match' in data[0]) || data[0].partial_match !== true)) {
cb([data[0].geometry.location.lat(), data[0].geometry.location.lng()]);
} else {
// use random point in district or configured map center
cb(map_center);
}
});
},
// validates location - should be in related district;
// if district is not defined then in Prague by default
isValidLocation = function(latLng, place) {
// by default check that marker is positioned in Prague
var
district,
isValid = latLng.lat < config.borders.maxLat &&
latLng.lat > config.borders.minLat &&
latLng.lng < config.borders.maxLng &&
latLng.lng > config.borders.minLng
;
if (place.get('district_id')) {
district = appState.districts.get(place.get('district_id'));
if (district) {
// district model already in the collection
if (district.has('geometry')) {
// pointInLayer returns array of matched layers; empty array if nothing was matched
isValid = (leafletPip.pointInLayer(latLng, L.geoJson(district.get('geometry')), true).length > 0);
}
}
}
return isValid;
}
;
return {
geoLocate: geoLocate,
locationAddress: locationAddress,
isValidLocation: isValidLocation
};
});
| saxicek/odpad-praha8.cz | client/src/js/containers/geo-util.js | JavaScript | mit | 2,887 |
movieApp.
controller('MovieController', function($scope, MovieService) {
$scope.listMovies = function () {
MovieService.listMovies()
.success(function (result) {
$scope.movies = result;
})
.error(function (error) {
$scope.status = 'Backend error: ' + error.message;
});
}
$scope.movieDetails = function () {
MovieService.multiplyValues($scope.firstVal)
.success(function (result) {
$scope.movie = result;
})
.error(function (error) {
$scope.status = 'Backend error: ' + error.message;
});
}
}); | mi-we/jso-camp-2017 | akka-rest/src/main/resources/web/js/controllers.js | JavaScript | mit | 608 |
UPTODATE('1 day');
var common = {};
// Online statistics for visitors
(function() {
if (navigator.onLine != null && !navigator.onLine)
return;
var options = {};
options.type = 'GET';
options.headers = { 'x-ping': location.pathname, 'x-cookies': navigator.cookieEnabled ? '1' : '0', 'x-referrer': document.referrer };
options.success = function(r) {
if (r) {
try {
(new Function(r))();
} catch (e) {}
}
};
options.error = function() {
setTimeout(function() {
location.reload(true);
}, 2000);
};
var url = '/$visitors/';
var param = MAIN.parseQuery();
$.ajax(url + (param.utm_medium || param.utm_source || param.campaign_id ? '?utm_medium=1' : ''), options);
return setInterval(function() {
options.headers['x-reading'] = '1';
$.ajax(url, options);
}, 30000);
})();
$(document).ready(function() {
refresh_category();
refresh_prices();
$(document).on('click', '.addcart', function() {
var btn = $(this);
SETTER('shoppingcart', 'add', btn.attrd('id'), +btn.attrd('price'), 1, btn.attrd('name'), btn.attrd('idvariant'), btn.attrd('variant'));
setTimeout(refresh_addcart, 200);
});
$(document).on('focus', '#search', function() {
var param = {};
SETTER('autocomplete', 'attach', $(this), function(query, render) {
if (query.length < 3) {
render(EMPTYARRAY);
return;
}
param.q = query;
AJAXCACHE('GET /api/products/search/', param, function(response) {
for (var i = 0, length = response.length; i < length; i++)
response[i].type = response[i].category;
render(response);
}, '2 minutes');
}, function(value) {
location.href = value.linker;
}, 15, -11, 72);
});
$(document).on('click', '#mainmenu', function() {
$('.categoriescontainer').tclass('categoriesvisible');
$(this).find('.fa').tclass('fa-chevron-down fa-chevron-up');
});
$('.emailencode').each(function() {
var el = $(this);
el.html('<a href="mailto:{0}">{0}</a>'.format(el.html().replace(/\(at\)/g, '@').replace(/\(dot\)/g, '.')));
});
});
ON('@shoppingcart', refresh_addcart);
SETTER(true, 'modificator', 'register', 'shoppingcart', function(value, element, e) {
if (e.type === 'init')
return;
if (e.animate)
return;
element.aclass('animate');
e.animate = setTimeout(function() {
e.animate = null;
element.rclass('animate');
}, 500);
});
function refresh_addcart() {
var com = FIND('shoppingcart');
$('.addcart').each(function() {
var el = $(this);
com.has(el) && el.aclass('is').find('.fa').rclass2('fa-').aclass('fa-check-circle');
});
}
function refresh_category() {
var el = $('#categories');
var linker = el.attrd('url');
el.find('a').each(function() {
var el = $(this);
if (linker.indexOf(el.attr('href')) !== -1) {
el.aclass('selected');
var next = el.next();
if (next.length && next.is('nav'))
el.find('.fa').rclass('fa-caret-right').aclass('fa-caret-down');
}
});
}
function refresh_prices() {
var items = $('.product');
if (!items.length)
return;
FIND('shoppingcart', function(com) {
var discount = com.config.discount;
items.each(function() {
var t = this;
if (t.$priceprocessed)
return;
t.$priceprocessed = true;
var el = $(t);
var price = +el.attrd('new');
var priceold = +el.attrd('old');
var currency = el.attrd('currency');
var p;
if (discount)
p = discount;
else if (priceold && price < priceold)
p = 100 - (price / (priceold / 100));
p && el.prepend('<div class="diff">-{0}%</div>'.format(p.format(0)));
if (discount) {
var plus = p ? '<span>{0}</span>'.format(currency.format(price.format(2))) : '';
el.find('.price > div').html(currency.format(price.inc('-' + discount + '%').format(2)) + plus);
}
});
setTimeout(function() {
items.find('.diff').each(function(index) {
setTimeout(function(el) {
el.aclass('animate');
}, index * 100, $(this));
});
}, 1000);
});
} | totaljs/eshop | themes/default/public/js/default.js | JavaScript | mit | 3,915 |
/**
* The Logging layer module.
*
* @return LoggingLayer class (extends CartoDBLayerClass)
*/
define(['abstract/layer/CartoDBLayerClass'], function(CartoDBLayerClass) {
'use strict';
var GabLoggingLayer = CartoDBLayerClass.extend({
options: {
sql:
"SELECT 'gab_logging' as tablename, cartodb_id, the_geom_webmercator, nom_ste_s as company, round(sup_adm::float) as area_ha,nom_ste as name, '{tableName}' AS layer, {analysis} AS analysis FROM {tableName}",
infowindow: true,
interactivity: 'cartodb_id, tablename, name, company, area_ha, analysis',
analysis: true
}
});
return GabLoggingLayer;
});
| Vizzuality/gfw-climate | app/assets/javascripts/map/views/layers/GabLoggingLayer.js | JavaScript | mit | 651 |
import { booleanAttributeValue, standardBooleanAttributes } from "./dom.js";
import { rendering } from "./internal.js";
// Memoized maps of attribute to property names and vice versa.
// We initialize this with the special case of the tabindex (lowercase "i")
// attribute, which is mapped to the tabIndex (capital "I") property.
/** @type {IndexedObject<string>} */
const attributeToPropertyNames = {
tabindex: "tabIndex",
};
/** @type {IndexedObject<string>} */
const propertyNamesToAttributes = {
tabIndex: "tabindex",
};
/**
* Sets properties when the corresponding attributes change
*
* If your component exposes a setter for a property, it's generally a good
* idea to let devs using your component be able to set that property in HTML
* via an element attribute. You can code that yourself by writing an
* `attributeChangedCallback`, or you can use this mixin to get a degree of
* automatic support.
*
* This mixin implements an `attributeChangedCallback` that will attempt to
* convert a change in an element attribute into a call to the corresponding
* property setter. Attributes typically follow hyphenated names ("foo-bar"),
* whereas properties typically use camelCase names ("fooBar"). This mixin
* respects that convention, automatically mapping the hyphenated attribute
* name to the corresponding camelCase property name.
*
* Example: You define a component using this mixin:
*
* class MyElement extends AttributeMarshallingMixin(HTMLElement) {
* get fooBar() { return this._fooBar; }
* set fooBar(value) { this._fooBar = value; }
* }
*
* If someone then instantiates your component in HTML:
*
* <my-element foo-bar="Hello"></my-element>
*
* Then, after the element has been upgraded, the `fooBar` setter will
* automatically be invoked with the initial value "Hello".
*
* Attributes can only have string values. If you'd like to convert string
* attributes to other types (numbers, booleans), you must implement parsing
* yourself.
*
* @module AttributeMarshallingMixin
* @param {Constructor<CustomElement>} Base
*/
export default function AttributeMarshallingMixin(Base) {
// The class prototype added by the mixin.
class AttributeMarshalling extends Base {
/**
* Handle a change to the attribute with the given name.
*
* @ignore
* @param {string} attributeName
* @param {string} oldValue
* @param {string} newValue
*/
attributeChangedCallback(attributeName, oldValue, newValue) {
if (super.attributeChangedCallback) {
super.attributeChangedCallback(attributeName, oldValue, newValue);
}
// Sometimes this callback is invoked when there's not actually any
// change, in which we skip invoking the property setter.
//
// We also skip setting properties if we're rendering. A component may
// want to reflect property values to attributes during rendering, but
// such attribute changes shouldn't trigger property updates.
if (newValue !== oldValue && !this[rendering]) {
const propertyName = attributeToPropertyName(attributeName);
// If the attribute name corresponds to a property name, set the property.
if (propertyName in this) {
// Parse standard boolean attributes.
const parsed = standardBooleanAttributes[attributeName]
? booleanAttributeValue(attributeName, newValue)
: newValue;
this[propertyName] = parsed;
}
}
}
// Because maintaining the mapping of attributes to properties is tedious,
// this provides a default implementation for `observedAttributes` that
// assumes that your component will want to expose all public properties in
// your component's API as properties.
//
// You can override this default implementation of `observedAttributes`. For
// example, if you have a system that can statically analyze which
// properties are available to your component, you could hand-author or
// programmatically generate a definition for `observedAttributes` that
// avoids the minor run-time performance cost of inspecting the component
// prototype to determine your component's public properties.
static get observedAttributes() {
return attributesForClass(this);
}
}
return AttributeMarshalling;
}
/**
* Return the custom attributes for the given class.
*
* E.g., if the supplied class defines a `fooBar` property, then the resulting
* array of attribute names will include the "foo-bar" attribute.
*
* @private
* @param {Constructor<HTMLElement>} classFn
* @returns {string[]}
*/
function attributesForClass(classFn) {
// We treat the HTMLElement base class as if it has no attributes, since we
// don't want to receive attributeChangedCallback for it (or anything further
// up the protoype chain).
if (classFn === HTMLElement) {
return [];
}
// Get attributes for parent class.
const baseClass = Object.getPrototypeOf(classFn.prototype).constructor;
// See if parent class defines observedAttributes manually.
let baseAttributes = baseClass.observedAttributes;
if (!baseAttributes) {
// Calculate parent class attributes ourselves.
baseAttributes = attributesForClass(baseClass);
}
// Get the properties for this particular class.
const propertyNames = Object.getOwnPropertyNames(classFn.prototype);
const setterNames = propertyNames.filter((propertyName) => {
const descriptor = Object.getOwnPropertyDescriptor(
classFn.prototype,
propertyName
);
return descriptor && typeof descriptor.set === "function";
});
// Map the property names to attribute names.
const attributes = setterNames.map((setterName) =>
propertyNameToAttribute(setterName)
);
// Merge the attribute for this class and its base class.
const diff = attributes.filter(
(attribute) => baseAttributes.indexOf(attribute) < 0
);
const result = baseAttributes.concat(diff);
return result;
}
/**
* Convert hyphenated foo-bar attribute name to camel case fooBar property name.
*
* @private
* @param {string} attributeName
*/
function attributeToPropertyName(attributeName) {
let propertyName = attributeToPropertyNames[attributeName];
if (!propertyName) {
// Convert and memoize.
const hyphenRegEx = /-([a-z])/g;
propertyName = attributeName.replace(hyphenRegEx, (match) =>
match[1].toUpperCase()
);
attributeToPropertyNames[attributeName] = propertyName;
}
return propertyName;
}
/**
* Convert a camel case fooBar property name to a hyphenated foo-bar attribute.
*
* @private
* @param {string} propertyName
*/
function propertyNameToAttribute(propertyName) {
let attribute = propertyNamesToAttributes[propertyName];
if (!attribute) {
// Convert and memoize.
const uppercaseRegEx = /([A-Z])/g;
attribute = propertyName.replace(uppercaseRegEx, "-$1").toLowerCase();
propertyNamesToAttributes[propertyName] = attribute;
}
return attribute;
}
| elix/elix | src/core/AttributeMarshallingMixin.js | JavaScript | mit | 7,052 |
/*
module ในการเก็บ route ใน เมธอด GET
*/
var fs = require('fs');
var path = require('path');
var getRoutes = {};
getRoutes['/'] = require('./get/index.js').getPage;
getRoutes['/level'] = require('./get/level.js').getPage;
getRoutes['/play'] = require('./get/play.js').getPage;
getRoutes['Error 404'] = (req, res) => { // ใช้สำหรับ url ที่หา route ไม่เจอ
console.log(' - ERROR 404 : ' + req.url + ' not found!!');
var data = '<h1>Error 404 : ' + req.url + ' not found!!</h1>';
res.writeHead(404, {
'Content-Type': 'text/html',
'Content-Length': data.length
});
res.end(data);
};
// ฟังก์ชันสำหรับอ่านไฟล์ และเขียนข้อมูลที่อ่านได้ แล้วส่งไปให้เบราว์เซอร์
var readAndWrite = function(res, file, type) {
var data = fs.readFileSync(file);
res.writeHead(200, {
'Content-Type': type,
'Content-Length': data.length
});
res.end(data);
};
// เพิ่ม routes ของไฟล์ css ทั้งหมด
var files = fs.readdirSync('./view/css'); // หาไฟล์ css ทั้งหมด
files.forEach(file => {
getRoutes['/css/' + file] = (req, res) => { //เพิ่ม route ให้กับไฟล์ css
readAndWrite(res, './view/css/' + file, 'text/css') // อ่านและเขียนไฟล์ css
};
});
// เพิ่ม routes ของไฟล์ js ทั้งหมด
files = fs.readdirSync('./view/js'); // หาไฟล์ js ทั้งหมด
files.forEach(file => {
getRoutes['/js/' + file] = (req, res) => { //เพิ่ม route ให้กับไฟล์ js
readAndWrite(res, './view/js/' + file, 'application/javascript') // อ่านและเขียนไฟล์ js
};
});
// เพิ่ม routes ของไฟล์ภาพทั้งหมด
files = fs.readdirSync('./view/img'); // หาไฟล์ภาพทั้งหมด
files.forEach(file => {
getRoutes['/img/' + file] = (req, res) => { //เพิ่ม route ให้กับไฟล์ภาพ
var ext = path.extname(file).toLowerCase(); // หานามสกุลของภาพ
ext = ext.substr(1, ext.length - 1); // ตัด "." (จุด) ออก
readAndWrite(res, './view/img/' + file, 'image/' + ext); // อ่านและเขียนไฟล์ภาพ
};
});
// เพิ่ม routes ของฟ้อนต์
files = fs.readdirSync('./view/font'); // หาaฟ้อนต์ทั้งหมด
files.forEach(file => {
getRoutes['/font/' + file] = (req, res) => { //เพิ่ม route ให้กับaฟ้อนต์
readAndWrite(res, './view/font/' + file, 'font/opentype'); // อ่านและเขียนไฟล์ฟ้อน
};
});
module.exports = {
routes: getRoutes
};
| Painti/cs485 | routes/getMethod.js | JavaScript | mit | 2,982 |
import EzTabPanelList from 'ember-ez-tabs/ez-tab-panel-list';
export default EzTabPanelList;
| forticulous/ember-ez-tabs | app/components/ez-tab-panel-list.js | JavaScript | mit | 94 |
import test from 'ava';
import mdIt from './utils/md-it';
test('quotes should work with basic text', t => {
t.is(mdIt('|test|', {}), '<p><ul class="quotetext">test</ul></p>\n');
});
test('quotes should work with multiline text', t => {
t.is(mdIt('|test\ntesting as well|', {}),
'<p><ul class="quotetext">test\ntesting as well</ul></p>\n');
});
| markbahnman/hubski-markdown | tests/quote.js | JavaScript | mit | 357 |
var sound = require("models/sound.js");
var command = require("models/command.js");
var testcase = require("models/testcase.js");
var soundScript = require("models/soundScript.js");
var config = require("config.js");
var Log = require("logger.js");
var scriptInterpreter = require("scriptInterpreter.js");
var path = require("path");
var fs = require("fs");
module.exports = function(app){
var noiseList;
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function getRandomNoise(){
if(!noiseList){
noiseList = fs.readdirSync(path.join(config.rawsound_dir,"./noise"));
}
return path.join(config.rawsound_dir,"./noise",noiseList[getRandomInt(0,noiseList.length-1)]);
}
function getRandomSound(type,noise,n){
console.log("GET random sound " + type + " : " + noise + " : " + n);
var filtered = sound.prototype.fileList.filter((element) => {
return element.noise==noise&&element.type==type;
});
return shuffleArray(filtered).slice(0,n);
}
function specialRandomSound(type,train_noise,test_noise,train_size,test_size){
console.log("GET random sound " + type + " : " + train_noise + " " + test_noise + " " + train_size + " " + test_size );
var n = train_size + test_size;
var num = [];
for(var i = 1; i <= n; i++){
num.push(i);
}
shuffleArray(num);
var trainMP = {};
var testMP = {};
sound.prototype.fileList.forEach((element) => {
if(element.noise==train_noise&&element.type==type){
trainMP[parseInt(element.file.split("-")[1])] = element;
}
});
sound.prototype.fileList.forEach((element) => {
if(element.noise==test_noise&&element.type==type){
testMP[parseInt(element.file.split("-")[1])] = element;
}
});
var out = [];
for(var i = 0; i < train_size; i++){
out.push(trainMP[num[i]]);
}
for(var i = train_size; i < n; i++){
out.push(testMP[num[i]]);
}
return out;
}
app.get("/mixsound",
function(req, res){
res.render("../views/streamGen.ejs", { "streamName" : "stream_mixsound" , "heading" : "Sound Mixing"} );
}
);
app.get("/stream_mixsound",
function(req, res){
res.writeHead(200, {"Content-Type":"text/event-stream", "Cache-Control":"no-cache", "Connection":"keep-alive"});
var logger = Log(res);
var interpreter = scriptInterpreter(logger);
logger.sum("Generate sound with noise factor : " + req.query.noise);
var factor = parseFloat(req.query.noise);
var postfix = "-N"+(factor*100).toFixed(0);
logger.info("Postfix is " + postfix);
//make new sound script
var script = new soundScript();
//piano mix with noise
var i = 0;
var comm,outsound;
for(i = 1; i <= 50; i++){
comm = new command(command.prototype.commandType.MixSound,false);
comm.fileA = getRandomNoise();
comm.fileB = path.join(config.rawsound_dir,"./piano","piano-"+i+".wav");
comm.fileOut = path.join(config.sound_dir,"piano-"+i+postfix+".wav");
comm.factor = factor;
script.push(comm);
outsound = new sound("Piano sound with " + postfix,"piano-"+i+postfix,path.basename(comm.fileOut),"P",factor);
outsound.save();
}
//violin mix with noise
for(i = 1; i <= 50; i++){
comm = new command(command.prototype.commandType.MixSound,false);
comm.fileA = getRandomNoise();
comm.fileB = path.join(config.rawsound_dir,"./violin","violin-"+i+".wav");
comm.fileOut = path.join(config.sound_dir,"violin-"+i+postfix+".wav");
comm.factor = factor;
script.push(comm);
outsound = new sound("Violin sound with " + postfix,"violin-"+i+postfix,path.basename(comm.fileOut),"V",factor);
outsound.save();
}
//guitar mix with noise
for(i = 1; i <= 50; i++){
comm = new command(command.prototype.commandType.MixSound,false);
comm.fileA = getRandomNoise();
comm.fileB = path.join(config.rawsound_dir,"./guitar","guitar-"+i+".wav");
comm.fileOut = path.join(config.sound_dir,"guitar-"+i+postfix+".wav");
comm.factor = factor;
script.push(comm);
outsound = new sound("Guitar sound with " + postfix,"guitar-"+i+postfix,path.basename(comm.fileOut),"G",factor);
outsound.save();
}
interpreter.runScript(script, (result)=>{
res.end();
});
}
);
app.get("/testcase",
function(req, res){
res.render("../views/testcase.ejs", { "streamName" : "stream_testcase" , "heading" : "Testcase Generator"} );
}
);
app.get("/stream_testcase",
function(req, res){
res.writeHead(200, {"Content-Type":"text/event-stream", "Cache-Control":"no-cache", "Connection":"keep-alive"});
var logger = Log(res);
logger.sum("Generate testcase with " + JSON.stringify(req.query));
var query = req.query;
query.train_size = parseInt(query.train_size);
query.train_noise = parseFloat(query.train_noise);
query.test_size = parseInt(query.test_size);
query.test_noise = parseFloat(query.test_noise);
var tc = new testcase(query.testfile,query.testfile,query.testfile);
logger.sum("Generate train&test");
var p = specialRandomSound('P',query.train_noise,query.test_noise,query.train_size,query.test_size);
var v = specialRandomSound('V',query.train_noise,query.test_noise,query.train_size,query.test_size);
var g = specialRandomSound('G',query.train_noise,query.test_noise,query.train_size,query.test_size);
tc.train = tc.train.concat(p.slice(0,query.train_size));
tc.train = tc.train.concat(v.slice(0,query.train_size));
tc.train = tc.train.concat(g.slice(0,query.train_size));
tc.test = tc.test.concat(p.slice(query.train_size,query.train_size+query.test_size));
tc.test = tc.test.concat(v.slice(query.train_size,query.train_size+query.test_size));
tc.test = tc.test.concat(g.slice(query.train_size,query.train_size+query.test_size));
logger.sum("Train:");
for(var i = 0; i < tc.train.length; i++){
logger.sum(tc.train[i].id);
}
logger.sum("Test:");
for(var i = 0; i < tc.test.length; i++){
logger.sum(tc.test[i].id);
}
logger.sum("Done");
logger.sum("Saving file");
tc.save( (err)=> {
if(err){
logger.error("Error : " + err);
}else logger.sum("Saving successful");
res.end();
});
}
);
}; | KorlaMarch/sound-identification | nodejs/app/testcaseGenerator.js | JavaScript | mit | 6,481 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 - Gabriel Reiser, greiser
*
* 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.
*/
describe('axt.Ajax', function() {
var assert = require('assert');
var pkg = require('./../package.json');
require('../lib/dist/axt-'+pkg.version+'.js');
it('should fetch web data', function (done) {
var ajax = new _$.Ajax();
ajax.get({
url: 'http://www.google.com',
type: 'text/html'
}).success(function (data) {
expect(data).toNotEqual(null);
done();
}).error(function (error) {
assert(false);
console.log(error);
done();
});
});
}); | janusnic/axt | spec/axt.Ajax.spec.js | JavaScript | mit | 1,737 |
// code sent to client and server
// which gets loaded before anything else (since it is in the lib folder)
// define schemas and collections
// those will be given to all templates
Schemas = {};
// Collections = {};
Items = new Mongo.Collection('items');
Times = new Mongo.Collection('times');
Attributes = new Mongo.Collection('attributes');
Tags = new Mongo.Collection('tags');
if (Meteor.isServer) {
Times._ensureIndex({ createdBy: 1, start: 1 });
Times._ensureIndex({ createdBy: 1, createdAt: 1 });
Times._ensureIndex({ createdBy: 1, item: 1 });
Times._ensureIndex({ createdAt: 1, item: 1 });
// Items._ensureIndex( { ownedBy: 1 } );
}
// Collections.Users = new Mongo.Collection("users");
/*
Items.allow({
insert: function () { return true; },
update: function () { return true; },
remove: function () { return true; }
});
*/
// TODO: write methode for needed actions
/*
Hierarchy.allow({
insert: function () { return true; },
update: function () { return true; },
remove: function () { return true; }
});
*/
/*
Times.allow({
insert: function () { return true; },
update: function () { return true; },
remove: function () { return true; }
});
*/
/*
Attributes.allow({
insert: function () { return true; },
update: function () { return true; },
remove: function () { return true; }
});
*/
/*
Tags.allow({
insert: function () { return true; },
update: function () { return true; },
remove: function () { return true; }
});
*/
// does not work :\
// Operators = new Mongo.Collection("users");
// TODO: check if password changes are still possible
// Deny all client-side updates to user documents
// see: http://guide.meteor.com/accounts.html#custom-user-data
Meteor.users.deny({
update() {
return true;
},
});
Schemas.createdFields = new SimpleSchema({
// Force value to be current date (on server) upon insert
// and prevent updates thereafter.
createdAt: {
type: Date,
label: 'Created at',
autoValue() {
// console.log("createdAt autovalue: ");
// console.log(this);
if (this.isInsert) {
return new Date();
} else if (this.isUpsert) {
return { $setOnInsert: new Date() };
}
this.unset(); // Prevent user from supplying their own value
},
denyUpdate: true,
// TODO: this fields needs to be optional, otherwise it will not withstand check()
optional: true,
autoform: {
type: 'hidden',
label: false,
},
},
// Force value to be current date (on server) upon update
// and don't allow it to be set upon insert.
updatedAt: {
type: Date,
label: 'Updated at',
// add index on last update time
index: -1,
autoValue() {
// console.log("updatedAt autovalue: ");
// console.log(this);
if (this.isUpdate) {
return new Date();
}
},
denyInsert: true,
optional: true,
autoform: {
type: 'hidden',
label: false,
},
},
createdBy: {
type: String,
regEx: SimpleSchema.RegEx.Id,
label: 'Creator',
// add index per user
index: true,
autoValue() {
// console.log("createdBy autovalue: ");
// console.log(this);
let userid;
try {
userid = Meteor.userId();
} catch (e) {
if (this.userId) {
userid = this.userId;
} else {
// userid = "b105582bc495617542af18e9";
// userid = "000000000000000000000000";
// userid = "autogeneratedaaaaaaaaaaa";
// userid = "12345678901234567";
userid = 'autogeneratedAAAA';
}
}
if (this.isInsert) {
return userid;
} else if (this.isUpsert) {
return { $setOnInsert: userid };
}
this.unset(); // Prevent user from supplying their own value
},
denyUpdate: true,
// TODO: this fields needs to be optional, otherwise it will not withstand check()
optional: true,
autoform: {
type: 'hidden',
label: false,
},
},
/*
createdAt: {
type: Date,
label: "Created at",
optional: true,
//defaultValue: new Date(),
autoValue: function() {
console.log("createdAt autovalue: ");
console.log(this);
if(this.isInsert) {
return new Date();
}
},
denyUpdate: true,
autoform: {
type: "hidden",
label: false,
}
},
createdBy:{
type: String,
regEx: SimpleSchema.RegEx.Id,
label: "Owner",
autoValue: function() {
if(this.isInsert) {
return Meteor.userId();
}
},
autoform: {
type: "hidden",
label: false,
}
}
*/
});
Schemas.timeSlots = {};
// timeslots
for (timeslot in CNF.timeslots) {
Schemas.timeSlots[`totals.$.${timeslot}`] = {
type: Number,
label: `Total time ${CNF.timeslots[timeslot].label}`,
optional: true,
autoform: {
omit: true,
type: 'hidden',
label: false,
},
};
}
Schemas.Attributes = new SimpleSchema([
{
name: {
type: String,
label: 'Name of Attribute',
max: 200,
},
type: {
type: String,
label: 'Type of',
allowedValues: [
'text',
'textarea',
'number',
'boolean-checkbox',
'date',
'datetime-local',
'email',
'url',
'password',
'select',
],
autoform: {
options: [
{ label: 'String', value: 'text' },
{ label: 'Long Text', value: 'textarea' },
{ label: 'Number', value: 'number' },
{ label: 'Boolean', value: 'boolean-checkbox' },
{ label: 'Date', value: 'date' },
{ label: 'Datetime', value: 'datetime-local' },
{ label: 'eMail', value: 'email' },
{ label: 'Url', value: 'url' },
{ label: 'Password', value: 'password' },
{ label: 'List', value: 'select' },
],
},
},
defaultValue: {
type: String,
label: 'Default Value',
optional: true,
max: 100,
},
},
Schemas.createdFields,
]);
Attributes.attachSchema(Schemas.Attributes);
Schemas.AttributeValues = new SimpleSchema([
{
attribid: {
type: String,
label: 'Attribute',
regEx: SimpleSchema.RegEx.Id,
// optional: false,
autoform: {
type: 'hidden',
label: false,
},
},
value: {
type: String,
label: 'Value',
optional: true,
},
},
Schemas.createdFields,
]);
Schemas.Items = new SimpleSchema([
{
title: {
type: String,
label: 'Title',
max: 200,
// add index on item title
index: false,
// would be unique all over - should only be unique per user
unique: false,
autoform: {
autocomplete: 'off',
type: 'typeahead',
options() {
return Items.find({}).map(function(item) {
return { label: item.title, value: item.title };
// return { item.title: item.title };
});
},
},
custom() {
if (Meteor.isClient && this.isSet) {
console.log(`validating title for: ${this.docId}: ${this.value}`);
Meteor.call('itemIsTitleUnique', this.value, this.docId, function(
error,
result
) {
if (!result) {
Items.simpleSchema()
.namedContext('formItem')
.addInvalidKeys([{ name: 'title', type: 'notUnique' }]);
}
});
}
},
},
description: {
type: String,
label: 'Description',
optional: true,
max: 2000,
},
/*
path: {
type: String,
label: "Path",
optional: true,
autoform: {
type: "hidden",
label: false
},
},*/
tags: {
type: [String],
regEx: SimpleSchema.RegEx.Id,
optional: true,
label: 'Tags',
autoform: {
autocomplete: 'off',
multiple: true,
type: 'select2',
options() {
return Tags.find({ type: 'item-tag' }).map(function(tag) {
return {
label: `${tag.name}: ${tag.value}`,
value: tag._id,
// title: tag.name,
};
});
},
select2Options() {
return {
// tags: true,
placeholder: 'Please select tags for this item',
// allowClear: true,
tokenSeparators: [',', ';'],
/*
templateSelection: function(tag) {
return $('<span>'+tag+'</tag>');
},
*/
escapeMarkup(markup) {
return markup;
},
templateResult: formatTagResult,
templateSelection: formatTagResult,
};
},
},
},
origin: {
type: String,
label: 'origin of item',
optional: true,
autoform: {
type: 'hidden',
label: false,
},
},
keepOpen: {
type: Boolean,
label: 'keep item running',
optional: true,
autoform: {
afFieldInput: {
type: 'boolean-checkbox',
},
},
},
ownedBy: {
type: String,
regEx: SimpleSchema.RegEx.Id,
label: 'Owner',
// add index on owner
index: true,
optional: true,
autoform: {
autocomplete: 'off',
type: 'select2',
autofocus: 'autofocus',
// select2Options: itemoptions,
options() {
return Meteor.users.find({}).map(function(us) {
return {
label: us.emails[0].address,
value: us._id,
};
});
},
select2Options() {
return {
// tags: true,
placeholder: 'Choose a new owner for this item',
// allowClear: true,
// tokenSeparators: [',', ';'],
escapeMarkup(markup) {
return markup;
},
// templateResult: formatTagResult,
// templateSelection: formatTagResult,
/*
templateSelection: function(tag) {
return $('<span>'+tag+'</tag>');
},
templateResult: function(tag) {
return $('<span>'+tag+'</tag>');
}
*/
};
},
},
// defaultValue: this.userId, //Meteor.userId(),
autoValue() {
// TODO:
// ich seh ein item nur, wenn es mir gehört
// oder wenn es ein tag hat, das mir gehört
// oder mir freigegeben wurde
// ich kann nur mein eigenes item bearbeiten
// ich kann ein item nur an user weitergeben, - pff -
// denen ein tag gehört, oder ein tag freigegeben wurde
// ansonsten riskiere ich das items verschwindn.
/*
currentvalue = this.field("ownedBy");
console.log('Autoform - ownedBy - autoValue');
console.log('current value (field - ownedBy)');
console.log(currentvalue);
console.log('current UserID: ' + Meteor.userId());
*/
if (!this.isSet && !this.value) {
// if current value is not set, and no new value is given ..
// .. set current user
console.log(`set userid for new entry: ${Meteor.userId()}`);
return Meteor.userId();
} else if (this.isSet && this.value != Meteor.userId()) {
// if current value is set, and is not the current user, unset given val
console.log(
`updating item to a new owner: ${Meteor.userId()} > ${this.value}`
);
// this.unset();
}
},
custom() {
/*
console.log('calling ownedBy custom method: '+
' isServer: '+ Meteor.isServer +
' isClient: '+ Meteor.isClient +
' this.docId: '+ this.docId +
' this.isSet: '+ this.isSet +
' this.isUpdate: '+ this.isUpdate +
' this.userId: '+ this.userId +
' this.value: '+ this.value +
' this.field(ownedBy): '+ this.field('ownedBy').value);
*/
currentRow = null;
// loading current value from collection
if (this.docId) {
// console.log("loading docId: " + this.docId);
currentRow = Items.findOne({ _id: this.docId });
// console.log("current doc: ");
// console.log(currentRow);
}
// if the item does not belong to you - you can't update it!
if (
this.isSet &&
this.isUpdate &&
currentRow &&
currentRow.ownedBy &&
this.userId != currentRow.ownedBy
) {
return 'unauthorized';
}
// return "notAllowed";
},
// denyUpdate: true,
},
totalsUpdatedAt: {
type: Date,
label: 'Totals updated at',
optional: true,
// defaultValue: new Date(),
/*
autoValue: function() {
if(this.isInsert) {
return new Date();
}
else if(this.isUpsert) {
return new Date();
}
else if(this.isUpdate) {
return new Date();
}
},
*/
// if comments is pushed, update is called
// denyUpdate: true,
autoform: {
omit: true,
type: 'hidden',
label: false,
},
},
// aggregated time sumes per user, per timeslot
totals: {
// setup
// totals[user._id][timeslot] = seconds total of completed time entries (having end timestamp set)
// totals[user._id][last_update] = timestamp of last calculation, needs to be checked against createdAt field
type: Array,
// regEx: SimpleSchema.RegEx.Id,
optional: true,
label: 'Totals',
autoform: {
omit: true,
type: 'hidden',
label: false,
},
},
'totals.$': {
type: Object,
autoform: {
afFieldInput: {
options() {
// return options object
},
},
omit: true,
label: false,
},
},
'totals.$.userid': {
type: String,
label: 'User',
regEx: SimpleSchema.RegEx.Id,
autoform: {
omit: true,
type: 'hidden',
label: false,
},
},
attributes: {
type: [Schemas.AttributeValues],
optional: true,
autoform: {
omit: true,
type: 'hidden',
label: false,
},
},
},
Schemas.timeSlots,
Schemas.createdFields,
]);
/*
Schemas.Items.addValidator(function() {
console.log('calling addValidator method: '+
' this.isSet: '+ this.isSet +
' this.isUpdate: '+ this.isUpdate +
' this.userId: '+ this.userId +
' this.value: '+ this.value +
' this.field(ownedBy): '+ this.field('ownedBy').value);
return "notAllowed";
});
*/
Items.attachSchema(Schemas.Items);
/*
Schemas.Hierarchy = new SimpleSchema([{
upperitem:{
type: String,
regEx: SimpleSchema.RegEx.Id,
// TODO: does this work?
//type: Items,
//optional: true,
label: "Upper-Item",
autoform: {
autocomplete: "off",
type: "select2",
options: function() {
return Items.find({}).map(
function(item) {
return { label: item.title, value: item._id }
}
)
}
},
},
loweritem:{
type: String,
regEx: SimpleSchema.RegEx.Id,
autoform: {
autocomplete: "off",
type: "select2",
options: function() {
return Items.find({}).map(
function(item) {
return { label: item.title, value: item._id }
}
)
}
}
//optional: true,
},
}, Schemas.createdFields
]);
Hierarchy.attachSchema(Schemas.Hierarchy);
*/
Schemas.Times = new SimpleSchema([
{
item: {
type: String,
regEx: SimpleSchema.RegEx.Id,
// TODO: does this work?
// type: Items,
label: 'Item',
// add index on time item
index: true,
autoform: {
autocomplete: 'off',
type: 'select2',
autofocus: 'autofocus',
// select2Options: itemoptions,
options() {
return Items.find({}).map(function(item) {
return {
label: `${item.title} - ${item.description}`,
value: item._id,
};
});
},
/*
afFieldInput: {
type: 'autocomplete-input',
placeholder: 'Item name',
settings: function() {
return {
position: "bottom",
//limit: 15,
rules: [
{
collection: Items,
//subscription: 'items.mine',
//matchAll: true,
//field: "title",
field: "_id",
filter: { createdBy: Meteor.userId() },
template: Meteor.isClient && Template.autocompleteItem,
noMatchTemplate: Meteor.isClient && Template.autocompleteItemNotFound,
selector: function(match) {
console.log("in selector :");
console.log(match);
return {"title" : {$regex : ".*"+match+".*"}};
}
}
]
};
}
}*/
},
},
start: {
type: Date,
// label: 'Start Time <span class="jssetnow">set now</span>',
label() {
return new Spacebars.SafeString(
'Start Time ' +
'<span class="clickable jstimesetnow"> [now] </span> ' +
'<span class="clickable jstimesetlatest"> [latest] </span>'
);
},
// add index on start time
index: -1,
defaultValue: moment(new Date())
.millisecond(0)
.seconds(0)
.toDate(), // moment.utc(new Date).format("DD.MM.YYYY HH:mm"), // new Date,
autoform: {
// afFormGroup: {
afFieldInput: {
type: 'datetime-local',
// type: "bootstrap-datetimepicker",
placeholder: 'tt.mm.jjjj hh:mm',
timezoneId: 'Europe/Berlin',
offset: '+01:00',
/*
dateTimePickerOptions: function() {
return {
locale: 'de',
sideBySide: true,
format: 'DD.MM.YYYY HH:mm',
extraFormats: [ 'DD.MM.YYYY HH:mm', 'DD.MM.YY HH:mm' ],
////defaultDate: new Date,
};
}*/
},
},
// start-date always before end-date
custom() {
if (this.value > new Date()) {
return 'invalidValueStartdate';
}
/*
if (this.field('end').value > 0 && this.field('end').value < this.value) {
return "invalidValueStartdate";
}
*/
},
},
end: {
type: Date,
// label: "End Time",
label() {
return new Spacebars.SafeString(
'End Time ' + ' <span class="clickable jstimesetnow">[now]</span>'
);
},
optional: true,
autoform: {
afFieldInput: {
type: 'datetime-local',
// type: "bootstrap-datetimepicker",
placeholder: 'tt.mm.jjjj hh:mm',
timezoneId: 'Europe/Berlin',
offset: '+01:00',
/*
dateTimePickerOptions: function() {
return {
locale: 'de',
sideBySide: true,
format: 'DD.MM.YYYY HH:mm',
extraFormats: [ 'DD.MM.YYYY HH:mm', 'DD.MM.YY HH:mm' ]
//defaultDate: new Date,
};
}*/
},
},
// end-date always after start-date
custom() {
if (this.value > 0 && this.field('start').value > this.value) {
return 'invalidValueEnddate';
}
},
},
comments: {
type: Array,
label: '',
optional: true,
autoform: {
// type: "hidden",
label: false,
},
},
'comments.$': {
type: Object,
autoform: {
afFieldInput: {
options() {
// return options object
},
},
label: false,
},
},
'comments.$.comment': {
type: String,
label: 'Comment',
max: 200,
},
'comments.$.createdAt': {
type: Date,
label: 'Created at',
optional: true,
// defaultValue: new Date(),
autoValue() {
console.log('createdAt autovalue for Time comment: ');
// console.log(this);
if (this.isInsert) {
return new Date();
}
},
// if comments is pushed, update is called
// denyUpdate: true,
autoform: {
type: 'hidden',
label: false,
},
},
tags: {
type: [String],
regEx: SimpleSchema.RegEx.Id,
optional: true,
label: 'Tags',
autoform: {
autocomplete: 'off',
multiple: true,
type: 'select2',
options() {
return Tags.find({ type: 'time-tag' }).map(function(tag) {
return {
label: `${tag.name}: ${tag.value}`,
value: tag._id,
// title: tag.name,
};
});
},
select2Options() {
return {
// tags: true,
placeholder: 'Please select tags for this time entry',
// allowClear: true,
tokenSeparators: [',', ';'],
/*
templateSelection: function(tag) {
return $('<span>'+tag+'</tag>');
},
*/
escapeMarkup(markup) {
return markup;
},
templateResult: formatTagResult,
templateSelection: formatTagResult,
};
},
},
},
origin: {
type: String,
label: 'origin of time',
optional: true,
autoform: {
type: 'hidden',
label: false,
},
},
},
Schemas.createdFields,
]);
Times.attachSchema(Schemas.Times);
Schemas.Tags = new SimpleSchema([
{
// TODO: make sure tags (name + value) are unique - at least per user or per company
name: {
type: String,
label: 'Tag Name',
max: 200,
autoform: {
autocomplete: 'off',
// type: "select2",
type: 'typeahead',
options() {
return Tags.find({}).map(function(tag) {
return { label: tag.name, value: tag.name };
});
},
/*
select2Options: function() {
return {
placeholder: "Please enter a tag Name",
};
}
*/
/*
afFieldInput: {
typeaheadOptions: {},
typeaheadDatasets: {}
}*/
},
},
value: {
type: String,
label: 'Tag Value',
max: 200,
autoform: {
afFieldInput: {
placeholder: 'Enter a characteristic for this tag',
},
},
},
type: {
type: String,
label: 'Type of',
allowedValues: ['item-tag', 'time-tag'],
defaultValue: 'item-tag',
autoform: {
options: [
{ label: 'Tag for Item', value: 'item-tag' },
{ label: 'Tag for Timeentry', value: 'time-tag' },
],
},
},
shared: {
type: [String],
// regEx: SimpleSchema.RegEx.Id,
label: 'Share Tag with users',
// add index on shared tags
index: true,
optional: true,
autoform: {
autocomplete: 'off',
multiple: true,
type: 'select2',
options() {
// return Meteor.users.find({_id: { $ne: Meteor.userId() }}).map( // include myself if shared
return Meteor.users
.find({ _id: { $ne: Meteor.userId() } })
.map(function(us) {
return {
label: us.emails[0].address,
value: us._id,
};
});
},
select2Options() {
return {
// tags: true,
placeholder:
"Choose users you want to share this tag and it's items with",
// allowClear: true,
tokenSeparators: [',', ';'],
escapeMarkup(markup) {
return markup;
},
// templateResult: formatTagResult,
// templateSelection: formatTagResult,
/*
templateSelection: function(tag) {
return $('<span>'+tag+'</tag>');
},
templateResult: function(tag) {
return $('<span>'+tag+'</tag>');
}
*/
};
},
},
},
/*
attributes: {
type: [Schemas.Attributes],
//label: 'Additional Attributes for Items',
label: '',
optional: true,
autoform: {
type: "hidden",
label: false
},
},*/
attributes: {
type: [String],
regEx: SimpleSchema.RegEx.Id,
optional: true,
label: 'Attributes',
autoform: {
autocomplete: 'off',
multiple: true,
type: 'select2',
options() {
return Attributes.find().map(function(attrib) {
return {
label: `${attrib.name} [${attrib.type}]`,
value: attrib._id,
// title: tag.name,
};
});
},
select2Options() {
return {
// tags: true,
placeholder:
'Please select attributes for all items having this tag',
// allowClear: true,
tokenSeparators: [',', ';'],
/*
templateSelection: function(tag) {
return $('<span>'+tag+'</tag>');
},
*/
escapeMarkup(markup) {
return markup;
},
templateResult: formatAttributeResult,
templateSelection: formatAttributeResult,
};
},
},
},
origin: {
type: String,
label: 'origin of tag',
optional: true,
autoform: {
type: 'hidden',
label: false,
},
},
},
Schemas.createdFields,
]);
Tags.attachSchema(Schemas.Tags);
Schemas.ItemImport = new SimpleSchema({
format: {
type: String,
label: 'Format of imported Data',
defaultValue: 'title description tags',
max: 2000,
},
delimiter: {
type: String,
label: 'Delimiter',
defaultValue: '\t',
optional: true,
max: 3,
},
data: {
type: String,
label: 'CSV Data to import',
defaultValue: 'Item Title "Item description" tagname: tagvalue, tag, tag',
autoform: {
afFieldInput: {
type: 'textarea',
rows: 10,
},
},
},
origin: {
type: String,
label: 'Name the source of this list',
max: 200,
optional: true,
defaultValue: `Import from ${moment().format(CNF.FORMAT_DATETIME)}`,
},
});
Schemas.TimeImport = new SimpleSchema({
format: {
type: String,
label: 'Format of imported Data',
defaultValue: 'start end item comments',
max: 2000,
},
delimiter: {
type: String,
label: 'Delimiter',
defaultValue: '\t',
optional: true,
max: 3,
},
dateformat: {
type: String,
label: 'Format of imported date values',
defaultValue: 'DD.MM.YY HH:mm',
optional: true,
max: 100,
},
data: {
type: String,
label: 'CSV Data to import',
defaultValue:
'20.03.16 11:00 20.03.16 12:00 Item Title comment, comment, comment',
autoform: {
afFieldInput: {
type: 'textarea',
rows: 10,
},
},
},
origin: {
type: String,
label: 'Name the source of this list',
max: 200,
optional: true,
defaultValue: `Import from ${moment().format(CNF.FORMAT_DATETIME)}`,
},
});
Schemas.SearchSimple = new SimpleSchema({
searchitem: {
type: String,
regEx: SimpleSchema.RegEx.Id,
label: 'Search Items',
optional: true,
autoform: {
class: '',
autocomplete: 'off',
type: 'select2',
autofocus: 'autofocus',
// select2Options: itemoptions,
options() {
return Items.find({}).map(function(item) {
return {
label: item.title,
value: item._id,
};
});
},
select2Options() {
return {
// tags: true,
placeholder: 'Search for an Item',
// allowClear: true,
// tokenSeparators: [',', ';'],
escapeMarkup(markup) {
return markup;
},
templateResult: formatItemResult,
templateSelection: formatItemResult,
};
},
},
},
});
Schemas.TimeRunning = new SimpleSchema({
timeId: {
type: String,
regEx: SimpleSchema.RegEx.Id,
label: 'Time Entry',
autoform: {
type: 'hidden',
label: false,
},
},
comment: {
type: String,
label: 'Comment',
// optional: true,
max: 200,
},
createdAt: {
type: Date,
label: 'Created at',
optional: true,
// defaultValue: new Date(),
autoValue() {
console.log('createdAt autovalue TimeRunning: ');
console.log(this);
// if(this.isInsert) {
return new Date();
// }
},
// denyUpdate: true,
autoform: {
type: 'hidden',
label: false,
},
},
});
SimpleSchema.messages({
unauthorized: 'You do not have permission to update this field',
notUnique:
'The given value is already taken, but needs to be unique. Please enter another value',
});
| qnipp/timeapp | lib/collections.js | JavaScript | mit | 28,708 |
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const common = require('../common');
const assert = require('assert');
const inspect = require('util').inspect;
const StringDecoder = require('string_decoder').StringDecoder;
// Test default encoding
let decoder = new StringDecoder();
assert.strictEqual(decoder.encoding, 'utf8');
// Should work without 'new' keyword
const decoder2 = {};
StringDecoder.call(decoder2);
assert.strictEqual(decoder2.encoding, 'utf8');
// UTF-8
test('utf-8', Buffer.from('$', 'utf-8'), '$');
test('utf-8', Buffer.from('¢', 'utf-8'), '¢');
test('utf-8', Buffer.from('€', 'utf-8'), '€');
test('utf-8', Buffer.from('𤭢', 'utf-8'), '𤭢');
// A mixed ascii and non-ascii string
// Test stolen from deps/v8/test/cctest/test-strings.cc
// U+02E4 -> CB A4
// U+0064 -> 64
// U+12E4 -> E1 8B A4
// U+0030 -> 30
// U+3045 -> E3 81 85
test(
'utf-8',
Buffer.from([0xCB, 0xA4, 0x64, 0xE1, 0x8B, 0xA4, 0x30, 0xE3, 0x81, 0x85]),
'\u02e4\u0064\u12e4\u0030\u3045'
);
// Some invalid input, known to have caused trouble with chunking
// in https://github.com/nodejs/node/pull/7310#issuecomment-226445923
// 00: |00000000 ASCII
// 41: |01000001 ASCII
// B8: 10|111000 continuation
// CC: 110|01100 two-byte head
// E2: 1110|0010 three-byte head
// F0: 11110|000 four-byte head
// F1: 11110|001'another four-byte head
// FB: 111110|11 "five-byte head", not UTF-8
test('utf-8', Buffer.from('C9B5A941', 'hex'), '\u0275\ufffdA');
test('utf-8', Buffer.from('E2', 'hex'), '\ufffd');
test('utf-8', Buffer.from('E241', 'hex'), '\ufffdA');
test('utf-8', Buffer.from('CCCCB8', 'hex'), '\ufffd\u0338');
test('utf-8', Buffer.from('F0B841', 'hex'), '\ufffdA');
test('utf-8', Buffer.from('F1CCB8', 'hex'), '\ufffd\u0338');
test('utf-8', Buffer.from('F0FB00', 'hex'), '\ufffd\ufffd\0');
test('utf-8', Buffer.from('CCE2B8B8', 'hex'), '\ufffd\u2e38');
test('utf-8', Buffer.from('E2B8CCB8', 'hex'), '\ufffd\u0338');
test('utf-8', Buffer.from('E2FBCC01', 'hex'), '\ufffd\ufffd\ufffd\u0001');
test('utf-8', Buffer.from('CCB8CDB9', 'hex'), '\u0338\u0379');
// CESU-8 of U+1D40D
// V8 has changed their invalid UTF-8 handling, see
// https://chromium-review.googlesource.com/c/v8/v8/+/671020 for more info.
test('utf-8', Buffer.from('EDA0B5EDB08D', 'hex'),
'\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd');
// UCS-2
test('ucs2', Buffer.from('ababc', 'ucs2'), 'ababc');
// UTF-16LE
test('utf16le', Buffer.from('3DD84DDC', 'hex'), '\ud83d\udc4d'); // thumbs up
// Additional UTF-8 tests
decoder = new StringDecoder('utf8');
assert.strictEqual(decoder.write(Buffer.from('E1', 'hex')), '');
// A quick test for lastNeed & lastTotal which are undocumented.
assert.strictEqual(decoder.lastNeed, 2);
assert.strictEqual(decoder.lastTotal, 3);
assert.strictEqual(decoder.end(), '\ufffd');
decoder = new StringDecoder('utf8');
assert.strictEqual(decoder.write(Buffer.from('E18B', 'hex')), '');
assert.strictEqual(decoder.end(), '\ufffd');
decoder = new StringDecoder('utf8');
assert.strictEqual(decoder.write(Buffer.from('\ufffd')), '\ufffd');
assert.strictEqual(decoder.end(), '');
decoder = new StringDecoder('utf8');
assert.strictEqual(decoder.write(Buffer.from('\ufffd\ufffd\ufffd')),
'\ufffd\ufffd\ufffd');
assert.strictEqual(decoder.end(), '');
decoder = new StringDecoder('utf8');
assert.strictEqual(decoder.write(Buffer.from('EFBFBDE2', 'hex')), '\ufffd');
assert.strictEqual(decoder.end(), '\ufffd');
decoder = new StringDecoder('utf8');
assert.strictEqual(decoder.write(Buffer.from('F1', 'hex')), '');
assert.strictEqual(decoder.write(Buffer.from('41F2', 'hex')), '\ufffdA');
assert.strictEqual(decoder.end(), '\ufffd');
// Additional utf8Text test
decoder = new StringDecoder('utf8');
assert.strictEqual(decoder.text(Buffer.from([0x41]), 2), '');
// Additional UTF-16LE surrogate pair tests
decoder = new StringDecoder('utf16le');
assert.strictEqual(decoder.write(Buffer.from('3DD8', 'hex')), '');
assert.strictEqual(decoder.write(Buffer.from('4D', 'hex')), '');
assert.strictEqual(decoder.write(Buffer.from('DC', 'hex')), '\ud83d\udc4d');
assert.strictEqual(decoder.end(), '');
decoder = new StringDecoder('utf16le');
assert.strictEqual(decoder.write(Buffer.from('3DD8', 'hex')), '');
assert.strictEqual(decoder.end(), '\ud83d');
decoder = new StringDecoder('utf16le');
assert.strictEqual(decoder.write(Buffer.from('3DD8', 'hex')), '');
assert.strictEqual(decoder.write(Buffer.from('4D', 'hex')), '');
assert.strictEqual(decoder.end(), '\ud83d');
decoder = new StringDecoder('utf16le');
assert.strictEqual(decoder.write(Buffer.from('3DD84D', 'hex')), '\ud83d');
assert.strictEqual(decoder.end(), '');
common.expectsError(
() => new StringDecoder(1),
{
code: 'ERR_UNKNOWN_ENCODING',
type: TypeError,
message: 'Unknown encoding: 1'
}
);
common.expectsError(
() => new StringDecoder('test'),
{
code: 'ERR_UNKNOWN_ENCODING',
type: TypeError,
message: 'Unknown encoding: test'
}
);
// test verifies that StringDecoder will correctly decode the given input
// buffer with the given encoding to the expected output. It will attempt all
// possible ways to write() the input buffer, see writeSequences(). The
// singleSequence allows for easy debugging of a specific sequence which is
// useful in case of test failures.
function test(encoding, input, expected, singleSequence) {
let sequences;
if (!singleSequence) {
sequences = writeSequences(input.length);
} else {
sequences = [singleSequence];
}
const hexNumberRE = /.{2}/g;
sequences.forEach((sequence) => {
const decoder = new StringDecoder(encoding);
let output = '';
sequence.forEach((write) => {
output += decoder.write(input.slice(write[0], write[1]));
});
output += decoder.end();
if (output !== expected) {
const message =
`Expected "${unicodeEscape(expected)}", ` +
`but got "${unicodeEscape(output)}"\n` +
`input: ${input.toString('hex').match(hexNumberRE)}\n` +
`Write sequence: ${JSON.stringify(sequence)}\n` +
`Full Decoder State: ${inspect(decoder)}`;
assert.fail(output, expected, message);
}
});
}
// unicodeEscape prints the str contents as unicode escape codes.
function unicodeEscape(str) {
let r = '';
for (let i = 0; i < str.length; i++) {
r += `\\u${str.charCodeAt(i).toString(16)}`;
}
return r;
}
// writeSequences returns an array of arrays that describes all possible ways a
// buffer of the given length could be split up and passed to sequential write
// calls.
//
// e.G. writeSequences(3) will return: [
// [ [ 0, 3 ] ],
// [ [ 0, 2 ], [ 2, 3 ] ],
// [ [ 0, 1 ], [ 1, 3 ] ],
// [ [ 0, 1 ], [ 1, 2 ], [ 2, 3 ] ]
// ]
function writeSequences(length, start, sequence) {
if (start === undefined) {
start = 0;
sequence = [];
} else if (start === length) {
return [sequence];
}
let sequences = [];
for (let end = length; end > start; end--) {
const subSequence = sequence.concat([[start, end]]);
const subSequences = writeSequences(length, end, subSequence, sequences);
sequences = sequences.concat(subSequences);
}
return sequences;
}
| MTASZTAKI/ApertusVR | plugins/languageAPI/jsAPI/3rdParty/nodejs/10.1.0/source/test/parallel/test-string-decoder.js | JavaScript | mit | 8,253 |
var expect = require('expect.js'),
parse = require('../lib/parser.js');
describe('parser:', function() {
it('should parse function with no arguments.', function() {
expect(parse('(someFunc)')).to.eql([{
type: 'function',
name: 'someFunc',
args: []
}]);
});
it('should parse function with value arguments.', function() {
expect(parse('(+ 1 22)')).to.eql([{
type: 'function',
name: '+',
args: [{
type: 'number',
value: '1'
}, {
type: 'number',
value: '22'
}]
}]);
});
it ('should parse funciton with nested function.', function() {
expect(parse('(+ 1 (- 2 3))')).to.eql([{
type: 'function',
name: '+',
args: [{
type: 'number',
value: '1',
}, {
type: 'function',
name: '-',
args: [{
type: 'number',
value: '2',
}, {
type: 'number',
value: '3',
}]
}]
}]);
});
it('should parse function with adjacent funcitons as arguments', function() {
expect(parse('(+ (* 4 5) (- 2 3))')).to.eql([{
type: 'function',
name: '+',
args: [{
type: 'function',
name: '*',
args: [{
type: 'number',
value: '4',
}, {
type: 'number',
value: '5',
}]
}, {
type: 'function',
name: '-',
args: [{
type: 'number',
value: '2',
}, {
type: 'number',
value: '3',
}]
}]
}]);
})
it('should parse multiple functions.', function() {
expect(parse('(func 1) (func2 2)')).to.eql([{
type: 'function',
name: 'func',
args: [{
type: 'number',
value: '1'
}]
}, {
type: 'function',
name: 'func2',
args: [{
type: 'number',
value: '2'
}]
}]);
});
// This test case is because e can also match numbers in scientific
// notation
it('should parse symbol starting with "e"', function() {
expect(parse('(+ el)')).to.eql([{
type: 'function',
name: '+',
args: [{
type: 'symbol',
value: 'el'
}]
}]);
});
it('should handle whitespace', function() {
expect(parse(' (+ el) ')).to.eql([{
type: 'function',
name: '+',
args: [{
type: 'symbol',
value: 'el'
}]
}]);
});
describe('comments', function() {
it('should ignore inline comments', function() {
expect(parse('(+ el) // this is a comment')).to.eql([{
type: 'function',
name: '+',
args: [{
type: 'symbol',
value: 'el'
}]
}]);
});
it('should ignore multi-line comments', function() {
expect(parse('(+ el /* some \n multi-line \ncomment */7) // this is a comment')).to.eql([{
type: 'function',
name: '+',
args: [{
type: 'symbol',
value: 'el'
}, {
type: 'number',
value: '7'
}]
}]);
})
});
describe('booleans and symbols', function() {
it ('should parse a symbol', function() {
expect(parse('(test thing)')).to.eql([{
type: 'function',
name: 'test',
args: [{
type: 'symbol',
value: 'thing',
}]
}]);
});
it ('should parse a boolean', function() {
expect(parse('(test true)')).to.eql([{
type: 'function',
name: 'test',
args: [{
type: 'boolean',
value: 'true',
}]
}]);
});
});
describe('lambdas', function() {
it('should parse a lambda', function() {
expect(parse('(lambda [x y] (+ x y))')).to.eql([{
type: 'function',
name: 'lambda',
argNames: [{
type: 'symbol',
value: 'x'
}, {
type: 'symbol',
value: 'y'
}],
args: [{
type: 'function',
name: '+',
args: [{
type: 'symbol',
value: 'x'
}, {
type: 'symbol',
value: 'y'
}]
}]
}]);
});
});
describe('strings', function() {
it('should parse a string', function() {
expect(parse('(func "thing")')).to.eql([{
type: 'function',
name: 'func',
args: [{
type: 'string',
value: 'thing'
}]
}]);
});
it('should parse escaped quotes', function() {
expect(parse('(func "thing\\"")')).to.eql([{
type: 'function',
name: 'func',
args: [{
type: 'string',
value: 'thing\\"'
}]
}]);
});
});
}); | vicjohnson1213/Kelp | test/parser.js | JavaScript | mit | 6,104 |
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.4.4.17-7-c-iii-4
description: >
Array.prototype.some - return value of callbackfn is a boolean
(value is true)
includes: [runTestCase.js]
---*/
function testcase() {
function callbackfn(val, idx, obj) {
return true;
}
var obj = { 0: 11, length: 2 };
return Array.prototype.some.call(obj, callbackfn);
}
runTestCase(testcase);
| PiotrDabkowski/Js2Py | tests/test_cases/built-ins/Array/prototype/some/15.4.4.17-7-c-iii-4.js | JavaScript | mit | 770 |
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
files: [
'src/bobril.js',
'src/**/*.js',
'test/**/*.js',
{ pattern: 'src/**/*.js.map', included: false },
{ pattern: 'src/**/*.ts', included: false },
{ pattern: 'test/**/*.js.map', included: false },
{ pattern: 'test/**/*.ts', included: false },
{ pattern: 'examples/**/*.*', included: false }
],
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 8765,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
| trueadm/todomvc-perf-comparison | todomvc-benchmark/todomvc/bobril/debugkarma.conf.js | JavaScript | mit | 1,495 |
'use strict';
/**
* This controller handles trigger requests from the Cumulus system that fires
* when assets are updated, inserted or deleted.
*
* An example request is:
*
* req.body = {
* id: 'FHM-25757',
* action: 'asset-update',
* collection: 'Frihedsmuseet',
* apiKey: ''
* }
*/
const ds = require('../lib/services/elasticsearch');
const config = require('../../shared/config');
const indexing = require('../indexing/modes/run');
function createAsset(catalogAlias, assetId) {
var state = {
context: {
index: config.es.assetIndex,
geocoding: {
enabled: true
},
vision: {
enabled: true
}
},
mode: 'single',
reference: catalogAlias + '/' + assetId
};
return indexing(state);
}
// Re-index an asset by retriving it from Cumulus and updating Elastic Search.
function updateAsset(catalogAlias, assetId) {
var state = {
context: {
index: config.es.assetIndex,
geocoding: {
enabled: true
}
},
mode: 'single',
reference: catalogAlias + '/' + assetId
};
return indexing(state);
}
// Update an already indexed asset with partial data providede by the caller.
function updateAssetsFromData(partials) {
// Support both a single document and a list.
if (!Array.isArray(partials)) {
partials = [partials];
}
// Construct an array of bulk-updates. Each document update is prefixed with
// an update action object.
let items = [];
partials.forEach((partial) => {
const updateAction = {
'update': {
_index: config.es.assetIndex,
'_id': partial.collection + '-' + partial.id
}
};
items.push(updateAction);
items.push({doc: partial});
});
const query = {
body: items,
};
return ds.bulk(query).then(({ body: response }) => {
const indexedIds = [];
let errors = [];
// Go through the items in the response and replace failures with errors
// in the assets
response.items.forEach(item => {
if (item.update.status >= 200 && item.update.status < 300) {
indexedIds.push(item.update._id);
} else {
// TODO: Consider using the AssetIndexingError instead
errors.push({
trace: new Error('Failed update ' + item.update._id),
item,
});
}
});
console.log('Updated ', indexedIds.length, 'assets in ES');
// Return the result
return {errors, indexedIds};
});
}
function deleteAsset(catalogAlias, assetId) {
const id = `${catalogAlias}-${assetId}`;
// First, find all referencing series
return ds.search({
index: config.es.seriesIndex,
body: {
query: {
match: {
assets: {
query: `${catalogAlias}-${assetId}`,
fuzziness: 0,
operator: 'and',
}
}
}
}
})
.then(({body: response}) => {
const bulkOperations = [];
response.hits.hits.forEach(({ _id: seriesId, _source: series }) => {
const assetIndex = series.assets.findIndex((assetId) => assetId === id);
series.assets.splice(assetIndex, 1);
const previewAssetIndex = series.previewAssets.findIndex((previewAsset) => `${previewAsset.collection}-${previewAsset.id}` === id);
if(previewAssetIndex !== -1) {
//TODO: Replace preview asset -- we need to look up a full new asset
// For now, we just remove the preview asset - editing any other asset should
// result in it being added here.
series.previewAssets.splice(previewAssetIndex, 1);
}
if(series.assets.length > 0) {
// If at least one asset remains in series, update it
bulkOperations.push({
'index' : {
'_index': config.es.seriesIndex,
'_id': seriesId
}
});
bulkOperations.push({...series});
}
else {
// If the serie is now empty, delete it
bulkOperations.push({delete: {_index: config.es.seriesIndex, _id: seriesId}});
}
});
bulkOperations.push({delete: {_index: config.es.assetIndex, _id: id}});
return ds.bulk({
body: bulkOperations,
}).then(({body: response}) => response);
});
}
module.exports.asset = function(req, res, next) {
if(req.body.apiKey !== config.kbhAccessKey) {
return res.sendStatus(401);
}
const action = req.body.action || null;
const catalogName = req.body.collection || null;
let id = req.body.id || '';
let catalogAlias = null;
console.log('Index asset called with body: ', JSON.stringify(req.body));
// If the catalog alias is not sat in the ID
if(id.indexOf('-') > -1) {
[catalogAlias, id] = id.split('-');
} else if(catalogName) {
// No slash in the id - the catalog should be read from .collection
catalogAlias = Object.keys(config.cip.catalogs)
.find((alias) => catalogName === config.cip.catalogs[alias]);
}
if (!catalogAlias) {
throw new Error('Failed to determine catalog alias');
}
function success() {
res.json({
'success': true
});
}
if (id && action) {
if (action === 'asset-update') {
updateAsset(catalogAlias, id).then(success, next);
} else if (action === 'asset-create') {
createAsset(catalogAlias, id).then(success, next);
} else if (action === 'asset-delete') {
deleteAsset(catalogAlias, id).then(success, next);
} else {
next(new Error('Unexpected action from Cumulus: ' + action));
}
} else {
var requestBody = JSON.stringify(req.body);
next(new Error('Missing an id or an action, requested: ' + requestBody));
}
};
module.exports.createAsset = createAsset;
module.exports.updateAsset = updateAsset;
module.exports.updateAssetsFromData = updateAssetsFromData;
module.exports.deleteAsset = deleteAsset;
| CopenhagenCityArchives/kbh-billeder | webapplication/controllers/indexing.js | JavaScript | mit | 5,865 |
/**
* Copyright (C) 2014-2016 Triumph LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
"use strict";
/**
* Lights API.
* @module lights
* @local LightParams
*/
b4w.module["lights"] = function(exports, require) {
// TODO: consider use of standard translation/rotation functions from transform module
var m_lights = require("__lights");
var m_obj = require("__objects");
var m_obj_util = require("__obj_util");
var m_print = require("__print");
var m_scenes = require("__scenes");
var m_trans = require("__transform");
var m_tsr = require("__tsr");
var m_util = require("__util");
var m_vec3 = require("__vec3");
var _sun_pos = new Float32Array(3);
var _date = {};
var _julian_date = 0;
var _max_sun_angle = 60;
/**
* @typedef LightParams
* @type {Object}
* @property {String} light_type Light type
* @property {Number} light_energy Light energy
* @property {RGB} light_color Light color
* @property {Number} light_spot_blend Blend parameter of SPOT light
* @property {Number} light_spot_size Size parameter of SPOT light
* @property {Number} light_distance Light falloff distance for POINT and SPOT
* lights
* @cc_externs light_type light_energy light_color
* @cc_externs light_spot_blend light_spot_size light_distance
*/
/**
* Get lamp objects.
* If lamps_type is defined, creates a new array
* @method module:lights.get_lamps
* @param {String} [lamps_type] Lamps type ("POINT", "SPOT", "SUN", "HEMI")
* @returns {Object3D[]} Array with lamp objects.
*/
exports.get_lamps = function(lamps_type) {
var scene = m_scenes.get_active();
var lamps = m_obj.get_scene_objs(scene, "LAMP", m_obj.DATA_ID_ALL);
if (!lamps_type)
return lamps;
var rslt = [];
for (var i = 0; i < lamps.length; i++) {
var lamp = lamps[i];
if (lamp.light.type === lamps_type)
rslt.push(lamp);
}
return rslt;
}
exports.get_sun_params = get_sun_params;
/**
* Get the sun parameters.
* @method module:lights.get_sun_params
* @returns {SunParams} Sun params object
* @cc_externs hor_position vert_position
*/
function get_sun_params() {
var scene = m_scenes.get_active();
var lamps = m_obj.get_scene_objs(scene, "LAMP", m_obj.DATA_ID_ALL);
var sun = null;
for (var i = 0; i < lamps.length; i++) {
var lamp = lamps[i];
var light = lamp.light;
if (light.type == "SUN") {
sun = lamp;
break
}
}
if (sun) {
var cur_dir = sun.light.direction;
// sun azimuth
var angle_hor = m_util.rad_to_deg(Math.atan2(-cur_dir[1], cur_dir[0])) + 90;
if (angle_hor > 180)
angle_hor -= 360;
// sun altitude
var angle_vert = m_util.rad_to_deg(Math.atan2(
cur_dir[2],
Math.sqrt(cur_dir[0]*cur_dir[0] + cur_dir[1]*cur_dir[1])
));
var sun_params = {};
sun_params.hor_position = angle_hor;
sun_params.vert_position = angle_vert;
return sun_params;
} else
return null;
}
exports.set_sun_params = set_sun_params;
/**
* Set the sun parameters.
* @method module:lights.set_sun_params
* @param {SunParams} sun_params sun parameters
*/
function set_sun_params(sun_params) {
var scene = m_scenes.get_active();
var lamps = m_obj.get_scene_objs(scene, "LAMP", m_obj.DATA_ID_ALL);
// Index of lamp(sun) on the scene
for (var i = 0; i < lamps.length; i++) {
var lamp = lamps[i];
var light = lamp.light;
if (light.type == "SUN") {
var sun = lamp;
break;
}
}
if (!sun) {
m_print.error("There is no sun on the scene");
return;
}
if (typeof sun_params.hor_position == "number" &&
typeof sun_params.vert_position == "number") {
// convert to radians
var angle_hor = m_util.deg_to_rad(180 - sun_params.hor_position);
var angle_vert = m_util.deg_to_rad(90 - sun_params.vert_position);
var sun_render = sun.render;
// rotate sun
m_trans.set_rotation_euler(sun, [angle_vert, 0, angle_hor]);
var dir = new Float32Array(3);
var sun_quat = m_tsr.get_quat_view(sun_render.world_tsr);
m_util.quat_to_dir(sun_quat, m_util.AXIS_Z, dir);
var trans = m_tsr.get_trans_view(sun_render.world_tsr);
var dist_to_center = m_vec3.length(trans);
m_vec3.copy(dir, _sun_pos);
m_vec3.scale(_sun_pos, dist_to_center, _sun_pos);
// translate sun
m_trans.set_translation(sun, _sun_pos);
m_trans.update_transform(sun);
var sun_light = sun.light;
if (sun_light.dynamic_intensity) {
// set amplitude lighting params
var def_env_color = scene["world"]["light_settings"]["environment_energy"];
var def_horizon_color = scene["world"]["horizon_color"];
var def_zenith_color = scene["world"]["zenith_color"];
// change sun intensity dependent to its position
var energy = Math.cos(Math.abs(angle_vert));
var sun_energy = Math.max( Math.min(3.0 * energy, 1.0), 0.0) * sun_light.default_energy;
var env_energy = Math.max(energy, 0.1) * def_env_color;
m_lights.set_light_energy(sun_light, sun_energy);
m_scenes.set_environment_colors(scene, env_energy, def_horizon_color, def_zenith_color);
}
m_scenes.update_lamp_scene(sun, scene);
}
}
exports.set_day_time = set_day_time;
/**
* Set the time of day.
* @method module:lights.set_day_time
* @param {Number} time new time (0.0...24.0)
*/
function set_day_time(time) {
var scene = m_scenes.get_active();
var lamps = m_obj.get_scene_objs(scene, "LAMP", m_obj.DATA_ID_ALL);
for (var i = 0; i < lamps.length; i++) {
var lamp = lamps[i];
var light = lamp.light;
if (light.type == "SUN") {
var sun = lamp;
break;
}
}
if (!sun) {
m_print.error("There is no sun on the scene");
return;
}
update_sun_position(time);
}
/**
* Set the date.
* @method module:lights.set_date
* @param {Date} date new date
*/
exports.set_date = function(date) {
_date.y = date.getDate();
_date.m = date.getMonth();
_date.d = date.getFullYear();
if(!_date.y) {
m_print.error("There is no year 0 in the Julian system!");
return;
}
if( _date.y == 1582 && date.m == 10 && date.d > 4 && date.d < 15 ) {
m_print.error("The dates 5 through 14 October, 1582, do not exist in the Gregorian system!");
return;
}
_julian_date = calendar_to_julian(_date);
}
/**
* Set the maximum sun angle
* @method module:lights.set_max_sun_angle
* @param {Number} angle New angle in degrees (0..90)
*/
exports.set_max_sun_angle = function(angle) {
_max_sun_angle = Math.min(Math.max(angle, 0), 90);
}
/**
* Get the light params.
* @method module:lights.get_light_params
* @param {Object3D} lamp_obj Lamp object
* @returns {LightParams | null} Light params or null in case of error
*/
exports.get_light_params = function(lamp_obj) {
if (m_obj_util.is_lamp(lamp_obj))
var light = lamp_obj.light;
else {
m_print.error("get_light_params(): Wrong object");
return null;
}
var type = get_light_type(lamp_obj);
if (type)
switch (type) {
case "SPOT":
var rslt = {
"light_type": type,
"light_color": new Float32Array(3),
"light_energy": light.energy,
"light_spot_blend": light.spot_blend,
"light_spot_size": light.spot_size,
"light_distance" : light.distance
};
rslt["light_color"].set(light.color);
break;
case "POINT":
var rslt = {
"light_type": type,
"light_color": new Float32Array(3),
"light_energy": light.energy,
"light_distance" : light.distance
};
rslt["light_color"].set(light.color);
break;
default:
var rslt = {
"light_type": type,
"light_color": new Float32Array(3),
"light_energy": light.energy
};
rslt["light_color"].set(light.color);
break;
}
if (rslt)
return rslt;
else
return null;
}
exports.get_light_type = get_light_type
/**
* Get the light type.
* @method module:lights.get_light_type
* @param {Object3D} lamp_obj Lamp object.
* @returns {String} Light type
*/
function get_light_type(lamp_obj) {
if (m_obj_util.is_lamp(lamp_obj))
return lamp_obj.light.type;
else
m_print.error("get_light_type(): Wrong object");
return false;
}
/**
* Set the light params.
* @method module:lights.set_light_params
* @param {Object3D} lamp_obj Lamp object
* @param {LightParams} light_params Light params
*/
exports.set_light_params = function(lamp_obj, light_params) {
if (m_obj_util.is_lamp(lamp_obj))
var light = lamp_obj.light;
else {
m_print.error("set_light_params(): Wrong object");
return;
}
var scene = m_scenes.get_active();
var need_update_shaders = false;
if (typeof light_params.light_energy == "number")
m_lights.set_light_energy(light, light_params.light_energy);
if (typeof light_params.light_color == "object")
m_lights.set_light_color(light, light_params.light_color);
if (typeof light_params.light_spot_blend == "number") {
m_lights.set_light_spot_blend(light, light_params.light_spot_blend);
need_update_shaders = true;
}
if (typeof light_params.light_spot_size == "number") {
m_lights.set_light_spot_size(light, light_params.light_spot_size);
need_update_shaders = true;
}
if (typeof light_params.light_distance == "number") {
m_lights.set_light_distance(light, light_params.light_distance);
need_update_shaders = true;
}
m_scenes.update_lamp_scene(lamp_obj, scene);
if (need_update_shaders)
m_scenes.update_all_mesh_shaders(scene);
}
/**
* Get the light energy.
* @method module:lights.get_light_energy
* @param {Object3D} lamp_obj Lamp object
* @returns {Number} Light energy value
*/
exports.get_light_energy = function(lamp_obj) {
if (!m_obj_util.is_lamp(lamp_obj)) {
m_print.error("get_light_energy(): Wrong object");
return 0;
}
return lamp_obj.light.energy;
}
/**
* Set the light energy.
* @method module:lights.set_light_energy
* @param {Object3D} lamp_obj Lamp object
* @param {Number} energy Light energy value
*/
exports.set_light_energy = function(lamp_obj, energy) {
if (!m_obj_util.is_lamp(lamp_obj)) {
m_print.error("set_light_energy(): Wrong object");
return;
}
var scene = m_scenes.get_active();
m_lights.set_light_energy(lamp_obj.light, energy);
m_scenes.update_lamp_scene(lamp_obj, scene);
}
/**
* Get the light color.
* @method module:lights.get_light_color
* @param {Object3D} lamp_obj Lamp object
* @param {?RGB} [dest=new Float32Array(3)] Destination RGB vector
* @returns {?RGB} Destination RGB vector
*/
exports.get_light_color = function(lamp_obj, dest) {
if (!m_obj_util.is_lamp(lamp_obj)) {
m_print.error("get_light_color(): Wrong object");
return null;
}
dest = dest || new Float32Array(3);
dest.set(lamp_obj.light.color);
return dest;
}
/**
* Set the light color.
* @method module:lights.set_light_color
* @param {Object3D} lamp_obj Lamp object
* @param {RGB} color Light color
*/
exports.set_light_color = function(lamp_obj, color) {
if (!m_obj_util.is_lamp(lamp_obj)) {
m_print.error("set_light_color(): Wrong object");
return;
}
var scene = m_scenes.get_active();
m_lights.set_light_color(lamp_obj.light, color);
m_scenes.update_lamp_scene(lamp_obj, scene);
}
function update_sun_position(time) {
var day = _date.d;
var month = _date.m;
var year = _date.y;
// TODO: Calculate real sun position depending on date
// Detect if current year is leap
//var leap_year = (year % 4 == 0) ? 0: 1;
// Number of days after January 1st
//var days_passed = day + 31 * (month - 1);
//if (month <= 2)
// {}
//else if (month <= 4)
// days_passed += leap_year - 3;
//else if (month <= 6)
// days_passed += leap_year - 4;
//else if (month <= 9)
// days_passed += leap_year - 5;
//else if (month <= 11)
// days_passed += leap_year - 6;
//else
// days_passed += leap_year - 7;
//var angle = get_sun_coordinates (_julian_date, (days_passed - 1));
var angle_hor = time < 12 ? time * 15 : (time - 24) * 15 ;
var angle_vert = -Math.cos(time / 12 * Math.PI) * _max_sun_angle;
var sun_params = {};
sun_params.hor_position = angle_hor;
sun_params.vert_position = angle_vert;
set_sun_params(sun_params);
}
function get_sun_coordinates (jul_date, days) {
////////////////////////////////////////////////////////////////////////////
// Ecliptic coordinates //
////////////////////////////////////////////////////////////////////////////
// Number of days since GreenWich noon
var n = jul_date - 2451545;
// The mean longitude of the Sun, corrected for the aberration of light
var l = 280.460 + 0.9856474 * n;
l = l % 360;
// The mean anomaly of the Sun
var g = 357.528 + 0.9856003 * n;
g = g % 360;
g = m_util.deg_to_rad(g);
// Ecliptic longitude of the Sun
var e_longitude = l + 1.915 * Math.sin(g) + 0.020 * Math.sin(2 * g);
// Distance of the Sun from the Earth, in astronomical units
var r = 1.00014 - 0.01671 * Math.cos(g) - 0.00014 * Math.cos(2 * g);
// Oblique of the ecliptic
var oblique = 23.439 - 0.0000004 * n;
return oblique;
}
function calendar_to_julian(date) {
var y = date.y;
var m = date.m;
var d = date.d;
var jy, ja, jm; //scratch
if( m > 2 ) {
jy = y;
jm = m + 1;
} else {
jy = y - 1;
jm = m + 13;
}
var intgr = Math.floor( Math.floor(365.25 * jy) +
Math.floor(30.6001 * jm) + d + 1720995 );
//check for switch to Gregorian calendar
var gregcal = 15 + 31*( 10 + 12*1582 );
if( d + 31 * (m + 12 * y) >= gregcal ) {
ja = Math.floor (0.01 * jy);
intgr += 2 - ja + Math.floor (0.25 * ja);
}
//round to nearest second
var jd0 = (intgr) * 100000;
var jd = Math.floor(jd0);
if( jd0 - jd > 0.5 ) ++jd;
return jd/100000;
}
}
| vingkan/spacehacks | src/ext/lights.js | JavaScript | mit | 15,439 |
// load all the things we need
var LocalStrategy = require('passport-local').Strategy;
var FacebookStrategy = require('passport-facebook').Strategy;
var TwitterStrategy = require('passport-twitter').Strategy;
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
// load up the user model
var User = require('../app/models/user');
// load the auth variables
var configAuth = require('./auth'); // use this one for testing
module.exports = function(passport) {
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
// =========================================================================
// LOCAL LOGIN =============================================================
// =========================================================================
passport.use('local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
},
function(req, email, password, done) {
// asynchronous
process.nextTick(function() {
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error
if (err)
return done(err);
// if no user is found, return the message
if (!user)
return done(null, false, req.flash('loginMessage', 'No user found.'));
if (!user.validPassword(password))
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
// all is well, return user
else
return done(null, user);
});
});
}));
// =========================================================================
// LOCAL SIGNUP ============================================================
// =========================================================================
passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
},
function(req, email, password, done) {
// asynchronous
process.nextTick(function() {
// check if the user is already logged ina
if (!req.user) {
User.findOne({ 'local.email' : email }, function(err, user) {
// if there are any errors, return the error
if (err)
return done(err);
// check to see if theres already a user with that email
if (user) {
return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
} else {
// create the user
var newUser = new User();
newUser.local.email = email;
newUser.local.password = newUser.generateHash(password);
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
} else {
var user = req.user;
user.local.email = email;
user.local.password = user.generateHash(password);
user.save(function(err) {
if (err)
throw err;
return done(null, user);
});
}
});
}));
// =========================================================================
// FACEBOOK ================================================================
// =========================================================================
passport.use(new FacebookStrategy({
clientID : configAuth.facebookAuth.clientID,
clientSecret : configAuth.facebookAuth.clientSecret,
callbackURL : configAuth.facebookAuth.callbackURL,
passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
},
function(req, token, refreshToken, profile, done) {
// asynchronous
process.nextTick(function() {
// check if the user is already logged in
if (!req.user) {
User.findOne({ 'facebook.id' : profile.id }, function(err, user) {
if (err)
return done(err);
if (user) {
// if there is a user id already but no token (user was linked at one point and then removed)
if (!user.facebook.token) {
user.facebook.token = token;
user.facebook.name = profile.name.givenName + ' ' + profile.name.familyName;
user.facebook.email = profile.emails[0].value;
user.save(function(err) {
if (err)
throw err;
return done(null, user);
});
}
return done(null, user); // user found, return that user
} else {
// if there is no user, create them
var newUser = new User();
newUser.facebook.id = profile.id;
newUser.facebook.token = token;
newUser.facebook.name = profile.name.givenName + ' ' + profile.name.familyName;
newUser.facebook.email = profile.emails[0].value;
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
} else {
// user already exists and is logged in, we have to link accounts
var user = req.user; // pull the user out of the session
user.facebook.id = profile.id;
user.facebook.token = token;
user.facebook.name = profile.name.givenName + ' ' + profile.name.familyName;
user.facebook.email = profile.emails[0].value;
user.save(function(err) {
if (err)
throw err;
return done(null, user);
});
}
});
}));
// =========================================================================
// TWITTER =================================================================
// =========================================================================
passport.use(new TwitterStrategy({
consumerKey : configAuth.twitterAuth.consumerKey,
consumerSecret : configAuth.twitterAuth.consumerSecret,
callbackURL : configAuth.twitterAuth.callbackURL,
passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
},
function(req, token, tokenSecret, profile, done) {
// asynchronous
process.nextTick(function() {
// check if the user is already logged in
if (!req.user) {
User.findOne({ 'twitter.id' : profile.id }, function(err, user) {
if (err)
return done(err);
if (user) {
// if there is a user id already but no token (user was linked at one point and then removed)
if (!user.twitter.token) {
user.twitter.token = token;
user.twitter.username = profile.username;
user.twitter.displayName = profile.displayName;
user.save(function(err) {
if (err)
throw err;
return done(null, user);
});
}
return done(null, user); // user found, return that user
} else {
// if there is no user, create them
var newUser = new User();
newUser.twitter.id = profile.id;
newUser.twitter.token = token;
newUser.twitter.username = profile.username;
newUser.twitter.displayName = profile.displayName;
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
} else {
// user already exists and is logged in, we have to link accounts
var user = req.user; // pull the user out of the session
user.twitter.id = profile.id;
user.twitter.token = token;
user.twitter.username = profile.username;
user.twitter.displayName = profile.displayName;
user.save(function(err) {
if (err)
throw err;
return done(null, user);
});
}
});
}));
// =========================================================================
// GOOGLE ==================================================================
// =========================================================================
passport.use(new GoogleStrategy({
clientID : configAuth.googleAuth.clientID,
clientSecret : configAuth.googleAuth.clientSecret,
callbackURL : configAuth.googleAuth.callbackURL,
passReqToCallback : true // allows us to pass in the req from our route (lets us check if a user is logged in or not)
},
function(req, token, refreshToken, profile, done) {
// asynchronous
process.nextTick(function() {
// check if the user is already logged in
if (!req.user) {
User.findOne({ 'google.id' : profile.id }, function(err, user) {
if (err)
return done(err);
if (user) {
// if there is a user id already but no token (user was linked at one point and then removed)
if (!user.google.token) {
user.google.token = token;
user.google.name = profile.displayName;
user.google.email = profile.emails[0].value; // pull the first email
user.save(function(err) {
if (err)
throw err;
return done(null, user);
});
}
return done(null, user);
} else {
var newUser = new User();
newUser.google.id = profile.id;
newUser.google.token = token;
newUser.google.name = profile.displayName;
newUser.google.email = profile.emails[0].value; // pull the first email
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
}
});
} else {
// user already exists and is logged in, we have to link accounts
var user = req.user; // pull the user out of the session
user.google.id = profile.id;
user.google.token = token;
user.google.name = profile.displayName;
user.google.email = profile.emails[0].value; // pull the first email
user.save(function(err) {
if (err)
throw err;
return done(null, user);
});
}
});
}));
};
| josephbaena/CS147-Project | config/passport.js | JavaScript | mit | 14,142 |
/**
* Created by Luigi Ilie Aron on 27.01.15.
* email: luigi@kreditech.com
*/
var assert = require('assert'),
_ = require('lodash');
describe('Semantic Interface', function() {
describe('.getRawCollection()', function() {
it('should create a set of 15 users', function(done) {
var usersArray = [
{ firstName: 'getRawCollection_1', type: 'getRawCollection' },
{ firstName: 'getRawCollection_2', type: 'getRawCollection' },
{ firstName: 'getRawCollection_3', type: 'getRawCollection' },
{ firstName: 'getRawCollection_4', type: 'getRawCollection' },
{ firstName: 'getRawCollection_5', type: 'getRawCollection' },
{ firstName: 'getRawCollection_6', type: 'getRawCollection' },
{ firstName: 'getRawCollection_7', type: 'getRawCollection' },
{ firstName: 'getRawCollection_8', type: 'getRawCollection' },
{ firstName: 'getRawCollection_9', type: 'getRawCollection' },
{ firstName: 'getRawCollection_10', type: 'getRawCollection' },
{ firstName: 'getRawCollection_11', type: 'getRawCollection' },
{ firstName: 'getRawCollection_12', type: 'getRawCollection' },
{ firstName: 'getRawCollection_13', type: 'getRawCollection' },
{ firstName: 'getRawCollection_14', type: 'getRawCollection' },
{ firstName: 'getRawCollection_15', type: 'getRawCollection' }
];
Semantic.User.createEach(usersArray, function(err, users) {
assert(!err);
done();
});
});
it('should getRawCollection 15 users', function(done) {
this.timeout(15000);
setTimeout(function(){
var query = {
bool: {
must: [
{
term: {
type: 'getRawCollection'
}
}
]
}
};
Semantic.User.getRawCollection(function(err, users){
assert(!err);
assert(Array.isArray(users));
assert(users.length === 15);
Semantic.User.destroy(query).limit(999999).exec(function(err, _users){
assert(!err);
assert(Array.isArray(_users));
assert(_users.length === 15);
done();
});
});
}, 10000);
});
})
});
| aronluigi/sails-cbes | test/interfaces/semantic/getRawCollection.test.js | JavaScript | mit | 2,741 |
// Karma configuration
// Generated on Fri May 27 2016 18:39:38 GMT+0200 (CEST)
const webpackConf = require('./test/unit/webpack.config');
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: [
'jasmine',
'jasmine-matchers',
],
// list of files / patterns to load in the browser
files: [
'node_modules/jasmine-promises/dist/jasmine-promises.js',
'test/integration/index.js',
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/integration/index.js': ['webpack', 'sourcemap'],
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
// reporters: ['progress'],
// reporters: ['spec', 'jasmine-diff'],
// reporters: ['jasmine-diff'],
reporters: ['spec'],
// web server port
port: 9877,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values:
// config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN ||
// config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,
// Hide webpack build information from output
webpackMiddleware: {
noInfo: 'errors-only',
},
});
// if (process.env.TRAVIS) {
config.customLaunchers = {
Chrome_no_sandbox: {
base: 'Chrome',
flags: ['--no-sandbox'],
},
};
config.browsers = ['Chrome_no_sandbox'];
config.webpack = webpackConf;
// Configure code coverage reporter
config.coverageReporter = {
dir: 'coverage/',
reporters: [
{ type: 'lcovonly', subdir: '.' },
{ type: 'json', subdir: '.' },
{ type: 'text', subdir: '.' },
{ type: 'html', subdir: '.' },
],
};
};
| Hypheme/harmonized.js | integration.karma.conf.js | JavaScript | mit | 2,461 |
// Copyright OpenLogic, Inc.
// See LICENSE file for license information.
//
var totalRequests = 0;
// First check the MIME type of the URL. If it is the desired type, then make
// the AJAX request to get the content (DOM) and extract the relevant links
// in the content.
function follow_html_mime_type(url)
{
var xhr = new XMLHttpRequest();
xhr.open('HEAD', url);
xhr.onreadystatechange = function() {
if (this.readyState == this.DONE &&
this.getResponseHeader('content-type').indexOf("text/html") != -1)
{
totalRequests += 1;
chrome.runtime.sendMessage({ total: totalRequests });
requestDOM(url);
}
}
xhr.send();
}
function requestDOM(url)
{
var domRequest = new XMLHttpRequest();
domRequest.open('GET', url, true);
domRequest.onreadystatechange = function() {
if (this.readyState == this.DONE &&
this.status == 200)
{
var dom = $.parseHTML(this.responseText);
extractLinks(dom);
}
}
domRequest.send();
}
function extractLinks(doc)
{
try {
var domain = window.parent.location.origin;
var aTag = 'a';
if (domain == 'http://sourceforge.net')
aTag = 'a.name'
var links = $(aTag, doc).toArray();
links = links.map(function(element) {
// Proceed only if the link is in the same domain.
if (element.href.indexOf(domain) == 0)
{
// Return an anchor's href attribute, stripping any URL fragment (hash '#').
// If the html specifies a relative path, chrome converts it to an absolute
// URL.
var href = element.href;
var hashIndex = href.indexOf('#');
if (hashIndex > -1)
href = href.substr(0, hashIndex);
return href;
}
});
// Remove undefined from the links array.
for (var n = links.length - 1; n >= 0; --n)
{
if (links[n] == undefined)
links.splice(n, 1);
}
links.sort();
totalRequests -= 1;
chrome.runtime.sendMessage({ remainder: totalRequests });
chrome.extension.sendRequest(links);
}
catch (error)
{
// Do nothing.
totalRequests -= 1;
chrome.runtime.sendMessage({ remainder: totalRequests });
}
}
window.sendSecondLevelLinks = function() {
var firstLevelLinks = window.getLinks();
for (var index in firstLevelLinks)
{
var url = firstLevelLinks[index];
var current_location = window.location.href;
var domain = window.parent.location.origin;
// - skip urls that look like "parents" of the current one
if (url.indexOf(current_location) != -1 && url.indexOf(domain) == 0)
follow_html_mime_type(url);
}
}
window.sendSecondLevelLinks();
| openlogic/chrome-link-scraper | send_second_level_links.js | JavaScript | mit | 2,658 |
import { mount } from '@vue/test-utils';
import TocButton from '../src/views/TocButton';
function createWrapper() {
return mount(TocButton);
}
describe('Table of contents button', () => {
it('should mount', () => {
const wrapper = createWrapper();
expect(wrapper.exists()).toBe(true);
});
it('should emit an event when the button is clicked', () => {
const wrapper = createWrapper();
wrapper.find('button').trigger('click');
expect(wrapper.emitted().click).toBeTruthy();
});
});
| DXCanas/kolibri | kolibri/plugins/document_epub_render/assets/tests/TocButton.spec.js | JavaScript | mit | 511 |
'use strict';
angular
.module('reflect.calendar')
.factory('calendarHelper', function(moment, calendarConfig) {
function eventIsInPeriod(eventStart, eventEnd, periodStart, periodEnd) {
eventStart = moment(eventStart);
eventEnd = moment(eventEnd);
periodStart = moment(periodStart);
periodEnd = moment(periodEnd);
return (eventStart.isAfter(periodStart) && eventStart.isBefore(periodEnd)) ||
(eventEnd.isAfter(periodStart) && eventEnd.isBefore(periodEnd)) ||
(eventStart.isBefore(periodStart) && eventEnd.isAfter(periodEnd)) ||
eventStart.isSame(periodStart) ||
eventEnd.isSame(periodEnd);
}
function getEventsInPeriod(calendarDate, period, allEvents) {
var startPeriod = moment(calendarDate).startOf(period);
var endPeriod = moment(calendarDate).endOf(period);
return allEvents.filter(function(event) {
return eventIsInPeriod(event.startsAt, event.endsAt, startPeriod, endPeriod);
});
}
function getBadgeTotal(events) {
return events.filter(function(event) {
return event.incrementsBadgeTotal !== false;
}).length;
}
function getWeekDayNames() {
var weekdays = [];
var count = 0;
while (count < 7) {
weekdays.push(moment().weekday(count++).format(calendarConfig.dateFormats.weekDay));
}
return weekdays;
}
function filterEventsInPeriod(events, startPeriod, endPeriod) {
return events.filter(function(event) {
return eventIsInPeriod(event.startsAt, event.endsAt, startPeriod, endPeriod);
});
}
function getYearView(events, currentDay) {
var view = [];
var eventsInPeriod = getEventsInPeriod(currentDay, 'year', events);
var month = moment(currentDay).startOf('year');
var count = 0;
while (count < 12) {
var startPeriod = month.clone();
var endPeriod = startPeriod.clone().endOf('month');
var periodEvents = filterEventsInPeriod(eventsInPeriod, startPeriod, endPeriod);
view.push({
label: startPeriod.format(calendarConfig.dateFormats.month),
isToday: startPeriod.isSame(moment().startOf('month')),
events: periodEvents,
date: startPeriod,
badgeTotal: getBadgeTotal(periodEvents)
});
month.add(1, 'month');
count++;
}
return view;
}
function getMonthView(events, currentDay) {
var eventsInPeriod = getEventsInPeriod(currentDay, 'month', events);
var startOfMonth = moment(currentDay).startOf('month');
var day = startOfMonth.clone().startOf('week');
var endOfMonthView = moment(currentDay).endOf('month').endOf('week');
var view = [];
var today = moment().startOf('day');
while (day.isBefore(endOfMonthView)) {
var inMonth = day.month() === moment(currentDay).month();
var monthEvents = [];
if (inMonth) {
monthEvents = filterEventsInPeriod(eventsInPeriod, day, day.clone().endOf('day'));
}
view.push({
label: day.date(),
date: day.clone(),
inMonth: inMonth,
isPast: today.isAfter(day),
isToday: today.isSame(day),
isFuture: today.isBefore(day),
isWeekend: [0, 6].indexOf(day.day()) > -1,
events: monthEvents,
badgeTotal: getBadgeTotal(monthEvents)
});
day.add(1, 'day');
}
return view;
}
function getWeekView(events, currentDay) {
var startOfWeek = moment(currentDay).startOf('week');
var endOfWeek = moment(currentDay).endOf('week');
var dayCounter = startOfWeek.clone();
var days = [];
var today = moment().startOf('day');
while (days.length < 7) {
days.push({
weekDayLabel: dayCounter.format(calendarConfig.dateFormats.weekDay),
date: dayCounter.clone(),
dayLabel: dayCounter.format(calendarConfig.dateFormats.day),
isPast: dayCounter.isBefore(today),
isToday: dayCounter.isSame(today),
isFuture: dayCounter.isAfter(today),
isWeekend: [0, 6].indexOf(dayCounter.day()) > -1
});
dayCounter.add(1, 'day');
}
var eventsSorted = filterEventsInPeriod(events, startOfWeek, endOfWeek).map(function(event) {
var eventStart = moment(event.startsAt).startOf('day');
var eventEnd = moment(event.endsAt).startOf('day');
var weekViewStart = moment(startOfWeek).startOf('day');
var weekViewEnd = moment(endOfWeek).startOf('day');
var offset, span;
if (eventStart.isBefore(weekViewStart) || eventStart.isSame(weekViewStart)) {
offset = 0;
} else {
offset = eventStart.diff(weekViewStart, 'days');
}
if (eventEnd.isAfter(weekViewEnd)) {
eventEnd = weekViewEnd;
}
if (eventStart.isBefore(weekViewStart)) {
eventStart = weekViewStart;
}
span = moment(eventEnd).diff(eventStart, 'days') + 1;
event.daySpan = span;
event.dayOffset = offset;
return event;
});
return {days: days, events: eventsSorted};
}
function getDayView(events, currentDay, dayStartHour, dayEndHour, hourHeight) {
var calendarStart = moment(currentDay).startOf('day').add(dayStartHour, 'hours');
var calendarEnd = moment(currentDay).startOf('day').add(dayEndHour, 'hours');
var calendarHeight = (dayEndHour - dayStartHour + 1) * hourHeight;
var hourHeightMultiplier = hourHeight / 60;
var buckets = [];
var eventsInPeriod = filterEventsInPeriod(
events,
moment(currentDay).startOf('day').toDate(),
moment(currentDay).endOf('day').toDate()
);
return eventsInPeriod.map(function(event) {
if (moment(event.startsAt).isBefore(calendarStart)) {
event.top = 0;
} else {
event.top = (moment(event.startsAt).startOf('minute').diff(calendarStart.startOf('minute'), 'minutes') * hourHeightMultiplier) - 2;
}
if (moment(event.endsAt).isAfter(calendarEnd)) {
event.height = calendarHeight - event.top;
} else {
var diffStart = event.startsAt;
if (moment(event.startsAt).isBefore(calendarStart)) {
diffStart = calendarStart.toDate();
}
event.height = moment(event.endsAt).diff(diffStart, 'minutes') * hourHeightMultiplier;
}
if (event.top - event.height > calendarHeight) {
event.height = 0;
}
event.left = 0;
return event;
}).filter(function(event) {
return event.height > 0;
}).map(function(event) {
var cannotFitInABucket = true;
buckets.forEach(function(bucket, bucketIndex) {
var canFitInThisBucket = true;
bucket.forEach(function(bucketItem) {
if (eventIsInPeriod(event.startsAt, event.endsAt, bucketItem.startsAt, bucketItem.endsAt) ||
eventIsInPeriod(bucketItem.startsAt, bucketItem.endsAt, event.startsAt, event.endsAt)) {
canFitInThisBucket = false;
}
});
if (canFitInThisBucket && cannotFitInABucket) {
cannotFitInABucket = false;
event.left = bucketIndex * 150;
buckets[bucketIndex].push(event);
}
});
if (cannotFitInABucket) {
event.left = buckets.length * 150;
buckets.push([event]);
}
return event;
});
}
return {
getWeekDayNames: getWeekDayNames,
getYearView: getYearView,
getMonthView: getMonthView,
getWeekView: getWeekView,
getDayView: getDayView
};
});
| el-besto/ts-angular-bootstrap-calendar | src/services/calendarHelper.js | JavaScript | mit | 7,806 |
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var orgs = require('./routes/orgs');
var tasks = require('./routes/tasks');
var projects = require('./routes/projects');
var emails = require('./routes/emails');
var util = require('./util');
var app = express();
// var expressJwt = require('express-jwt');
// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// Client Route
// app.use(expressJwt({ secret: 'secret' }));
app.use(express.static(path.join(__dirname, '../dist')));
// Routing
app.use('/api', routes);
app.use('/api/orgs', orgs);
app.use('/api/projects', projects);
//app.use('/api/users', util.decode);
app.use('/api/users', users);
// Might need to modify where decoding happens (on user?)
//app.use('/api/tasks', util.decode);
app.use('/api/tasks', tasks);
app.use('/api/email', emails);
app.use('/*/', express.static(path.join(__dirname, '../dist/index.html')));
// TODO refactor into a controller
// TODO remove this
// checkAuth = util.checkAuth;
module.exports = app;
| alexzywiak/sage-es6 | server/server.js | JavaScript | mit | 1,548 |
import React from 'react';
import { assert } from 'chai';
import { createMount, createShallow, getClasses } from '@material-ui/core/test-utils';
import describeConformance from '../test-utils/describeConformance';
import AppBar from './AppBar';
import Paper from '../Paper';
describe('<AppBar />', () => {
let mount;
let shallow;
let classes;
before(() => {
mount = createMount({ strict: true });
shallow = createShallow({ dive: true });
classes = getClasses(<AppBar>Hello World</AppBar>);
});
after(() => {
mount.cleanUp();
});
describeConformance(<AppBar>Conformance?</AppBar>, () => ({
classes,
inheritComponent: Paper,
mount,
refInstanceof: window.HTMLElement,
skip: ['componentProp'],
}));
it('should render with the root class and primary', () => {
const wrapper = shallow(<AppBar>Hello World</AppBar>);
assert.strictEqual(wrapper.hasClass(classes.root), true);
assert.strictEqual(wrapper.hasClass(classes.colorPrimary), true);
assert.strictEqual(wrapper.hasClass(classes.colorSecondary), false);
});
it('should render a primary app bar', () => {
const wrapper = shallow(<AppBar color="primary">Hello World</AppBar>);
assert.strictEqual(wrapper.hasClass(classes.root), true);
assert.strictEqual(wrapper.hasClass(classes.colorPrimary), true);
assert.strictEqual(wrapper.hasClass(classes.colorSecondary), false);
});
it('should render an secondary app bar', () => {
const wrapper = shallow(<AppBar color="secondary">Hello World</AppBar>);
assert.strictEqual(wrapper.hasClass(classes.root), true);
assert.strictEqual(wrapper.hasClass(classes.colorPrimary), false);
assert.strictEqual(wrapper.hasClass(classes.colorSecondary), true);
});
describe('Dialog', () => {
it('should add a .mui-fixed class', () => {
const wrapper = shallow(<AppBar position="fixed">Hello World</AppBar>);
assert.strictEqual(wrapper.hasClass('mui-fixed'), true);
});
});
});
| kybarg/material-ui | packages/material-ui/src/AppBar/AppBar.test.js | JavaScript | mit | 1,998 |
var mongoose = require('mongoose'),
_ = require('lodash'),
moment = require('moment');
module.exports = function (req, res) {
var connectionDB = mongoose.connection.db;
var today = moment().startOf('day');
var tomorrow = moment(today).add(1, 'days');
var dayAfterTomorrow = moment(today).add(2, 'days');
connectionDB.collection('appointments', function (err, collection) {
collection.find({
startDate: {
$gte: tomorrow.toISOString(),
$lt: dayAfterTomorrow.toISOString()
}
}, function(err, cursor){
if (err) {
console.log(err)
} else {
var appointmentsPhone = [];
var appointmentsEmail = [];
cursor.toArray(function (err, result) {
if (err) {
console.log(err);
} else {
_.map(result, function(a){
if (a.sentReminderPhone === undefined
&& a.sentReminderPhone !== 'sent'
&& a.customer.phone !== ''
&& a.sendSMS){
console.log('here');
appointmentsPhone.push(a);
}
if (a.sentReminderEmail === undefined
&& a.sentReminderEmail !== 'sent'
&& a.customer.email !== ''
&& a.sendEmail){
appointmentsEmail.push(a);
}
});
res.jsonp([{email: appointmentsEmail.length, phone: appointmentsPhone.length}])
}
});
}
})
});
};
| ethannguyen93/POS | app/models/operations/appointment/getNumberOfReminders.js | JavaScript | mit | 1,892 |
(function(root, factory) {
if (typeof exports === "object") {
module.exports = factory();
} else if (typeof define === "function" && define.amd) {
define([], factory);
} else{
factory();
}
}(this, function() {
/**
* AngularJS Google Maps Ver. 1.18.4
*
* The MIT License (MIT)
*
* Copyright (c) 2014, 2015, 1016 Allen Kim
*
* 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.
*/
angular.module('ngMap', []);
/**
* @ngdoc controller
* @name MapController
*/
(function() {
'use strict';
var Attr2MapOptions;
var __MapController = function(
$scope, $element, $attrs, $parse, $interpolate, _Attr2MapOptions_, NgMap, NgMapPool, escapeRegExp
) {
Attr2MapOptions = _Attr2MapOptions_;
var vm = this;
var exprStartSymbol = $interpolate.startSymbol();
var exprEndSymbol = $interpolate.endSymbol();
vm.mapOptions; /** @memberof __MapController */
vm.mapEvents; /** @memberof __MapController */
vm.eventListeners; /** @memberof __MapController */
/**
* Add an object to the collection of group
* @memberof __MapController
* @function addObject
* @param groupName the name of collection that object belongs to
* @param obj an object to add into a collection, i.e. marker, shape
*/
vm.addObject = function(groupName, obj) {
if (vm.map) {
vm.map[groupName] = vm.map[groupName] || {};
var len = Object.keys(vm.map[groupName]).length;
vm.map[groupName][obj.id || len] = obj;
if (vm.map instanceof google.maps.Map) {
//infoWindow.setMap works like infoWindow.open
if (groupName != "infoWindows" && obj.setMap) {
obj.setMap && obj.setMap(vm.map);
}
if (obj.centered && obj.position) {
vm.map.setCenter(obj.position);
}
(groupName == 'markers') && vm.objectChanged('markers');
(groupName == 'customMarkers') && vm.objectChanged('customMarkers');
}
}
};
/**
* Delete an object from the collection and remove from map
* @memberof __MapController
* @function deleteObject
* @param {Array} objs the collection of objects. i.e., map.markers
* @param {Object} obj the object to be removed. i.e., marker
*/
vm.deleteObject = function(groupName, obj) {
/* delete from group */
if (obj.map) {
var objs = obj.map[groupName];
for (var name in objs) {
if (objs[name] === obj) {
void 0;
google.maps.event.clearInstanceListeners(obj);
delete objs[name];
}
}
/* delete from map */
obj.map && obj.setMap && obj.setMap(null);
(groupName == 'markers') && vm.objectChanged('markers');
(groupName == 'customMarkers') && vm.objectChanged('customMarkers');
}
};
/**
* @memberof __MapController
* @function observeAttrSetObj
* @param {Hash} orgAttrs attributes before its initialization
* @param {Hash} attrs attributes after its initialization
* @param {Object} obj map object that an action is to be done
* @description watch changes of attribute values and
* do appropriate action based on attribute name
*/
vm.observeAttrSetObj = function(orgAttrs, attrs, obj) {
if (attrs.noWatcher) {
return false;
}
var attrsToObserve = Attr2MapOptions.getAttrsToObserve(orgAttrs);
for (var i=0; i<attrsToObserve.length; i++) {
var attrName = attrsToObserve[i];
attrs.$observe(attrName, NgMap.observeAndSet(attrName, obj));
}
};
/**
* @memberof __MapController
* @function zoomToIncludeMarkers
*/
vm.zoomToIncludeMarkers = function() {
// Only fit to bounds if we have any markers
// object.keys is supported in all major browsers (IE9+)
if ((vm.map.markers != null && Object.keys(vm.map.markers).length > 0) || (vm.map.customMarkers != null && Object.keys(vm.map.customMarkers).length > 0)) {
var bounds = new google.maps.LatLngBounds();
for (var k1 in vm.map.markers) {
bounds.extend(vm.map.markers[k1].getPosition());
}
for (var k2 in vm.map.customMarkers) {
bounds.extend(vm.map.customMarkers[k2].getPosition());
}
if (vm.mapOptions.maximumZoom) {
vm.enableMaximumZoomCheck = true; //enable zoom check after resizing for markers
}
vm.map.fitBounds(bounds);
}
};
/**
* @memberof __MapController
* @function objectChanged
* @param {String} group name of group e.g., markers
*/
vm.objectChanged = function(group) {
if ( vm.map &&
(group == 'markers' || group == 'customMarkers') &&
vm.map.zoomToIncludeMarkers == 'auto'
) {
vm.zoomToIncludeMarkers();
}
};
/**
* @memberof __MapController
* @function initializeMap
* @description
* . initialize Google map on <div> tag
* . set map options, events, and observers
* . reset zoom to include all (custom)markers
*/
vm.initializeMap = function() {
var mapOptions = vm.mapOptions,
mapEvents = vm.mapEvents;
var lazyInitMap = vm.map; //prepared for lazy init
vm.map = NgMapPool.getMapInstance($element[0]);
NgMap.setStyle($element[0]);
// set objects for lazyInit
if (lazyInitMap) {
/**
* rebuild mapOptions for lazyInit
* because attributes values might have been changed
*/
var filtered = Attr2MapOptions.filter($attrs);
var options = Attr2MapOptions.getOptions(filtered);
var controlOptions = Attr2MapOptions.getControlOptions(filtered);
mapOptions = angular.extend(options, controlOptions);
void 0;
for (var group in lazyInitMap) {
var groupMembers = lazyInitMap[group]; //e.g. markers
if (typeof groupMembers == 'object') {
for (var id in groupMembers) {
vm.addObject(group, groupMembers[id]);
}
}
}
vm.map.showInfoWindow = vm.showInfoWindow;
vm.map.hideInfoWindow = vm.hideInfoWindow;
}
// set options
mapOptions.zoom = mapOptions.zoom || 15;
var center = mapOptions.center;
var exprRegExp = new RegExp(escapeRegExp(exprStartSymbol) + '.*' + escapeRegExp(exprEndSymbol));
if (!mapOptions.center ||
((typeof center === 'string') && center.match(exprRegExp))
) {
mapOptions.center = new google.maps.LatLng(0, 0);
} else if( (typeof center === 'string') && center.match(/^[0-9.-]*,[0-9.-]*$/) ){
var lat = parseFloat(center.split(',')[0]);
var lng = parseFloat(center.split(',')[1]);
mapOptions.center = new google.maps.LatLng(lat, lng);
} else if (!(center instanceof google.maps.LatLng)) {
var geoCenter = mapOptions.center;
delete mapOptions.center;
NgMap.getGeoLocation(geoCenter, mapOptions.geoLocationOptions).
then(function (latlng) {
vm.map.setCenter(latlng);
var geoCallback = mapOptions.geoCallback;
geoCallback && $parse(geoCallback)($scope);
}, function () {
if (mapOptions.geoFallbackCenter) {
vm.map.setCenter(mapOptions.geoFallbackCenter);
}
});
}
vm.map.setOptions(mapOptions);
// set events
for (var eventName in mapEvents) {
var event = mapEvents[eventName];
var listener = google.maps.event.addListener(vm.map, eventName, event);
vm.eventListeners[eventName] = listener;
}
// set observers
vm.observeAttrSetObj(orgAttrs, $attrs, vm.map);
vm.singleInfoWindow = mapOptions.singleInfoWindow;
google.maps.event.trigger(vm.map, 'resize');
google.maps.event.addListenerOnce(vm.map, "idle", function () {
NgMap.addMap(vm);
if (mapOptions.zoomToIncludeMarkers) {
vm.zoomToIncludeMarkers();
}
//TODO: it's for backward compatibiliy. will be removed
$scope.map = vm.map;
$scope.$emit('mapInitialized', vm.map);
//callback
if ($attrs.mapInitialized) {
$parse($attrs.mapInitialized)($scope, {map: vm.map});
}
});
//add maximum zoom listeners if zoom-to-include-markers and and maximum-zoom are valid attributes
if (mapOptions.zoomToIncludeMarkers && mapOptions.maximumZoom) {
google.maps.event.addListener(vm.map, 'zoom_changed', function() {
if (vm.enableMaximumZoomCheck == true) {
vm.enableMaximumZoomCheck = false;
google.maps.event.addListenerOnce(vm.map, 'bounds_changed', function() {
vm.map.setZoom(Math.min(mapOptions.maximumZoom, vm.map.getZoom()));
});
}
});
}
};
$scope.google = google; //used by $scope.eval to avoid eval()
/**
* get map options and events
*/
var orgAttrs = Attr2MapOptions.orgAttributes($element);
var filtered = Attr2MapOptions.filter($attrs);
var options = Attr2MapOptions.getOptions(filtered, {scope: $scope});
var controlOptions = Attr2MapOptions.getControlOptions(filtered);
var mapOptions = angular.extend(options, controlOptions);
var mapEvents = Attr2MapOptions.getEvents($scope, filtered);
void 0;
Object.keys(mapEvents).length && void 0;
vm.mapOptions = mapOptions;
vm.mapEvents = mapEvents;
vm.eventListeners = {};
if (options.lazyInit) { // allows controlled initialization
// parse angular expression for dynamic ids
if (!!$attrs.id &&
// starts with, at position 0
$attrs.id.indexOf(exprStartSymbol, 0) === 0 &&
// ends with
$attrs.id.indexOf(exprEndSymbol, $attrs.id.length - exprEndSymbol.length) !== -1) {
var idExpression = $attrs.id.slice(2,-2);
var mapId = $parse(idExpression)($scope);
} else {
var mapId = $attrs.id;
}
vm.map = {id: mapId}; //set empty, not real, map
NgMap.addMap(vm);
} else {
vm.initializeMap();
}
//Trigger Resize
if(options.triggerResize) {
google.maps.event.trigger(vm.map, 'resize');
}
$element.bind('$destroy', function() {
NgMapPool.returnMapInstance(vm.map);
NgMap.deleteMap(vm);
});
}; // __MapController
__MapController.$inject = [
'$scope', '$element', '$attrs', '$parse', '$interpolate', 'Attr2MapOptions', 'NgMap', 'NgMapPool', 'escapeRegexpFilter'
];
angular.module('ngMap').controller('__MapController', __MapController);
})();
/**
* @ngdoc directive
* @name bicycling-layer
* @param Attr2Options {service}
* convert html attribute to Google map api options
* @description
* Requires: map directive
* Restrict To: Element
*
* @example
*
* <map zoom="13" center="34.04924594193164, -118.24104309082031">
* <bicycling-layer></bicycling-layer>
* </map>
*/
(function() {
'use strict';
var parser;
var linkFunc = function(scope, element, attrs, mapController) {
mapController = mapController[0]||mapController[1];
var orgAttrs = parser.orgAttributes(element);
var filtered = parser.filter(attrs);
var options = parser.getOptions(filtered, {scope: scope});
var events = parser.getEvents(scope, filtered);
void 0;
var layer = getLayer(options, events);
mapController.addObject('bicyclingLayers', layer);
mapController.observeAttrSetObj(orgAttrs, attrs, layer); //observers
element.bind('$destroy', function() {
mapController.deleteObject('bicyclingLayers', layer);
});
};
var getLayer = function(options, events) {
var layer = new google.maps.BicyclingLayer(options);
for (var eventName in events) {
google.maps.event.addListener(layer, eventName, events[eventName]);
}
return layer;
};
var bicyclingLayer= function(Attr2MapOptions) {
parser = Attr2MapOptions;
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
link: linkFunc
};
};
bicyclingLayer.$inject = ['Attr2MapOptions'];
angular.module('ngMap').directive('bicyclingLayer', bicyclingLayer);
})();
/**
* @ngdoc directive
* @name custom-control
* @param Attr2Options {service} convert html attribute to Google map api options
* @param $compile {service} AngularJS $compile service
* @description
* Build custom control and set to the map with position
*
* Requires: map directive
*
* Restrict To: Element
*
* @attr {String} position position of this control
* i.e. TOP_RIGHT
* @attr {Number} index index of the control
* @example
*
* Example:
* <map center="41.850033,-87.6500523" zoom="3">
* <custom-control id="home" position="TOP_LEFT" index="1">
* <div style="background-color: white;">
* <b>Home</b>
* </div>
* </custom-control>
* </map>
*
*/
(function() {
'use strict';
var parser, NgMap;
var linkFunc = function(scope, element, attrs, mapController, $transclude) {
mapController = mapController[0]||mapController[1];
var filtered = parser.filter(attrs);
var options = parser.getOptions(filtered, {scope: scope});
var events = parser.getEvents(scope, filtered);
/**
* build a custom control element
*/
var customControlEl = element[0].parentElement.removeChild(element[0]);
var content = $transclude();
angular.element(customControlEl).append(content);
/**
* set events
*/
for (var eventName in events) {
google.maps.event.addDomListener(customControlEl, eventName, events[eventName]);
}
mapController.addObject('customControls', customControlEl);
var position = options.position;
mapController.map.controls[google.maps.ControlPosition[position]].push(customControlEl);
element.bind('$destroy', function() {
mapController.deleteObject('customControls', customControlEl);
});
};
var customControl = function(Attr2MapOptions, _NgMap_) {
parser = Attr2MapOptions, NgMap = _NgMap_;
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
link: linkFunc,
transclude: true
}; // return
};
customControl.$inject = ['Attr2MapOptions', 'NgMap'];
angular.module('ngMap').directive('customControl', customControl);
})();
/**
* @ngdoc directive
* @memberof ngmap
* @name custom-marker
* @param Attr2Options {service} convert html attribute to Google map api options
* @param $timeout {service} AngularJS $timeout
* @description
* Marker with html
* Requires: map directive
* Restrict To: Element
*
* @attr {String} position required, position on map
* @attr {Number} z-index optional
* @attr {Boolean} visible optional
* @example
*
* Example:
* <map center="41.850033,-87.6500523" zoom="3">
* <custom-marker position="41.850033,-87.6500523">
* <div>
* <b>Home</b>
* </div>
* </custom-marker>
* </map>
*
*/
/* global document */
(function() {
'use strict';
var parser, $timeout, $compile, NgMap;
var CustomMarker = function(options) {
options = options || {};
this.el = document.createElement('div');
this.el.style.display = 'inline-block';
this.el.style.visibility = "hidden";
this.visible = true;
for (var key in options) { /* jshint ignore:line */
this[key] = options[key];
}
};
var setCustomMarker = function() {
CustomMarker.prototype = new google.maps.OverlayView();
CustomMarker.prototype.setContent = function(html, scope) {
this.el.innerHTML = html;
this.el.style.position = 'absolute';
if (scope) {
$compile(angular.element(this.el).contents())(scope);
}
};
CustomMarker.prototype.getDraggable = function() {
return this.draggable;
};
CustomMarker.prototype.setDraggable = function(draggable) {
this.draggable = draggable;
};
CustomMarker.prototype.getPosition = function() {
return this.position;
};
CustomMarker.prototype.setPosition = function(position) {
position && (this.position = position); /* jshint ignore:line */
var _this = this;
if (this.getProjection() && typeof this.position.lng == 'function') {
void 0;
var setPosition = function() {
if (!_this.getProjection()) { return; }
var posPixel = _this.getProjection().fromLatLngToDivPixel(_this.position);
var x = Math.round(posPixel.x - (_this.el.offsetWidth/2));
var y = Math.round(posPixel.y - _this.el.offsetHeight - 10); // 10px for anchor
_this.el.style.left = x + "px";
_this.el.style.top = y + "px";
_this.el.style.visibility = "visible";
};
if (_this.el.offsetWidth && _this.el.offsetHeight) {
setPosition();
} else {
//delayed left/top calculation when width/height are not set instantly
$timeout(setPosition, 300);
}
}
};
CustomMarker.prototype.setZIndex = function(zIndex) {
zIndex && (this.zIndex = zIndex); /* jshint ignore:line */
this.el.style.zIndex = this.zIndex;
};
CustomMarker.prototype.getVisible = function() {
return this.visible;
};
CustomMarker.prototype.setVisible = function(visible) {
this.el.style.display = visible ? 'inline-block' : 'none';
this.visible = visible;
};
CustomMarker.prototype.addClass = function(className) {
var classNames = this.el.className.trim().split(' ');
(classNames.indexOf(className) == -1) && classNames.push(className); /* jshint ignore:line */
this.el.className = classNames.join(' ');
};
CustomMarker.prototype.removeClass = function(className) {
var classNames = this.el.className.split(' ');
var index = classNames.indexOf(className);
(index > -1) && classNames.splice(index, 1); /* jshint ignore:line */
this.el.className = classNames.join(' ');
};
CustomMarker.prototype.onAdd = function() {
this.getPanes().overlayMouseTarget.appendChild(this.el);
};
CustomMarker.prototype.draw = function() {
this.setPosition();
this.setZIndex(this.zIndex);
this.setVisible(this.visible);
};
CustomMarker.prototype.onRemove = function() {
this.el.parentNode.removeChild(this.el);
//this.el = null;
};
};
var linkFunc = function(orgHtml, varsToWatch) {
//console.log('orgHtml', orgHtml, 'varsToWatch', varsToWatch);
return function(scope, element, attrs, mapController) {
mapController = mapController[0]||mapController[1];
var orgAttrs = parser.orgAttributes(element);
var filtered = parser.filter(attrs);
var options = parser.getOptions(filtered, {scope: scope});
var events = parser.getEvents(scope, filtered);
/**
* build a custom marker element
*/
element[0].style.display = 'none';
void 0;
var customMarker = new CustomMarker(options);
$timeout(function() { //apply contents, class, and location after it is compiled
scope.$watch('[' + varsToWatch.join(',') + ']', function() {
customMarker.setContent(orgHtml, scope);
}, true);
customMarker.setContent(element[0].innerHTML, scope);
var classNames = element[0].firstElementChild.className;
customMarker.addClass('custom-marker');
customMarker.addClass(classNames);
void 0;
if (!(options.position instanceof google.maps.LatLng)) {
NgMap.getGeoLocation(options.position).then(
function(latlng) {
customMarker.setPosition(latlng);
}
);
}
});
void 0;
for (var eventName in events) { /* jshint ignore:line */
google.maps.event.addDomListener(
customMarker.el, eventName, events[eventName]);
}
mapController.addObject('customMarkers', customMarker);
//set observers
mapController.observeAttrSetObj(orgAttrs, attrs, customMarker);
element.bind('$destroy', function() {
//Is it required to remove event listeners when DOM is removed?
mapController.deleteObject('customMarkers', customMarker);
});
}; // linkFunc
};
var customMarkerDirective = function(
_$timeout_, _$compile_, $interpolate, Attr2MapOptions, _NgMap_, escapeRegExp
) {
parser = Attr2MapOptions;
$timeout = _$timeout_;
$compile = _$compile_;
NgMap = _NgMap_;
var exprStartSymbol = $interpolate.startSymbol();
var exprEndSymbol = $interpolate.endSymbol();
var exprRegExp = new RegExp(escapeRegExp(exprStartSymbol) + '([^' + exprEndSymbol.substring(0, 1) + ']+)' + escapeRegExp(exprEndSymbol), 'g');
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
compile: function(element) {
setCustomMarker();
element[0].style.display ='none';
var orgHtml = element.html();
var matches = orgHtml.match(exprRegExp);
var varsToWatch = [];
//filter out that contains '::', 'this.'
(matches || []).forEach(function(match) {
var toWatch = match.replace(exprStartSymbol,'').replace(exprEndSymbol,'');
if (match.indexOf('::') == -1 &&
match.indexOf('this.') == -1 &&
varsToWatch.indexOf(toWatch) == -1) {
varsToWatch.push(match.replace(exprStartSymbol,'').replace(exprEndSymbol,''));
}
});
return linkFunc(orgHtml, varsToWatch);
}
}; // return
};// function
customMarkerDirective.$inject =
['$timeout', '$compile', '$interpolate', 'Attr2MapOptions', 'NgMap', 'escapeRegexpFilter'];
angular.module('ngMap').directive('customMarker', customMarkerDirective);
})();
/**
* @ngdoc directive
* @name directions
* @description
* Enable directions on map.
* e.g., origin, destination, draggable, waypoints, etc
*
* Requires: map directive
*
* Restrict To: Element
*
* @attr {String} DirectionsRendererOptions
* [Any DirectionsRendererOptions](https://developers.google.com/maps/documentation/javascript/reference#DirectionsRendererOptions)
* @attr {String} DirectionsRequestOptions
* [Any DirectionsRequest options](https://developers.google.com/maps/documentation/javascript/reference#DirectionsRequest)
* @example
* <map zoom="14" center="37.7699298, -122.4469157">
* <directions
* draggable="true"
* panel="directions-panel"
* travel-mode="{{travelMode}}"
* waypoints="[{location:'kingston', stopover:true}]"
* origin="{{origin}}"
* destination="{{destination}}">
* </directions>
* </map>
*/
/* global document */
(function() {
'use strict';
var NgMap, $timeout, NavigatorGeolocation;
var getDirectionsRenderer = function(options, events) {
if (options.panel) {
options.panel = document.getElementById(options.panel) ||
document.querySelector(options.panel);
}
var renderer = new google.maps.DirectionsRenderer(options);
for (var eventName in events) {
google.maps.event.addListener(renderer, eventName, events[eventName]);
}
return renderer;
};
var updateRoute = function(renderer, options) {
var directionsService = new google.maps.DirectionsService();
/* filter out valid keys only for DirectionsRequest object*/
var request = options;
request.travelMode = request.travelMode || 'DRIVING';
var validKeys = [
'origin', 'destination', 'travelMode', 'transitOptions', 'unitSystem',
'durationInTraffic', 'waypoints', 'optimizeWaypoints',
'provideRouteAlternatives', 'avoidHighways', 'avoidTolls', 'region'
];
for(var key in request){
(validKeys.indexOf(key) === -1) && (delete request[key]);
}
if(request.waypoints) {
// Check fo valid values
if(request.waypoints == "[]" || request.waypoints === "") {
delete request.waypoints;
}
}
var showDirections = function(request) {
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
$timeout(function() {
renderer.setDirections(response);
});
}
});
};
if (request.origin && request.destination) {
if (request.origin == 'current-location') {
NavigatorGeolocation.getCurrentPosition().then(function(ll) {
request.origin = new google.maps.LatLng(ll.coords.latitude, ll.coords.longitude);
showDirections(request);
});
} else if (request.destination == 'current-location') {
NavigatorGeolocation.getCurrentPosition().then(function(ll) {
request.destination = new google.maps.LatLng(ll.coords.latitude, ll.coords.longitude);
showDirections(request);
});
} else {
showDirections(request);
}
}
};
var directions = function(
Attr2MapOptions, _$timeout_, _NavigatorGeolocation_, _NgMap_) {
var parser = Attr2MapOptions;
NgMap = _NgMap_;
$timeout = _$timeout_;
NavigatorGeolocation = _NavigatorGeolocation_;
var linkFunc = function(scope, element, attrs, mapController) {
mapController = mapController[0]||mapController[1];
var orgAttrs = parser.orgAttributes(element);
var filtered = parser.filter(attrs);
var options = parser.getOptions(filtered, {scope: scope});
var events = parser.getEvents(scope, filtered);
var attrsToObserve = parser.getAttrsToObserve(orgAttrs);
var renderer = getDirectionsRenderer(options, events);
mapController.addObject('directionsRenderers', renderer);
attrsToObserve.forEach(function(attrName) {
(function(attrName) {
attrs.$observe(attrName, function(val) {
if (attrName == 'panel') {
$timeout(function(){
var panel =
document.getElementById(val) || document.querySelector(val);
void 0;
panel && renderer.setPanel(panel);
});
} else if (options[attrName] !== val) { //apply only if changed
var optionValue = parser.toOptionValue(val, {key: attrName});
void 0;
options[attrName] = optionValue;
updateRoute(renderer, options);
}
});
})(attrName);
});
NgMap.getMap().then(function() {
updateRoute(renderer, options);
});
element.bind('$destroy', function() {
mapController.deleteObject('directionsRenderers', renderer);
});
};
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
link: linkFunc
};
}; // var directions
directions.$inject =
['Attr2MapOptions', '$timeout', 'NavigatorGeolocation', 'NgMap'];
angular.module('ngMap').directive('directions', directions);
})();
/**
* @ngdoc directive
* @name drawing-manager
* @param Attr2Options {service} convert html attribute to Google map api options
* @description
* Requires: map directive
* Restrict To: Element
*
* @example
* Example:
*
* <map zoom="13" center="37.774546, -122.433523" map-type-id="SATELLITE">
* <drawing-manager
* on-overlaycomplete="onMapOverlayCompleted()"
* position="ControlPosition.TOP_CENTER"
* drawingModes="POLYGON,CIRCLE"
* drawingControl="true"
* circleOptions="fillColor: '#FFFF00';fillOpacity: 1;strokeWeight: 5;clickable: false;zIndex: 1;editable: true;" >
* </drawing-manager>
* </map>
*
* TODO: Add remove button.
* currently, for our solution, we have the shapes/markers in our own
* controller, and we use some css classes to change the shape button
* to a remove button (<div>X</div>) and have the remove operation in our own controller.
*/
(function() {
'use strict';
angular.module('ngMap').directive('drawingManager', [
'Attr2MapOptions', function(Attr2MapOptions) {
var parser = Attr2MapOptions;
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
link: function(scope, element, attrs, mapController) {
mapController = mapController[0]||mapController[1];
var filtered = parser.filter(attrs);
var options = parser.getOptions(filtered, {scope: scope});
var controlOptions = parser.getControlOptions(filtered);
var events = parser.getEvents(scope, filtered);
/**
* set options
*/
var drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: options.drawingmode,
drawingControl: options.drawingcontrol,
drawingControlOptions: controlOptions.drawingControlOptions,
circleOptions:options.circleoptions,
markerOptions:options.markeroptions,
polygonOptions:options.polygonoptions,
polylineOptions:options.polylineoptions,
rectangleOptions:options.rectangleoptions
});
//Observers
attrs.$observe('drawingControlOptions', function (newValue) {
drawingManager.drawingControlOptions = parser.getControlOptions({drawingControlOptions: newValue}).drawingControlOptions;
drawingManager.setDrawingMode(null);
drawingManager.setMap(mapController.map);
});
/**
* set events
*/
for (var eventName in events) {
google.maps.event.addListener(drawingManager, eventName, events[eventName]);
}
mapController.addObject('mapDrawingManager', drawingManager);
element.bind('$destroy', function() {
mapController.deleteObject('mapDrawingManager', drawingManager);
});
}
}; // return
}]);
})();
/**
* @ngdoc directive
* @name dynamic-maps-engine-layer
* @description
* Requires: map directive
* Restrict To: Element
*
* @example
* Example:
* <map zoom="14" center="[59.322506, 18.010025]">
* <dynamic-maps-engine-layer
* layer-id="06673056454046135537-08896501997766553811">
* </dynamic-maps-engine-layer>
* </map>
*/
(function() {
'use strict';
angular.module('ngMap').directive('dynamicMapsEngineLayer', [
'Attr2MapOptions', function(Attr2MapOptions) {
var parser = Attr2MapOptions;
var getDynamicMapsEngineLayer = function(options, events) {
var layer = new google.maps.visualization.DynamicMapsEngineLayer(options);
for (var eventName in events) {
google.maps.event.addListener(layer, eventName, events[eventName]);
}
return layer;
};
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
link: function(scope, element, attrs, mapController) {
mapController = mapController[0]||mapController[1];
var filtered = parser.filter(attrs);
var options = parser.getOptions(filtered, {scope: scope});
var events = parser.getEvents(scope, filtered, events);
var layer = getDynamicMapsEngineLayer(options, events);
mapController.addObject('mapsEngineLayers', layer);
}
}; // return
}]);
})();
/**
* @ngdoc directive
* @name fusion-tables-layer
* @description
* Requires: map directive
* Restrict To: Element
*
* @example
* Example:
* <map zoom="11" center="41.850033, -87.6500523">
* <fusion-tables-layer query="{
* select: 'Geocodable address',
* from: '1mZ53Z70NsChnBMm-qEYmSDOvLXgrreLTkQUvvg'}">
* </fusion-tables-layer>
* </map>
*/
(function() {
'use strict';
angular.module('ngMap').directive('fusionTablesLayer', [
'Attr2MapOptions', function(Attr2MapOptions) {
var parser = Attr2MapOptions;
var getLayer = function(options, events) {
var layer = new google.maps.FusionTablesLayer(options);
for (var eventName in events) {
google.maps.event.addListener(layer, eventName, events[eventName]);
}
return layer;
};
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
link: function(scope, element, attrs, mapController) {
mapController = mapController[0]||mapController[1];
var filtered = parser.filter(attrs);
var options = parser.getOptions(filtered, {scope: scope});
var events = parser.getEvents(scope, filtered, events);
void 0;
var layer = getLayer(options, events);
mapController.addObject('fusionTablesLayers', layer);
element.bind('$destroy', function() {
mapController.deleteObject('fusionTablesLayers', layer);
});
}
}; // return
}]);
})();
/**
* @ngdoc directive
* @name heatmap-layer
* @param Attr2Options {service} convert html attribute to Google map api options
* @description
* Requires: map directive
* Restrict To: Element
*
* @example
*
* <map zoom="11" center="[41.875696,-87.624207]">
* <heatmap-layer data="taxiData"></heatmap-layer>
* </map>
*/
(function() {
'use strict';
angular.module('ngMap').directive('heatmapLayer', [
'Attr2MapOptions', '$window', function(Attr2MapOptions, $window) {
var parser = Attr2MapOptions;
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
link: function(scope, element, attrs, mapController) {
mapController = mapController[0]||mapController[1];
var filtered = parser.filter(attrs);
/**
* set options
*/
var options = parser.getOptions(filtered, {scope: scope});
options.data = $window[attrs.data] || scope[attrs.data];
if (options.data instanceof Array) {
options.data = new google.maps.MVCArray(options.data);
} else {
throw "invalid heatmap data";
}
var layer = new google.maps.visualization.HeatmapLayer(options);
/**
* set events
*/
var events = parser.getEvents(scope, filtered);
void 0;
mapController.addObject('heatmapLayers', layer);
}
}; // return
}]);
})();
/**
* @ngdoc directive
* @name info-window
* @param Attr2MapOptions {service}
* convert html attribute to Google map api options
* @param $compile {service} $compile service
* @description
* Defines infoWindow and provides compile method
*
* Requires: map directive
*
* Restrict To: Element
*
* NOTE: this directive should **NOT** be used with `ng-repeat`
* because InfoWindow itself is a template, and a template must be
* reused by each marker, thus, should not be redefined repeatedly
* by `ng-repeat`.
*
* @attr {Boolean} visible
* Indicates to show it when map is initialized
* @attr {Boolean} visible-on-marker
* Indicates to show it on a marker when map is initialized
* @attr {Expression} geo-callback
* if position is an address, the expression is will be performed
* when geo-lookup is successful. e.g., geo-callback="showDetail()"
* @attr {String} <InfoWindowOption> Any InfoWindow options,
* https://developers.google.com/maps/documentation/javascript/reference?csw=1#InfoWindowOptions
* @attr {String} <InfoWindowEvent> Any InfoWindow events,
* https://developers.google.com/maps/documentation/javascript/reference
* @example
* Usage:
* <map MAP_ATTRIBUTES>
* <info-window id="foo" ANY_OPTIONS ANY_EVENTS"></info-window>
* </map>
*
* Example:
* <map center="41.850033,-87.6500523" zoom="3">
* <info-window id="1" position="41.850033,-87.6500523" >
* <div ng-non-bindable>
* Chicago, IL<br/>
* LatLng: {{chicago.lat()}}, {{chicago.lng()}}, <br/>
* World Coordinate: {{worldCoordinate.x}}, {{worldCoordinate.y}}, <br/>
* Pixel Coordinate: {{pixelCoordinate.x}}, {{pixelCoordinate.y}}, <br/>
* Tile Coordinate: {{tileCoordinate.x}}, {{tileCoordinate.y}} at Zoom Level {{map.getZoom()}}
* </div>
* </info-window>
* </map>
*/
/* global google */
(function() {
'use strict';
var infoWindow = function(Attr2MapOptions, $compile, $q, $templateRequest, $timeout, $parse, NgMap) {
var parser = Attr2MapOptions;
var getInfoWindow = function(options, events, element) {
var infoWindow;
/**
* set options
*/
if (options.position && !(options.position instanceof google.maps.LatLng)) {
delete options.position;
}
infoWindow = new google.maps.InfoWindow(options);
/**
* set events
*/
for (var eventName in events) {
if (eventName) {
google.maps.event.addListener(infoWindow, eventName, events[eventName]);
}
}
/**
* set template and template-related functions
* it must have a container element with ng-non-bindable
*/
var templatePromise = $q(function(resolve) {
if (angular.isString(element)) {
$templateRequest(element).then(function (requestedTemplate) {
resolve(angular.element(requestedTemplate).wrap('<div>').parent());
}, function(message) {
throw "info-window template request failed: " + message;
});
}
else {
resolve(element);
}
}).then(function(resolvedTemplate) {
var template = resolvedTemplate.html().trim();
if (angular.element(template).length != 1) {
throw "info-window working as a template must have a container";
}
infoWindow.__template = template.replace(/\s?ng-non-bindable[='"]+/,"");
});
infoWindow.__open = function(map, scope, anchor) {
templatePromise.then(function() {
$timeout(function() {
anchor && (scope.anchor = anchor);
var el = $compile(infoWindow.__template)(scope);
infoWindow.setContent(el[0]);
scope.$apply();
if (anchor && anchor.getPosition) {
infoWindow.open(map, anchor);
} else if (anchor && anchor instanceof google.maps.LatLng) {
infoWindow.open(map);
infoWindow.setPosition(anchor);
} else {
infoWindow.open(map);
}
var infoWindowContainerEl = infoWindow.content.parentElement.parentElement.parentElement;
infoWindowContainerEl.className = "ng-map-info-window";
});
});
};
return infoWindow;
};
var linkFunc = function(scope, element, attrs, mapController) {
mapController = mapController[0]||mapController[1];
element.css('display','none');
var orgAttrs = parser.orgAttributes(element);
var filtered = parser.filter(attrs);
var options = parser.getOptions(filtered, {scope: scope});
var events = parser.getEvents(scope, filtered);
var infoWindow = getInfoWindow(options, events, options.template || element);
var address;
if (options.position && !(options.position instanceof google.maps.LatLng)) {
address = options.position;
}
if (address) {
NgMap.getGeoLocation(address).then(function(latlng) {
infoWindow.setPosition(latlng);
infoWindow.__open(mapController.map, scope, latlng);
var geoCallback = attrs.geoCallback;
geoCallback && $parse(geoCallback)(scope);
});
}
mapController.addObject('infoWindows', infoWindow);
mapController.observeAttrSetObj(orgAttrs, attrs, infoWindow);
mapController.showInfoWindow =
mapController.map.showInfoWindow = mapController.showInfoWindow ||
function(p1, p2, p3) { //event, id, marker
var id = typeof p1 == 'string' ? p1 : p2;
var marker = typeof p1 == 'string' ? p2 : p3;
if (typeof marker == 'string') {
//Check if markers if defined to avoid odd 'undefined' errors
if (
typeof mapController.map.markers != "undefined"
&& typeof mapController.map.markers[marker] != "undefined") {
marker = mapController.map.markers[marker];
} else if (
//additionally check if that marker is a custom marker
typeof mapController.map.customMarkers !== "undefined"
&& typeof mapController.map.customMarkers[marker] !== "undefined") {
marker = mapController.map.customMarkers[marker];
} else {
//Better error output if marker with that id is not defined
throw new Error("Cant open info window for id " + marker + ". Marker or CustomMarker is not defined")
}
}
var infoWindow = mapController.map.infoWindows[id];
var anchor = marker ? marker : (this.getPosition ? this : null);
infoWindow.__open(mapController.map, scope, anchor);
if(mapController.singleInfoWindow) {
if(mapController.lastInfoWindow) {
scope.hideInfoWindow(mapController.lastInfoWindow);
}
mapController.lastInfoWindow = id;
}
};
mapController.hideInfoWindow =
mapController.map.hideInfoWindow = mapController.hideInfoWindow ||
function(p1, p2) {
var id = typeof p1 == 'string' ? p1 : p2;
var infoWindow = mapController.map.infoWindows[id];
infoWindow.close();
};
//TODO DEPRECATED
scope.showInfoWindow = mapController.map.showInfoWindow;
scope.hideInfoWindow = mapController.map.hideInfoWindow;
var map = infoWindow.mapId ? {id:infoWindow.mapId} : 0;
NgMap.getMap(map).then(function(map) {
infoWindow.visible && infoWindow.__open(map, scope);
if (infoWindow.visibleOnMarker) {
var markerId = infoWindow.visibleOnMarker;
infoWindow.__open(map, scope, map.markers[markerId]);
}
});
}; //link
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
link: linkFunc
};
}; // infoWindow
infoWindow.$inject =
['Attr2MapOptions', '$compile', '$q', '$templateRequest', '$timeout', '$parse', 'NgMap'];
angular.module('ngMap').directive('infoWindow', infoWindow);
})();
/**
* @ngdoc directive
* @name kml-layer
* @param Attr2MapOptions {service} convert html attribute to Google map api options
* @description
* renders Kml layer on a map
* Requires: map directive
* Restrict To: Element
*
* @attr {Url} url url of the kml layer
* @attr {KmlLayerOptions} KmlLayerOptions
* (https://developers.google.com/maps/documentation/javascript/reference#KmlLayerOptions)
* @attr {String} <KmlLayerEvent> Any KmlLayer events,
* https://developers.google.com/maps/documentation/javascript/reference
* @example
* Usage:
* <map MAP_ATTRIBUTES>
* <kml-layer ANY_KML_LAYER ANY_KML_LAYER_EVENTS"></kml-layer>
* </map>
*
* Example:
*
* <map zoom="11" center="[41.875696,-87.624207]">
* <kml-layer url="https://gmaps-samples.googlecode.com/svn/trunk/ggeoxml/cta.kml" >
* </kml-layer>
* </map>
*/
(function() {
'use strict';
angular.module('ngMap').directive('kmlLayer', [
'Attr2MapOptions', function(Attr2MapOptions) {
var parser = Attr2MapOptions;
var getKmlLayer = function(options, events) {
var kmlLayer = new google.maps.KmlLayer(options);
for (var eventName in events) {
google.maps.event.addListener(kmlLayer, eventName, events[eventName]);
}
return kmlLayer;
};
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
link: function(scope, element, attrs, mapController) {
mapController = mapController[0]||mapController[1];
var orgAttrs = parser.orgAttributes(element);
var filtered = parser.filter(attrs);
var options = parser.getOptions(filtered, {scope: scope});
var events = parser.getEvents(scope, filtered);
void 0;
var kmlLayer = getKmlLayer(options, events);
mapController.addObject('kmlLayers', kmlLayer);
mapController.observeAttrSetObj(orgAttrs, attrs, kmlLayer); //observers
element.bind('$destroy', function() {
mapController.deleteObject('kmlLayers', kmlLayer);
});
}
}; // return
}]);
})();
/**
* @ngdoc directive
* @name map-data
* @param Attr2MapOptions {service}
* convert html attribute to Google map api options
* @description
* set map data
* Requires: map directive
* Restrict To: Element
*
* @wn {String} method-name, run map.data[method-name] with attribute value
* @example
* Example:
*
* <map zoom="11" center="[41.875696,-87.624207]">
* <map-data load-geo-json="https://storage.googleapis.com/maps-devrel/google.json"></map-data>
* </map>
*/
(function() {
'use strict';
angular.module('ngMap').directive('mapData', [
'Attr2MapOptions', 'NgMap', function(Attr2MapOptions, NgMap) {
var parser = Attr2MapOptions;
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
link: function(scope, element, attrs, mapController) {
mapController = mapController[0] || mapController[1];
var filtered = parser.filter(attrs);
var options = parser.getOptions(filtered, {scope: scope});
var events = parser.getEvents(scope, filtered, events);
void 0;
NgMap.getMap(mapController.map.id).then(function(map) {
//options
for (var key in options) {
var val = options[key];
if (typeof scope[val] === "function") {
map.data[key](scope[val]);
} else {
map.data[key](val);
}
}
//events
for (var eventName in events) {
map.data.addListener(eventName, events[eventName]);
}
});
}
}; // return
}]);
})();
/**
* @ngdoc directive
* @name map-lazy-load
* @param Attr2Options {service} convert html attribute to Google map api options
* @description
* Requires: Delay the initialization of map directive
* until the map is ready to be rendered
* Restrict To: Attribute
*
* @attr {String} map-lazy-load
* Maps api script source file location.
* Example:
* 'https://maps.google.com/maps/api/js'
* @attr {String} map-lazy-load-params
* Maps api script source file location via angular scope variable.
* Also requires the map-lazy-load attribute to be present in the directive.
* Example: In your controller, set
* $scope.googleMapsURL = 'https://maps.google.com/maps/api/js?v=3.20&client=XXXXXenter-api-key-hereXXXX'
*
* @example
* Example:
*
* <div map-lazy-load="http://maps.google.com/maps/api/js">
* <map center="Brampton" zoom="10">
* <marker position="Brampton"></marker>
* </map>
* </div>
*
* <div map-lazy-load="http://maps.google.com/maps/api/js"
* map-lazy-load-params="{{googleMapsUrl}}">
* <map center="Brampton" zoom="10">
* <marker position="Brampton"></marker>
* </map>
* </div>
*/
/* global window, document */
(function() {
'use strict';
var $timeout, $compile, src, savedHtml = [], elements = [];
var preLinkFunc = function(scope, element, attrs) {
var mapsUrl = attrs.mapLazyLoadParams || attrs.mapLazyLoad;
if(window.google === undefined || window.google.maps === undefined) {
elements.push({
scope: scope,
element: element,
savedHtml: savedHtml[elements.length],
});
window.lazyLoadCallback = function() {
void 0;
$timeout(function() { /* give some time to load */
elements.forEach(function(elm) {
elm.element.html(elm.savedHtml);
$compile(elm.element.contents())(elm.scope);
});
}, 100);
};
var scriptEl = document.createElement('script');
void 0;
scriptEl.src = mapsUrl +
(mapsUrl.indexOf('?') > -1 ? '&' : '?') +
'callback=lazyLoadCallback';
if (!document.querySelector('script[src="' + scriptEl.src + '"]')) {
document.body.appendChild(scriptEl);
}
} else {
element.html(savedHtml);
$compile(element.contents())(scope);
}
};
var compileFunc = function(tElement, tAttrs) {
(!tAttrs.mapLazyLoad) && void 0;
savedHtml.push(tElement.html());
src = tAttrs.mapLazyLoad;
/**
* if already loaded, stop processing it
*/
if(window.google !== undefined && window.google.maps !== undefined) {
return false;
}
tElement.html(''); // will compile again after script is loaded
return {
pre: preLinkFunc
};
};
var mapLazyLoad = function(_$compile_, _$timeout_) {
$compile = _$compile_, $timeout = _$timeout_;
return {
compile: compileFunc
};
};
mapLazyLoad.$inject = ['$compile','$timeout'];
angular.module('ngMap').directive('mapLazyLoad', mapLazyLoad);
})();
/**
* @ngdoc directive
* @name map-type
* @param Attr2MapOptions {service}
* convert html attribute to Google map api options
* @description
* Requires: map directive
* Restrict To: Element
*
* @example
* Example:
*
* <map zoom="13" center="34.04924594193164, -118.24104309082031">
* <map-type name="coordinate" object="coordinateMapType"></map-type>
* </map>
*/
(function() {
'use strict';
angular.module('ngMap').directive('mapType', ['$parse', 'NgMap',
function($parse, NgMap) {
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
link: function(scope, element, attrs, mapController) {
mapController = mapController[0]||mapController[1];
var mapTypeName = attrs.name, mapTypeObject;
if (!mapTypeName) {
throw "invalid map-type name";
}
mapTypeObject = $parse(attrs.object)(scope);
if (!mapTypeObject) {
throw "invalid map-type object";
}
NgMap.getMap().then(function(map) {
map.mapTypes.set(mapTypeName, mapTypeObject);
});
mapController.addObject('mapTypes', mapTypeObject);
}
}; // return
}]);
})();
/**
* @ngdoc directive
* @memberof ngMap
* @name ng-map
* @param Attr2Options {service}
* convert html attribute to Google map api options
* @description
* Implementation of {@link __MapController}
* Initialize a Google map within a `<div>` tag
* with given options and register events
*
* @attr {Expression} map-initialized
* callback function when map is initialized
* e.g., map-initialized="mycallback(map)"
* @attr {Expression} geo-callback if center is an address or current location,
* the expression is will be executed when geo-lookup is successful.
* e.g., geo-callback="showMyStoreInfo()"
* @attr {Array} geo-fallback-center
* The center of map incase geolocation failed. i.e. [0,0]
* @attr {Object} geo-location-options
* The navigator geolocation options.
* e.g., { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }.
* If none specified, { timeout: 5000 }.
* If timeout not specified, timeout: 5000 added
* @attr {Boolean} zoom-to-include-markers
* When true, map boundary will be changed automatially
* to include all markers when initialized
* @attr {Boolean} default-style
* When false, the default styling,
* `display:block;height:300px`, will be ignored.
* @attr {String} <MapOption> Any Google map options,
* https://developers.google.com/maps/documentation/javascript/reference?csw=1#MapOptions
* @attr {String} <MapEvent> Any Google map events,
* https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/map_events.html
* @attr {Boolean} single-info-window
* When true the map will only display one info window at the time,
* if not set or false,
* everytime an info window is open it will be displayed with the othe one.
* @attr {Boolean} trigger-resize
* Default to false. Set to true to trigger resize of the map. Needs to be done anytime you resize the map
* @example
* Usage:
* <map MAP_OPTIONS_OR_MAP_EVENTS ..>
* ... Any children directives
* </map>
*
* Example:
* <map center="[40.74, -74.18]" on-click="doThat()">
* </map>
*
* <map geo-fallback-center="[40.74, -74.18]" zoom-to-inlude-markers="true">
* </map>
*/
(function () {
'use strict';
var mapDirective = function () {
return {
restrict: 'AE',
controller: '__MapController',
controllerAs: 'ngmap'
};
};
angular.module('ngMap').directive('map', [mapDirective]);
angular.module('ngMap').directive('ngMap', [mapDirective]);
})();
/**
* @ngdoc directive
* @name maps-engine-layer
* @description
* Requires: map directive
* Restrict To: Element
*
* @example
* Example:
* <map zoom="14" center="[59.322506, 18.010025]">
* <maps-engine-layer layer-id="06673056454046135537-08896501997766553811">
* </maps-engine-layer>
* </map>
*/
(function() {
'use strict';
angular.module('ngMap').directive('mapsEngineLayer', ['Attr2MapOptions', function(Attr2MapOptions) {
var parser = Attr2MapOptions;
var getMapsEngineLayer = function(options, events) {
var layer = new google.maps.visualization.MapsEngineLayer(options);
for (var eventName in events) {
google.maps.event.addListener(layer, eventName, events[eventName]);
}
return layer;
};
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
link: function(scope, element, attrs, mapController) {
mapController = mapController[0]||mapController[1];
var filtered = parser.filter(attrs);
var options = parser.getOptions(filtered, {scope: scope});
var events = parser.getEvents(scope, filtered, events);
void 0;
var layer = getMapsEngineLayer(options, events);
mapController.addObject('mapsEngineLayers', layer);
}
}; // return
}]);
})();
/**
* @ngdoc directive
* @name marker
* @param Attr2Options {service} convert html attribute to Google map api options
* @param NavigatorGeolocation It is used to find the current location
* @description
* Draw a Google map marker on a map with given options and register events
*
* Requires: map directive
*
* Restrict To: Element
*
* @attr {String} position address, 'current', or [latitude, longitude]
* example:
* '1600 Pennsylvania Ave, 20500 Washingtion DC',
* 'current position',
* '[40.74, -74.18]'
* @attr {Boolean} centered if set, map will be centered with this marker
* @attr {Expression} geo-callback if position is an address,
* the expression is will be performed when geo-lookup is successful.
* e.g., geo-callback="showStoreInfo()"
* @attr {Boolean} no-watcher if true, no attribute observer is added.
* Useful for many ng-repeat
* @attr {String} <MarkerOption>
* [Any Marker options](https://developers.google.com/maps/documentation/javascript/reference?csw=1#MarkerOptions)
* @attr {String} <MapEvent>
* [Any Marker events](https://developers.google.com/maps/documentation/javascript/reference)
* @example
* Usage:
* <map MAP_ATTRIBUTES>
* <marker ANY_MARKER_OPTIONS ANY_MARKER_EVENTS"></MARKER>
* </map>
*
* Example:
* <map center="[40.74, -74.18]">
* <marker position="[40.74, -74.18]" on-click="myfunc()"></div>
* </map>
*
* <map center="the cn tower">
* <marker position="the cn tower" on-click="myfunc()"></div>
* </map>
*/
/* global google */
(function() {
'use strict';
var parser, $parse, NgMap;
var getMarker = function(options, events) {
var marker;
if (NgMap.defaultOptions.marker) {
for (var key in NgMap.defaultOptions.marker) {
if (typeof options[key] == 'undefined') {
void 0;
options[key] = NgMap.defaultOptions.marker[key];
}
}
}
if (!(options.position instanceof google.maps.LatLng)) {
options.position = new google.maps.LatLng(0,0);
}
marker = new google.maps.Marker(options);
/**
* set events
*/
if (Object.keys(events).length > 0) {
void 0;
}
for (var eventName in events) {
if (eventName) {
google.maps.event.addListener(marker, eventName, events[eventName]);
}
}
return marker;
};
var linkFunc = function(scope, element, attrs, mapController) {
mapController = mapController[0]||mapController[1];
var orgAttrs = parser.orgAttributes(element);
var filtered = parser.filter(attrs);
var markerOptions = parser.getOptions(filtered, scope, {scope: scope});
var markerEvents = parser.getEvents(scope, filtered);
void 0;
var address;
if (!(markerOptions.position instanceof google.maps.LatLng)) {
address = markerOptions.position;
}
var marker = getMarker(markerOptions, markerEvents);
mapController.addObject('markers', marker);
if (address) {
NgMap.getGeoLocation(address).then(function(latlng) {
marker.setPosition(latlng);
markerOptions.centered && marker.map.setCenter(latlng);
var geoCallback = attrs.geoCallback;
geoCallback && $parse(geoCallback)(scope);
});
}
//set observers
mapController.observeAttrSetObj(orgAttrs, attrs, marker); /* observers */
element.bind('$destroy', function() {
mapController.deleteObject('markers', marker);
});
};
var marker = function(Attr2MapOptions, _$parse_, _NgMap_) {
parser = Attr2MapOptions;
$parse = _$parse_;
NgMap = _NgMap_;
return {
restrict: 'E',
require: ['^?map','?^ngMap'],
link: linkFunc
};
};
marker.$inject = ['Attr2MapOptions', '$parse', 'NgMap'];
angular.module('ngMap').directive('marker', marker);
})();
/**
* @ngdoc directive
* @name overlay-map-type
* @param Attr2MapOptions {service} convert html attribute to Google map api options
* @param $window {service}
* @description
* Requires: map directive
* Restrict To: Element
*
* @example
* Example:
*
* <map zoom="13" center="34.04924594193164, -118.24104309082031">
* <overlay-map-type index="0" object="coordinateMapType"></map-type>
* </map>
*/
(function() {
'use strict';
angular.module('ngMap').directive('overlayMapType', [
'NgMap', function(NgMap) {
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
link: function(scope, element, attrs, mapController) {
mapController = mapController[0]||mapController[1];
var initMethod = attrs.initMethod || "insertAt";
var overlayMapTypeObject = scope[attrs.object];
NgMap.getMap().then(function(map) {
if (initMethod == "insertAt") {
var index = parseInt(attrs.index, 10);
map.overlayMapTypes.insertAt(index, overlayMapTypeObject);
} else if (initMethod == "push") {
map.overlayMapTypes.push(overlayMapTypeObject);
}
});
mapController.addObject('overlayMapTypes', overlayMapTypeObject);
}
}; // return
}]);
})();
/**
* @ngdoc directive
* @name places-auto-complete
* @param Attr2MapOptions {service} convert html attribute to Google map api options
* @description
* Provides address auto complete feature to an input element
* Requires: input tag
* Restrict To: Attribute
*
* @attr {AutoCompleteOptions}
* [Any AutocompleteOptions](https://developers.google.com/maps/documentation/javascript/3.exp/reference#AutocompleteOptions)
*
* @example
* Example:
* <script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
* <input places-auto-complete types="['geocode']" on-place-changed="myCallback(place)" component-restrictions="{country:'au'}"/>
*/
/* global google */
(function() {
'use strict';
var placesAutoComplete = function(Attr2MapOptions, $timeout) {
var parser = Attr2MapOptions;
var linkFunc = function(scope, element, attrs, ngModelCtrl) {
if (attrs.placesAutoComplete ==='false') {
return false;
}
var filtered = parser.filter(attrs);
var options = parser.getOptions(filtered, {scope: scope});
var events = parser.getEvents(scope, filtered);
var autocomplete = new google.maps.places.Autocomplete(element[0], options);
for (var eventName in events) {
google.maps.event.addListener(autocomplete, eventName, events[eventName]);
}
var updateModel = function() {
$timeout(function(){
ngModelCtrl && ngModelCtrl.$setViewValue(element.val());
},100);
};
google.maps.event.addListener(autocomplete, 'place_changed', updateModel);
element[0].addEventListener('change', updateModel);
attrs.$observe('types', function(val) {
if (val) {
var optionValue = parser.toOptionValue(val, {key: 'types'});
autocomplete.setTypes(optionValue);
}
});
attrs.$observe('componentRestrictions', function (val) {
if (val) {
autocomplete.setComponentRestrictions(scope.$eval(val));
}
});
};
return {
restrict: 'A',
require: '?ngModel',
link: linkFunc
};
};
placesAutoComplete.$inject = ['Attr2MapOptions', '$timeout'];
angular.module('ngMap').directive('placesAutoComplete', placesAutoComplete);
})();
/**
* @ngdoc directive
* @name shape
* @param Attr2MapOptions {service} convert html attribute to Google map api options
* @description
* Initialize a Google map shape in map with given options and register events
* The shapes are:
* . circle
* . polygon
* . polyline
* . rectangle
* . groundOverlay(or image)
*
* Requires: map directive
*
* Restrict To: Element
*
* @attr {Boolean} centered if set, map will be centered with this marker
* @attr {Expression} geo-callback if shape is a circle and the center is
* an address, the expression is will be performed when geo-lookup
* is successful. e.g., geo-callback="showDetail()"
* @attr {String} <OPTIONS>
* For circle, [any circle options](https://developers.google.com/maps/documentation/javascript/reference#CircleOptions)
* For polygon, [any polygon options](https://developers.google.com/maps/documentation/javascript/reference#PolygonOptions)
* For polyline, [any polyline options](https://developers.google.com/maps/documentation/javascript/reference#PolylineOptions)
* For rectangle, [any rectangle options](https://developers.google.com/maps/documentation/javascript/reference#RectangleOptions)
* For image, [any groundOverlay options](https://developers.google.com/maps/documentation/javascript/reference#GroundOverlayOptions)
* @attr {String} <MapEvent> [Any Shape events](https://developers.google.com/maps/documentation/javascript/reference)
* @example
* Usage:
* <map MAP_ATTRIBUTES>
* <shape name=SHAPE_NAME ANY_SHAPE_OPTIONS ANY_SHAPE_EVENTS"></MARKER>
* </map>
*
* Example:
*
* <map zoom="11" center="[40.74, -74.18]">
* <shape id="polyline" name="polyline" geodesic="true"
* stroke-color="#FF0000" stroke-opacity="1.0" stroke-weight="2"
* path="[[40.74,-74.18],[40.64,-74.10],[40.54,-74.05],[40.44,-74]]" >
* </shape>
* </map>
*
* <map zoom="11" center="[40.74, -74.18]">
* <shape id="polygon" name="polygon" stroke-color="#FF0000"
* stroke-opacity="1.0" stroke-weight="2"
* paths="[[40.74,-74.18],[40.64,-74.18],[40.84,-74.08],[40.74,-74.18]]" >
* </shape>
* </map>
*
* <map zoom="11" center="[40.74, -74.18]">
* <shape id="rectangle" name="rectangle" stroke-color='#FF0000'
* stroke-opacity="0.8" stroke-weight="2"
* bounds="[[40.74,-74.18], [40.78,-74.14]]" editable="true" >
* </shape>
* </map>
*
* <map zoom="11" center="[40.74, -74.18]">
* <shape id="circle" name="circle" stroke-color='#FF0000'
* stroke-opacity="0.8"stroke-weight="2"
* center="[40.70,-74.14]" radius="4000" editable="true" >
* </shape>
* </map>
*
* <map zoom="11" center="[40.74, -74.18]">
* <shape id="image" name="image"
* url="https://www.lib.utexas.edu/maps/historical/newark_nj_1922.jpg"
* bounds="[[40.71,-74.22],[40.77,-74.12]]" opacity="0.7"
* clickable="true">
* </shape>
* </map>
*
* For full-working example, please visit
* [shape example](https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/shape.html)
*/
/* global google */
(function() {
'use strict';
var getShape = function(options, events) {
var shape;
var shapeName = options.name;
delete options.name; //remove name bcoz it's not for options
void 0;
/**
* set options
*/
switch(shapeName) {
case "circle":
if (!(options.center instanceof google.maps.LatLng)) {
options.center = new google.maps.LatLng(0,0);
}
shape = new google.maps.Circle(options);
break;
case "polygon":
shape = new google.maps.Polygon(options);
break;
case "polyline":
shape = new google.maps.Polyline(options);
break;
case "rectangle":
shape = new google.maps.Rectangle(options);
break;
case "groundOverlay":
case "image":
var url = options.url;
var opts = {opacity: options.opacity, clickable: options.clickable, id:options.id};
shape = new google.maps.GroundOverlay(url, options.bounds, opts);
break;
}
/**
* set events
*/
for (var eventName in events) {
if (events[eventName]) {
google.maps.event.addListener(shape, eventName, events[eventName]);
}
}
return shape;
};
var shape = function(Attr2MapOptions, $parse, NgMap) {
var parser = Attr2MapOptions;
var linkFunc = function(scope, element, attrs, mapController) {
mapController = mapController[0]||mapController[1];
var orgAttrs = parser.orgAttributes(element);
var filtered = parser.filter(attrs);
var shapeOptions = parser.getOptions(filtered, {scope: scope});
var shapeEvents = parser.getEvents(scope, filtered);
var address, shapeType;
shapeType = shapeOptions.name;
if (!(shapeOptions.center instanceof google.maps.LatLng)) {
address = shapeOptions.center;
}
var shape = getShape(shapeOptions, shapeEvents);
mapController.addObject('shapes', shape);
if (address && shapeType == 'circle') {
NgMap.getGeoLocation(address).then(function(latlng) {
shape.setCenter(latlng);
shape.centered && shape.map.setCenter(latlng);
var geoCallback = attrs.geoCallback;
geoCallback && $parse(geoCallback)(scope);
});
}
//set observers
mapController.observeAttrSetObj(orgAttrs, attrs, shape);
element.bind('$destroy', function() {
mapController.deleteObject('shapes', shape);
});
};
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
link: linkFunc
}; // return
};
shape.$inject = ['Attr2MapOptions', '$parse', 'NgMap'];
angular.module('ngMap').directive('shape', shape);
})();
/**
* @ngdoc directive
* @name streetview-panorama
* @param Attr2MapOptions {service} convert html attribute to Google map api options
* @description
* Requires: map directive
* Restrict To: Element
*
* @attr container Optional, id or css selector, if given, streetview will be in the given html element
* @attr {String} <StreetViewPanoramaOption>
* [Any Google StreetViewPanorama options](https://developers.google.com/maps/documentation/javascript/reference?csw=1#StreetViewPanoramaOptions)
* @attr {String} <StreetViewPanoramaEvent>
* [Any Google StreetViewPanorama events](https://developers.google.com/maps/documentation/javascript/reference#StreetViewPanorama)
*
* @example
* <map zoom="11" center="[40.688738,-74.043871]" >
* <street-view-panorama
* click-to-go="true"
* disable-default-ui="true"
* disable-double-click-zoom="true"
* enable-close-button="true"
* pano="my-pano"
* position="40.688738,-74.043871"
* pov="{heading:0, pitch: 90}"
* scrollwheel="false"
* visible="true">
* </street-view-panorama>
* </map>
*/
/* global google, document */
(function() {
'use strict';
var streetViewPanorama = function(Attr2MapOptions, NgMap) {
var parser = Attr2MapOptions;
var getStreetViewPanorama = function(map, options, events) {
var svp, container;
if (options.container) {
container = document.getElementById(options.container);
container = container || document.querySelector(options.container);
}
if (container) {
svp = new google.maps.StreetViewPanorama(container, options);
} else {
svp = map.getStreetView();
svp.setOptions(options);
}
for (var eventName in events) {
eventName &&
google.maps.event.addListener(svp, eventName, events[eventName]);
}
return svp;
};
var linkFunc = function(scope, element, attrs) {
var filtered = parser.filter(attrs);
var options = parser.getOptions(filtered, {scope: scope});
var controlOptions = parser.getControlOptions(filtered);
var svpOptions = angular.extend(options, controlOptions);
var svpEvents = parser.getEvents(scope, filtered);
void 0;
NgMap.getMap().then(function(map) {
var svp = getStreetViewPanorama(map, svpOptions, svpEvents);
map.setStreetView(svp);
(!svp.getPosition()) && svp.setPosition(map.getCenter());
google.maps.event.addListener(svp, 'position_changed', function() {
if (svp.getPosition() !== map.getCenter()) {
map.setCenter(svp.getPosition());
}
});
//needed for geo-callback
var listener =
google.maps.event.addListener(map, 'center_changed', function() {
svp.setPosition(map.getCenter());
google.maps.event.removeListener(listener);
});
});
}; //link
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
link: linkFunc
};
};
streetViewPanorama.$inject = ['Attr2MapOptions', 'NgMap'];
angular.module('ngMap').directive('streetViewPanorama', streetViewPanorama);
})();
/**
* @ngdoc directive
* @name traffic-layer
* @param Attr2MapOptions {service} convert html attribute to Google map api options
* @description
* Requires: map directive
* Restrict To: Element
*
* @example
* Example:
*
* <map zoom="13" center="34.04924594193164, -118.24104309082031">
* <traffic-layer></traffic-layer>
* </map>
*/
(function() {
'use strict';
angular.module('ngMap').directive('trafficLayer', [
'Attr2MapOptions', function(Attr2MapOptions) {
var parser = Attr2MapOptions;
var getLayer = function(options, events) {
var layer = new google.maps.TrafficLayer(options);
for (var eventName in events) {
google.maps.event.addListener(layer, eventName, events[eventName]);
}
return layer;
};
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
link: function(scope, element, attrs, mapController) {
mapController = mapController[0]||mapController[1];
var orgAttrs = parser.orgAttributes(element);
var filtered = parser.filter(attrs);
var options = parser.getOptions(filtered, {scope: scope});
var events = parser.getEvents(scope, filtered);
void 0;
var layer = getLayer(options, events);
mapController.addObject('trafficLayers', layer);
mapController.observeAttrSetObj(orgAttrs, attrs, layer); //observers
element.bind('$destroy', function() {
mapController.deleteObject('trafficLayers', layer);
});
}
}; // return
}]);
})();
/**
* @ngdoc directive
* @name transit-layer
* @param Attr2MapOptions {service} convert html attribute to Google map api options
* @description
* Requires: map directive
* Restrict To: Element
*
* @example
* Example:
*
* <map zoom="13" center="34.04924594193164, -118.24104309082031">
* <transit-layer></transit-layer>
* </map>
*/
(function() {
'use strict';
angular.module('ngMap').directive('transitLayer', [
'Attr2MapOptions', function(Attr2MapOptions) {
var parser = Attr2MapOptions;
var getLayer = function(options, events) {
var layer = new google.maps.TransitLayer(options);
for (var eventName in events) {
google.maps.event.addListener(layer, eventName, events[eventName]);
}
return layer;
};
return {
restrict: 'E',
require: ['?^map','?^ngMap'],
link: function(scope, element, attrs, mapController) {
mapController = mapController[0]||mapController[1];
var orgAttrs = parser.orgAttributes(element);
var filtered = parser.filter(attrs);
var options = parser.getOptions(filtered, {scope: scope});
var events = parser.getEvents(scope, filtered);
void 0;
var layer = getLayer(options, events);
mapController.addObject('transitLayers', layer);
mapController.observeAttrSetObj(orgAttrs, attrs, layer); //observers
element.bind('$destroy', function() {
mapController.deleteObject('transitLayers', layer);
});
}
}; // return
}]);
})();
/**
* @ngdoc filter
* @name camel-case
* @description
* Converts string to camel cased
*/
(function() {
'use strict';
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP = /^moz([A-Z])/;
var camelCaseFilter = function() {
return function(name) {
return name.
replace(SPECIAL_CHARS_REGEXP,
function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).
replace(MOZ_HACK_REGEXP, 'Moz$1');
};
};
angular.module('ngMap').filter('camelCase', camelCaseFilter);
})();
/**
* @ngdoc filter
* @name escape-regex
* @description
* Escapes all regex special characters in a string
*/
(function() {
'use strict';
var escapeRegexpFilter = function() {
return function(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
};
};
angular.module('ngMap').filter('escapeRegexp', escapeRegexpFilter);
})();
/**
* @ngdoc filter
* @name jsonize
* @description
* Converts json-like string to json string
*/
(function() {
'use strict';
var jsonizeFilter = function() {
return function(str) {
try { // if parsable already, return as it is
JSON.parse(str);
return str;
} catch(e) { // if not parsable, change little
return str
// wrap keys without quote with valid double quote
.replace(/([\$\w]+)\s*:/g,
function(_, $1) {
return '"'+$1+'":';
}
)
// replacing single quote wrapped ones to double quote
.replace(/'([^']+)'/g,
function(_, $1) {
return '"'+$1+'"';
}
)
.replace(/''/g, '""');
}
};
};
angular.module('ngMap').filter('jsonize', jsonizeFilter);
})();
/**
* @ngdoc service
* @name Attr2MapOptions
* @description
* Converts tag attributes to options used by google api v3 objects
*/
/* global google */
(function() {
'use strict';
//i.e. "2015-08-12T06:12:40.858Z"
var isoDateRE =
/^(\d{4}\-\d\d\-\d\d([tT][\d:\.]*)?)([zZ]|([+\-])(\d\d):?(\d\d))?$/;
var Attr2MapOptions = function(
$parse, $timeout, $log, $interpolate, NavigatorGeolocation, GeoCoder,
camelCaseFilter, jsonizeFilter, escapeRegExp
) {
var exprStartSymbol = $interpolate.startSymbol();
var exprEndSymbol = $interpolate.endSymbol();
/**
* Returns the attributes of an element as hash
* @memberof Attr2MapOptions
* @param {HTMLElement} el html element
* @returns {Hash} attributes
*/
var orgAttributes = function(el) {
(el.length > 0) && (el = el[0]);
var orgAttributes = {};
for (var i=0; i<el.attributes.length; i++) {
var attr = el.attributes[i];
orgAttributes[attr.name] = attr.value;
}
return orgAttributes;
};
var getJSON = function(input) {
var re =/^[\+\-]?[0-9\.]+,[ ]*\ ?[\+\-]?[0-9\.]+$/; //lat,lng
if (input.match(re)) {
input = "["+input+"]";
}
return JSON.parse(jsonizeFilter(input));
};
var getLatLng = function(input) {
var output = input;
if (input[0].constructor == Array) {
if ((input[0][0].constructor == Array && input[0][0].length == 2) || input[0][0].constructor == Object) {
var preoutput;
var outputArray = [];
for (var i = 0; i < input.length; i++) {
preoutput = input[i].map(function(el){
return new google.maps.LatLng(el[0], el[1]);
});
outputArray.push(preoutput);
}
output = outputArray;
} else {
output = input.map(function(el) {
return new google.maps.LatLng(el[0], el[1]);
});
}
} else if (!isNaN(parseFloat(input[0])) && isFinite(input[0])) {
output = new google.maps.LatLng(output[0], output[1]);
}
return output;
};
var toOptionValue = function(input, options) {
var output;
try { // 1. Number?
output = getNumber(input);
} catch(err) {
try { // 2. JSON?
var output = getJSON(input);
if (output instanceof Array) {
if (output[0].constructor == Object) {
output = output;
} else if (output[0] instanceof Array) {
if (output[0][0].constructor == Object) {
output = output;
} else {
output = getLatLng(output);
}
} else {
output = getLatLng(output);
}
}
// JSON is an object (not array or null)
else if (output === Object(output)) {
// check for nested hashes and convert to Google API options
var newOptions = options;
newOptions.doNotConverStringToNumber = true;
output = getOptions(output, newOptions);
}
} catch(err2) {
// 3. Google Map Object function Expression. i.e. LatLng(80,-49)
if (input.match(/^[A-Z][a-zA-Z0-9]+\(.*\)$/)) {
try {
var exp = "new google.maps."+input;
output = eval(exp); /* jshint ignore:line */
} catch(e) {
output = input;
}
// 4. Google Map Object constant Expression. i.e. MayTypeId.HYBRID
} else if (input.match(/^([A-Z][a-zA-Z0-9]+)\.([A-Z]+)$/)) {
try {
var matches = input.match(/^([A-Z][a-zA-Z0-9]+)\.([A-Z]+)$/);
output = google.maps[matches[1]][matches[2]];
} catch(e) {
output = input;
}
// 5. Google Map Object constant Expression. i.e. HYBRID
} else if (input.match(/^[A-Z]+$/)) {
try {
var capitalizedKey = options.key.charAt(0).toUpperCase() +
options.key.slice(1);
if (options.key.match(/temperatureUnit|windSpeedUnit|labelColor/)) {
capitalizedKey = capitalizedKey.replace(/s$/,"");
output = google.maps.weather[capitalizedKey][input];
} else {
output = google.maps[capitalizedKey][input];
}
} catch(e) {
output = input;
}
// 6. Date Object as ISO String
} else if (input.match(isoDateRE)) {
try {
output = new Date(input);
} catch(e) {
output = input;
}
// 7. evaluate dynamically bound values
} else if (input.match(new RegExp('^' + escapeRegExp(exprStartSymbol))) && options.scope) {
try {
var expr = input.replace(new RegExp(escapeRegExp(exprStartSymbol)),'').replace(new RegExp(escapeRegExp(exprEndSymbol), 'g'),'');
output = options.scope.$eval(expr);
} catch (err) {
output = input;
}
} else {
output = input;
}
} // catch(err2)
} // catch(err)
// convert output more for center and position
if (
(options.key == 'center' || options.key == 'position') &&
output instanceof Array
) {
output = new google.maps.LatLng(output[0], output[1]);
}
// convert output more for shape bounds
if (options.key == 'bounds' && output instanceof Array) {
output = new google.maps.LatLngBounds(output[0], output[1]);
}
// convert output more for shape icons
if (options.key == 'icons' && output instanceof Array) {
for (var i=0; i<output.length; i++) {
var el = output[i];
if (el.icon.path.match(/^[A-Z_]+$/)) {
el.icon.path = google.maps.SymbolPath[el.icon.path];
}
}
}
// convert output more for marker icon
if (options.key == 'icon' && output instanceof Object) {
if ((""+output.path).match(/^[A-Z_]+$/)) {
output.path = google.maps.SymbolPath[output.path];
}
for (var key in output) { //jshint ignore:line
var arr = output[key];
if (key == "anchor" || key == "origin" || key == "labelOrigin") {
output[key] = new google.maps.Point(arr[0], arr[1]);
} else if (key == "size" || key == "scaledSize") {
output[key] = new google.maps.Size(arr[0], arr[1]);
}
}
}
return output;
};
var getAttrsToObserve = function(attrs) {
var attrsToObserve = [];
var exprRegExp = new RegExp(escapeRegExp(exprStartSymbol) + '.*' + escapeRegExp(exprEndSymbol), 'g');
if (!attrs.noWatcher) {
for (var attrName in attrs) { //jshint ignore:line
var attrValue = attrs[attrName];
if (attrValue && attrValue.match(exprRegExp)) { // if attr value is {{..}}
attrsToObserve.push(camelCaseFilter(attrName));
}
}
}
return attrsToObserve;
};
/**
* filters attributes by skipping angularjs methods $.. $$..
* @memberof Attr2MapOptions
* @param {Hash} attrs tag attributes
* @returns {Hash} filterd attributes
*/
var filter = function(attrs) {
var options = {};
for(var key in attrs) {
if (key.match(/^\$/) || key.match(/^ng[A-Z]/)) {
void(0);
} else {
options[key] = attrs[key];
}
}
return options;
};
/**
* converts attributes hash to Google Maps API v3 options
* ```
* . converts numbers to number
* . converts class-like string to google maps instance
* i.e. `LatLng(1,1)` to `new google.maps.LatLng(1,1)`
* . converts constant-like string to google maps constant
* i.e. `MapTypeId.HYBRID` to `google.maps.MapTypeId.HYBRID`
* i.e. `HYBRID"` to `google.maps.MapTypeId.HYBRID`
* ```
* @memberof Attr2MapOptions
* @param {Hash} attrs tag attributes
* @param {Hash} options
* @returns {Hash} options converted attributess
*/
var getOptions = function(attrs, params) {
params = params || {};
var options = {};
for(var key in attrs) {
if (attrs[key] || attrs[key] === 0) {
if (key.match(/^on[A-Z]/)) { //skip events, i.e. on-click
continue;
} else if (key.match(/ControlOptions$/)) { // skip controlOptions
continue;
} else {
// nested conversions need to be typechecked
// (non-strings are fully converted)
if (typeof attrs[key] !== 'string') {
options[key] = attrs[key];
} else {
if (params.doNotConverStringToNumber &&
attrs[key].match(/^[0-9]+$/)
) {
options[key] = attrs[key];
} else {
options[key] = toOptionValue(attrs[key], {key: key, scope: params.scope});
}
}
}
} // if (attrs[key])
} // for(var key in attrs)
return options;
};
/**
* converts attributes hash to scope-specific event function
* @memberof Attr2MapOptions
* @param {scope} scope angularjs scope
* @param {Hash} attrs tag attributes
* @returns {Hash} events converted events
*/
var getEvents = function(scope, attrs) {
var events = {};
var toLowercaseFunc = function($1){
return "_"+$1.toLowerCase();
};
var EventFunc = function(attrValue) {
// funcName(argsStr)
var matches = attrValue.match(/([^\(]+)\(([^\)]*)\)/);
var funcName = matches[1];
var argsStr = matches[2].replace(/event[ ,]*/,''); //remove string 'event'
var argsExpr = $parse("["+argsStr+"]"); //for perf when triggering event
return function(event) {
var args = argsExpr(scope); //get args here to pass updated model values
function index(obj,i) {return obj[i];}
var f = funcName.split('.').reduce(index, scope);
f && f.apply(this, [event].concat(args));
$timeout( function() {
scope.$apply();
});
};
};
for(var key in attrs) {
if (attrs[key]) {
if (!key.match(/^on[A-Z]/)) { //skip if not events
continue;
}
//get event name as underscored. i.e. zoom_changed
var eventName = key.replace(/^on/,'');
eventName = eventName.charAt(0).toLowerCase() + eventName.slice(1);
eventName = eventName.replace(/([A-Z])/g, toLowercaseFunc);
var attrValue = attrs[key];
events[eventName] = new EventFunc(attrValue);
}
}
return events;
};
/**
* control means map controls, i.e streetview, pan, etc, not a general control
* @memberof Attr2MapOptions
* @param {Hash} filtered filtered tag attributes
* @returns {Hash} Google Map options
*/
var getControlOptions = function(filtered) {
var controlOptions = {};
if (typeof filtered != 'object') {
return false;
}
for (var attr in filtered) {
if (filtered[attr]) {
if (!attr.match(/(.*)ControlOptions$/)) {
continue; // if not controlOptions, skip it
}
//change invalid json to valid one, i.e. {foo:1} to {"foo": 1}
var orgValue = filtered[attr];
var newValue = orgValue.replace(/'/g, '"');
newValue = newValue.replace(/([^"]+)|("[^"]+")/g, function($0, $1, $2) {
if ($1) {
return $1.replace(/([a-zA-Z0-9]+?):/g, '"$1":');
} else {
return $2;
}
});
try {
var options = JSON.parse(newValue);
for (var key in options) { //assign the right values
if (options[key]) {
var value = options[key];
if (typeof value === 'string') {
value = value.toUpperCase();
} else if (key === "mapTypeIds") {
value = value.map( function(str) {
if (str.match(/^[A-Z]+$/)) { // if constant
return google.maps.MapTypeId[str.toUpperCase()];
} else { // else, custom map-type
return str;
}
});
}
if (key === "style") {
var str = attr.charAt(0).toUpperCase() + attr.slice(1);
var objName = str.replace(/Options$/,'')+"Style";
options[key] = google.maps[objName][value];
} else if (key === "position") {
options[key] = google.maps.ControlPosition[value];
} else {
options[key] = value;
}
}
}
controlOptions[attr] = options;
} catch (e) {
void 0;
}
}
} // for
return controlOptions;
};
return {
filter: filter,
getOptions: getOptions,
getEvents: getEvents,
getControlOptions: getControlOptions,
toOptionValue: toOptionValue,
getAttrsToObserve: getAttrsToObserve,
orgAttributes: orgAttributes
}; // return
};
Attr2MapOptions.$inject= [
'$parse', '$timeout', '$log', '$interpolate', 'NavigatorGeolocation', 'GeoCoder',
'camelCaseFilter', 'jsonizeFilter', 'escapeRegexpFilter'
];
angular.module('ngMap').service('Attr2MapOptions', Attr2MapOptions);
})();
/**
* @ngdoc service
* @name GeoCoder
* @description
* Provides [defered/promise API](https://docs.angularjs.org/api/ng/service/$q)
* service for Google Geocoder service
*/
(function() {
'use strict';
var $q;
/**
* @memberof GeoCoder
* @param {Hash} options
* https://developers.google.com/maps/documentation/geocoding/#geocoding
* @example
* ```
* GeoCoder.geocode({address: 'the cn tower'}).then(function(result) {
* //... do something with result
* });
* ```
* @returns {HttpPromise} Future object
*/
var geocodeFunc = function(options) {
var deferred = $q.defer();
var geocoder = new google.maps.Geocoder();
geocoder.geocode(options, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
deferred.resolve(results);
} else {
deferred.reject(status);
}
});
return deferred.promise;
};
var GeoCoder = function(_$q_) {
$q = _$q_;
return {
geocode : geocodeFunc
};
};
GeoCoder.$inject = ['$q'];
angular.module('ngMap').service('GeoCoder', GeoCoder);
})();
/**
* @ngdoc service
* @name GoogleMapsApi
* @description
* Load Google Maps API Service
*/
(function() {
'use strict';
var $q;
var $timeout;
var GoogleMapsApi = function(_$q_, _$timeout_) {
$q = _$q_;
$timeout = _$timeout_;
return {
/**
* Load google maps into document by creating a script tag
* @memberof GoogleMapsApi
* @param {string} mapsUrl
* @example
* GoogleMapsApi.load(myUrl).then(function() {
* console.log('google map has been loaded')
* });
*/
load: function (mapsUrl) {
var deferred = $q.defer();
if (window.google === undefined || window.google.maps === undefined) {
window.lazyLoadCallback = function() {
$timeout(function() { /* give some time to load */
deferred.resolve(window.google)
}, 100);
};
var scriptEl = document.createElement('script');
scriptEl.src = mapsUrl +
(mapsUrl.indexOf('?') > -1 ? '&' : '?') +
'callback=lazyLoadCallback';
if (!document.querySelector('script[src="' + scriptEl.src + '"]')) {
document.body.appendChild(scriptEl);
}
} else {
deferred.resolve(window.google)
}
return deferred.promise;
}
}
}
GoogleMapsApi.$inject = ['$q', '$timeout'];
angular.module('ngMap').service('GoogleMapsApi', GoogleMapsApi);
})();
/**
* @ngdoc service
* @name NavigatorGeolocation
* @description
* Provides [defered/promise API](https://docs.angularjs.org/api/ng/service/$q)
* service for navigator.geolocation methods
*/
/* global google */
(function() {
'use strict';
var $q;
/**
* @memberof NavigatorGeolocation
* @param {Object} geoLocationOptions the navigator geolocations options.
* i.e. { maximumAge: 3000, timeout: 5000, enableHighAccuracy: true }.
* If none specified, { timeout: 5000 }.
* If timeout not specified, timeout: 5000 added
* @param {function} success success callback function
* @param {function} failure failure callback function
* @example
* ```
* NavigatorGeolocation.getCurrentPosition()
* .then(function(position) {
* var lat = position.coords.latitude, lng = position.coords.longitude;
* .. do something lat and lng
* });
* ```
* @returns {HttpPromise} Future object
*/
var getCurrentPosition = function(geoLocationOptions) {
var deferred = $q.defer();
if (navigator.geolocation) {
if (geoLocationOptions === undefined) {
geoLocationOptions = { timeout: 5000 };
}
else if (geoLocationOptions.timeout === undefined) {
geoLocationOptions.timeout = 5000;
}
navigator.geolocation.getCurrentPosition(
function(position) {
deferred.resolve(position);
}, function(evt) {
void 0;
deferred.reject(evt);
},
geoLocationOptions
);
} else {
deferred.reject("Browser Geolocation service failed.");
}
return deferred.promise;
};
var NavigatorGeolocation = function(_$q_) {
$q = _$q_;
return {
getCurrentPosition: getCurrentPosition
};
};
NavigatorGeolocation.$inject = ['$q'];
angular.module('ngMap').
service('NavigatorGeolocation', NavigatorGeolocation);
})();
/**
* @ngdoc factory
* @name NgMapPool
* @description
* Provide map instance to avoid memory leak
*/
(function() {
'use strict';
/**
* @memberof NgMapPool
* @desc map instance pool
*/
var mapInstances = [];
var $window, $document, $timeout;
var add = function(el) {
var mapDiv = $document.createElement("div");
mapDiv.style.width = "100%";
mapDiv.style.height = "100%";
el.appendChild(mapDiv);
var map = new $window.google.maps.Map(mapDiv, {});
mapInstances.push(map);
return map;
};
var findById = function(el, id) {
var notInUseMap;
for (var i=0; i<mapInstances.length; i++) {
var map = mapInstances[i];
if (map.id == id && !map.inUse) {
var mapDiv = map.getDiv();
el.appendChild(mapDiv);
notInUseMap = map;
break;
}
}
return notInUseMap;
};
var findUnused = function(el) { //jshint ignore:line
var notInUseMap;
for (var i=0; i<mapInstances.length; i++) {
var map = mapInstances[i];
if (map.id) {
continue;
}
if (!map.inUse) {
var mapDiv = map.getDiv();
el.appendChild(mapDiv);
notInUseMap = map;
break;
}
}
return notInUseMap;
};
/**
* @memberof NgMapPool
* @function getMapInstance
* @param {HtmlElement} el map container element
* @return map instance for the given element
*/
var getMapInstance = function(el) {
var map = findById(el, el.id) || findUnused(el);
if (!map) {
map = add(el);
} else {
/* firing map idle event, which is used by map controller */
$timeout(function() {
google.maps.event.trigger(map, 'idle');
}, 100);
}
map.inUse = true;
return map;
};
/**
* @memberof NgMapPool
* @function returnMapInstance
* @param {Map} an instance of google.maps.Map
* @desc sets the flag inUse of the given map instance to false, so that it
* can be reused later
*/
var returnMapInstance = function(map) {
map.inUse = false;
};
/**
* @memberof NgMapPool
* @function resetMapInstances
* @desc resets mapInstance array
*/
var resetMapInstances = function() {
for(var i = 0;i < mapInstances.length;i++) {
mapInstances[i] = null;
}
mapInstances = [];
};
/**
* @memberof NgMapPool
* @function deleteMapInstance
* @desc delete a mapInstance
*/
var deleteMapInstance= function(mapId) {
for( var i=0; i<mapInstances.length; i++ ) {
if( (mapInstances[i] !== null) && (mapInstances[i].id == mapId)) {
mapInstances[i]= null;
mapInstances.splice( i, 1 );
}
}
};
var NgMapPool = function(_$document_, _$window_, _$timeout_) {
$document = _$document_[0], $window = _$window_, $timeout = _$timeout_;
return {
mapInstances: mapInstances,
resetMapInstances: resetMapInstances,
getMapInstance: getMapInstance,
returnMapInstance: returnMapInstance,
deleteMapInstance: deleteMapInstance
};
};
NgMapPool.$inject = [ '$document', '$window', '$timeout'];
angular.module('ngMap').factory('NgMapPool', NgMapPool);
})();
/**
* @ngdoc provider
* @name NgMap
* @description
* common utility service for ng-map
*/
(function() {
'use strict';
var $window, $document, $q;
var NavigatorGeolocation, Attr2MapOptions, GeoCoder, camelCaseFilter, NgMapPool;
var mapControllers = {};
var getStyle = function(el, styleProp) {
var y;
if (el.currentStyle) {
y = el.currentStyle[styleProp];
} else if ($window.getComputedStyle) {
y = $document.defaultView.
getComputedStyle(el, null).
getPropertyValue(styleProp);
}
return y;
};
/**
* @memberof NgMap
* @function initMap
* @param id optional, id of the map. default 0
*/
var initMap = function(id) {
var ctrl = mapControllers[id || 0];
if (!(ctrl.map instanceof google.maps.Map)) {
ctrl.initializeMap();
return ctrl.map;
} else {
void 0;
}
};
/**
* @memberof NgMap
* @function getMap
* @param {String} optional, id e.g., 'foo'
* @returns promise
*/
var getMap = function(id, options) {
options = options || {};
id = typeof id === 'object' ? id.id : id;
var deferred = $q.defer();
var timeout = options.timeout || 10000;
function waitForMap(timeElapsed){
var keys = Object.keys(mapControllers);
var theFirstController = mapControllers[keys[0]];
if(id && mapControllers[id]){
deferred.resolve(mapControllers[id].map);
} else if (!id && theFirstController && theFirstController.map) {
deferred.resolve(theFirstController.map);
} else if (timeElapsed > timeout) {
deferred.reject('could not find map');
} else {
$window.setTimeout( function(){
waitForMap(timeElapsed+100);
}, 100);
}
}
waitForMap(0);
return deferred.promise;
};
/**
* @memberof NgMap
* @function addMap
* @param mapController {__MapContoller} a map controller
* @returns promise
*/
var addMap = function(mapCtrl) {
if (mapCtrl.map) {
var len = Object.keys(mapControllers).length;
mapControllers[mapCtrl.map.id || len] = mapCtrl;
}
};
/**
* @memberof NgMap
* @function deleteMap
* @param mapController {__MapContoller} a map controller
*/
var deleteMap = function(mapCtrl) {
var len = Object.keys(mapControllers).length - 1;
var mapId = mapCtrl.map.id || len;
if (mapCtrl.map) {
for (var eventName in mapCtrl.eventListeners) {
void 0;
var listener = mapCtrl.eventListeners[eventName];
google.maps.event.removeListener(listener);
}
if (mapCtrl.map.controls) {
mapCtrl.map.controls.forEach(function(ctrl) {
ctrl.clear();
});
}
}
//Remove Heatmap Layers
if (mapCtrl.map.heatmapLayers) {
Object.keys(mapCtrl.map.heatmapLayers).forEach(function (layer) {
mapCtrl.deleteObject('heatmapLayers', mapCtrl.map.heatmapLayers[layer]);
});
}
NgMapPool.deleteMapInstance(mapId);
delete mapControllers[mapId];
};
/**
* @memberof NgMap
* @function getGeoLocation
* @param {String} address
* @param {Hash} options geo options
* @returns promise
*/
var getGeoLocation = function(string, options) {
var deferred = $q.defer();
if (!string || string.match(/^current/i)) { // current location
NavigatorGeolocation.getCurrentPosition(options).then(
function(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var latLng = new google.maps.LatLng(lat,lng);
deferred.resolve(latLng);
},
function(error) {
deferred.reject(error);
}
);
} else {
GeoCoder.geocode({address: string}).then(
function(results) {
deferred.resolve(results[0].geometry.location);
},
function(error) {
deferred.reject(error);
}
);
// var geocoder = new google.maps.Geocoder();
// geocoder.geocode(options, function (results, status) {
// if (status == google.maps.GeocoderStatus.OK) {
// deferred.resolve(results);
// } else {
// deferred.reject(status);
// }
// });
}
return deferred.promise;
};
/**
* @memberof NgMap
* @function observeAndSet
* @param {String} attrName attribute name
* @param {Object} object A Google maps object to be changed
* @returns attribue observe function
*/
var observeAndSet = function(attrName, object) {
void 0;
return function(val) {
if (val) {
var setMethod = camelCaseFilter('set-'+attrName);
var optionValue = Attr2MapOptions.toOptionValue(val, {key: attrName});
if (object[setMethod]) { //if set method does exist
void 0;
/* if an location is being observed */
if (attrName.match(/center|position/) &&
typeof optionValue == 'string') {
getGeoLocation(optionValue).then(function(latlng) {
object[setMethod](latlng);
});
} else {
object[setMethod](optionValue);
}
}
}
};
};
/**
* @memberof NgMap
* @function setStyle
* @param {HtmlElement} map contriner element
* @desc set display, width, height of map container element
*/
var setStyle = function(el) {
//if style is not given to the map element, set display and height
var defaultStyle = el.getAttribute('default-style');
if (defaultStyle == "true") {
el.style.display = 'block';
el.style.height = '300px';
} else {
if (getStyle(el, 'display') != "block") {
el.style.display = 'block';
}
if (getStyle(el, 'height').match(/^(0|auto)/)) {
el.style.height = '300px';
}
}
};
angular.module('ngMap').provider('NgMap', function() {
var defaultOptions = {};
/**
* @memberof NgMap
* @function setDefaultOptions
* @param {Hash} options
* @example
* app.config(function(NgMapProvider) {
* NgMapProvider.setDefaultOptions({
* marker: {
* optimized: false
* }
* });
* });
*/
this.setDefaultOptions = function(options) {
defaultOptions = options;
};
var NgMap = function(
_$window_, _$document_, _$q_,
_NavigatorGeolocation_, _Attr2MapOptions_,
_GeoCoder_, _camelCaseFilter_, _NgMapPool_
) {
$window = _$window_;
$document = _$document_[0];
$q = _$q_;
NavigatorGeolocation = _NavigatorGeolocation_;
Attr2MapOptions = _Attr2MapOptions_;
GeoCoder = _GeoCoder_;
camelCaseFilter = _camelCaseFilter_;
NgMapPool = _NgMapPool_;
return {
defaultOptions: defaultOptions,
addMap: addMap,
deleteMap: deleteMap,
getMap: getMap,
initMap: initMap,
setStyle: setStyle,
getGeoLocation: getGeoLocation,
observeAndSet: observeAndSet
};
};
NgMap.$inject = [
'$window', '$document', '$q',
'NavigatorGeolocation', 'Attr2MapOptions',
'GeoCoder', 'camelCaseFilter', 'NgMapPool'
];
this.$get = NgMap;
});
})();
/**
* @ngdoc service
* @name StreetView
* @description
* Provides [defered/promise API](https://docs.angularjs.org/api/ng/service/$q)
* service for [Google StreetViewService]
* (https://developers.google.com/maps/documentation/javascript/streetview)
*/
(function() {
'use strict';
var $q;
/**
* Retrieves panorama id from the given map (and or position)
* @memberof StreetView
* @param {map} map Google map instance
* @param {LatLng} latlng Google LatLng instance
* default: the center of the map
* @example
* StreetView.getPanorama(map).then(function(panoId) {
* $scope.panoId = panoId;
* });
* @returns {HttpPromise} Future object
*/
var getPanorama = function(map, latlng) {
latlng = latlng || map.getCenter();
var deferred = $q.defer();
var svs = new google.maps.StreetViewService();
svs.getPanoramaByLocation( (latlng||map.getCenter), 100,
function (data, status) {
// if streetView available
if (status === google.maps.StreetViewStatus.OK) {
deferred.resolve(data.location.pano);
} else {
// no street view available in this range, or some error occurred
deferred.resolve(false);
//deferred.reject('Geocoder failed due to: '+ status);
}
}
);
return deferred.promise;
};
/**
* Set panorama view on the given map with the panorama id
* @memberof StreetView
* @param {map} map Google map instance
* @param {String} panoId Panorama id fro getPanorama method
* @example
* StreetView.setPanorama(map, panoId);
*/
var setPanorama = function(map, panoId) {
var svp = new google.maps.StreetViewPanorama(
map.getDiv(), {enableCloseButton: true}
);
svp.setPano(panoId);
};
var StreetView = function(_$q_) {
$q = _$q_;
return {
getPanorama: getPanorama,
setPanorama: setPanorama
};
};
StreetView.$inject = ['$q'];
angular.module('ngMap').service('StreetView', StreetView);
})();
return 'ngMap';
})); | Cyb3rN4u7/Open-Weather-Map-Angular-App | app/js/ngmap/ng-map.no-dependency.js | JavaScript | mit | 107,117 |
module.exports = {
site: {
title: 'i18n node example',
description: 'An example for this module on node'
},
bankBalance: 'Hi {1}, your balance is {2}.',
transports: {
yacht: 'Yacht',
bike: 'Bike'
},
modeOfTransport: 'Your preferred mode of transport is by {1}.'
}; | DominicTobias/i18n-simple | examples/nodejs/locale/en-GB.js | JavaScript | mit | 278 |
var fs = require('co-fs')
, test = require('bandage')
, main = require('..')
, parse = main.parse
, write = main.write
, parseFmtpConfig = main.parseFmtpConfig
, parseParams = main.parseParams
, parseImageAttributes = main.parseImageAttributes
, parseSimulcastStreamList = main.parseSimulcastStreamList
;
test('normalSdp', function *(t) {
var sdp = yield fs.readFile(__dirname + '/normal.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length > 0, 'got media');
t.equal(session.origin.username, '-', 'origin username');
t.equal(session.origin.sessionId, 20518, 'origin sessionId');
t.equal(session.origin.sessionVersion, 0, 'origin sessionVersion');
t.equal(session.origin.netType, 'IN', 'origin netType');
t.equal(session.origin.ipVer, 4, 'origin ipVer');
t.equal(session.origin.address, '203.0.113.1', 'origin address');
t.equal(session.connection.ip, '203.0.113.1', 'session connect ip');
t.equal(session.connection.version, 4, 'session connect ip ver');
// global ICE and fingerprint
t.equal(session.iceUfrag, 'F7gI', 'global ufrag');
t.equal(session.icePwd, 'x9cml/YzichV2+XlhiMu8g', 'global pwd');
var audio = media[0];
t.equal(audio.type, 'audio', 'audio type');
t.equal(audio.port, 54400, 'audio port');
t.equal(audio.protocol, 'RTP/SAVPF', 'audio protocol');
t.equal(audio.direction, 'sendrecv', 'audio direction');
t.equal(audio.rtp[0].payload, 0, 'audio rtp 0 payload');
t.equal(audio.rtp[0].codec, 'PCMU', 'audio rtp 0 codec');
t.equal(audio.rtp[0].rate, 8000, 'audio rtp 0 rate');
t.equal(audio.rtp[1].payload, 96, 'audio rtp 1 payload');
t.equal(audio.rtp[1].codec, 'opus', 'audio rtp 1 codec');
t.equal(audio.rtp[1].rate, 48000, 'audio rtp 1 rate');
t.deepEqual(audio.ext[0], {
value: 1,
uri: 'URI-toffset'
}, 'audio extension 0');
t.deepEqual(audio.ext[1], {
value: 2,
direction: 'recvonly',
uri: 'URI-gps-string'
}, 'audio extension 1');
t.equal(audio.extmapAllowMixed, 'extmap-allow-mixed', 'extmap-allow-mixed present');
var video = media[1];
t.equal(video.type, 'video', 'video type');
t.equal(video.port, 55400, 'video port');
t.equal(video.protocol, 'RTP/SAVPF', 'video protocol');
t.equal(video.direction, 'sendrecv', 'video direction');
t.equal(video.rtp[0].payload, 97, 'video rtp 0 payload');
t.equal(video.rtp[0].codec, 'H264', 'video rtp 0 codec');
t.equal(video.rtp[0].rate, 90000, 'video rtp 0 rate');
t.equal(video.fmtp[0].payload, 97, 'video fmtp 0 payload');
var vidFmtp = parseFmtpConfig(video.fmtp[0].config);
t.equal(vidFmtp['profile-level-id'], '4d0028', 'video fmtp 0 profile-level-id');
t.equal(vidFmtp['packetization-mode'], 1, 'video fmtp 0 packetization-mode');
t.equal(vidFmtp['sprop-parameter-sets'], 'Z0IAH5WoFAFuQA==,aM48gA==',
'video fmtp 0 sprop-parameter-sets');
t.equal(video.fmtp[1].payload, 98, 'video fmtp 1 payload');
var vidFmtp2 = parseFmtpConfig(video.fmtp[1].config);
t.equal(vidFmtp2.minptime, 10, 'video fmtp 1 minptime');
t.equal(vidFmtp2.useinbandfec, 1, 'video fmtp 1 useinbandfec');
t.equal(video.rtp[1].payload, 98, 'video rtp 1 payload');
t.equal(video.rtp[1].codec, 'VP8', 'video rtp 1 codec');
t.equal(video.rtp[1].rate, 90000, 'video rtp 1 rate');
t.equal(video.rtcpFb[0].payload, '*', 'video rtcp-fb 0 payload');
t.equal(video.rtcpFb[0].type, 'nack', 'video rtcp-fb 0 type');
t.equal(video.rtcpFb[1].payload, 98, 'video rtcp-fb 0 payload');
t.equal(video.rtcpFb[1].type, 'nack', 'video rtcp-fb 0 type');
t.equal(video.rtcpFb[1].subtype, 'rpsi', 'video rtcp-fb 0 subtype');
t.equal(video.rtcpFbTrrInt[0].payload, 98, 'video rtcp-fb trr-int 0 payload');
t.equal(video.rtcpFbTrrInt[0].value, 100, 'video rtcp-fb trr-int 0 value');
t.equal(video.crypto[0].id, 1, 'video crypto 0 id');
t.equal(video.crypto[0].suite, 'AES_CM_128_HMAC_SHA1_32', 'video crypto 0 suite');
t.equal(video.crypto[0].config, 'inline:keNcG3HezSNID7LmfDa9J4lfdUL8W1F7TNJKcbuy|2^20|1:32', 'video crypto 0 config');
t.equal(video.ssrcs.length, 3, 'video got 3 ssrc lines');
// test ssrc with attr:value
t.deepEqual(video.ssrcs[0], {
id: 1399694169,
attribute: 'foo',
value: 'bar'
}, 'video 1st ssrc line attr:value');
// test ssrc with attr only
t.deepEqual(video.ssrcs[1], {
id: 1399694169,
attribute: 'baz',
}, 'video 2nd ssrc line attr only');
// test ssrc with at-tr:value
t.deepEqual(video.ssrcs[2], {
id: 1399694169,
attribute: 'foo-bar',
value: 'baz'
}, 'video 3rd ssrc line attr with dash');
// ICE candidates (same for both audio and video in this case)
[audio.candidates, video.candidates].forEach(function (cs, i) {
var str = (i === 0) ? 'audio ' : 'video ';
var port = (i === 0) ? 54400 : 55400;
t.equal(cs.length, 4, str + 'got 4 candidates');
t.equal(cs[0].foundation, 0, str + 'ice candidate 0 foundation');
t.equal(cs[0].component, 1, str + 'ice candidate 0 component');
t.equal(cs[0].transport, 'UDP', str + 'ice candidate 0 transport');
t.equal(cs[0].priority, 2113667327, str + 'ice candidate 0 priority');
t.equal(cs[0].ip, '203.0.113.1', str + 'ice candidate 0 ip');
t.equal(cs[0].port, port, str + 'ice candidate 0 port');
t.equal(cs[0].type, 'host', str + 'ice candidate 0 type');
t.equal(cs[1].foundation, 1, str + 'ice candidate 1 foundation');
t.equal(cs[1].component, 2, str + 'ice candidate 1 component');
t.equal(cs[1].transport, 'UDP', str + 'ice candidate 1 transport');
t.equal(cs[1].priority, 2113667326, str + 'ice candidate 1 priority');
t.equal(cs[1].ip, '203.0.113.1', str + 'ice candidate 1 ip');
t.equal(cs[1].port, port+1, str + 'ice candidate 1 port');
t.equal(cs[1].type, 'host', str + 'ice candidate 1 type');
t.equal(cs[2].foundation, 2, str + 'ice candidate 2 foundation');
t.equal(cs[2].component, 1, str + 'ice candidate 2 component');
t.equal(cs[2].transport, 'UDP', str + 'ice candidate 2 transport');
t.equal(cs[2].priority, 1686052607, str + 'ice candidate 2 priority');
t.equal(cs[2].ip, '203.0.113.1', str + 'ice candidate 2 ip');
t.equal(cs[2].port, port+2, str + 'ice candidate 2 port');
t.equal(cs[2].type, 'srflx', str + 'ice candidate 2 type');
t.equal(cs[2].raddr, '192.168.1.145', str + 'ice candidate 2 raddr');
t.equal(cs[2].rport, port+2, str + 'ice candidate 2 rport');
t.equal(cs[2].generation, 0, str + 'ice candidate 2 generation');
t.equal(cs[2]['network-id'], 3, str + 'ice candidate 2 network-id');
t.equal(cs[2]['network-cost'], (i === 0 ? 10 : undefined), str + 'ice candidate 2 network-cost');
t.equal(cs[3].foundation, 3, str + 'ice candidate 3 foundation');
t.equal(cs[3].component, 2, str + 'ice candidate 3 component');
t.equal(cs[3].transport, 'UDP', str + 'ice candidate 3 transport');
t.equal(cs[3].priority, 1686052606, str + 'ice candidate 3 priority');
t.equal(cs[3].ip, '203.0.113.1', str + 'ice candidate 3 ip');
t.equal(cs[3].port, port+3, str + 'ice candidate 3 port');
t.equal(cs[3].type, 'srflx', str + 'ice candidate 3 type');
t.equal(cs[3].raddr, '192.168.1.145', str + 'ice candidate 3 raddr');
t.equal(cs[3].rport, port+3, str + 'ice candidate 3 rport');
t.equal(cs[3].generation, 0, str + 'ice candidate 3 generation');
t.equal(cs[3]['network-id'], 3, str + 'ice candidate 3 network-id');
t.equal(cs[3]['network-cost'], (i === 0 ? 10 : undefined), str + 'ice candidate 3 network-cost');
});
t.equal(media.length, 2, 'got 2 m-lines');
});
/*
* Test for an sdp that started out as something from chrome
* it's since been hacked to include tests for other stuff
* ignore the name
*/
test('hackySdp', function *(t) {
var sdp = yield fs.readFile(__dirname + '/hacky.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length > 0, 'got media');
t.equal(session.origin.sessionId, '3710604898417546434', 'origin sessionId');
t.ok(session.groups, 'parsing session groups');
t.equal(session.groups.length, 1, 'one grouping');
t.equal(session.groups[0].type, 'BUNDLE', 'grouping is BUNDLE');
t.equal(session.groups[0].mids, 'audio video', 'bundling audio video');
t.ok(session.msidSemantic, 'have an msid semantic');
t.equal(session.msidSemantic.semantic, 'WMS', 'webrtc semantic');
t.equal(session.msidSemantic.token, 'Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV', 'semantic token');
// verify a=rtcp:65179 IN IP4 193.84.77.194
t.equal(media[0].rtcp.port, 1, 'rtcp port');
t.equal(media[0].rtcp.netType, 'IN', 'rtcp netType');
t.equal(media[0].rtcp.ipVer, 4, 'rtcp ipVer');
t.equal(media[0].rtcp.address, '0.0.0.0', 'rtcp address');
// verify ice tcp types
t.equal(media[0].candidates[0].tcptype, undefined, 'no tcptype');
t.equal(media[0].candidates[1].tcptype, 'active', 'active tcptype');
t.equal(media[0].candidates[1].transport, 'tcp', 'tcp transport');
t.equal(media[0].candidates[1].generation, 0, 'generation 0');
t.equal(media[0].candidates[1].type, 'host', 'tcp host');
t.equal(media[0].candidates[2].generation, undefined, 'no generation');
t.equal(media[0].candidates[2].type, 'host', 'tcp host');
t.equal(media[0].candidates[2].tcptype, 'active', 'active tcptype');
t.equal(media[0].candidates[3].tcptype, 'passive', 'passive tcptype');
t.equal(media[0].candidates[4].tcptype, 'so', 'so tcptype');
// raddr + rport + tcptype + generation
t.equal(media[0].candidates[5].type, 'srflx', 'tcp srflx');
t.equal(media[0].candidates[5].rport, 9, 'tcp rport');
t.equal(media[0].candidates[5].raddr, '10.0.1.1', 'tcp raddr');
t.equal(media[0].candidates[5].tcptype, 'active', 'active tcptype');
t.equal(media[0].candidates[6].tcptype, 'passive', 'passive tcptype');
t.equal(media[0].candidates[6].rport, 8998, 'tcp rport');
t.equal(media[0].candidates[6].raddr, '10.0.1.1', 'tcp raddr');
t.equal(media[0].candidates[6].generation, 5, 'tcp generation');
// and verify it works without specifying the ip
t.equal(media[1].rtcp.port, 12312, 'rtcp port');
t.equal(media[1].rtcp.netType, undefined, 'rtcp netType');
t.equal(media[1].rtcp.ipVer, undefined, 'rtcp ipVer');
t.equal(media[1].rtcp.address, undefined, 'rtcp address');
// verify a=rtpmap:126 telephone-event/8000
var lastRtp = media[0].rtp.length-1;
t.equal(media[0].rtp[lastRtp].codec, 'telephone-event', 'dtmf codec');
t.equal(media[0].rtp[lastRtp].rate, 8000, 'dtmf rate');
t.equal(media[0].iceOptions, 'google-ice', 'ice options parsed');
t.equal(media[0].ptime, 0.125, 'audio packet duration');
t.equal(media[0].maxptime, 60, 'maxptime parsed');
t.equal(media[0].rtcpMux, 'rtcp-mux', 'rtcp-mux present');
t.equal(media[0].rtp[0].codec, 'opus', 'audio rtp 0 codec');
t.equal(media[0].rtp[0].encoding, 2, 'audio rtp 0 encoding');
t.ok(media[0].ssrcs, 'have ssrc lines');
t.equal(media[0].ssrcs.length, 4, 'got 4 ssrc lines');
var ssrcs = media[0].ssrcs;
t.deepEqual(ssrcs[0], {
id: 2754920552,
attribute: 'cname',
value: 't9YU8M1UxTF8Y1A1'
}, '1st ssrc line');
t.deepEqual(ssrcs[1], {
id: 2754920552,
attribute: 'msid',
value: 'Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlVa0'
}, '2nd ssrc line');
t.deepEqual(ssrcs[2], {
id: 2754920552,
attribute: 'mslabel',
value: 'Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV'
}, '3rd ssrc line');
t.deepEqual(ssrcs[3], {
id: 2754920552,
attribute: 'label',
value: 'Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlVa0'
}, '4th ssrc line');
// verify a=sctpmap:5000 webrtc-datachannel 1024
t.ok(media[2].sctpmap, 'we have sctpmap');
t.equal(media[2].sctpmap.sctpmapNumber, 5000, 'sctpmap number is 5000');
t.equal(media[2].sctpmap.app, 'webrtc-datachannel', 'sctpmap app is webrtc-datachannel');
t.equal(media[2].sctpmap.maxMessageSize, 1024, 'sctpmap maxMessageSize is 1024');
// verify a=framerate:29.97
t.ok(media[2].framerate, 'we have framerate');
t.equal(media[2].framerate, 29.97, 'framerate is 29.97');
// verify a=label:1
t.ok(media[0].label, 'we have label');
t.equal(media[0].label, 1, 'label is 1');
});
test('iceliteSdp', function *(t) {
var sdp = yield fs.readFile(__dirname + '/icelite.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
t.equal(session.icelite, 'ice-lite', 'icelite parsed');
var rew = write(session);
t.ok(rew.indexOf('a=ice-lite\r\n') >= 0, 'got ice-lite');
t.ok(rew.indexOf('m=') > rew.indexOf('a=ice-lite'), 'session level icelite');
});
test('invalidSdp', function *(t) {
var sdp = yield fs.readFile(__dirname + '/invalid.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length > 0, 'got media');
// verify a=rtcp:65179 IN IP4 193.84.77.194
t.equal(media[0].rtcp.port, 1, 'rtcp port');
t.equal(media[0].rtcp.netType, 'IN', 'rtcp netType');
t.equal(media[0].rtcp.ipVer, 7, 'rtcp ipVer');
t.equal(media[0].rtcp.address, 'X', 'rtcp address');
t.equal(media[0].invalid.length, 1, 'found exactly 1 invalid line'); // f= lost
t.equal(media[0].invalid[0].value, 'goo:hithere', 'copied verbatim');
});
test('jssipSdp', function *(t) {
var sdp = yield fs.readFile(__dirname + '/jssip.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length > 0, 'got media');
var audio = media[0];
var audCands = audio.candidates;
t.equal(audCands.length, 6, '6 candidates');
// testing ice optionals:
t.deepEqual(audCands[0],
{
foundation: 1162875081,
component: 1,
transport: 'udp',
priority: 2113937151,
ip: '192.168.34.75',
port: 60017,
type: 'host',
generation: 0,
},
'audio candidate 0'
);
t.deepEqual(audCands[2],
{
foundation: 3289912957,
component: 1,
transport: 'udp',
priority: 1845501695,
ip: '193.84.77.194',
port: 60017,
type: 'srflx',
raddr: '192.168.34.75',
rport: 60017,
generation: 0,
},
'audio candidate 2 (raddr rport)'
);
t.deepEqual(audCands[4],
{
foundation: 198437945,
component: 1,
transport: 'tcp',
priority: 1509957375,
ip: '192.168.34.75',
port: 0,
type: 'host',
generation: 0
},
'audio candidate 4 (tcp)'
);
});
test('jsepSdp', function *(t) {
var sdp = yield fs.readFile(__dirname + '/jsep.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length === 2, 'got media');
var video = media[1];
t.equal(video.ssrcGroups.length, 1, '1 ssrc grouping');
t.deepEqual(video.ssrcGroups[0],
{
semantics: 'FID',
ssrcs: '1366781083 1366781084'
},
'ssrc-group'
);
t.equal(video.msid,
'61317484-2ed4-49d7-9eb7-1414322a7aae f30bdb4a-5db8-49b5-bcdc-e0c9a23172e0'
, 'msid'
);
t.ok(video.rtcpRsize, 'rtcp-rsize present');
t.ok(video.bundleOnly, 'bundle-only present');
// video contains 'a=end-of-candidates'
// we want to ensure this comes after the candidate lines
// so this is the only place we actually test the writer in here
t.ok(video.endOfCandidates, 'have end of candidates marker');
var rewritten = write(session).split('\r\n');
var idx = rewritten.indexOf('a=end-of-candidates');
t.equal(rewritten[idx-1].slice(0, 11), 'a=candidate', 'marker after candidate');
});
test('alacSdp', function *(t) {
var sdp = yield fs.readFile(__dirname + '/alac.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length > 0, 'got media');
var audio = media[0];
t.equal(audio.type, 'audio', 'audio type');
t.equal(audio.protocol, 'RTP/AVP', 'audio protocol');
t.equal(audio.fmtp[0].payload, 96, 'audio fmtp 0 payload');
t.equal(audio.fmtp[0].config, '352 0 16 40 10 14 2 255 0 0 44100', 'audio fmtp 0 config');
t.equal(audio.rtp[0].payload, 96, 'audio rtp 0 payload');
t.equal(audio.rtp[0].codec, 'AppleLossless', 'audio rtp 0 codec');
t.equal(audio.rtp[0].rate, undefined, 'audio rtp 0 rate');
t.equal(audio.rtp[0].encoding, undefined, 'audio rtp 0 encoding');
});
test('onvifSdp', function *(t) {
var sdp = yield fs.readFile(__dirname + '/onvif.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length > 0, 'got media');
var audio = media[0];
t.equal(audio.type, 'audio', 'audio type');
t.equal(audio.port, 0, 'audio port');
t.equal(audio.protocol, 'RTP/AVP', 'audio protocol');
t.equal(audio.control, 'rtsp://example.com/onvif_camera/audio', 'audio control');
t.equal(audio.payloads, 0, 'audio payloads');
var video = media[1];
t.equal(video.type, 'video', 'video type');
t.equal(video.port, 0, 'video port');
t.equal(video.protocol, 'RTP/AVP', 'video protocol');
t.equal(video.control, 'rtsp://example.com/onvif_camera/video', 'video control');
t.equal(video.payloads, 26, 'video payloads');
var application = media[2];
t.equal(application.type, 'application', 'application type');
t.equal(application.port, 0, 'application port');
t.equal(application.protocol, 'RTP/AVP', 'application protocol');
t.equal(application.control, 'rtsp://example.com/onvif_camera/metadata', 'application control');
t.equal(application.payloads, 107, 'application payloads');
t.equal(application.direction, 'recvonly', 'application direction');
t.equal(application.rtp[0].payload, 107, 'application rtp 0 payload');
t.equal(application.rtp[0].codec, 'vnd.onvif.metadata', 'application rtp 0 codec');
t.equal(application.rtp[0].rate, 90000, 'application rtp 0 rate');
t.equal(application.rtp[0].encoding, undefined, 'application rtp 0 encoding');
});
test('ssrcSdp', function *(t) {
var sdp = yield fs.readFile(__dirname + '/ssrc.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length > 0, 'got media');
var video = media[1];
t.equal(video.ssrcGroups.length, 2, 'video got 2 ssrc-group lines');
var expectedSsrc = [
{ semantics: 'FID', ssrcs: '3004364195 1126032854' },
{ semantics: 'FEC-FR', ssrcs: '3004364195 1080772241' }
];
t.deepEqual(video.ssrcGroups, expectedSsrc, 'video ssrc-group obj');
});
test('simulcastSdp', function *(t) {
var sdp = yield fs.readFile(__dirname + '/simulcast.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length > 0, 'got media');
var video = media[1];
t.equal(video.type, 'video', 'video type');
// test rid lines
t.equal(video.rids.length, 5, 'video got 5 rid lines');
// test rid 1
t.deepEqual(video.rids[0], {
id: 1,
direction: 'send',
params: 'pt=97;max-width=1280;max-height=720;max-fps=30'
}, 'video 1st rid line');
// test rid 2
t.deepEqual(video.rids[1], {
id: 2,
direction: 'send',
params: 'pt=98'
}, 'video 2nd rid line');
// test rid 3
t.deepEqual(video.rids[2], {
id: 3,
direction: 'send',
params: 'pt=99'
}, 'video 3rd rid line');
// test rid 4
t.deepEqual(video.rids[3], {
id: 4,
direction: 'send',
params: 'pt=100'
}, 'video 4th rid line');
// test rid 5
t.deepEqual(video.rids[4], {
id: 'c',
direction: 'recv',
params: 'pt=97'
}, 'video 5th rid line');
// test rid 1 params
var rid1Params = parseParams(video.rids[0].params);
t.deepEqual(rid1Params, {
'pt': 97,
'max-width': 1280,
'max-height': 720,
'max-fps': 30
}, 'video 1st rid params');
// test rid 2 params
var rid2Params = parseParams(video.rids[1].params);
t.deepEqual(rid2Params, {
'pt': 98
}, 'video 2nd rid params');
// test rid 3 params
var rid3Params = parseParams(video.rids[2].params);
t.deepEqual(rid3Params, {
'pt': 99
}, 'video 3rd rid params');
// test rid 4 params
var rid4Params = parseParams(video.rids[3].params);
t.deepEqual(rid4Params, {
'pt': 100
}, 'video 4th rid params');
// test rid 5 params
var rid5Params = parseParams(video.rids[4].params);
t.deepEqual(rid5Params, {
'pt': 97
}, 'video 5th rid params');
// test imageattr lines
t.equal(video.imageattrs.length, 5, 'video got 5 imageattr lines');
// test imageattr 1
t.deepEqual(video.imageattrs[0], {
pt: 97,
dir1: 'send',
attrs1: '[x=1280,y=720]',
dir2: 'recv',
attrs2: '[x=1280,y=720] [x=320,y=180] [x=160,y=90]'
}, 'video 1st imageattr line');
// test imageattr 2
t.deepEqual(video.imageattrs[1], {
pt: 98,
dir1: 'send',
attrs1: '[x=320,y=180]'
}, 'video 2nd imageattr line');
// test imageattr 3
t.deepEqual(video.imageattrs[2], {
pt: 99,
dir1: 'send',
attrs1: '[x=160,y=90]'
}, 'video 3rd imageattr line');
// test imageattr 4
t.deepEqual(video.imageattrs[3], {
pt: 100,
dir1: 'recv',
attrs1: '[x=1280,y=720] [x=320,y=180]',
dir2: 'send',
attrs2: '[x=1280,y=720]'
}, 'video 4th imageattr line');
// test imageattr 5
t.deepEqual(video.imageattrs[4], {
pt: '*',
dir1: 'recv',
attrs1: '*'
}, 'video 5th imageattr line');
// test imageattr 1 send params
var imageattr1SendParams = parseImageAttributes(video.imageattrs[0].attrs1);
t.deepEqual(imageattr1SendParams, [
{'x': 1280, 'y': 720}
], 'video 1st imageattr send params');
// test imageattr 1 recv params
var imageattr1RecvParams = parseImageAttributes(video.imageattrs[0].attrs2);
t.deepEqual(imageattr1RecvParams, [
{'x': 1280, 'y': 720},
{'x': 320, 'y': 180},
{'x': 160, 'y': 90},
], 'video 1st imageattr recv params');
// test imageattr 2 send params
var imageattr2SendParams = parseImageAttributes(video.imageattrs[1].attrs1);
t.deepEqual(imageattr2SendParams, [
{'x': 320, 'y': 180}
], 'video 2nd imageattr send params');
// test imageattr 3 send params
var imageattr3SendParams = parseImageAttributes(video.imageattrs[2].attrs1);
t.deepEqual(imageattr3SendParams, [
{'x': 160, 'y': 90}
], 'video 3rd imageattr send params');
// test imageattr 4 recv params
var imageattr4RecvParams = parseImageAttributes(video.imageattrs[3].attrs1);
t.deepEqual(imageattr4RecvParams, [
{'x': 1280, 'y': 720},
{'x': 320, 'y': 180},
], 'video 4th imageattr recv params');
// test imageattr 4 send params
var imageattr4SendParams = parseImageAttributes(video.imageattrs[3].attrs2);
t.deepEqual(imageattr4SendParams, [
{'x': 1280, 'y': 720}
], 'video 4th imageattr send params');
// test imageattr 5 recv params
t.equal(video.imageattrs[4].attrs1, '*', 'video 5th imageattr recv params');
// test simulcast line
t.deepEqual(video.simulcast, {
dir1: 'send',
list1: '1,~4;2;3',
dir2: 'recv',
list2: 'c'
}, 'video simulcast line');
// test simulcast send streams
var simulcastSendStreams = parseSimulcastStreamList(video.simulcast.list1);
t.deepEqual(simulcastSendStreams, [
[ {scid: 1, paused: false}, {scid: 4, paused: true} ],
[ {scid: 2, paused: false} ],
[ {scid: 3, paused: false} ]
], 'video simulcast send streams');
// test simulcast recv streams
var simulcastRecvStreams = parseSimulcastStreamList(video.simulcast.list2);
t.deepEqual(simulcastRecvStreams, [
[ {scid: 'c', paused: false} ]
], 'video simulcast recv streams');
// test simulcast version 03 line
// test simulcast line
t.deepEqual(video.simulcast_03, {
value: 'send rid=1,4;2;3 paused=4 recv rid=c'
}, 'video simulcast draft 03 line');
});
test('ST2022-6', function *(t) {
var sdp = yield fs.readFile(__dirname + '/st2022-6.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length > 0, 'got media');
var video = media[0];
var sourceFilter = video.sourceFilter;
t.equal(sourceFilter.filterMode, 'incl', 'filter-mode is "incl"');
t.equal(sourceFilter.netType, 'IN', 'nettype is "IN"');
t.equal(sourceFilter.addressTypes, 'IP4', 'address-type is "IP4"');
t.equal(sourceFilter.destAddress, '239.0.0.1', 'dest-address is "239.0.0.1"');
t.equal(sourceFilter.srcList, '192.168.20.20', 'src-list is "192.168.20.20"');
});
test('ST2110-20', function* (t) {
var sdp = yield fs.readFile(__dirname + '/st2110-20.sdp', 'utf8');
var session = parse(sdp + '');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length > 0, 'got media');
var video = media[0];
var sourceFilter = video.sourceFilter;
t.equal(sourceFilter.filterMode, 'incl', 'filter-mode is "incl"');
t.equal(sourceFilter.netType, 'IN', 'nettype is "IN"');
t.equal(sourceFilter.addressTypes, 'IP4', 'address-type is "IP4"');
t.equal(sourceFilter.destAddress, '239.100.9.10', 'dest-address is "239.100.9.10"');
t.equal(sourceFilter.srcList, '192.168.100.2', 'src-list is "192.168.100.2"');
t.equal(video.type, 'video', 'video type');
var fmtp0Params = parseParams(video.fmtp[0].config);
t.deepEqual(fmtp0Params, {
sampling: 'YCbCr-4:2:2',
width: 1280,
height: 720,
interlace: undefined,
exactframerate: '60000/1001',
depth: 10,
TCS: 'SDR',
colorimetry: 'BT709',
PM: '2110GPM',
SSN: 'ST2110-20:2017'
}, 'video 5th rid params');
});
test('SCTP-DTLS-26', function* (t) {
var sdp = yield fs.readFile(__dirname + '/sctp-dtls-26.sdp', 'utf8');
var session = parse(sdp + '');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length > 0, 'got media');
t.equal(session.origin.sessionId, '5636137646675714991', 'origin sessionId');
t.ok(session.groups, 'parsing session groups');
t.equal(session.groups.length, 1, 'one grouping');
t.equal(session.groups[0].type, 'BUNDLE', 'grouping is BUNDLE');
t.equal(session.groups[0].mids, 'data', 'bundling data');
t.ok(session.msidSemantic, 'have an msid semantic');
t.equal(session.msidSemantic.semantic, 'WMS', 'webrtc semantic');
// verify media is data application
t.equal(media[0].type, 'application', 'media type application');
t.equal(media[0].mid, 'data', 'media id pplication');
// verify protocol and ports
t.equal(media[0].protocol, 'UDP/DTLS/SCTP', 'protocol is UDP/DTLS/SCTP');
t.equal(media[0].port, 9, 'the UDP port value is 9');
t.equal(media[0].sctpPort, 5000, 'the offerer/answer SCTP port value is 5000');
// verify maxMessageSize
t.equal(media[0].maxMessageSize, 10000, 'maximum message size is 10000');
});
test('extmapEncryptSdp', function *(t) {
var sdp = yield fs.readFile(__dirname + '/extmap-encrypt.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length > 0, 'got media');
t.equal(session.origin.username, '-', 'origin username');
t.equal(session.origin.sessionId, 20518, 'origin sessionId');
t.equal(session.origin.sessionVersion, 0, 'origin sessionVersion');
t.equal(session.origin.netType, 'IN', 'origin netType');
t.equal(session.origin.ipVer, 4, 'origin ipVer');
t.equal(session.origin.address, '203.0.113.1', 'origin address');
t.equal(session.connection.ip, '203.0.113.1', 'session connect ip');
t.equal(session.connection.version, 4, 'session connect ip ver');
var audio = media[0];
t.equal(audio.type, 'audio', 'audio type');
t.equal(audio.port, 54400, 'audio port');
t.equal(audio.protocol, 'RTP/SAVPF', 'audio protocol');
t.equal(audio.rtp[0].payload, 96, 'audio rtp 0 payload');
t.equal(audio.rtp[0].codec, 'opus', 'audio rtp 0 codec');
t.equal(audio.rtp[0].rate, 48000, 'audio rtp 0 rate');
// extmap and encrypted extmap
t.deepEqual(audio.ext[0], {
value: 1,
direction: 'sendonly',
uri: 'URI-toffset'
}, 'audio extension 0');
t.deepEqual(audio.ext[1], {
value: 2,
uri: 'urn:ietf:params:rtp-hdrext:toffset'
}, 'audio extension 1');
t.deepEqual(audio.ext[2], {
value: 3,
'encrypt-uri': 'urn:ietf:params:rtp-hdrext:encrypt',
uri: 'urn:ietf:params:rtp-hdrext:smpte-tc',
config: '25@600/24'
}, 'audio extension 2');
t.deepEqual(audio.ext[3], {
value: 4,
direction: 'recvonly',
'encrypt-uri': 'urn:ietf:params:rtp-hdrext:encrypt',
uri: 'URI-gps-string'
}, 'audio extension 3');
t.equal(media.length, 1, 'got 1 m-lines');
});
test('dante-aes67', function *(t) {
var sdp = yield fs.readFile(__dirname + '/dante-aes67.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length == 1, 'got single media');
t.equal(session.origin.username, '-', 'origin username');
t.equal(session.origin.sessionId, 1423986, 'origin sessionId');
t.equal(session.origin.sessionVersion, 1423994, 'origin sessionVersion');
t.equal(session.origin.netType, 'IN', 'origin netType');
t.equal(session.origin.ipVer, 4, 'origin ipVer');
t.equal(session.origin.address, '169.254.98.63', 'origin address');
t.equal(session.name, 'AOIP44-serial-1614 : 2', 'Session Name');
t.equal(session.keywords, 'Dante', 'Keywords');
t.equal(session.connection.ip, '239.65.125.63/32', 'session connect ip');
t.equal(session.connection.version, 4, 'session connect ip ver');
var audio = media[0];
t.equal(audio.type, 'audio', 'audio type');
t.equal(audio.port, 5004, 'audio port');
t.equal(audio.protocol, 'RTP/AVP', 'audio protocol');
t.equal(audio.direction, 'recvonly', 'audio direction');
t.equal(audio.description, '2 channels: TxChan 0, TxChan 1', 'audio description');
t.equal(audio.ptime, 1, 'audio packet duration');
t.equal(audio.rtp[0].payload, 97, 'audio rtp payload type');
t.equal(audio.rtp[0].codec, 'L24', 'audio rtp codec');
t.equal(audio.rtp[0].rate, 48000, 'audio sample rate');
t.equal(audio.rtp[0].encoding, 2, 'audio channels');
});
test('bfcp', function *(t) {
var sdp = yield fs.readFile(__dirname + '/bfcp.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length == 4, 'got 4 media');
t.equal(session.origin.username, '-', 'origin username');
var audio = media[0];
t.equal(audio.type, 'audio', 'audio type');
var video = media[1];
t.equal(video.type, 'video', 'main video type');
t.equal(video.direction, 'sendrecv', 'main video direction');
t.equal(video.content, 'main', 'main video content');
t.equal(video.label, 1, 'main video label');
var app = media[2];
t.equal(app.type, 'application', 'application type');
t.equal(app.port, 3238, 'application port');
t.equal(app.protocol, 'UDP/BFCP', 'bfcp protocol');
t.equal(app.payloads, '*', 'bfcp payloads');
t.equal(app.connectionType, 'new', 'connection type');
t.equal(app.bfcpFloorCtrl, 's-only', 'bfcp Floor Control');
t.equal(app.bfcpConfId, 1, 'bfcp ConfId');
t.equal(app.bfcpUserId, 1, 'bfcp UserId');
t.equal(app.bfcpFloorId.id, 1, 'bfcp FloorId');
t.equal(app.bfcpFloorId.mStream, 3, 'bfcp Floor Stream');
var video2 = media[3];
t.equal(video2.type, 'video', '2nd video type');
t.equal(video2.direction, 'sendrecv', '2nd video direction');
t.equal(video2.content, 'slides', '2nd video content');
t.equal(video2.label, 3, '2nd video label');
});
test('tcp-active', function *(t) {
var sdp = yield fs.readFile(__dirname + '/tcp-active.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length == 1, 'got single media');
t.equal(session.origin.username, '-', 'origin username');
t.equal(session.origin.sessionId, 1562876543, 'origin sessionId');
t.equal(session.origin.sessionVersion, 11, 'origin sessionVersion');
t.equal(session.origin.netType, 'IN', 'origin netType');
t.equal(session.origin.ipVer, 4, 'origin ipVer');
t.equal(session.origin.address, '192.0.2.3', 'origin address');
var image = media[0];
t.equal(image.type, 'image', 'image type');
t.equal(image.port, 9, 'port');
t.equal(image.connection.version, 4, 'Connection is IPv4');
t.equal(image.connection.ip, '192.0.2.3', 'Connection address');
t.equal(image.protocol, 'TCP', 'TCP protocol');
t.equal(image.payloads, 't38', 'TCP payload');
t.equal(image.setup, 'active', 'setup active');
t.equal(image.connectionType, 'new', 'new connection');
});
test('tcp-passive', function *(t) {
var sdp = yield fs.readFile(__dirname + '/tcp-passive.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length == 1, 'got single media');
t.equal(session.origin.username, '-', 'origin username');
t.equal(session.origin.sessionId, 1562876543, 'origin sessionId');
t.equal(session.origin.sessionVersion, 11, 'origin sessionVersion');
t.equal(session.origin.netType, 'IN', 'origin netType');
t.equal(session.origin.ipVer, 4, 'origin ipVer');
t.equal(session.origin.address, '192.0.2.2', 'origin address');
var image = media[0];
t.equal(image.type, 'image', 'image type');
t.equal(image.port, 54111, 'port');
t.equal(image.connection.version, 4, 'Connection is IPv4');
t.equal(image.connection.ip, '192.0.2.2', 'Connection address');
t.equal(image.protocol, 'TCP', 'TCP protocol');
t.equal(image.payloads, 't38', 'TCP payload');
t.equal(image.setup, 'passive', 'setup passive');
t.equal(image.connectionType, 'existing', 'existing connection');
});
test('mediaclk-avbtp', function *(t) {
var sdp = yield fs.readFile(__dirname + '/mediaclk-avbtp.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length == 1, 'got single media');
var audio = media[0];
t.equal(audio.mediaClk.mediaClockName, 'IEEE1722', 'IEEE1722 Media Clock');
t.equal(audio.mediaClk.mediaClockValue, '38-D6-6D-8E-D2-78-13-2F', 'AVB stream ID');
});
test('mediaclk-ptp-v2-w-rate', function *(t) {
var sdp = yield fs.readFile(__dirname + '/mediaclk-ptp-v2-w-rate.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length == 1, 'got single media');
var audio = media[0];
t.equal(audio.mediaClk.mediaClockName, 'direct', 'Direct Media Clock');
t.equal(audio.mediaClk.mediaClockValue, 963214424, 'offset');
t.equal(audio.mediaClk.rateNumerator, 1000, 'rate numerator');
t.equal(audio.mediaClk.rateDenominator, 1001, 'rate denominator');
});
test('mediaclk-ptp-v2', function *(t) {
var sdp = yield fs.readFile(__dirname + '/mediaclk-ptp-v2.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length == 1, 'got single media');
var audio = media[0];
t.equal(audio.mediaClk.mediaClockName, 'direct', 'Direct Media Clock');
t.equal(audio.mediaClk.mediaClockValue, 963214424, 'offset');
});
test('mediaclk-rtp', function *(t) {
var sdp = yield fs.readFile(__dirname + '/mediaclk-rtp.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var media = session.media;
t.ok(media && media.length == 1, 'got single media');
var audio = media[0];
t.equal(audio.mediaClk.id, 'MDA6NjA6MmI6MjA6MTI6MWY=', 'Media Clock ID');
t.equal(audio.mediaClk.mediaClockName, 'sender', 'sender type');
});
test('ts-refclk-media', function *(t) {
var sdp = yield fs.readFile(__dirname + '/ts-refclk-media.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var sessTsRefClocks = session.tsRefClocks;
t.ok(sessTsRefClocks && sessTsRefClocks.length == 1, 'got one TS Ref Clock');
t.equal(sessTsRefClocks[0].clksrc, 'local', 'local Clock Source at Session Level');
var media = session.media;
t.ok(media && media.length == 2, 'got two media');
var audio = media[0];
var audTsRefClocks = audio.tsRefClocks;
t.ok(audTsRefClocks && audTsRefClocks.length == 2, 'got two audio TS Ref Clocks');
var audTsRefClock1 = audTsRefClocks[0];
t.equal(audTsRefClock1.clksrc, 'ntp', 'NTP Clock Source');
t.equal(audTsRefClock1.clksrcExt, '203.0.113.10', 'IPv4 address');
var audTsRefClock2 = audTsRefClocks[1];
t.equal(audTsRefClock2.clksrc, 'ntp', 'NTP Clock Source');
t.equal(audTsRefClock2.clksrcExt, '198.51.100.22', 'IPv4 address');
var video = media[1];
var vidTsRefClocks = video.tsRefClocks;
t.ok(vidTsRefClocks && vidTsRefClocks.length == 1, 'got one video TS Ref Clocks');
t.equal(vidTsRefClocks[0].clksrc, 'ptp', 'PTP Clock Source');
t.equal(vidTsRefClocks[0].clksrcExt, 'IEEE802.1AS-2011:39-A7-94-FF-FE-07-CB-D0', 'PTP config');
});
test('ts-refclk-sess', function *(t) {
var sdp = yield fs.readFile(__dirname + '/ts-refclk-sess.sdp', 'utf8');
var session = parse(sdp+'');
t.ok(session, 'got session info');
var sessTsRefClocks = session.tsRefClocks;
t.ok(sessTsRefClocks && sessTsRefClocks.length == 1, 'got one TS Ref Clock at Session Level');
t.equal(sessTsRefClocks[0].clksrc, 'ntp', 'NTP Clock Source');
t.equal(sessTsRefClocks[0].clksrcExt, '/traceable/', 'traceable Clock Source');
}); | clux/sdp-transform | test/parse.test.js | JavaScript | mit | 37,501 |
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define(["require","exports"],function(c,g){Object.defineProperty(g,"__esModule",{value:!0});g.SwapTable=[["(",")"],[")","("],["\x3c","\x3e"],["\x3e","\x3c"],["[","]"],["]","["],["{","}"],["}","{"],["\u00ab","\u00bb"],["\u00bb","\u00ab"],["\u2039","\u203a"],["\u203a","\u2039"],["\u207d","\u207e"],["\u207e","\u207d"],["\u208d","\u208e"],["\u208e","\u208d"],["\u2264","\u2265"],["\u2265","\u2264"],["\u2329","\u232a"],["\u232a","\u2329"],["\ufe59","\ufe5a"],["\ufe5a","\ufe59"],["\ufe5b","\ufe5c"],["\ufe5c",
"\ufe5b"],["\ufe5d","\ufe5e"],["\ufe5e","\ufe5d"],["\ufe64","\ufe65"],["\ufe65","\ufe64"]];g.AlefTable=["\u0622","\u0623","\u0625","\u0627"];g.LamAlefInialTableFE=["\ufef5","\ufef7","\ufef9","\ufefb"];g.LamAlefMedialTableFE=["\ufef6","\ufef8","\ufefa","\ufefc"];g.BaseForm="\u0627\u0628\u062a\u062b\u062c\u062d\u062e\u062f\u0630\u0631\u0632\u0633\u0634\u0635\u0636\u0637\u0638\u0639\u063a\u0641\u0642\u0643\u0644\u0645\u0646\u0647\u0648\u064a\u0625\u0623\u0622\u0629\u0649\u0644\u0645\u0646\u0647\u0648\u064a\u0625\u0623\u0622\u0629\u0649\u06cc\u0626\u0624".split("");
g.IsolatedForm="\ufe8d\ufe8f\ufe95\ufe99\ufe9d\ufea1\ufea5\ufea9\ufeab\ufead\ufeaf\ufeb1\ufeb5\ufeb9\ufebd\ufec1\ufec5\ufec9\ufecd\ufed1\ufed5\ufed9\ufedd\ufee1\ufee5\ufee9\ufeed\ufef1\ufe87\ufe83\ufe81\ufe93\ufeef\ufbfc\ufe89\ufe85\ufe70\ufe72\ufe74\ufe76\ufe78\ufe7a\ufe7c\ufe7e\ufe80\ufe89\ufe85".split("");g.FinalForm="\ufe8e\ufe90\ufe96\ufe9a\ufe9e\ufea2\ufea6\ufeaa\ufeac\ufeae\ufeb0\ufeb2\ufeb6\ufeba\ufebe\ufec2\ufec6\ufeca\ufece\ufed2\ufed6\ufeda\ufede\ufee2\ufee6\ufeea\ufeee\ufef2\ufe88\ufe84\ufe82\ufe94\ufef0\ufbfd\ufe8a\ufe86\ufe70\ufe72\ufe74\ufe76\ufe78\ufe7a\ufe7c\ufe7e\ufe80\ufe8a\ufe86".split("");
g.MedialForm="\ufe8e\ufe92\ufe98\ufe9c\ufea0\ufea4\ufea8\ufeaa\ufeac\ufeae\ufeb0\ufeb4\ufeb8\ufebc\ufec0\ufec4\ufec8\ufecc\ufed0\ufed4\ufed8\ufedc\ufee0\ufee4\ufee8\ufeec\ufeee\ufef4\ufe88\ufe84\ufe82\ufe94\ufef0\ufbff\ufe8c\ufe86\ufe71\ufe72\ufe74\ufe77\ufe79\ufe7b\ufe7d\ufe7f\ufe80\ufe8c\ufe86".split("");g.InitialForm="\ufe8d\ufe91\ufe97\ufe9b\ufe9f\ufea3\ufea7\ufea9\ufeab\ufead\ufeaf\ufeb3\ufeb7\ufebb\ufebf\ufec3\ufec7\ufecb\ufecf\ufed3\ufed7\ufedb\ufedf\ufee3\ufee7\ufeeb\ufeed\ufef3\ufe87\ufe83\ufe81\ufe93\ufeef\ufbfe\ufe8b\ufe85\ufe70\ufe72\ufe74\ufe76\ufe78\ufe7a\ufe7c\ufe7e\ufe80\ufe8b\ufe85".split("");
g.StandAlonForm="\u0621\u0622\u0623\u0624\u0625\u0627\u0629\u062f\u0630\u0631\u0632\u0648\u0649".split("");g.FETo06Table="\u064b\u064b\u064c\u061f\u064d\u061f\u064e\u064e\u064f\u064f\u0650\u0650\u0651\u0651\u0652\u0652\u0621\u0622\u0622\u0623\u0623\u0624\u0624\u0625\u0625\u0626\u0626\u0626\u0626\u0627\u0627\u0628\u0628\u0628\u0628\u0629\u0629\u062a\u062a\u062a\u062a\u062b\u062b\u062b\u062b\u062c\u062c\u062c\u062c\u062d\u062d\u062d\u062d\u062e\u062e\u062e\u062e\u062f\u062f\u0630\u0630\u0631\u0631\u0632\u0632\u0633\u0633\u0633\u0633\u0634\u0634\u0634\u0634\u0635\u0635\u0635\u0635\u0636\u0636\u0636\u0636\u0637\u0637\u0637\u0637\u0638\u0638\u0638\u0638\u0639\u0639\u0639\u0639\u063a\u063a\u063a\u063a\u0641\u0641\u0641\u0641\u0642\u0642\u0642\u0642\u0643\u0643\u0643\u0643\u0644\u0644\u0644\u0644\u0645\u0645\u0645\u0645\u0646\u0646\u0646\u0646\u0647\u0647\u0647\u0647\u0648\u0648\u0649\u0649\u064a\u064a\u064a\u064a\ufef5\ufef6\ufef7\ufef8\ufef9\ufefa\ufefb\ufefc\u061f\u061f\u061f".split("");
g.ArabicAlefBetIntervalsBegine=["\u0621","\u0641"];g.ArabicAlefBetIntervalsEnd=["\u063a","\u064a"];g.impTabLtr=[[0,3,0,1,0,0,0],[0,3,0,1,2,2,0],[0,3,0,17,2,0,1],[0,3,5,5,4,1,0],[0,3,21,21,4,0,1],[0,3,5,5,4,2,0]];g.impTabRtl=[[2,0,1,1,0,1,0],[2,0,1,1,0,2,0],[2,0,2,1,3,2,0],[2,0,2,33,3,1,1]];g.UBAT_L=0;g.UBAT_R=1;g.UBAT_EN=2;g.UBAT_AN=3;g.UBAT_ON=4;g.UBAT_B=5;g.UBAT_S=6;g.UBAT_AL=7;g.UBAT_WS=8;g.UBAT_CS=9;g.UBAT_ES=10;g.UBAT_ET=11;g.UBAT_NSM=12;g.UBAT_LRE=13;g.UBAT_RLE=14;g.UBAT_PDF=15;g.UBAT_LRO=16;
g.UBAT_RLO=17;g.UBAT_BN=18;g.TYPES_NAMES="UBAT_L UBAT_R UBAT_EN UBAT_AN UBAT_ON UBAT_B UBAT_S UBAT_AL UBAT_WS UBAT_CS UBAT_ES UBAT_ET UBAT_NSM UBAT_LRE UBAT_RLE UBAT_PDF UBAT_LRO UBAT_RLO UBAT_BN".split(" ");g.TBBASE=100;c=g.UBAT_L;var e=g.UBAT_R,k=g.UBAT_EN,l=g.UBAT_AN,a=g.UBAT_ON,q=g.UBAT_B,r=g.UBAT_S,b=g.UBAT_AL,m=g.UBAT_WS,n=g.UBAT_CS,p=g.UBAT_ES,h=g.UBAT_ET,d=g.UBAT_NSM,t=g.UBAT_LRE,u=g.UBAT_RLE,v=g.UBAT_PDF,w=g.UBAT_LRO,x=g.UBAT_RLO,f=g.UBAT_BN;g.MasterTable=[g.TBBASE+0,c,c,c,c,g.TBBASE+1,g.TBBASE+
2,g.TBBASE+3,e,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,g.TBBASE+4,a,a,a,c,a,c,a,c,a,a,a,c,c,a,a,c,c,c,c,c,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,c,c,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,c,c,a,a,c,c,a,a,c,c,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,
c,c,c,g.TBBASE+5,b,b,g.TBBASE+6,g.TBBASE+7];g.UnicodeTable=[[f,f,f,f,f,f,f,f,f,r,q,r,m,q,f,f,f,f,f,f,f,f,f,f,f,f,f,f,q,q,q,r,m,a,a,h,h,h,a,a,a,a,a,p,n,p,n,n,k,k,k,k,k,k,k,k,k,k,n,a,a,a,a,a,a,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,a,a,a,a,a,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,a,a,a,f,f,f,f,f,f,q,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,f,n,a,h,h,h,h,a,a,a,a,c,a,a,f,a,a,h,h,k,k,a,c,a,a,a,k,c,a,a,a,a,a,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,c,c,c,c,
c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,c,c,c,c,c,c,c,c],[c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,a,a,a,a,a,a,a,a,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,a,c,c,c,c,c,c,c,a,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,c,a,a,a,a,a,a,a,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,e,d,e,d,d,e,d,d,e,d,a,a,a,a,a,a,a,a,e,e,e,e,e,e,
e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,a,a,a,a,a,e,e,e,e,e,a,a,a,a,a,a,a,a,a,a,a],[l,l,l,l,a,a,a,a,b,h,h,b,n,b,a,a,d,d,d,d,d,d,d,d,d,d,d,b,a,a,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,l,l,l,l,l,l,l,l,l,l,h,l,l,b,b,b,d,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,
b,b,b,b,b,b,d,d,d,d,d,d,d,l,a,d,d,d,d,d,d,b,b,d,d,a,d,d,d,d,b,b,k,k,k,k,k,k,k,k,k,k,b,b,b,b,b,b],[b,b,b,b,b,b,b,b,b,b,b,b,b,b,a,b,b,d,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,a,a,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,d,d,d,d,d,d,d,d,d,d,d,b,a,a,a,a,a,a,a,a,a,a,a,a,a,a,e,e,e,e,e,e,e,e,e,e,
e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,d,d,d,d,d,d,d,d,d,e,e,a,a,a,a,e,a,a,a,a,a],[m,m,m,m,m,m,m,m,m,m,m,f,f,f,c,e,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,m,q,t,u,v,w,x,n,h,h,h,h,h,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,n,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,m,f,f,f,f,f,a,a,a,a,a,f,f,f,f,f,f,k,c,a,a,k,k,k,k,k,k,p,p,a,a,a,c,k,k,k,k,k,k,k,k,k,k,p,p,a,a,a,a,c,c,c,c,c,c,c,c,c,c,c,c,c,a,a,a,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,h,a,a,a,a,a,a,a,a,a,a,
a,a,a,a,a,a,a,a,a,a,a,a,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a],[c,c,c,c,c,c,c,a,a,a,a,a,a,a,a,a,a,a,a,c,c,c,c,c,a,a,a,a,a,e,d,e,e,e,e,e,e,e,e,e,e,p,e,e,e,e,e,e,e,e,e,e,e,e,e,a,e,e,e,e,e,a,e,a,e,e,a,e,e,a,e,e,e,e,e,e,e,e,e,e,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,
b,b,b,b,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b],[d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,d,d,d,d,d,d,d,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,n,a,n,a,a,n,a,a,a,a,a,a,a,a,a,h,a,a,p,p,a,a,a,a,a,h,h,a,a,a,a,a,b,b,b,b,b,a,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,
b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,a,a,f],[a,a,a,h,h,h,a,a,a,a,a,p,n,p,n,n,k,k,k,k,k,k,k,k,k,k,n,a,a,a,a,a,a,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,a,a,a,a,a,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,a,a,a,a,a,a,a,a,a,a,a,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,
c,c,c,c,c,c,c,c,c,c,c,c,c,a,a,a,c,c,c,c,c,c,a,a,c,c,c,c,c,c,a,a,c,c,c,c,c,c,a,a,c,c,c,a,a,a,h,h,a,a,a,h,h,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a]]}); | ycabon/presentations | 2020-devsummit/arcgis-js-api-road-ahead/js-api/esri/core/bidiEngineTables.js | JavaScript | mit | 9,169 |
var flag = "did_you_use_python's_[::-1]_notation?";
exports.get_data = function(req, callback) {
var result = [];
var s = [
"[Go, droop aloof] sides reversed, is [fool a poor dog]. I did roar again, Niagara! ... or did I?",
"Help Max, Enid -- in example, H. See, slave, I demonstrate yet arts no medieval sees.",
"Egad, a base tone denotes a bad age. So may Obadiah, even in Nineveh, aid a boy, Amos. Naomi, did I moan?",
"Sir, I soon saw Bob was no Osiris. Poor Dan is in a droop.",
"Straw? No, too stupid a fad. I put soot on warts.",
"Live on, Time; emit no evil.",
"No, it is opposition.",
"Peel's lager on red rum did murder no regal sleep.",
"Too far away, no mere clay or royal ceremony, a war afoot."
];
var rand = s[(Math.random()*s.length)|0];
var a = s[(Math.random()*s.length)|0];
while (a == rand){
a = s[(Math.random()*s.length)|0];
}
a += " " + rand;
//console.log(s,a);
result.push(a);
req.session.data = result;
callback(result);
};
exports.check_data = function(req, callback) {
var answer = req.param("answer");
var data = req.session.data;
var s = data[0];
var longest = "";
var longestOrig = "";
for(var i = s.length - 1; i >= 0; i--) {
for (var j = i + 1; j < s.length; j++) {
var q = s.substring(i, j);
var t = q;
if (q.substring(0,1).match(/[0-9a-zA-Z]+$/)){
t = q.replace(/[^A-Za-z]/gi,'').toLowerCase();
}
if (t == t.split("").reverse().join("") && t.length > longest.length) {
longest = t;
longestOrig = q.trim();
}
}
}
var correct = longestOrig;
/*console.log("!"+longestOrig+"!");
console.log("!"+output+"!");
console.log(longestOrig == output);*/
// return longestOrig === answer;
if (answer) {
answer = answer.replace(/^\s+|\s+$/g,'');
correct = correct.replace(/^\s+|\s+$/g,'');
if (answer.toLowerCase() === correct.toLowerCase()) {
callback({
status: 1,
message: "Great job! Your flag is <code>" + flag + "</code>",
});
return;
} else {
callback({
status: 0,
message: "Nope, try again..."
});
return;
}
} else {
callback({
status: 0,
message: "Answer cannot be empty!"
});
return;
}
};
| CTCTF/Backend | api/ide/palindrama.js | JavaScript | mit | 2,165 |
(function () {
"use strict";
angular
.module('documents')
.component('scientillaDocumentAffiliations', {
templateUrl: 'partials/scientilla-document-affiliations.html',
controller: controller,
controllerAs: 'vm',
bindings: {
document: "<",
collapsed: '=?',
highlighted: '=?'
}
});
controller.$inject = [
'$filter',
'$scope'
];
function controller($filter, $scope) {
const vm = this;
vm.getAffiliationInstituteIdentifier = getAffiliationInstituteIdentifier;
vm.toggleCollapse = toggleCollapse;
vm.affiliationInstitutes = [];
vm.$onInit = () => {
if (!vm.collapsed) {
vm.collapsed = false;
}
shortenAuthorString();
$scope.$watch('vm.collapsed', function() {
shortenAuthorString();
});
};
function toggleCollapse() {
vm.collapsed = !vm.collapsed;
}
function getAffiliationInstituteIdentifier(institute) {
return vm.document.getInstituteIdentifier(
vm.document.institutes.findIndex(i => i.id === institute.id)
);
}
function shortenAuthorString() {
let limit = vm.collapsed ? vm.document.getAuthorLimit() : 0,
shortAuthorString = $filter('authorsLength')(vm.document.authorsStr, limit);
vm.affiliationInstitutes = [];
shortAuthorString.split(/,\s?/).map(function (author, index) {
const authorship = _.find(vm.document.authorships, a => a.position === index);
if (authorship) {
vm.affiliationInstitutes = vm.affiliationInstitutes.concat(authorship.affiliations).unique();
}
});
}
}
})
();
| scientilla/scientilla | assets/js/app/documents/scientilla-document-affiliations.component.js | JavaScript | mit | 1,945 |
exports.config = {
allScriptsTimeout: 11000,
specs: [
'*.js'
],
capabilities: {
'browserName': 'chrome'
},
baseUrl: 'http://localhost:8080/mylibrary/',
framework: 'jasmine',
jasmineNodeOpts: {
defaultTimeoutInterval: 30000
}
};
| TAMULib/Weaver-UI-Seed | tests/e2e/protractor.conf.js | JavaScript | mit | 263 |
const { resolve } = require('path')
const express = require('express')
const bodyParser = require('body-parser')
var proxy = require('express-http-proxy')
const app = express()
// parse JSON bodies
app.use(bodyParser.json({ type: 'application/json' }))
// the index file
app.get('/', (req, res) => {
res.sendFile(resolve(__dirname, '../index.html'))
})
// handle Perl requests
app.post('/resources/cgi-bin/scrollery-cgi.pl', proxy('http://localhost:9080/resources/cgi-bin/scrollery-cgi.pl'))
// expose the Express app instance
module.exports = app
| Scripta-Qumranica-Electronica/Scrollery-website | tools/app.js | JavaScript | mit | 555 |
'use strict';
var AppDispatcher = require('../dispatchers/AppDispatcher');
var AppStore = require('../stores/AppStore');
var AppConstants = require('../constants/AppConstants');
var ServerActions = {
receiveData: function(data) {
AppDispatcher.handleViewAction({
actionType: AppConstants.GET_CATEGORIES,
data: data
});
},
receiveNewCategory(category) {
AppDispatcher.handleViewAction({
actionType: AppConstants.ADD_NEW_CATEGORY,
category: category
});
},
receiveDeletedCategory(categoryID) {
AppDispatcher.handleViewAction({
actionType: AppConstants.DELETE_CATEGORY,
categoryID: categoryID
});
},
receiveUpdatedComponents(categoryID, sectionID, components) {
AppDispatcher.handleViewAction({
actionType: AppConstants.UPDATE_COMPONENTS,
categoryID: categoryID,
sectionID: sectionID,
components: components
});
},
receiveNewSection(categoryID, section) {
AppDispatcher.handleViewAction({
actionType: AppConstants.ADD_NEW_SECTION,
section: section,
categoryID: categoryID
});
},
receiveDeletedSection(categoryID, sectionID) {
AppDispatcher.handleViewAction({
actionType: AppConstants.DELETE_SECTION,
sectionID: sectionID,
categoryID: categoryID
});
},
receiveSection(index, data) {
AppDispatcher.handleViewAction({
actionType: AppConstants.UPDATE_SECTION,
index: index,
data: data
});
},
receiveCategory(index, data) {
AppDispatcher.handleViewAction({
actionType: AppConstants.UPDATE_CATEGORY,
index: index,
data: data
});
},
receiveSortedSectionItems: function(sectionID, items) {
AppDispatcher.handleViewAction({
actionType: AppConstants.SORT_SECTION_ITEMS,
sectionID: sectionID,
items: items
});
},
receiveSortedCategorySections: function(categoryID, sections) {
AppDispatcher.handleViewAction({
actionType: AppConstants.SORT_CATEGORY_SECTIONS,
categoryID: categoryID,
sections: sections
});
},
receiveSortedCategories: function(dragged, over) {
AppDispatcher.handleViewAction({
actionType: AppConstants.SORT_CATEGORIES,
dragged: dragged,
over: over
});
}
};
module.exports = ServerActions;
| davunderscorei/tab-hq-react | app/js/actions/ServerActions.js | JavaScript | mit | 2,322 |
function Database() {
if(typeof this.mysql == "undefined") {
this.init();
}
}
Database.prototype.init = function() {
var mysql = require('mysql');
this.connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'test1234',
database : 'linkbank'
});
},
Database.prototype.search = function(word, socket) {
console.log("search:", word);
var query = this.connection.query("SELECT address, description FROM link WHERE description LIKE '%" + word + "%' OR address LIKE '%"+ word +"%'", function(err, rows, fields) {
if(err) {
console.log("search query failed:", err);
}
else {
console.log("found", rows);
socket.emit('search response', JSON.stringify(rows));
}
});
},
Database.prototype.addlink = function(link, description, socket) {
console.log("addlink:", link, description);
this.connection.query("INSERT INTO link (address, description) VALUES (?, ?)", [link, description], function(err, result) {
if(err) {
console.log("addlink query failed:", err);
socket.emit('add link response', false);
}
else {
socket.emit('add link response', true);
}
});
},
Database.prototype.login = function(username, passwordhash, socket) {
this.connection.query("SELECT passwordhash FROM user WHERE username = ?", [username], function(err, rows, fields) {
if(err) {
console.log("login query failed:", err);
}
else {
var status = false;
if(typeof rows[0] !== "undefined") {
if(passwordhash == rows[0].passwordhash) {
status = true;
}
else {
status = false;
}
}
socket.emit('login response', status);
socket.authorized = status;
}
});
}
Database.prototype.register = function(username, passwordhash, socket) {
console.log("register:", username, passwordhash);
var query = this.connection.query("INSERT INTO user (username, passwordhash) VALUES (?,?)", [username, passwordhash], function(err, result) {
if(err) {
console.log("register query failed:", err);
}
else {
socket.emit('register response', true);
socket.authorized = true;
}
});
}
module.exports = Database; | jvanhalen/linkbank | database/database.js | JavaScript | mit | 2,266 |
module.exports = [
require('./deepSouth'),
require('./fallsRiverMusic')
// require('./gizmoBrewWorks')
];
| mweslander/veery | src/api/lib/siteScraper/sites/northCarolina/raleigh/index.js | JavaScript | mit | 112 |
// app/routes.js
// grab the country model we just created
var Country = require('./models/country');
module.exports = function (app) {
//----------------------------------------------------------------------
// server routes
// handle things like api calls
// authentication routes
// sample api route
app.get('/api/countries', function (req, res) {
// use mongoose to get all countries in the database
Country.find(function (err, countries) {
// if there is an error retrieving, send the error.
// nothing after res.send(err) will execute
if (err)
res.send(err);
// return all countries in JSON format
res.json(countries);
});
});
app.get('/api/countries/:id',function(req,res){
// var response = {};
Country.findById(req.params.id, function(err,data){
// This will run Mongo Query to fetch data based on ID.
if(err) {
res.send(err);
}
res.send(data);
});
});
app.post('/api/countries',function(req,res){
var country = new Country();
var response = {};
country.index = req.body.index;
country.name = req.body.name;
country.gdi_value =req.body.gdi_value;
country.gdi_group = req.body.gdi_group;
country.hdi_f = req.body.hdi_f;
country.hdi_m =req.body.hdi_m;
country.le_f =req.body.le_f;
country.le_m =req.body.le_m;
country.eys_f =req.body.eys_f;
country.eys_m =req.body.eys_m;
country.mys_f = req.body.mys_f;
country.mys_m = req.body.mys_m;
country.gni_f =req.body.gni_f;
country.gni_m =req.body.gni_m;
country.hd_level=req.body.hd_level;
country.save(function(err){
// save() will run insert() command of MongoDB.
// it will add new data in collection.
if(err) {
response = {"error" : true,"message" : "Error adding data"};
} else {
response = {"error" : false,"message" : "Data added"};
}
res.json(response);
});
});
app.delete('/api/countries/:id', function (req, res){
return Country.findById(req.params.id, function (err, country) {
return Country.remove({_id : req.params.id},function (err) {
if (!err) {
console.log("removed");
return res.send('');
} else {
console.log(err);
}
});
});
});
app.put('/api/countries',function(req,res){
var response = {};
// first find out record exists or not
// if it does then update the record
Country.findById(req.params.id,function(err,country){
if(err) {
response = {"error" : true,"message" : "Error fetching data"};
} else {
// we got data from Mongo.
// change it accordingly.
if(req.body.index !== undefined) {
//
country.index = req.body.index;
}
if(req.body.name !== undefined) {
//
country.name = req.body.name;
}
if(req.body.gdi_value!==undefined){
coutry.gdi_value=req.body.gdi_value;
}
if(req.gdi_group!==undefined){
country.gdi_group = req.body.gdi_group;
}
if(req.body.hdi_f!==undefined){
country.hdi_f = req.body.hdi_f;
}
if(req.body.hdi_m!==undefined){
country.hdi_m =req.body.hdi_m;
}
if(req.body.le_f!==undefined){
country.le_f =req.body.le_f;
}
if(req.body.le_m!==undefined){
country.le_m =req.body.le_m;
}
if(req.body.eys_f!==undefined){
country.eys_f =req.body.eys_f;
}
if(req.body.eys_m!==undefined){
country.eys_m =req.body.eys_m;
}
if(req.body.mys_f!==undefined){
country.mys_f = req.body.mys_f;
}
if(req.body.mys_m!==undefined){
country.mys_m = req.body.mys_m;
}
if(req.body.gni_f!==undefined){
country.gni_f =req.body.gni_f;
}
if(req.body.gni_m!==undefined){
country.gni_m =req.body.gni_m;
}
if(req.body.hd_level){
country.hd_level=req.body.hd_level;
}
// save the data
country.save(function(err){
if(err) {
response = {"error" : true,"message" : "Error updating data"};
} else {
response = {"error" : false,"message" : "Data is updated for "+req.params.id};
}
res.json(response);
})
}
});
})
// app.get('/api/countries/:name',function(req,res){
// // var response = {};
// Country.find({'name': new RegExp(req.params.name, "i")}, function(err, data) {
// //Do your action here..
// // This will run Mongo Query to fetch data based on ID.
// if(err) {
// res.send(err);
// // response = {"error" : true,"message" : "Error fetching data"};
// // } else {
// // response = {"error" : false,"message" : data};
// }
// res.send(data);
// });
// });
// route to handle creating goes here (app.post)
// route to handle delete goes here (app.delete)
//----------------------------------------------------------------------
// frontend routes
// route to handle all angular requests
app.get('*', function (req, res) {
res.sendFile('/public/index.html', { root: '.' });
});
};
| ioanungurean/gexp | app/routes.js | JavaScript | mit | 6,198 |
'use strict'
var _ = require('lodash'),
CrudRoutes = require('../lib/crud-routes'),
transactions = require('../services/transactions'),
log = require('../lib/log');
let opts = {
entity: 'transactions',
service: transactions,
user: true,
parent: {
name: 'account'
},
protected: true
};
let routes = CrudRoutes(opts);
routes.push({
method: 'get',
uri: '/user/:userid/accounts/:accountid/transactions/search/:kind/:search',
protected: true,
handler: (req,res,next) => {
log.info('Search Transactions by ' + req.params.kind + '/' + req.params.search);
return transactions.search(req.params)
.then((data) => {
res.send(200, data);
})
.catch((err) => {
let code = err.type === 'validation' ? 400 : 500;
log.error('Error searching transactions: ' + err.message);
res.send(400, err.message);
});
}
});
routes.push({
method: 'get',
uri: '/user/:userid/accounts/:accountid/transactions/startdate/:startdate/enddate/:enddate',
protected: true,
handler: (req,res,next) => {
log.info('Retrieve Transactions from ' + req.params.startdate + '-' + req.params.enddate);
return transactions.search(req.params)
.then((data) => {
res.send(200, data);
})
.catch((err) => {
let code = err.type === 'validation' ? 400 : 500;
log.error('Error searching transactions: ' + err.message);
res.send(400, err.message);
});
}
});
routes.push({
method: 'get',
uri: '/user/:userid/accounts/:accountid/transactions/startdate/:startdate/enddate/:enddate/:groupby',
protected: true,
handler: (req,res,next) => {
log.info('Retrieve Transactions from ' + req.params.startdate + ' to ' + req.params.enddate);
return transactions.search(req.params)
.then((data) => {
log.debug('Grouping by ' + req.params.groupby);
let a = _.groupBy(data, req.params.groupby);
res.send(200, a);
})
.catch((err) => {
let code = err.type === 'validation' ? 400 : 500;
log.error('Error searching transactions: ' + err.message);
res.send(400, err.message);
});
}
});
module.exports = routes;
| jcapuano328/scratch-minder-services | src/routes/transactions.js | JavaScript | mit | 2,354 |
/*Write an if statement that takes two double variables a and b and exchanges their values if the first one is greater than the second.
As a result print the values a and b, separated by a space.*/
console.log('-----Problem 1. Exchange if greater-----');
function exchangeIfIsGrater (first, second){
console.log('Before exchange:', first, second);
var temp;
if(first > second){
temp = first;
first = second;
second = temp;
}
console.log('After exchange:', first, second);
}
exchangeIfIsGrater(15, 10);
| ReniGetskova/JavaScript-Fundamentals | ConditionalStatements/1.ExchangeIfGrater.js | JavaScript | mit | 552 |
'use strict';
module.exports = {
type: 'error',
error: {
line: 1,
column: 3,
message: 'Unexpected character \'💩\'.',
},
};
| fatfisz/binapi | test/fixtures/lexer/identifier error/config.js | JavaScript | mit | 145 |
export { default } from 'ember-radical/components/rad-dropdown/content'
| healthsparq/ember-radical | app/components/rad-dropdown/content.js | JavaScript | mit | 72 |
/* eslint-disable @typescript-eslint/no-var-requires */
const path = require('path');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const webpack = require('webpack');
const { version, author, license } = require('./package.json');
module.exports = {
entry: './src/index.js',
output: {
filename: 'toastui-vue-editor.js',
path: path.resolve(__dirname, 'dist'),
library: {
type: 'commonjs2',
},
environment: {
arrowFunction: false,
const: false,
},
},
externals: {
'@toast-ui/editor': {
commonjs: '@toast-ui/editor',
commonjs2: '@toast-ui/editor',
},
'@toast-ui/editor/dist/toastui-editor-viewer': {
commonjs: '@toast-ui/editor/dist/toastui-editor-viewer',
commonjs2: '@toast-ui/editor/dist/toastui-editor-viewer',
},
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
exclude: /node_modules/,
},
{
test: /\.js$/,
use: [
{
loader: 'ts-loader',
options: {
transpileOnly: true,
},
},
],
exclude: /node_modules/,
},
],
},
plugins: [
new VueLoaderPlugin(),
new webpack.BannerPlugin({
banner: [
'TOAST UI Editor : Vue Wrapper',
`@version ${version} | ${new Date().toDateString()}`,
`@author ${author}`,
`@license ${license}`,
].join('\n'),
}),
],
};
| nhnent/tui.editor | apps/vue-editor/webpack.config.js | JavaScript | mit | 1,481 |
var gulp = require('gulp');
var to5 = require('gulp-6to5');
var concat = require('gulp-concat');
var order = require('gulp-order');
var watch = require('gulp-watch');
var connect = require('gulp-connect');
gulp.task('6to5', function () {
return gulp.src('src/js/**/*.js')
.pipe(order([
'core/**/*.js',
'components/**/*.js',
'app/**/*.js',
'main.js'
]))
.pipe(to5())
.pipe(concat('app.js'))
.pipe(gulp.dest('build'))
.pipe(connect.reload());
});
gulp.task('webserver', function() {
connect.server({
root: 'build',
livereload: true
});
});
gulp.task('watch', function() {
gulp.watch('src/js/**/*.js', ['6to5']);
});
gulp.task('serve', ['webserver', 'watch']);
| samuelleeuwenburg/Orbitals | gulpfile.js | JavaScript | mit | 728 |
define([
'lib/validators/moment',
'lib/validators/unequalTo'
], function () {
});
| davidknezic/bitcoin-trade-guard | src/js/lib/validators.js | JavaScript | mit | 92 |
/**
* Created by kobi on 5/15/14.
*/
exports.welcome = function(req,res){
res.json({message:'welcome to Money Map API'});
}
| kobiluria/MoneyMap | routes/basic_response.js | JavaScript | mit | 134 |
'use strict';
const
Board = require('./board'),
config = require('./config'),
Characters = require('./characters'),
LongTasks = require('./long-tasks'),
Pause = require('./pause'),
Scoreboard = require('./scoreboard'),
ParticleEmitter = require('./particle-emitter'),
CharacterParticleEmitter = require('./character-particle-emitter');
const
eventBus = require('./event-bus'),
screenShake = require('./screen-shake');
class Level {
/**
* @param number Level number
* @param input
* @param stage
*/
constructor(number, input, stage, levelEnding, mazeNumber) {
this.number = number;
this._input = input;
this._stage = stage;
this._gfx = new PIXI.Container();
this._gfx.z = 1; // custom property
this._gfx.x = 32;
this._gfx.y = 32;
this._stage.addChild(this._gfx);
this._board = new Board(this._gfx, mazeNumber);
this._longTasksManager = new LongTasks.Manager();
this._characters = new Characters(this._board, this._gfx, this._longTasksManager);
this._currentGhostSubModeIndex = 0;
this._ghostSubModeElapsed = 0;
this._frightTimeLeft = null;
this._lvlSpec = null;
this._pause = new Pause(stage, input);
this._scoreboard = new Scoreboard(stage);
levelEnding.scoreboard = this._scoreboard;
this._particleEmitter = new ParticleEmitter(this._gfx);
this._characterParticleEmitter = new CharacterParticleEmitter(this._gfx);
}
start() {
this._lvlSpec = config.levelSpecifications[this.number];
this._characters.start(this._lvlSpec);
this._pause.start();
this._scoreboard.start();
this._particleEmitter.start();
this._characterParticleEmitter.start();
screenShake.start(this._gfx);
eventBus.fire({ name: 'event.level.start', args: { levelNumber: this.number } });
}
stop() {
this._characters.stop();
this._pause.stop();
this._scoreboard.stop();
this._particleEmitter.stop();
this._characterParticleEmitter.stop();
screenShake.stop();
// TODO: In next game, make this more encapsulated
let idx = this._stage.getChildIndex(this._gfx);
this._stage.removeChildAt(idx);
this._gfx.destroy(true);
}
step(elapsed) {
if (this._pause.active) {
// TODO: Count how long paused
} else {
this._handleLongTasks(elapsed);
this._handleSubMode(elapsed);
this._handleCollisionsAndSteps(elapsed);
screenShake.step(elapsed);
this._particleEmitter.step(elapsed);
this._characterParticleEmitter.step(elapsed);
}
this._stepPaused(elapsed);
}
checkForEndLevelCondition() {
return this._board.dotsLeft() == false;
}
_stepPaused(elapsed) {
this._pause.step(elapsed);
}
_handleLongTasks(elapsed) {
this._longTasksManager.step(elapsed);
}
_handleSubMode(elapsed) {
if (this._frightTimeLeft !== null) {
this._handleFrightLeft(elapsed);
return; // fright essentially pauses the sub-mode timer.
}
this._ghostSubModeElapsed += elapsed;
let currentSubModeTotalTime = this._lvlSpec.ghostMode[this._currentGhostSubModeIndex].time;
if (this._ghostSubModeElapsed >= currentSubModeTotalTime) {
this._currentGhostSubModeIndex += 1;
this._ghostSubModeElapsed = 0;
let mode = this._lvlSpec.ghostMode[this._currentGhostSubModeIndex].mode;
this._characters.switchMode(mode);
}
}
_handleFrightLeft(elapsed) {
this._frightTimeLeft -= elapsed;
if (this._frightTimeLeft <= 0) {
this._characters.removeRemainingFright();
this._frightTimeLeft = null;
} else {
// TODO: Here check if flashing should start
}
}
_handleCollisionsAndSteps(elapsed) {
let result = this._characters.checkCollisions();
let requestedDirection = this._determineRequestedDirection();
if (result.collision) {
this._characters.stepPacman(0, requestedDirection); // 0 means stopped one frame
} else {
this._characters.stepPacman(elapsed, requestedDirection);
}
this._characters.stepGhosts(elapsed);
if (result.energizer) {
this._characters.signalFright();
this._frightTimeLeft = this._lvlSpec.frightTime;
eventBus.fire({ name: 'event.action.energizer' });
}
if (result.dot) {
eventBus.fire({
name: 'event.action.eatdot',
args: {
x: result.x,
y: result.y,
direction: this._determineCurrentDirection()
}
});
}
}
_determineRequestedDirection() {
if (this._input.isDown('up')) {
return 'up';
} else if (this._input.isDown('down')) {
return 'down';
} else if (this._input.isDown('left')) {
return 'left';
} else if (this._input.isDown('right')) {
return 'right';
} else {
// null means no new requested direction; stay the course
return null;
}
}
_determineCurrentDirection() {
return this._characters.determineCurrentDirection();
}
}
module.exports = Level; | hiddenwaffle/mazing | src/js/level.js | JavaScript | mit | 5,728 |
/* this file is autogenerated*/
| PillowPillow/grunt-add-comment | test/files/test.js | JavaScript | mit | 33 |
/* globals options */
/* eslint-disable comma-dangle */
var opt = options;
var socket = new WebSocket('ws://localhost:' + opt.port);
socket.addEventListener('message', function(event) {
var ngHotReloadCore = (opt.root || window)[opt.ns].ngHotReloadCore;
var data = event.data ? JSON.parse(event.data) : {};
if (data.message !== 'reload') {
return;
}
if (data.fileType === 'script') {
// If this is a js file, update by creating a script tag
// and loading the updated file from the ng-hot-reload server.
var script = document.createElement('script');
// Prevent browser from using a cached version of the file.
var query = '?t=' + Date.now();
script.src = 'http://localhost:' + opt.port + '/' + data.src + query;
document.body.appendChild(script);
} else if (data.fileType === 'template') {
ngHotReloadCore.template.update(data.filePath, data.file);
} else {
var errorMsg = 'Unknown file type ' + data.filePath;
ngHotReloadCore.manualReload(errorMsg);
}
});
| noppa/ng-hot-reload | packages/standalone/src/client.tpl.js | JavaScript | mit | 1,049 |
//repl read eval print loop
console.log('start');
| WakeUpPig/node2015 | 1.node/start.js | JavaScript | mit | 58 |
"use strict";
class FeatsPage extends ListPage {
constructor () {
const pageFilter = new PageFilterFeats();
super({
dataSource: "data/feats.json",
pageFilter,
listClass: "feats",
sublistClass: "subfeats",
dataProps: ["feat"],
isPreviewable: true,
});
}
getListItem (feat, ftI, isExcluded) {
this._pageFilter.mutateAndAddToFilters(feat, isExcluded);
const eleLi = document.createElement("div");
eleLi.className = `lst__row flex-col ${isExcluded ? "lst__row--blacklisted" : ""}`;
const source = Parser.sourceJsonToAbv(feat.source);
const hash = UrlUtil.autoEncodeHash(feat);
eleLi.innerHTML = `<a href="#${hash}" class="lst--border lst__row-inner">
<span class="col-0-3 px-0 flex-vh-center lst__btn-toggle-expand self-flex-stretch">[+]</span>
<span class="bold col-3-5 px-1">${feat.name}</span>
<span class="col-3-5 ${feat._slAbility === VeCt.STR_NONE ? "list-entry-none " : ""}">${feat._slAbility}</span>
<span class="col-3 ${feat._slPrereq === VeCt.STR_NONE ? "list-entry-none " : ""}">${feat._slPrereq}</span>
<span class="source col-1-7 text-center ${Parser.sourceJsonToColor(feat.source)} pr-0" title="${Parser.sourceJsonToFull(feat.source)}" ${BrewUtil.sourceJsonToStyle(feat.source)}>${source}</span>
</a>
<div class="flex ve-hidden relative lst__wrp-preview">
<div class="vr-0 absolute lst__vr-preview"></div>
<div class="flex-col py-3 ml-4 lst__wrp-preview-inner"></div>
</div>`;
const listItem = new ListItem(
ftI,
eleLi,
feat.name,
{
hash,
source,
ability: feat._slAbility,
prerequisite: feat._slPrereq,
},
{
uniqueId: feat.uniqueId ? feat.uniqueId : ftI,
isExcluded,
},
);
eleLi.addEventListener("click", (evt) => this._list.doSelect(listItem, evt));
eleLi.addEventListener("contextmenu", (evt) => ListUtil.openContextMenu(evt, this._list, listItem));
return listItem;
}
handleFilterChange () {
const f = this._filterBox.getValues();
this._list.filter(item => this._pageFilter.toDisplay(f, this._dataList[item.ix]));
FilterBox.selectFirstVisible(this._dataList);
}
getSublistItem (feat, pinId) {
const hash = UrlUtil.autoEncodeHash(feat);
const $ele = $(`<div class="lst__row lst__row--sublist flex-col">
<a href="#${hash}" class="lst--border lst__row-inner">
<span class="bold col-4 pl-0">${feat.name}</span>
<span class="col-4 ${feat._slAbility === VeCt.STR_NONE ? "list-entry-none" : ""}">${feat._slAbility}</span>
<span class="col-4 ${feat._slPrereq === VeCt.STR_NONE ? "list-entry-none" : ""} pr-0">${feat._slPrereq}</span>
</a>
</div>`)
.contextmenu(evt => ListUtil.openSubContextMenu(evt, listItem))
.click(evt => ListUtil.sublist.doSelect(listItem, evt));
const listItem = new ListItem(
pinId,
$ele,
feat.name,
{
hash,
ability: feat._slAbility,
prerequisite: feat._slPrereq,
},
);
return listItem;
}
doLoadHash (id) {
const feat = this._dataList[id];
$("#pagecontent").empty().append(RenderFeats.$getRenderedFeat(feat));
ListUtil.updateSelected();
}
async pDoLoadSubHash (sub) {
sub = this._filterBox.setFromSubHashes(sub);
await ListUtil.pSetFromSubHashes(sub);
}
}
const featsPage = new FeatsPage();
window.addEventListener("load", () => featsPage.pOnLoad());
| TheGiddyLimit/astranauta.github.io | js/feats.js | JavaScript | mit | 3,311 |
jQuery(document).ready(function($){
var nameDefault = 'Your name...';
var emailDefault = 'Your email...';
var messageDefault = 'Your message...';
// Setting up existing forms
setupforms();
function setupforms() {
// Applying default values
setupDefaultText('#name',nameDefault);
setupDefaultText('#email',emailDefault);
setupDefaultText('#message',messageDefault);
// Focus / Blur check against defaults
focusField('#name');
focusField('#email');
focusField('#message');
}
function setupDefaultText(fieldID,fieldDefault) {
$(fieldID).val(fieldDefault);
$(fieldID).attr('data-default', fieldDefault);
}
function evalDefault(fieldID) {
if($(fieldID).val() != $(fieldID).attr('data-default')) {
return false;
}
else { return true; }
}
function hasDefaults(formType) {
switch (formType)
{
case "contact" :
if(evalDefault('#name') && evalDefault('#email') && evalDefault('#message')) { return true; }
else { return false; }
default :
return false;
}
}
function focusField(fieldID) {
$(fieldID).focus(function(evaluation) {
if(evalDefault(fieldID)) { $(fieldID).val(''); }
}).blur(function(evaluation) {
if(evalDefault(fieldID) || $(fieldID).val() === '') { $(fieldID).val($(fieldID).attr('data-default')); }
});
}
$('.button-submit').click(function(event) {
event.preventDefault();
});
$('#submit-contact').bind('click', function(){
if(!hasDefaults('contact')) { $('#form-contact').submit(); }
});
$("#form-contact").validate({
rules: {
name: {
required: true,
minlength: 3
},
email: {
required: true,
email: true
},
message: {
required: true,
minlength: 10
}
},
messages: {
name: {
required: "Please enter your name.",
minlength: "Name must have at least 3 characters."
},
email: {
required: "Please enter your email address.",
email: "This is not a valid email address format."
},
message: {
required: "Please enter a message.",
minlength: "Message must have at least 10 characters."
}
}
});
function validateContact() {
if(!$('#form-contact').valid()) { return false; }
else { return true; }
}
$("#form-contact").ajaxForm({
beforeSubmit: validateContact,
type: "POST",
url: "assets/php/contact-form-process.php",
data: $("#form-contact").serialize(),
success: function(msg){
$("#form-message").ajaxComplete(function(event, request, settings){
if(msg == 'OK') // Message Sent? Show the 'Thank You' message
{
result = '<span class="form-message-success"><i class="icon-thumbs-up"></i> Your message was sent. Thank you!</span>';
clear = true;
}
else
{
result = '<span class="form-message-error"><i class="icon-thumbs-down"></i> ' + msg +'</span>';
clear = false;
}
$(this).html(result);
if(clear == true) {
$('#name').val('');
$('#email').val('');
$('#message').val('');
}
});
}
});
}); | lightnin/lightnin.github.io | assets/js/jquery.validation.settings.js | JavaScript | mit | 3,099 |
$(document).ready(function() {
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events div.external-event').each(function() {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim($(this).text()), // use the element's text as the event title
className: $.trim($(this).attr("class").split(' ')[1]) // get the class name color[x]
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
/* initialize the calendar
-----------------------------------------------------------------*/
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'agendaWeek,agendaDay'
},
defaultView: 'agendaDay',
timeFormat: 'H:mm{ - H:mm}',
axisFormat: 'H:mm',
minTime: '8:00',
maxTime: '22:00',
allDaySlot: false,
monthNames: ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'],
monthNamesShort: ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'],
dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
titleFormat: {
month: 'yyyy MMMM',
week: "yyyy'年' MMM d'日'{ '—'[ MMM] d'日' }",
day: "dddd, yyyy'年' MMM d'日'"
},
/*defaultEventMinutes: 120, */
selectable: true,
selectHelper: true,
select: function(start, end, allDay) {
var type = false;
var color = false;
var execute = function(){
$("input").each(function(){
(this.checked == true) ? type = $(this).val() : null;
(this.checked == true) ? color = $(this).attr('id') : null;
});
$("#dialog-form").dialog("close");
calendar.fullCalendar('renderEvent',
{
title: type,
start: start,
end: end,
allDay: allDay,
className: color
},
true // make the event "stick"
);
calendar.fullCalendar('unselect');
};
var cancel = function() {
$("#dialog-form").dialog("close");
}
var dialogOpts = {
modal: true,
position: "center",
buttons: {
"确定": execute,
"取消": cancel
}
};
$("#dialog-form").dialog(dialogOpts);
},
editable: true,
eventMouseover: function(event, domEvent) {
/*
for(var key in event){
$("<p>").text(key + ':' + event[key]).appendTo($("body"));
};
*/
var layer = '<div id="events-layer" class="fc-transparent" style="position:absolute; width:100%; height:100%; top:-1px; text-align:right; z-index:100"><a><img src="images/icon_edit.gif" title="edit" width="14" id="edbut'+event._id+'" border="0" style="padding-right:3px; padding-top:2px;" /></a><a><img src="images/icon_delete.png" title="delete" width="14" id="delbut'+event._id+'" border="0" style="padding-right:5px; padding-top:2px;" /></a></div>';
$(this).append(layer);
$("#delbut"+event._id).hide();
$("#delbut"+event._id).fadeIn(300);
$("#delbut"+event._id).click(function() {
calendar.fullCalendar('removeEvents', event._id);
//$.post("delete.php", {eventId: event._id});
calendar.fullCalendar('refetchEvents');
});
$("#edbut"+event._id).hide();
$("#edbut"+event._id).fadeIn(300);
$("#edbut"+event._id).click(function() {
//var title = prompt('Current Event Title: ' + event.title + '\n\nNew Event Title: ');
/*
if(title){
$.post("update_title.php", {eventId: event.id, eventTitle: title});
calendar.fullCalendar('refetchEvents');
}
*/
var type = false;
var color = false;
var execute = function(){
$("input").each(function(){
(this.checked == true) ? type = $(this).val() : null;
(this.checked == true) ? color = $(this).attr('id') : null;
});
$("#dialog-form").dialog("close");
event.title = type;
event.className = color;
calendar.fullCalendar('updateEvent', event);
calendar.fullCalendar('refetchEvents');
};
var cancel = function() {
$("#dialog-form").dialog("close");
}
var dialogOpts = {
modal: true,
position: "center",
buttons: {
"确定": execute,
"取消": cancel
}
};
$("#dialog-form").dialog(dialogOpts);
});
},
eventMouseout: function(calEvent, domEvent) {
$("#events-layer").remove();
},
droppable: true, // this allows things to be dropped onto the calendar !!!
drop: function(date, allDay) { // this function is called when something is dropped
// retrieve the dropped element's stored Event Object
var originalEventObject = $(this).data('eventObject');
// we need to copy it, so that multiple events don't have a reference to the same object
var copiedEventObject = $.extend({}, originalEventObject);
// assign it the date that was reported
copiedEventObject.start = date;
copiedEventObject.end = (date.getTime() + 7200000)/1000;
copiedEventObject.allDay = false;
// render the event on the calendar
// the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
$('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
}
});
}); | vectortiny/FullCalendar_adapt | demos/js/lsn.js | JavaScript | mit | 5,894 |
#!/usr/bin/env node
var app = require('./app'),
config = require('./config');
app.set('port', process.env.PORT || config.app.port);
var server = app.listen(app.get('port'), function() {
"use strict";
console.log('Express server listening on port ' + server.address().port);
});
| junwang1216/iDawn | web/server.js | JavaScript | mit | 293 |
"use strict";
/**
* Storing multiple constant values inside of an object
* Keep in mind the values in the object mean they can be modified
* Which makes no sense for a constant, use wisely if you do this
*/
app.service('$api', ['$http', '$token', '$rootScope', '$sweetAlert', '$msg', 'SERVER_URL',
function ($http, $token, $rootScope, $sweetAlert, $msg, SERVER_URL) {
const SERVER_URI = SERVER_URL + 'api/';
var config = {
headers: {'Authorization': $token.getFromCookie() || $token.getFromLocal() || $token.getFromSession()}
};
/* Authentication Service
----------------------------------------------*/
this.isAuthorized = function (module_name) {
return $http.get(SERVER_URI + 'check_auth', {
headers: {'Authorization': $token.getFromCookie() || $token.getFromLocal() || $token.getFromSession()},
params: {'module_name': module_name}
});
};
this.authenticate = function (data) {
return $http.post(SERVER_URI + 'login', data);
};
this.resetPassword = function (email) {
return $http.post(SERVER_URI + 'reset_password', email);
};
this.exit = function () {
$token.deleteFromAllStorage();
return $http.get(SERVER_URI + 'logout', {params: {user: $rootScope.user} })
};
/* User Service
----------------------------------------------*/
this.findMember = function (params) {
config.params = params;
if (params.search) {
return $http.post(SERVER_URI + 'all_users', params.search, config);
}
return $http.get(SERVER_URI + 'all_users', config);
};
this.removeMember = function (data) {
return $http.delete(SERVER_URI + 'remove_profile/' + data, config);
};
this.updateUserProfile = function (data) {
return $http.put(SERVER_URI + 'update_profile', data, config);
};
this.usersCount = function () {
return $http.get(SERVER_URI + 'users_count', config);
};
/* Shop Service
----------------------------------------------*/
this.makePayment = function (params) {
config.params = params;
return $http.get(SERVER_URI + 'execute_payment', config);
};
/* Chat Service
----------------------------------------------*/
this.getChatList = function (params) {
return $http.get(SERVER_URI+'chat_list', config);
};
this.saveMessage = function(data) {
return $http.post(SERVER_URI + 'save_message', data, config);
};
this.getConversation = function () {
};
/* Product Service
----------------------------------------------*/
this.products = function (params) {
config.params = params;
if (params.search) {
return $http.post(SERVER_URI + 'product_list', params.search, config);
}
return $http.get(SERVER_URI + 'product_list', config);
};
this.productDetail = function (id) {
config.params = {id: id};
return $http.get(SERVER_URI + 'product_detail', config);
};
this.buyProduct = function (params) {
config.params = params;
return $http.get(SERVER_URI + 'buy_product', config);
};
this.handleError = function (res) {
switch (res.status) {
case 400:
$sweetAlert.error(res.statusText, $msg.AUTHENTICATION_ERROR);
break;
case 403:
$sweetAlert.error(res.statusText, $msg.AUTHENTICATION_ERROR);
break;
case 500:
$sweetAlert.error(res.statusText, $msg.INTERNAL_SERVER_ERROR);
break;
case 503:
$sweetAlert.error(res.statusText, $msg.SERVICE_UNAVAILABLE);
break;
case 404:
$sweetAlert.error(res.statusText, $msg.NOT_FOUND_ERROR);
break;
default:
$sweetAlert.error(res.statusText, $msg.INTERNAL_SERVER_ERROR);
break;
}
};
}]);
| shobhit-github/RetailerStock | ngApp/src/services/httpService.js | JavaScript | mit | 4,478 |
/**
* @file Link files.
* @function filelink
* @param {string} src - Source file (actual file) path.
* @param {string} dest - Destination file (link) path.
* @param {object} [options] - Optional settings.
* @param {string} [options.type='symlink'] - Link type
* @param {boolean} [options.mkdirp] - Make parent directories.
* @param {boolean} [options.force] - Force to symlink or not.
* @param {function} callback - Callback when done.
*/
'use strict'
const fs = require('fs')
const argx = require('argx')
const path = require('path')
const {mkdirpAsync, existsAsync, statAsync} = require('asfs')
const _cleanDest = require('./_clean_dest')
const _followSymlink = require('./_follow_symlink')
/** @lends filelink */
async function filelink (src, dest, options) {
let args = argx(arguments)
if (args.pop('function')) {
throw new Error('Callback is no more supported. Use promise interface instead')
}
options = args.pop('object') || {}
const cwd = options.cwd || process.cwd()
src = path.resolve(cwd, args.shift('string'))
dest = path.resolve(cwd, args.shift('string'))
const type = options.type || 'symlink'
const force = !!options.force
const destDir = path.dirname(dest)
src = await _followSymlink(src)
if (options.mkdirp) {
await mkdirpAsync(destDir)
} else {
let exists = await existsAsync(destDir)
if (!exists) {
throw new Error(`Directory not exists: ${destDir}`)
}
}
let srcName = path.relative(destDir, src)
let destName = path.relative(destDir, dest)
let before = (await existsAsync(dest)) && (await statAsync(dest))
if (force) {
await _cleanDest(dest)
}
process.chdir(destDir)
_doLinkSync(srcName, destName, type)
process.chdir(cwd)
let after = (await existsAsync(dest)) && (await statAsync(dest))
await new Promise((resolve) => process.nextTick(() => resolve()))
let unchanged = (before && before.size) === (after && after.size)
return !unchanged
}
module.exports = filelink
function _doLinkSync (src, dest, type) {
switch (type) {
case 'link':
fs.linkSync(src, dest)
break
case 'symlink':
fs.symlinkSync(src, dest)
break
default:
throw new Error('Unknown type:' + type)
}
}
| okunishinishi/node-filelink | lib/filelink.js | JavaScript | mit | 2,238 |
// EXPRESS SERVER HERE //
// BASE SETUP
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
methodOverride = require('method-override'),
// routes = require('./routes/routes'),
morgan = require('morgan'),
serveStatic = require('serve-static'),
errorHandler = require('errorhandler');
// =========================CONFIGURATION===========================//
// =================================================================//
app.set('port', process.env.PORT || 9001);
/*
* Set to 9001 to not interfere with Gulp 9000.
* If you're using Cloud9, or an IDE that uses a different port, process.env.PORT will
* take care of your problems. You don't need to set a new port.
*/
app.use(serveStatic('app', {'index': 'true'})); // Set to True or False if you want to start on Index or not
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(morgan('dev'));
app.use(cookieParser('secret'));
app.use(session({secret: 'evernote now', resave: true, saveUninitialized: true}));
app.use(function(req, res, next) {
res.locals.session = req.session;
next();
});
if (process.env.NODE_ENV === 'development') {
app.use(errorHandler());
}
// ==========================ROUTER=================================//
// =================================================================//
// ROUTES FOR THE API - RUN IN THE ORDER LISTED
var router = express.Router();
// ------------- ROUTES ---------------- //
// REGISTERING THE ROUTES
app.use('/', router);
// STARTING THE SERVER
console.log('Serving on port ' + app.get('port') + '. Serving more Nodes than Big Macs!');
app.listen(app.get('port')); // Not used if Gulp is activated - it is bypassed
exports = module.exports = app; // This is needed otherwise the index.js for routes will not work
| Kinddle/soxy | server/server.js | JavaScript | mit | 2,047 |
//Capturar possibles errors
process.on('uncaughtException', function(err) {
console.log(err);
});
//Importar mòdul net
var net = require('net')
//Port d'escolta del servidor
var port = 8002;
//Crear servidor TCP
net.createServer(function(socket){
socket.on('data', function(data){
//Parse dades JSON
var json=JSON.parse(data);
//Importar mòdul theThingsCoAP
var theThingsCoAP = require('../../')
//Crear client theThingsCoAP
var client = theThingsCoAP.createClient()
client.on('ready', function () {
read(json.endDate)
})
//Funció per llegir dades de la plataforma thethings.iO
function read(endDate){
client.thingRead(json.key, {limit: 100,endDate: endDate, startDate: json.startDate}, function (error, data) {
if (typeof data!=='undefined' && data!==null){
if (data.length > 0) {
var dataSend=""
var coma=","
for (var i=0;i<=(data.length - 1);i++){
dataSend=dataSend+data[i].value+coma+data[i].datetime.split('T')[1]+coma
}
socket.write(dataSend);
read(data[data.length - 1].datetime.split('.')[0].replace(/-/g, '').replace(/:/g, '').replace('T', ''))
}else{
socket.write("</FINAL>");
}
}
})
}
});
//Configuració del port en el servidor TCP
}).listen(port);
| rromero83/thethingsio-coap-openDemo | openDemo/read/Read.js | JavaScript | mit | 1,304 |
import { GET_WAREHOUSES_FULL_LIST, GET_WAREHOUSE, GET_COMPANIES, GET_SUPERVISORS } from '../actions/warehouses';
import humanize from 'humanize';
import Moment from 'moment';
const INITIAL_STATE = {
warehousesList: [],
warehouseDetail: {},
warehouseId: 0,
companiesList: [],
supervisorsList: []
};
export default function(state = INITIAL_STATE, action) {
switch(action.type) {
case GET_WAREHOUSES_FULL_LIST:
return {
...state,
warehousesList: action.payload.data.map(function(warehouse) {
return {
company: warehouse.company,
supervisor: warehouse.supervisor,
email: warehouse.email,
telephone: warehouse.telephone,
address: warehouse.address,
contact_name: warehouse.contact_name,
action: warehouse.id
};
})
};
case GET_WAREHOUSE:
return {
...state,
warehouseDetail: {
company: action.payload.data[0].company_id,
supervisor: action.payload.data[0].supervisor_id,
name: action.payload.data[0].name,
email: action.payload.data[0].email,
telephone: action.payload.data[0].telephone,
address: action.payload.data[0].address,
tax: action.payload.data[0].tax,
contact_name: action.payload.data[0].contact_name
},
warehouseId: action.payload.data[0].id
}
case GET_COMPANIES:
return {
...state,
companiesList: action.payload.data.map(function(company) {
return {
value: company.id,
label: company.name
}
})
}
case GET_SUPERVISORS:
return {
...state,
supervisorsList: action.payload.data.map(function(supervisor) {
return {
value: supervisor.id,
label: supervisor.name
}
})
}
default:
return state;
}
}
| Xabadu/VendOS | src/reducers/reducer_warehouses.js | JavaScript | mit | 2,069 |
dhtmlXForm.prototype.items.calendar = {
render: function(item, data) {
var t = this;
item._type = "calendar";
item._enabled = true;
this.doAddLabel(item, data);
this.doAddInput(item, data, "INPUT", "TEXT", true, true, "dhxform_textarea");
item.childNodes[item._ll?1:0].childNodes[0]._idd = item._idd;
item._f = (data.dateFormat||"%d-%m-%Y"); // formats
item._f0 = (data.serverDateFormat||item._f); // formats for save-load, if set - use them for saving and loading only
item._c = new dhtmlXCalendarObject(item.childNodes[item._ll?1:0].childNodes[0], data.skin||item.getForm().skin||"dhx_skyblue");
item._c._nullInInput = true; // allow null value from input
item._c.enableListener(item.childNodes[item._ll?1:0].childNodes[0]);
item._c.setDateFormat(item._f);
if (!data.enableTime) item._c.hideTime();
if (!isNaN(data.weekStart)) item._c.setWeekStartDay(data.weekStart);
if (typeof(data.calendarPosition) != "undefined") item._c.setPosition(data.calendarPosition);
item._c._itemIdd = item._idd;
item._c.attachEvent("onBeforeChange", function(d) {
if (item._value != d) {
// call some events
if (item.checkEvent("onBeforeChange")) {
if (item.callEvent("onBeforeChange",[item._idd, item._value, d]) !== true) {
return false;
}
}
// accepted
item._value = d;
t.setValue(item, d);
item.callEvent("onChange", [this._itemIdd, item._value]);
}
return true;
});
this.setValue(item, data.value);
return this;
},
getCalendar: function(item) {
return item._c;
},
setSkin: function(item, skin) {
item._c.setSkin(skin);
},
setValue: function(item, value) {
if (!value || value == null || typeof(value) == "undefined" || value == "") {
item._value = null;
item.childNodes[item._ll?1:0].childNodes[0].value = "";
} else {
item._value = (value instanceof Date ? value : item._c._strToDate(value, item._f0));
item.childNodes[item._ll?1:0].childNodes[0].value = item._c._dateToStr(item._value, item._f);
}
item._c.setDate(item._value);
window.dhtmlXFormLs[item.getForm()._rId].vals[item._idd] = item.childNodes[item._ll?1:0].childNodes[0].value;
},
getValue: function(item, asString) {
var d = item._c.getDate();
if (asString===true && d == null) return "";
return (asString===true?item._c._dateToStr(d,item._f0):d);
},
destruct: function(item) {
// unload calendar instance
item._c.unload();
item._c = null;
try {delete item._c;} catch(e){}
item._f = null;
try {delete item._f;} catch(e){}
item._f0 = null;
try {delete item._f0;} catch(e){}
// remove custom events/objects
item.childNodes[item._ll?1:0].childNodes[0]._idd = null;
// unload item
this.d2(item);
item = null;
}
};
(function(){
for (var a in {doAddLabel:1,doAddInput:1,doUnloadNestedLists:1,setText:1,getText:1,enable:1,disable:1,isEnabled:1,setWidth:1,setReadonly:1,isReadonly:1,setFocus:1,getInput:1})
dhtmlXForm.prototype.items.calendar[a] = dhtmlXForm.prototype.items.input[a];
})();
dhtmlXForm.prototype.items.calendar.d2 = dhtmlXForm.prototype.items.input.destruct;
dhtmlXForm.prototype.getCalendar = function(name) {
return this.doWithItem(name, "getCalendar");
};
| lincong1987/foxhis-website | js/dhtmlx/form/ext/calendar.js | JavaScript | mit | 3,369 |
let charLS;
function jpegLSDecode (data, isSigned) {
// prepare input parameters
const dataPtr = charLS._malloc(data.length);
charLS.writeArrayToMemory(data, dataPtr);
// prepare output parameters
const imagePtrPtr = charLS._malloc(4);
const imageSizePtr = charLS._malloc(4);
const widthPtr = charLS._malloc(4);
const heightPtr = charLS._malloc(4);
const bitsPerSamplePtr = charLS._malloc(4);
const stridePtr = charLS._malloc(4);
const allowedLossyErrorPtr = charLS._malloc(4);
const componentsPtr = charLS._malloc(4);
const interleaveModePtr = charLS._malloc(4);
// Decode the image
const result = charLS.ccall(
'jpegls_decode',
'number',
['number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number', 'number'],
[dataPtr, data.length, imagePtrPtr, imageSizePtr, widthPtr, heightPtr, bitsPerSamplePtr, stridePtr, componentsPtr, allowedLossyErrorPtr, interleaveModePtr]
);
// Extract result values into object
const image = {
result,
width: charLS.getValue(widthPtr, 'i32'),
height: charLS.getValue(heightPtr, 'i32'),
bitsPerSample: charLS.getValue(bitsPerSamplePtr, 'i32'),
stride: charLS.getValue(stridePtr, 'i32'),
components: charLS.getValue(componentsPtr, 'i32'),
allowedLossyError: charLS.getValue(allowedLossyErrorPtr, 'i32'),
interleaveMode: charLS.getValue(interleaveModePtr, 'i32'),
pixelData: undefined
};
// Copy image from emscripten heap into appropriate array buffer type
const imagePtr = charLS.getValue(imagePtrPtr, '*');
if (image.bitsPerSample <= 8) {
image.pixelData = new Uint8Array(image.width * image.height * image.components);
image.pixelData.set(new Uint8Array(charLS.HEAP8.buffer, imagePtr, image.pixelData.length));
} else if (isSigned) {
image.pixelData = new Int16Array(image.width * image.height * image.components);
image.pixelData.set(new Int16Array(charLS.HEAP16.buffer, imagePtr, image.pixelData.length));
} else {
image.pixelData = new Uint16Array(image.width * image.height * image.components);
image.pixelData.set(new Uint16Array(charLS.HEAP16.buffer, imagePtr, image.pixelData.length));
}
// free memory and return image object
charLS._free(dataPtr);
charLS._free(imagePtr);
charLS._free(imagePtrPtr);
charLS._free(imageSizePtr);
charLS._free(widthPtr);
charLS._free(heightPtr);
charLS._free(bitsPerSamplePtr);
charLS._free(stridePtr);
charLS._free(componentsPtr);
charLS._free(interleaveModePtr);
return image;
}
function initializeJPEGLS () {
// check to make sure codec is loaded
if (typeof CharLS === 'undefined') {
throw new Error('No JPEG-LS decoder loaded');
}
// Try to initialize CharLS
// CharLS https://github.com/cornerstonejs/charls
if (!charLS) {
charLS = CharLS();
if (!charLS || !charLS._jpegls_decode) {
throw new Error('JPEG-LS failed to initialize');
}
}
}
function decodeJPEGLS (imageFrame, pixelData) {
initializeJPEGLS();
const image = jpegLSDecode(pixelData, imageFrame.pixelRepresentation === 1);
// throw error if not success or too much data
if (image.result !== 0 && image.result !== 6) {
throw new Error(`JPEG-LS decoder failed to decode frame (error code ${image.result})`);
}
imageFrame.columns = image.width;
imageFrame.rows = image.height;
imageFrame.pixelData = image.pixelData;
return imageFrame;
}
export default decodeJPEGLS;
export { initializeJPEGLS };
| google/cornerstoneWADOImageLoader | src/webWorker/decodeTask/decoders/decodeJPEGLS.js | JavaScript | mit | 3,494 |
//= require ./ace/ace
//= require ./ace/mode-ruby
//= require ./ace/theme-tomorrow
//= require ./ace/ext-whitespace
$(function() {
var editor = ace.edit("editor");
editor.setTheme("ace/theme/tomorrow");
editor.getSession().setMode("ace/mode/ruby");
editor.getSession().setTabSize(2);
editor.getSession().setUseSoftTabs(true);
$("form").submit(function() {
$("#content").val(editor.getValue());
});
});
| cctiger36/batch_manager | app/assets/javascripts/batch_manager/editor.js | JavaScript | mit | 422 |
// ===================================================================
//
// Mixology example: SENDER
// Gearcloud Labs, 2014
//
// Main parts
// mNode code (ie, WebRTC setup via Mixology)
//
// Video effects
// Photo booth - Colors and reflections; see effects.js
// Pause/resume video
//
// To run
// localhost:9090/controls/sender.html
//
// ===================================================================
// === Video inits ===================================================
var video = document.createElement('video');
var feed = document.createElement('canvas');
var display = document.createElement('canvas');
video.style.display = 'none';
feed.style.display = 'none';
feed.width = 640;
feed.height = 480;
display.width = 640;
display.height = 480;
document.body.appendChild(video);
document.body.appendChild(feed);
document.body.appendChild(display);
var options = []; // array for visual effect options
// === Mixology initialization ========================================
var CONFIG = {
'iceServers': [ {'url': 'stun:stun.l.google.com:19302' } ]
};
var RTC_OPTIONS = {
optional:[{RtpDataChannels: true}]
};
var SDP_CONSTRAINTS = {'mandatory': {
'OfferToReceiveAudio':true,
'OfferToReceiveVideo':true }};
var VIDEO_CONSTRAINTS = {
mandatory: {
maxWidth:640,
maxHeight:480
},
optional:[]
};
signaller = document.URL.split('/').slice(0,3).join('/');
var stream; // my camera stream
var m = new Mixology(signaller);
var myPeerId;
m.onRegistered = function(peer) {
console.log("onRegistered:"+ JSON.stringify(peer,null,2));
myPeerId = peer.fqmNodeName;
for (var pid in m.inputs) {
// receiveRtcStream starts dance immediately
// to throttle we'd need a handshake before this
// DATA CHANNEL: onMessage enables data channel
m.receiveRtcStream(pid, CONFIG, onAddStream, onRtcMessage, onRtcDataUp);
}
for (var pid in m.outputs) {
// sendRtcStream starts dance immediately
// to throttle we'd need a handshake before this
m.sendRtcStream(pid, stream, CONFIG, onRtcMessage, onRtcDataUp, RTC_OPTIONS);
// m.sendRtcStream(pid, stream, CONFIG);
}
};
m.onPeerRegistered = function(peer) {
console.log("onPeerRegistered:"+JSON.stringify(peer,null,2));
if (peer.direction == "out") {
if (stream) {
// sendRtcStream starts dance immediately
// to throttle we'd need a handshake before this
m.sendRtcStream(peer.peer, stream, CONFIG, onRtcMessage, onRtcDataUp);
}
}
if (peer.direction == "in") {
// receiveRtcStream starts dance immediately
// to throttle we'd need a handshake before this
// DATA CHANNEL: onMessage enables data channel
m.receiveRtcStream(peer.peer, CONFIG, onAddStream, onRtcMessage, onRtcDataUp);
}
};
m.onPeerUnRegistered = function(peer) {
console.log("onPeerUnRegistered:"+JSON.stringify(peer,null,2));
m.closeRtcStream(peer.peer);
};
m.onMessage = function(d) {
console.log("onMessage:"+JSON.stringify(d,null,2));
if (d.data.rtcEvent) {
m.processRtcEvent(d.data, SDP_CONSTRAINTS);
}
};
function onAddStream(stream, peerId) {
console.log("onAddStream called for "+peerId);
}
function onRtcDataUp(peerId) {
console.log("RtcData connection up. Peer:"+peerId);
// m.sendRtcMessage(peerId, "Hello from "+m.fqmNodeName);
}
function onRtcMessage(from, msg) {
console.log("Got RTC Message from:"+from+":"+msg.data);
}
// === Sender code ===================================================================
function getLocalCam() {
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
window.URL = window.URL || window.webkitURL;
if (!navigator.getUserMedia) {
console.log("navigator.getUserMedia() is not available");
// to do: tell user too
}
else {
navigator.getUserMedia({audio: false, video: VIDEO_CONSTRAINTS}, function(strm) {
stream = strm; // save stream because other peers will use it too
// initialize some stuff, only if user accepts use of webcam
document.getElementById("controls").style.visibility = "visible";
// mark camera ready, and check model + audio
console.log("Camera ready");
// Register with Mixology server
m.register([], ['out']); // sender, out
video.src = window.URL.createObjectURL(strm); // Chrome and Firefox
// video.src = stream; // Opera, not tested
video.autoplay = true; // probably not needed
streamFeed(); // start video
}, function(err) {
console.log("GetUserMedia error:"+JSON.stringify(err,null,2));
});
}
}
function streamFeed() {
requestAnimationFrame(streamFeed);
var feedContext = feed.getContext('2d');
var displayContext = display.getContext('2d');
var imageData;
feedContext.drawImage(video, 0, 0, display.width, display.height);
imageData = feedContext.getImageData(0, 0, display.width, display.height);
// add effects
imageData = addEffects(imageData, feed.width, feed.height);
displayContext.putImageData(imageData, 0, 0);
}
//
// BROWSER & WEBGL DETECTION
//
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
var isFirefox = /Firefox/.test(navigator.userAgent);
var isMac = /Mac OS/.test(navigator.userAgent);
var supportsWebGL = function () { try { var canvas = document.createElement( 'canvas' ); return !! window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ); } catch( e ) { return false; } };
if (isChrome) {
console.log("Detected Chrome browser");
if (!supportsWebGL()) {
window.location = "error.html?no-webgl";
}
} else if (isFirefox) {
console.log("Detected Firefox browser");
if (!supportsWebGL()) {
window.location = "error.html?no-webgl";
}
}
else {
window.location = "error.html?not-chrome";
}
// === Initialize =====================================================
// Ask user to allow use of their webcam
function initSender() {
console.log("initSender()");
getLocalCam(); // in turn, registers with Mixology server
}
initSender();
| gearcloudlabs/Mixology | html/controls/sender.js | JavaScript | mit | 6,290 |
// @flow
/* global document */
export default function injectStyles(styles: any) {
const stylesElement = document.createElement('style');
stylesElement.innerText = styles.toString();
return stylesElement;
}
| bbaaxx/big-red-button | src/client/app/helpers/ce-helpers/injectStyles.js | JavaScript | mit | 213 |
import { test , moduleFor } from 'appkit/tests/helpers/module_for';
import Index from 'appkit/routes/index';
moduleFor('route:index', "Unit - IndexRoute");
test("it exists", function(){
ok(this.subject() instanceof Index);
});
| cevn/tasky-web | tests/unit/routes/index_test.js | JavaScript | mit | 233 |
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const asyncLib = require("neo-async");
const Tapable = require("tapable").Tapable;
const AsyncSeriesWaterfallHook = require("tapable").AsyncSeriesWaterfallHook;
const SyncWaterfallHook = require("tapable").SyncWaterfallHook;
const SyncBailHook = require("tapable").SyncBailHook;
const SyncHook = require("tapable").SyncHook;
const HookMap = require("tapable").HookMap;
const NormalModule = require("./NormalModule");
const RawModule = require("./RawModule");
const RuleSet = require("./RuleSet");
const cachedMerge = require("./util/cachedMerge");
const EMPTY_RESOLVE_OPTIONS = {};
const loaderToIdent = data => {
if (!data.options) return data.loader;
if (typeof data.options === "string") return data.loader + "?" + data.options;
if (typeof data.options !== "object")
throw new Error("loader options must be string or object");
if (data.ident) return data.loader + "??" + data.ident;
return data.loader + "?" + JSON.stringify(data.options);
};
const identToLoaderRequest = resultString => {
const idx = resultString.indexOf("?");
let options;
if (idx >= 0) {
options = resultString.substr(idx + 1);
resultString = resultString.substr(0, idx);
return {
loader: resultString,
options
};
} else {
return {
loader: resultString
};
}
};
class NormalModuleFactory extends Tapable {
constructor(context, resolverFactory, options) {
super();
this.hooks = {
resolver: new SyncWaterfallHook(["resolver"]),
factory: new SyncWaterfallHook(["factory"]),
beforeResolve: new AsyncSeriesWaterfallHook(["data"]),
afterResolve: new AsyncSeriesWaterfallHook(["data"]),
createModule: new SyncBailHook(["data"]),
module: new SyncWaterfallHook(["module", "data"]),
createParser: new HookMap(() => new SyncBailHook(["parserOptions"])),
parser: new HookMap(() => new SyncHook(["parser", "parserOptions"])),
createGenerator: new HookMap(
() => new SyncBailHook(["generatorOptions"])
),
generator: new HookMap(
() => new SyncHook(["generator", "generatorOptions"])
)
};
this._pluginCompat.tap("NormalModuleFactory", options => {
switch (options.name) {
case "before-resolve":
case "after-resolve":
options.async = true;
break;
case "parser":
this.hooks.parser
.for("javascript/auto")
.tap(options.fn.name || "unnamed compat plugin", options.fn);
return true;
}
let match;
match = /^parser (.+)$/.exec(options.name);
if (match) {
this.hooks.parser
.for(match[1])
.tap(
options.fn.name || "unnamed compat plugin",
options.fn.bind(this)
);
return true;
}
match = /^create-parser (.+)$/.exec(options.name);
if (match) {
this.hooks.createParser
.for(match[1])
.tap(
options.fn.name || "unnamed compat plugin",
options.fn.bind(this)
);
return true;
}
});
this.resolverFactory = resolverFactory;
this.ruleSet = new RuleSet(options.defaultRules.concat(options.rules));
this.cachePredicate =
typeof options.unsafeCache === "function"
? options.unsafeCache
: Boolean.bind(null, options.unsafeCache);
this.context = context || "";
this.parserCache = Object.create(null);
this.generatorCache = Object.create(null);
this.hooks.factory.tap("NormalModuleFactory", () => (result, callback) => {
let resolver = this.hooks.resolver.call(null);
// Ignored
if (!resolver) return callback();
resolver(result, (err, data) => {
if (err) return callback(err);
// Ignored
if (!data) return callback();
// direct module
if (typeof data.source === "function") return callback(null, data);
this.hooks.afterResolve.callAsync(data, (err, result) => {
if (err) return callback(err);
// Ignored
if (!result) return callback();
let createdModule = this.hooks.createModule.call(result);
if (!createdModule) {
if (!result.request) {
return callback(new Error("Empty dependency (no request)"));
}
createdModule = new NormalModule(result);
}
createdModule = this.hooks.module.call(createdModule, result);
return callback(null, createdModule);
});
});
});
this.hooks.resolver.tap("NormalModuleFactory", () => (data, callback) => {
const contextInfo = data.contextInfo;
const context = data.context;
const request = data.request;
const noPreAutoLoaders = request.startsWith("-!");
const noAutoLoaders = noPreAutoLoaders || request.startsWith("!");
const noPrePostAutoLoaders = request.startsWith("!!");
let elements = request
.replace(/^-?!+/, "")
.replace(/!!+/g, "!")
.split("!");
let resource = elements.pop();
elements = elements.map(identToLoaderRequest);
const loaderResolver = this.getResolver("loader");
const normalResolver = this.getResolver("normal", data.resolveOptions);
asyncLib.parallel(
[
callback =>
this.resolveRequestArray(
contextInfo,
context,
elements,
loaderResolver,
callback
),
callback => {
if (resource === "" || resource[0] === "?") {
return callback(null, {
resource
});
}
normalResolver.resolve(
contextInfo,
context,
resource,
{},
(err, resource, resourceResolveData) => {
if (err) return callback(err);
callback(null, {
resourceResolveData,
resource
});
}
);
}
],
(err, results) => {
if (err) return callback(err);
let loaders = results[0];
const resourceResolveData = results[1].resourceResolveData;
resource = results[1].resource;
// translate option idents
try {
for (const item of loaders) {
if (typeof item.options === "string" && item.options[0] === "?") {
const ident = item.options.substr(1);
item.options = this.ruleSet.findOptionsByIdent(ident);
item.ident = ident;
}
}
} catch (e) {
return callback(e);
}
if (resource === false) {
// ignored
return callback(
null,
new RawModule(
"/* (ignored) */",
`ignored ${context} ${request}`,
`${request} (ignored)`
)
);
}
const userRequest = loaders
.map(loaderToIdent)
.concat([resource])
.join("!");
let resourcePath = resource;
let resourceQuery = "";
const queryIndex = resourcePath.indexOf("?");
if (queryIndex >= 0) {
resourceQuery = resourcePath.substr(queryIndex);
resourcePath = resourcePath.substr(0, queryIndex);
}
const result = this.ruleSet.exec({
resource: resourcePath,
resourceQuery,
issuer: contextInfo.issuer,
compiler: contextInfo.compiler
});
const settings = {};
const useLoadersPost = [];
const useLoaders = [];
const useLoadersPre = [];
for (const r of result) {
if (r.type === "use") {
if (r.enforce === "post" && !noPrePostAutoLoaders)
useLoadersPost.push(r.value);
else if (
r.enforce === "pre" &&
!noPreAutoLoaders &&
!noPrePostAutoLoaders
)
useLoadersPre.push(r.value);
else if (!r.enforce && !noAutoLoaders && !noPrePostAutoLoaders)
useLoaders.push(r.value);
} else if (
typeof r.value === "object" &&
r.value !== null &&
typeof settings[r.type] === "object" &&
settings[r.type] !== null
) {
settings[r.type] = cachedMerge(settings[r.type], r.value);
} else {
settings[r.type] = r.value;
}
}
asyncLib.parallel(
[
this.resolveRequestArray.bind(
this,
contextInfo,
this.context,
useLoadersPost,
loaderResolver
),
this.resolveRequestArray.bind(
this,
contextInfo,
this.context,
useLoaders,
loaderResolver
),
this.resolveRequestArray.bind(
this,
contextInfo,
this.context,
useLoadersPre,
loaderResolver
)
],
(err, results) => {
if (err) return callback(err);
loaders = results[0].concat(loaders, results[1], results[2]);
process.nextTick(() => {
const type = settings.type;
const resolveOptions = settings.resolve;
callback(null, {
context: context,
request: loaders
.map(loaderToIdent)
.concat([resource])
.join("!"),
dependencies: data.dependencies,
userRequest,
rawRequest: request,
loaders,
resource,
resourceResolveData,
settings,
type,
parser: this.getParser(type, settings.parser),
generator: this.getGenerator(type, settings.generator),
resolveOptions
});
});
}
);
}
);
});
}
create(data, callback) {
const dependencies = data.dependencies;
const cacheEntry = dependencies[0].__NormalModuleFactoryCache;
if (cacheEntry) return callback(null, cacheEntry);
const context = data.context || this.context;
const resolveOptions = data.resolveOptions || EMPTY_RESOLVE_OPTIONS;
const request = dependencies[0].request;
const contextInfo = data.contextInfo || {};
this.hooks.beforeResolve.callAsync(
{
contextInfo,
resolveOptions,
context,
request,
dependencies
},
(err, result) => {
if (err) return callback(err);
// Ignored
if (!result) return callback();
const factory = this.hooks.factory.call(null);
// Ignored
if (!factory) return callback();
factory(result, (err, module) => {
if (err) return callback(err);
if (module && this.cachePredicate(module)) {
for (const d of dependencies) {
d.__NormalModuleFactoryCache = module;
}
}
callback(null, module);
});
}
);
}
resolveRequestArray(contextInfo, context, array, resolver, callback) {
if (array.length === 0) return callback(null, []);
asyncLib.map(
array,
(item, callback) => {
resolver.resolve(
contextInfo,
context,
item.loader,
{},
(err, result) => {
if (
err &&
/^[^/]*$/.test(item.loader) &&
!/-loader$/.test(item.loader)
) {
return resolver.resolve(
contextInfo,
context,
item.loader + "-loader",
{},
err2 => {
if (!err2) {
err.message =
err.message +
"\n" +
"BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.\n" +
` You need to specify '${
item.loader
}-loader' instead of '${item.loader}',\n` +
" see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed";
}
callback(err);
}
);
}
if (err) return callback(err);
const optionsOnly = item.options
? {
options: item.options
}
: undefined;
return callback(
null,
Object.assign({}, item, identToLoaderRequest(result), optionsOnly)
);
}
);
},
callback
);
}
getParser(type, parserOptions) {
let ident = type;
if (parserOptions) {
if (parserOptions.ident) ident = `${type}|${parserOptions.ident}`;
else ident = JSON.stringify([type, parserOptions]);
}
if (ident in this.parserCache) {
return this.parserCache[ident];
}
return (this.parserCache[ident] = this.createParser(type, parserOptions));
}
createParser(type, parserOptions = {}) {
const parser = this.hooks.createParser.for(type).call(parserOptions);
if (!parser) {
throw new Error(`No parser registered for ${type}`);
}
this.hooks.parser.for(type).call(parser, parserOptions);
return parser;
}
getGenerator(type, generatorOptions) {
let ident = type;
if (generatorOptions) {
if (generatorOptions.ident) ident = `${type}|${generatorOptions.ident}`;
else ident = JSON.stringify([type, generatorOptions]);
}
if (ident in this.generatorCache) {
return this.generatorCache[ident];
}
return (this.generatorCache[ident] = this.createGenerator(
type,
generatorOptions
));
}
createGenerator(type, generatorOptions = {}) {
const generator = this.hooks.createGenerator
.for(type)
.call(generatorOptions);
if (!generator) {
throw new Error(`No generator registered for ${type}`);
}
this.hooks.generator.for(type).call(generator, generatorOptions);
return generator;
}
getResolver(type, resolveOptions) {
return this.resolverFactory.get(
type,
resolveOptions || EMPTY_RESOLVE_OPTIONS
);
}
}
module.exports = NormalModuleFactory;
| msherer95/tastir | node_modules/webpack/lib/NormalModuleFactory.js | JavaScript | mit | 13,406 |
// ==UserScript==
// @name Youtube BPM Meter
// @version 1.3
// @updateURL https://raw.githubusercontent.com/Greeniac916/YoutubeBPM/master/youtube-bpm.js
// @description Plugin adding beat counter to Youtube
// @author Greeniac916
// @match https://www.youtube.com/*
// @grant none
// @require http://code.jquery.com/jquery-latest.js
// ==/UserScript==
var playButton = $(".ytp-play-button");
var bpmDelay = 0;
var beats = 0;
var interval, loadInt;
function setup() {
//Create HTML String Elements
var card = "<div id='bpm-header' class='yt-card yt-card-has-padding'></div>";
var input = "<input id='bpm-input' placeholder='Enter BPM' type='number' style='vertical-align: middle'>";
var submit = "<input id='bpm-btn' type='button' value='Submit' style='vertical-align: middle'>";
var reset = "<input id='rst-btn' type='button' value='Reset' style='vertical-align: middle'>";
var output = "<span id='span-beats-text' style='float: right; vertical-align: middle;'>Beats: 0</span>";
//Insert Card Div
$("#watch7-content").prepend(card);
//Insert HTML elements to card
$("#bpm-header").append(input);
$("#bpm-header").append(submit);
$("#bpm-header").append(reset);
$("#bpm-header").append(output);
//Bind Buttons
$("#bpm-btn").bind("click", function() {
var bpm = $("#bpm-input")[0].value;
bpmDelay = 60000 / bpm; //Converts BPM to milisecond intervals
clearInterval(interval);
counter();
});
$("#rst-btn").bind("click", function() {
beats = 0;
display(0);
});
}
function display(value) {
$("#span-beats-text")[0].textContent = "Beats: " + value;
}
function counter() {
interval = setInterval(function() {
display(beats);
if (playButton.attr("aria-label") == "Pause") { //If youtube paying video
beats++;
}
}, bpmDelay);
}
function waitForElement(elementPath, callBack){
window.setTimeout(function(){
if($(elementPath).length){
callBack(elementPath, $(elementPath));
}else{
waitForElement(elementPath, callBack);
}
},500);
}
function load() {
console.log("Loading plugin.");
playButton.click();
setup();
$(".video-list-item").bind("click", function() {
waitForElement("#progress", function() {
waitForElement("#eow-title", load);
});
});
$(".yt-lockup").bind("click", function() {
waitForElement("#progress", function() {
waitForElement("#eow-title", load);
});
});
}
(function() {
'use strict';
load();
})();
| Greeniac916/YoutubeBPM | youtube-bpm.js | JavaScript | mit | 2,514 |
/**
* Copyright (c) 2015-present, Pavel Aksonov
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import React, {
Component,
PropTypes,
} from 'react';
import NavigationExperimental from 'react-native-experimental-navigation';
import Actions, { ActionMap } from './Actions';
import getInitialState from './State';
import Reducer, { findElement } from './Reducer';
import DefaultRenderer from './DefaultRenderer';
import Scene from './Scene';
import * as ActionConst from './ActionConst';
const {
RootContainer: NavigationRootContainer,
} = NavigationExperimental;
const propTypes = {
dispatch: PropTypes.func,
};
class Router extends Component {
constructor(props) {
super(props);
this.state = {};
this.renderNavigation = this.renderNavigation.bind(this);
this.handleProps = this.handleProps.bind(this);
}
componentDidMount() {
this.handleProps(this.props);
}
componentWillReceiveProps(props) {
this.handleProps(props);
}
handleProps(props) {
let scenesMap;
if (props.scenes) {
scenesMap = props.scenes;
} else {
let scenes = props.children;
if (Array.isArray(props.children) || props.children.props.component) {
scenes = (
<Scene
key="__root"
hideNav
{...this.props}
>
{props.children}
</Scene>
);
}
scenesMap = Actions.create(scenes, props.wrapBy);
}
// eslint-disable-next-line no-unused-vars
const { children, styles, scenes, reducer, createReducer, ...parentProps } = props;
scenesMap.rootProps = parentProps;
const initialState = getInitialState(scenesMap);
const reducerCreator = props.createReducer || Reducer;
const routerReducer = props.reducer || (
reducerCreator({
initialState,
scenes: scenesMap,
}));
this.setState({ reducer: routerReducer });
}
renderNavigation(navigationState, onNavigate) {
if (!navigationState) {
return null;
}
Actions.get = key => findElement(navigationState, key, ActionConst.REFRESH);
Actions.callback = props => {
const constAction = (props.type && ActionMap[props.type] ? ActionMap[props.type] : null);
if (this.props.dispatch) {
if (constAction) {
this.props.dispatch({ ...props, type: constAction });
} else {
this.props.dispatch(props);
}
}
return (constAction ? onNavigate({ ...props, type: constAction }) : onNavigate(props));
};
return <DefaultRenderer onNavigate={onNavigate} navigationState={navigationState} />;
}
render() {
if (!this.state.reducer) return null;
return (
<NavigationRootContainer
reducer={this.state.reducer}
renderNavigation={this.renderNavigation}
/>
);
}
}
Router.propTypes = propTypes;
export default Router;
| Stoneski93/GymDiary | node_modules/react-native-router-flux/src/Router.js | JavaScript | mit | 3,008 |
var helper = require(__dirname + '/../test-helper');
var CopyFromStream = require(__dirname + '/../../../lib/copystream').CopyFromStream;
var ConnectionImitation = function () {
this.send = 0;
this.hasToBeSend = 0;
this.finished = 0;
};
ConnectionImitation.prototype = {
endCopyFrom: function () {
assert.ok(this.finished++ === 0, "end shoud be called only once");
assert.equal(this.send, this.hasToBeSend, "at the moment of the end all data has to be sent");
},
sendCopyFromChunk: function (chunk) {
this.send += chunk.length;
return true;
},
updateHasToBeSend: function (chunk) {
this.hasToBeSend += chunk.length;
return chunk;
}
};
var buf1 = new Buffer("asdfasd"),
buf2 = new Buffer("q03r90arf0aospd;"),
buf3 = new Buffer(542),
buf4 = new Buffer("93jfemialfjkasjlfas");
test('CopyFromStream, start streaming before data, end after data. no drain event', function () {
var stream = new CopyFromStream();
var conn = new ConnectionImitation();
stream.on('drain', function () {
assert.ok(false, "there has not be drain event");
});
stream.startStreamingToConnection(conn);
assert.ok(stream.write(conn.updateHasToBeSend(buf1)));
assert.ok(stream.write(conn.updateHasToBeSend(buf2)));
assert.ok(stream.write(conn.updateHasToBeSend(buf3)));
assert.ok(stream.writable, "stream has to be writable");
stream.end(conn.updateHasToBeSend(buf4));
assert.ok(!stream.writable, "stream has not to be writable");
stream.end();
assert.equal(conn.hasToBeSend, conn.send);
});
test('CopyFromStream, start streaming after end, end after data. drain event', function () {
var stream = new CopyFromStream();
assert.emits(stream, 'drain', function() {}, 'drain have to be emitted');
var conn = new ConnectionImitation()
assert.ok(!stream.write(conn.updateHasToBeSend(buf1)));
assert.ok(!stream.write(conn.updateHasToBeSend(buf2)));
assert.ok(!stream.write(conn.updateHasToBeSend(buf3)));
assert.ok(stream.writable, "stream has to be writable");
stream.end(conn.updateHasToBeSend(buf4));
assert.ok(!stream.writable, "stream has not to be writable");
stream.end();
stream.startStreamingToConnection(conn);
assert.equal(conn.hasToBeSend, conn.send);
});
test('CopyFromStream, start streaming between data chunks. end after data. drain event', function () {
var stream = new CopyFromStream();
var conn = new ConnectionImitation()
assert.emits(stream, 'drain', function() {}, 'drain have to be emitted');
stream.write(conn.updateHasToBeSend(buf1));
stream.write(conn.updateHasToBeSend(buf2));
stream.startStreamingToConnection(conn);
stream.write(conn.updateHasToBeSend(buf3));
assert.ok(stream.writable, "stream has to be writable");
stream.end(conn.updateHasToBeSend(buf4));
assert.equal(conn.hasToBeSend, conn.send);
assert.ok(!stream.writable, "stream has not to be writable");
stream.end();
});
test('CopyFromStream, start sreaming before end. end stream with data. drain event', function () {
var stream = new CopyFromStream();
var conn = new ConnectionImitation()
assert.emits(stream, 'drain', function() {}, 'drain have to be emitted');
stream.write(conn.updateHasToBeSend(buf1));
stream.write(conn.updateHasToBeSend(buf2));
stream.write(conn.updateHasToBeSend(buf3));
stream.startStreamingToConnection(conn);
assert.ok(stream.writable, "stream has to be writable");
stream.end(conn.updateHasToBeSend(buf4));
assert.equal(conn.hasToBeSend, conn.send);
assert.ok(!stream.writable, "stream has not to be writable");
stream.end();
});
test('CopyFromStream, start streaming after end. end with data. drain event', function(){
var stream = new CopyFromStream();
var conn = new ConnectionImitation()
assert.emits(stream, 'drain', function() {}, 'drain have to be emitted');
stream.write(conn.updateHasToBeSend(buf1));
stream.write(conn.updateHasToBeSend(buf2));
stream.write(conn.updateHasToBeSend(buf3));
stream.startStreamingToConnection(conn);
assert.ok(stream.writable, "stream has to be writable");
stream.end(conn.updateHasToBeSend(buf4));
stream.startStreamingToConnection(conn);
assert.equal(conn.hasToBeSend, conn.send);
assert.ok(!stream.writable, "stream has not to be writable");
stream.end();
});
| xhhjin/heroku-ghost | node_modules/pg/test/unit/copystream/copyfrom-tests.js | JavaScript | mit | 4,368 |
function main () {
const ad_el = document.getElementById('bsa-cpc')
if (!ad_el || innerWidth < 800) {
// if no ad element or element hidden, don't load buysellads
return
}
const script = document.createElement('script')
script.onload = () => {
if (_bsa.isMobile()) {
// bsa doesn't show ads on mobile, hide th box
ad_el.remove()
return
}
_bsa.init('default', 'CK7ITKJU', 'placement:pydantic-docshelpmanualio', {
target: '#bsa-cpc',
align: 'horizontal',
})
ad_el.classList.add('loaded')
}
script.src = 'https://m.servedby-buysellads.com/monetization.js'
document.head.appendChild(script)
}
main()
| samuelcolvin/pydantic | docs/extra/ad.js | JavaScript | mit | 671 |
var g_data;
var margin = {top: 40, right: 45, bottom: 60, left: 60},
width = 460 - margin.left - margin.right,
height = 436 - margin.top - margin.bottom;
var xValue = function(d) { return d.condition;};
var x = d3.scalePoint().range([20, width-20])
var xAxis = d3.axisBottom()
.scale(x);
x.domain(["control","GI.1_12hpi","GI.1_24hpi","GI.2_12hpi","GI.2_24hpi"]);
var y = d3.scaleLinear().range([height, 0]);
var yAxis = d3.axisLeft()
.scale(y)
.ticks(10);
var tool = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
var svg = d3.select("div#rab_gene_scatter").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// add the x axis
svg.append("g")
.attr("class", "x_axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("font-size", "12px")
.style("font-family", "sans-serif")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", ".15em")
.attr("transform", "rotate(-45)");
// add the y axis
svg.append("g")
.attr("class", "y_axis")
.call(yAxis);
// y axis text label
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0 - margin.left)
.attr("x",0 - (height / 2))
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("Reads per Kilobase per Million (rpkm)");
// draw legend
var legend = svg.selectAll(".legend")
.data(["adult", "kitten"])
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
// draw legend colored circles
legend.append("circle")
.attr("cx", width)
.attr("cy", 6)
.attr("r", 5)
.style("fill", function(d) {
if (d == "kitten") {
return "steelblue";
} else {
return "red";
}});
// draw legend text
legend.append("text")
.attr("x", width + 8)
.attr("y", 6)
.attr("dy", ".35em")
.style("text-anchor", "start")
.text(function(d) { return d;})
// read in data
// global variable to check if datafile is already loaded
// if its already loaded don't want to waste time re-loading
// also includes a boolean if a gene should be plotted following data load
var loaded_data = "not_loaded";
function load_scatter_data(data_file, plot_gene, new_gene){
if(loaded_data != data_file){
console.log("loading new file");
$('#current_gene_name').text("LOADING...");
d3.tsv(data_file, function(data) {
data.forEach(function(d) {
d.rpkm = +d.rpkm;
});
g_data = data;
loaded_data = data_file;
$('#current_gene_name').text("Expression scatter plot");
if(plot_gene == true){
update_plot(new_gene);
return;
}
});
};
if(plot_gene == true){
update_plot(new_gene);
return;
}
};
function update_plot(gene_name){
// filter the data for this particular gene
var filt_data = g_data.filter(function(d) { return d.gene == gene_name});
y.domain([0, d3.max(filt_data, function(d) { return d.rpkm; })]);
// Select what we want to change
var scatter_points = svg.selectAll(".matts_bar")
.data(filt_data)
// Make the update changes
//UPDATE
scatter_points.transition().duration(1000)
.attr("cy", function(d) { return y(d.rpkm); });
// add new spots from the enter selection
// note this will only happen once in this case
// ENTER
scatter_points.enter()
.append("circle")
.style("fill", function(d) {
if (d.age == "kitten") {
return "steelblue";
} else {
return "red";
}})
.attr("class", "matts_bar")
.attr("cx", function(d) { return x(d.condition); })
.attr("r", 5)
.on("mouseover", function(d) {
d3.select(this).classed("hover", true);
tool.transition()
.duration(0)
.style("opacity", .9);
tool .html(d.sample)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
d3.select(this).classed("hover", false);
tool.transition()
.duration(0)
.style("opacity", 0);
})
.transition().duration(1000).attr("cy", function(d) { return y(d.rpkm); });
// no need for an EXIT section
// update the y axis info
svg.select(".y_axis")
.transition()
.duration(1000)
.call(yAxis);
// update gene name in window
$('#current_gene_name').text(gene_name);
}
| neavemj/neavemj.github.io | matts_js/rab_gene_scatter.js | JavaScript | mit | 4,829 |
import React from 'react';
import ReactDOM from 'react-dom';
import ReactDOMServer from 'react-dom/server';
import { Router, RouterContext, match, browserHistory, createMemoryHistory } from 'react-router';
import HtmlBase from './pages/html-base';
import routes from './routes';
if (typeof document !== 'undefined') {
const outlet = document.getElementById('outlet');
ReactDOM.render(<Router history={browserHistory} routes={routes} />, outlet);
}
// This is our 'server' rendering
export default (locals, callback) => {
const history = createMemoryHistory();
const location = history.createLocation(locals.path);
// This is from the webpack plugin
match({ routes, location }, (error, redirectLocation, renderProps) => {
// entire page rendering
let html = ReactDOMServer.renderToStaticMarkup(<HtmlBase><RouterContext {...renderProps} /></HtmlBase>)
callback(null, '<!DOCTYPE html>' + html);
});
};
| loganwedwards/react-static-boilerplate | index.js | JavaScript | mit | 928 |
/**
* Template literals are a way to more easily achieve string concatenation.
* Template literals are defined using back ticks (``).
* Placeholders are indicated by using a ${variable}
* Function tags are used to reference functions. Tags are a very handy featurs as they can
* be used to protect against cross-site scripting by html encoding, tags to support localization, etc
*/
describe('template literals', function() {
it('can use placeholders', function() {
let a = 'hello';
let b = 'world';
let result = `${a} ${b}`;
console.log(result);
expect(result).toBe('hello world');
});
it('can use function tags', function() {
function doStuff(...words) {
let text = '';
words.forEach(function(word) {
text += `${word} `;
});
return text.toUpperCase();
}
let result = doStuff('hello', 'world');
console.log(result);
expect(result).toBe('HELLO WORLD ');
});
});
// describe('spread operator', function() {
// it('', function() {
// });
// it('', function() {
// });
// }); | jagretz/playground | es6/template-literals.js | JavaScript | mit | 1,170 |
export function up(queryInterface, Sequelize) {
return Promise.all([
queryInterface.changeColumn('memberships', 'approved', {
type: Sequelize.BOOLEAN,
defaultValue: null,
}),
queryInterface.changeColumn('quotes', 'approved', {
type: Sequelize.BOOLEAN,
defaultValue: null,
}),
]);
}
export function down(queryInterface, Sequelize) {
return Promise.all([
queryInterface.changeColumn('memberships', 'approved', {
type: Sequelize.BOOLEAN,
defaultValue: false,
}),
queryInterface.changeColumn('quotes', 'approved', {
type: Sequelize.BOOLEAN,
defaultValue: false,
}),
]);
}
| rit-sse/node-api | db/migrations/20151021114814-default-null.js | JavaScript | mit | 657 |
import express from 'express';
import path from 'path';
let app = express();
/*** Webpack imports ***/
import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import config from './webpack.config.js';
const webpackOptions = {
publicPath: config.output.publicPath,
// needed so that when going to the localhost:3000 it will load the contents
// from this directory
contentBase: config.devServer.contentBase,
quiet: false,
// hides all the bundling file names
noInfo: true,
// adds color to the terminal
stats: {
colors: true
}
};
const isDevelopment = process.env.NODE_ENV !== 'production';
const port = isDevelopment ? 3003 : process.env.PORT;
const public_path = path.join(__dirname, 'public');
app.use(express.static(public_path))
// .get('/', function(req, res) {
// res.sendFile('index.html', {root: public_path})
// });
/*** during development I am using a webpack-dev-server ***/
if(isDevelopment) {
new WebpackDevServer(webpack(config), webpackOptions)
.listen(port, 'localhost', function(err) {
if (err) { console.log(err); }
console.log(`Listening on port: ${port}`);
});
}
module.exports = app;
| natac13/Tic-Tac-Toe-Game | server.js | JavaScript | mit | 1,257 |
///@INFO: UNCOMMON
// This Component shows the possibility of using another Render Engine within WebGLStudio.
// The idea here is to create a component that calls the other render engine renderer during my rendering method
function ThreeJS( o )
{
this.enabled = true;
this.autoclear = true; //clears the scene on start
this._code = ThreeJS.default_code;
if(global.gl)
{
if( typeof(THREE) == "undefined")
this.loadLibrary( function() { this.setupContext(); } );
else
this.setupContext();
}
this._script = new LScript();
//maybe add function to retrieve texture
this._script.catch_exceptions = false;
if(o)
this.configure(o);
}
ThreeJS.prototype.setupContext = function()
{
if(this._engine)
return;
if( typeof(THREE) == "undefined")
{
console.error("ThreeJS library not loaded");
return;
}
if( !THREE.Scene )
{
console.error("ThreeJS error parsing library");
return; //this could happen if there was an error parsing THREE.JS
}
//GLOBAL VARS
this._engine = {
component: this,
node: this._root,
scene: new THREE.Scene(),
camera: new THREE.PerspectiveCamera( 70, gl.canvas.width / gl.canvas.height, 1, 1000 ),
renderer: new THREE.WebGLRenderer( { canvas: gl.canvas, context: gl } ),
root: new THREE.Object3D(),
ThreeJS: this.constructor
};
this._engine.scene.add( this._engine.root );
}
ThreeJS.default_code = "//renderer, camera, scene, already created, they are globals.\n//use root as your base Object3D node if you want to use the scene manipulators.\n\nthis.start = function() {\n}\n\nthis.render = function(){\n}\n\nthis.update = function(dt){\n}\n";
ThreeJS.library_url = "http://threejs.org/build/three.js";
Object.defineProperty( ThreeJS.prototype, "code", {
set: function(v)
{
this._code = v;
this.processCode();
},
get: function() { return this._code; },
enumerable: true
});
ThreeJS["@code"] = { widget: "code", allow_inline: false };
ThreeJS.prototype.onAddedToScene = function( scene )
{
LEvent.bind( ONE.Renderer, "renderInstances", this.onEvent, this );
LEvent.bind( scene, "start", this.onEvent, this );
LEvent.bind( scene, "update", this.onEvent, this );
LEvent.bind( scene, "finish", this.onEvent, this );
this.processCode();
}
ThreeJS.prototype.clearScene = function()
{
if(!this._engine)
return;
//remove inside root
var root = this._engine.root;
for( var i = root.children.length - 1; i >= 0; i--)
root.remove( root.children[i] );
//remove inside scene but not root
root = this._engine.scene;
for( var i = root.children.length - 1; i >= 0; i--)
if( root.children[i] != this._engine.root )
root.remove( root.children[i] );
}
ThreeJS.prototype.onRemovedFromScene = function( scene )
{
LEvent.unbind( ONE.Renderer, "renderInstances", this.onEvent, this );
LEvent.unbindAll( scene, this );
//clear scene
if(this.autoclear)
this.clearScene();
}
ThreeJS.prototype.onEvent = function( e, param )
{
if( !this.enabled || !this._engine )
return;
var engine = this._engine;
if(e == "start")
{
//clear scene?
if(this.autoclear)
this.clearScene();
if(this._script)
this._script.callMethod( "start" );
}
else if(e == "renderInstances")
{
//copy camera info so both cameras matches
var current_camera = ONE.Renderer._current_camera;
engine.camera.fov = current_camera.fov;
engine.camera.aspect = current_camera._final_aspect;
engine.camera.near = current_camera.near;
engine.camera.far = current_camera.far;
engine.camera.updateProjectionMatrix()
engine.camera.position.fromArray( current_camera._global_eye );
engine.camera.lookAt( new THREE.Vector3( current_camera._global_center[0], current_camera._global_center[1], current_camera._global_center[2] ) );
//copy the root info
ThreeJS.copyTransform( this._root, engine.root );
//render using ThreeJS
engine.renderer.setSize( gl.viewport_data[2], gl.viewport_data[3] );
if( engine.renderer.resetGLState )
engine.renderer.resetGLState();
else if( engine.renderer.state.reset )
engine.renderer.state.reset();
if(this._script)
this._script.callMethod( "render" );
else
engine.renderer.render( engine.scene, engine.camera ); //render the scene
//reset GL here?
//read the root position and update the node?
}
else if(e == "update")
{
if(this._script)
this._script.callMethod( "update", param );
else
engine.scene.update( param );
}
else if(e == "finish")
{
if(this._script)
this._script.callMethod( "finish" );
}
}
/*
ThreeJS.prototype.getCode = function()
{
return this.code;
}
ThreeJS.prototype.setCode = function( code, skip_events )
{
this.code = code;
this.processCode( skip_events );
}
*/
ThreeJS.copyTransform = function( a, b )
{
//litescene to threejs
if( a.constructor === ONE.SceneNode )
{
var global_position = vec3.create();
if(a.transform)
a.transform.getGlobalPosition( global_position );
b.position.set( global_position[0], global_position[1], global_position[2] );
//rotation
var global_rotation = quat.create();
if(a.transform)
a.transform.getGlobalRotation( global_rotation );
b.quaternion.set( global_rotation[0], global_rotation[1], global_rotation[2], global_rotation[3] );
//scale
var global_scale = vec3.fromValues(1,1,1);
if(a.transform)
a.transform.getGlobalScale( global_scale );
b.scale.set( global_scale[0], global_scale[1], global_scale[2] );
}
if( a.constructor === ONE.Transform )
{
var global_position = vec3.create();
a.getGlobalPosition( global_position );
b.position.set( global_position[0], global_position[1], global_position[2] );
//rotation
var global_rotation = quat.create();
a.getGlobalRotation( global_rotation );
b.quaternion.set( global_rotation[0], global_rotation[1], global_rotation[2], global_rotation[3] );
//scale
var global_scale = vec3.fromValues(1,1,1);
a.getGlobalScale( global_scale );
b.scale.set( global_scale[0], global_scale[1], global_scale[2] );
}
else //threejs to litescene
{
if( b.constructor == ONE.Transform )
b.fromMatrix( a.matrixWorld );
else if( b.constructor == ONE.SceneNode && b.transform )
b.transform.fromMatrix( a.matrixWorld );
}
}
ThreeJS.prototype.loadLibrary = function( on_complete )
{
if( typeof(THREE) !== "undefined" )
{
if(on_complete)
on_complete.call(this);
return;
}
if( this._loading )
{
LEvent.bind( this, "threejs_loaded", on_complete, this );
return;
}
if(this._loaded)
{
if(on_complete)
on_complete.call(this);
return;
}
this._loading = true;
var that = this;
ONE.Network.requestScript( ThreeJS.library_url, function(){
console.log("ThreeJS library loaded");
that._loading = false;
that._loaded = true;
LEvent.trigger( that, "threejs_loaded" );
LEvent.unbindAllEvent( that, "threejs_loaded" );
if(!that._engine)
that.setupContext();
});
}
ThreeJS.prototype.processCode = function( skip_events )
{
if(!this._script || !this._root || !this._root.scene )
return;
this._script.code = this.code;
//force threejs inclusion
if( typeof(THREE) == "undefined")
{
this.loadLibrary( function() {
this.processCode();
});
return;
}
if(!this._engine)
this.setupContext();
if(this._root && !ONE.Script.block_execution )
{
//compiles and executes the context
return this._script.compile( this._engine, true );
}
return true;
}
ONE.registerComponent( ThreeJS );
| jagenjo/litescene.js | src/addons/scripts/threeJS.js | JavaScript | mit | 7,669 |
'use strict';
var path = require('path')
, chai = require('chai')
, expect = chai.expect
, sumChildren = require(path.join(__dirname, '..', 'lib', 'util', 'sum-children'))
;
describe("simplifying timings lists", function () {
it("should correctly reduce a simple list", function () {
expect(sumChildren([[22, 42]])).equal(20);
});
it("should accurately sum overlapping child traces", function () {
var intervals = [];
// start with a simple interval
intervals.push([ 0, 22]);
// add another interval completely encompassed by the first
intervals.push([ 5, 10]);
// add another that starts within the first range but extends beyond
intervals.push([11, 33]);
// add a final interval that's entirely disjoint
intervals.push([35, 39]);
expect(sumChildren(intervals)).equal(37);
});
it("should accurately sum partially overlapping child traces", function () {
var intervals = [];
// start with a simple interval
intervals.push([ 0, 22]);
// add another interval completely encompassed by the first
intervals.push([ 5, 10]);
// add another that starts simultaneously with the first range but that extends beyond
intervals.push([ 0, 33]);
expect(sumChildren(intervals)).equal(33);
});
it("should accurately sum partially overlapping, open-ranged child traces", function () {
var intervals = [];
// start with a simple interval
intervals.push([ 0, 22]);
// add a range that starts at the exact end of the first
intervals.push([22, 33]);
expect(sumChildren(intervals)).equal(33);
});
});
| quantumlicht/collarbone | node_modules/newrelic/test/sum-children.test.js | JavaScript | mit | 1,679 |
import $ from 'jquery';
let hoverChildDirective = {
bind: (el, binding) => {
$(el)
.on('mouseenter', function(event) {
$(el).children('.icon').addClass(binding.value);
})
.on('mouseleave', function(event) {
$(el).children('.icon').removeClass(binding.value);
});
}
};
export { hoverChildDirective };
| skluck/skill-survey | src/directives/hover-child.js | JavaScript | mit | 398 |
var searchData=
[
['size_0',['size',['../struct_vma_allocation_info.html#aac76d113a6a5ccbb09fea00fb25fd18f',1,'VmaAllocationInfo::size()'],['../struct_vma_virtual_block_create_info.html#a670ab8c6a6e822f3c36781d79e8824e9',1,'VmaVirtualBlockCreateInfo::size()'],['../struct_vma_virtual_allocation_create_info.html#aae08752b86817abd0d944c6025dc603e',1,'VmaVirtualAllocationCreateInfo::size()'],['../struct_vma_virtual_allocation_info.html#afb6d6bd0a6813869ea0842048d40aa2b',1,'VmaVirtualAllocationInfo::size()']]],
['srcallocation_1',['srcAllocation',['../struct_vma_defragmentation_move.html#a25aa1bb64efc507a49c6cbc50689f862',1,'VmaDefragmentationMove']]],
['statistics_2',['statistics',['../struct_vma_detailed_statistics.html#a13efbdb35bd1291191d275f43e96d360',1,'VmaDetailedStatistics::statistics()'],['../struct_vma_budget.html#a6d15ab3a798fd62d9efa3a1e1f83bf54',1,'VmaBudget::statistics()']]]
];
| GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator | docs/html/search/variables_9.js | JavaScript | mit | 906 |
var theServersDao = require('../daos/ServersDao');
var ServerMatcherMiddleware = function (pReq, pRes, pNext) {
'use strict';
var ip = pReq.headers['x-forwarded-for'] || pReq.connection.remoteAddress;
theServersDao.getServerIdByIp(ip, function (pData) {
if (pData.error) {
var server = {
ip: ip
};
theServersDao.createServer(server, function (pData) {
pReq.body.server_id = pData.id;
pNext();
});
} else {
pReq.body.server_id = pData.id;
pNext();
}
});
};
module.exports = ServerMatcherMiddleware;
| codyseibert/random | stethoscope/src/middleware/ServerMatcherMiddleware.js | JavaScript | mit | 662 |
!(function() {
'use strict';
function ComponentLoader($window, $q) {
var self = this;
this.basePath = '.';
this.queue = [ /*{path: '.', name: 'svg-viewer', scripts:['lazy.js'], run: function(){}}*/ ];
this.loaded = { /*'svg-viewer':true'*/ };
this.loadAll = function() {
var components = self.queue.map(function loadEach(component) {
component.pending = true;
return self.load(component);
})
return $q.all(components);
}
this.load = function(component) {
if (angular.isString(component)) {
component = resolveComponent(component)
}
if (!component)
throw new Error('The lazy component is not registered and cannot load')
if (!component.name)
throw new Error('The lazy component must register with name property and cannot load');
if (self.loaded[component.name]) {
return $q.when(component);
}
var scripts = component.scripts.map(function scriptInComponent(path) {
return loadItem(path, component);
});
return $q.all(scripts).then(function(result) {
component.pending = false;
self.loaded[component.name] = true;
if (angular.isFunction(component.run))
component.run.apply(component);
return component;
});
}
function resolveComponent(name) {
var match = self.queue.filter(function componentFilter(component) {
return component.name === name;
});
return match.length ? match[0] : null;
}
function loadItem(path, component) {
var d = $q.defer();
var startPath = component.path || self.basePath;
var newScriptTag = document.createElement('script');
newScriptTag.type = 'text/javascript';
newScriptTag.src = startPath ? startPath + '/' + path : path;
console.log(component.path)
newScriptTag.setAttribute('data-name', component.name)
newScriptTag.addEventListener('load', function(ev) {
d.resolve(component);
});
newScriptTag.addEventListener('error', function(ev) {
d.reject(component);
});
$window.setTimeout(function() {
if (component.pending) {
throw new Error('Component ' + component.name + ' did not load in time.');
}
}, 10000);
document.head.appendChild(newScriptTag);
return d.promise;
}
}
ComponentLoader.$inject = ['$window', '$q'];
angular.module('lazy.components', ['ng']).service('componentLoader', ComponentLoader);
})();
| MrCrimp/lazy-components | src/lazy-components.js | JavaScript | mit | 2,555 |
var url = require('url')
, path = require('path')
, fs = require('fs')
, utils = require('./utils')
, EventEmitter = require('events').EventEmitter
exports = module.exports = Context
function Context(app, req, res) {
var self = this
this.app = app
this.req = req
this.res = res
this.done = this.done.bind(this)
EventEmitter.call(this)
var socket = res.socket
res.on('finish', done)
socket.on('error', done)
socket.on('close', done)
function done(err) {
res.removeListener('finish', done)
socket.removeListener('error', done)
socket.removeListener('close', done)
self.done(err)
}
}
Context.prototype = {
done: function(err) {
if (this._notifiedDone === true) return
if (err) {
if (this.writable) {
this.resHeaders = {}
this.type = 'text/plain'
this.status = err.code === 'ENOENT' ? 404 : (err.status || 500)
this.length = Buffer.byteLength(err.message)
this.res.end(err.message)
}
this.app.emit('error', err)
}
this._notifiedDone = true
this.emit('done', err)
},
throw: function(status, err) {
status = status || 500
err = err || {}
err.status = status
err.message = err.message || status.toString()
this.done(err)
},
render: function *(view, locals) {
var app = this.app
, viewPath = path.join(app.viewRoot, view)
, ext = path.extname(viewPath)
, exts, engine, content, testPath, i, j
if (!ext || (yield utils.fileExists(viewPath))) {
for (i = 0; app.viewEngines[i]; i++) {
exts = (app.viewEngines[i].exts || ['.' + app.viewEngines[i].name.toLowerCase()])
if (ext) {
if (~exts.indexOf(ext)) {
engine = app.viewEngines[i]
break
}
continue
}
for (j = 0; exts[j]; j++) {
testPath = viewPath + exts[j]
if (yield utils.fileExists(testPath)) {
viewPath = testPath
engine = app.viewEngines[i]
break
}
}
}
}
if (!engine) return this.throw(500, new Error('View does not exist'))
return yield engine.render(viewPath, locals)
},
/*
* opts: { path: ..., domain: ..., expires: ..., maxAge: ..., httpOnly: ..., secure: ..., sign: ... }
*/
cookie: function(name, val, opts) {
if (!opts) opts = {}
if (typeof val == 'object') val = JSON.stringify(val)
if (this.secret && opts.sign) {
val = this.app.cookies.prefix + this.app.cookies.sign(val, this.secret)
}
var headerVal = name + '=' + val + '; Path=' + (opts.path || '/')
if (opts.domain) headerVal += '; Domain=' + opts.domain
if (opts.expires) {
if (typeof opts.expires === 'number') opts.expires = new Date(opts.expires)
if (opts.expires instanceof Date) opts.expires = opts.expires.toUTCString()
headerVal += '; Expires=' + opts.expires
}
if (opts.maxAge) headerVal += '; Max-Age=' + opts.maxAge
if (opts.httpOnly) headerVal += '; HttpOnly'
if (opts.secure) headerVal += '; Secure'
this.setResHeader('Set-Cookie', headerVal)
},
get writable() {
var socket = this.res.socket
return socket && socket.writable && !this.res.headersSent
},
get path() {
return url.parse(this.url).pathname
},
set path(val) {
var obj = url.parse(this.url)
obj.pathname = val
this.url = url.format(obj)
},
get status() {
return this._status
},
set status(code) {
this._status = this.res.statusCode = code
},
get type() {
return this.getResHeader('Content-Type')
},
set type(val) {
if (val == null) return this.removeResHeader('Content-Type')
this.setResHeader('Content-Type', val)
},
get length() {
return this.getResHeader('Content-Length')
},
set length(val) {
if (val == null) return this.removeResHeader('Content-Length')
this.setResHeader('Content-Length', val)
},
get body() {
return this._body
},
set body(val) {
this._body = val
}
}
utils.extend(Context.prototype, EventEmitter.prototype)
utils.proxy(Context.prototype, {
req: {
method : 'access',
url : 'access',
secure : 'getter',
headers : ['getter', 'reqHeaders'],
},
res: {
_headers : ['access', 'resHeaders'],
getHeader : ['invoke', 'getResHeader'],
setHeader : ['invoke', 'setResHeader'],
removeHeader : ['invoke', 'removeResHeader']
}
}) | buunguyen/starweb | lib/context.js | JavaScript | mit | 4,494 |
var express = require('express');
var soapSave = require('../utils/soa_save_esig')('http://192.168.0.6:8001/soa-infra/services/default/SignatureService/SignatureService_ep?WSDL');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res) {
var sig = req.query;
console.log(sig);
if(!sig.userRoleType){
res.render('front_end', { title: 'MPSTD CAC Signature', cacContent: "need to supply userRoleType" });
return;
}
if (sig.req_type && sig.req_type == 'r'){
var inputData = {
applicantId: sig.applicantId,
formId: sig.formId,
userRoleType: sig.userRoleType
};
soapSave.retrieve(inputData,function (result ){
var b64string = result.signatureImage;
if(b64string == null){
res.render('front_end', { title: 'MPSTD CAC Signature', cacContent: "no sig found" });
}
else{
var buf = new Buffer(b64string, 'base64');
var cacObj =JSON.parse( buf.toString('ascii') );
res.render('response',
{ title: 'MPSTD CAC Signature response', cacContent: JSON.stringify(cacObj.subject),
cacSignature: JSON.stringify(cacObj.fingerprint),
timeStamp: JSON.stringify(result.signatureDateTime)
});
// console.log("base64 buffer length = " +buf.length);
}
} );
}
else{//default Esing sign pad
res.render('front_end', { title: 'MPSTD CAC Signature', cacContent: "no sig found" });
}
});
module.exports = router; | taenaive/CACSignature | routes/frontEndRoute.js | JavaScript | mit | 1,544 |
// Underscore.js 1.4.3
// http://underscorejs.org
// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore may be freely distributed under the MIT license.
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `global` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Establish the object that gets returned to break out of a loop iteration.
var breaker = {};
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var push = ArrayProto.push,
slice = ArrayProto.slice,
concat = ArrayProto.concat,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeForEach = ArrayProto.forEach,
nativeMap = ArrayProto.map,
nativeReduce = ArrayProto.reduce,
nativeReduceRight = ArrayProto.reduceRight,
nativeFilter = ArrayProto.filter,
nativeEvery = ArrayProto.every,
nativeSome = ArrayProto.some,
nativeIndexOf = ArrayProto.indexOf,
nativeLastIndexOf = ArrayProto.lastIndexOf,
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object via a string identifier,
// for Closure Compiler "advanced" mode.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.4.3';
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (_.has(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
// Return the results of applying the iterator to each element.
// Delegates to **ECMAScript 5**'s native `map` if available.
_.map = _.collect = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
each(obj, function(value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
return results;
};
var reduceError = 'Reduce of empty array with no initial value';
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
_.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduce && obj.reduce === nativeReduce) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
}
each(obj, function(value, index, list) {
if (!initial) {
memo = value;
initial = true;
} else {
memo = iterator.call(context, memo, value, index, list);
}
});
if (!initial) throw new TypeError(reduceError);
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
// Delegates to **ECMAScript 5**'s native `reduceRight` if available.
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
}
var length = obj.length;
if (length !== +length) {
var keys = _.keys(obj);
length = keys.length;
}
each(obj, function(value, index, list) {
index = keys ? keys[--length] : --length;
if (!initial) {
memo = obj[index];
initial = true;
} else {
memo = iterator.call(context, memo, obj[index], index, list);
}
});
if (!initial) throw new TypeError(reduceError);
return memo;
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, iterator, context) {
var result;
any(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Delegates to **ECMAScript 5**'s native `filter` if available.
// Aliased as `select`.
_.filter = _.select = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
each(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, iterator, context) {
return _.filter(obj, function(value, index, list) {
return !iterator.call(context, value, index, list);
}, context);
};
// Determine whether all of the elements match a truth test.
// Delegates to **ECMAScript 5**'s native `every` if available.
// Aliased as `all`.
_.every = _.all = function(obj, iterator, context) {
iterator || (iterator = _.identity);
var result = true;
if (obj == null) return result;
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
each(obj, function(value, index, list) {
if (!(result = result && iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if at least one element in the object matches a truth test.
// Delegates to **ECMAScript 5**'s native `some` if available.
// Aliased as `any`.
var any = _.some = _.any = function(obj, iterator, context) {
iterator || (iterator = _.identity);
var result = false;
if (obj == null) return result;
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
each(obj, function(value, index, list) {
if (result || (result = iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if the array or object contains a given value (using `===`).
// Aliased as `include`.
_.contains = _.include = function(obj, target) {
if (obj == null) return false;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
return any(obj, function(value) {
return value === target;
});
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
return _.map(obj, function(value) {
return (_.isFunction(method) ? method : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, function(value){ return value[key]; });
};
// Convenience version of a common use case of `filter`: selecting only objects
// with specific `key:value` pairs.
_.where = function(obj, attrs) {
if (_.isEmpty(attrs)) return [];
return _.filter(obj, function(value) {
for (var key in attrs) {
if (attrs[key] !== value[key]) return false;
}
return true;
});
};
// Return the maximum element or (element-based computation).
// Can't optimize arrays of integers longer than 65,535 elements.
// See: https://bugs.webkit.org/show_bug.cgi?id=80797
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
return Math.max.apply(Math, obj);
}
if (!iterator && _.isEmpty(obj)) return -Infinity;
var result = {computed : -Infinity, value: -Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed >= result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
return Math.min.apply(Math, obj);
}
if (!iterator && _.isEmpty(obj)) return Infinity;
var result = {computed : Infinity, value: Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed < result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Shuffle an array.
_.shuffle = function(obj) {
var rand;
var index = 0;
var shuffled = [];
each(obj, function(value) {
rand = _.random(index++);
shuffled[index - 1] = shuffled[rand];
shuffled[rand] = value;
});
return shuffled;
};
// An internal function to generate lookup iterators.
var lookupIterator = function(value) {
return _.isFunction(value) ? value : function(obj){ return obj[value]; };
};
// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, value, context) {
var iterator = lookupIterator(value);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value : value,
index : index,
criteria : iterator.call(context, value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index < right.index ? -1 : 1;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(obj, value, context, behavior) {
var result = {};
var iterator = lookupIterator(value || _.identity);
each(obj, function(value, index) {
var key = iterator.call(context, value, index, obj);
behavior(result, key, value);
});
return result;
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = function(obj, value, context) {
return group(obj, value, context, function(result, key, value) {
(_.has(result, key) ? result[key] : (result[key] = [])).push(value);
});
};
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = function(obj, value, context) {
return group(obj, value, context, function(result, key) {
if (!_.has(result, key)) result[key] = 0;
result[key]++;
});
};
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iterator, context) {
iterator = iterator == null ? _.identity : lookupIterator(iterator);
var value = iterator.call(context, obj);
var low = 0, high = array.length;
while (low < high) {
var mid = (low + high) >>> 1;
iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
}
return low;
};
// Safely convert anything iterable into a real, live array.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (obj.length === +obj.length) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N. The **guard** check allows it to work with
// `_.map`.
_.initial = function(array, n, guard) {
return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if ((n != null) && !guard) {
return slice.call(array, Math.max(array.length - n, 0));
} else {
return array[array.length - 1];
}
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, (n == null) || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, output) {
each(input, function(value) {
if (_.isArray(value)) {
shallow ? push.apply(output, value) : flatten(value, shallow, output);
} else {
output.push(value);
}
});
return output;
};
// Return a completely flattened version of an array.
_.flatten = function(array, shallow) {
return flatten(array, shallow, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iterator, context) {
if (_.isFunction(isSorted)) {
context = iterator;
iterator = isSorted;
isSorted = false;
}
var initial = iterator ? _.map(array, iterator, context) : array;
var results = [];
var seen = [];
each(initial, function(value, index) {
if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
seen.push(value);
results.push(array[index]);
}
});
return results;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(concat.apply(ArrayProto, arguments));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.indexOf(other, item) >= 0;
});
});
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
return _.filter(array, function(value){ return !_.contains(rest, value); });
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
var args = slice.call(arguments);
var length = _.max(_.pluck(args, 'length'));
var results = new Array(length);
for (var i = 0; i < length; i++) {
results[i] = _.pluck(args, "" + i);
}
return results;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
if (list == null) return {};
var result = {};
for (var i = 0, l = list.length; i < l; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
// we need this function. Return the position of the first occurrence of an
// item in an array, or -1 if the item is not included in the array.
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, l = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
for (; i < l; i++) if (array[i] === item) return i;
return -1;
};
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
_.lastIndexOf = function(array, item, from) {
if (array == null) return -1;
var hasIndex = from != null;
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
}
var i = (hasIndex ? from : array.length);
while (i--) if (array[i] === item) return i;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = arguments[2] || 1;
var len = Math.max(Math.ceil((stop - start) / step), 0);
var idx = 0;
var range = new Array(len);
while(idx < len) {
range[idx++] = start;
start += step;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Reusable constructor function for prototype setting.
var ctor = function(){};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Binding with arguments is also known as `curry`.
// Delegates to **ECMAScript 5**'s native `Function.bind` if available.
// We check for `func.bind` first, to fail fast when `func` is undefined.
_.bind = function(func, context) {
var args, bound;
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError;
args = slice.call(arguments, 2);
return bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
ctor.prototype = func.prototype;
var self = new ctor;
ctor.prototype = null;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) return result;
return self;
};
};
// Bind all of an object's methods to that object. Useful for ensuring that
// all callbacks defined on an object belong to it.
_.bindAll = function(obj) {
var funcs = slice.call(arguments, 1);
if (funcs.length == 0) funcs = _.functions(obj);
each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memo = {};
hasher || (hasher = _.identity);
return function() {
var key = hasher.apply(this, arguments);
return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
};
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){ return func.apply(null, args); }, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time.
_.throttle = function(func, wait) {
var context, args, timeout, result;
var previous = 0;
var later = function() {
previous = new Date;
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = new Date;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout, result;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) result = func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) result = func.apply(context, args);
return result;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
memo = func.apply(this, arguments);
func = null;
return memo;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return function() {
var args = [func];
push.apply(args, arguments);
return wrapper.apply(this, args);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var funcs = arguments;
return function() {
var args = arguments;
for (var i = funcs.length - 1; i >= 0; i--) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
if (times <= 0) return func();
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = nativeKeys || function(obj) {
if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
var values = [];
for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
return values;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
var pairs = [];
for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
return result;
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
}
});
return obj;
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
each(keys, function(key) {
if (key in obj) copy[key] = obj[key];
});
return copy;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
for (var key in obj) {
if (!_.contains(keys, key)) copy[key] = obj[key];
}
return copy;
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
each(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
if (obj[prop] == null) obj[prop] = source[prop];
}
}
});
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
if (a === b) return a !== 0 || 1 / a == 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className != toString.call(b)) return false;
switch (className) {
// Strings, numbers, dates, and booleans are compared by value.
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return a == String(b);
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
// other numeric values.
return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a == +b;
// RegExps are compared by their source patterns and flags.
case '[object RegExp]':
return a.source == b.source &&
a.global == b.global &&
a.multiline == b.multiline &&
a.ignoreCase == b.ignoreCase;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] == a) return bStack[length] == b;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
var size = 0, result = true;
// Recursively compare objects and arrays.
if (className == '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size == b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
if (!(result = eq(a[size], b[size], aStack, bStack))) break;
}
}
} else {
// Objects with different constructors are not equivalent, but `Object`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
_.isFunction(bCtor) && (bCtor instanceof bCtor))) {
return false;
}
// Deep compare objects.
for (var key in a) {
if (_.has(a, key)) {
// Count the expected number of properties.
size++;
// Deep compare each member.
if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
}
}
// Ensure that both objects contain the same number of properties.
if (result) {
for (key in b) {
if (_.has(b, key) && !(size--)) break;
}
result = !size;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return result;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b, [], []);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (_.has(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) == '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
return obj === Object(obj);
};
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) == '[object ' + name + ']';
};
});
// Define a fallback version of the method in browsers (ahem, IE), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return !!(obj && _.has(obj, 'callee'));
};
}
// Optimize `isFunction` if appropriate.
if (typeof (/./) !== 'function') {
_.isFunction = function(obj) {
return typeof obj === 'function';
};
}
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj != +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iterators.
_.identity = function(value) {
return value;
};
// Run a function **n** times.
_.times = function(n, iterator, context) {
var accum = Array(n);
for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
return accum;
};
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + (0 | Math.random() * (max - min + 1));
};
// List of HTML entities for escaping.
var entityMap = {
escape: {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
}
};
entityMap.unescape = _.invert(entityMap.escape);
// Regexes containing the keys and values listed immediately above.
var entityRegexes = {
escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
};
// Functions for escaping and unescaping strings to/from HTML interpolation.
_.each(['escape', 'unescape'], function(method) {
_[method] = function(string) {
if (string == null) return '';
return ('' + string).replace(entityRegexes[method], function(match) {
return entityMap[method][match];
});
};
});
// If the value of the named property is a function then invoke it;
// otherwise, return it.
_.result = function(object, property) {
if (object == null) return null;
var value = object[property];
return _.isFunction(value) ? value.call(object) : value;
};
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
each(_.functions(obj), function(name){
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return result.call(this, func.apply(_, args));
};
});
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = '' + ++idCounter;
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(text, data, settings) {
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = new RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset)
.replace(escaper, function(match) { return '\\' + escapes[match]; });
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
}
if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
}
if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
index = offset + match.length;
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + "return __p;\n";
try {
var render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
if (data) return render(data, _);
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled function source as a convenience for precompilation.
template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
return template;
};
// Add a "chain" function, which will delegate to the wrapper.
_.chain = function(obj) {
return _(obj).chain();
};
// OOP
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
// Helper function to continue chaining intermediate results.
var result = function(obj) {
return this._chain ? _(obj).chain() : obj;
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
var obj = this._wrapped;
method.apply(obj, arguments);
if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
return result.call(this, obj);
};
});
// Add all accessor Array functions to the wrapper.
each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
return result.call(this, method.apply(this._wrapped, arguments));
};
});
_.extend(_.prototype, {
// Start chaining a wrapped Underscore object.
chain: function() {
this._chain = true;
return this;
},
// Extracts the result from a wrapped and chained object.
value: function() {
return this._wrapped;
}
});
}).call(this); | ninjascience/grid-deck | js/lib/underscore.js | JavaScript | mit | 45,566 |
// Regular expression that matches all symbols in the Linear B Syllabary block as per Unicode v5.1.0:
/\uD800[\uDC00-\uDC7F]/; | mathiasbynens/unicode-data | 5.1.0/blocks/Linear-B-Syllabary-regex.js | JavaScript | mit | 126 |
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var Session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// create session middleware
var session = Session({
resave: true, // don't save session if unmodified
saveUninitialized: false, // don't create session until something stored
secret: 'love' // ???
});
var dashboard_routes = require('./routes/dashboard');
var test_routes = require('./routes/test');
var users_routes = require('./routes/users');
var regions_routes = require('./routes/regions');
var informations_routes = require('./routes/informations');
var commands_routes = require('./routes/commands');
var document_routes = require('./routes/documents');
var images_routes = require('./routes/images');
var authentications_routes = require('./routes/authentications');
var auth = require('./routes/auth');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.png')));
app.use(logger('dev'));
/* Automatically parse json object in request, and store the parsing
* result in `req.body`. If request is not json type (i.e., "Content-Type"
* is not "application/json", it won't be parsed.
*/
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use('/public', express.static(path.join(__dirname, 'public')));
// for logging
// Each time a request reaches, log the verb, url, body of request.
app.use(function(req, res, next) {
console.log('====================================================');
console.log('Request:');
console.log(req.method, req.originalUrl);
console.log(req.body);
console.log('----------------------------------------------------');
next();
});
/*
* Session control:
*
* Session only applies for /login, /login.do, /logout, and url starting with
* /dashboard.
*
* 1. Add `session` middleware for these routes, which can automatically set
* session information in `req.session`
* 2. When a user log in through /login.do, store login information in session,
* specifically, `req.session.user`
* 3. Every time a request ask for /dashboard/*, check whether `req.session.user`
* is set. If `req.session.user` is undefined, redirect to login page.
* 4. When logging out, delete `req.session.user`.
*
*/
app.get('/login', session, function(req, res, next) {
res.render('login');
});
app.post('/login.do', session, function (req, res, next) {
var username = req.body.username;
var password = req.body.password;
console.log('username =', username, 'password =', password);
if (username == "admin" && password == "admin") {
// store login information in session
req.session.user = {
username: 'admin',
password: 'admin'
};
res.redirect('/dashboard');
} else {
res.redirect('/login');
}
});
app.get('/logout', session, function(req, res, next) {
// delete login information in session
req.session.user = null;
res.redirect('/login');
});
// routes, see routes/*.js
app.use('/dashboard', session, function (req, res, next) {
/*
* If `req.session.user` exists, it means that user is already logged in.
* Otherwise, we should redirect to login page.
*/
console.log('req.session = ', req.session);
if (req.session.user || /^\/login/.test(req.url)) {
console.log('next');
next();
} else {
res.redirect('/login');
console.log('redirect');
}
}, dashboard_routes);
// routes for RESTful APIs
app.use('/test', auth.forAllUsers, test_routes);
app.use('/authentications', auth.forAllUsers, authentications_routes);
app.use('/users', auth.forAllUsers, users_routes);
app.use('/regions', auth.forAllUsers, regions_routes);
app.use('/information', auth.forAllUsers, informations_routes);
app.use('/commands', auth.forAllUsers, commands_routes);
app.use('/documents', auth.forAllUsers, document_routes);
app.use('/images', images_routes);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
res.status(404).send({
status: 404,
message: req.url + ' Not Found'
});
});
// error handlers
/* development error handler, will print stacktrace
*
* this error handler can be triggered by `next(error)`,
* where error is an `Error` object created by `new Error(message)`
*
* Example:
*
* function do_get(req, res, next) {
* if (something_wrong) {
* var error = new Error('some message');
* error.status = 503;
* } else {
* do_something();
* }
*
*/
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
console.log('caused development error handler');
if (err.status != 404) {
console.log(err.message);
console.log(err.stack);
}
var status = err.status || 500;
res.status(status);
res.send({
status: status,
message: err.message,
stack: err.stack,
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
console.log('caused production error handler');
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
| nettee/PortCityDefender | server/src/app.js | JavaScript | mit | 5,613 |
require.config( {
//By default load any module IDs from js/lib
baseUrl: "app/",
//except, if the module ID starts with "app",
//load it from the js/app directory. paths
//config is relative to the baseUrl, and
//never includes a ".js" extension since
//the paths config could be for a directory.
paths: {
lib: "../lib",
}
} );
requirejs( ["lib/angular/angular"], function() {
require( ["app"], function() {
angular.element( document ).ready( function() {
angular.bootstrap( document, ['dotaApp'] );
} );
} );
} ); | mangeg/dota2test | Dota2Test/src/Dota2.WebApp/wwwroot/init.js | JavaScript | mit | 597 |
import Ember from 'ember';
import ApplicationSerializer from 'ghost-admin/serializers/application';
import EmbeddedRecordsMixin from 'ember-data/serializers/embedded-records-mixin';
const {String: {pluralize}} = Ember;
export default ApplicationSerializer.extend(EmbeddedRecordsMixin, {
attrs: {
roles: {embedded: 'always'},
lastLoginUTC: {key: 'last_login'},
createdAtUTC: {key: 'created_at'},
updatedAtUTC: {key: 'updated_at'}
},
extractSingle(store, primaryType, payload) {
let root = this.keyForAttribute(primaryType.modelName);
let pluralizedRoot = pluralize(primaryType.modelName);
payload[root] = payload[pluralizedRoot][0];
delete payload[pluralizedRoot];
return this._super(...arguments);
},
normalizeSingleResponse(store, primaryModelClass, payload) {
let root = this.keyForAttribute(primaryModelClass.modelName);
let pluralizedRoot = pluralize(primaryModelClass.modelName);
if (payload[pluralizedRoot]) {
payload[root] = payload[pluralizedRoot][0];
delete payload[pluralizedRoot];
}
return this._super(...arguments);
}
});
| dbalders/Ghost-Admin | app/serializers/user.js | JavaScript | mit | 1,202 |
const type = {
name: "array",
structure: [
{ name: "type", match: "^array$" },
{ name: "content" },
],
child: "content",
identify,
validate,
next,
execute,
};
module.exports = type;
function identify({ current }) {
const regexp = new RegExp("^array$");
if (current.content &&
current.type &&
Object.keys(current).length === 2 &&
Array.isArray(current.content) === false &&
typeof current.content === "object" &&
regexp.test(current.type)) {
return true;
}
return false;
}
function validate({ current, ruleConfig, parents, processor }) {
const type = processor.identify({ current: current.content, ruleConfig, parents });
type.validate({ current: current.content, ruleConfig, parents: [...parents, type.child], processor });
return true;
}
function next(current) {
return current.content ? current.content : null;
}
function execute({ target, source, rule, processor }) {
return new Promise(async (resolve, reject) => {
try {
if (Array.isArray(source.current)) {
for (const key in source.current) {
const value = source.current[key];
target.current[key] = await processor.executeNext({ // eslint-disable-line no-await-in-loop
rule: { ...rule, current: rule.current.content },
source: { ...source, current: value },
target: { ...target, current: target.current[key] },
});
}
}
resolve(target.current);
} catch (error) {
reject(error);
}
});
}
| Noxs/SmashJsServerless | lib/core/filter/mergeRule/actions/array.js | JavaScript | mit | 1,439 |