code
stringlengths
2
1.05M
'use strict'; let gulp = require('gulp'); let babel = require('gulp-babel'); // 获取 uglify 模块(用于压缩 JS) let uglify = require('gulp-uglify'); /** * 编译js文件 */ gulp.task('es6-js', function () { //pages下面的业务代码进行babel处理 gulp.src(['./src/ec-do-2.0.0.js','./src/ec-do-3.0.0-beta.1.js','./test-es6.js','./src/ec-do-3.0.0-beta.2.js']) .pipe(babel({ presets: ['es2015'] })) .pipe(gulp.dest('./dist')); }); /** * 压缩js */ gulp.task('minify-js',()=>{ return gulp.src(['./dist/ec-do-3.0.0-beta.1.js','./dist/ec-do-3.0.0-beta.2.js','./dist/ec-do-2.0.0.js','./src/ec-do-1.1.4.js']) .pipe(uglify({ compress:false, mangle:{ reserved:['$super', '$', 'exports', 'require', 'define', 'module'] } })) .pipe(gulp.dest('./dist/min')); }); /** * 运行任务 */ gulp.task('default', ['es6-js'], function () { gulp.watch('*.js', ['es6-js']); });;
require('should'); var _ = require('underscore'); var uuid = require('node-uuid'); var async = require('async'); var lock = require('../../lib/lock'); var client = require('../../lib/redis-client').client; describe("The locking module", function() { var testKey = null; var testMultipleKeys = null; beforeEach(function() { testKey = uuid.v1(); testMultipleKeys = [uuid.v1(), uuid.v1()]; }); afterEach(function(done) { client.del(testKey, function(err, value) { if (err) { done(err); } testKey = null; done(err); }); }); describe("acquires a single lock", function() { it("on a non-existent key", function(done) { lock.acquireLock(testKey, 1, 60, function(err, lockId) { client.multi() .get(lockId) .ttl(lockId) .smembers(testKey) .exec(function(err, replies) { if (err) { done(err); } replies[0].should.equal(testKey); replies[1].should.be.approximately(60, 5); replies[2].should.eql([lockId]); done(err); }); }); }); it("on an existing key with sufficient availabiilty", function(done) { lock.acquireLock(testKey, 5, 60, function(err, firstLockId) { if (err) { done(err); } lock.acquireLock(testKey, 5, 60, function(err, secondLockId) { firstLockId.should.be.ok; secondLockId.should.be.ok; client.multi() .get(secondLockId) .ttl(secondLockId) .smembers(testKey) .exec(function(err, replies) { if (err) { done(err); } replies[0].should.equal(testKey); replies[1].should.be.approximately(60, 5); replies[2].should.have.length(2); replies[2].should.containEql(firstLockId); replies[2].should.containEql(secondLockId); done(err); }); }); }); }); it("on an existing key with insufficient availability and fails", function(done) { async.waterfall([ function(callback) { lock.acquireLock(testKey, 1, 60, callback); }, function(firstLockId, callback) { lock.acquireLock(testKey, 1, 60, function(err, secondLockId) { if (err) { callback(err); } firstLockId.should.be.ok; (secondLockId === null).should.be.true; client.multi() .get(secondLockId) .ttl(secondLockId) .smembers(testKey) .exec(function(err, replies) { if (err) { done(err); } (replies[0] === null).should.be.true; replies[1].should.be.lessThan(0); replies[2].should.be.eql([firstLockId]); callback(err); }); }); } ], function(err, result) { done(err); }); }); }); describe("counts currently held locks", function() { it("when there are no held locks", function(done) { lock.countLocks(testKey, function(err, count) { if (err) { return done(err); } count.should.equal(0); done(err); }); }); it("when there is one held lock", function(done) { lock.acquireLock(testKey, 5, 60, function(err, lockId) { if (err) { return done(err); } lock.countLocks(testKey, function(err, count) { if (err) { return done(err); } count.should.equal(1); done(err); }); }); }); it("when there are multiple held locks", function(done) { lock.acquireLock(testKey, 5, 60, function(err, lockId) { if (err) { return done(err); } lock.acquireLock(testKey, 5, 60, function(err, lockId) { if (err) { return done(err); } lock.countLocks(testKey, function(err, count) { if (err) { return done(err); } count.should.equal(2); done(err); }); }); }); }); }); describe("acquires multiple locks", function() { it("on two non-existent keys", function(done) { lock.acquireMultipleLocks(testMultipleKeys, 1, 60, function(err, lockIdMapping) { if (err) { return done(err); } afterDone = _.after(testMultipleKeys.length, done); _.each(lockIdMapping, function(lockId, lockKey) { client.multi() .get(lockId) .ttl(lockId) .smembers(lockKey) .exec(function(err, replies) { if (err) { afterDone(err); } replies[0].should.equal(lockKey); replies[1].should.be.approximately(60, 5); replies[2].should.eql([lockId]); return afterDone(err); }); }); }); }); it("on existing keys with sufficient availability", function(done) { lock.acquireMultipleLocks(testMultipleKeys, 1, 60, function(err, lockIdMapping) { if (err) { return done(err); } lockIdMapping.should.be.ok; _.keys(lockIdMapping).length.should.equal(2); lock.acquireMultipleLocks(testMultipleKeys, 2, 60, function(err, lockIdMapping) { if (err) { return done(err); } afterDone = _.after(testMultipleKeys.length, done); _.each(lockIdMapping, function(lockId, lockKey) { client.multi() .get(lockId) .ttl(lockId) .smembers(lockKey) .exec(function(err, replies) { if (err) { return done(err); } replies[0].should.equal(lockKey); replies[1].should.be.approximately(60, 5); replies[2].should.have.length(2); replies[2].should.containEql(lockId); return afterDone(null); }); }); }); }); }); it("on existing keys with insufficient availability and fails", function(done) { lock.acquireMultipleLocks(testMultipleKeys, 1, 60, function(err, lockIdMapping) { if (err) { return done(err); } lockIdMapping.should.be.ok; _.keys(lockIdMapping).length.should.equal(2); lock.acquireMultipleLocks(testMultipleKeys, 1, 60, function(err, secondLockIdMapping) { if (err) { return done(err); } (secondLockIdMapping === null).should.be.true; afterDone = _.after(testMultipleKeys.length, done); _.each(lockIdMapping, function(lockId, lockKey) { client.multi() .get(lockId) .ttl(lockId) .smembers(lockKey) .exec(function(err, replies) { if (err) { return done(err); } replies[0].should.equal(lockKey); replies[1].should.be.approximately(60, 5); replies[2].should.have.length(1); replies[2].should.containEql(lockId); return afterDone(null); }); }); }); }); }); }); describe("releases a lock", function() { it("on a non-existent or expired key", function(done) { lock.releaseLock(testKey, function(err) { if (err) { done(err); } client.get(testKey, function(err, value) { (value === null).should.be.true; done(err); }); }); }); it("on an existing and current key", function(done) { async.waterfall([ function(callback) { lock.acquireLock(testKey, 5, 60, callback); }, function(firstLockId, callback) { lock.acquireLock(testKey, 5, 60, function(err, secondLockId) { callback(err, firstLockId, secondLockId); }); }, function(firstLockId, secondLockId, callback) { lock.releaseLock(secondLockId, function(err) { if (err) { callback(err); } firstLockId.should.be.ok; secondLockId.should.be.ok; client.multi() .get(firstLockId) .get(secondLockId) .smembers(testKey) .exec(function(err, replies) { if (err) { done(err); } replies[0].should.be.eql(testKey); (replies[1] === null).should.be.true; replies[2].should.be.eql([firstLockId]); callback(err); }); }); }], function(err, result) { done(err); }); }); }); describe("reaps expired locks", function() { it("on an empty set", function(done) { lock.reapLock(testKey, function(err) { if (err) { done(err); } client.get(testKey, function(err, value) { if (err) { done(err); } (value === null).should.be.true; done(err); }); }); }); it("on a populated set", function(done) { async.waterfall([ function(callback) { lock.acquireLock(testKey, 5, 60, callback); }, function(firstLockId, callback) { lock.acquireLock(testKey, 5, 60, function(err, secondLockId) { callback(err, firstLockId, secondLockId); }); }, function(firstLockId, secondLockId, callback) { client.del(secondLockId, function(err, value) { callback(err, firstLockId, secondLockId); }); }, function(firstLockId, secondLockId, callback) { lock.reapLock(testKey, function(err) { if (err) { callback(err); } firstLockId.should.be.ok; secondLockId.should.be.ok; client.multi() .get(firstLockId) .get(secondLockId) .smembers(testKey) .exec(function(err, replies) { if (err) { callback(err); } replies[0].should.be.eql(testKey); (replies[1] === null).should.be.true; replies[2].should.be.eql([firstLockId]); callback(err); }); }); } ], function(err, result) { done(err); }); }); }); });
// extends from DashboardCtrl DashboardCtrl.prototype.filterPendingTransfersByFacility = function(facility) { var _this = this; var filters = { permanent_location_facility: facility }; _this.getPendingItemTransfers(filters); } DashboardCtrl.prototype.getPendingItemTransfers = function(filters) { this.dashbaordLoading = true; var _this = this; var path = '/items/pending_transfers'; var config = { params: {} } this.filters = filters || {}; if (filters) { for (var key in filters) { if (filters.hasOwnProperty(key)) { config.params['filters[' + key + ']'] = filters[key] } } } this.apiRequests.get(path, config).then(function(response) { _this.dashbaordLoading = false; if (response.status == 200) { _this.pendingItemTransfers = response.data; } else if (response.data['error'] && response.data['error']['detail']) { _this.flash = response.data['error']['detail']; } }); } DashboardCtrl.prototype.openPullList = function() { var url = this.rootPath() + '/items/transfer_list'; var q = []; if (this.filters) { for (var key in this.filters) { if (this.filters.hasOwnProperty(key)) { qComponent = 'filters[' + key + ']=' + encodeURIComponent(this.filters[key]); q.push(qComponent); } } } if (q.length > 0) { url = url + '?' + q.join('&'); } this.window.open(url,'_blank'); }
'use strict' angular.module('ProyectoISApp') .controller('PrincipalController', ['$scope', '$location', '$timeout', '$cookies','$http', 'ResourceCuentaLogueada', function($scope, $location, $timeout, $cookies, $http, ResourceCuentaLogueada){ $scope.cuentaLogueadaDesdeInicio = $cookies.get('CookieCuentaLogueada'); $scope.usuarioLogueado; $scope.ocultarBotonPerfilUsuario = true; $scope.ocultarBotonPerfilLugar = true; var tipoCuentaLogueada = $cookies.get('CookieTipoCuentaLogueada'); function cargarDatosUsuarioLogueado(){ ResourcePrincipalDatosUsuarioLogueado.get({id: $cookies.get('CookieCuentaLogueada')}, function(respuesta){ $scope.usuarioLogueado = respuesta.cuenta; //tipocuenta es con numero 1: Visitante, 2 if($scope.usuarioLogueado.tipoCuenta == 1){ $scope.ocultarBotonPerfilUsuario = true; $scope.ocultarBotonPerfilLugar = false; } if($scope.usuarioLogueado.tipoCuenta == 2){ $scope.ocultarBotonPerfilUsuario = false; $scope.ocultarBotonPerfilLugar = true; } }); } function changeCSSProperties(){ $("#body").removeClass("sidebar-mini"); $("#body").removeClass("skin-black"); $("#body").addClass("login-page"); $("#MasterContent").removeClass("wrapper"); } changeCSSProperties(); // cargarDatosUsuarioLogueado(); /* $scope.cargarLugaresTuristicos = function(){ ResourcePrincipalLugaresPreferidos.get(function(respuesta){ for(var i=0; i<respuesta.categorias.length; i++){ for(var j=0; j<respuesta.categorias[i].mejoresLugares.length; j++){ $scope.DB_listaLugaresTuristicos.push({codigoLugar: respuesta.categorias[i].mejoresLugares[j].codigoLugar, nombreCategoria: respuesta.categorias[i].nombreCategoria, nombre: respuesta.categorias[i].mejoresLugares[j].nombreLugar, nivelRecomendacion: respuesta.categorias[i].mejoresLugares[j].nivelRecomendacion, direccion: respuesta.categorias[i].mejoresLugares[j].nombreUbicacion, visitas: respuesta.categorias[i].mejoresLugares[j].cantidadVisitas, seguidores: respuesta.categorias[i].mejoresLugares[j].cantidadSeguidores, likes: respuesta.categorias[i].mejoresLugares[j].cantidadLikes, imagenLogo: respuesta.categorias[i].mejoresLugares[j].imagenLogo, imagenBanner: respuesta.categorias[i].mejoresLugares[j].imagenBanner} ); } } }); } */ /* Ejemplo de trato de data function cargarCategoriaLugares(){ ResourcePrincipalCategorias.get(function(respuesta){ for(var i=0; i<respuesta.categorias.length; i++){ $scope.categoriasLugares.push( {nombreCategoria: respuesta.categorias[i].nombreCategoria, codigoCategoria: respuesta.categorias[i].codigoCategoria , icono: 'glyphicon glyphicon-check'}); } }); } */ // cargarCategoriaLugares(); }]);
/** * DocuSign REST API * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * * NOTE: This class is auto generated. Do not edit the class manually and submit a new issue instead. * */ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['ApiClient', 'model/ConditionalRecipientRuleFilter'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. module.exports = factory(require('../ApiClient'), require('./ConditionalRecipientRuleFilter')); } else { // Browser globals (root is window) if (!root.Docusign) { root.Docusign = {}; } root.Docusign.ConditionalRecipientRuleCondition = factory(root.Docusign.ApiClient, root.Docusign.ConditionalRecipientRuleFilter); } }(this, function(ApiClient, ConditionalRecipientRuleFilter) { 'use strict'; /** * The ConditionalRecipientRuleCondition model module. * @module model/ConditionalRecipientRuleCondition */ /** * Constructs a new <code>ConditionalRecipientRuleCondition</code>. * @alias module:model/ConditionalRecipientRuleCondition * @class */ var exports = function() { var _this = this; }; /** * Constructs a <code>ConditionalRecipientRuleCondition</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/ConditionalRecipientRuleCondition} obj Optional instance to populate. * @return {module:model/ConditionalRecipientRuleCondition} The populated <code>ConditionalRecipientRuleCondition</code> instance. */ exports.constructFromObject = function(data, obj) { if (data) { obj = obj || new exports(); if (data.hasOwnProperty('filters')) { obj['filters'] = ApiClient.convertToType(data['filters'], [ConditionalRecipientRuleFilter]); } if (data.hasOwnProperty('order')) { obj['order'] = ApiClient.convertToType(data['order'], 'String'); } if (data.hasOwnProperty('recipientLabel')) { obj['recipientLabel'] = ApiClient.convertToType(data['recipientLabel'], 'String'); } } return obj; } /** * * @member {Array.<module:model/ConditionalRecipientRuleFilter>} filters */ exports.prototype['filters'] = undefined; /** * * @member {String} order */ exports.prototype['order'] = undefined; /** * * @member {String} recipientLabel */ exports.prototype['recipientLabel'] = undefined; return exports; }));
'use strict'; const assert = require('assert'); const http = require('http'); const request = require('supertest'); const bory = require('..'); describe('bory.json()', () => { it('should parse JSON', (done) => { request(createServer()) .post('/') .set('Content-Type', 'application/json') .send('{"user":"daniel"}') .expect(200, '{"user":"daniel"}', done); }); it('should fail gracefully', (done) => { request(createServer()) .post('/') .set('Content-Type', 'application/json') .send('{"user"') .expect(400, /unexpected end/i, done); }); it('should handle Content-Length: 0', (done) => { request(createServer()) .get('/') .set('Content-Type', 'application/json') .set('Content-Length', '0') .expect(200, '{}', done); }); it('should handle empty message-body', (done) => { request(createServer()) .get('/') .set('Content-Type', 'application/json') .set('Transfer-Encoding', 'chunked') .expect(200, '{}', done); }); it('should handle no message-body', (done) => { request(createServer()) .get('/') .set('Content-Type', 'application/json') .unset('Transfer-Encoding') .expect(200, '{}', done); }); it('should 400 on malformed JSON', (done) => { request(createServer()) .post('/') .set('Content-Type', 'application/json') .send('{:') .expect(400, /unexpected token/i, done); }); it('should 400 when invalid content-length', (done) => { const jsonParser = bory.json(); const server = createServer((req, res, next) => { req.headers['content-length'] = '20'; // bad length jsonParser(req, res, next); }); request(server) .post('/') .set('Content-Type', 'application/json') .send('{"str":') .expect(400, /content length/, done); }); it('should handle duplicated middleware', (done) => { const jsonParser = bory.json(); const server = createServer((req, res, next) => { jsonParser(req, res, (err) => { if (err) return next(err); jsonParser(req, res, next); }); }); request(server) .post('/') .set('Content-Type', 'application/json') .send('{"user":"daniel"}') .expect(200, '{"user":"daniel"}', done); }); describe('when strict is false', () => { it('should parse primitives', (done) => { request(createServer({ strict: false })) .post('/') .set('Content-Type', 'application/json') .send('true') .expect(200, 'true', done); }); }); describe('when strict is true', () => { let server; before(() => server = createServer({ strict: true })); it('should not parse primitives', (done) => { request(server) .post('/') .set('Content-Type', 'application/json') .send('true') .expect(400, /unexpected token/i, done); }); it('should allow leading whitespaces in JSON', (done) => { request(server) .post('/') .set('Content-Type', 'application/json') .send(' { "user": "daniel" }') .expect(200, '{"user":"daniel"}', done); }); }); describe('by default', () => { it('should 400 on primitives', (done) => { request(createServer()) .post('/') .set('Content-Type', 'application/json') .send('true') .expect(400, /unexpected token/i, done); }); }); describe('with limit option', () => { it('should 413 when over limit with Content-Length', (done) => { const buf = allocBuffer(1024, '.'); request(createServer({ limit: '1kb' })) .post('/') .set('Content-Type', 'application/json') .set('Content-Length', '1034') .send(JSON.stringify({ str: buf.toString() })) .expect(413, done); }); it('should 413 when over limit with chunked encoding', (done) => { const buf = allocBuffer(1024, '.'); const server = createServer({ limit: '1kb' }); const test = request(server).post('/'); test.set('Content-Type', 'application/json'); test.set('Transfer-Encoding', 'chunked'); test.write('{"str":'); test.write(`"${buf.toString()}"}`); test.expect(413, done); }); it('should accept number of bytes', (done) => { const buf = allocBuffer(1024, '.'); request(createServer({ limit: 1024 })) .post('/') .set('Content-Type', 'application/json') .send(JSON.stringify({ str: buf.toString() })) .expect(413, done); }); it('should not change when options altered', (done) => { const buf = allocBuffer(1024, '.'); const options = { limit: '1kb' }; const server = createServer(options); options.limit = '100kb'; request(server) .post('/') .set('Content-Type', 'application/json') .send(JSON.stringify({ str: buf.toString() })) .expect(413, done); }); it('should not hang response', (done) => { const buf = allocBuffer(10240, '.'); const server = createServer({ limit: '8kb' }); const test = request(server).post('/'); test.set('Content-Type', 'application/json'); test.write(buf); test.write(buf); test.write(buf); test.expect(413, done); }); }); describe('with inflate option', () => { describe('when false', () => { let server; before(() => server = createServer({ inflate: false })); it('should not accept content-encoding', (done) => { const test = request(server).post('/'); test.set('Content-Encoding', 'gzip'); test.set('Content-Type', 'application/json'); test.write(new Buffer('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')); test.expect(415, 'content encoding unsupported', done); }); }); describe('when true', () => { let server; before(() => server = createServer({ inflate: true })); it('should accept content-encoding', (done) => { const test = request(server).post('/'); test.set('Content-Encoding', 'gzip'); test.set('Content-Type', 'application/json'); test.write(new Buffer('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')); test.expect(200, '{"name":"论"}', done); }); }); }); describe('with type option', () => { describe('when "application/vnd.api+json"', () => { let server; before(() => server = createServer({ type: 'application/vnd.api+json' })); it('should parse JSON for custom type', (done) => { request(server) .post('/') .set('Content-Type', 'application/vnd.api+json') .send('{"user":"daniel"}') .expect(200, '{"user":"daniel"}', done); }); it('should ignore standard type', (done) => { request(server) .post('/') .set('Content-Type', 'application/json') .send('{"user":"daniel"}') .expect(200, '{}', done); }); }); describe('when a function', () => { it('should parse when truthy value returned', (done) => { const server = createServer({ type: accept }); function accept(req) { return req.headers['content-type'] === 'application/vnd.api+json'; } request(server) .post('/') .set('Content-Type', 'application/vnd.api+json') .send('{"user":"daniel"}') .expect(200, '{"user":"daniel"}', done); }); it('should work without content-type', (done) => { const server = createServer({ type: accept }); function accept() { return true; } const test = request(server).post('/'); test.write('{"user":"daniel"}'); test.expect(200, '{"user":"daniel"}', done); }); it('should not invoke without a body', (done) => { const server = createServer({ type: accept }); function accept() { throw new Error('oops!'); } request(server) .get('/') .expect(200, done); }); }); }); describe('with verify option', () => { it('should assert value if function', () => { assert.throws(createServer.bind(null, { verify: 'lol' }), /TypeError: option verify must be function/); }); it('should error from verify', (done) => { const server = createServer({ verify: (req, res, buf) => { if (buf[0] === 0x5b) throw new Error('no arrays'); }, }); request(server) .post('/') .set('Content-Type', 'application/json') .send('["daniel"]') .expect(403, 'no arrays', done); }); it('should allow custom codes', (done) => { const server = createServer({ verify: (req, res, buf) => { if (buf[0] !== 0x5b) return; const err = new Error('no arrays'); err.status = 400; throw err; }, }); request(server) .post('/') .set('Content-Type', 'application/json') .send('["daniel"]') .expect(400, 'no arrays', done); }); it('should allow pass-through', (done) => { const server = createServer({ verify: (req, res, buf) => { if (buf[0] === 0x5b) throw new Error('no arrays'); }, }); request(server) .post('/') .set('Content-Type', 'application/json') .send('{"user":"daniel"}') .expect(200, '{"user":"daniel"}', done); }); it('should work with different charsets', (done) => { const server = createServer({ verify: (req, res, buf) => { if (buf[0] === 0x5b) throw new Error('no arrays'); }, }); const test = request(server).post('/'); test.set('Content-Type', 'application/json; charset=utf-16'); test.write(new Buffer('feff007b0022006e0061006d00650022003a00228bba0022007d', 'hex')); test.expect(200, '{"name":"论"}', done); }); it('should 415 on unknown charset prior to verify', (done) => { const server = createServer({ verify: () => { throw new Error('unexpected verify call'); }, }); const test = request(server).post('/'); test.set('Content-Type', 'application/json; charset=x-bogus'); test.write(new Buffer('00000000', 'hex')); test.expect(415, 'unsupported charset "X-BOGUS"', done); }); }); describe('charset', () => { let server; before(() => server = createServer()); it('should parse utf-8', (done) => { const test = request(server).post('/'); test.set('Content-Type', 'application/json; charset=utf-8'); test.write(new Buffer('7b226e616d65223a22e8aeba227d', 'hex')); test.expect(200, '{"name":"论"}', done); }); it('should parse utf-16', (done) => { const test = request(server).post('/'); test.set('Content-Type', 'application/json; charset=utf-16'); test.write(new Buffer('feff007b0022006e0061006d00650022003a00228bba0022007d', 'hex')); test.expect(200, '{"name":"论"}', done); }); it('should parse when content-length != char length', (done) => { const test = request(server).post('/'); test.set('Content-Type', 'application/json; charset=utf-8'); test.set('Content-Length', '13'); test.write(new Buffer('7b2274657374223a22c3a5227d', 'hex')); test.expect(200, '{"test":"å"}', done); }); it('should default to utf-8', (done) => { const test = request(server).post('/'); test.set('Content-Type', 'application/json'); test.write(new Buffer('7b226e616d65223a22e8aeba227d', 'hex')); test.expect(200, '{"name":"论"}', done); }); it('should fail on unknown charset', (done) => { const test = request(server).post('/'); test.set('Content-Type', 'application/json; charset=koi8-r'); test.write(new Buffer('7b226e616d65223a22cec5d4227d', 'hex')); test.expect(415, 'unsupported charset "KOI8-R"', done); }); }); describe('encoding', () => { let server; before(() => server = createServer({ limit: '1kb' })); it('should parse without encoding', (done) => { const test = request(server).post('/'); test.set('Content-Type', 'application/json'); test.write(new Buffer('7b226e616d65223a22e8aeba227d', 'hex')); test.expect(200, '{"name":"论"}', done); }); it('should support identity encoding', (done) => { const test = request(server).post('/'); test.set('Content-Encoding', 'identity'); test.set('Content-Type', 'application/json'); test.write(new Buffer('7b226e616d65223a22e8aeba227d', 'hex')); test.expect(200, '{"name":"论"}', done); }); it('should support gzip encoding', (done) => { const test = request(server).post('/'); test.set('Content-Encoding', 'gzip'); test.set('Content-Type', 'application/json'); test.write(new Buffer('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')); test.expect(200, '{"name":"论"}', done); }); it('should support deflate encoding', (done) => { const test = request(server).post('/'); test.set('Content-Encoding', 'deflate'); test.set('Content-Type', 'application/json'); test.write(new Buffer('789cab56ca4bcc4d55b2527ab16e97522d00274505ac', 'hex')); test.expect(200, '{"name":"论"}', done); }); it('should be case-insensitive', (done) => { const test = request(server).post('/'); test.set('Content-Encoding', 'GZIP'); test.set('Content-Type', 'application/json'); test.write(new Buffer('1f8b080000000000000bab56ca4bcc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')); test.expect(200, '{"name":"论"}', done); }); it('should 415 on unknown encoding', (done) => { const test = request(server).post('/'); test.set('Content-Encoding', 'nulls'); test.set('Content-Type', 'application/json'); test.write(new Buffer('000000000000', 'hex')); test.expect(415, 'unsupported content encoding "nulls"', done); }); it('should 400 on malformed encoding', (done) => { const test = request(server).post('/'); test.set('Content-Encoding', 'gzip'); test.set('Content-Type', 'application/json'); test.write(new Buffer('1f8b080000000000000bab56cc4d55b2527ab16e97522d00515be1cc0e000000', 'hex')); test.expect(400, done); }); it('should 413 when inflated value exceeds limit', (done) => { // gzip'd data exceeds 1kb, but deflated below 1kb const test = request(server).post('/'); test.set('Content-Encoding', 'gzip'); test.set('Content-Type', 'application/json'); test.write(new Buffer('1f8b080000000000000bedc1010d000000c2a0f74f6d0f071400000000000000', 'hex')); test.write(new Buffer('0000000000000000000000000000000000000000000000000000000000000000', 'hex')); test.write(new Buffer('0000000000000000004f0625b3b71650c30000', 'hex')); test.expect(413, done); }); }); }); function allocBuffer(size, fill) { if (Buffer.alloc) { return Buffer.alloc(size, fill); } const buf = new Buffer(size); buf.fill(fill); return buf; } function createServer(opts) { const _bory = typeof opts !== 'function' ? bory.json(opts) : opts; return http.createServer((req, res) => { _bory(req, res, (err) => { res.statusCode = err ? (err.status || 500) : 200; res.end(err ? err.message : JSON.stringify(req.body)); }); }); }
"use strict"; /** * @module opcua.address_space */ require("requirish")._(module); var NodeClass = require("lib/datamodel/nodeclass").NodeClass; var NodeId = require("lib/datamodel/nodeid").NodeId; var resolveNodeId = require("lib/datamodel/nodeid").resolveNodeId; var DataValue = require("lib/datamodel/datavalue").DataValue; var extractRange = require("lib/datamodel/datavalue").extractRange; var Variant = require("lib/datamodel/variant").Variant; var DataType = require("lib/datamodel/variant").DataType; var VariantArrayType = require("lib/datamodel/variant").VariantArrayType; var NumericRange = require("lib/datamodel/numeric_range").NumericRange; var StatusCodes = require("lib/datamodel/opcua_status_code").StatusCodes; var read_service = require("lib/services/read_service"); var AttributeIds = read_service.AttributeIds; var assert = require("better-assert"); var util = require("util"); var _ = require("underscore"); var BaseNode = require("lib/address_space/base_node").BaseNode; var makeAccessLevel = require("lib/datamodel/access_level").makeAccessLevel; var write_service = require("lib/services/write_service"); var WriteValue = write_service.WriteValue; var doDebug = false; var debugLog = function(){} function isGoodish(statusCode) { return statusCode.value < 0x10000000; } function adjust_accessLevel(accessLevel) { accessLevel = accessLevel || "CurrentRead | CurrentWrite"; accessLevel = makeAccessLevel(accessLevel); assert(_.isFinite(accessLevel.value)); return accessLevel; } function adjust_userAccessLevel(accessLevel) { accessLevel = accessLevel || "CurrentRead | CurrentWrite"; accessLevel = makeAccessLevel(accessLevel); return accessLevel; } function adjust_samplingInterval(minimumSamplingInterval) { assert(_.isFinite(minimumSamplingInterval)); return minimumSamplingInterval; } function is_Variant(v) { return v instanceof Variant; } function is_StatusCode(v) { return v && v.constructor && v.constructor.name === "StatusCode"; } function is_Variant_or_StatusCode(v) { if (is_Variant(v)) { // /@@assert(v.isValid()); } return is_Variant(v) || is_StatusCode(v); } var is_valid_dataEncoding = require("lib/misc/data_encoding").is_valid_dataEncoding; var is_dataEncoding = require("lib/misc/data_encoding").is_dataEncoding; var UADataType = require("./ua_data_type").UADataType; function _dataType_toUADataType(__address_space, dataType) { assert(__address_space); assert(dataType); var dataTypeNode = __address_space.findDataType(dataType.key); /* istanbul ignore next */ if (!dataTypeNode) { throw new Error(" Cannot find DataType " + dataType.key + " in address Space"); } return dataTypeNode; } var findBuiltInType = require("lib/misc/factories_builtin_types").findBuiltInType; /*== * * * @param __address_space * @param dataTypeNodeId : the nodeId matching the dataType of the destination variable. * @param variantDataType: the dataType of the variant to write to the destination variable * @param nodeId * @return {boolean} true if the variant datatype is compatible with the Variable DataType */ function validateDataType(__address_space, dataTypeNodeId, variantDataType, nodeId) { if (variantDataType === DataType.ExtensionObject) { return true; } var builtInType, builtInUADataType; var destUADataType = __address_space.findObject(dataTypeNodeId); assert(destUADataType instanceof UADataType); if (destUADataType.isAbstract) { builtInUADataType = destUADataType; } else { builtInType = findBuiltInType(destUADataType.browseName).name; builtInUADataType = __address_space.findDataType(builtInType); } assert(builtInUADataType instanceof UADataType); // The value supplied for the attribute is not of the same type as the value. var variantUADataType = _dataType_toUADataType(__address_space, variantDataType); assert(variantUADataType instanceof UADataType); var dest_isSuperTypeOf_variant = variantUADataType.isSupertypeOf(builtInUADataType); function debugValidateDataType() { if (dest_isSuperTypeOf_variant) { /* istanbul ignore next*/ console.log(" ---------- Type match !!! ".green, " on ", nodeId.toString()); } else { /* istanbul ignore next*/ console.log(" ---------- Type mismatch ".red, " on ", nodeId.toString()); } console.log(" Variable data Type is = ".cyan, destUADataType.browseName.toString()); console.log(" which matches basic Type = ".cyan, builtInUADataType.browseName.toString()); console.log(" Actual dataType = ".yellow, variantUADataType.browseName.toString()); } /* istanbul ignore next */ if (doDebug) { debugValidateDataType(); } return (dest_isSuperTypeOf_variant); } function isSameVariant(va,vb) { assert( va instanceof Variant); assert( vb instanceof Variant); if (va.dataType !== vb.dataType) { return false; } if (va.arrayType !== vb.arrayType) { return false; } return (_.isEqual(va.value,vb.value)); } /** * A OPCUA Variable Node * * @class UAVariable * @constructor * @extends BaseNode * @param options {Object} * @param options.value * @param options.browseName {string} * @param options.dataType {NodeId|String} * @param options.valueRank {Int32} * @param options.arrayDimensions {null|Array<Integer>} * @param options.accessLevel {AccessLevel} * @param options.userAccessLevel {AccessLevel} * @param [options.minimumSamplingInterval = -1] * @param [options.historizing = false] {Boolean} * @param options.parentNodeId {NodeId} * * The AccessLevel Attribute is used to indicate how the Value of a Variable can be accessed (read/write) and if it * contains current and/or historic data. The AccessLevel does not take any user access rights into account, * i.e. although the Variable is writable this may be restricted to a certain user / user group. * The AccessLevel is an 8-bit unsigned integer with the structure defined in the following table: * * Field Bit Description * CurrentRead 0 Indicates if the current value is readable * (0 means not readable, 1 means readable). * CurrentWrite 1 Indicates if the current value is writable * (0 means not writable, 1 means writable). * HistoryRead 2 Indicates if the history of the value is readable * (0 means not readable, 1 means readable). * HistoryWrite 3 Indicates if the history of the value is writable (0 means not writable, 1 means writable). * SemanticChange 4 Indicates if the Variable used as Property generates SemanticChangeEvents (see 9.31). * Reserved 5:7 Reserved for future use. Shall always be zero. * * The first two bits also indicate if a current value of this Variable is available and the second two bits * indicates if the history of the Variable is available via the OPC UA server. * */ function UAVariable(options) { var self = this; BaseNode.apply(this, arguments); // assert(self.typeDefinition.value === self.resolveNodeId("VariableTypeNode").value); /** * @property dataType * @type {NodeId} */ self.dataType = self.resolveNodeId(options.dataType); // DataType (NodeId) assert(self.dataType instanceof NodeId); /** * @property valueRank * @type {number} UInt32 * This Attribute indicates whether the Value Attribute of the Variable is an array and how many dimensions * the array has. * It may have the following values: * n > 1: the Value is an array with the specified number of dimensions. * OneDimension (1): The value is an array with one dimension. * OneOrMoreDimensions (0): The value is an array with one or more dimensions. * Scalar (?1): The value is not an array. * Any (?2): The value can be a scalar or an array with any number of dimensions. * ScalarOrOneDimension (?3): The value can be a scalar or a one dimensional array. * NOTE All DataTypes are considered to be scalar, even if they have array-like semantics * like ByteString and String. */ self.valueRank = options.valueRank || 0; // UInt32 assert(typeof self.valueRank === "number"); /** * This Attribute specifies the length of each dimension for an array value. T * @property arrayDimensions * @type {number[]} UInt32 * The Attribute is intended to describe the capability of the Variable, not the current size. * The number of elements shall be equal to the value of the ValueRank Attribute. Shall be null * if ValueRank ? 0. * A value of 0 for an individual dimension indicates that the dimension has a variable length. * For example, if a Variable is defined by the following C array: * Int32 myArray[346]; * then this Variable’s DataType would point to an Int32, the Variable’s ValueRank has the * value 1 and the ArrayDimensions is an array with one entry having the value 346. * Note that the maximum length of an array transferred on the wire is 2147483647 (max Int32) * and a multidimentional array is encoded as a one dimensional array. */ self.arrayDimensions = options.arrayDimensions || null; assert(_.isNull(self.arrayDimensions) || _.isArray(self.arrayDimensions)); /** * @property accessLevel * @type {number} */ self.accessLevel = adjust_accessLevel(options.accessLevel); /** * @property userAccessLevel * @type {number} * */ self.userAccessLevel = adjust_userAccessLevel(options.userAccessLevel); /** * The MinimumSamplingInterval Attribute indicates how “current” the Value of the Variable will * be kept. * @property minimumSamplingInterval * @type {number} [Optional] * It specifies (in milliseconds) how fast the Server can reasonably sample the value * for changes (see Part 4 for a detailed description of sampling interval). * A MinimumSamplingInterval of 0 indicates that the Server is to monitor the item continuously. * A MinimumSamplingInterval of -1 means indeterminate. */ self.minimumSamplingInterval = adjust_samplingInterval(options.minimumSamplingInterval); self.parentNodeId = options.parentNodeId; /** * The Historizing Attribute indicates whether the Server is actively collecting data for the * history of the Variable. * @property historizing * @type {Boolean} * This differs from the AccessLevel Attribute which identifies if the * Variable has any historical data. A value of TRUE indicates that the Server is actively c * ollecting data. A value of FALSE indicates the Server is not actively collecting data. * Default value is FALSE. */ self.historizing = options.historizing; self._dataValue = new DataValue({statusCode: StatusCodes.BadNodeIdUnknown, value: {}}); if (options.value) { self.bindVariable(options.value); } } util.inherits(UAVariable, BaseNode); UAVariable.prototype.nodeClass = NodeClass.Variable; UAVariable.prototype.isWritable = function () { return this.accessLevel.has("CurrentWrite") && this.userAccessLevel.has("CurrentWrite"); }; /** * * @method readValue * @param [indexRange] {NumericRange|null} * @param [dataEncoding] {String} * @return {DataValue} * * * from OPC.UA.Spec 1.02 part 4 * 5.10.2.4 StatusCodes * Table 51 defines values for the operation level statusCode contained in the DataValue structure of * each values element. Common StatusCodes are defined in Table 166. * * Table 51 Read Operation Level Result Codes * * Symbolic Id Description * * BadNodeIdInvalid The syntax of the node id is not valid. * BadNodeIdUnknown The node id refers to a node that does not exist in the server address space. * BadAttributeIdInvalid Bad_AttributeIdInvalid The attribute is not supported for the specified node. * BadIndexRangeInvalid The syntax of the index range parameter is invalid. * BadIndexRangeNoData No data exists within the range of indexes specified. * BadDataEncodingInvalid The data encoding is invalid. * This result is used if no dataEncoding can be applied because an Attribute other than * Value was requested or the DataType of the Value Attribute is not a subtype of the * Structure DataType. * BadDataEncodingUnsupported The server does not support the requested data encoding for the node. * This result is used if a dataEncoding can be applied but the passed data encoding is not * known to the Server. * BadNotReadable The access level does not allow reading or subscribing to the Node. * BadUserAccessDenied User does not have permission to perform the requested operation. (table 165) */ UAVariable.prototype.readValue = function (indexRange, dataEncoding) { var self = this; if (!is_valid_dataEncoding(dataEncoding)) { return new DataValue({statusCode: StatusCodes.BadDataEncodingInvalid}); } var dataValue = self._dataValue; if (isGoodish(dataValue.statusCode)) { dataValue = extractRange(dataValue, indexRange); } /* istanbul ignore next */ if (dataValue.statusCode === StatusCodes.BadNodeIdUnknown) { console.log(" Warning: ", self.browseName, self.nodeId.toString(), "exists but dataValue has not been defined"); } return dataValue; }; UAVariable.prototype._readDataType = function () { assert(this.dataType instanceof NodeId); var options = { value: {dataType: DataType.NodeId, value: this.dataType}, statusCode: StatusCodes.Good }; return new DataValue(options); }; UAVariable.prototype._readValueRank = function () { assert(typeof this.valueRank === "number"); var options = { value: {dataType: DataType.Int32, value: this.valueRank}, statusCode: StatusCodes.Good }; return new DataValue(options); }; UAVariable.prototype._readArrayDimensions = function () { assert(_.isArray(this.arrayDimensions) || this.arrayDimensions === null); var options = { value: {dataType: DataType.UInt32, arrayType: VariantArrayType.Array, value: this.arrayDimensions}, statusCode: StatusCodes.Good }; return new DataValue(options); }; UAVariable.prototype._readAccessLevel = function () { var options = { value: {dataType: DataType.Byte, value: this.accessLevel.value}, statusCode: StatusCodes.Good }; return new DataValue(options); }; UAVariable.prototype._readUserAccessLevel = function () { var options = { value: {dataType: DataType.Byte, value: this.userAccessLevel.value}, statusCode: StatusCodes.Good }; return new DataValue(options); }; UAVariable.prototype._readMinimumSamplingInterval = function () { var options = {}; if (this.minimumSamplingInterval === undefined) { options.statusCode = StatusCodes.BadAttributeIdInvalid; } else { options.value = {dataType: DataType.Int32, value: this.minimumSamplingInterval}; options.statusCode = StatusCodes.Good; } return new DataValue(options); }; UAVariable.prototype._readHistorizing = function () { var options = { value: {dataType: DataType.Boolean, value: this.historizing}, statusCode: StatusCodes.Good }; return new DataValue(options); }; /** * @method readAttribute * @param attributeId {AttributeIds} the attributeId to read * @param indexRange {NumericRange || null} * @param dataEncoding {String} * @return {DataValue} */ UAVariable.prototype.readAttribute = function (attributeId, indexRange, dataEncoding) { var options = {}; if (attributeId !== AttributeIds.Value) { if (indexRange && indexRange.isDefined()) { options.statusCode = StatusCodes.BadIndexRangeNoData; return new DataValue(options); } if (is_dataEncoding(dataEncoding)) { options.statusCode = StatusCodes.BadDataEncodingInvalid; return new DataValue(options); } } switch (attributeId) { case AttributeIds.Value: return this.readValue(indexRange, dataEncoding); case AttributeIds.DataType: return this._readDataType(); case AttributeIds.ValueRank: return this._readValueRank(); case AttributeIds.ArrayDimensions: return this._readArrayDimensions(); case AttributeIds.AccessLevel: return this._readAccessLevel(); case AttributeIds.UserAccessLevel: return this._readUserAccessLevel(); case AttributeIds.MinimumSamplingInterval: return this._readMinimumSamplingInterval(); case AttributeIds.Historizing: return this._readHistorizing(); default: return BaseNode.prototype.readAttribute.call(this, attributeId); } }; UAVariable.prototype._validate_DataType = function (variantDataType) { return validateDataType(this.__address_space, this.dataType, variantDataType, this.nodeId); }; function check_valid_array(dataType, array) { if (_.isArray(array)) { return true; } switch (dataType) { case DataType.Double: return array instanceof Float64Array; case DataType.Float: return array instanceof Float32Array; case DataType.Int32: return array instanceof Int32Array; case DataType.Int16: return array instanceof Int16Array; case DataType.SByte: return array instanceof Int8Array; case DataType.UInt32: return array instanceof Uint32Array; case DataType.UInt16: return array instanceof Uint16Array; case DataType.Byte: return array instanceof Uint8Array || array instanceof Buffer; } return false; } /** * setValueFromSource is used to let the device sets the variable values * this method also records the current time as sourceTimestamp and serverTimestamp. * the method broadcasts an "value_changed" event * @method setValueFromSource * @param variant * @param statusCode */ UAVariable.prototype.setValueFromSource = function (variant, statusCode) { // istanbul ignore next if (variant.hasOwnProperty("value")) { if (!variant.dataType) { throw new Error("Variant must provide a valid dataType"); } } variant = (variant instanceof Variant) ? variant : new Variant(variant); assert(variant instanceof Variant); var self = this; var now = new Date(); var dataValue = new DataValue({ sourceTimestamp: now, sourcePicoseconds: 0, serverTimestamp: now, serverPicoseconds: 0, statusCode: statusCode || StatusCodes.Good }); dataValue.value = variant; self._internal_set_dataValue(dataValue, null); }; var Range = require("lib/data_access/Range").Range; function validate_value_range(range, variant) { assert(range instanceof Range); assert(variant instanceof Variant); if (variant.value < range.low || variant.value > range.high) { return false; } return true; } UAVariable.prototype.isValueInRange = function (value) { assert(value instanceof Variant); var self = this; // test dataType if (!self._validate_DataType(value.dataType)) { return StatusCodes.BadTypeMismatch; } if (self.instrumentRange) { if (!validate_value_range(self.instrumentRange.readValue().value.value, value)) { return StatusCodes.BadOutOfRange; } } return StatusCodes.Good; }; /** * @method writeValue * @param dataValue {DataValue} * @param [indexRange] {NumericRange} * @param callback {Function} * @param callback.err {Error|null} * @param callback.statusCode {StatusCode} * @async * */ UAVariable.prototype.writeValue = function (dataValue, indexRange, callback) { var self = this; // adjust arguments if optional indexRange Parameter is not given if (!_.isFunction(callback) && _.isFunction(indexRange)) { callback = indexRange; indexRange = new NumericRange(); } assert(_.isFunction(callback)); assert(dataValue instanceof DataValue); indexRange = NumericRange.coerce(indexRange); // test write permission if (!self.isWritable()) { return callback(null, StatusCodes.BadNotWritable); } // adjust special case // convert Variant( Scalar|ByteString) => Variant(Array|ByteArray) var variant = dataValue.value; if (variant.arrayType === VariantArrayType.Scalar && variant.dataType === DataType.ByteString) { if ((self.dataType.value === 3) && (self.dataType.namespace === 0)) { // Byte variant.arrayType = VariantArrayType.Array; variant.dataType = DataType.Byte; } } var statusCode = self.isValueInRange(dataValue.value); if (statusCode !== StatusCodes.Good) { return callback(null,statusCode); } if(!self._timestamped_set_func) { return callback(null,StatusCodes.BadNotWritable); } assert(self._timestamped_set_func); self._timestamped_set_func(dataValue, indexRange, function (err, statusCode, correctedDataValue) { if (!err) { correctedDataValue = correctedDataValue || dataValue; assert(correctedDataValue instanceof DataValue); if (indexRange && !indexRange.isEmpty()) { if (!indexRange.isValid()) { return callback(null, StatusCodes.BadIndexRangeInvalid); } var newArr = dataValue.value.value; // check that source data is an array if (dataValue.value.arrayType !== VariantArrayType.Array) { return callback(null, StatusCodes.BadTypeMismatch); } // check that destination data is also an array assert(check_valid_array(self._dataValue.value.dataType, self._dataValue.value.value)); var destArr = self._dataValue.value.value; var result = indexRange.set_values(destArr, newArr); if (result.statusCode !== StatusCodes.Good) { return callback(null, result.statusCode); } dataValue.value.value = result.array; } self._internal_set_dataValue(correctedDataValue, indexRange); //xx self._dataValue = correctedDataValue; } callback(err, statusCode); }); }; /** * @method writeAttribute * @param writeValue {WriteValue} * @param writeValue.nodeId {NodeId} * @param writeValue.attributeId {AttributeId}* * @param writeValue.value {DataValue} * @param writeValue.indexRange {NumericRange} * @param callback {Function} * @param callback.err {Error|null} * @param callback.statusCode {StatusCode} * @async */ UAVariable.prototype.writeAttribute = function (writeValue, callback) { assert(writeValue instanceof WriteValue); assert(writeValue.value instanceof DataValue); assert(writeValue.value.value instanceof Variant); assert(_.isFunction(callback)); // Spec 1.0.2 Part 4 page 58 // If the SourceTimestamp or the ServerTimestamp is specified, the Server shall // use these values. if (!writeValue.value.sourceTimestamp) { writeValue.value.sourceTimestamp = new Date(); writeValue.value.sourcePicoseconds = 0; } if (!writeValue.value.serverTimestamp) { writeValue.value.serverTimestamp = new Date(); writeValue.value.serverPicosecons = 0; } switch (writeValue.attributeId) { case AttributeIds.Value: this.writeValue(writeValue.value, writeValue.indexRange, callback); break; default: BaseNode.prototype.writeAttribute.call(this, writeValue, callback); } }; function _not_writable_timestamped_set_func(dataValue, callback) { assert(dataValue instanceof DataValue); callback(null, StatusCodes.BadNotWritable, null); } function _default_writable_timestamped_set_func(dataValue, callback) { /* jshint validthis: true */ assert(dataValue instanceof DataValue); callback(null, StatusCodes.Good, dataValue); } function turn_sync_to_async(f, numberOfArgs) { if (f.length <= numberOfArgs) { return function (data, callback) { var r = f(data); setImmediate(function () { return callback(null, r); }); }; } else { assert(f.length === numberOfArgs + 1); return f; } } var MonitoredItem = require("lib/server/monitored_item").MonitoredItem; // variation #3 : function _Variable_bind_with_async_refresh(options) { /* jshint validthis: true */ var self = this; assert(self instanceof UAVariable); assert(_.isFunction(options.refreshFunc)); assert(!options.get, "a getter shall not be specified when refreshFunc is set"); assert(!options.timestamped_get, "a getter shall not be specified when refreshFunc is set"); assert(!self.asyncRefresh); assert(!self.refreshFunc); self.refreshFunc = options.refreshFunc; self.asyncRefresh = function (callback) { self.refreshFunc.call(self, function (err, dataValue) { if (err || !dataValue) { dataValue = {statusCode: StatusCodes.BadNoDataAvailable}; } self._internal_set_dataValue(dataValue, null); callback(err, self._dataValue); }); }; //assert(self._dataValue.statusCode === StatusCodes.BadNodeIdUnknown); self._dataValue.statusCode = StatusCodes.UncertainInitialValue; if (self.minimumSamplingInterval === 0 ) { // when a getter /timestamped_getter or async_getter is provided // samplingInterval cannot be 0, as the item value must be scanned to be updated. self.minimumSamplingInterval = MonitoredItem.minimumSamplingInterval; debugLog("adapting minimumSamplingInterval on " + self.browseName.toString() + " to " + self.minimumSamplingInterval); } } // variation 2 function _Variable_bind_with_timestamped_get(options) { /* jshint validthis: true */ var self = this; assert(self instanceof UAVariable); assert(_.isFunction(options.timestamped_get)); assert(!options.get, "should not specify 'get' when 'timestamped_get' exists "); assert(!self._timestamped_get_func); self._timestamped_get_func = options.timestamped_get; var dataValue_verify = self._timestamped_get_func(); /* istanbul ignore next */ if (!(dataValue_verify instanceof DataValue)) { console.log(" Bind variable error: ".red, " : the timestamped_get function must return a DataValue"); console.log("value_check.constructor.name ", dataValue_verify ? dataValue_verify.constructor.name : "null"); throw new Error(" Bind variable error: ".red, " : the timestamped_get function must return a DataValue"); } function async_refresh_func(callback) { var dataValue = self._timestamped_get_func(); callback(null, dataValue); } _Variable_bind_with_async_refresh.call(self, {refreshFunc: async_refresh_func}); } // variation 1 function _Variable_bind_with_simple_get(options) { /* jshint validthis: true */ var self = this; assert(self instanceof UAVariable); assert(_.isFunction(options.get), "should specify get function"); assert(options.get.length === 0, "get function should not have arguments"); assert(!options.timestamped_get, "should not specify a timestamped_get function when get is specified"); assert(!self._timestamped_get_func); assert(!self._get_func); self._get_func = options.get; function timestamped_get_func_from__Variable_bind_with_simple_get() { var value = self._get_func(); /* istanbul ignore next */ if (!is_Variant_or_StatusCode(value)) { console.log(" Bind variable error: ".red, " : the getter must return a Variant or a StatusCode"); console.log("value_check.constructor.name ", value ? value.constructor.name : "null"); throw new Error(" bindVariable : the value getter function returns a invalid result ( expecting a Variant or a StatusCode !!!"); } if (is_StatusCode(value)) { return new DataValue({statusCode: value}); } else { if (!self._dataValue || !isSameVariant(self._dataValue.value,value) || self._dataValue.statusCode !== StatusCodes.Good) { self.setValueFromSource(value,StatusCodes.Good); } else { //XXXY console.log("YYYYYYYYYYYYYYYYYYYYYYYYYY".red,self.browseName.toString()); } return self._dataValue; } } _Variable_bind_with_timestamped_get.call(self, {timestamped_get: timestamped_get_func_from__Variable_bind_with_simple_get}); } function _Variable_bind_with_simple_set(options) { /* jshint validthis: true */ var self = this; assert(self instanceof UAVariable); assert(_.isFunction(options.set), "should specify set function"); assert(!options.timestamped_set, "should not specify a timestamped_set function"); assert(!self._timestamped_set_func); assert(!self._set_func); self._set_func = turn_sync_to_async(options.set, 1); assert(self._set_func.length === 2, " set function must have 2 arguments ( variant, callback)"); self._timestamped_set_func = function (timestamped_value, indexRange, callback) { assert(timestamped_value instanceof DataValue); self._set_func(timestamped_value.value, function (err, statusCode) { callback(err, statusCode, timestamped_value); }); }; } function _Variable_bind_with_timestamped_set(options) { /* jshint validthis: true */ var self = this; assert(self instanceof UAVariable); assert(_.isFunction(options.timestamped_set)); assert(!options.set, "should not specify set when timestamped_set_func exists "); self._timestamped_set_func = function (dataValue, indexRange, callback) { //xx assert(!indexRange,"indexRange Not Implemented"); return options.timestamped_set(dataValue, callback); }; } var sourceTimestampHasChanged = require("lib/datamodel/datavalue").sourceTimestampHasChanged; function bind_setter(self,options) { if (_.isFunction(options.set)) { // variation 1 _Variable_bind_with_simple_set.call(self, options); } else if (_.isFunction(options.timestamped_set)) { // variation 2 assert(_.isFunction(options.timestamped_get, "timestamped_set must be used with timestamped_get ")); _Variable_bind_with_timestamped_set.call(self, options); } else if (_.isFunction(options.timestamped_get)) { // timestamped_get is specified but timestamped_set is not // => Value is read-only _Variable_bind_with_timestamped_set.call(self, {timestamped_set: _not_writable_timestamped_set_func}); } else { _Variable_bind_with_timestamped_set.call(self, {timestamped_set: _default_writable_timestamped_set_func}); } } function bind_getter(self,options) { if (_.isFunction(options.get)) { // variation 1 _Variable_bind_with_simple_get.call(self, options); } else if (_.isFunction(options.timestamped_get)) { // variation 2 _Variable_bind_with_timestamped_get.call(self, options); } else if (_.isFunction(options.refreshFunc)) { // variation 3 _Variable_bind_with_async_refresh.call(self, options); } else { assert(!options.set, "getter is missing : a getter must be provided if a setter is provided"); //xx bind_variant.call(self,options); self.setValueFromSource(options); } } UAVariable.prototype._internal_set_dataValue = function (dataValue, indexRange) { var self = this; var old_dataValue = self._dataValue; self._dataValue = dataValue; self._dataValue.statusCode = self._dataValue.statusCode || StatusCodes.Good; if (sourceTimestampHasChanged(old_dataValue, dataValue)) { self.emit("value_changed", self._dataValue, indexRange); } }; /** * bind a variable with a get and set functions. * * @method bindVariable * @param options * @param [options.dataType=null] {DataType} the nodeId of the dataType * @param [options.accessLevel] {Number} AccessLevelFlagItem * @param [options.userAccessLevel] {Number} AccessLevelFlagItem * @param [options.set] {Function} the variable setter function * @param [options.get] {Function} the variable getter function. the function must return a Variant or a status code * @param [options.timestamped_get] {Function} the getter function. this function must return a object with the following * properties: * - value: a Variant or a status code * - sourceTimestamp * - sourcePicoseconds * @param [options.timestamped_set] {Function} * @param [options.refreshFunc] {Function} the variable asynchronous getter function. * @return void * * * ### Providing read access to the underlying value * * #### Variation 1 * * In this variation, the user provides a function that returns a Variant with the current value. * * The sourceTimestamp will be set automatically. * * The get function is called synchronously. * * @example * * * ```javascript * ... * var options = { * get : function() { * return new Variant({...}); * }, * set : function(variant) { * // store the variant somewhere * return StatusCodes.Good; * } * }; * ... * engine.bindVariable(nodeId,options): * ... * ``` * * * #### Variation 2: * * This variation can be used when the user wants to specify a specific '''sourceTimestamp''' associated * with the current value of the UAVariable. * * The provided ```timestamped_get``` function should return an object with three properties: * * value: containing the variant value or a error StatusCode, * * sourceTimestamp * * sourcePicoseconds * * ```javascript * ... * var myDataValue = new DataValue({ * value: {dataType: DataType.Double , value: 10.0}, * sourceTimestamp : new Date(), * sourcePicoseconds: 0 * }); * ... * var options = { * timestamped_get : function() { return myDataValue; } * }; * ... * engine.bindVariable(nodeId,options): * ... * // record a new value * myDataValue.value.value = 5.0; * myDataValue.sourceTimestamp = new Date(); * ... * ``` * * * #### Variation 3: * * This variation can be used when the value associated with the variables requires a asynchronous function call to be * extracted. In this case, the user should provide an async method ```refreshFunc```. * * * The ```refreshFunc``` shall do whatever is necessary to fetch the most up to date version of the variable value, and * call the ```callback``` function when the data is ready. * * * The ```callback``` function follow the standard callback function signature: * * the first argument shall be **null** or **Error**, depending of the outcome of the fetch operation, * * the second argument shall be a DataValuewith the new UAVariable Value, a StatusCode, and time stamps. * * * Optionally, it is possible to pass a sourceTimestamp and a sourcePicoseconds value as a third and fourth arguments * of the callback. When sourceTimestamp and sourcePicoseconds are missing, the system will set their default value * to the current time.. * * * ```javascript * ... * var options = { * refreshFunc : function(callback) { * ... do_some_async_stuff_to_get_the_new_variable_value * var dataValue = new DataValue({ * value: new Variant({...}), * statusCode: StatusCodes.Good, * sourceTimestamp: new Date() * }); * callback(null,dataValue); * } * }; * ... * engine.bindVariable(nodeId,options): * ... * ``` * * ### Providing write access to the underlying value * * #### Variation1 - provide a simple synchronous set function * * * #### Notes * to do : explain return StatusCodes.GoodCompletesAsynchronously; * */ UAVariable.prototype.bindVariable = function (options) { var self = this; options = options || {}; assert(!_.isFunction(self._timestamped_set_func)); bind_getter(self,options); bind_setter(self,options); assert(_.isFunction(self._timestamped_set_func)); assert(self._timestamped_set_func.length === 3); }; /** * @method readValueAsync * @param callback {Function} * @param callback.err {null|Error} * @param callback.dataValue {DataValue|null} the value read * @async */ UAVariable.prototype.readValueAsync = function (callback) { var self = this; self.__waiting_callbacks = self.__waiting_callbacks || []; self.__waiting_callbacks.push(callback); var _readValueAsync_in_progress = self.__waiting_callbacks.length >= 2; if (_readValueAsync_in_progress) { return; } function readImmediate(callback) { assert(self._dataValue instanceof DataValue); callback(null, self._dataValue); } var func = _.isFunction(self.asyncRefresh) ? self.asyncRefresh : readImmediate; function satisfy_callbacks(err, dataValue) { // now call all pending callbacks var callbacks = self.__waiting_callbacks; self.__waiting_callbacks = []; callbacks.forEach(function (callback) { callback.call(self, err, dataValue); }); } try { func.call(this, satisfy_callbacks); } catch (err) { // istanbul ignore next console.log("func readValueAsync has failed ".red); console.log(" stack",err.stack); satisfy_callbacks(err); } }; UAVariable.prototype.getWriteMask = function () { return BaseNode.prototype.getWriteMask.call(this); }; UAVariable.prototype.getUserWriteMask = function () { return BaseNode.prototype.getUserWriteMask.call(this); }; UAVariable.prototype.clone = function () { var self = this; var options = { eventNotifier: self.eventNotifier, symbolicName: self.symbolicName, value: self.value, dataType: self.dataType, valueRank: self.valueRank, arrayDimensions: self.arrayDimensions, accessLevel: self.accessLevel, userAccessLevel: self.userAccessLevel, minimumSamplingInterval: self.minimumSamplingInterval, historizing: self.historizing }; var newVariable = self._clone(UAVariable, options); assert(newVariable.dataType === self.dataType); newVariable._dataValue = self._dataValue.clone(); return newVariable; }; exports.UAVariable = UAVariable;
// Generated by CoffeeScript 1.12.6 (function() { var Bits, CustomReceiver, DEBUG_INCOMING_PACKET_DATA, DEBUG_INCOMING_PACKET_HASH, DEFAULT_SERVER_NAME, Sequent, StreamServer, aac, avstreams, config, crypto, fs, h264, http, logger, mp4, net, packageJson, ref, rtmp, rtsp, serverName; net = require('net'); fs = require('fs'); crypto = require('crypto'); config = require('./config'); rtmp = require('./rtmp'); http = require('./http'); rtsp = require('./rtsp'); h264 = require('./h264'); aac = require('./aac'); mp4 = require('./mp4'); Bits = require('./bits'); avstreams = require('./avstreams'); CustomReceiver = require('./custom_receiver'); logger = require('./logger'); packageJson = require('./package.json'); Sequent = require('sequent'); DEBUG_INCOMING_PACKET_DATA = false; DEBUG_INCOMING_PACKET_HASH = false; DEFAULT_SERVER_NAME = "node-rtsp-rtmp-server/" + packageJson.version; serverName = (ref = config.serverName) != null ? ref : DEFAULT_SERVER_NAME; StreamServer = (function() { function StreamServer(opts) { var httpHandler, ref1, rtmptCallback; this.serverName = (ref1 = opts != null ? opts.serverName : void 0) != null ? ref1 : serverName; if (config.enableRTMP || config.enableRTMPT) { this.rtmpServer = new rtmp.RTMPServer; this.rtmpServer.on('video_start', (function(_this) { return function(streamId) { var stream; stream = avstreams.getOrCreate(streamId); return _this.onReceiveVideoControlBuffer(stream); }; })(this)); this.rtmpServer.on('video_data', (function(_this) { return function(streamId, pts, dts, nalUnits) { var stream; stream = avstreams.get(streamId); if (stream != null) { return _this.onReceiveVideoPacket(stream, nalUnits, pts, dts); } else { return logger.warn("warn: Received invalid streamId from rtmp: " + streamId); } }; })(this)); this.rtmpServer.on('audio_start', (function(_this) { return function(streamId) { var stream; stream = avstreams.getOrCreate(streamId); return _this.onReceiveAudioControlBuffer(stream); }; })(this)); this.rtmpServer.on('audio_data', (function(_this) { return function(streamId, pts, dts, adtsFrame) { var stream; stream = avstreams.get(streamId); if (stream != null) { return _this.onReceiveAudioPacket(stream, adtsFrame, pts, dts); } else { return logger.warn("warn: Received invalid streamId from rtmp: " + streamId); } }; })(this)); } if (config.enableCustomReceiver) { this.customReceiver = new CustomReceiver(config.receiverType, { videoControl: (function(_this) { return function() { return _this.onReceiveVideoControlBuffer.apply(_this, arguments); }; })(this), audioControl: (function(_this) { return function() { return _this.onReceiveAudioControlBuffer.apply(_this, arguments); }; })(this), videoData: (function(_this) { return function() { return _this.onReceiveVideoDataBuffer.apply(_this, arguments); }; })(this), audioData: (function(_this) { return function() { return _this.onReceiveAudioDataBuffer.apply(_this, arguments); }; })(this) }); this.customReceiver.deleteReceiverSocketsSync(); } if (config.enableHTTP) { this.httpHandler = new http.HTTPHandler({ serverName: this.serverName, documentRoot: opts != null ? opts.documentRoot : void 0 }); } if (config.enableRTSP || config.enableHTTP || config.enableRTMPT) { if (config.enableRTMPT) { rtmptCallback = (function(_this) { return function() { var ref2; return (ref2 = _this.rtmpServer).handleRTMPTRequest.apply(ref2, arguments); }; })(this); } else { rtmptCallback = null; } if (config.enableHTTP) { httpHandler = this.httpHandler; } else { httpHandler = null; } this.rtspServer = new rtsp.RTSPServer({ serverName: this.serverName, httpHandler: httpHandler, rtmptCallback: rtmptCallback }); this.rtspServer.on('video_start', (function(_this) { return function(stream) { return _this.onReceiveVideoControlBuffer(stream); }; })(this)); this.rtspServer.on('audio_start', (function(_this) { return function(stream) { return _this.onReceiveAudioControlBuffer(stream); }; })(this)); this.rtspServer.on('video', (function(_this) { return function(stream, nalUnits, pts, dts) { return _this.onReceiveVideoNALUnits(stream, nalUnits, pts, dts); }; })(this)); this.rtspServer.on('audio', (function(_this) { return function(stream, accessUnits, pts, dts) { return _this.onReceiveAudioAccessUnits(stream, accessUnits, pts, dts); }; })(this)); } avstreams.on('new', function(stream) { if (DEBUG_INCOMING_PACKET_HASH) { return stream.lastSentVideoTimestamp = 0; } }); avstreams.on('reset', function(stream) { if (DEBUG_INCOMING_PACKET_HASH) { return stream.lastSentVideoTimestamp = 0; } }); avstreams.on('end', (function(_this) { return function(stream) { if (config.enableRTSP) { _this.rtspServer.sendEOS(stream); } if (config.enableRTMP || config.enableRTMPT) { return _this.rtmpServer.sendEOS(stream); } }; })(this)); avstreams.on('audio_data', (function(_this) { return function(stream, data, pts) { return _this.onReceiveAudioAccessUnits(stream, [data], pts, pts); }; })(this)); avstreams.on('video_data', (function(_this) { return function(stream, nalUnits, pts, dts) { if (dts == null) { dts = pts; } return _this.onReceiveVideoNALUnits(stream, nalUnits, pts, dts); }; })(this)); avstreams.on('audio_start', (function(_this) { return function(stream) { return _this.onReceiveAudioControlBuffer(stream); }; })(this)); avstreams.on('video_start', (function(_this) { return function(stream) { return _this.onReceiveVideoControlBuffer(stream); }; })(this)); } StreamServer.prototype.attachRecordedDir = function(dir) { if (config.recordedApplicationName != null) { logger.info("attachRecordedDir: dir=" + dir + " app=" + config.recordedApplicationName); return avstreams.attachRecordedDirToApp(dir, config.recordedApplicationName); } }; StreamServer.prototype.attachMP4 = function(filename, streamName) { var context, generator; logger.info("attachMP4: file=" + filename + " stream=" + streamName); context = this; generator = new avstreams.AVStreamGenerator({ generate: function() { var ascBuf, ascInfo, audioSpecificConfig, bits, err, mp4File, mp4Stream, streamId; try { mp4File = new mp4.MP4File(filename); } catch (error) { err = error; logger.error("error opening MP4 file " + filename + ": " + err); return null; } streamId = avstreams.createNewStreamId(); mp4Stream = new avstreams.MP4Stream(streamId); logger.info("created stream " + streamId + " from " + filename); avstreams.emit('new', mp4Stream); avstreams.add(mp4Stream); mp4Stream.type = avstreams.STREAM_TYPE_RECORDED; audioSpecificConfig = null; mp4File.on('audio_data', function(data, pts) { return context.onReceiveAudioAccessUnits(mp4Stream, [data], pts, pts); }); mp4File.on('video_data', function(nalUnits, pts, dts) { if (dts == null) { dts = pts; } return context.onReceiveVideoNALUnits(mp4Stream, nalUnits, pts, dts); }); mp4File.on('eof', (function(_this) { return function() { return mp4Stream.emit('end'); }; })(this)); mp4File.parse(); mp4Stream.updateSPS(mp4File.getSPS()); mp4Stream.updatePPS(mp4File.getPPS()); ascBuf = mp4File.getAudioSpecificConfig(); bits = new Bits(ascBuf); ascInfo = aac.readAudioSpecificConfig(bits); mp4Stream.updateConfig({ audioSpecificConfig: ascBuf, audioASCInfo: ascInfo, audioSampleRate: ascInfo.samplingFrequency, audioClockRate: 90000, audioChannels: ascInfo.channelConfiguration, audioObjectType: ascInfo.audioObjectType }); mp4Stream.durationSeconds = mp4File.getDurationSeconds(); mp4Stream.lastTagTimestamp = mp4File.getLastTimestamp(); mp4Stream.mp4File = mp4File; mp4File.fillBuffer(function() { context.onReceiveAudioControlBuffer(mp4Stream); return context.onReceiveVideoControlBuffer(mp4Stream); }); return mp4Stream; }, play: function() { return this.mp4File.play(); }, pause: function() { return this.mp4File.pause(); }, resume: function() { return this.mp4File.resume(); }, seek: function(seekSeconds, callback) { var actualStartTime; actualStartTime = this.mp4File.seek(seekSeconds); return callback(null, actualStartTime); }, sendVideoPacketsSinceLastKeyFrame: function(endSeconds, callback) { return this.mp4File.sendVideoPacketsSinceLastKeyFrame(endSeconds, callback); }, teardown: function() { this.mp4File.close(); return this.destroy(); }, getCurrentPlayTime: function() { return this.mp4File.currentPlayTime; }, isPaused: function() { return this.mp4File.isPaused(); } }); return avstreams.addGenerator(streamName, generator); }; StreamServer.prototype.stop = function(callback) { if (config.enableCustomReceiver) { this.customReceiver.deleteReceiverSocketsSync(); } return typeof callback === "function" ? callback() : void 0; }; StreamServer.prototype.start = function(callback) { var seq, waitCount; seq = new Sequent; waitCount = 0; if (config.enableRTMP) { waitCount++; this.rtmpServer.start({ port: config.rtmpServerPort }, function() { return seq.done(); }); } if (config.enableCustomReceiver) { this.customReceiver.start(); } if (config.enableRTSP || config.enableHTTP || config.enableRTMPT) { waitCount++; this.rtspServer.start({ port: config.serverPort }, function() { return seq.done(); }); } return seq.wait(waitCount, function() { return typeof callback === "function" ? callback() : void 0; }); }; StreamServer.prototype.setLivePathConsumer = function(func) { if (config.enableRTSP) { return this.rtspServer.setLivePathConsumer(func); } }; StreamServer.prototype.setAuthenticator = function(func) { if (config.enableRTSP) { return this.rtspServer.setAuthenticator(func); } }; StreamServer.prototype.onReceiveVideoControlBuffer = function(stream, buf) { stream.resetFrameRate(stream); stream.isVideoStarted = true; stream.timeAtVideoStart = Date.now(); return stream.timeAtAudioStart = stream.timeAtVideoStart; }; StreamServer.prototype.onReceiveAudioControlBuffer = function(stream, buf) { stream.isAudioStarted = true; stream.timeAtAudioStart = Date.now(); return stream.timeAtVideoStart = stream.timeAtAudioStart; }; StreamServer.prototype.onReceiveVideoDataBuffer = function(stream, buf) { var dts, nalUnit, pts; pts = buf[1] * 0x010000000000 + buf[2] * 0x0100000000 + buf[3] * 0x01000000 + buf[4] * 0x010000 + buf[5] * 0x0100 + buf[6]; dts = pts; nalUnit = buf.slice(7); return this.onReceiveVideoPacket(stream, nalUnit, pts, dts); }; StreamServer.prototype.onReceiveAudioDataBuffer = function(stream, buf) { var adtsFrame, dts, pts; pts = buf[1] * 0x010000000000 + buf[2] * 0x0100000000 + buf[3] * 0x01000000 + buf[4] * 0x010000 + buf[5] * 0x0100 + buf[6]; dts = pts; adtsFrame = buf.slice(7); return this.onReceiveAudioPacket(stream, adtsFrame, pts, dts); }; StreamServer.prototype.onReceiveVideoNALUnits = function(stream, nalUnits, pts, dts) { var hasVideoFrame, j, len, md5, nalUnit, nalUnitType, tsDiff; if (DEBUG_INCOMING_PACKET_DATA) { logger.info("receive video: num_nal_units=" + nalUnits.length + " pts=" + pts); } if (config.enableRTSP) { this.rtspServer.sendVideoData(stream, nalUnits, pts, dts); } if (config.enableRTMP || config.enableRTMPT) { this.rtmpServer.sendVideoPacket(stream, nalUnits, pts, dts); } hasVideoFrame = false; for (j = 0, len = nalUnits.length; j < len; j++) { nalUnit = nalUnits[j]; nalUnitType = h264.getNALUnitType(nalUnit); if (nalUnitType === h264.NAL_UNIT_TYPE_SPS) { stream.updateSPS(nalUnit); } else if (nalUnitType === h264.NAL_UNIT_TYPE_PPS) { stream.updatePPS(nalUnit); } else if ((nalUnitType === h264.NAL_UNIT_TYPE_IDR_PICTURE) || (nalUnitType === h264.NAL_UNIT_TYPE_NON_IDR_PICTURE)) { hasVideoFrame = true; } if (DEBUG_INCOMING_PACKET_HASH) { md5 = crypto.createHash('md5'); md5.update(nalUnit); tsDiff = pts - stream.lastSentVideoTimestamp; logger.info("video: pts=" + pts + " pts_diff=" + tsDiff + " md5=" + (md5.digest('hex').slice(0, 7)) + " nal_unit_type=" + nalUnitType + " bytes=" + nalUnit.length); stream.lastSentVideoTimestamp = pts; } } if (hasVideoFrame) { stream.calcFrameRate(pts); } }; StreamServer.prototype.onReceiveVideoPacket = function(stream, nalUnitGlob, pts, dts) { var nalUnits; nalUnits = h264.splitIntoNALUnits(nalUnitGlob); if (nalUnits.length === 0) { return; } this.onReceiveVideoNALUnits(stream, nalUnits, pts, dts); }; StreamServer.prototype.onReceiveAudioAccessUnits = function(stream, accessUnits, pts, dts) { var accessUnit, i, j, len, md5, ptsPerFrame; if (config.enableRTSP) { this.rtspServer.sendAudioData(stream, accessUnits, pts, dts); } if (DEBUG_INCOMING_PACKET_DATA) { logger.info("receive audio: num_access_units=" + accessUnits.length + " pts=" + pts); } ptsPerFrame = 90000 / (stream.audioSampleRate / 1024); for (i = j = 0, len = accessUnits.length; j < len; i = ++j) { accessUnit = accessUnits[i]; if (DEBUG_INCOMING_PACKET_HASH) { md5 = crypto.createHash('md5'); md5.update(accessUnit); logger.info("audio: pts=" + pts + " md5=" + (md5.digest('hex').slice(0, 7)) + " bytes=" + accessUnit.length); } if (config.enableRTMP || config.enableRTMPT) { this.rtmpServer.sendAudioPacket(stream, accessUnit, Math.round(pts + ptsPerFrame * i), Math.round(dts + ptsPerFrame * i)); } } }; StreamServer.prototype.onReceiveAudioPacket = function(stream, adtsFrameGlob, pts, dts) { var adtsFrame, adtsFrames, adtsInfo, i, isConfigUpdated, j, len, rawDataBlock, rawDataBlocks, rtpTimePerFrame; adtsFrames = aac.splitIntoADTSFrames(adtsFrameGlob); if (adtsFrames.length === 0) { return; } adtsInfo = aac.parseADTSFrame(adtsFrames[0]); isConfigUpdated = false; stream.updateConfig({ audioSampleRate: adtsInfo.sampleRate, audioClockRate: adtsInfo.sampleRate, audioChannels: adtsInfo.channels, audioObjectType: adtsInfo.audioObjectType }); rtpTimePerFrame = 1024; rawDataBlocks = []; for (i = j = 0, len = adtsFrames.length; j < len; i = ++j) { adtsFrame = adtsFrames[i]; rawDataBlock = adtsFrame.slice(7); rawDataBlocks.push(rawDataBlock); } return this.onReceiveAudioAccessUnits(stream, rawDataBlocks, pts, dts); }; return StreamServer; })(); module.exports = StreamServer; }).call(this);
// @flow import React from 'react' import {connect} from 'react-redux'; import * as THREE from 'three' import ReactAnimationFrame from 'react-animation-frame' import { increaseBuildingTargetHeight, progressTime, placeNewBuilding, placeStreet, reset, updateEventStatus} from '../sceneActionCreators' import { FACINGS, GRID_WIDTH, GRID_LENGTH, BUILDING, STREET, VACANT, BUILDING_COLORS} from '../constants' class Ticker extends React.Component { noMoreUpdates = false; onAnimationFrame(time) { if (!this.noMoreUpdates) { if (this.props.ticks >= this.props.nextEventAt) { this.generateBuildingEvent(); this.updateEventState(); } if (this.props.ticks < 500) { this.props.handleFrameUpdate(); } else { this.props.handleReset(); } } } updateEventState() { this.props.handleEventStatusUpdate(); } generateBuildingEvent() { let x = parseInt(Math.random() * GRID_WIDTH, 10); let y = parseInt(Math.random() * GRID_LENGTH, 10); let lot = this.props.grid[x][y]; if (lot.lotType === BUILDING) { this.props.handleBuildingShouldGrow(x, y); } else if (lot.lotType === VACANT) { let facingIndex = parseInt(Math.random() * FACINGS.length, 10); let facing = FACINGS[facingIndex]; let placeable = false; let smallBuilding = parseInt(Math.random() * 5) === 0; for (var i = 0; i < FACINGS.length; i++) { let faceToTry = FACINGS[(facingIndex + i) % FACINGS.length]; let tryX = x + faceToTry.direction.x; let tryY = y + faceToTry.direction.y; let tryX2 = tryX + faceToTry.direction.x; let tryY2 = tryY + faceToTry.direction.y; if (tryX < 0 || tryX >= GRID_WIDTH) { continue; } if (tryY < 0 || tryY >= GRID_LENGTH) { continue; } if (!(tryX2 < 0 || tryX2 >= GRID_WIDTH || tryY2 < 0 || tryY2 >= GRID_LENGTH || this.props.grid[tryX2][tryY2].lotType !== STREET)) { continue; } if (this.props.grid[tryX][tryY].lotType !== BUILDING) { placeable = true; facing = faceToTry; break; } } if (!placeable) { return; } let goodPositions = [{x, y}]; if (!smallBuilding) { let startFromLeftPositions = [{x, y}]; let startFromRightPositions = [{x, y}]; let startFromBackPositions = [{x, y}]; let backPos = this.applyDirection({x, y}, facing.opposite); let leftPos = this.applyDirection({x, y}, facing.left); let rightPos = this.applyDirection({x, y}, facing.right); if (this.inBounds(rightPos) && this.props.grid[rightPos.x][rightPos.y].lotType === VACANT) { startFromRightPositions.push(rightPos); let posBackRight = this.applyDirection(rightPos, facing.opposite); if (this.inBounds(posBackRight) && this.inBounds(backPos) && this.props.grid[posBackRight.x][posBackRight.y].lotType === VACANT && this.props.grid[backPos.x][backPos.y].lotType === VACANT) { startFromRightPositions.push(posBackRight); startFromRightPositions.push(backPos); } } if (this.inBounds(leftPos) && this.props.grid[leftPos.x][leftPos.y].lotType === VACANT) { startFromLeftPositions.push(leftPos); let posBackLeft = this.applyDirection(leftPos, facing.opposite); if (this.inBounds(posBackLeft) && this.inBounds(backPos) && this.props.grid[posBackLeft.x][posBackLeft.y].lotType === VACANT && this.props.grid[backPos.x][backPos.y].lotType === VACANT) { startFromLeftPositions.push(posBackLeft); startFromLeftPositions.push(backPos); } } if (this.inBounds(backPos) && this.props.grid[backPos.x][backPos.y].lotType === VACANT) { startFromBackPositions.push(backPos); } if (startFromBackPositions.length > goodPositions.length) { goodPositions = startFromBackPositions; } if (startFromLeftPositions.length > goodPositions.length) { goodPositions = startFromLeftPositions; } if (startFromRightPositions.length > goodPositions.length) { goodPositions = startFromRightPositions; } } let newBuilding = { color: this.pickBuildingColor(), connectedLots: goodPositions, name: `building_${x}-${y}`, facing: facing } this.props.handlePlaceBuilding(x, y, newBuilding); this.props.handlePlaceStreet(x + facing.direction.x, y + facing.direction.y, facing); } } render() { return (<h1>{this.props.ticks}</h1>) } pickBuildingColor() { return BUILDING_COLORS[parseInt(Math.random() * BUILDING_COLORS.length)]; } inBounds(pos: {x: number, y: number}) { return (pos.x >= 0 && pos.x < GRID_WIDTH && pos.y >= 0 && pos.y < GRID_LENGTH); } applyDirection(pos: {x:number, y:number}, direction: {x: number, y:number}) { return {x: pos.x + direction.x, y: pos.y + direction.y}; } } const mapStateToProps = state => { return ({ ticks: state.get("scene").ticks, nextEventAt: state.get("scene").nextEventAt, grid: state.get("scene").city.grid }); } const mapDispatchToProps = (dispatch: Function) => ({ handleFrameUpdate() { dispatch(progressTime()) }, handleEventStatusUpdate() { dispatch(updateEventStatus(parseInt(Math.random() * 5, 10) + 5)); }, handleBuildingShouldGrow(x: number, y: number) { dispatch(increaseBuildingTargetHeight(x, y)); }, handlePlaceBuilding(x: number, y: number, building: {color: number, connectedLots: Array, name: string}) { dispatch(placeNewBuilding(x, y, building)); }, handlePlaceStreet(x: number, y: number, facing: Object) { dispatch(placeStreet(x,y, facing)); }, handleReset() { dispatch(reset()); } }); export default connect(mapStateToProps, mapDispatchToProps)(ReactAnimationFrame(Ticker, 20));
/** * Build client */ 'use strict'; /** * Module dependencies. */ var middleware = require('./middleware'); /** * Initialize a new `Build` client. */ function Build(jenkins) { this.jenkins = jenkins; } /** * Build details */ Build.prototype.get = function(opts, callback) { var arg0 = typeof arguments[0]; var arg1 = typeof arguments[1]; var arg2 = typeof arguments[2]; var arg3 = typeof arguments[3]; if (arg0 === 'string' && (arg1 === 'string' || arg1 === 'number')) { if (arg2 === 'object') { opts = arguments[2]; callback = arg3 === 'function' ? arguments[3] : undefined; } else { opts = {}; callback = arg2 === 'function' ? arguments[2] : undefined; } opts.name = arguments[0]; opts.number = arguments[1]; } else { opts = opts || {}; } opts.depth = opts.depth || 0; this.jenkins._log(['debug', 'build', 'get'], opts); var req = { name: 'build.get' }; try { if (!opts.name) throw new Error('name required'); if (!opts.number) throw new Error('number required'); req.path = '/job/{name}/{number}/api/json'; req.params = { name: opts.name, number: opts.number, }; req.query = { depth: opts.depth }; } catch (err) { return callback(this.jenkins._err(err, req)); } return this.jenkins._get( req, middleware.notFound(opts.name + ' ' + opts.number), middleware.body, callback ); }; /** * Stop build */ Build.prototype.stop = function(opts, callback) { var arg0 = typeof arguments[0]; var arg1 = typeof arguments[1]; if (arg0 === 'string' && (arg1 === 'string' || arg1 === 'number')) { opts = { name: arguments[0], number: arguments[1], }; callback = arguments[2]; } else { opts = opts || {}; } this.jenkins._log(['debug', 'build', 'stop'], opts); var req = { name: 'build.stop' }; try { if (!opts.name) throw new Error('name required'); if (!opts.number) throw new Error('number required'); req.path = '/job/{name}/{number}/stop'; req.params = { name: opts.name, number: opts.number, }; } catch (err) { return callback(this.jenkins._err(err, req)); } return this.jenkins._get( req, middleware.notFound(opts.name + ' ' + opts.number), middleware.require302('failed to stop: ' + opts.name), middleware.empty, callback ); }; /** * Get build log */ Build.prototype.log = function(opts, callback) { var arg0 = typeof arguments[0]; var arg1 = typeof arguments[1]; var arg2 = typeof arguments[2]; var arg3 = typeof arguments[3]; if (arg0 === 'string' && (arg1 === 'string' || arg1 === 'number')) { if (arg2 === 'object') { opts = arguments[2]; callback = arg3 === 'function' ? arguments[3] : undefined; } else { opts = {}; callback = arg2 === 'function' ? arguments[2] : undefined; } opts.name = arguments[0]; opts.number = arguments[1]; } else { opts = opts || {}; } opts.depth = opts.depth || 0; this.jenkins._log(['debug', 'build', 'log'], opts); var req = { name: 'build.log' }; try { if (!opts.name) throw new Error('name required'); if (!opts.number) throw new Error('number required'); req.path = '/job/{name}/{number}/consoleText'; req.params = { name: opts.name, number: opts.number, }; } catch (err) { return callback(this.jenkins._err(err, req)); } return this.jenkins._get( req, middleware.notFound(opts.name + ' ' + opts.number), middleware.body, callback ); }; /** * Module exports. */ exports.Build = Build;
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import Router from 'react-routing/src/Router'; import http from './core/HttpClient'; // boilerplate included components import App from './components/App'; import ContentPage from './components/ContentPage'; import RegisterPage from './components/RegisterPage'; import NotFoundPage from './components/NotFoundPage'; import ErrorPage from './components/ErrorPage'; // // custom components import HomePage from './components/HomePage'; import CaseStudy from './components/CaseStudy'; const router = new Router(on => { on('*', async (state, next) => { const component = await next(); return component && <App context={state.context}> {component} </App>; }); on('/work/*', async () => { const content = await http.get(`http://sullivan-public-website.dev/wp-json/posts/211`); return content && <CaseStudy content={content} />; }); on('/contact', async () => <ContactPage />); on('/', async () => <HomePage /> ); on('/register', async () => <RegisterPage />); on('*', async (state) => { const content = await http.get(`/api/content?path=${state.path}`); return content && <ContentPage {...content} />; }); on('error', (state, error) => state.statusCode === 404 ? <App context={state.context} error={error}><NotFoundPage /></App> : <App context={state.context} error={error}><ErrorPage /></App> ); }); export default router;
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../xml/xml"), require("../meta")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../xml/xml", "../meta"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) { var htmlMode = CodeMirror.getMode(cmCfg, "text/html"); var htmlModeMissing = htmlMode.name == "null" function getMode(name) { if (CodeMirror.findModeByName) { var found = CodeMirror.findModeByName(name); if (found) name = found.mime || found.mimes[0]; } var mode = CodeMirror.getMode(cmCfg, name); return mode.name == "null" ? null : mode; } // Should characters that affect highlighting be highlighted separate? // Does not include characters that will be output (such as `1.` and `-` for lists) if (modeCfg.highlightFormatting === undefined) modeCfg.highlightFormatting = false; // Maximum number of nested blockquotes. Set to 0 for infinite nesting. // Excess `>` will emit `error` token. if (modeCfg.maxBlockquoteDepth === undefined) modeCfg.maxBlockquoteDepth = 0; // Should underscores in words open/close em/strong? if (modeCfg.underscoresBreakWords === undefined) modeCfg.underscoresBreakWords = true; // Use `fencedCodeBlocks` to configure fenced code blocks. false to // disable, string to specify a precise regexp that the fence should // match, and true to allow three or more backticks or tildes (as // per CommonMark). // Turn on task lists? ("- [ ] " and "- [x] ") if (modeCfg.taskLists === undefined) modeCfg.taskLists = false; // Turn on strikethrough syntax if (modeCfg.strikethrough === undefined) modeCfg.strikethrough = false; // Allow token types to be overridden by user-provided token types. if (modeCfg.tokenTypeOverrides === undefined) modeCfg.tokenTypeOverrides = {}; var tokenTypes = { header: "header", code: "comment", quote: "quote", list1: "variable-2", list2: "variable-3", list3: "variable-3", hr: "hr", image: "image", imageAltText: "image-alt-text", imageMarker: "image-marker", formatting: "formatting", linkInline: "link", linkEmail: "link", linkText: "link", linkHref: "string", em: "em", strong: "strong", strikethrough: "strikethrough" }; for (var tokenType in tokenTypes) { if (tokenTypes.hasOwnProperty(tokenType) && modeCfg.tokenTypeOverrides[tokenType]) { tokenTypes[tokenType] = modeCfg.tokenTypeOverrides[tokenType]; } } var hrRE = /^([*\-_])(?:\s*\1){2,}\s*$/ , ulRE = /^[*\-+]\s+/ , olRE = /^[0-9]+([.)])\s+/ , taskListRE = /^\[(x| )\](?=\s)/ // Must follow ulRE or olRE , atxHeaderRE = modeCfg.allowAtxHeaderWithoutSpace ? /^(#+)/ : /^(#+)(?: |$)/ , setextHeaderRE = /^ *(?:\={1,}|-{1,})\s*$/ , textRE = /^[^#!\[\]*_\\<>` "'(~]+/ , fencedCodeRE = new RegExp("^(" + (modeCfg.fencedCodeBlocks === true ? "~~~+|```+" : modeCfg.fencedCodeBlocks) + ")[ \\t]*([\\w+#\-]*)"); function switchInline(stream, state, f) { state.f = state.inline = f; return f(stream, state); } function switchBlock(stream, state, f) { state.f = state.block = f; return f(stream, state); } function lineIsEmpty(line) { return !line || !/\S/.test(line.string) } // Blocks function blankLine(state) { // Reset linkTitle state state.linkTitle = false; // Reset EM state state.em = false; // Reset STRONG state state.strong = false; // Reset strikethrough state state.strikethrough = false; // Reset state.quote state.quote = 0; // Reset state.indentedCode state.indentedCode = false; if (htmlModeMissing && state.f == htmlBlock) { state.f = inlineNormal; state.block = blockNormal; } // Reset state.trailingSpace state.trailingSpace = 0; state.trailingSpaceNewLine = false; // Mark this line as blank state.prevLine = state.thisLine state.thisLine = null return null; } function blockNormal(stream, state) { var sol = stream.sol(); var prevLineIsList = state.list !== false, prevLineIsIndentedCode = state.indentedCode; state.indentedCode = false; if (prevLineIsList) { if (state.indentationDiff >= 0) { // Continued list if (state.indentationDiff < 4) { // Only adjust indentation if *not* a code block state.indentation -= state.indentationDiff; } state.list = null; } else if (state.indentation > 0) { state.list = null; } else { // No longer a list state.list = false; } } var match = null; if (state.indentationDiff >= 4) { stream.skipToEnd(); if (prevLineIsIndentedCode || lineIsEmpty(state.prevLine)) { state.indentation -= 4; state.indentedCode = true; return tokenTypes.code; } else { return null; } } else if (stream.eatSpace()) { return null; } else if ((match = stream.match(atxHeaderRE)) && match[1].length <= 6) { state.header = match[1].length; if (modeCfg.highlightFormatting) state.formatting = "header"; state.f = state.inline; return getType(state); } else if (!lineIsEmpty(state.prevLine) && !state.quote && !prevLineIsList && !prevLineIsIndentedCode && (match = stream.match(setextHeaderRE))) { state.header = match[0].charAt(0) == '=' ? 1 : 2; if (modeCfg.highlightFormatting) state.formatting = "header"; state.f = state.inline; return getType(state); } else if (stream.eat('>')) { state.quote = sol ? 1 : state.quote + 1; if (modeCfg.highlightFormatting) state.formatting = "quote"; stream.eatSpace(); return getType(state); } else if (stream.peek() === '[') { return switchInline(stream, state, footnoteLink); } else if (stream.match(hrRE, true)) { state.hr = true; return tokenTypes.hr; } else if ((lineIsEmpty(state.prevLine) || prevLineIsList) && (stream.match(ulRE, false) || stream.match(olRE, false))) { var listType = null; if (stream.match(ulRE, true)) { listType = 'ul'; } else { stream.match(olRE, true); listType = 'ol'; } state.indentation = stream.column() + stream.current().length; state.list = true; // While this list item's marker's indentation // is less than the deepest list item's content's indentation, // pop the deepest list item indentation off the stack. while (state.listStack && stream.column() < state.listStack[state.listStack.length - 1]) { state.listStack.pop(); } // Add this list item's content's indentation to the stack state.listStack.push(state.indentation); if (modeCfg.taskLists && stream.match(taskListRE, false)) { state.taskList = true; } state.f = state.inline; if (modeCfg.highlightFormatting) state.formatting = ["list", "list-" + listType]; return getType(state); } else if (modeCfg.fencedCodeBlocks && (match = stream.match(fencedCodeRE, true))) { state.fencedChars = match[1] // try switching mode state.localMode = getMode(match[2]); if (state.localMode) state.localState = CodeMirror.startState(state.localMode); state.f = state.block = local; if (modeCfg.highlightFormatting) state.formatting = "code-block"; state.code = -1 return getType(state); } return switchInline(stream, state, state.inline); } function htmlBlock(stream, state) { var style = htmlMode.token(stream, state.htmlState); if (!htmlModeMissing) { var inner = CodeMirror.innerMode(htmlMode, state.htmlState) if ((inner.mode.name == "xml" && inner.state.tagStart === null && (!inner.state.context && inner.state.tokenize.isInText)) || (state.md_inside && stream.current().indexOf(">") > -1)) { state.f = inlineNormal; state.block = blockNormal; state.htmlState = null; } } return style; } function local(stream, state) { if (state.fencedChars && stream.match(state.fencedChars, false)) { state.localMode = state.localState = null; state.f = state.block = leavingLocal; return null; } else if (state.localMode) { return state.localMode.token(stream, state.localState); } else { stream.skipToEnd(); return tokenTypes.code; } } function leavingLocal(stream, state) { stream.match(state.fencedChars); state.block = blockNormal; state.f = inlineNormal; state.fencedChars = null; if (modeCfg.highlightFormatting) state.formatting = "code-block"; state.code = 1 var returnType = getType(state); state.code = 0 return returnType; } // Inline function getType(state) { var styles = []; if (state.formatting) { styles.push(tokenTypes.formatting); if (typeof state.formatting === "string") state.formatting = [state.formatting]; for (var i = 0; i < state.formatting.length; i++) { styles.push(tokenTypes.formatting + "-" + state.formatting[i]); if (state.formatting[i] === "header") { styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.header); } // Add `formatting-quote` and `formatting-quote-#` for blockquotes // Add `error` instead if the maximum blockquote nesting depth is passed if (state.formatting[i] === "quote") { if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) { styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.quote); } else { styles.push("error"); } } } } if (state.taskOpen) { styles.push("meta"); return styles.length ? styles.join(' ') : null; } if (state.taskClosed) { styles.push("property"); return styles.length ? styles.join(' ') : null; } if (state.linkHref) { styles.push(tokenTypes.linkHref, "url"); } else { // Only apply inline styles to non-url text if (state.strong) { styles.push(tokenTypes.strong); } if (state.em) { styles.push(tokenTypes.em); } if (state.strikethrough) { styles.push(tokenTypes.strikethrough); } if (state.linkText) { styles.push(tokenTypes.linkText); } if (state.code) { styles.push(tokenTypes.code); } if (state.image) { styles.push(tokenTypes.image); } if (state.imageAltText) { styles.push(tokenTypes.imageAltText, "link"); } if (state.imageMarker) { styles.push(tokenTypes.imageMarker); } } if (state.header) { styles.push(tokenTypes.header, tokenTypes.header + "-" + state.header); } if (state.quote) { styles.push(tokenTypes.quote); // Add `quote-#` where the maximum for `#` is modeCfg.maxBlockquoteDepth if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) { styles.push(tokenTypes.quote + "-" + state.quote); } else { styles.push(tokenTypes.quote + "-" + modeCfg.maxBlockquoteDepth); } } if (state.list !== false) { var listMod = (state.listStack.length - 1) % 3; if (!listMod) { styles.push(tokenTypes.list1); } else if (listMod === 1) { styles.push(tokenTypes.list2); } else { styles.push(tokenTypes.list3); } } if (state.trailingSpaceNewLine) { styles.push("trailing-space-new-line"); } else if (state.trailingSpace) { styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b")); } return styles.length ? styles.join(' ') : null; } function handleText(stream, state) { if (stream.match(textRE, true)) { return getType(state); } return undefined; } function inlineNormal(stream, state) { var style = state.text(stream, state); if (typeof style !== 'undefined') return style; if (state.list) { // List marker (*, +, -, 1., etc) state.list = null; return getType(state); } if (state.taskList) { var taskOpen = stream.match(taskListRE, true)[1] !== "x"; if (taskOpen) state.taskOpen = true; else state.taskClosed = true; if (modeCfg.highlightFormatting) state.formatting = "task"; state.taskList = false; return getType(state); } state.taskOpen = false; state.taskClosed = false; if (state.header && stream.match(/^#+$/, true)) { if (modeCfg.highlightFormatting) state.formatting = "header"; return getType(state); } // Get sol() value now, before character is consumed var sol = stream.sol(); var ch = stream.next(); // Matches link titles present on next line if (state.linkTitle) { state.linkTitle = false; var matchCh = ch; if (ch === '(') { matchCh = ')'; } matchCh = (matchCh+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh; if (stream.match(new RegExp(regex), true)) { return tokenTypes.linkHref; } } // If this block is changed, it may need to be updated in GFM mode if (ch === '`') { var previousFormatting = state.formatting; if (modeCfg.highlightFormatting) state.formatting = "code"; stream.eatWhile('`'); var count = stream.current().length if (state.code == 0) { state.code = count return getType(state) } else if (count == state.code) { // Must be exact var t = getType(state) state.code = 0 return t } else { state.formatting = previousFormatting return getType(state) } } else if (state.code) { return getType(state); } if (ch === '\\') { stream.next(); if (modeCfg.highlightFormatting) { var type = getType(state); var formattingEscape = tokenTypes.formatting + "-escape"; return type ? type + " " + formattingEscape : formattingEscape; } } if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) { state.imageMarker = true; state.image = true; if (modeCfg.highlightFormatting) state.formatting = "image"; return getType(state); } if (ch === '[' && state.imageMarker) { state.imageMarker = false; state.imageAltText = true if (modeCfg.highlightFormatting) state.formatting = "image"; return getType(state); } if (ch === ']' && state.imageAltText) { if (modeCfg.highlightFormatting) state.formatting = "image"; var type = getType(state); state.imageAltText = false; state.image = false; state.inline = state.f = linkHref; return type; } if (ch === '[' && stream.match(/[^\]]*\](\(.*\)| ?\[.*?\])/, false) && !state.image) { state.linkText = true; if (modeCfg.highlightFormatting) state.formatting = "link"; return getType(state); } if (ch === ']' && state.linkText && stream.match(/\(.*?\)| ?\[.*?\]/, false)) { if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); state.linkText = false; state.inline = state.f = linkHref; return type; } if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) { state.f = state.inline = linkInline; if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); if (type){ type += " "; } else { type = ""; } return type + tokenTypes.linkInline; } if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) { state.f = state.inline = linkInline; if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); if (type){ type += " "; } else { type = ""; } return type + tokenTypes.linkEmail; } if (ch === '<' && stream.match(/^(!--|\w)/, false)) { var end = stream.string.indexOf(">", stream.pos); if (end != -1) { var atts = stream.string.substring(stream.start, end); if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) state.md_inside = true; } stream.backUp(1); state.htmlState = CodeMirror.startState(htmlMode); return switchBlock(stream, state, htmlBlock); } if (ch === '<' && stream.match(/^\/\w*?>/)) { state.md_inside = false; return "tag"; } var ignoreUnderscore = false; if (!modeCfg.underscoresBreakWords) { if (ch === '_' && stream.peek() !== '_' && stream.match(/(\w)/, false)) { var prevPos = stream.pos - 2; if (prevPos >= 0) { var prevCh = stream.string.charAt(prevPos); if (prevCh !== '_' && prevCh.match(/(\w)/, false)) { ignoreUnderscore = true; } } } } if (ch === '*' || (ch === '_' && !ignoreUnderscore)) { if (sol && stream.peek() === ' ') { // Do nothing, surrounded by newline and space } else if (state.strong === ch && stream.eat(ch)) { // Remove STRONG if (modeCfg.highlightFormatting) state.formatting = "strong"; var t = getType(state); state.strong = false; return t; } else if (!state.strong && stream.eat(ch)) { // Add STRONG state.strong = ch; if (modeCfg.highlightFormatting) state.formatting = "strong"; return getType(state); } else if (state.em === ch) { // Remove EM if (modeCfg.highlightFormatting) state.formatting = "em"; var t = getType(state); state.em = false; return t; } else if (!state.em) { // Add EM state.em = ch; if (modeCfg.highlightFormatting) state.formatting = "em"; return getType(state); } } else if (ch === ' ') { if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces if (stream.peek() === ' ') { // Surrounded by spaces, ignore return getType(state); } else { // Not surrounded by spaces, back up pointer stream.backUp(1); } } } if (modeCfg.strikethrough) { if (ch === '~' && stream.eatWhile(ch)) { if (state.strikethrough) {// Remove strikethrough if (modeCfg.highlightFormatting) state.formatting = "strikethrough"; var t = getType(state); state.strikethrough = false; return t; } else if (stream.match(/^[^\s]/, false)) {// Add strikethrough state.strikethrough = true; if (modeCfg.highlightFormatting) state.formatting = "strikethrough"; return getType(state); } } else if (ch === ' ') { if (stream.match(/^~~/, true)) { // Probably surrounded by space if (stream.peek() === ' ') { // Surrounded by spaces, ignore return getType(state); } else { // Not surrounded by spaces, back up pointer stream.backUp(2); } } } } if (ch === ' ') { if (stream.match(/ +$/, false)) { state.trailingSpace++; } else if (state.trailingSpace) { state.trailingSpaceNewLine = true; } } return getType(state); } function linkInline(stream, state) { var ch = stream.next(); if (ch === ">") { state.f = state.inline = inlineNormal; if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); if (type){ type += " "; } else { type = ""; } return type + tokenTypes.linkInline; } stream.match(/^[^>]+/, true); return tokenTypes.linkInline; } function linkHref(stream, state) { // Check if space, and return NULL if so (to avoid marking the space) if(stream.eatSpace()){ return null; } var ch = stream.next(); if (ch === '(' || ch === '[') { state.f = state.inline = getLinkHrefInside(ch === "(" ? ")" : "]", 0); if (modeCfg.highlightFormatting) state.formatting = "link-string"; state.linkHref = true; return getType(state); } return 'error'; } var linkRE = { ")": /^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/, "]": /^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\\]]|\\.)*\])*?(?=\])/ } function getLinkHrefInside(endChar) { return function(stream, state) { var ch = stream.next(); if (ch === endChar) { state.f = state.inline = inlineNormal; if (modeCfg.highlightFormatting) state.formatting = "link-string"; var returnState = getType(state); state.linkHref = false; return returnState; } stream.match(linkRE[endChar]) state.linkHref = true; return getType(state); }; } function footnoteLink(stream, state) { if (stream.match(/^([^\]\\]|\\.)*\]:/, false)) { state.f = footnoteLinkInside; stream.next(); // Consume [ if (modeCfg.highlightFormatting) state.formatting = "link"; state.linkText = true; return getType(state); } return switchInline(stream, state, inlineNormal); } function footnoteLinkInside(stream, state) { if (stream.match(/^\]:/, true)) { state.f = state.inline = footnoteUrl; if (modeCfg.highlightFormatting) state.formatting = "link"; var returnType = getType(state); state.linkText = false; return returnType; } stream.match(/^([^\]\\]|\\.)+/, true); return tokenTypes.linkText; } function footnoteUrl(stream, state) { // Check if space, and return NULL if so (to avoid marking the space) if(stream.eatSpace()){ return null; } // Match URL stream.match(/^[^\s]+/, true); // Check for link title if (stream.peek() === undefined) { // End of line, set flag to check next line state.linkTitle = true; } else { // More content on line, check if link title stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true); } state.f = state.inline = inlineNormal; return tokenTypes.linkHref + " url"; } var mode = { startState: function() { return { f: blockNormal, prevLine: null, thisLine: null, block: blockNormal, htmlState: null, indentation: 0, inline: inlineNormal, text: handleText, formatting: false, linkText: false, linkHref: false, linkTitle: false, code: 0, em: false, strong: false, header: 0, hr: false, taskList: false, list: false, listStack: [], quote: 0, trailingSpace: 0, trailingSpaceNewLine: false, strikethrough: false, fencedChars: null }; }, copyState: function(s) { return { f: s.f, prevLine: s.prevLine, thisLine: s.thisLine, block: s.block, htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState), indentation: s.indentation, localMode: s.localMode, localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null, inline: s.inline, text: s.text, formatting: false, linkTitle: s.linkTitle, code: s.code, em: s.em, strong: s.strong, strikethrough: s.strikethrough, header: s.header, hr: s.hr, taskList: s.taskList, list: s.list, listStack: s.listStack.slice(0), quote: s.quote, indentedCode: s.indentedCode, trailingSpace: s.trailingSpace, trailingSpaceNewLine: s.trailingSpaceNewLine, md_inside: s.md_inside, fencedChars: s.fencedChars }; }, token: function(stream, state) { // Reset state.formatting state.formatting = false; if (stream != state.thisLine) { var forceBlankLine = state.header || state.hr; // Reset state.header and state.hr state.header = 0; state.hr = false; if (stream.match(/^\s*$/, true) || forceBlankLine) { blankLine(state); if (!forceBlankLine) return null state.prevLine = null } state.prevLine = state.thisLine state.thisLine = stream // Reset state.taskList state.taskList = false; // Reset state.trailingSpace state.trailingSpace = 0; state.trailingSpaceNewLine = false; state.f = state.block; var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, ' ').length; state.indentationDiff = Math.min(indentation - state.indentation, 4); state.indentation = state.indentation + state.indentationDiff; if (indentation > 0) return null; } return state.f(stream, state); }, innerMode: function(state) { if (state.block == htmlBlock) return {state: state.htmlState, mode: htmlMode}; if (state.localState) return {state: state.localState, mode: state.localMode}; return {state: state, mode: mode}; }, blankLine: blankLine, getType: getType, fold: "markdown" }; return mode; }, "xml"); CodeMirror.defineMIME("text/x-markdown", "markdown"); });
const lams = require('../../../index.js') const mocks = require('../../../lib/mocks.js') const path= require('path') const options = {reporting:"no", cwd:__dirname} require('../../../lib/expect-to-contain-message'); const log = x=>console.log(x) const testProjectName = __dirname.split(path.sep).slice(-1)[0]; describe('Projects', () => { describe(testProjectName, () => { let {spies, process, console} = mocks() let messages beforeAll( async () => { messages = await lams(options,{process, console}) }) it("should not error out", ()=> { expect(console.error).not.toHaveBeenCalled() }); it("it should not contain any unexpected parser (P0) errors", ()=> { expect({messages}).not.toContainMessage({ rule: "P0", level: "error" }); }); it("it should not contain any parser syntax (P1) errors", ()=> { expect({messages}).not.toContainMessage({ rule: "P1", level: "error" }); }); }); });
/** * Created by bobtian on 16/2/3. */ export default class DomMultipleElementsController { constructor() { this.options = { "dom": '<"top"iflp<"clear">>rt<"bottom"iflp<"clear">>' }; } } DomMultipleElementsController.$inject = [];
import Ember from 'ember'; import layout from '../templates/components/ember-form-master-2000/fm-radio-group'; export default Ember.Component.extend({ layout: layout, classNameBindings: ['radioGroupWrapperClass', 'errorClass'], fmConfig: Ember.inject.service('fm-config'), errorClass: Ember.computed('showErrors', 'fmConfig.errorClass', function() { if(this.get('showErrors')) { return this.get('fmConfig.errorClass'); } }), radioGroupWrapperClass: Ember.computed.reads('fmConfig.radioGroupWrapperClass'), labelClass: Ember.computed.reads('fmConfig.labelClass'), shouldShowErrors: false, showErrors: Ember.computed('errors', 'shouldShowErrors', function() { return this.get('shouldShowErrors') && !Ember.isEmpty(this.get('errors')); }), actions: { userInteraction() { this.set('shouldShowErrors', true); } } });
/* * angular-socket-io v0.2.0 * (c) 2013 Brian Ford http://briantford.com * License: MIT */ 'use strict'; module.exports = angular.module('btford.socket-io', []). provider('socket', function () { // when forwarding events, prefix the event name var prefix = 'socket:', ioSocket; // expose to provider this.$get = function ($rootScope, $timeout) { var socket = ioSocket || io.connect('http://localhost:8000'); var asyncAngularify = function (callback) { return function () { var args = arguments; $rootScope.$apply(function () { callback.apply(socket, args); }); }; }; var addListener = function (eventName, callback) { socket.on(eventName, asyncAngularify(callback)); }; var wrappedSocket = { on: function (eventName, callback) { //console.log ( "registering callback for event: ", eventName ); socket.on(eventName, asyncAngularify ( callback )); }, addListener: addListener, emit: function (eventName, data, callback) { if ( !callback && typeof data === 'function' ) { callback = data; data = undefined; } if ( callback ) { socket.emit(eventName, data, asyncAngularify(callback)); } else { socket.emit(eventName, data); } }, removeListener: function ( eventName ) { //console.log ( "de-registering callback for event: ", eventName ); return socket.removeAllListeners.apply ( socket, [ eventName ] ); }, // when socket.on('someEvent', fn (data) { ... }), // call scope.$broadcast('someEvent', data) forward: function (events, scope) { if (events instanceof Array === false) { events = [events]; } if (!scope) { scope = $rootScope; } events.forEach(function (eventName) { var prefixed = prefix + eventName; var forwardEvent = asyncAngularify(function (data) { scope.$broadcast(prefixed, data); }); scope.$on('$destroy', function () { socket.removeListener(eventName, forwardEvent); }); socket.on(eventName, forwardEvent); }); } }; return wrappedSocket; }; this.prefix = function (newPrefix) { prefix = newPrefix; }; this.ioSocket = function (socket) { ioSocket = socket; }; });
/* * This file is part of the Fxp package. * * (c) François Pluchino <francois.pluchino@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Refresh the size list of pager. * * @param {TablePager} self The table pager instance * @param {boolean} [rebuild] Rebuild the pager or not */ export function refreshSizeList(self, rebuild) { let $sizeList = $(self.options.selectors.sizeList, self.$element), sizeList = self.getSizeList(), $opt, i; $sizeList.attr('disabled', 'disabled'); if (rebuild) { $sizeList.empty(); for (i = 0; i < sizeList.length; i += 1) { $opt = $('<option value="' + sizeList[i].value + '">' + sizeList[i].label + '</option>'); if (sizeList[i].value === self.pageSize) { $opt.prop('selected', 'selected'); } $sizeList.append($opt); } } if (sizeList.length > 1) { $sizeList.removeAttr('disabled'); } } /** * Refresh the page number of pager. * * @param {TablePager} self The table pager instance */ export function refreshPageNumber(self) { let $pageNumber = $(self.options.selectors.pageNumber, self.$element), $pageCount = $('span.table-pager-page-count', self.$element); $pageNumber.attr('disabled', 'disabled'); $pageNumber.prop('value', self.getPageNumber()); $pageCount.text(self.getPageCount()); if (self.getPageCount() > 1) { $pageNumber.removeAttr('disabled'); } } /** * Refresh the page buttons. * * @param {TablePager} self The table pager instance */ export function refreshPageButtons(self) { let $start = $(self.options.selectors.startPage, self.$element), $previous = $(self.options.selectors.previousPage, self.$element), $next = $(self.options.selectors.nextPage, self.$element), $end = $(self.options.selectors.endPage, self.$element), $listSort = $(self.options.selectors.listSortBtn, self.$element), $refresh = $(self.options.selectors.refresh, self.$element); $start.attr('disabled', 'disabled'); $previous.attr('disabled', 'disabled'); $next.attr('disabled', 'disabled'); $end.attr('disabled', 'disabled'); $listSort.removeAttr('disabled'); $refresh.removeAttr('disabled'); if (self.pageNumber > 1) { $start.removeAttr('disabled'); $previous.removeAttr('disabled'); } if (self.pageNumber < self.getPageCount()) { $next.removeAttr('disabled'); $end.removeAttr('disabled'); } } /** * Refresh the page elements. * * @param {TablePager} self The table pager instance */ export function refreshPageElements(self) { let $elements = $('div.table-pager-elements', self.$element); $('> span.table-pager-start', $elements).text(self.getStart()); $('> span.table-pager-end', $elements).text(self.getEnd()); $('> span.table-pager-size', $elements).text(self.getSize()); } /** * Refresh the column headers. * * @param {TablePager} self The table pager instance * @param {Array} sortDefinitions The sort column definitions * * @typedef {Array} self.sortOrder The sort order list */ export function refreshColumnHeaders(self, sortDefinitions) { self.sortOrder = []; let $ths = self.$table.find(self.options.selectors.sortable), $items = self.$sortMenu.find(self.options.selectors.listSortable), $th, $item, i; $ths.removeAttr('data-table-sort'); $items.removeAttr('data-table-sort'); for (i = 0; i < sortDefinitions.length; i += 1) { $th = $ths.filter('[data-col-name=' + sortDefinitions[i].name + ']'); $item = $items.filter('[data-col-name=' + sortDefinitions[i].name + ']'); $th.attr('data-table-sort', sortDefinitions[i].sort); $item.attr('data-table-sort', sortDefinitions[i].sort); self.sortOrder.push(sortDefinitions[i].name); } self.$element.attr('data-sort-order', JSON.stringify(self.sortOrder)); } /** * Refresh the column headers. * * @param {TablePager} self The table pager instance */ export function refreshEmptySelector(self) { if (null !== self.options.emptySelector) { if (0 === self.size) { $(self.options.emptySelector).addClass(self.options.emptyClass); } else { $(self.options.emptySelector).removeClass(self.options.emptyClass); } } }
dependenciesLoader(["React", "ReactDOM", "$"], function () { // Debounce resize !function (n, r) { var t = function (n, r, t) { var e;return function () { function i() { t || n.apply(u, a), e = null; }var u = this, a = arguments;e ? clearTimeout(e) : t && n.apply(u, a), e = setTimeout(i, r || 100); }; };jQuery.fn[r] = function (n) { return n ? this.bind("resize", t(n)) : this.trigger(r); }; }(jQuery, "smartresize"); var widthWindow = $(window).width(); $(window).smartresize(function () { widthWindow = $(window).width(); initInterface(); }); // Display content when page is loaded $('#content, .sidenav').animate({ opacity: 1 }, 300); // Size of the BIG Title function initInterface() { $("#docsTitleBlock").height($(window).height()); $("#docsTitleBlock .content").height($(window).height() - 80); $("#docsTitleBlock .content").css('line-height', $(window).height() - 80 + "px"); $('#docsTitleBlock .content span, .material-icons').css("opacity", 1); if (widthWindow > 992) { var topMarginSidenav = $("#docsTitleBlock .content").height() - $(window).scrollTop() + 80; if (topMarginSidenav < 0) { topMarginSidenav = 0; } $(".sidenav").css('top', topMarginSidenav); $("#sidebar .sidenav").css('max-height', $(window).height()); $("#sidebar .sidenav").css('max-width', widthWindow - $('#content').width() - 60); $("#sidebar .sidenav").css('min-width', widthWindow - $('#content').width() - 60); } else { $(".sidenav").css('top', '0'); $("#sidebar .sidenav").css('max-width', 'initial'); $("#sidebar .sidenav").css('min-width', 'initial'); $("#sidebar .sidenav").css('max-height', 'initial'); } }; initInterface(); var navsections = $('.navsection'); $(window).scroll(function () { // Position of the sidenav if (widthWindow > 992) { var topMarginSidenav = $("#docsTitleBlock .content").height() - $(window).scrollTop() + 80; if (topMarginSidenav < 0) { topMarginSidenav = 0; } $(".sidenav").css('top', topMarginSidenav); } else { $(".sidenav").css('top', '0'); } // Color to choose for the sidenav var amountOfMatch = 0; var elements = []; navsections.each(function () { var scrollTop = $(window).scrollTop(), elementOffset = $(this).offset().top, distance = elementOffset - scrollTop; elements.push({ el: $(this), top: $(this).offset().top }); if (distance >= 0 && distance <= 10) { amountOfMatch++; $('.sidenav').css('background-color', $(this).attr("data-background-color")); $('.sidebar .nav > li > a').css('color', $(this).attr("data-color")); $('.sidebar .nav > .active > a').css('color', $(this).attr("data-active-color")); } }); if (!amountOfMatch) { _.each(elements, function (row) { if (row.top > $(window).scrollTop() && !amountOfMatch) { amountOfMatch++; $('.sidenav').css('background-color', row.el.attr("data-background-color")); $('.sidebar .nav > li > a').css('color', row.el.attr("data-color")); $('.sidebar .nav > .active > a').css('color', row.el.attr("data-active-color")); } }); } }); // Replace all of the elements of the docs that match a pattern // Public key $("code").each(function () { if (Synchronise.User.current()) { // user is connected // user has a javascript publuc key if (Synchronise.User.current().public_key) { $(this).html($(this).html().replace('{{public_key}}', Synchronise.User.current().public_key)); } } }); });
import lenientFunction from './lenient.js'; export default function yn(value, { lenient = false, default: default_, } = {}) { if (default_ !== undefined && typeof default_ !== 'boolean') { throw new TypeError(`Expected the \`default\` option to be of type \`boolean\`, got \`${typeof default_}\``); } if (value === undefined || value === null) { return default_; } value = String(value).trim(); if (/^(?:y|yes|true|1|on)$/i.test(value)) { return true; } if (/^(?:n|no|false|0|off)$/i.test(value)) { return false; } if (lenient === true) { return lenientFunction(value, default_); } return default_; }
"use strict"; angular.module("wrektranet.adminTicketCtrl", []) // container for list of tickets .controller('adminTicketListCtrl', [ '$scope', 'Restangular', function($scope, Restangular) { Restangular.setBaseUrl('/admin'); // update contests for any appropriate tickets $scope.$on('updateContests', function(e, contest) { $scope.$broadcast('updateContest', contest); angular.forEach($scope.tickets, function(ticket) { if (ticket.contest.id === contest.id) { ticket.contest = contest; } }); }); $scope.addTicket = function() { var ticket, restangularTicket; ticket = { contest_id: $scope.contest.id, user_id: $scope.user_id }; restangularTicket = Restangular .restangularizeElement(null, ticket, 'staff_tickets'); restangularTicket .post() .then(function(newTicket) { if (newTicket.id !== false) { $scope.tickets.push(newTicket); $scope.user_id = null; $scope.$emit('updateContests', newTicket.contest); } }); }; } ]) // controller for individual ticket rows .controller('adminTicketCtrl', [ '$scope', 'Restangular', function($scope, Restangular) { Restangular.setBaseUrl('/admin'); $scope.isContestFull = function() { var limit, total; limit = $scope.ticket.contest.staff_ticket_limit; total = $scope.ticket.contest.staff_count; return (limit - total === 0); }; $scope.openEdit = function() { var newName = null; newName = prompt("Enter a custom name for this ticket:", $scope.ticket.display_name); if (newName !== null) { $scope.ticket.display_name = newName; $scope.saveName(); } }; $scope.revertName = function() { var restangularTicket = Restangular. restangularizeElement(null, $scope.ticket, 'staff_tickets'); restangularTicket.display_name = null; restangularTicket.put(); }; $scope.saveName = function() { var restangularTicket = Restangular. restangularizeElement(null, $scope.ticket, 'staff_tickets'); restangularTicket.put(); }; $scope.award = function() { var restangularTicket = Restangular. restangularizeElement(null, $scope.ticket, 'staff_tickets'); restangularTicket.awarded = true; restangularTicket .put() .then(function(updatedTicket) { $scope.ticket.awarded = true; $scope.$emit('updateContests', updatedTicket.contest); }); }; $scope.unaward = function() { var restangularTicket = Restangular .restangularizeElement(null, $scope.ticket, 'staff_tickets'); restangularTicket.awarded = false; restangularTicket .put() .then(function(updatedTicket) { $scope.ticket.awarded = false; $scope.$emit('updateContests', updatedTicket.contest); }); }; $scope.remove = function() { var restangularTicket = Restangular .restangularizeElement(null, $scope.ticket, 'staff_tickets'); if (confirm("Are you sure you want to delete this signup?")) { restangularTicket .remove() .then(function() { _.remove($scope.tickets, $scope.ticket); $scope.ticket = null; }); } }; } ]);
var path = require('path'); var minimist = require('./lib/minimist'); var wordwrap = require('./lib/wordwrap'); /* Hack an instance of Argv with process.argv into Argv so people can do require('yargs')(['--beeble=1','-z','zizzle']).argv to parse a list of args and require('yargs').argv to get a parsed version of process.argv. */ var inst = Argv(process.argv.slice(2)); Object.keys(inst).forEach(function (key) { Argv[key] = typeof inst[key] == 'function' ? inst[key].bind(inst) : inst[key]; }); var exports = module.exports = Argv; function Argv (processArgs, cwd) { var self = {}; if (!cwd) cwd = process.cwd(); self.$0 = process.argv .slice(0,2) .map(function (x) { var b = rebase(cwd, x); return x.match(/^\//) && b.length < x.length ? b : x }) .join(' ') ; if (process.env._ != undefined && process.argv[1] == process.env._) { self.$0 = process.env._.replace( path.dirname(process.execPath) + '/', '' ); } var options; self.resetOptions = function () { options = { boolean: [], string: [], alias: {}, default: [], requiresArg: [], count: [], normalize: [], config: [] }; return self; }; self.resetOptions(); self.boolean = function (bools) { options.boolean.push.apply(options.boolean, [].concat(bools)); return self; }; self.normalize = function (strings) { options.normalize.push.apply(options.normalize, [].concat(strings)); return self; }; self.config = function (configs) { options.config.push.apply(options.config, [].concat(configs)); return self; }; var examples = []; self.example = function (cmd, description) { examples.push([cmd, description]); return self; }; self.string = function (strings) { options.string.push.apply(options.string, [].concat(strings)); return self; }; self.default = function (key, value) { if (typeof key === 'object') { Object.keys(key).forEach(function (k) { self.default(k, key[k]); }); } else { options.default[key] = value; } return self; }; self.alias = function (x, y) { if (typeof x === 'object') { Object.keys(x).forEach(function (key) { self.alias(key, x[key]); }); } else { options.alias[x] = (options.alias[x] || []).concat(y); } return self; }; self.count = function(counts) { options.count.push.apply(options.count, [].concat(counts)); return self; }; var demanded = {}; self.demand = function (keys, msg) { if (typeof keys == 'number') { if (!demanded._) demanded._ = { count: 0, msg: null }; demanded._.count += keys; demanded._.msg = msg; } else if (Array.isArray(keys)) { keys.forEach(function (key) { self.demand(key, msg); }); } else { demanded[keys] = { msg: msg }; } return self; }; self.requiresArg = function (requiresArgs) { options.requiresArg.push.apply(options.requiresArg, [].concat(requiresArgs)); return self; }; var implied = {}; self.implies = function (key, value) { if (typeof key === 'object') { Object.keys(key).forEach(function (k) { self.implies(k, key[k]); }); } else { implied[key] = value; } return self; }; var usage; self.usage = function (msg, opts) { if (!opts && typeof msg === 'object') { opts = msg; msg = null; } usage = msg; if (opts) self.options(opts); return self; }; var fails = []; self.fail = function (f) { fails.push(f); return self; }; function fail (msg) { if (fails.length) { fails.forEach(function (f) { f(msg); }); } else { if (showHelpOnFail) { self.showHelp(); } if (msg) console.error(msg); if (failMessage) { if (msg) { console.error(""); } console.error(failMessage); } process.exit(1); } } var checks = []; self.check = function (f) { checks.push(f); return self; }; self.defaults = self.default; var descriptions = {}; self.describe = function (key, desc) { if (typeof key === 'object') { Object.keys(key).forEach(function (k) { self.describe(k, key[k]); }); } else { descriptions[key] = desc; } return self; }; self.parse = function (args) { return parseArgs(args); }; self.option = self.options = function (key, opt) { if (typeof key === 'object') { Object.keys(key).forEach(function (k) { self.options(k, key[k]); }); } else { if (opt.alias) self.alias(key, opt.alias); if (opt.demand) self.demand(key, opt.demand); if (typeof opt.default !== 'undefined') { self.default(key, opt.default); } if (opt.boolean || opt.type === 'boolean') { self.boolean(key); if (opt.alias) self.boolean(opt.alias); } if (opt.string || opt.type === 'string') { self.string(key); if (opt.alias) self.string(opt.alias); } if (opt.count || opt.type === 'count') { self.count(key); } var desc = opt.describe || opt.description || opt.desc; if (desc) { self.describe(key, desc); } if (opt.requiresArg) { self.requiresArg(key); } } return self; }; var wrap = null; self.wrap = function (cols) { wrap = cols; return self; }; var strict = false; self.strict = function () { strict = true; return self; }; self.showHelp = function (fn) { if (!fn) fn = console.error.bind(console); fn(self.help()); return self; }; var version = null; var versionOpt = null; self.version = function (ver, opt, msg) { version = ver; versionOpt = opt; self.describe(opt, msg || 'Show version number'); return self; }; var helpOpt = null; self.addHelpOpt = function (opt, msg) { helpOpt = opt; self.describe(opt, msg || 'Show help'); return self; }; var failMessage = null; var showHelpOnFail = true; self.showHelpOnFail = function (enabled, message) { if (typeof enabled === 'string') { enabled = true; message = enabled; } else if (typeof enabled === 'undefined') { enabled = true; } failMessage = message; showHelpOnFail = enabled; return self; }; self.help = function () { if (arguments.length > 0) { return self.addHelpOpt.apply(self, arguments); } var keys = Object.keys( Object.keys(descriptions) .concat(Object.keys(demanded)) .concat(Object.keys(options.default)) .reduce(function (acc, key) { if (key !== '_') acc[key] = true; return acc; }, {}) ); var help = keys.length ? [ 'Options:' ] : []; if (examples.length) { help.unshift(''); examples.forEach(function (example) { example[0] = example[0].replace(/\$0/g, self.$0); }); var commandlen = longest(examples.map(function (a) { return a[0]; })); var exampleLines = examples.map(function(example) { var command = example[0]; var description = example[1]; command += Array(commandlen + 5 - command.length).join(' '); return ' ' + command + description; }); exampleLines.push(''); help = exampleLines.concat(help); help.unshift('Examples:'); } if (usage) { help.unshift(usage.replace(/\$0/g, self.$0), ''); } keys = keys.filter(function(key) { return Object.keys(options.alias).every(function(alias) { return -1 == options.alias[alias].indexOf(key); }); }); var switches = keys.reduce(function (acc, key) { acc[key] = [ key ].concat(options.alias[key] || []) .map(function (sw) { return (sw.length > 1 ? '--' : '-') + sw }) .join(', ') ; return acc; }, {}); var switchlen = longest(Object.keys(switches).map(function (s) { return switches[s] || ''; })); var desclen = longest(Object.keys(descriptions).map(function (d) { return descriptions[d] || ''; })); keys.forEach(function (key) { var kswitch = switches[key]; var desc = descriptions[key] || ''; if (wrap) { desc = wordwrap(switchlen + 4, wrap)(desc) .slice(switchlen + 4) ; } var spadding = new Array( Math.max(switchlen - kswitch.length + 3, 0) ).join(' '); var dpadding = new Array( Math.max(desclen - desc.length + 1, 0) ).join(' '); var type = null; if (options.boolean[key]) type = '[boolean]'; if (options.count[key]) type = '[count]'; if (options.string[key]) type = '[string]'; if (options.normalize[key]) type = '[string]'; if (!wrap && dpadding.length > 0) { desc += dpadding; } var prelude = ' ' + kswitch + spadding; var extra = [ type, demanded[key] ? '[required]' : null , options.default[key] !== undefined ? '[default: ' + (typeof options.default[key] === 'string' ? JSON.stringify : String)(options.default[key]) + ']' : null ].filter(Boolean).join(' '); var body = [ desc, extra ].filter(Boolean).join(' '); if (wrap) { var dlines = desc.split('\n'); var dlen = dlines.slice(-1)[0].length + (dlines.length === 1 ? prelude.length : 0) body = desc + (dlen + extra.length > wrap - 2 ? '\n' + new Array(wrap - extra.length + 1).join(' ') + extra : new Array(wrap - extra.length - dlen + 1).join(' ') + extra ); } help.push(prelude + body); }); if (keys.length) help.push(''); return help.join('\n'); }; Object.defineProperty(self, 'argv', { get : function () { return parseArgs(processArgs) }, enumerable : true }); function parseArgs (args) { var parsed = minimist(args, options), argv = parsed.argv, aliases = parsed.aliases; argv.$0 = self.$0; Object.keys(argv).forEach(function(key) { if (key === helpOpt) { self.showHelp(console.log); process.exit(0); } else if (key === versionOpt) { console.log(version); process.exit(0); } }); if (demanded._ && argv._.length < demanded._.count) { if (demanded._.msg) { fail(demanded._.msg); } else { fail('Not enough non-option arguments: got ' + argv._.length + ', need at least ' + demanded._.count ); } } if (options.requiresArg.length > 0) { var missingRequiredArgs = []; options.requiresArg.forEach(function(key) { var value = argv[key]; // minimist sets --foo value to true / --no-foo to false if (value === true || value === false) { missingRequiredArgs.push(key); } }); if (missingRequiredArgs.length == 1) { fail("Missing argument value: " + missingRequiredArgs[0]); } else if (missingRequiredArgs.length > 1) { message = "Missing argument values: " + missingRequiredArgs.join(", "); fail(message); } } var missing = null; Object.keys(demanded).forEach(function (key) { if (!argv.hasOwnProperty(key)) { missing = missing || {}; missing[key] = demanded[key]; } }); if (missing) { var customMsgs = []; Object.keys(missing).forEach(function(key) { var msg = missing[key].msg; if (msg && customMsgs.indexOf(msg) < 0) { customMsgs.push(msg); } }); var customMsg = customMsgs.length ? '\n' + customMsgs.join('\n') : ''; fail('Missing required arguments: ' + Object.keys(missing).join(', ') + customMsg); } if (strict) { var unknown = []; var aliases = {}; Object.keys(parsed.aliases).forEach(function (key) { parsed.aliases[key].forEach(function (alias) { aliases[alias] = key; }); }); Object.keys(argv).forEach(function (key) { if (key !== "$0" && key !== "_" && !descriptions.hasOwnProperty(key) && !demanded.hasOwnProperty(key) && !aliases.hasOwnProperty(key)) { unknown.push(key); } }); if (unknown.length == 1) { fail("Unknown argument: " + unknown[0]); } else if (unknown.length > 1) { fail("Unknown arguments: " + unknown.join(", ")); } } checks.forEach(function (f) { try { var result = f(argv, aliases); if (result === false) { fail('Argument check failed: ' + f.toString()); } else if (typeof result === 'string') { fail(result); } } catch (err) { fail(err) } }); var implyFail = []; Object.keys(implied).forEach(function (key) { var num, origKey = key, value = implied[key]; // convert string '1' to number 1 var num = Number(key); key = isNaN(num) ? key : num; if (typeof key === 'number') { // check length of argv._ key = argv._.length >= key; } else if (key.match(/^--no-.+/)) { // check if key doesn't exist key = key.match(/^--no-(.+)/)[1]; key = !argv[key]; } else { // check if key exists key = argv[key]; } num = Number(value); value = isNaN(num) ? value : num; if (typeof value === 'number') { value = argv._.length >= value; } else if (value.match(/^--no-.+/)) { value = value.match(/^--no-(.+)/)[1]; value = !argv[value]; } else { value = argv[value]; } if (key && !value) { implyFail.push(origKey); } }); if (implyFail.length) { var msg = 'Implications failed:\n'; implyFail.forEach(function (key) { msg += (' ' + key + ' -> ' + implied[key] + '\n'); }); fail(msg); } return argv; } function longest (xs) { return Math.max.apply( null, xs.map(function (x) { return x.length }) ); } return self; }; // rebase an absolute path to a relative one with respect to a base directory // exported for tests exports.rebase = rebase; function rebase (base, dir) { var ds = path.normalize(dir).split('/').slice(1); var bs = path.normalize(base).split('/').slice(1); for (var i = 0; ds[i] && ds[i] == bs[i]; i++); ds.splice(0, i); bs.splice(0, i); var p = path.normalize( bs.map(function () { return '..' }).concat(ds).join('/') ).replace(/\/$/,'').replace(/^$/, '.'); return p.match(/^[.\/]/) ? p : './' + p; };
var preloader = {}; preloader.preload = function () { this.game.load.image('logo', 'images/phaser.png'); }; preloader.create = function () { this.game.state.start('game'); }; module.exports = preloader;
import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import SwipeableViews from 'react-swipeable-views'; import { makeStyles, useTheme } from '@material-ui/core/styles'; import AppBar from '@material-ui/core/AppBar'; import Tabs from '@material-ui/core/Tabs'; import Tab from '@material-ui/core/Tab'; import Typography from '@material-ui/core/Typography'; import Zoom from '@material-ui/core/Zoom'; import Fab from '@material-ui/core/Fab'; import AddIcon from '@material-ui/icons/Add'; import EditIcon from '@material-ui/icons/Edit'; import UpIcon from '@material-ui/icons/KeyboardArrowUp'; import green from '@material-ui/core/colors/green'; function TabContainer(props) { const { children, dir } = props; return ( <Typography component="div" dir={dir} style={{ padding: 8 * 3 }}> {children} </Typography> ); } TabContainer.propTypes = { children: PropTypes.node.isRequired, dir: PropTypes.string.isRequired, }; const useStyles = makeStyles(theme => ({ root: { backgroundColor: theme.palette.background.paper, width: 500, position: 'relative', minHeight: 200, }, fab: { position: 'absolute', bottom: theme.spacing(2), right: theme.spacing(2), }, fabGreen: { color: theme.palette.common.white, backgroundColor: green[500], '&:hover': { backgroundColor: green[600], }, }, })); function FloatingActionButtonZoom() { const classes = useStyles(); const theme = useTheme(); const [value, setValue] = React.useState(0); function handleChange(event, newValue) { setValue(newValue); } function handleChangeIndex(index) { setValue(index); } const transitionDuration = { enter: theme.transitions.duration.enteringScreen, exit: theme.transitions.duration.leavingScreen, }; const fabs = [ { color: 'primary', className: classes.fab, icon: <AddIcon />, label: 'Add', }, { color: 'secondary', className: classes.fab, icon: <EditIcon />, label: 'Edit', }, { color: 'inherit', className: clsx(classes.fab, classes.fabGreen), icon: <UpIcon />, label: 'Expand', }, ]; return ( <div className={classes.root}> <AppBar position="static" color="default"> <Tabs value={value} onChange={handleChange} indicatorColor="primary" textColor="primary" variant="fullWidth" > <Tab label="Item One" /> <Tab label="Item Two" /> <Tab label="Item Three" /> </Tabs> </AppBar> <SwipeableViews axis={theme.direction === 'rtl' ? 'x-reverse' : 'x'} index={value} onChangeIndex={handleChangeIndex} > <TabContainer dir={theme.direction}>Item One</TabContainer> <TabContainer dir={theme.direction}>Item Two</TabContainer> <TabContainer dir={theme.direction}>Item Three</TabContainer> </SwipeableViews> {fabs.map((fab, index) => ( <Zoom key={fab.color} in={value === index} timeout={transitionDuration} style={{ transitionDelay: `${value === index ? transitionDuration.exit : 0}ms`, }} unmountOnExit > <Fab aria-label={fab.label} className={fab.className} color={fab.color}> {fab.icon} </Fab> </Zoom> ))} </div> ); } export default FloatingActionButtonZoom;
/*! jQuery Markup - v0.1.0 - 2013-03-11 * Copyright (c) 2013 pstulzer; Licensed MIT */ ;(function($, window, document, undefined) { if (!$.ps) { $.ps = {}; } $.ps.snippets = function(el, options) { var defaults = { showdocu : true, showcode : true, codeview : true, snippets : {}, callback : function() {} }; var plugin = this; plugin.settings = {}; plugin.markup = {}; var init = function() { console.log('init'); plugin.settings = $.extend({}, defaults, options); plugin.counter = 0; plugin.el = el; plugin.markup.render = plugin.settings.snippets; $.each(plugin.markup, recursiveLookup); }; // escape some tags to entities plugin.htmlEscape = function(s) { s=s.replace(/&/g,'&amp;'); s=s.replace(/>/g,'&gt;'); s=s.replace(/</g,'&lt;'); s=s.replace(/\"/g,'&quot;'); return s; }; plugin.removeSnippet = function() { $('[role="snippet"]').each(function() { $(this).remove(); }); }; // private functions var renderHTML = function(type, content) { var json = ''; var html = '<p>' + type.toUpperCase() + '</p>'; if (typeof content.json === 'string') { json = JSON.parse(content.json); } if (typeof content.html === 'string') { html = content.html; } if (typeof content.includes === 'object') { var options = { includes : content.includes }; return Mark.up(html, json, options); } else { return Mark.up(html, json); } }; var recursiveMarkup = function(key,val) { if ( val instanceof Object) { var element = $.each(val, recursiveMarkup); if (key === 'includes') { $.each(element, function(type, content) { if (typeof content.tmpl === 'string') { val[type] = content.tmpl; } else { val[type] = renderHTML(type, content); } }); } } else { return val; } }; var collectData = function() { plugin.counter--; if (plugin.counter === 0) { $.each(plugin.markup, recursiveMarkup); var rederedHtml = renderHTML('render', plugin.markup.render); $(plugin.el).html(rederedHtml); if (plugin.settings.showdocu === true && typeof $(plugin.markup.render.docu).html() === 'string') { $('body').append($(plugin.markup.render.docu)); } if (plugin.settings.showcode === true) { $('body').append('<div class="newcode" id="codeView" role="snippet"><pre class="syntax xml"></pre></div>'); $('#codeView pre').text(rederedHtml).html(); $.syntax(); } plugin.settings.callback(); } }; var loadUrl = function(el, type, url) { $.ajax({ url : url }) .done(function(data) { switch (type) { case 'docu': var converter = new Markdown.Converter(); data = $('<div/>', { 'id' : 'snippet_doku', 'role' : 'snippet', 'class' : 'clearfix' }).html(converter.makeHtml(data)); break; } el[type] = data; collectData(); }) .fail(function(err) { console.log("error", err); }) .always(function() { // console.log("complete"); }); }; var recursiveLookup = function(key, val) { if ( val instanceof Object) { var element = $.each(val, recursiveLookup); if ( typeof element.tmpl === 'string') { if (element.tmpl.length > 0) { // console.log('last html', key, element.tmpl); plugin.counter++; loadUrl(element, 'tmpl', element.tmpl); } } if ( typeof element.html === 'string') { if (element.html.length > 0) { // console.log('last html', key, element.html); plugin.counter++; loadUrl(element, 'html', element.html); } } if ( typeof element.json === 'string') { if (element.json.length > 0) { // console.log('last json', key, element.json); plugin.counter++; loadUrl(element, 'json', element.json); } } if ( typeof element.docu === 'string' && plugin.settings.showdocu === true) { if (element.docu.length > 0) { // console.log('last docu', key, element.docu); plugin.counter++; loadUrl(element, 'docu', element.docu); } } } else { return val; } }; init(); }; })(jQuery, window, document);
import gulp from 'gulp'; import gulpif from 'gulp-if'; import plumber from 'gulp-plumber'; import jade from 'gulp-jade'; import inheritance from 'gulp-jade-inheritance'; import cached from 'gulp-cached'; import filter from 'gulp-filter'; import rename from 'gulp-rename'; import prettify from 'gulp-html-prettify'; import inline from 'gulp-inline'; import errorHandler from '../utils/errorHandler'; import settings from '../settings'; let data = { jv0: 'javascript:void(0);', timestamp: +new Date() }; gulp.task('markup', () => { return gulp .src([settings.baseSrc + '/**/*.jade', '!' + settings.baseSrc + '/bower_components/**/*.jade']) .pipe(plumber({errorHandler: errorHandler})) .pipe(cached('jade')) .pipe(gulpif(global.watch, inheritance({basedir: settings.baseSrc}))) .pipe(filter((file) => /src[\\\/]pages/.test(file.path))) .pipe(jade({data: data})) .pipe(prettify({ brace_style: 'expand', indent_size: 1, indent_char: '\t', indent_inner_html: true, preserve_newlines: true })) .pipe(rename({dirname: '.'})) .pipe(inline({ base: 'static/', disabledTypes: ['css', 'img', 'js'], ignore: settings.ignoreInline })) .pipe(gulp.dest(settings.baseDist)); });
/* * @Date : 04-02-2014 * Params Get From /components/user/Main.js * Author : Accel FrontLine@Cochin */ var AppDispatcher = require('../dispatcher/AppDispatcher'); var ProjectConstants = require('../constants/ProjectConstants'); var ProjectActions = { //Create New Client Action create : function(ProjectDetails){ AppDispatcher.handleViewAction({ actionType : ProjectConstants.PROJECT_CREATE, ProjectDetails : ProjectDetails }); }, //List entire Client details projectList : function(){ AppDispatcher.handleViewAction({ actionType : ProjectConstants.PROJECT_LIST, }); },//Delete User projectDelete : function(ProjectDetails){ AppDispatcher.handleViewAction({ actionType : ProjectConstants.PROJECT_DELETE, ProjectDetails:ProjectDetails }); }, update : function(ProjectDetails){ AppDispatcher.handleViewAction({ actionType : ProjectConstants.PROJECT_EDIT, ProjectDetails : ProjectDetails }); } }; module.exports = ProjectActions;
(function() { var HollaBack, assert, vows; vows = require('vows'); assert = require('assert'); HollaBack = require('../holla_back.js'); vows.describe('EventEmitter').addBatch({ 'Binding events': { topic: new HollaBack, "throws an exception if the event handler is missing": function(obj) { var erroneousBinding; erroneousBinding = function() { return obj.bind('change'); }; return assert.throws(erroneousBinding, "BindMissingEventHandler"); }, "throws an exception if event name contains a dot (.)": function(obj) { var erroneousBinding; erroneousBinding = function() { return obj.bind('.event', function() { return 1; }); }; return assert.throws(erroneousBinding, "EventNameUnacceptable"); }, "throws an exception if event name begins with a number": function(obj) { var erroneousBinding; erroneousBinding = function() { return obj.bind('123change', function() { return 1; }); }; return assert.throws(erroneousBinding, "EventNameUnacceptable"); } }, 'Simple triggers': { topic: new HollaBack, "can be triggered": function(obj) { var invocations; invocations = []; obj.bind('change', function() { return invocations.push("trigger"); }); obj.trigger('change'); return assert.equal(invocations.length, 1); }, "does nothing if an event is triggered with no event listeners": function(obj) { return assert.equal(obj.trigger('does-not-exists'), null); } }, 'Simple unbinding': { topic: new HollaBack, "a single event": function(obj) { var handler, invocations; invocations = []; handler = function() { return invocations.push('trigger'); }; obj.bind('change', handler); obj.unbind('change'); obj.trigger('change'); return assert.equal(invocations.length, 0); }, "a namespace": function(obj) { var handler, invocations; invocations = []; handler = function() { return invocations.push('trigger'); }; obj.bind('change.client', handler); obj.bind('explode.client', handler); obj.unbind('.client', handler); obj.trigger('change'); obj.trigger('explode'); return assert.equal(invocations.length, 0); }, "a handler of an event": function(obj) { var handler, invocations; invocations = []; handler = function() { return invocations.push('trigger'); }; obj.bind('change', handler); obj.bind('change', function() { return invocations.push('awesome'); }); obj.unbind('change', handler); obj.trigger('change'); return assert.notEqual(invocations.indexOf('awesome'), -1); }, "a handler of a namespace": function(obj) { var handler, invocations; invocations = []; handler = function() { return invocations.push('trigger'); }; obj.bind('change.world.hello', handler); obj.bind('change.world', handler); obj.bind('change.world', function() { return invocations.push('awesome'); }); obj.unbind('.world', handler); obj.trigger('change'); return assert.notEqual(invocations.indexOf('awesome'), -1); } }, 'Multi Namespaced Unbinding': { topic: new HollaBack, "unbinds an event if it matches a namespace": function(obj) { var handler, invocations; invocations = []; handler = function() { return invocations.push('trigger'); }; obj.bind('change.the.world', handler); obj.unbind('.the', handler); obj.trigger('change'); return assert.equal(invocations.length, 0); } }, 'Simple Namespacing': { topic: new HollaBack, "can be namespaced": function(obj) { var invocations; invocations = []; obj.bind('change.server', function() { return invocations.push("trigger"); }); obj.trigger('change.server'); return assert.equal(invocations.length, 1); }, "triggers only namespaced events and generically bound events if a namespaced event is triggered": function(obj) { var handler, invocations; invocations = []; handler = function() { return invocations.push('trigger'); }; obj.bind('change.server', handler); obj.bind('change', handler); obj.trigger('change.server'); return assert.equal(invocations.length, 2); }, "triggers all events with the same event name regardless of namespace if namespace is not specified": function(obj) { var handler, invocations; invocations = []; handler = function() { return invocations.push('trigger'); }; obj.bind('change.server', handler); obj.bind('change.client', handler); obj.bind('change', handler); obj.trigger('change'); return assert.equal(invocations.length, 3); } }, 'Multi Namespaced Trigger': { topic: new HollaBack, "does not have hierarchy": function(obj) { var handler, invocations; invocations = []; handler = function() { return invocations.push('trigger'); }; obj.bind('change.server.client', handler); obj.bind('change.client.server', handler); obj.trigger('change.server.client'); return assert.equal(invocations.length, 2); }, "must match all trigger namespaces in order to be triggered": function(obj) { var invocations; invocations = []; obj.bind('change.server.random', function() { return invocations.push('trigger_a'); }); obj.bind('change.server.client', function() { return invocations.push('trigger_b'); }); obj.bind('change.client.server', function() { return invocations.push('trigger_c'); }); obj.bind('change.client', function() { return invocations.push('trigger_d'); }); obj.trigger('change.client.server'); assert.equal(invocations.indexOf('trigger_a'), -1); assert.notEqual(invocations.indexOf('trigger_b'), -1); assert.notEqual(invocations.indexOf('trigger_c'), -1); return assert.notEqual(invocations.indexOf('trigger_d'), -1); } } })["export"](module); }).call(this);
// @flow import React, { Component } from 'react'; import { Link } from 'react-router'; export default class App extends Component { props: { children: HTMLElement }; render() { return ( <div> <nav className="navbar navbar-light navbar-fixed-top bg-white"> <a className="navbar-brand">Crew Keeper</a> <ul className="nav navbar-nav"> <li className="nav-item"> <Link className="nav-link" title="Home" to="home" > {'Home'} </Link> </li> <li className="nav-item"> <Link className="nav-link" title="Crews" to="crews" > {'Crews'} </Link> </li> </ul> </nav> {this.props.children} </div> ); } }
require('./setup') var fount = require('../src/index.js') describe('Resolving', function () { before(function () { fount.setModule(module) }) describe('with dependencies', function () { before(function () { fount.register('an value!', 'ohhai') }) it('should resolve correctly', function () { return fount.resolve('an value!') .should.eventually.equal('ohhai') }) }) describe('when resolving sinon.stub', function () { var stub = sinon.stub() var result before(function () { fount.register('aStub', stub) return fount.inject(function (aStub) { result = aStub }) }) it('should resolve the stub as a function', function () { result.should.eql(stub) }) }) describe('when resolving a function with unresolvable dependencies', function () { var fn = function (x, y, z) { return x + y + z } var result before(function () { fount.register('unresolvable', fn) return fount.inject(function (unresolvable) { result = unresolvable(1, 2, 3) }) }) it('should resolve the stub as a function', function () { result.should.eql(6) }) }) describe('when resolving functions', function () { describe('without dependencies', function () { describe('when registered normally', function () { before(function () { fount.register('simpleFn', function () { return 'hello, world!' }) }) it('should resolve the function\'s result', function () { this.timeout(100) fount.resolve('simpleFn') .should.eventually.equal('hello, world!') }) }) describe('when registered as a value', function () { before(function () { fount.registerAsValue('simpleFn2', function () { return 'hello, world!' }) }) it('should resolve to the function', function () { this.timeout(100) fount.resolve('simpleFn2') .then(function (fn) { return fn() }) .should.eventually.equal('hello, world!') }) }) }) describe('with dependency on a list', function () { before(function () { fount.register('simpleList', [ 1, 2, 3 ]) }) it('should resolve to the list', function () { return fount.resolve('simpleList') .should.eventually.eql([ 1, 2, 3 ]) }) }) var a = { one: 1 } describe('with static lifecycle', function () { before(function () { fount.register('a', function () { return a }) fount.register('b', 2) fount.register('c', new Promise(resolve => resolve(3))) fount.register('line', [ 'a', 'b', 'c' ], function (a, b, c) { return 'easy as ' + a.one + ', ' + b + ', ' + c + '!' }) }) it('should resolve function\'s dependencies', function () { return fount.resolve('line') .should.eventually.equal('easy as 1, 2, 3!') }) }) describe('with initially unmet dependencies', function () { var calls = 0 function delayed (a2, b2, c2 = 1) { calls++ return a2 + b2 + c2 } before(function () { fount.register('delayed', delayed) }) it('should resolve to the function if called before dependencies are registered', function () { return fount.resolve('delayed') .should.eventually.eql(delayed) }) describe('after dependencies are registered', function () { before(function () { fount.register('a2', 1) fount.register('b2', 10) fount.register('c2', 100) }) it('should resolve to function result', function () { return fount.resolve('delayed') .should.eventually.eql(111) }) it('should not call function after initial resolution', function () { return fount.resolve('delayed') .then(function () { return calls }) .should.eventually.eql(1) }) }) }) describe('when modifying static dependency', function () { before(function () { a.one = 'DURP' }) it('should resolve to original value', function () { return fount.resolve('line') .should.eventually.equal('easy as 1, 2, 3!') }) }) describe('with multiple calls to a scopes', function () { var obj = { x: 1 } before(function () { fount.register('o', function () { return obj }, 'scoped') fount.register('getX', function (o) { return o.x }, 'scoped') return fount.resolve('getX', 'testScope') }) it('should resolve correctly', function () { return fount.resolve('getX', 'testScope') .should.eventually.equal(1) }) }) describe('with multiple scopes', function () { var obj = { x: 1 } describe('in scope default', function () { before(function () { fount.register('o', function () { return obj }, 'scoped') fount.register('getX', [ 'o' ], function (o) { return o.x }, 'scoped') }) it('should resolve correctly', function () { return fount.resolve([ 'o', 'getX' ]) .should.eventually.eql({ 'o': { x: 1 }, 'getX': 1 }) }) }) describe('in scope custom', function () { before(function () { obj.x = 10 }) it('should resolve indepedent results', function () { return fount.resolve([ 'o', 'getX' ], 'custom') .should.eventually.eql({ 'o': { x: 10 }, 'getX': 10 }) }) }) describe('back to default', function () { it('should resolve original scoped results', function () { return fount.resolve([ 'o', 'getX' ]) .should.eventually.eql({ 'o': { x: 1 }, 'getX': 1 }) }) }) }) describe('with factory lifecycle', function () { var obj = { x: 1 } describe('in scope default', function () { before(function () { fount.register('o2', function () { return obj }, 'factory') fount.register('getX2', [ 'o2' ], function (o) { return o.x }, 'factory') }) it('should resolve correctly', function () { return fount.resolve([ 'o2', 'getX2' ]) .should.eventually.eql({ 'o2': { x: 1 }, 'getX2': 1 }) }) }) describe('after changing property', function () { it('should resolve to new result showing change', function () { obj.x = 10 return fount.resolve([ 'o2', 'getX2' ]) .should.eventually.eql({ 'o2': { x: 10 }, 'getX2': 10 }) }) }) }) describe('when checking to see if key can be resolved', function () { describe('with existing and missing dependencies', function () { before(function () { fount.register('met', 'true') fount.register('one.a', 1) fount('two').register('b', 2) }) it('should correctly resolve a check across multiple containers', function () { fount.canResolve([ 'one.a', 'two.b' ]).should.equal(true) }) it('should resolve existing dependency', function () { fount.canResolve('met').should.equal(true) }) it('should not resolve missing dependency', function () { fount.canResolve('unmet').should.equal(false) }) it('should not resolve missing dependency in non-default container from npm', function () { fount.canResolve('special.when').should.equal(false) }) }) }) describe('when resolving missing keys', function () { it('should throw meaningful error message', function () { should.throw(function () { fount.resolve([ 'lol', 'rofl' ]) }, 'Fount could not resolve the following dependencies: lol, rofl') }) }) }) describe('when resolving across multiple containers', function () { before(function () { fount.register('three.a', 3) fount('three').register('b', 4) fount('three').register('c', 4.5) fount.register('four.c', 5) }) it('should resolve correct values', function () { fount.resolve([ 'three.a', 'three.b', 'four.c' ], function (results) { return results }).should.eventually.eql({ 'three.a': 3, 'three.b': 4, 'four.c': 5 }) }) }) describe('when registering and resolving 10k of keys', function () { it('should register 10k keys in the same container in 50 ms', function () { let container = fount('new.sync') let time = Date.now() for (let i = 1; i < 10000; i++) { container.register(`${i}`, Promise.resolve(i)) } let elapsed = Date.now() - time elapsed.should.be.lessThan(50) }) it('should resolve 10k keys from the same container in 150 ms', function () { let container = fount('new.sync') let time = Date.now() let promises = [] for (var i = 1; i < 10000; i++) { promises.push(container.resolve(`${i}`)) } return Promise.all(promises).then(() => { let elapsed = Date.now() - time elapsed.should.be.lessThan(150) }) }) }) after(function () { fount.purgeAll() }) })
/** * Hilo 1.0.0 for amd * Copyright 2016 alibaba.com * Licensed under the MIT License */ define("hilo/view/Bitmap",["hilo/core/Hilo","hilo/core/Class","hilo/view/View","hilo/view/Drawable"],function(i,t,e,h){var s=t.create({Extends:e,constructor:function(t){if(t=t||{},this.id=this.id||t.id||i.getUid("Bitmap"),s.superclass.constructor.call(this,t),this.drawable=new h(t),!this.width||!this.height){var e=this.drawable.rect;e&&(this.width=e[2],this.height=e[3])}},setImage:function(i,t){return this.drawable.init({image:i,rect:t}),t&&(this.width=t[2],this.height=t[3]),this}});return s});
//used for the media picker dialog angular.module("umbraco") .controller("Umbraco.Editors.MediaPickerController", function ($scope, $timeout, mediaResource, entityResource, userService, mediaHelper, mediaTypeHelper, eventsService, treeService, localStorageService, localizationService, editorService, umbSessionStorage, notificationsService, clipboardService) { var vm = this; vm.submit = submit; vm.close = close; vm.toggle = toggle; vm.upload = upload; vm.dragLeave = dragLeave; vm.dragEnter = dragEnter; vm.onUploadComplete = onUploadComplete; vm.onFilesQueue = onFilesQueue; vm.changeSearch = changeSearch; vm.submitFolder = submitFolder; vm.enterSubmitFolder = enterSubmitFolder; vm.focalPointChanged = focalPointChanged; vm.changePagination = changePagination; vm.onNavigationChanged = onNavigationChanged; vm.clickClearClipboard = clickClearClipboard; vm.clickHandler = clickHandler; vm.clickItemName = clickItemName; vm.gotoFolder = gotoFolder; vm.toggleListView = toggleListView; vm.selectLayout = selectLayout; vm.showMediaList = false; vm.navigation = []; var dialogOptions = $scope.model; vm.clipboardItems = dialogOptions.clipboardItems; $scope.disableFolderSelect = (dialogOptions.disableFolderSelect && dialogOptions.disableFolderSelect !== "0") ? true : false; $scope.disableFocalPoint = (dialogOptions.disableFocalPoint && dialogOptions.disableFocalPoint !== "0") ? true : false; $scope.onlyImages = (dialogOptions.onlyImages && dialogOptions.onlyImages !== "0") ? true : false; $scope.onlyFolders = (dialogOptions.onlyFolders && dialogOptions.onlyFolders !== "0") ? true : false; $scope.showDetails = (dialogOptions.showDetails && dialogOptions.showDetails !== "0") ? true : false; $scope.multiPicker = (dialogOptions.multiPicker && dialogOptions.multiPicker !== "0") ? true : false; $scope.startNodeId = dialogOptions.startNodeId ? dialogOptions.startNodeId : -1; $scope.cropSize = dialogOptions.cropSize; $scope.lastOpenedNode = localStorageService.get("umbLastOpenedMediaNodeId"); $scope.lockedFolder = true; $scope.allowMediaEdit = dialogOptions.allowMediaEdit ? dialogOptions.allowMediaEdit : false; $scope.filterOptions = { excludeSubFolders: umbSessionStorage.get("mediaPickerExcludeSubFolders") || false }; var userStartNodes = []; var umbracoSettings = Umbraco.Sys.ServerVariables.umbracoSettings; var allowedUploadFiles = mediaHelper.formatFileTypes(umbracoSettings.allowedUploadFiles); if ($scope.onlyImages) { vm.acceptedFileTypes = mediaHelper.formatFileTypes(umbracoSettings.imageFileTypes); } else { // Use list of allowed file types if provided if (allowedUploadFiles !== '') { vm.acceptedFileTypes = allowedUploadFiles; } else { // If no allowed list, we pass in a disallowed list by adding ! to the file extensions, allowing everything EXCEPT for disallowedUploadFiles vm.acceptedFileTypes = !mediaHelper.formatFileTypes(umbracoSettings.disallowedUploadFiles); } } vm.maxFileSize = umbracoSettings.maxFileSize + "KB"; $scope.model.selection = []; vm.acceptedMediatypes = []; mediaTypeHelper.getAllowedImagetypes($scope.startNodeId) .then(function (types) { vm.acceptedMediatypes = types; }); var dataTypeKey = null; if ($scope.model && $scope.model.dataTypeKey) { dataTypeKey = $scope.model.dataTypeKey; } vm.searchOptions = { pageNumber: 1, pageSize: 100, totalItems: 0, totalPages: 0, filter: '', dataTypeKey: dataTypeKey }; vm.layout = { layouts: [{ name: "Grid", icon: "icon-thumbnails-small", path: "gridpath", selected: true }, { name: "List", icon: "icon-list", path: "listpath", selected: true }], activeLayout: { name: "Grid", icon: "icon-thumbnails-small", path: "gridpath", selected: true } }; // preload selected item $scope.target = null; if (dialogOptions.currentTarget) { $scope.target = dialogOptions.currentTarget; } function setTitle() { if (!$scope.model.title) { localizationService.localizeMany(["defaultdialogs_selectMedia", "mediaPicker_tabClipboard"]) .then(function (data) { $scope.model.title = data[0]; vm.navigation = [{ "alias": "empty", "name": data[0], "icon": "icon-umb-media", "active": true, "view": "" }]; if(vm.clipboardItems) { vm.navigation.push({ "alias": "clipboard", "name": data[1], "icon": "icon-paste-in", "view": "", "disabled": vm.clipboardItems.length === 0 }); } vm.activeTab = vm.navigation[0]; }); } } function onInit() { setTitle(); userService.getCurrentUser().then(function (userData) { userStartNodes = userData.startMediaIds; if ($scope.startNodeId !== -1) { entityResource.getById($scope.startNodeId, "media") .then(function (ent) { $scope.startNodeId = ent.id; run(); }); } else { run(); } }); } function run() { //default root item if (!$scope.target) { if ($scope.lastOpenedNode && $scope.lastOpenedNode !== -1) { entityResource.getById($scope.lastOpenedNode, "media") .then(ensureWithinStartNode, gotoStartNode); } else { gotoStartNode(); } } else { // if a target is specified, go look it up - generally this target will just contain ids not the actual full // media object so we need to look it up var originalTarget = $scope.target; var id = $scope.target.udi ? $scope.target.udi : $scope.target.id; var altText = $scope.target.altText; // ID of a UDI or legacy int ID still could be null/undefinied here // As user may dragged in an image that has not been saved to media section yet if (id) { entityResource.getById(id, "Media") .then(function (node) { $scope.target = node; // Moving directly to existing node's folder gotoFolder({ id: node.parentId }).then(function () { selectMedia(node); $scope.target.url = mediaHelper.resolveFileFromEntity(node); $scope.target.thumbnail = mediaHelper.resolveFileFromEntity(node, true); $scope.target.altText = altText; $scope.target.focalPoint = originalTarget.focalPoint; $scope.target.coordinates = originalTarget.coordinates; openDetailsDialog(); }); }, gotoStartNode); } else { // No ID set - then this is going to be a tmpimg that has not been uploaded // User editing this will want to be changing the ALT text openDetailsDialog(); } } } function upload(v) { var fileSelect = $(".umb-file-dropzone .file-select"); if (fileSelect.length === 0) { localizationService.localize('media_uploadNotAllowed').then(function (message) { notificationsService.warning(message); }); } else { fileSelect.trigger("click"); } } function dragLeave() { $scope.activeDrag = false; } function dragEnter() { $scope.activeDrag = true; } function submitFolder() { if ($scope.model.newFolderName) { $scope.model.creatingFolder = true; mediaResource .addFolder($scope.model.newFolderName, $scope.currentFolder.id) .then(function (data) { //we've added a new folder so lets clear the tree cache for that specific item treeService.clearCache({ cacheKey: "__media", //this is the main media tree cache key childrenOf: data.parentId //clear the children of the parent }); $scope.model.creatingFolder = false; gotoFolder(data); $scope.model.showFolderInput = false; $scope.model.newFolderName = ""; }); } else { $scope.model.showFolderInput = false; } } function enterSubmitFolder(event) { if (event.keyCode === 13) { submitFolder(); event.stopPropagation(); } } function gotoFolder(folder) { if (!$scope.multiPicker) { deselectAllMedia($scope.model.selection); } if (!folder) { folder = { id: -1, name: "Media", icon: "icon-folder" }; } if (folder.id > 0) { entityResource.getAncestors(folder.id, "media", null, { dataTypeKey: dataTypeKey }) .then(function (anc) { $scope.path = _.filter(anc, function (f) { return f.path.indexOf($scope.startNodeId) !== -1; }); }); } else { $scope.path = []; } mediaTypeHelper.getAllowedImagetypes(folder.id).then(function (types) { vm.acceptedMediatypes = types; }); $scope.lockedFolder = (folder.id === -1 && $scope.model.startNodeIsVirtual) || hasFolderAccess(folder) === false; $scope.currentFolder = folder; localStorageService.set("umbLastOpenedMediaNodeId", folder.id); return getChildren(folder.id); } function toggleListView() { vm.showMediaList = !vm.showMediaList; } function selectLayout(layout) { //this somehow doesn't set the 'active=true' property for the chosen layout vm.layout.activeLayout = layout; //workaround vm.layout.layouts.forEach(element => element.active = false); layout.active = true; //set whether to toggle the list vm.showMediaList = (layout.name === "List"); } function clickHandler(media, event, index) { if (media.isFolder) { if ($scope.disableFolderSelect) { gotoFolder(media); } else { selectMedia(media); } } else { if ($scope.showDetails) { $scope.target = media; // handle both entity and full media object if (media.image) { $scope.target.url = media.image; } else { $scope.target.url = mediaHelper.resolveFile(media); } openDetailsDialog(); } else { selectMedia(media); } } } function clickItemName(item, event, index) { if (item.isFolder) { gotoFolder(item); } else { clickHandler(item, event, index); } }; function selectMedia(media) { if (!media.selectable) { return; } if (media.selected) { for (var i = 0; $scope.model.selection.length > i; i++) { var imageInSelection = $scope.model.selection[i]; if (media.key === imageInSelection.key) { media.selected = false; $scope.model.selection.splice(i, 1); } } } else { if (!$scope.multiPicker) { deselectAllMedia($scope.model.selection); } eventsService.emit("dialogs.mediaPicker.select", media); media.selected = true; $scope.model.selection.push(media); } } function deselectAllMedia(medias) { for (var i = 0; i < medias.length; i++) { var media = medias[i]; media.selected = false; } medias.length = 0; } function onUploadComplete(files) { gotoFolder($scope.currentFolder).then(function () { $timeout(function () { if ($scope.multiPicker) { var images = _.rest(_.sortBy($scope.images, 'id'), $scope.images.length - files.length); images.forEach(image => selectMedia(image)); } else { var image = _.sortBy($scope.images, 'id')[$scope.images.length - 1]; clickHandler(image); } }); }); } function onFilesQueue() { $scope.activeDrag = false; } function ensureWithinStartNode(node) { // make sure that last opened node is on the same path as start node var nodePath = node.path.split(","); // also make sure the node is not trashed if (nodePath.indexOf($scope.startNodeId.toString()) !== -1 && node.trashed === false) { gotoFolder({ id: $scope.lastOpenedNode || $scope.startNodeId, name: "Media", icon: "icon-folder", path: node.path }); return true; } else { gotoFolder({ id: $scope.startNodeId, name: "Media", icon: "icon-folder" }); return false; } } function hasFolderAccess(node) { var nodePath = node.path ? node.path.split(',') : [node.id]; for (var i = 0; i < nodePath.length; i++) { if (userStartNodes.indexOf(parseInt(nodePath[i])) !== -1) return true; } return false; } function gotoStartNode() { gotoFolder({ id: $scope.startNodeId, name: "Media", icon: "icon-folder" }); } function openDetailsDialog() { const dialog = { size: "small", cropSize: $scope.cropSize, target: $scope.target, disableFocalPoint: $scope.disableFocalPoint, submit: function () { $scope.model.selection.push($scope.target); $scope.model.submit($scope.model); editorService.close(); }, close: function () { editorService.close(); } }; localizationService.localize("defaultdialogs_editSelectedMedia").then(value => { dialog.title = value; editorService.mediaCropDetails(dialog); }); }; function onNavigationChanged(tab) { vm.activeTab.active = false; vm.activeTab = tab; vm.activeTab.active = true; }; function clickClearClipboard() { vm.onNavigationChanged(vm.navigation[0]); vm.navigation[1].disabled = true; vm.clipboardItems = []; dialogOptions.clickClearClipboard(); }; var debounceSearchMedia = _.debounce(function () { $scope.$apply(function () { if (vm.searchOptions.filter) { searchMedia(); } else { // reset pagination vm.searchOptions = { pageNumber: 1, pageSize: 100, totalItems: 0, totalPages: 0, filter: '', dataTypeKey: dataTypeKey }; getChildren($scope.currentFolder.id); } }); }, 500); function changeSearch() { vm.loading = true; debounceSearchMedia(); } function toggle() { umbSessionStorage.set("mediaPickerExcludeSubFolders", $scope.filterOptions.excludeSubFolders); // Make sure to activate the changeSearch function everytime the toggle is clicked changeSearch(); } function changePagination(pageNumber) { vm.loading = true; vm.searchOptions.pageNumber = pageNumber; searchMedia(); }; function searchMedia() { vm.loading = true; entityResource.getPagedDescendants($scope.filterOptions.excludeSubFolders ? $scope.currentFolder.id : $scope.startNodeId, "Media", vm.searchOptions) .then(function (data) { // update image data to work with image grid if (data.items) { var allowedTypes = dialogOptions.filter ? dialogOptions.filter.split(",") : null; data.items.forEach(function(mediaItem) { setMediaMetaData(mediaItem); mediaItem.filtered = allowedTypes && allowedTypes.indexOf(mediaItem.metaData.ContentTypeAlias) < 0; }); } // update images $scope.images = data.items ? data.items : []; // update pagination if (data.pageNumber > 0) vm.searchOptions.pageNumber = data.pageNumber; if (data.pageSize > 0) vm.searchOptions.pageSize = data.pageSize; vm.searchOptions.totalItems = data.totalItems; vm.searchOptions.totalPages = data.totalPages; // set already selected medias to selected preSelectMedia(); vm.loading = false; }); } function setMediaMetaData(mediaItem) { // set thumbnail and src mediaItem.thumbnail = mediaHelper.resolveFileFromEntity(mediaItem, true); mediaItem.image = mediaHelper.resolveFileFromEntity(mediaItem, false); // set properties to match a media object if (mediaItem.metaData) { mediaItem.properties = []; if (mediaItem.metaData.umbracoWidth && mediaItem.metaData.umbracoHeight) { mediaItem.properties.push( { alias: "umbracoWidth", editor: mediaItem.metaData.umbracoWidth.PropertyEditorAlias, value: mediaItem.metaData.umbracoWidth.Value }, { alias: "umbracoHeight", editor: mediaItem.metaData.umbracoHeight.PropertyEditorAlias, value: mediaItem.metaData.umbracoHeight.Value } ); } if (mediaItem.metaData.umbracoFile) { // this is required for resolving files through the mediahelper mediaItem.properties.push( { alias: "umbracoFile", editor: mediaItem.metaData.umbracoFile.PropertyEditorAlias, value: mediaItem.metaData.umbracoFile.Value } ); } if (mediaItem.metaData.UpdateDate !== null) { mediaItem.updateDate = mediaItem.metaData.UpdateDate; } } } function getChildren(id) { vm.loading = true; return entityResource.getChildren(id, "Media", vm.searchOptions).then(function (data) { var allowedTypes = dialogOptions.filter ? dialogOptions.filter.split(",") : null; for (var i = 0; i < data.length; i++) { setDefaultData(data[i]); data[i].filtered = allowedTypes && allowedTypes.indexOf(data[i].metaData.ContentTypeAlias) < 0; } vm.searchOptions.filter = ""; $scope.images = data ? data : []; // set already selected medias to selected preSelectMedia(); vm.loading = false; }); } function setDefaultData(item) { if (item.metaData.MediaPath !== null) { item.thumbnail = mediaHelper.resolveFileFromEntity(item, true); item.image = mediaHelper.resolveFileFromEntity(item, false); } if (item.metaData.UpdateDate !== null) { item.updateDate = item.metaData.UpdateDate; } } function preSelectMedia() { for (var folderIndex = 0; folderIndex < $scope.images.length; folderIndex++) { var folderImage = $scope.images[folderIndex]; var imageIsSelected = false; if ($scope.model && Utilities.isArray($scope.model.selection)) { for (var selectedIndex = 0; selectedIndex < $scope.model.selection.length; selectedIndex++) { var selectedImage = $scope.model.selection[selectedIndex]; if (folderImage.key === selectedImage.key) { imageIsSelected = true; } } } if (imageIsSelected) { folderImage.selected = true; } } } /** * Called when the umbImageGravity component updates the focal point value * @param {any} left * @param {any} top */ function focalPointChanged(left, top) { // update the model focalpoint value $scope.target.focalPoint = { left: left, top: top }; } function submit() { if ($scope.model && $scope.model.submit) { $scope.model.submit($scope.model); } } function close() { if ($scope.model && $scope.model.close) { $scope.model.close($scope.model); } } onInit(); });
export default { key: 'B', suffix: '7', positions: [ { frets: 'x21202', fingers: '021304' }, { frets: '224242', fingers: '113141', barres: 2, capo: true }, { frets: 'xx4445', fingers: '001112', barres: 4, capo: true }, { frets: '797877', fingers: '131211', barres: 7, capo: true } ] };
// janium_api.js ///// // Para uso exclusivo en el Sistema Nacional de Bibliotecas de Costa Rica (SINABI) ///// // // Copyright (C) 2014 - 2015, Janium Technology, S.A. de C.V. // // Todos los derechos reservados. // // Este programa de cómputo es un producto intelectual protegido en favor de su // productor Janium Technology. S.A. de C.V. La titularidad de los derechos del // programa se encuentran reconocidos en la Ley Federal del Derecho de Autor. Se // prohíbe su producción, reproducción, importación, almacenamiento, transporte, // distribución, comercialización, venta o arrendamiento, así como su adaptación o // transformación y comunicación directa a terceros, sin la previa autorización por // escrito del titular. La violación a esta prohibición constituye un delito y una // infracción, sancionados por la Ley Federal del Derecho de Autor. var JaniumAPI = { Version: '7.03', REQUIRED_PROTOTYPE: '1.5.1', KEY: 'q98mzb-cv889s-z5w90r-9v4kc6', // Validación y carga basada en la de script.aculo.us. Las inserciones de // código se hacen por fuerza bruta porque en Safari 2 no funcionan via DOM. // Si el usuario no ha incluido prototype, se carga load: function() { function convertVersionString(versionString) { var r = versionString.split('.'); return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]); } if ((typeof Prototype == 'undefined') || (typeof Element == 'undefined') || (typeof Element.Methods == 'undefined')) { document.write('<script type="text/javascript" src="http://janium.net/api/prototype.js"></script>'); } else { if (convertVersionString(Prototype.Version) < convertVersionString(JaniumAPI.REQUIRED_PROTOTYPE)) { throw("Para usar janium_api.js se require el framework de JavaScript 'Prototype' v. >= " + JaniumAPI.REQUIRED_PROTOTYPE); } } document.write('<script type="text/javascript" src="http://janium.net/api/janium_api_' + JaniumAPI.KEY + '.js"></script>'); } } JaniumAPI.load();
const through = require('through2'); const gutil = require('gulp-util'); const path = require('path'); const uuid = require('uuid'); const mkdirp = require('mkdirp'); const fs = require('fs'); const url = require('url'); const webpack = require('webpack'); const Utils = require('./src/utils'); const { processCss, processLess, processScss, processJs, preprocess, processAsset } = require('./src/processor'); const PluginError = gutil.PluginError; const PLUGIN_NAME = 'gulp-view-complete'; function complete(filepath, options) { if (!fs.existsSync(filepath)) { return Promise.resolve(); } const ext = path.extname(filepath).toLowerCase(); if (/\.(png|jpe?g|svg|ico)$/.test(ext)) { return processAsset(filepath, options); } switch (ext) { case '.js': return processJs(filepath, options); case '.css': return processCss(filepath, options); case '.less': return processLess(filepath, options); case '.scss': return processScss(filepath, options); default: return Promise.resolve(); } } // 插件级别函数 (处理文件) function viewComplete(options) { options.publicPath = options.publicPath || '/'; options.assetsPath = options.assetsPath || path.resolve(process.cwd(), 'dist'); const { publicPath } = options; // 创建一个让每个文件通过的 stream 通道 return through.obj(function (file, enc, cb) { if (file.isStream()) { this.emit('error', new PluginError(PLUGIN_NAME, 'Streams are not supported!')); return cb(); } let remarkMap = {}; let content; if (file.isBuffer()) { const input = file.contents.toString(); const remarkObj = preprocess(input); content = remarkObj.content; remarkMap = remarkObj.remarkMap; } const done = Object.keys(remarkMap).reduce((promise, ref) => { const filepath = path.join(path.dirname(file.path), ref); return promise .then(() => complete(filepath, options)) .then((assetPath) => { const finalUrl = assetPath ? url.resolve(publicPath, assetPath) : ref; const remarkId = remarkMap[ref]; const reg = new RegExp(`${Utils.escapeRegExp(remarkId)}`, 'g'); content = content.replace(reg, finalUrl); }) }, Promise.resolve()); done.then(() => { if (content) { file.contents = new Buffer(content); } cb(null, file); }) .catch(err => { console.error(err); cb(null, file); }); }); } module.exports = viewComplete;
/* * * This example demonstrates how to read custom metadata from device * * API Documentation: * https://m2x.att.com/developer/documentation/v2/device#Read-Device-Metadata */ var config = require("./config"); var M2X = require("../lib/m2x"); var m2x_client = new M2X(config.api_key); var deviceId = config.device; console.log("Read MetaData... "); m2x_client.devices.metadata(deviceId, function (response) { if (response.isSuccess()) { var jsonObj; console.log("Status Code: ".concat(response.status)); console.log("\nCustom Metadata For Device:"); jsonObj = JSON.parse(response.raw); for (var key in jsonObj) { console.log("# %s: %s", key, jsonObj[key]); } } else { console.log("Read Device MetaData Failed.Please Try Again."); console.log(JSON.stringify(response.error())); } });
'use strict'; describe('Controller: AboutCtrl', function () { // load the controller's module beforeEach(module('battleshipApp')); var AboutCtrl, scope; // Initialize the controller and a mock scope beforeEach(inject(function ($controller, $rootScope) { scope = $rootScope.$new(); AboutCtrl = $controller('AboutCtrl', { $scope: scope }); })); it('should attach a list of awesomeThings to the scope', function () { expect(scope.awesomeThings.length).toBe(3); }); });
var {Operator, Type} = require("@kaoscript/runtime"); module.exports = function() { function foo(x, y, __ks_cb) { if(arguments.length < 3) { let __ks_error = new SyntaxError("Wrong number of arguments (" + arguments.length + " for 2 + 1)"); if(arguments.length > 0 && Type.isFunction((__ks_cb = arguments[arguments.length - 1]))) { return __ks_cb(__ks_error); } else { throw __ks_error; } } else if(!Type.isFunction(__ks_cb)) { throw new TypeError("'callback' must be a function"); } if(x === void 0 || x === null) { return __ks_cb(new TypeError("'x' is not nullable")); } if(y === void 0 || y === null) { return __ks_cb(new TypeError("'y' is not nullable")); } return __ks_cb(null, Operator.subtraction(x, y)); } function bar(__ks_cb) { if(arguments.length < 1) { throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 0 + 1)"); } else if(!Type.isFunction(__ks_cb)) { throw new TypeError("'callback' must be a function"); } let d = null; let __ks_1 = () => { return __ks_cb(null, d); }; let __ks_2 = (__ks_3) => { d = 0; __ks_1(); }; try { let x = 42; let y = 24; foo(x, y, (__ks_e, __ks_0) => { if(__ks_e) { __ks_2(__ks_e); } else { try { d = __ks_0; d = Operator.multiplication(d, 3); } catch(__ks_e) { return __ks_2(__ks_e); } __ks_1(); } }); } catch(__ks_e) { __ks_2(__ks_e); } } };
//Definicion del modelo Attachment module.exports=function(sequelize,DataTypes){ return sequelize.define("Attachment", { public_id:{ type: DataTypes.STRING, validate: {notEmpty:{msg:"El Campo public_id no puede estar Vacío"}} }, url:{ type: DataTypes.STRING, validate: {notEmpty:{msg:"El Campo url no puede estar Vacío"}} }, filename:{ type: DataTypes.STRING, validate: {notEmpty:{msg:"El Campo filename no puede estar Vacío"}} }, mime:{ type: DataTypes.STRING, validate: {notEmpty:{msg:"El Campo mime no puede estar Vacío"}} } } ); };
'use strict'; /** * @ngdoc function * @name familyhistorydatabaseApp.controller:NavCtrl * @description * # NavCtrl * Controller of the familyhistorydatabaseApp */ app.controller('NavCtrl', ['$rootScope', '$scope', '$aside', 'business', '$location', function ($rootScope, $scope, $aside, Business, $location) { /*jshint unused:false*/ $scope.user = $rootScope.user; $scope.searchKey = null; $scope.loggedIn = false; $scope.aside = { 'title': 'Title', 'content': 'Hello Aside<br />This is a multiline message!' }; $scope.$on('$NOTLOGGEDIN', function(){ $scope.logout(); }) $scope.logout = function() { Business.user.logout(); $scope.$emit('$triggerEvent', '$LOGOUT'); $scope.user = null; $rootScope.user = null; $scope.loggedIn = false; }; $scope.login = function() { $scope.$emit('$triggerEvent', '$triggerModal', { 'nav': { 'bars': [ { 'title': 'Login', 'include': 'views/auth/login.html' }, { 'title': 'Register', 'include': 'views/auth/register.html' } ], 'current': 'Login' }, 'showFooter': false, 'classes': [ 'hasNav', 'darkTheme' ] }); }; $rootScope.$watch('user', function() { $scope.user = $rootScope.user; if ($scope.user) { // console.log('$scope.user', $scope.user); $scope.loggedIn = true; if (Business.user.getIsAdmin()){ $scope.admin = true; } else { $scope.admin = false; } } else { $scope.logout(); } }); $scope.onSelect = function(item, model, something) { if (typeof $scope.searchKey === 'object' && $scope.searchKey){ Business.individual.getIndData($scope.searchKey.id).then(function(result) { // console.log('Typeahead Item Found: ', $scope.searchKey); // console.log('Individual: ', result); }); } else { // console.log('searchKey', $scope.searchKey); } }; $scope.goTo = function(location) { $location.search({}); $location.path(location); } $scope.checkLogin().then(function(response){ if (response) { // console.log('response', response); $scope.loggedIn = true; $scope.user = response; } }); // Pre-fetch an external template populated with a custom scope // var myOtherAside = $aside({scope: $scope, template: 'views/navAside.html'}); // // Show when some event occurs (use $promise property to ensure the template has been loaded) // myOtherAside.$promise.then(function() { // myOtherAside.show(); // }) }]);
var waigo = require('waigo'); module.exports = function(config) { waigo.load('waigo:config/base')(config); config.port = parseInt(Math.random() * 20000 + 10000); config.baseURL = 'http://localhost:' + config.port; config.middleware.order = [ 'errorHandler', 'urlSlashSeo' ]; };
'use strict' const _ = require('lodash') const getValue = require('get-value') const setValue = require('set-value') const config = require('config') const getPlugins = require('../../src/plugins') const getServer = require('../../src/server') const agent = require('supertest-as-promised').agent let exerciseCollection let Exercise const exposePlugin = {} exposePlugin.register = function (server, options, next) { exerciseCollection = server.plugins.model.exerciseCollection Exercise = server.plugins.model.Exercise next() } exposePlugin.register.attributes = { name: 'expose-plugin', version: '1.0.0', dependency: ['model'] } class HapiWorld { constructor(){ this.hapiServer = null this.request = null } setUp() { return this.startServer() } tearDown() { return this.stopServer() } startServer(extraConfig) { const appConfig = _.extend({}, config, extraConfig) const server = getServer(appConfig) const plugins = getPlugins(appConfig) this.hapiServer = server return Promise.resolve() .then(() => server.register(plugins.list, plugins.options)) .then(() => server.register(exposePlugin)) .then(() => server.start()) .then(() => { this.request = agent(server.listener) }) .catch(err => console.log(err, err.stack)) } stopServer() { if (!this.hapiServer) { return Promise.resolve() } return this.hapiServer.stop() } } class RequestableHapiWorld extends HapiWorld { constructor() { super() this.currentPayload = {} } setPayloadPropertyIfNotExists(name, value) { if (typeof getValue(this.currentPayload, name) == "undefined") { this.setPayloadProperty(name, value) } } setPayloadProperty(name, value) { setValue(this.currentPayload, name, value) } getPayload() { return this.currentPayload } getLastResponse() { return this.lastResponse } getLastResponseCode() { return this.getLastResponse().statusCode } getLastResponseBody() { return this.getLastResponse().body } captureLastResponse(res) { this.lastResponse = res return res } } class TommyApiWorld extends RequestableHapiWorld { addExercise(data) { const ex = Exercise.create(data.title, data.specsCode) return exerciseCollection.add(ex) } getExercises() { return this.request .get('/v1/exercises') .then(res => this.captureLastResponse(res)) } getExerciseById(id) { return this.request .get(`/v1/exercises/${id}`) .then(res => this.captureLastResponse(res)) } getExerciseBySlug(slug) { return this.request .get(`/v1/exercises?slug=${slug}`) .then(res => this.captureLastResponse(res)) } } module.exports = function () { this.World = TommyApiWorld this.Before(function (scenario, callback) { this.setUp().then(() => callback()) }) this.After(function (scenario, callback) { this.tearDown().then(() => callback()) }) }
var Sequelize = require('sequelize') var attributes = { username: { type: Sequelize.STRING, allowNull: false, unique: true, validate: { is: /^[a-z0-9\_\-\.]+$/i, } }, email: { type: Sequelize.STRING, validate: { isEmail: true } }, firstName: { type: Sequelize.STRING, }, lastName: { type: Sequelize.STRING, }, password: { type: Sequelize.STRING, }, salt: { type: Sequelize.STRING } } var options = { freezeTableName: true } module.exports.attributes = attributes module.exports.options = options
/** * Created by berthelot on 05/11/14. */ 'use strict'; describe('[images-resizer][resize-service]', function () { var service; var $rootScope; beforeEach(module('images-resizer')); beforeEach(inject(function ($injector) { service = $injector.get('resizeService'); $rootScope = $injector.get('$rootScope'); })); describe('- createImage -', function () { it('should return a JS image', function (done) { service .createImage('base/fixture/img.jpg') .then(function (image) { expect(image).to.be.not.null; done(); }) .catch(function () { done('fail'); }); setTimeout(function () { $rootScope.$digest(); }, 1000); }); it('should add a crossOrigin parameter', function (done) { service .createImage('base/fixture/img.jpg', 'Anonymous') .then(function (image) { expect(image.crossOrigin).to.equal('Anonymous'); done(); }) .catch(function () { done('fail'); }); setTimeout(function () { $rootScope.$digest(); }, 1000); }); }); describe('- resizeImageWidthHeight -', function () { it('should return a base64 image with an jpg image in entry with same size', function (done) { var img = new Image(); img.onload = function () { var data = service.resizeImageWidthHeight(img); expect(data).to.be.not.null; expect(data).to.contain('data:image/jpeg;base64'); //check size of the returned image service.createImage(data) .then(function (image) { expect(image).to.be.not.null; done(); }) .catch(function () { done('fail'); }); setTimeout(function () { $rootScope.$digest(); }, 500); }; img.src = 'base/fixture/img.jpg'; }); it('should return a base64 image with specific height', function (done) { var img = new Image(); img.onload = function () { var data = service.resizeImageWidthHeight(img, null, 300); expect(data).to.be.not.null; expect(data).to.contain('data:image/jpeg;base64'); //check size of the returned image service.createImage(data) .then(function (image) { expect(image).to.be.not.null; expect(image.height).to.be.equal(300); done(); }) .catch(function () { done('fail'); }); setTimeout(function () { $rootScope.$digest(); }, 500); }; img.src = 'base/fixture/img.jpg'; }); it('should return a base64 image with specific width', function (done) { var img = new Image(); img.onload = function () { var data = service.resizeImageWidthHeight(img, 300, null, 2); expect(data).to.be.not.null; expect(data).to.contain('data:image/jpeg;base64'); //check size of the returned image service.createImage(data) .then(function (image) { expect(image).to.be.not.null; expect(image.width).to.be.equal(300); done(); }) .catch(function () { done('fail'); }); setTimeout(function () { $rootScope.$digest(); }, 500); }; img.src = 'base/fixture/img.jpg'; }); it('should return a base64 image with specific height and width', function (done) { var img = new Image(); img.onload = function () { var data = service.resizeImageWidthHeight(img, 300, 300, 2); expect(data).to.be.not.null; expect(data).to.contain('data:image/jpeg;base64'); //check size of the returned image service.createImage(data) .then(function (image) { expect(image).to.be.not.null; expect(image.width).to.be.equal(300); expect(image.height).to.be.equal(300); done(); }) .catch(function () { done('fail'); }); setTimeout(function () { $rootScope.$digest(); }, 500); }; img.src = 'base/fixture/img.jpg'; }); it('should return a base64 image with specific height and width to png format', function (done) { var img = new Image(); img.onload = function () { var data = service.resizeImageWidthHeight(img, 300, 300, 2, 'image/png'); expect(data).to.be.not.null; expect(data).to.contain('data:image/png;base64'); //check size of the returned image service.createImage(data) .then(function (image) { expect(image).to.be.not.null; expect(image.width).to.be.equal(300); expect(image.height).to.be.equal(300); done(); }) .catch(function () { done('fail'); }); setTimeout(function () { $rootScope.$digest(); }, 500); }; img.src = 'base/fixture/img.jpg'; }); }); describe('- resizeImageBySize -', function () { it('should return a base64 img with a lower size than specified in the option', function (done) { var img = new Image(); img.onload = function () { //When i wrote this test, the test image = 8.3Ko var data = service.resizeImageBySize(img, 5000); expect(data).to.be.not.null; expect(data).to.contain('data:image/jpeg;base64'); //check the size of the returned image expect(Math.round(data.length - 'data:image/jpeg;base64,'.length) * 3 / 4).to.be.below(6000); done(); }; img.src = 'base/fixture/img.jpg'; }); it('should return null when no image is specified', function () { var data = service.resizeImageBySize(); expect(data).to.be.null; }); }); describe('- resizeImage -', function () { it('should return nothing when there is no param send', function (done) { service .resizeImage() .then(function () { done('fail'); }) .catch(function (err) { expect(err).to.equal('Missing argument when calling resizeImage function'); done(); }); $rootScope.$digest(); }); it('should fire an error when there is missing options', function (done) { service .resizeImage('base/fixture/img.jpg', null) .then(function () { done('fail'); }) .catch(function (err) { expect(err).to.equal('Missing argument when calling resizeImage function'); done(); }); $rootScope.$digest(); }); it('should return a base64 img with no error when no specific option is specified', function (done) { service .resizeImage('base/fixture/img.jpg', {}) .then(function (data) { expect(data).to.be.not.null; expect(data).to.contain('data:image/jpeg;base64'); done(); }) .catch(function () { done('fail'); }); setTimeout(function () { $rootScope.$digest(); setTimeout(function () { $rootScope.$digest(); }, 500); }, 500); }); it('should return a base64 img according to the size given in octet', function (done) { service .resizeImage('base/fixture/img.jpg', {size: 5000, sizeScale: 'o'}) .then(function (data) { expect(data).to.be.not.null; expect(data).to.contain('data:image/jpeg;base64'); //check the size of the returned image expect(Math.round(data.length - 'data:image/jpeg;base64,'.length) * 3 / 4).to.be.below(6000); done(); }) .catch(function () { done('fail'); }); setTimeout(function () { $rootScope.$digest(); setTimeout(function () { $rootScope.$digest(); }, 500); }, 500); }); it('should return a base64 img according to the size given in Ko', function (done) { var sizeInKo = 5000 / 1024; service .resizeImage('base/fixture/img.jpg', {size: sizeInKo, sizeScale: 'ko'}) .then(function (data) { expect(data).to.be.not.null; expect(data).to.contain('data:image/jpeg;base64'); //check the size of the returned image expect(Math.round(data.length - 'data:image/jpeg;base64,'.length) * 3 / 4).to.be.below(6000); done(); }) .catch(function () { done('fail'); }); setTimeout(function () { $rootScope.$digest(); setTimeout(function () { $rootScope.$digest(); }, 500); }, 500); }); it('should return a base64 img according to the size given in Mo', function (done) { var sizeInMo = 5000 / (1024 * 1024); service.resizeImage('base/fixture/img.jpg', {size: sizeInMo, sizeScale: 'mo'}) .then(function (data) { expect(data).to.be.not.null; expect(data).to.contain('data:image/jpeg;base64'); //check the size of the returned image expect(Math.round(data.length - 'data:image/jpeg;base64,'.length) * 3 / 4).to.be.below(6000); done(); }) .catch(function () { done('fail'); }); setTimeout(function () { $rootScope.$digest(); setTimeout(function () { $rootScope.$digest(); }, 500); }, 500); }); it('should return a base64 img according to the size given in Go', function (done) { var sizeInGo = 5000 / (1024 * 1024 * 1024); service .resizeImage('base/fixture/img.jpg', {size: sizeInGo, sizeScale: 'go'}) .then(function (data) { expect(data).to.be.not.null; expect(data).to.contain('data:image/jpeg;base64'); //check the size of the returned image expect(Math.round(data.length - 'data:image/jpeg;base64,'.length) * 3 / 4).to.be.below(6000); done(); }) .catch(function () { done('fail'); }); setTimeout(function () { $rootScope.$digest(); setTimeout(function () { $rootScope.$digest(); }, 500); }, 500); }); }); describe('- calulateImageSize -', function () { it('should return the size of the img for a jpg image', function (done) { var img = new Image(); img.onload = function () { var data = service.resizeImageWidthHeight(img, null, null, null, 'image/jpeg'); expect(service.calulateImageSize(data)).to.be.equal(58219); done(); }; img.src = 'base/fixture/img.png'; setTimeout(function () { $rootScope.$digest(); }, 500); }); it('should return the size of the img for a png image', function (done) { var img = new Image(); img.onload = function () { var data = service.resizeImageWidthHeight(img, null, null, null, 'image/png'); expect(service.calulateImageSize(data, 'image/png')).to.be.equal(398604); done(); }; img.src = 'base/fixture/img.png'; setTimeout(function () { $rootScope.$digest(); }, 500); }); it('should return 0 when the img is empty', function () { expect(service.calulateImageSize('', 'image/png')).to.be.equal(0); }); }); });
// // Generated on Tue Dec 16 2014 12:13:47 GMT+0100 (CET) by Charlie Robbins, Paolo Fragomeni & the Contributors (Using Codesurgeon). // Version 1.2.6 // (function (exports) { /* * browser.js: Browser specific functionality for director. * * (C) 2011, Charlie Robbins, Paolo Fragomeni, & the Contributors. * MIT LICENSE * */ var dloc = document.location; function dlocHashEmpty() { // Non-IE browsers return '' when the address bar shows '#'; Director's logic // assumes both mean empty. return dloc.hash === '' || dloc.hash === '#'; } var listener = { mode: 'modern', hash: dloc.hash, history: false, check: function () { var h = dloc.hash; if (h != this.hash) { this.hash = h; this.onHashChanged(); } }, fire: function () { if (this.mode === 'modern') { this.history === true ? window.onpopstate() : window.onhashchange(); } else { this.onHashChanged(); } }, init: function (fn, history) { var self = this; this.history = history; if (!Router.listeners) { Router.listeners = []; } function onchange(onChangeEvent) { for (var i = 0, l = Router.listeners.length; i < l; i++) { Router.listeners[i](onChangeEvent); } } //note IE8 is being counted as 'modern' because it has the hashchange event if ('onhashchange' in window && (document.documentMode === undefined || document.documentMode > 7)) { // At least for now HTML5 history is available for 'modern' browsers only if (this.history === true) { // There is an old bug in Chrome that causes onpopstate to fire even // upon initial page load. Since the handler is run manually in init(), // this would cause Chrome to run it twise. Currently the only // workaround seems to be to set the handler after the initial page load // http://code.google.com/p/chromium/issues/detail?id=63040 // setTimeout(function() { window.onpopstate = onchange; // }, 500); } else { window.onhashchange = onchange; } this.mode = 'modern'; } else { // // IE support, based on a concept by Erik Arvidson ... // var frame = document.createElement('iframe'); frame.id = 'state-frame'; frame.style.display = 'none'; document.body.appendChild(frame); this.writeFrame(''); if ('onpropertychange' in document && 'attachEvent' in document) { document.attachEvent('onpropertychange', function () { if (event.propertyName === 'location') { self.check(); } }); } window.setInterval(function () { self.check(); }, 50); this.onHashChanged = onchange; this.mode = 'legacy'; } Router.listeners.push(fn); return this.mode; }, destroy: function (fn) { if (!Router || !Router.listeners) { return; } var listeners = Router.listeners; for (var i = listeners.length - 1; i >= 0; i--) { if (listeners[i] === fn) { listeners.splice(i, 1); } } }, setHash: function (s) { // Mozilla always adds an entry to the history if (this.mode === 'legacy') { this.writeFrame(s); } if (this.history === true) { window.history.pushState({}, document.title, s); // Fire an onpopstate event manually since pushing does not obviously // trigger the pop event. this.fire(); } else { dloc.hash = (s[0] === '/') ? s : '/' + s; } return this; }, writeFrame: function (s) { // IE support... var f = document.getElementById('state-frame'); var d = f.contentDocument || f.contentWindow.document; d.open(); d.write("<script>_hash = '" + s + "'; onload = parent.listener.syncHash;<script>"); d.close(); }, syncHash: function () { // IE support... var s = this._hash; if (s != dloc.hash) { dloc.hash = s; } return this; }, onHashChanged: function () {} }; var Router = exports.Router = function (routes) { if (!(this instanceof Router)) return new Router(routes); this.params = {}; this.routes = {}; this.methods = ['on', 'once', 'after', 'before']; this.scope = []; this._methods = {}; this._insert = this.insert; this.insert = this.insertEx; this.historySupport = (window.history != null ? window.history.pushState : null) != null this.configure(); this.mount(routes || {}); }; Router.prototype.init = function (r) { var self = this , routeTo; this.handler = function(onChangeEvent) { var newURL = onChangeEvent && onChangeEvent.newURL || window.location.hash; var url = self.history === true ? self.getPath() : newURL.replace(/.*#/, ''); self.dispatch('on', url.charAt(0) === '/' ? url : '/' + url); }; listener.init(this.handler, this.history); if (this.history === false) { if (dlocHashEmpty() && r) { dloc.hash = r; } else if (!dlocHashEmpty()) { self.dispatch('on', '/' + dloc.hash.replace(/^(#\/|#|\/)/, '')); } } else { if (this.convert_hash_in_init) { // Use hash as route routeTo = dlocHashEmpty() && r ? r : !dlocHashEmpty() ? dloc.hash.replace(/^#/, '') : null; if (routeTo) { window.history.replaceState({}, document.title, routeTo); } } else { // Use canonical url routeTo = this.getPath(); } // Router has been initialized, but due to the chrome bug it will not // yet actually route HTML5 history state changes. Thus, decide if should route. if (routeTo || this.run_in_init === true) { this.handler(); } } return this; }; Router.prototype.explode = function () { var v = this.history === true ? this.getPath() : dloc.hash; if (v.charAt(1) === '/') { v=v.slice(1) } return v.slice(1, v.length).split("/"); }; Router.prototype.setRoute = function (i, v, val) { var url = this.explode(); if (typeof i === 'number' && typeof v === 'string') { url[i] = v; } else if (typeof val === 'string') { url.splice(i, v, s); } else { url = [i]; } listener.setHash(url.join('/')); return url; }; // // ### function insertEx(method, path, route, parent) // #### @method {string} Method to insert the specific `route`. // #### @path {Array} Parsed path to insert the `route` at. // #### @route {Array|function} Route handlers to insert. // #### @parent {Object} **Optional** Parent "routes" to insert into. // insert a callback that will only occur once per the matched route. // Router.prototype.insertEx = function(method, path, route, parent) { if (method === "once") { method = "on"; route = function(route) { var once = false; return function() { if (once) return; once = true; return route.apply(this, arguments); }; }(route); } return this._insert(method, path, route, parent); }; Router.prototype.getRoute = function (v) { var ret = v; if (typeof v === "number") { ret = this.explode()[v]; } else if (typeof v === "string"){ var h = this.explode(); ret = h.indexOf(v); } else { ret = this.explode(); } return ret; }; Router.prototype.destroy = function () { listener.destroy(this.handler); return this; }; Router.prototype.getPath = function () { var path = window.location.pathname; if (path.substr(0, 1) !== '/') { path = '/' + path; } return path; }; function _every(arr, iterator) { for (var i = 0; i < arr.length; i += 1) { if (iterator(arr[i], i, arr) === false) { return; } } } function _flatten(arr) { var flat = []; for (var i = 0, n = arr.length; i < n; i++) { flat = flat.concat(arr[i]); } return flat; } function _asyncEverySeries(arr, iterator, callback) { if (!arr.length) { return callback(); } var completed = 0; (function iterate() { iterator(arr[completed], function(err) { if (err || err === false) { callback(err); callback = function() {}; } else { completed += 1; if (completed === arr.length) { callback(); } else { iterate(); } } }); })(); } function paramifyString(str, params, mod) { mod = str; for (var param in params) { if (params.hasOwnProperty(param)) { mod = params[param](str); if (mod !== str) { break; } } } return mod === str ? "([._a-zA-Z0-9-%()]+)" : mod; } function regifyString(str, params) { var matches, last = 0, out = ""; while (matches = str.substr(last).match(/[^\w\d\- %@&]*\*[^\w\d\- %@&]*/)) { last = matches.index + matches[0].length; matches[0] = matches[0].replace(/^\*/, "([_.()!\\ %@&a-zA-Z0-9-]+)"); out += str.substr(0, matches.index) + matches[0]; } str = out += str.substr(last); var captures = str.match(/:([^\/]+)/ig), capture, length; if (captures) { length = captures.length; for (var i = 0; i < length; i++) { capture = captures[i]; if (capture.slice(0, 2) === "::") { str = capture.slice(1); } else { str = str.replace(capture, paramifyString(capture, params)); } } } return str; } function terminator(routes, delimiter, start, stop) { var last = 0, left = 0, right = 0, start = (start || "(").toString(), stop = (stop || ")").toString(), i; for (i = 0; i < routes.length; i++) { var chunk = routes[i]; if (chunk.indexOf(start, last) > chunk.indexOf(stop, last) || ~chunk.indexOf(start, last) && !~chunk.indexOf(stop, last) || !~chunk.indexOf(start, last) && ~chunk.indexOf(stop, last)) { left = chunk.indexOf(start, last); right = chunk.indexOf(stop, last); if (~left && !~right || !~left && ~right) { var tmp = routes.slice(0, (i || 1) + 1).join(delimiter); routes = [ tmp ].concat(routes.slice((i || 1) + 1)); } last = (right > left ? right : left) + 1; i = 0; } else { last = 0; } } return routes; } var QUERY_SEPARATOR = /\?.*/; Router.prototype.configure = function(options) { options = options || {}; for (var i = 0; i < this.methods.length; i++) { this._methods[this.methods[i]] = true; } this.recurse = options.recurse || this.recurse || false; this.async = options.async || false; this.delimiter = options.delimiter || "/"; this.strict = typeof options.strict === "undefined" ? true : options.strict; this.notfound = options.notfound; this.resource = options.resource; this.history = options.html5history && this.historySupport || false; this.run_in_init = this.history === true && options.run_handler_in_init !== false; this.convert_hash_in_init = this.history === true && options.convert_hash_in_init !== false; this.every = { after: options.after || null, before: options.before || null, on: options.on || null }; return this; }; Router.prototype.param = function(token, matcher) { if (token[0] !== ":") { token = ":" + token; } var compiled = new RegExp(token, "g"); this.params[token] = function(str) { return str.replace(compiled, matcher.source || matcher); }; return this; }; Router.prototype.on = Router.prototype.route = function(method, path, route) { var self = this; if (!route && typeof path == "function") { route = path; path = method; method = "on"; } if (Array.isArray(path)) { return path.forEach(function(p) { self.on(method, p, route); }); } if (path.source) { path = path.source.replace(/\\\//ig, "/"); } if (Array.isArray(method)) { return method.forEach(function(m) { self.on(m.toLowerCase(), path, route); }); } path = path.split(new RegExp(this.delimiter)); path = terminator(path, this.delimiter); this.insert(method, this.scope.concat(path), route); }; Router.prototype.path = function(path, routesFn) { var self = this, length = this.scope.length; if (path.source) { path = path.source.replace(/\\\//ig, "/"); } path = path.split(new RegExp(this.delimiter)); path = terminator(path, this.delimiter); this.scope = this.scope.concat(path); routesFn.call(this, this); this.scope.splice(length, path.length); }; Router.prototype.dispatch = function(method, path, callback) { var self = this, fns = this.traverse(method, path.replace(QUERY_SEPARATOR, ""), this.routes, ""), invoked = this._invoked, after; this._invoked = true; if (!fns || fns.length === 0) { this.last = []; if (typeof this.notfound === "function") { this.invoke([ this.notfound ], { method: method, path: path }, callback); } return false; } if (this.recurse === "forward") { fns = fns.reverse(); } function updateAndInvoke() { self.last = fns.after; self.invoke(self.runlist(fns), self, callback); } after = this.every && this.every.after ? [ this.every.after ].concat(this.last) : [ this.last ]; if (after && after.length > 0 && invoked) { if (this.async) { this.invoke(after, this, updateAndInvoke); } else { this.invoke(after, this); updateAndInvoke(); } return true; } updateAndInvoke(); return true; }; Router.prototype.invoke = function(fns, thisArg, callback) { var self = this; var apply; if (this.async) { apply = function(fn, next) { if (Array.isArray(fn)) { return _asyncEverySeries(fn, apply, next); } else if (typeof fn == "function") { fn.apply(thisArg, (fns.captures || []).concat(next)); } }; _asyncEverySeries(fns, apply, function() { if (callback) { callback.apply(thisArg, arguments); } }); } else { apply = function(fn) { if (Array.isArray(fn)) { return _every(fn, apply); } else if (typeof fn === "function") { return fn.apply(thisArg, fns.captures || []); } else if (typeof fn === "string" && self.resource) { self.resource[fn].apply(thisArg, fns.captures || []); } }; _every(fns, apply); } }; Router.prototype.traverse = function(method, path, routes, regexp, filter) { var fns = [], current, exact, match, next, that; function filterRoutes(routes) { if (!filter) { return routes; } function deepCopy(source) { var result = []; for (var i = 0; i < source.length; i++) { result[i] = Array.isArray(source[i]) ? deepCopy(source[i]) : source[i]; } return result; } function applyFilter(fns) { for (var i = fns.length - 1; i >= 0; i--) { if (Array.isArray(fns[i])) { applyFilter(fns[i]); if (fns[i].length === 0) { fns.splice(i, 1); } } else { if (!filter(fns[i])) { fns.splice(i, 1); } } } } var newRoutes = deepCopy(routes); newRoutes.matched = routes.matched; newRoutes.captures = routes.captures; newRoutes.after = routes.after.filter(filter); applyFilter(newRoutes); return newRoutes; } if (path === this.delimiter && routes[method]) { next = [ [ routes.before, routes[method] ].filter(Boolean) ]; next.after = [ routes.after ].filter(Boolean); next.matched = true; next.captures = []; return filterRoutes(next); } for (var r in routes) { if (routes.hasOwnProperty(r) && (!this._methods[r] || this._methods[r] && typeof routes[r] === "object" && !Array.isArray(routes[r]))) { current = exact = regexp + this.delimiter + r; if (!this.strict) { exact += "[" + this.delimiter + "]?"; } match = path.match(new RegExp("^" + exact)); if (!match) { continue; } if (match[0] && match[0] == path && routes[r][method]) { next = [ [ routes[r].before, routes[r][method] ].filter(Boolean) ]; next.after = [ routes[r].after ].filter(Boolean); next.matched = true; next.captures = match.slice(1); if (this.recurse && routes === this.routes) { next.push([ routes.before, routes.on ].filter(Boolean)); next.after = next.after.concat([ routes.after ].filter(Boolean)); } return filterRoutes(next); } next = this.traverse(method, path, routes[r], current); if (next.matched) { if (next.length > 0) { fns = fns.concat(next); } if (this.recurse) { fns.push([ routes[r].before, routes[r].on ].filter(Boolean)); next.after = next.after.concat([ routes[r].after ].filter(Boolean)); if (routes === this.routes) { fns.push([ routes["before"], routes["on"] ].filter(Boolean)); next.after = next.after.concat([ routes["after"] ].filter(Boolean)); } } fns.matched = true; fns.captures = next.captures; fns.after = next.after; return filterRoutes(fns); } } } return false; }; Router.prototype.insert = function(method, path, route, parent) { var methodType, parentType, isArray, nested, part; path = path.filter(function(p) { return p && p.length > 0; }); parent = parent || this.routes; part = path.shift(); if (/\:|\*/.test(part) && !/\\d|\\w/.test(part)) { part = regifyString(part, this.params); } if (path.length > 0) { parent[part] = parent[part] || {}; return this.insert(method, path, route, parent[part]); } if (!part && !path.length && parent === this.routes) { methodType = typeof parent[method]; switch (methodType) { case "function": parent[method] = [ parent[method], route ]; return; case "object": parent[method].push(route); return; case "undefined": parent[method] = route; return; } return; } parentType = typeof parent[part]; isArray = Array.isArray(parent[part]); if (parent[part] && !isArray && parentType == "object") { methodType = typeof parent[part][method]; switch (methodType) { case "function": parent[part][method] = [ parent[part][method], route ]; return; case "object": parent[part][method].push(route); return; case "undefined": parent[part][method] = route; return; } } else if (parentType == "undefined") { nested = {}; nested[method] = route; parent[part] = nested; return; } throw new Error("Invalid route context: " + parentType); }; Router.prototype.extend = function(methods) { var self = this, len = methods.length, i; function extend(method) { self._methods[method] = true; self[method] = function() { var extra = arguments.length === 1 ? [ method, "" ] : [ method ]; self.on.apply(self, extra.concat(Array.prototype.slice.call(arguments))); }; } for (i = 0; i < len; i++) { extend(methods[i]); } }; Router.prototype.runlist = function(fns) { var runlist = this.every && this.every.before ? [ this.every.before ].concat(_flatten(fns)) : _flatten(fns); if (this.every && this.every.on) { runlist.push(this.every.on); } runlist.captures = fns.captures; runlist.source = fns.source; return runlist; }; Router.prototype.mount = function(routes, path) { if (!routes || typeof routes !== "object" || Array.isArray(routes)) { return; } var self = this; path = path || []; if (!Array.isArray(path)) { path = path.split(self.delimiter); } function insertOrMount(route, local) { var rename = route, parts = route.split(self.delimiter), routeType = typeof routes[route], isRoute = parts[0] === "" || !self._methods[parts[0]], event = isRoute ? "on" : rename; if (isRoute) { rename = rename.slice((rename.match(new RegExp("^" + self.delimiter)) || [ "" ])[0].length); parts.shift(); } if (isRoute && routeType === "object" && !Array.isArray(routes[route])) { local = local.concat(parts); self.mount(routes[route], local); return; } if (isRoute) { local = local.concat(rename.split(self.delimiter)); local = terminator(local, self.delimiter); } self.insert(event, local, routes[route]); } for (var route in routes) { if (routes.hasOwnProperty(route)) { insertOrMount(route, path.slice(0)); } } }; }(typeof exports === "object" ? exports : window));
version https://git-lfs.github.com/spec/v1 oid sha256:5e818b98f37edeeeefc68e11b821a84d65a6a6a3500727280ee7a63d2d56cad0 size 27828
// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js.\ // manifest workflow function validateFileUrl(){ $('#validate_files').on('click', function(){ var location_urls = $('#location_urls').val(); var form = $(this).parents('form'); $(form).trigger('submit.rails'); $('#location_urls').val(''); event.preventDefault(); $ }); }
const config = { firebase: { apiKey: 'AIzaSyCsXIExz25SRWDT0b_1hsdq-AjQTcPs5Fw', authDomain: 'tardis-exp.firebaseapp.com', databaseURL: 'https://tardis-exp.firebaseio.com', projectId: 'tardis-exp', storageBucket: 'tardis-exp.appspot.com', messagingSenderId: '1015923519552' }, }; export default config;
var searchData= [ ['xictolerance',['XicTolerance',['../class_uimf_data_extractor_1_1_models_1_1_command_line_options.html#a2a87cfd6a2d757f6e6d5719633ec007a',1,'UimfDataExtractor::Models::CommandLineOptions']]] ];
/* #!/usr/local/bin/node -*- coding:utf-8 -*- Copyright 2013 freedom Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --- Created with Sublime Text 2. Date: 16/11/13 Time: 14:32 PM Desc: logout - the controller of logout */ //mode /*jslint nomen: true*/ "use strict"; /** * sign out * @param {object} req the instance of request * @param {object} res the instance of response * @param {Function} next the next handler * @return {null} */ exports.signOut = function (req, res, next) { req.session.destroy(); res.clearCookie(); res.redirect("/login"); }
require('longjohn'); if ( ! process.env.RABBITMQ_URL) throw new Error('Tests require a RABBITMQ_URL environment variable to be set, pointing to the RabbiqMQ instance you wish to use. Example url: "amqp://localhost:5672"'); var busUrl = process.env.RABBITMQ_URL; var bus = require('../').bus({ url: busUrl, enableConfirms: true }); var retry = require('servicebus-retry'); bus.use(bus.messageDomain()); bus.use(bus.package()); bus.use(bus.correlate()); bus.use(bus.logger()); bus.use(retry({ store: retry.MemoryStore() })) module.exports.bus = bus;
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h(h.f, null, h("path", { d: "M5 13h2.83L10 15.17V8.83L7.83 11H5z", opacity: ".3" }), h("path", { d: "M3 9v6h4l5 5V4L7 9H3zm7-.17v6.34L7.83 13H5v-2h2.83L10 8.83zm4-.86v8.05c1.48-.73 2.5-2.25 2.5-4.02 0-1.77-1.02-3.29-2.5-4.03zm0-4.74v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77 0-4.28-2.99-7.86-7-8.77z" })), 'VolumeUpTwoTone');
var chai = require('chai'); var expect = chai.expect; var readblet = require('../lib/index.js'); describe('toMillisec function', function(){ it('Convert readable time to millisec : 01:00:00 => 3600', function() { var result = readblet.toMillisec('01:00:00'); var millisec = 3600; expect(millisec).to.equal(result); }); it('Convert readable time to millisec : 00:01:00 => 60', function() { var result = readblet.toMillisec('00:01:00'); var millisec = 60; expect(millisec).to.equal(result); }); it('Convert readable time to millisec : 00:00:01 => 1', function() { var result = readblet.toMillisec('00:00:01'); var millisec = 1; expect(millisec).to.equal(result); }); it('Convert readable time to millisec : 00:00:00.1 => 0.1', function() { var result = readblet.toMillisec('00:00:00.1'); var millisec = 0.1; expect(millisec).to.equal(result); }); it('Convert readable time to millisec : 00:00:00.01 => 0.01', function() { var result = readblet.toMillisec('00:00:00.01'); var millisec = 0.01; expect(millisec).to.equal(result); }); it('Convert readable time to millisec : 01:01:01.16 => 3661.16', function() { var result = readblet.toMillisec('01:01:01.16'); var millisec = 3661.16; expect(millisec).to.equal(result); }); it('Convert readable time to millisec : 00:00:00.99 => 0.99', function() { var result = readblet.toMillisec('00:00:00.99'); var millisec = 0.99; expect(millisec).to.equal(result); }); it('When put argument of 61:00:00 then not throw exception', function() { var result = readblet.toMillisec('61:00:00'); var millisec = 219600; expect(millisec).to.equal(result); }); it('When put argument of 00:61:00 then throe exception', function() { expect(function(){readblet.toMillisec('00:61:00')}).to.throw(Error); }); it('When put argument of 00:00:61 then throe exception', function() { expect(function(){readblet.toMillisec('00:00:61')}).to.throw(Error); }); it('For unexpected arguments, TypeError is returned', function() { expect(function(){readblet.toMillisec('000000')}).to.throw(Error); expect(function(){readblet.toMillisec('test')}).to.throw(Error); expect(function(){readblet.toMillisec('01:0101')}).to.throw(Error); expect(function(){readblet.toMillisec('0101:01')}).to.throw(Error); expect(function(){readblet.toMillisec('01:0101.01')}).to.throw(Error); expect(function(){readblet.toMillisec('0101:01.11')}).to.throw(Error); expect(function(){readblet.toMillisec('010101.11')}).to.throw(Error); }); }); describe('toReadable function', function(){ it('3600 => 01:00:00', function() { var result = readblet.toReadable(3600); var readableTime = '01:00:00'; expect(readableTime).to.equal(result); }); it('60 => 00:01:00', function() { var result = readblet.toReadable(60); var readableTime = '00:01:00'; expect(readableTime).to.equal(result); }); it('1 => 00:00:01', function() { var result = readblet.toReadable(1); var readableTime = '00:00:01'; expect(readableTime).to.equal(result); }); it('0.1 => 00:00:00.1', function() { var result = readblet.toReadable(0.1); var readableTime = '00:00:00.1'; expect(readableTime).to.equal(result); }); it('0.01 => 00:00:00.01', function() { var result = readblet.toReadable(0.01); var readableTime = '00:00:00.01'; expect(readableTime).to.equal(result); }); it('3661.16 => 01:01:01.16', function() { var result = readblet.toReadable(3661.16); var readableTime = '01:01:01.16'; expect(readableTime).to.equal(result); }); it('0.99 => 00:00:00.99', function() { var result = readblet.toReadable(0.99); var readableTime = '00:00:00.99'; expect(readableTime).to.equal(result); }); it('219600 => 61:00:00', function() { var result = readblet.toReadable(219600); var readableTime = '61:00:00'; expect(readableTime).to.equal(result); }); it('3660 => 01:01:00', function() { var result = readblet.toReadable(3660); var readableTime = '01:01:00'; expect(readableTime).to.equal(result); }); it('61 => 00:01:01', function() { var result = readblet.toReadable(61); var readableTime = '00:01:01'; expect(readableTime).to.equal(result); }); it('0.61 => 00:00:00.61', function() { var result = readblet.toReadable(0.61); var readableTime = '00:00:00.61'; expect(readableTime).to.equal(result); }); });
import { defineMessages } from 'react-intl'; const translations = defineMessages({ title: { id: 'course.assessment.form.title', defaultMessage: 'Title', }, description: { id: 'course.assessment.form.description', defaultMessage: 'Description', }, startAt: { id: 'course.assessment.form.startAt', defaultMessage: 'Start At', }, endAt: { id: 'course.assessment.form.endAt', defaultMessage: 'End At', }, bonusEndAt: { id: 'course.assessment.form.bonusEndAt', defaultMessage: 'Bonus End At', }, baseExp: { id: 'course.assessment.form.baseExp', defaultMessage: 'Base EXP', }, timeBonusExp: { id: 'course.assessment.form.timeBonusExp', defaultMessage: 'Time Bonus EXP', }, autograded: { id: 'course.assessment.form.autograded', defaultMessage: 'Autograded', }, autogradeTestCasesHint: { id: 'course.assessment.form.autogradeTestCasesHint', defaultMessage: 'Select test case types for grade and exp calculation:', }, usePublic: { id: 'course.assessment.form.usePublic', defaultMessage: 'Public', }, usePrivate: { id: 'course.assessment.form.usePrivate', defaultMessage: 'Private', }, useEvaluation: { id: 'course.assessment.form.useEvaluation', defaultMessage: 'Evaluation', }, allowPartialSubmission: { id: 'course.assessment.form.allowPartialSubmission', defaultMessage: 'Allow submission with incorrect answers', }, showMcqAnswer: { id: 'course.assessment.form.showMcqAnswer', defaultMessage: 'Show MCQ Submit Result', }, showMcqAnswerHint: { id: 'course.assessment.form.showMcqAnswerHint', defaultMessage: 'Students can try to submit answer to MCQ and get feedback until they get the right answer', }, showPrivate: { id: 'course.assessment.form.showPrivate', defaultMessage: 'Show private tests', }, showPrivateHint: { id: 'course.assessment.form.showPrivateHint', defaultMessage: 'Show private tests to students after the submission is graded and published (For programming questions)', }, showEvaluation: { id: 'course.assessment.form.showEvaluation', defaultMessage: 'Show evaluation tests', }, showEvaluationHint: { id: 'course.assessment.form.showEvaluationHint', defaultMessage: 'Show evaluation tests to students after the submission is graded and published (For programming questions)', }, hasPersonalTimes: { id: 'course.assessment.form.hasPersonalTimes', defaultMessage: 'Has personal times', }, hasPersonalTimesHint: { id: 'course.assessment.form.hasPersonalTimesHint', defaultMessage: 'Timings for this item will be automatically adjusted for users based on learning rate', }, affectsPersonalTimes: { id: 'course.assessment.form.affectsPersonalTimes', defaultMessage: 'Affects personal times', }, affectsPersonalTimesHint: { id: 'course.assessment.form.affectsPersonalTimesHint', defaultMessage: 'Student\'s submission time for this item will be taken into account \ when updating personal times for other items', }, published: { id: 'course.assessment.form.published', defaultMessage: 'Published', }, autogradedHint: { id: 'course.assessment.form.autogradedHint', defaultMessage: 'Automatically assign grade and experience points after assessment is \ submitted. Answers that are not auto-gradable will always receive the maximum grade.', }, modeSwitchingDisabled: { id: 'course.assessment.form.modeSwitchingHint', defaultMessage: 'Autograded ( Switch to autograded mode is not allowed as there are submissions \ for the assessment. )', }, skippable: { id: 'course.assessment.form.skippable', defaultMessage: 'Allow to skip steps', }, layout: { id: 'course.assessment.form.layout', defaultMessage: 'Layout', }, tabbedView: { id: 'course.assessment.form.tabbedView', defaultMessage: 'Tabbed View', }, singlePage: { id: 'course.assessment.form.singlePage', defaultMessage: 'Single Page', }, delayedGradePublication: { id: 'course.assessment.form.delayedGradePublication', defaultMessage: 'Delayed Grade Publication', }, delayedGradePublicationHint: { id: 'course.assessment.form.delayedGradePublicationHint', defaultMessage: "When delayed grade publication is enabled, gradings done by course staff will \ not be immediately shown to the student. To publish all gradings for this assessment, click \ on the 'Publish Grades' button on the top right of the submissions listing for this assessment.", }, passwordRequired: { id: 'course.assessment.form.passwordRequired', defaultMessage: 'At least one password is required', }, passwordProtection: { id: 'course.assessment.form.passwordProtection', defaultMessage: 'Password Protection', }, viewPasswordHint: { id: 'course.assessment.form.viewPasswordHint', defaultMessage: 'When assessment password is enabled, students are required to input the password in order to \ view/attempt the assessment.', }, viewPassword: { id: 'course.assessment.form.viewPassword', defaultMessage: 'Input Assessment Password', }, sessionPasswordHint: { id: 'course.assessment.form.sessionPasswordHint', defaultMessage: "When submission password is enabled, students are allowed to access their \ submission once. Further attempts at editing the submission using a different session are \ not allowed unless the password is provided by the staff. This can be used to prevent \ students from accessing each other's submissions in exams. You should NOT give the submission password \ to the students.", }, sessionPassword: { id: 'course.assessment.form.sessionPassword', defaultMessage: 'Input Submission Password', }, startEndValidationError: { id: 'course.assessment.form.startEndValidationError', defaultMessage: "Must be after 'Start At'", }, noTestCaseChosenError: { id: 'course.assessment.form.noTestCaseChosenError', defaultMessage: 'Select at least one type of test case', }, fetchTabFailure: { id: 'course.assessment.form.fetchCategoryFailure', defaultMessage: 'Loading of Tabs failed. Please refresh the page, or try again.', }, tab: { id: 'course.assessment.form.tab', defaultMessage: 'Tab', }, enableRandomization: { id: 'course.assessment.form.enable_randomization', defaultMessage: 'Enable Randomization', }, enableRandomizationHint: { id: 'course.assessment.form.enable_randomization_hint', defaultMessage: 'Enables randomized assignment of question bundles to students (per question group)', }, }); export default translations;
$(document).ready(function(){ //Gets the contestants and puts them into an array var contestants = $(".botb-contestent").toArray(); //Prints them out in a random order while(contestants.length > 0) { //Getting a random index number from array length var index = Math.floor(Math.random() * (contestants.length)); //Removing one element of array var shuffled_contestants = contestants.splice(index, 1); $('.botb-contestants-wrapper').append(shuffled_contestants[0]); } });
export default [ {id: 1, title: 'Akira'}, {id: 2, title: 'Blacksad'}, {id: 3, title: 'Calvin And Hobbes'} ];
(function() { 'use strict'; function MDLInputSearch() { function MDLInputSearchLink($scope, $element, $attrs) { } var directive = { restrict: 'EA', scope: { mdlInputSearch: '@', // id item: '=', type: '@', name: '@', label: '@' }, link: MDLInputSearchLink, templateUrl: 'modules/mdl_input/mdl_input_search/directives/MDLInputSearchDirectiveTemplate.html' }; return directive; } angular.module('AngularMDL.Modules.Input.Search', []) .directive('mdlInputSearch', MDLInputSearch); MDLInputSearch.$inject = []; })();
'use strict'; // Declare app level module which depends on views, and components angular.module('Cheersee', [ 'routes', 'landingpage', 'login', 'logout', 'authentication', 'storageservice', 'currentuser', 'feeds', 'allfeeds', 'userfeeds', 'relatedfeeds', 'mm.foundation', 'timer', 'userinfo', 'infinite-scroll', 'contests', 'markcontests', 'allcontests', 'participations', 'allparticipations', 'createcontest', 'createparticipation', 'marked', 'angularFileUpload', 'ownerfeeds', 'aws', 'participation_commend', 'contest_commend', 'btford.socket-io' ]) .run(function($rootScope, $state, Auth) { $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) { if (!Auth.authorize(toState.data.access)) { event.preventDefault(); $state.go('anon.login'); } }); }) .factory('socket', function(socketFactory) { var myIoSocket = io.connect('http://localhost:8080'); var mySocket = socketFactory({ ioSocket: myIoSocket }); return mySocket; });
require("copy-paste"); var inspect = require("util").inspect; var fs = require("fs"); module.exports = function(grunt) { var task = grunt.task; var file = grunt.file; var log = grunt.log; var verbose = grunt.verbose; var fail = grunt.fail; var option = grunt.option; var config = grunt.config; var template = grunt.template; var _ = grunt.util._; var templates = { doc: _.template(file.read("tpl/.docs.md")), img: _.template(file.read("tpl/.img.md")), fritzing: _.template(file.read("tpl/.fritzing.md")), doclink: _.template(file.read("tpl/.readme.doclink.md")), readme: _.template(file.read("tpl/.readme.md")), noedit: _.template(file.read("tpl/.noedit.md")), plugin: _.template(file.read("tpl/.plugin.md")), }; // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), docs: { files: ["programs.json"] }, nodeunit: { tests: [ "test/bootstrap.js", "test/board.js", "test/board-connection.js", "test/compass.js", "test/options.js", "test/board.pins.js", "test/board.component.js", "test/capabilities.js", // ------------------ "test/accelerometer.js", "test/animation.js", "test/button.js", "test/distance.js", "test/esc.js", "test/fn.js", "test/gyro.js", "test/imu.js", "test/lcd.js", "test/led.js", "test/ledcontrol.js", "test/motor.js", "test/pin.js", "test/piezo.js", "test/ping.js", "test/pir.js", "test/reflectancearray.js", "test/relay.js", "test/repl.js", "test/sensor.js", "test/servo.js", "test/shiftregister.js", "test/sonar.js", "test/stepper.js", "test/temperature.js", "test/switch.js", "test/wii.js" ] }, jshint: { options: { curly: true, eqeqeq: true, immed: true, latedef: false, newcap: false, noarg: true, sub: true, undef: true, boss: true, eqnull: true, node: true, strict: false, esnext: true, globals: { exports: true, document: true, $: true, Radar: true, WeakMap: true, window: true, copy: true } }, files: { src: [ "Gruntfile.js", "lib/**/!(johnny-five)*.js", "test/**/*.js", "eg/**/*.js", "wip/autobot-2.js" ] } }, jscs: { files: { src: [ "Gruntfile.js", "lib/**/!(johnny-five)*.js", "test/**/*.js", "eg/**/*.js", ] }, options: { config: ".jscsrc", requireCurlyBraces: [ "if", "else", "for", "while", "do", "try", "catch", ], disallowNewlineBeforeBlockStatements: true, requireSpaceBeforeBlockStatements: true, requireParenthesesAroundIIFE: true, requireSpacesInConditionalExpression: true, // requireSpaceBeforeKeywords: true, requireSpaceAfterKeywords: [ "if", "else", "switch", "case", "try", "catch", "do", "while", "for", "return", "typeof", "void", ], validateQuoteMarks: { mark: "\"", escape: true } } }, jsbeautifier: { files: ["lib/**/*.js", "eg/**/*.js", "test/**/*.js"], options: { js: { braceStyle: "collapse", breakChainedMethods: false, e4x: false, evalCode: false, indentChar: " ", indentLevel: 0, indentSize: 2, indentWithTabs: false, jslintHappy: false, keepArrayIndentation: false, keepFunctionIndentation: false, maxPreserveNewlines: 10, preserveNewlines: true, spaceBeforeConditional: true, spaceInParen: false, unescapeStrings: false, wrapLineLength: 0 } } }, watch: { src: { files: [ "Gruntfile.js", "lib/**/!(johnny-five)*.js", "test/**/*.js", "eg/**/*.js" ], tasks: ["default"], options: { interrupt: true, }, } } }); // Support running a single test suite: // grunt nodeunit:just:motor for example grunt.registerTask("nodeunit:just", function(file) { if (file) { grunt.config("nodeunit.tests", "test/" + file + ".js"); } grunt.task.run("nodeunit"); }); grunt.loadNpmTasks("grunt-contrib-watch"); grunt.loadNpmTasks("grunt-contrib-nodeunit"); grunt.loadNpmTasks("grunt-contrib-jshint"); grunt.loadNpmTasks("grunt-jsbeautifier"); grunt.loadNpmTasks("grunt-jscs"); grunt.registerTask("default", ["jshint", "jscs", "nodeunit"]); grunt.registerMultiTask("docs", "generate simple docs from examples", function() { // Concat specified files. var entries = JSON.parse(file.read(file.expand(this.data))); var readme = []; var tplType = "doc"; entries.forEach(function(entry) { var values, markdown, eg, md, png, fzz, title, hasPng, hasFzz, inMarkdown, filepath, fritzfile, fritzpath; var isHeading = Array.isArray(entry); var heading = isHeading ? entry[0] : null; if (isHeading) { tplType = entry.length === 2 ? entry[1] : "doc"; // Produces: // "### Heading\n" readme.push("\n### " + heading + "\n"); // TODO: figure out a way to have tiered subheadings // readme.push( // entry.reduce(function( prev, val, k ) { // // Produces: // // "### Board\n" // return prev + (Array(k + 4).join("#")) + " " + val + "\n"; // }, "") // ); } else { filepath = "eg/" + entry; eg = file.read(filepath); md = "docs/" + entry.replace(".js", ".md"); png = "docs/breadboard/" + entry.replace(".js", ".png"); fzz = "docs/breadboard/" + entry.replace(".js", ".fzz"); title = entry; markdown = []; // Generate a title string from the file name [ [/^.+\//, ""], [/\.js/, ""], [/\-/g, " "] ].forEach(function(args) { title = "".replace.apply(title, args); }); fritzpath = fzz.split("/"); fritzfile = fritzpath[fritzpath.length - 1]; inMarkdown = false; // Modify code in example to appear as it would if installed via npm eg = eg.replace(/\.\.\/lib\/|\.js/g, "") .split("\n").filter(function(line) { if (/@markdown/.test(line)) { inMarkdown = !inMarkdown; return false; } if (inMarkdown) { line = line.trim(); if (line) { markdown.push( line.replace(/^\/\//, "").trim() ); } // Filter out the markdown lines // from the main content. return false; } return true; }).join("\n"); hasPng = fs.existsSync(png); hasFzz = fs.existsSync(fzz); // console.log( markdown ); values = { title: _.titleize(title), command: "node " + filepath, example: eg, file: md, markdown: markdown.join("\n"), breadboard: hasPng ? templates.img({ png: png }) : "", fritzing: hasFzz ? templates.fritzing({ fzz: fzz }) : "" }; // Write the file to /docs/* file.write(md, templates[tplType](values)); // Push a rendered markdown link into the readme "index" readme.push(templates.doclink(values)); } }); // Write the readme with doc link index file.write("README.md", templates.noedit() + templates.readme({ doclinks: readme.join("") }) ); log.writeln("Docs created."); }); grunt.registerTask("bump", "Bump the version", function(version) { // THIS IS SLIGHTLY INSANE. // // // // I don't want the whole package.json file reformatted, // (because it makes the contributors section look insane) // so we're going to look at lines and update the version // line with either the next version of the specified version. // // It's either this or the whole contributors section // changes from 1 line per contributor to 3 lines per. // var pkg = grunt.file.read("package.json").split(/\n/).map(function(line) { var replacement, minor, data; if (/version/.test(line)) { data = line.replace(/"|,/g, "").split(":")[1].split("."); if (version) { replacement = version; } else { minor = +data[2]; data[2] = ++minor; replacement = data.join(".").trim(); } copy(replacement); return ' "version": "' + replacement + '",'; } return line; }); grunt.file.write("package.json", pkg.join("\n")); // TODO: // // - git commit with "vX.X.X" for commit message // - npm publish // // }); };
'use strict'; module.exports = { 'browserPort' : 3000, 'UIPort' : 3001, 'serverPort' : 3002, 'styles': { 'src' : 'app/styles/**/*.scss', 'dest': 'build/css', 'prodSourcemap': false, 'sassIncludePaths': [] }, 'scripts': { 'src' : 'app/js/**/*.js', 'dest': 'build/js' }, 'images': { 'src' : 'app/images/**/*', 'dest': 'build/images' }, 'fonts': { 'src' : ['app/fonts/**/*'], 'dest': 'build/fonts' }, 'views': { 'watch': [ 'app/index.html', 'app/views/**/*.html' ], 'src': 'app/views/**/*.html', 'dest': 'app/js' }, 'gzip': { 'src': 'build/**/*.{html,xml,json,css,js,js.map,css.map}', 'dest': 'build/', 'options': {} }, 'dist': { 'root' : 'build' }, 'browserify': { 'entries' : ['./app/js/main.js'], 'bundleName': 'main.js', 'prodSourcemap' : false }, 'test': { 'karma': process.cwd() + '/test/karma.conf.js', 'protractor': 'test/protractor.conf.js' } };
/** * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'filetools', 'es', { loadError: 'Ha ocurrido un error durante la lectura del archivo.', networkError: 'Error de red ocurrido durante carga de archivo.', httpError404: 'Un error HTTP ha ocurrido durante la carga del archivo (404: Archivo no encontrado).', httpError403: 'Un error HTTP ha ocurrido durante la carga del archivo (403: Prohibido).', httpError: 'Error HTTP ocurrido durante la carga del archivo (Estado del error: %1).', noUrlError: 'URL cargada no está definida.', responseError: 'Respueta del servidor incorrecta.' } );
// Generated by CoffeeScript 1.12.6 /* * Modular spec options parsing */ (function() { 'use strict'; var object; object = require('../common/object'); module.exports = { collect: function(params, moduleName, moduleParams, options) { var i, len, option; this.params = params; this.moduleName = moduleName; this.moduleParams = moduleParams; for (i = 0, len = options.length; i < len; i++) { option = options[i]; this.parse(option); } return this.moduleParams; }, get: function(option) { var cursor, i, len, node, xPath; xPath = this.moduleName.split('.'); xPath.unshift(option); cursor = this.params; for (i = 0, len = xPath.length; i < len; i++) { node = xPath[i]; if (typeof cursor[node] === 'undefined') { return false; } cursor = cursor[node]; } return cursor; }, getModuleParams: function(codeModules, moduleName, params) { return this.collect(params, moduleName, { path: codeModules[moduleName] }, ['title:moduleTitles', 'methods', 'initial', ['use']]); }, getSet: function(option) { var optionValue; optionValue = object.toArray(this.params[option], 'string'); if (!Array.isArray(optionValue)) { return false; } return optionValue.indexOf(this.moduleName) !== -1; }, parse: function(option) { if (Array.isArray(option)) { return this.parseSet(option); } return this.parseSingle(option); }, parseRequired: function(option, required) { if (option) { return option; } if (required) { return this.moduleName; } return option; }, parseSet: function(options) { var i, len, option; for (i = 0, len = options.length; i < len; i++) { option = options[i]; this.moduleParams[option] = this.getSet(option); } return true; }, parseSingle: function(option) { var optionName, paramsKey, paramsOption, required; option = option.split(':'); paramsKey = option[0], optionName = option[option.length - 1]; paramsOption = this.get(optionName); required = option.length > 1; paramsOption = this.parseRequired(paramsOption, required); if (paramsOption) { return this.moduleParams[paramsKey] = paramsOption; } } }; }).call(this);
var app = require('express')(), server = require('http').Server(app), io = require('socket.io')(server), cote = require('cote'); app.get('/', function (req, res) { console.log(`${req.ip} requested end-user interface`); res.sendFile(__dirname + '/index.html'); }); server.listen(5001); new cote.Sockend(io, { name: 'end-user sockend server' });
module.exports = function(key, initValue, dataSources, rename){ var dataSource = dataSources.get(key); var newName = rename ? rename : key + "Delta"; var prevVal = initValue ? initValue : null; var hit = (prevVal !== null); var newSource = dataSource.map(function(val){ var delta; if(prevVal === null){ prevVal = val; } delta = val - prevVal; prevVal = val; return delta; }).filter(function(){ if(hit){ return hit; } else { hit = true; return false; } }); dataSources.get("creationMap").set(newName, key, [key, initValue], "delta"); dataSources.set(newName, newSource); } module.exports.initialize = function(dataSources){ dataSources.get("translations").set("delta", module.exports); }
'use strict'; // Setting up route angular.module('articles').config(['$stateProvider', function ($stateProvider) { // Articles state routing $stateProvider .state('articles', { abstract: true, url: '/articles', template: '<ui-view/>' }) .state('articles.list', { url: '', templateUrl: 'modules/articles/client/views/list-articles.client.view.html' }) .state('articles.create', { url: '/create', templateUrl: 'modules/articles/client/views/create-lifemaps.client.view.html', data: { roles: ['user', 'admin'] } }) .state('articles.view', { url: '/:articleId', templateUrl: 'modules/articles/client/views/view-article.client.view.html' }) .state('articles.edit', { url: '/:articleId/edit', templateUrl: 'modules/articles/client/views/edit-article.client.view.html', data: { roles: ['user', 'admin'] } }); } ]);
const { isFunction } = require('lodash'); exports.create = function createCoercionFor(coercion, attributeDefinition) { return { coerce(value) { if (value === undefined) { return; } if (value === null) { return getNullableValue(coercion, attributeDefinition); } if (coercion.isCoerced(value, attributeDefinition)) { return value; } return coercion.coerce(value, attributeDefinition); }, }; }; exports.disabled = { coerce: (value) => value, }; const getNullableValue = (coercion, attributeDefinition) => needsNullableInitialization(attributeDefinition) ? getNullValue(coercion) : null; const needsNullableInitialization = (attributeDefinition) => !attributeDefinition.options.required && !attributeDefinition.options.nullable; const getNullValue = (coercion) => isFunction(coercion.nullValue) ? coercion.nullValue() : coercion.nullValue;
exports.errConst = { errCode:{ nologin:1, }, errMsg:{ nologin:"未登录", } }
$context.section('Постраничный вывод'); //= require pagination-basic
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { localize } from '../../../nls'; import { Emitter } from '../../../base/common/event'; import { basename } from '../../../base/common/resources'; import { dispose, DisposableStore } from '../../../base/common/lifecycle'; import * as strings from '../../../base/common/strings'; import { defaultGenerator } from '../../../base/common/idGenerator'; import { Range } from '../../common/core/range'; var OneReference = /** @class */ (function () { function OneReference(isProviderFirst, parent, _range, _rangeCallback) { this.isProviderFirst = isProviderFirst; this.parent = parent; this._range = _range; this._rangeCallback = _rangeCallback; this.id = defaultGenerator.nextId(); } Object.defineProperty(OneReference.prototype, "uri", { get: function () { return this.parent.uri; }, enumerable: true, configurable: true }); Object.defineProperty(OneReference.prototype, "range", { get: function () { return this._range; }, set: function (value) { this._range = value; this._rangeCallback(this); }, enumerable: true, configurable: true }); Object.defineProperty(OneReference.prototype, "ariaMessage", { get: function () { return localize('aria.oneReference', "symbol in {0} on line {1} at column {2}", basename(this.uri), this.range.startLineNumber, this.range.startColumn); }, enumerable: true, configurable: true }); return OneReference; }()); export { OneReference }; var FilePreview = /** @class */ (function () { function FilePreview(_modelReference) { this._modelReference = _modelReference; } FilePreview.prototype.dispose = function () { this._modelReference.dispose(); }; FilePreview.prototype.preview = function (range, n) { if (n === void 0) { n = 8; } var model = this._modelReference.object.textEditorModel; if (!model) { return undefined; } var startLineNumber = range.startLineNumber, startColumn = range.startColumn, endLineNumber = range.endLineNumber, endColumn = range.endColumn; var word = model.getWordUntilPosition({ lineNumber: startLineNumber, column: startColumn - n }); var beforeRange = new Range(startLineNumber, word.startColumn, startLineNumber, startColumn); var afterRange = new Range(endLineNumber, endColumn, endLineNumber, 1073741824 /* MAX_SAFE_SMALL_INTEGER */); var before = model.getValueInRange(beforeRange).replace(/^\s+/, ''); var inside = model.getValueInRange(range); var after = model.getValueInRange(afterRange).replace(/\s+$/, ''); return { value: before + inside + after, highlight: { start: before.length, end: before.length + inside.length } }; }; return FilePreview; }()); export { FilePreview }; var FileReferences = /** @class */ (function () { function FileReferences(parent, uri) { this.parent = parent; this.uri = uri; this.children = []; } FileReferences.prototype.dispose = function () { dispose(this._preview); this._preview = undefined; }; Object.defineProperty(FileReferences.prototype, "preview", { get: function () { return this._preview; }, enumerable: true, configurable: true }); Object.defineProperty(FileReferences.prototype, "failure", { get: function () { return this._loadFailure; }, enumerable: true, configurable: true }); Object.defineProperty(FileReferences.prototype, "ariaMessage", { get: function () { var len = this.children.length; if (len === 1) { return localize('aria.fileReferences.1', "1 symbol in {0}, full path {1}", basename(this.uri), this.uri.fsPath); } else { return localize('aria.fileReferences.N', "{0} symbols in {1}, full path {2}", len, basename(this.uri), this.uri.fsPath); } }, enumerable: true, configurable: true }); FileReferences.prototype.resolve = function (textModelResolverService) { var _this = this; if (this._resolved) { return Promise.resolve(this); } return Promise.resolve(textModelResolverService.createModelReference(this.uri).then(function (modelReference) { var model = modelReference.object; if (!model) { modelReference.dispose(); throw new Error(); } _this._preview = new FilePreview(modelReference); _this._resolved = true; return _this; }, function (err) { // something wrong here _this.children.length = 0; _this._resolved = true; _this._loadFailure = err; return _this; })); }; return FileReferences; }()); export { FileReferences }; var ReferencesModel = /** @class */ (function () { function ReferencesModel(links, title) { var _this = this; this._disposables = new DisposableStore(); this.groups = []; this.references = []; this._onDidChangeReferenceRange = new Emitter(); this.onDidChangeReferenceRange = this._onDidChangeReferenceRange.event; this._links = links; this._title = title; // grouping and sorting var providersFirst = links[0]; links.sort(ReferencesModel._compareReferences); var current; for (var _i = 0, links_1 = links; _i < links_1.length; _i++) { var link = links_1[_i]; if (!current || current.uri.toString() !== link.uri.toString()) { // new group current = new FileReferences(this, link.uri); this.groups.push(current); } // append, check for equality first! if (current.children.length === 0 || !Range.equalsRange(link.range, current.children[current.children.length - 1].range)) { var oneRef = new OneReference(providersFirst === link, current, link.targetSelectionRange || link.range, function (ref) { return _this._onDidChangeReferenceRange.fire(ref); }); this.references.push(oneRef); current.children.push(oneRef); } } } ReferencesModel.prototype.dispose = function () { dispose(this.groups); this._disposables.dispose(); this._onDidChangeReferenceRange.dispose(); this.groups.length = 0; }; ReferencesModel.prototype.clone = function () { return new ReferencesModel(this._links, this._title); }; Object.defineProperty(ReferencesModel.prototype, "title", { get: function () { return this._title; }, enumerable: true, configurable: true }); Object.defineProperty(ReferencesModel.prototype, "isEmpty", { get: function () { return this.groups.length === 0; }, enumerable: true, configurable: true }); Object.defineProperty(ReferencesModel.prototype, "ariaMessage", { get: function () { if (this.isEmpty) { return localize('aria.result.0', "No results found"); } else if (this.references.length === 1) { return localize('aria.result.1', "Found 1 symbol in {0}", this.references[0].uri.fsPath); } else if (this.groups.length === 1) { return localize('aria.result.n1', "Found {0} symbols in {1}", this.references.length, this.groups[0].uri.fsPath); } else { return localize('aria.result.nm', "Found {0} symbols in {1} files", this.references.length, this.groups.length); } }, enumerable: true, configurable: true }); ReferencesModel.prototype.nextOrPreviousReference = function (reference, next) { var parent = reference.parent; var idx = parent.children.indexOf(reference); var childCount = parent.children.length; var groupCount = parent.parent.groups.length; if (groupCount === 1 || next && idx + 1 < childCount || !next && idx > 0) { // cycling within one file if (next) { idx = (idx + 1) % childCount; } else { idx = (idx + childCount - 1) % childCount; } return parent.children[idx]; } idx = parent.parent.groups.indexOf(parent); if (next) { idx = (idx + 1) % groupCount; return parent.parent.groups[idx].children[0]; } else { idx = (idx + groupCount - 1) % groupCount; return parent.parent.groups[idx].children[parent.parent.groups[idx].children.length - 1]; } }; ReferencesModel.prototype.nearestReference = function (resource, position) { var nearest = this.references.map(function (ref, idx) { return { idx: idx, prefixLen: strings.commonPrefixLength(ref.uri.toString(), resource.toString()), offsetDist: Math.abs(ref.range.startLineNumber - position.lineNumber) * 100 + Math.abs(ref.range.startColumn - position.column) }; }).sort(function (a, b) { if (a.prefixLen > b.prefixLen) { return -1; } else if (a.prefixLen < b.prefixLen) { return 1; } else if (a.offsetDist < b.offsetDist) { return -1; } else if (a.offsetDist > b.offsetDist) { return 1; } else { return 0; } })[0]; if (nearest) { return this.references[nearest.idx]; } return undefined; }; ReferencesModel.prototype.referenceAt = function (resource, position) { for (var _i = 0, _a = this.references; _i < _a.length; _i++) { var ref = _a[_i]; if (ref.uri.toString() === resource.toString()) { if (Range.containsPosition(ref.range, position)) { return ref; } } } return undefined; }; ReferencesModel.prototype.firstReference = function () { for (var _i = 0, _a = this.references; _i < _a.length; _i++) { var ref = _a[_i]; if (ref.isProviderFirst) { return ref; } } return this.references[0]; }; ReferencesModel._compareReferences = function (a, b) { return strings.compare(a.uri.toString(), b.uri.toString()) || Range.compareRangesUsingStarts(a.range, b.range); }; return ReferencesModel; }()); export { ReferencesModel };
var $M = require("@effectful/debugger"), $ret = $M.ret, $retA = $M.retA, $unhandled = $M.unhandled, $unhandledA = $M.unhandledA, $raise = $M.raise, $brk = $M.brk, $mcall = $M.mcall, $m = $M.module("file.js", null, typeof module === "undefined" ? null : module, null, "$", { __webpack_require__: typeof __webpack_require__ !== "undefined" && __webpack_require__ }, null), $s$1 = [{ main: [1, "3:15-3:19"] }, null, 0], $s$2 = [{ arg1: [1, "3:20-3:24"], items: [2, "4:8-4:13"], abandoned: [3, "5:6-5:15"] }, $s$1, 1], $s$3 = [{}, $s$2, 2], $s$4 = [{ item: [1, "7:6-7:10"] }, $s$3, 2], $s$5 = [{ existingItem: [2, "10:16-10:28"] }, $s$4, 2], $s$6 = [{ _ref: [1, null], productId: [2, "11:15-11:24"] }, $s$5, 3], $m$0 = $M.fun("m$0", "file.js", null, null, [], 0, 2, "1:0-22:0", 32, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $l[1] = $m$1($); $.goto = 1; $brk(); $.state = 1; case 1: $.goto = 3; $mcall("profile", M, "es"); continue; case 2: $.goto = 3; return $unhandled($.error); case 3: return $ret($.result); default: throw new Error("Invalid state"); } }, null, null, 0, [[4, "1:0-1:16", $s$1], [2, "1:0-1:15", $s$1], [16, "22:0-22:0", $s$1], [16, "22:0-22:0", $s$1]]), $m$1 = $M.fun("m$1", "main", null, $m$0, ["arg1"], 0, 5, "3:0-21:1", 1, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $.goto = 1; $brk(); $.state = 1; case 1: $l[2] = []; $.goto = 2; $brk(); $.state = 2; case 2: $l[3] = false; $.goto = 3; $brk(); $.state = 3; case 3: $l = $.$ = [$l, void 0, void 0]; $.state = 4; case 4: $.goto = 5; $brk(); $.state = 5; case 5: $l[1] = $l[0][2][0]; $.goto = 6; $brk(); $.state = 6; case 6: switch (signal.type) { case "timeout": $.state = 7; break; case "checkout": $.goto = 13; continue; default: $.goto = 14; continue; } case 7: $.goto = 8; $brk(); $.state = 8; case 8: $.goto = 9; $p = $mcall("find", $l[0][2], $m$2($)); $.state = 9; case 9: $l[2] = $p; $.goto = 10; $brk(); $.state = 10; case 10: if ($l[0][3]) { $.state = 11; } else { $.goto = 12; continue; } case 11: $l[0][4] = 19; $.goto = 17; $brk(); continue; case 12: $.goto = 14; $brk(); continue; case 13: $l[0][4] = 19; $.goto = 17; $brk(); continue; case 14: $.goto = 15; $brk(); $.state = 15; case 15: $l = $.$ = [$l[0], void 0, void 0]; $.goto = 4; continue; case 16: return $raise($.error); case 17: $l = $.$ = $l[0]; $.goto = $l[4]; continue; case 18: $.goto = 19; return $unhandledA($.error); case 19: return $retA($.result); default: throw new Error("Invalid state"); } }, function ($, $l) { switch ($.state) { case 15: case 14: case 13: case 12: case 11: case 10: case 9: case 8: case 7: case 6: case 5: case 4: $.goto = 17; $l[0][4] = 16; break; default: $.goto = 18; } }, function ($, $l) { switch ($.state) { case 15: case 14: case 13: case 12: case 11: case 10: case 9: case 8: case 7: case 6: case 5: case 4: $l[0][4] = 19; $.goto = 17; break; default: $.goto = 19; break; } }, 1, [[4, "4:2-4:18", $s$2], [4, "5:2-5:24", $s$2], [4, "6:2-20:3", $s$2], [0, null, $s$2], [4, "7:2-7:22", $s$4], [4, "8:4-19:5", $s$4], [0, null, $s$3], [4, "10:10-12:12", $s$5], [2, "10:31-12:11", $s$5], [4, "13:8-15:9", $s$5], [0, null, $s$3], [4, "14:10-14:17", $s$5], [4, "16:8-16:14", $s$5], [4, "18:8-18:15", $s$5], [36, "20:3-20:3", $s$3], [0, null, $s$3], [0, null, $s$2], [0, null, $s$2], [16, "21:1-21:1", $s$2], [16, "21:1-21:1", $s$2]]), $m$2 = $M.fun("m$2", null, null, $m$1, ["_ref"], 0, 3, "11:12-11:59", 4, function ($, $l, $p) { for (;;) switch ($.state = $.goto) { case 0: $.goto = 1; $brk(); $.state = 1; case 1: $l[2] = $l[1].productId; $.goto = 2; $brk(); $.state = 2; case 2: $.result = $l[2] === $l[0][1].productId; $.goto = 4; continue; case 3: $.goto = 4; return $unhandled($.error); case 4: return $ret($.result); default: throw new Error("Invalid state"); } }, null, null, 3, [[4, "11:15-11:24", $s$6], [4, "11:31-11:59", $s$6], [0, "11:31-11:59", $s$6], [16, "11:59-11:59", $s$6], [16, "11:59-11:59", $s$6]]); $M.moduleExports();
import gulp from "gulp"; import cp from "child_process"; import gutil from "gulp-util"; import postcss from "gulp-postcss"; import cssImport from "postcss-import"; import cssnext from "postcss-cssnext"; import BrowserSync from "browser-sync"; import webpack from "webpack"; import webpackConfig from "./webpack.conf"; const browserSync = BrowserSync.create(); const hugoBin = `./bin/hugo_0.17_${process.platform}_amd64${process.platform === "windows" ? ".exe" : ""}`; const defaultArgs = ["-d", "../dist", "-s", "site", "-v"]; gulp.task("hugo", (cb) => buildSite(cb)); gulp.task("hugo-preview", (cb) => buildSite(cb, ["--buildDrafts", "--buildFuture"])); gulp.task("build", ["css", "js", "hugo"]); gulp.task("build-preview", ["css", "js", "hugo-preview"]); gulp.task("css", () => ( gulp.src("./src/css/*.css") .pipe(postcss([cssnext(), cssImport({from: "./src/css/main.css"})])) .pipe(gulp.dest("./dist/css")) .pipe(browserSync.stream()) )); gulp.task("js", (cb) => { const myConfig = Object.assign({}, webpackConfig); webpack(myConfig, (err, stats) => { if (err) throw new gutil.PluginError("webpack", err); gutil.log("[webpack]", stats.toString({ colors: true, progress: true })); browserSync.reload(); cb(); }); }); gulp.task("server", ["hugo", "css", "js"], () => { browserSync.init({ server: { baseDir: "./dist" } }); gulp.watch("./src/js/**/*.js", ["js"]); gulp.watch("./src/css/**/*.css", ["css"]); gulp.watch("./site/**/*", ["hugo"]); }); function buildSite(cb, options) { const args = options ? defaultArgs.concat(options) : defaultArgs; return cp.spawn(hugoBin, args, {stdio: "inherit"}).on("close", (code) => { if (code === 0) { browserSync.reload(); cb(); } else { browserSync.notify("Hugo build failed :("); cb("Hugo build failed"); } }); }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const path = require("path"); const glob = require("glob"); const webpack = require("webpack"); const config_1 = require("../config"); const karma_webpack_emitless_error_1 = require("../../plugins/karma-webpack-emitless-error"); /** * Enumerate loaders and their dependencies from this file to let the dependency validator * know they are used. * * require('istanbul-instrumenter-loader') * */ function getTestConfig(testConfig) { const configPath = config_1.CliConfig.configFilePath(); const projectRoot = path.dirname(configPath); const appConfig = config_1.CliConfig.fromProject().config.apps[0]; const extraRules = []; if (testConfig.codeCoverage && config_1.CliConfig.fromProject()) { const codeCoverageExclude = config_1.CliConfig.fromProject().get('test.codeCoverage.exclude'); let exclude = [ /\.(e2e|spec)\.ts$/, /node_modules/ ]; if (codeCoverageExclude) { codeCoverageExclude.forEach((excludeGlob) => { const excludeFiles = glob .sync(path.join(projectRoot, excludeGlob), { nodir: true }) .map(file => path.normalize(file)); exclude.push(...excludeFiles); }); } extraRules.push({ test: /\.(js|ts)$/, loader: 'istanbul-instrumenter-loader', enforce: 'post', exclude }); } return { devtool: testConfig.sourcemaps ? 'inline-source-map' : 'eval', entry: { test: path.resolve(projectRoot, appConfig.root, appConfig.test) }, module: { rules: [].concat(extraRules) }, plugins: [ new webpack.SourceMapDevToolPlugin({ filename: null, test: /\.(ts|js)($|\?)/i // process .js and .ts files only }), new karma_webpack_emitless_error_1.KarmaWebpackEmitlessError() ] }; } exports.getTestConfig = getTestConfig; //# sourceMappingURL=/users/mikkeldamm/forked-repos/angular-cli/models/webpack-configs/test.js.map
/*global describe,it,expect,$$,element,browser,by*/ describe('ShowView', function () { 'use strict'; var hasToLoad = true; beforeEach(function() { if (hasToLoad) { browser.get(browser.baseUrl + '#/posts/show/1'); hasToLoad = false; } }); describe('ChoiceField', function() { it('should render as a label when choices is an array', function () { $$('.ng-admin-field-category').then(function (fields) { expect(fields[0].getText()).toBe('Tech'); }); }); it('should render as a label when choices is a function', function () { $$('.ng-admin-field-subcategory').then(function (fields) { expect(fields[0].getText()).toBe('Computers'); }); }); }); describe('ReferencedListField', function() { it('should render as a datagrid', function () { $$('.ng-admin-field-comments th').then(function (inputs) { expect(inputs.length).toBe(2); expect(inputs[0].getAttribute('class')).toBe('ng-scope ng-admin-column-id'); expect(inputs[1].getAttribute('class')).toBe('ng-scope ng-admin-column-body'); }); }); }); });
define(function(require) { 'use strict'; var Backbone = require('backbone'), homeTemplate = require('text!templates/homeTpl.html'); return Backbone.View.extend({ el: 'body', initialize: function() { this.render(); }, render: function() { this.$el.html(homeTemplate); return this; } }); });
'use strict'; var config = require('../../../config/api') , anomaly = require('../anomaly-detection'); module.exports = function() { //services require('./services/email-service')(config, anomaly, function(template, transport) { var locals = config.locals; template.render(locals, function(err, result) { if(err) { return console.error(err); } var async = require('async'); var recepients = locals.recepients.split(','); async.each(recepients, function(to, callback) { transport.sendMail({ to: to, subject: 'Sudden increase on freshdesk tickets!', html: result.html }, function(err, info) { if(err) { return console.error(err); } console.log('Message %s sent: %s', info.messageId, info.response); }); }) }); }); }
var restify = require('restify'); var builder = require('botbuilder'); var Firebase = require("firebase"); var myFirebaseRef = new Firebase("https://vive.firebaseio.com/Users/"); var curData = []; var lastUsedName = ""; myFirebaseRef.on('value', function(snapshot) { curData=snapshot.val(); }); var NodeGeocoder = require('node-geocoder'); var request = require("request"); var client = require('twilio')('AC59a2a7d898b46d6b39fa102380816d40', '7f53052dbd2df38c182d0e01331c6f7f'); // Get secrets from server environment var botConnectorOptions = { appId: process.env.BOTFRAMEWORK_APPID, appSecret: process.env.BOTFRAMEWORK_APPSECRET }; // Create bot var bot = new builder.BotConnectorBot(botConnectorOptions); //var bot = new builder.TextBot(); // Setup Restify Server var server = restify.createServer(); // Handle Bot Framework messages server.post('/api/messages', bot.verifyBotFramework(), bot.listen()); // Serve a static web page server.get(/.*/, restify.serveStatic({ 'directory': '.', 'default': 'index.html' })); server.listen(process.env.port || 3978, function () { console.log('%s listening to %s', server.name, server.url); }); var dialog = new builder.LuisDialog('https://api.projectoxford.ai/luis/v1/application?id=dbc0fee8-f1bb-4932-a453-98ca65ba1b2c&subscription-key=eea3e95656e74c91b1d45b283cc6a91c'); bot.add('/', dialog); dialog.onDefault("I am sorry I didn't understand."); dialog.on('Greeting', [ function (session) { builder.Prompts.choice(session, "Hey " + curData[lastUsedName]['name'] + ". Is there an emergency?", "Yes|No"); //next(); }, function (session, results) { if(results.response.entity == "Yes"){ builder.Prompts.text(session,"Now recording your emergency status. What city are you in?"); } else{ session.send("Good! Do you need anything else?"); session.endDialog(); } }, function(session, results) { var city = results.response; curData[lastUsedName]['number'] // phone number var options = { provider: 'google', // Optional depending on the providers httpAdapter: 'https', // Default apiKey: 'AIzaSyAbhgQXE4PijQum7zG1jwcpFhGqkujSH1k', // for Mapquest, OpenCage, Google Premier formatter: null // 'gpx', 'string', ... }; var geocoder = NodeGeocoder(options); // Using callback geocoder.geocode(city, function(err, res) { // console.log(res); var countryCode = res[0].countryCode; // console.log('http://emergencynumberapi.com/api/country/'+countryCode); request('http://emergencynumberapi.com/api/country/'+countryCode, function (error, response, body) { if (!error && response.statusCode == 200) { //console.log(body) // Show the HTML for the Google homepage. var json = JSON.parse(body); var dispatchNumber = json.data.dispatch.all[0]; if(dispatchNumber == "") { dispatchNumber = json.data.police.all[0]; } client.sendMessage({ to:'+16303019617', // Any number Twilio can deliver to from: '+12132701371 ', // A number you bought from Twilio and can use for outbound communication body: '\n' + 'Name: ' + curData[lastUsedName]['name'] + '\n' + 'Current City: ' + city + '\n' + "Sex: " + curData[lastUsedName]['sex'] + '\n' + "DOB: " + curData[lastUsedName]['DoB'] + '\n' + "Medical Conditions: " + curData[lastUsedName]['medicalConditions'] + '\n' + "Local Number: " + curData[lastUsedName]['number'] + '\n' + "Allergies: " + curData['medicationAllergies'] // body of the SMS message }, function(err, responseData) { //this function is executed when a response is received from Twilio session.send("Your health and contact information has been sent to a local dispatcher at number " + dispatchNumber + " in the city " + city + ". You will receive a phone call shortly from emergency services."); if (!err) { // "err" is an error received during the request, if any // "responseData" is a JavaScript object containing data received from Twilio. // A sample response from sending an SMS message is here (click "JSON" to see how the data appears in JavaScript): // http://www.twilio.com/docs/api/rest/sending-sms#example-1 console.log(responseData.from); // outputs "+14506667788" console.log(responseData.body); // outputs "word to your mother." } else { console.log(err); } }); } }) }); } //, // function (session, results) { // session.send("I am here to help you."); // } ]); dialog.on('GetInformation', [ function (session, args, next) { //session.send("getting information for ya " ); // session.send(JSON.stringify(session)); var organization = builder.EntityRecognizer.findEntity(args.entities, 'Organization'); var medical = builder.EntityRecognizer.findEntity(args.entities, 'Disaster::Medical'); var criminal = builder.EntityRecognizer.findEntity(args.entities, 'Disaster::Criminal'); var environmental = builder.EntityRecognizer.findEntity(args.entities, 'Disaster::Environmental'); if(organization){ // response: organization.entity; if(organization.entity === "police" ){ session.send("The nearest police station to you is..."); } else if(organization.entity === "fire station" ){ session.send("The nearest fire station to you is..."); } else if(organization.entity === "hospital" ){ session.send("The nearest hospital to you is..."); } else if(organization.entity === "embassy" ){ session.send("The nearest embassy to you is..."); } session.endDialog(); } else if(medical){ if(medical.entity === "heart attack" ){ console.log("heart attack"); session.beginDialog('/HeartAttack'); } else if(medical.entity === "broken bone" ){ session.send("It is hard to tell a dislocated joint from a broken bone. However, both are emergency situations, " + "and the basic first aid steps are the same. Symptoms of a broken bone include: 1) A visibly out-of-place or misshapen limb or joint 2) Swelling, bruising, or bleeding 3) Intense pain 4) Numbness and tingling" + "5) Broken skin with bone protruding 6) Limited mobility or inability to move a limb"); } else if(medical.entity === "not breathing" ){ session.send("If an adult is unconscious and not breathing, you’ll need to do CPR (which is short for cardiopulmonary resuscitation). " + "CPR involves giving someone a combination of chest compressions and rescue breaths to keep their heart and " + "circulation going to try to save their life. If they start breathing normally again, stop CPR and put them in the " + "recovery position. Step 1: Check their airway. If they are unconscious, open their airway. Step 2: Check their breathing. " + "If they are not breathing, you need to start CPR (cardiopulmonary resuscitation – a combination of chest pressure and rescue breaths) straight away." + "Step 3: Call for help and start CPR. Step 4: Give chest compressions. Step 5: Give a rescue breath."); } else if(medical.entity === "suicide" ){ session.send("A suicidal person may not ask for help, but that doesn't mean that help isn't wanted. Most people who commit suicide " + "don't want to die—they just want to stop hurting. Suicide prevention starts with recognizing the warning signs and taking them seriously. " + "If you think a friend or family member is considering suicide, you might be afraid to bring up the subject. But talking openly about " + "suicidal thoughts and feelings can save a life. If you're thinking about committing suicide, please read Suicide Help or call 1-800-273-TALK in the U.S.!" + "To find a suicide helpline outside the U.S., visit IASP or Suicide.org."); } else if(medical.entity === "gun wound" ){ session.send("In most circumstances, you don’t want to remove an implanted bullet. It’s almost impossible to find, and it may actually " + "be corking up a big blood vessel. Thousands of military members live daily with shrapnel in their bodies. Unless there’s initial " + "infection from the wound itself, the body adapts to most metal without much serious problem. Gunshot wounds can run the gamut. " + "Some people are too severely injured to save. Get expert treatment as soon as possible."); } else if(medical.entity === "burn" ){ session.send("Most minor burns will heal on their own, and home treatment is usually all that is needed to relieve your symptoms and " + "promote healing. But if you suspect you may have a more severe injury, use first-aid measures while you arrange for an evaluation " + "by your doctor."); } session.endDialog(); // session.endDialog(); //session.send( "Here is what I know about " + medical.entity); //next({ response: medical.entity }); } else if(criminal){ if(criminal.entity === "missing person" ){ session.send("In the case of a missing person, contact your nearest police station and report a missing persons case. Ask that the " + "missing persons case report be sent to the FBI’s National Crime Information Center (https://www.fbi.gov/about-us/cjis/ncic). and " + "the National Missing and Unidentified Persons System (http://www.namus.gov/). If you believe the missing person may be dead, " + "ask if the coroner or medical examiner can take a DNA sample from a family member or the person’s belongings to be compared " + "against the DNA of any unidentified remains."); } else if(criminal.entity === "robbed" ){ session.send("In the case of a robbery, stay calm, consider that the safety of you, your customers, and your staff is paramount, " + "and remember as many details as possible. When the incident is over, do not confer with other witnesses and avoid re-watching " + "the surveillance footage as this may affect your memory. Remember that anything touched or left by the robbers is evidence so " + "do not touch anything touched or left by offenders. Fingerprints and DNA can lead to a successful prosecution."); } else if(criminal.entity === "assaulted" ){ session.send("Assault is a physical attack or a threat that causes fear of an attack. Victims of assault may be attacked by one or " + "more people. An assault may include one or more types of harm, such as pushing, shoving, slapping, punching, or kicking. " + "It may also include the use of weapons like knives, sticks, bottles, or bats. Common injuries from an assault include bruises, " + "black eyes, cuts, scratches, and broken bones. Victims may even be killed during an assault. Even if the attack results in no " + "physical injury to the victim, it still can be considered an assault.Assault can happen to anyone. Most teen victims of " + "assault report that they know who attacked them, and often the attacker is a family member, friend, or someone the victim " + "knows from school or the neighborhood. If someone assaults you, it is important to tell an adult you trust and to contact " + "the police. Being assaulted is not your fault. It is important to remember that assault is a crime, and as an assault victim, " + "you do not have to deal with this alone. There are people in your community who can help you."); } else if(criminal.entity === "terrorist attack" ){ session.beginDialog('/TerroristAttack'); } session.endDialog(); } else if(environmental) { if(environmental.entity === "tornado" ){ session.beginDialog('/Tornado'); } else if(environmental.entity === "hurricane" ){ session.send("To stay safe in a home during a hurricane, stay inside and away from windows, skylights and glass doors. Find a safe area in the " + "home (an interior room, a closet or bathroom on the lower level). If flooding threatens a home, turn off electricity at the main breaker." + "If a home loses power, turn off major appliances such as the air conditioner and water heater to reduce damage. Do not use electrical appliances, " + "including your computer. Do not go outside. If the eye of the storm passes over your area, there will be a short period of calm, but at the other " + "side of the eye, the wind speed rapidly increases to hurricane force and will come from the opposite direction. Also, do not go outside to see " + "what the wind feels like. It is too easy to be hit by flying debris. Beware of lightning. Stay away from electrical equipment. Don't use the " + "phone or take a bath/shower during the storm."); } else if(environmental.entity === "earthquake" ){ session.send("There are several common beliefs as to earthquake safety. Many people think having bottled water on hand is a good idea. " + "That’s true, as long as you have enough. Many are certain that standing in a doorway during the shaking is a good idea. That’s false," + "unless you live in an unreinforced adode structure; otherwise, you're more likely to be hurt by the door swinging wildly in a doorway" + "or trampled by people trying to hurry outside if you’re in a public place."); } else if(environmental.entity === "fire" ){ session.send("The average response time for the fire service is 14 minutes. Therefore, you are on your own and must function as " + "your own fire fighter for the first several minutes. 'Rescue, alarm, extinguish' is a simple rule to help you remember what to do " + "in the event of a fire. You will have to determine the order in which you address these points, depending on your assessment of " + "the situation."); } session.endDialog(); //session.send( "Here is what I know about " + environmental.entity); //next({ response: environmental.entity }); } else{ session.send("I couldn't find any relevant information :("); session.endDialog(); //next({ response: organization.entity }); } } // function (session, results) { // if (results.response) { // if(results.response == "police") // { // } // session.send("Ok... Added the '%s' task.", results.response); // } // }, ]); bot.add('/TerroristAttack', [ function (session) { builder.Prompts.choice(session, "What about terrorist attacks would you like to learn?", "Summary|How to Prepare|In The Event Of|Possible Outcomes"); }, function (session, results) { if(results.response.entity == "Summary"){ session.send("Terrorist attacks like the ones we experienced on September 11, 2001 have left many concerned about the possibility " + "of future incidents of terrorism in the United States and their potential impact. They have raised uncertainty about what might " + "happen next, increasing stress levels. There are things you can do to prepare for terrorist attacks and reduce the stress that " + "you may feel now and later should another emergency arise. Taking preparatory action can reassure you and your children that " + "you can exert a measure of control even in the face of such events." ); } else if(results.response.entity == "How to Prepare"){ session.send( "Finding out what can happen is the first step. Once you have determined the events possible and their potential in your community, " + "it is important that you discuss them with your family or household. Develop a disaster plan together. Also, prepare an emergency kit. The emergency kit" + " should be easily accessible should you and your family be forced to shelter in place (stay at home) for a period of time. Be wary of suspicious " + "packages and letters. They can contain explosives, chemical or biological agents. Be particularly cautious at your place of employment. " ); } else if (results.response.entity == "In The Event Of"){ session.send( "Remain calm and be patient. Follow the advice of local emergency officials. Listen to your radio or television for news and instructions." + "If the event occurs near you, check for injuries. Give first aid and get help for seriously injured people. If the event occurs near your home while you are there, check for damage using a flashlight. Do not light matches or candles or turn on electrical switches. Check for fires, fire hazards and other household hazards. Sniff for gas leaks, starting at the water heater. If you smell gas or suspect a leak, turn off the main gas valve, open windows, and get everyone outside quickly. " + "Shut off any other damaged utilities. Confine or secure your pets. Call your family contact—do not use the telephone again unless it is a life-threatening emergency." + "Check on your neighbors, especially those who are elderly or disabled." ); } else if (results.response.entity == "Possible Outcomes"){ session.send( "As we’ve learned from previous events, the following things can happen after a terrorist attack: " + "There can be significant numbers of casualties and/or damage to buildings and the infrastructure. So employers need up-to-date information about any medical needs you may have and on how to contact your designated beneficiaries. " + "Heavy law enforcement involvement at local, state and federal levels follows a terrorist attack due to the event's criminal nature. " + "Health and mental health resources in the affected communities can be strained to their limits, maybe even overwhelmed. " + "Extensive media coverage, strong public fear and international implications and consequences can continue for a prolonged period. " + "Workplaces and schools may be closed, and there may be restrictions on domestic and international travel. " + "You and your family or household may have to evacuate an area, avoiding roads blocked for your safety. " + "Clean-up may take many months." ); } session.endDialog(); } ]); bot.add('/Tornado', [ function (session) { builder.Prompts.choice(session, "What about tornados would you like to learn?", "Summary|How to Prepare|Tornado Watch vs. Warning|Danger Signs|During Tornado|After Tornado"); }, function (session, results) { if(results.response.entity == "Summary"){ session.send("Continued vigilance and quick response to tornado watches and warnings are critical, since tornadoes can strike virtually" + " anywhere at any time. Most tornadoes are abrupt at onset, short-lived and often obscured by rain or darkness. That's why it's so " + "important to plan ahead. Every individual, family, and business should have a tornado emergency plan for their homes or places of work, " + "and should learn how to protect themselves in cars, open country, and other situations that may arise."); } else if(results.response.entity == "How to Prepare"){ session.send( "The most important step you can take " + "to prepare for a tornado is to have a shelter plan in place. Where will you go when a tornado warning has been issued for your county or city? " + "Is it a basement or a storm cellar? Is there an interior room on the ground floor that you can use as a storm shelter? Have a plan, " + "and make sure everyone in your family or workplace knows it." ); } else if (results.response.entity == "Tornado Watch vs. Warning"){ session.send( "Know the difference between a tornado watch and a warning: Tornado Watch alerts when conditions are right for tornadoes, and tornadoes are " + "possible. Remain alert: watch the sky and tune in to NOAA Weather Radio, commercial radio, or a local television station in case a warning " + "is issued. Tornado Warnings are when a tornado has been spotted by human eye or radar, and is moving toward you in the warning area. " + "Take shelter immediately." ); } else if (results.response.entity == "Danger Signs"){ session.send( "Look for the following danger signs: Dark, greenish sky; Large hail; A large, dark, low-lying cloud (particularly if rotating); " + "A loud roar, similar to a freight train; When a tornado warning has been issued for your county or city, seek shelter immediately!" ); } else if (results.response.entity == "During Tornado"){ session.send( "If you are in a structure or residence area, Head to your pre-designated shelter area. This could be a basement, storm cellar, or the " + "lowest building level. If you are home and you don't have a basement, go to the most interior room of the ground floor. Often a " + "bathroom or laundry room makes a suitable shelter area because the water pipes reenforce the walls, providing a more sturdy structure. " + "Stay away from corners, windows, doors, and exterior walls. Put as many walls as possible between you and the outside. Get down on your " + "knees and use your hands to protect your head and neck. Do not open windows. If you are outside with no nearby structure, lie flat in a nearby ditch or depression " + "and cover your head and neck with your hands. Be aware of flying debris. Tornadoes can pick up large objects and turn them into missiles. Flying debris cause the most tornado deaths." ); } else if (results.response.entity == "After Tornado"){ session.send( "After a tornado passes, it is important to take some precautions. Be careful as your leave your tornado shelter, since there might " + "be unseen damage waiting for you on the other side of doors. If your home has been damaged, walk carefully around the outside and check " + "for things like loose power lines, gas leaks, and general structural damage. Leave the premises if you smell gas or if floodwaters " + "exist around the building. Call your insurance agent and take pictures of the damage to your home or vehicle. If the destruction is " + "extensive, don't panic. The American Red Crossand other volunteer agencies will arrive with food and water, and temporary housing will " + "be designated by FEMA." ); } session.endDialog(); //// } ]); bot.add('/HeartAttack', [ function (session) { builder.Prompts.choice(session, "What about heart attacks would you like to learn?", "Summary|Symptoms|Emergency|Prevention"); }, function (session, results) { if(results.response.entity == "Summary"){ session.send( "A heart attack usually occurs when there is blockage in one of the heart's arteries." + " This is an emergency that can cause death. It requires quick action. " + "Do not ignore even minor heart attack symptoms. Immediate treatment lessens heart damage and saves lives." ); } else if(results.response.entity == "Symptoms"){ session.send( "Common heart attack symptoms and warning signs may include: " + "Chest discomfort that feels like pressure, fullness, or a squeezing pain in the center of your " + "chest; it lasts for more than a few minutes, or goes away and comes back. Pain and discomfort that " + "extend beyond your chest to other parts of your upper body, such as one or both arms, back, neck, " + "stomach,teeth, and jaw. Unexplained shortness of breath, with or without chest discomfort " + "Other symptoms, such as cold sweats, nausea or vomiting, lightheadedness, anxiety, indigestion, and " + "unexplained fatigue" ); } else if (results.response.entity == "Emergency"){ session.send( "If you or someone you are with experiences chest discomfort or other heart attack symptoms, call 911 " + "right away. Do not wait more than 5 minutes to make the call. While your first impulse may be to drive " + "yourself or the heart attack victim to the hospital, it is better to call 911. Emergency medical services " + "(EMS) personnel can begin treatment on the way to the hospital and are trained to revive a person if his " + "heart stops. If you witness heart attack symptoms in someone and are unable to reach EMS, drive the " + "person to the hospital. If you are experiencing heart attack symptoms, do not drive yourself to the " + "hospital unless you have no other choice." ); } else if (results.response.entity == "Prevention"){ session.send( "There are many ways to prevent heart disease. These include quitting smoking, exercising more, and reducing stress. " + "Maintaining a healthy and balanced diet is also key." ); } session.endDialog(); } ]); dialog.on('SetupUserProfile', [ function (session) { builder.Prompts.text(session, "Welcome!, I'm Viva. Let’s set up your profile.\n\n\n\nIn the case of an emergency, we can communicate your personal information to emergency service operators.\n\n\n\nWhat is your full name?"); }, function (session, results) { if (results.response == "Crash") { session.endDialog(); } session.userData.name = results.response; /*if(curData[results.response] !== undefined){ sender.send('You are already registered'); }*/ builder.Prompts.text(session, "Hi " + results.response + "\n\n\n\nWhat's your sex?"); }, function (session, results) { if (results.response == "Crash") { session.endDialog(); } session.userData.sex = results.response; builder.Prompts.number(session, "What is your phone number?"); }, function (session, results) { if (results.response == "Crash") { session.endDialog(); } session.userData.number = results.response; builder.Prompts.text(session, "What is your country?"); }, function (session, results) { if (results.response == "Crash") { session.endDialog(); } session.userData.country = results.response; builder.Prompts.text(session, "What is your date of birth?"); }, function (session, results) { if (results.response == "Crash") { session.endDialog(); } session.userData.DoB = results.response; builder.Prompts.text(session, "Do you have any existing medical conditions?"); }, function (session, results) { if (results.response == "Crash") { session.endDialog(); } session.userData.medicalConditions = results.response; builder.Prompts.text(session, "Are you allergic to any medications?"); }, function (session, results) { if (results.response == "Crash") { session.endDialog(); } session.userData.medicationAllergies = results.response; builder.Prompts.text(session, "Last one! What is your health provider?"); }, function (session, results) { if (results.response == "Crash") { session.endDialog(); } session.userData.healthProvider = results.response; myFirebaseRef.child(session.userData.name).set(session.userData); country = session.userData.country; lastUsedName = session.userData.name; session.send("Your profile is set up. Stay safe!"); } ]); dialog.on('ContactOrganization', [ function (session, args) { var organization = builder.EntityRecognizer.findEntity(args.entities, 'Organization'); var medical = builder.EntityRecognizer.findEntity(args.entities, 'Disaster::Medical'); var criminal = builder.EntityRecognizer.findEntity(args.entities, 'Disaster::Criminal'); var environmental = builder.EntityRecognizer.findEntity(args.entities, 'Disaster::Environmental'); if(organization){ // response: organization.entity; session.send( "Contacting " + organization.entity); } if(medical){ session.send( "Contacting " + medical.entity); } if(criminal){ session.send( "Contacting " + criminal.entity); } if(environmental){ session.send( "Contacting " + environmental.entity); } else{ session.send( "Contacting no one"); } }, function (session, results) { } ]);
var AWS = require('aws-sdk'); AWS.config.update({region: 'us-east-1'}); const codepipeline = new AWS.CodePipeline(); const ssm = new AWS.SSM(); var iCodePipelineStack = ""; function getCodePipelineStack(callback) { var params = { Name: 'CodePipelineStack', /* required */ WithDecryption: false }; ssm.getParameter(params, function(err, data) { if (err) console.log(err, err.stack); // an error occurred else iCodePipelineStack = data.Parameter['Value']; callback(); // successful response }); } exports.handler = function(event, context) { getCodePipelineStack(function() { console.log(iCodePipelineStack); var params = { name: iCodePipelineStack }; codepipeline.startPipelineExecution(params, function(err, data) { if (err) console.log(err, err.stack); // an error occurred else console.log(data); // successful response }); }); };
/** * @author Tatamae * @copyright Copyright © 2009, Tatemae. */ (function() { tinymce.create('tinymce.plugins.muckFlickr', { init : function(ed, url) { // Register commands ed.addCommand('muckFlickr', function() { var e = ed.selection.getNode(); // Internal file object like a flash placeholder if (ed.dom.getAttrib(e, 'class').indexOf('mceItem') != -1) return; ed.windowManager.open({ file : jQuery('#tiny_mce_flickr_path').val(), width : parseInt(jQuery('#tiny_mce_flickr_width').val()) + parseInt(ed.getLang('muckflickr.delta_width', 0)), height : parseInt(jQuery('#tiny_mce_flickr_height').val()) + parseInt(ed.getLang('muckflickr.delta_height', 0)), inline : 1 }, { search_string : ed.selection.getContent({format : 'text'}), plugin_url : url }); }); // Register button ed.addButton('flickr', { title : 'Flickr', cmd : 'muckFlickr', image : '/images/tinymce/flickr.gif' }); }, getInfo : function() { return { longname : 'Flickr in muck', author : 'Tatemae', authorurl : 'http://Tatemae.com', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('muckflickr', tinymce.plugins.muckFlickr); })();
import { connect } from 'react-redux' import React, { Component } from 'react' import { Button, Card, Row, Col } from 'react-bootstrap' import Select from 'react-select' import CommentsBox from '../../components/CommentsBox' import InputOption from '../../components/InputOption' import DropdownOption from '../../components/DropdownOption' import CheckboxOption from '../../components/CheckboxOption' import ToggleButtonOption from '../../components/ToggleButtonOption' import Transforms from '../transforms/Transforms' import { updateLayer, setShapeType, restoreDefaults } from '../layers/layersSlice' import { getCurrentLayer } from './selectors' import { getShape, getShapeSelectOptions } from '../../models/shapes' import './Layer.scss' const mapStateToProps = (state, ownProps) => { const layer = getCurrentLayer(state) const shape = getShape(layer) return { layer: layer, shape: shape, options: shape.getOptions(), selectOptions: getShapeSelectOptions(false), showShapeSelectRender: layer.selectGroup !== 'import' && !layer.effect, link: shape.link, linkText: shape.linkText } } const mapDispatchToProps = (dispatch, ownProps) => { const { id } = ownProps return { onChange: (attrs) => { attrs.id = id dispatch(updateLayer(attrs)) }, onChangeType: (selected) => { dispatch(setShapeType({id: id, type: selected.value})) }, onRestoreDefaults: (event) => { dispatch(restoreDefaults(id)) } } } class Layer extends Component { render() { const selectedOption = { value: this.props.shape.id, label: this.props.shape.name } const optionsRender = Object.keys(this.props.options).map((key, index) => { return this.getOptionComponent(key, index) }) const linkText = this.props.linkText || this.props.link const linkRender = this.props.link ? <Row><Col sm={5}></Col><Col sm={7}><p className="mt-2">See <a target="_blank" rel="noopener noreferrer" href={this.props.link}>{linkText}</a> for ideas.</p></Col></Row> : undefined let optionsListRender = undefined if (Object.entries(this.props.options).length > 0) { optionsListRender = <div className="m-0"> {optionsRender} </div> } let shapeSelectRender = undefined if (this.props.showShapeSelectRender) { shapeSelectRender = <Row className="align-items-center"> <Col sm={5}> Shape </Col> <Col sm={7}> <Select value={selectedOption} onChange={this.props.onChangeType} maxMenuHeight={305} options={this.props.selectOptions} /> </Col> </Row> } return ( <Card className="p-3 overflow-auto flex-grow-1" style={{borderTop: "1px solid #aaa", borderBottom: "none"}}> <Row className="align-items-center mb-2"> <Col sm={5}> <h2 className="panel m-0">Properties</h2> </Col> <Col sm={7}> <Button className="ml-auto" variant="outline-primary" size="sm" onClick={this.props.onRestoreDefaults}>Restore defaults</Button> </Col> </Row> { shapeSelectRender } { linkRender } <div className="pt-1"> { optionsListRender } <Transforms id={this.props.layer.id} /> </div> </Card> ) } getOptionComponent(key, index) { const option = this.props.options[key] if (option.type === 'dropdown') { return <DropdownOption onChange={this.props.onChange} options={this.props.options} optionKey={key} key={key} index={index} model={this.props.layer} /> } else if (option.type === 'checkbox') { return <CheckboxOption onChange={this.props.onChange} options={this.props.options} optionKey={key} key={key} index={index} model={this.props.layer} /> } else if (option.type === 'comments') { return <CommentsBox options={this.props.options} optionKey={key} key={key} comments={this.props.layer.comments} /> } else if (option.type === 'togglebutton') { return <ToggleButtonOption onChange={this.props.onChange} options={this.props.options} optionKey={key} key={key} index={index} model={this.props.layer} /> } else { return <InputOption onChange={this.props.onChange} options={this.props.options} optionKey={key} key={key} index={index} model={this.props.layer} /> } } } export default connect(mapStateToProps, mapDispatchToProps)(Layer)
const should = require('should'); const supertest = require('supertest'); const sinon = require('sinon'); const testUtils = require('../../../utils'); const localUtils = require('./utils'); const config = require('../../../../server/config'); const mailService = require('../../../../server/services/mail'); const ghost = testUtils.startGhost; let request; describe('Invites API', function () { let ghostServer; before(function () { return ghost() .then(function (_ghostServer) { ghostServer = _ghostServer; request = supertest.agent(config.get('url')); }) .then(function () { return localUtils.doAuth(request, 'invites'); }); }); beforeEach(function () { sinon.stub(mailService.GhostMailer.prototype, 'send').resolves('Mail is disabled'); }); afterEach(function () { sinon.restore(); }); it('Can fetch all invites', function (done) { request.get(localUtils.API.getApiQuery('invites/')) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.invites); jsonResponse.invites.should.have.length(2); localUtils.API.checkResponse(jsonResponse, 'invites'); localUtils.API.checkResponse(jsonResponse.invites[0], 'invite'); jsonResponse.invites[0].status.should.eql('sent'); jsonResponse.invites[0].email.should.eql('test1@ghost.org'); jsonResponse.invites[0].role_id.should.eql(testUtils.roles.ids.admin); jsonResponse.invites[1].status.should.eql('sent'); jsonResponse.invites[1].email.should.eql('test2@ghost.org'); jsonResponse.invites[1].role_id.should.eql(testUtils.roles.ids.author); mailService.GhostMailer.prototype.send.called.should.be.false(); done(); }); }); it('Can read an invitation by id', function (done) { request.get(localUtils.API.getApiQuery(`invites/${testUtils.DataGenerator.forKnex.invites[0].id}/`)) .set('Origin', config.get('url')) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(200) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.invites); jsonResponse.invites.should.have.length(1); localUtils.API.checkResponse(jsonResponse.invites[0], 'invite'); mailService.GhostMailer.prototype.send.called.should.be.false(); done(); }); }); it('Can add a new invite', function (done) { request .post(localUtils.API.getApiQuery('invites/')) .set('Origin', config.get('url')) .send({ invites: [{email: 'test@example.com', role_id: testUtils.existingData.roles[1].id}] }) .expect('Content-Type', /json/) .expect('Cache-Control', testUtils.cacheRules.private) .expect(201) .end(function (err, res) { if (err) { return done(err); } should.not.exist(res.headers['x-cache-invalidate']); const jsonResponse = res.body; should.exist(jsonResponse); should.exist(jsonResponse.invites); jsonResponse.invites.should.have.length(1); localUtils.API.checkResponse(jsonResponse.invites[0], 'invite'); jsonResponse.invites[0].role_id.should.eql(testUtils.existingData.roles[1].id); mailService.GhostMailer.prototype.send.called.should.be.true(); done(); }); }); it('Can destroy an existing invite', function (done) { request.del(localUtils.API.getApiQuery(`invites/${testUtils.DataGenerator.forKnex.invites[0].id}/`)) .set('Origin', config.get('url')) .expect('Cache-Control', testUtils.cacheRules.private) .expect(204) .end(function (err) { if (err) { return done(err); } mailService.GhostMailer.prototype.send.called.should.be.false(); done(); }); }); });
var vue = require('vue-loader'); var webpack = require('webpack'); module.exports = { entry: './src/main.js', output: { path: './static', publicPath: '/static/', filename: 'build.js' }, module: { loaders: [ { test: /\.vue$/, loader: 'vue' }, { test: /\.js$/, // excluding some local linked packages. // for normal use cases only node_modules is needed. exclude: /node_modules/, loader: 'babel' }, { test: /\.json$/, loader: 'json' }, { test: /\.(png|ttf|eot|svg|woff|woff2)(\?[a-z0-9]+)?$/, loader: 'file' } ] }, babel: { presets: ['es2015'], plugins: ['transform-runtime'] } } if (process.env.NODE_ENV === 'production') { module.exports.plugins = [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } }), new webpack.optimize.OccurenceOrderPlugin() ]; } else { module.exports.devtool = '#source-map'; }
import RedemptionTx from 'meklebar/models/redemption_tx'; var RedeemRoute = Ember.Route.extend({ model: function() { return RedemptionTx.create(); } }); export default RedeemRoute;
require("babel-register") var gulp = require('gulp'); var gutil = require('gulp-util'); var babel = require('gulp-babel'); var coveralls = require('gulp-coveralls'); var nodemon = require('gulp-nodemon'); var jsxCoverage = require('gulp-jsx-coverage'); var jasmine = require('gulp-jasmine'); var uglify = require('gulp-uglify'); var gulpif = require('gulp-if'); var redis = require('redis'); var bluebird = require('bluebird'); var fs = require('fs'); var nconf = require('nconf'); var browserify = require("browserify"); var source = require('vinyl-source-stream'); var buffer = require('vinyl-buffer'); nconf.argv().env().file({ file: './config.json' }); var ENVIRONMENT = nconf.get('environment'); var CLIENT_DIR = nconf.get('client.dir'); var PUBLIC_DIR = nconf.get('public.dir'); var DEPENDENCIES = [ 'react', 'react-dom' ]; process.env.NODE_ENV = ENVIRONMENT; var path = { JS_SOURCE: 'server/src/main/**/*.js', SPEC_SOURCE: 'server/src/test/**/*.js', REACT_RENDERER: 'server/src/main/components/renderer.react.js', CLIENT_JS_DEST: PUBLIC_DIR + '/js/', SERVER_JS_DEST: './dist', CSS_SOURCE: [ CLIENT_DIR + '/src/stylesheets/**/*.less' ], CACHE_SEED: './server/cache-seed-local.json', COVERAGE_DIR: './coverage' }; gulp.task('compile-server', function() { return gulp.src(path.JS_SOURCE) .pipe(babel({ presets: ['react', 'es2015'] })) .pipe(gulp.dest(path.SERVER_JS_DEST)); }); gulp.task('compile-client', function() { var stream = browserify({ entries: path.REACT_RENDERER, external: DEPENDENCIES, bundleExternal: false }).transform('babelify', { presets: ['es2015', 'react'] }).bundle() .on('error', gutil.log) .pipe(source('bundle.js')) .pipe(buffer()) .pipe(gulpif(ENVIRONMENT === 'production', uglify())) .pipe(gulp.dest(path.CLIENT_JS_DEST)); return stream; }); gulp.task('libify', function () { var stream = browserify({ require: DEPENDENCIES }).bundle() .on('error', gutil.log) .pipe(source('libs.js')) .pipe(buffer()) .pipe(gulpif(ENVIRONMENT === 'production', uglify())) .pipe(gulp.dest(path.CLIENT_JS_DEST)); return stream; }); gulp.task('test', function() { var options = { src: [path.SPEC_SOURCE, path.JS_SOURCE], istanbul: { preserveComments: true, coverageVariable: '$$cov_' + new Date().getTime() + '$$', exclude: /node_modules|test[0-9]/ }, coverage: { reporters: ['text-summary', 'json', 'lcov'], directory: path.COVERAGE_DIR } }; jsxCoverage.initModuleLoaderHack(options); return gulp.src(path.SPEC_SOURCE) .pipe(jasmine({ verbose: true, includeStackTrace: true })) .on('end', jsxCoverage.collectIstanbulCoverage(options)); }); gulp.task('coveralls', ['test'], function () { console.log('Sending results to coveralls...'); return gulp.src('coverage/**/lcov.info') .pipe(coveralls()); }); gulp.task('warmup-local-cache', function(done) { console.log('Warm-up local cache...'); bluebird.promisifyAll(redis.Multi.prototype); var redisClient = redis.createClient(), multi = redisClient.multi(), caches = JSON.parse(fs.readFileSync(path.CACHE_SEED, 'utf8')).local; caches.forEach(function (cache) { var logMsg = function() { console.log('Inserting cache: ' + cache.key + ' ' + cache.field); } multi.hset(cache.key, cache.field, JSON.stringify(cache.value), logMsg); }); multi.execAsync().then(function(data) { if (data) { console.log('Caches are warmed!'); } else { console.log('Some problem occurred while trying to warm the cache'); } done(process.exit(0)); }); }); gulp.task('watch', ['libify', 'compile-client', 'compile-server'], function() { var stream = nodemon({ script: path.SERVER_JS_DEST + '/server.js', watch: path.JS_SOURCE, ignore: [ 'dist/', 'node_modules/' ], tasks: ['compile-client', 'compile-server'] }); return stream; }); gulp.task('default', ['libify', 'compile-client', 'compile-server']);
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 app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); require('lodash-express')(app, 'html'); app.set('view engine', 'html'); // uncomment after placing your favicon in /public //app.use(favicon(__dirname + '/public/favicon.ico')); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); var routes = require('./routes/index'); app.use('/', routes); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { console.log(err + " - " + err.stack); res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
;(function () { 'use strict'; /** * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs. * * @codingstandard ftlabs-jsv2 * @copyright The Financial Times Limited [All Rights Reserved] * @license MIT License (see LICENSE.txt) */ /*jslint browser:true, node:true*/ /*global define, Event, Node*/ /** * Instantiate fast-clicking listeners on the specified layer. * * @constructor * @param {Element} layer The layer to listen on * @param {Object} [options={}] The options to override the defaults */ function FastClick(layer, options) { var oldOnClick; options = options || {}; /** * Whether a click is currently being tracked. * * @type boolean */ this.trackingClick = false; /** * Timestamp for when click tracking started. * * @type number */ this.trackingClickStart = 0; /** * The element being tracked for a click. * * @type EventTarget */ this.targetElement = null; /** * X-coordinate of touch start event. * * @type number */ this.touchStartX = 0; /** * Y-coordinate of touch start event. * * @type number */ this.touchStartY = 0; /** * ID of the last touch, retrieved from Touch.identifier. * * @type number */ this.lastTouchIdentifier = 0; /** * Touchmove boundary, beyond which a click will be cancelled. * * @type number */ this.touchBoundary = options.touchBoundary || 10; /** * The FastClick layer. * * @type Element */ this.layer = layer; /** * The minimum time between tap(touchstart and touchend) events * * @type number */ this.tapDelay = options.tapDelay || 200; /** * The maximum time for a tap * * @type number */ this.tapTimeout = options.tapTimeout || 700; if (FastClick.notNeeded(layer)) { return; } // Some old versions of Android don't have Function.prototype.bind function bind(method, context) { return function() { return method.apply(context, arguments); }; } var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel']; var context = this; for (var i = 0, l = methods.length; i < l; i++) { context[methods[i]] = bind(context[methods[i]], context); } // Set up event handlers as required if (deviceIsAndroid) { layer.addEventListener('mouseover', this.onMouse, true); layer.addEventListener('mousedown', this.onMouse, true); layer.addEventListener('mouseup', this.onMouse, true); } layer.addEventListener('click', this.onClick, true); layer.addEventListener('touchstart', this.onTouchStart, false); layer.addEventListener('touchmove', this.onTouchMove, false); layer.addEventListener('touchend', this.onTouchEnd, false); layer.addEventListener('touchcancel', this.onTouchCancel, false); // Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2) // which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick // layer when they are cancelled. if (!Event.prototype.stopImmediatePropagation) { layer.removeEventListener = function(type, callback, capture) { var rmv = Node.prototype.removeEventListener; if (type === 'click') { rmv.call(layer, type, callback.hijacked || callback, capture); } else { rmv.call(layer, type, callback, capture); } }; layer.addEventListener = function(type, callback, capture) { var adv = Node.prototype.addEventListener; if (type === 'click') { adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) { if (!event.propagationStopped) { callback(event); } }), capture); } else { adv.call(layer, type, callback, capture); } }; } // If a handler is already declared in the element's onclick attribute, it will be fired before // FastClick's onClick handler. Fix this by pulling out the user-defined handler function and // adding it as listener. if (typeof layer.onclick === 'function') { // Android browser on at least 3.2 requires a new reference to the function in layer.onclick // - the old one won't work if passed to addEventListener directly. oldOnClick = layer.onclick; layer.addEventListener('click', function(event) { oldOnClick(event); }, false); layer.onclick = null; } } /** * Windows Phone 8.1 fakes user agent string to look like Android and iPhone. * * @type boolean */ var deviceIsWindowsPhone = navigator.userAgent.indexOf("Windows Phone") >= 0; /** * Android requires exceptions. * * @type boolean */ var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0 && !deviceIsWindowsPhone; /** * iOS requires exceptions. * * @type boolean */ var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent) && !deviceIsWindowsPhone; /** * iOS 4 requires an exception for select elements. * * @type boolean */ var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent); /** * iOS 6.0-7.* requires the target element to be manually derived * * @type boolean */ var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS [6-7]_\d/).test(navigator.userAgent); /** * BlackBerry requires exceptions. * * @type boolean */ var deviceIsBlackBerry10 = navigator.userAgent.indexOf('BB10') > 0; /** * Determine whether a given element requires a native click. * * @param {EventTarget|Element} target Target DOM element * @returns {boolean} Returns true if the element needs a native click */ FastClick.prototype.needsClick = function(target) { switch (target.nodeName.toLowerCase()) { // Don't send a synthetic click to disabled inputs (issue #62) case 'button': case 'select': case 'textarea': if (target.disabled) { return true; } break; case 'input': // File inputs need real clicks on iOS 6 due to a browser bug (issue #68) if ((deviceIsIOS && target.type === 'file') || target.disabled) { return true; } break; case 'label': case 'iframe': // iOS8 homescreen apps can prevent events bubbling into frames case 'video': return true; } return (/\bneedsclick\b/).test(target.className); }; /** * Determine whether a given element requires a call to focus to simulate click into element. * * @param {EventTarget|Element} target Target DOM element * @returns {boolean} Returns true if the element requires a call to focus to simulate native click. */ FastClick.prototype.needsFocus = function(target) { switch (target.nodeName.toLowerCase()) { case 'textarea': return true; case 'select': return !deviceIsAndroid; case 'input': switch (target.type) { case 'button': case 'checkbox': case 'file': case 'image': case 'radio': case 'submit': return false; } // No point in attempting to focus disabled inputs return !target.disabled && !target.readOnly; default: return (/\bneedsfocus\b/).test(target.className); } }; /** * Send a click event to the specified element. * * @param {EventTarget|Element} targetElement * @param {Event} event */ FastClick.prototype.sendClick = function(targetElement, event) { var clickEvent, touch; // On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24) if (document.activeElement && document.activeElement !== targetElement) { document.activeElement.blur(); } touch = event.changedTouches[0]; // Synthesise a click event, with an extra attribute so it can be tracked clickEvent = document.createEvent('MouseEvents'); clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null); clickEvent.forwardedTouchEvent = true; targetElement.dispatchEvent(clickEvent); }; FastClick.prototype.determineEventType = function(targetElement) { //Issue #159: Android Chrome Select Box does not open with a synthetic click event if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') { return 'mousedown'; } return 'click'; }; /** * @param {EventTarget|Element} targetElement */ FastClick.prototype.focus = function(targetElement) { var length; // Issue #160: on iOS 7, some input elements (e.g. date datetime month) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724. if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time' && targetElement.type !== 'month') { length = targetElement.value.length; try { targetElement.setSelectionRange(length, length); } catch(e) {} } else { targetElement.focus(); } }; /** * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it. * * @param {EventTarget|Element} targetElement */ FastClick.prototype.updateScrollParent = function(targetElement) { var scrollParent, parentElement; scrollParent = targetElement.fastClickScrollParent; // Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the // target element was moved to another parent. if (!scrollParent || !scrollParent.contains(targetElement)) { parentElement = targetElement; do { if (parentElement.scrollHeight > parentElement.offsetHeight) { scrollParent = parentElement; targetElement.fastClickScrollParent = parentElement; break; } parentElement = parentElement.parentElement; } while (parentElement); } // Always update the scroll top tracker if possible. if (scrollParent) { scrollParent.fastClickLastScrollTop = scrollParent.scrollTop; } }; /** * @param {EventTarget} targetElement * @returns {Element|EventTarget} */ FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) { // On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node. if (eventTarget.nodeType === Node.TEXT_NODE) { return eventTarget.parentNode; } return eventTarget; }; /** * On touch start, record the position and scroll offset. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onTouchStart = function(event) { var targetElement, touch, selection; // Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111). if (event.targetTouches.length > 1) { return true; } targetElement = this.getTargetElementFromEventTarget(event.target); touch = event.targetTouches[0]; if (deviceIsIOS) { // Only trusted events will deselect text on iOS (issue #49) selection = window.getSelection(); if (selection.rangeCount && !selection.isCollapsed) { return true; } if (!deviceIsIOS4) { // Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23): // when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched // with the same identifier as the touch event that previously triggered the click that triggered the alert. // Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an // immediately preceeding touch event (issue #52), so this fix is unavailable on that platform. // Issue 120: touch.identifier is 0 when Chrome dev tools 'Emulate touch events' is set with an iOS device UA string, // which causes all touch events to be ignored. As this block only applies to iOS, and iOS identifiers are always long, // random integers, it's safe to to continue if the identifier is 0 here. if (touch.identifier && touch.identifier === this.lastTouchIdentifier) { event.preventDefault(); return false; } this.lastTouchIdentifier = touch.identifier; // If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and: // 1) the user does a fling scroll on the scrollable layer // 2) the user stops the fling scroll with another tap // then the event.target of the last 'touchend' event will be the element that was under the user's finger // when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check // is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42). this.updateScrollParent(targetElement); } } this.trackingClick = true; this.trackingClickStart = event.timeStamp; this.targetElement = targetElement; this.touchStartX = touch.pageX; this.touchStartY = touch.pageY; // Prevent phantom clicks on fast double-tap (issue #36) if ((event.timeStamp - this.lastClickTime) < this.tapDelay) { event.preventDefault(); } return true; }; /** * Based on a touchmove event object, check whether the touch has moved past a boundary since it started. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.touchHasMoved = function(event) { var touch = event.changedTouches[0], boundary = this.touchBoundary; if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) { return true; } return false; }; /** * Update the last position. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onTouchMove = function(event) { if (!this.trackingClick) { return true; } // If the touch has moved, cancel the click tracking if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) { this.trackingClick = false; this.targetElement = null; } return true; }; /** * Attempt to find the labelled control for the given label element. * * @param {EventTarget|HTMLLabelElement} labelElement * @returns {Element|null} */ FastClick.prototype.findControl = function(labelElement) { // Fast path for newer browsers supporting the HTML5 control attribute if (labelElement.control !== undefined) { return labelElement.control; } // All browsers under test that support touch events also support the HTML5 htmlFor attribute if (labelElement.htmlFor) { return document.getElementById(labelElement.htmlFor); } // If no for attribute exists, attempt to retrieve the first labellable descendant element // the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea'); }; /** * On touch end, determine whether to send a click event at once. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onTouchEnd = function(event) { var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement; if (!this.trackingClick) { return true; } // Prevent phantom clicks on fast double-tap (issue #36) if ((event.timeStamp - this.lastClickTime) < this.tapDelay) { this.cancelNextClick = true; return true; } if ((event.timeStamp - this.trackingClickStart) > this.tapTimeout) { return true; } // Reset to prevent wrong click cancel on input (issue #156). this.cancelNextClick = false; this.lastClickTime = event.timeStamp; trackingClickStart = this.trackingClickStart; this.trackingClick = false; this.trackingClickStart = 0; // On some iOS devices, the targetElement supplied with the event is invalid if the layer // is performing a transition or scroll, and has to be re-detected manually. Note that // for this to function correctly, it must be called *after* the event target is checked! // See issue #57; also filed as rdar://13048589 . if (deviceIsIOSWithBadTarget) { touch = event.changedTouches[0]; // In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement; targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent; } targetTagName = targetElement.tagName.toLowerCase(); if (targetTagName === 'label') { forElement = this.findControl(targetElement); if (forElement) { this.focus(targetElement); if (deviceIsAndroid) { return false; } targetElement = forElement; } } else if (this.needsFocus(targetElement)) { // Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through. // Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37). if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) { this.targetElement = null; return false; } this.focus(targetElement); this.sendClick(targetElement, event); // Select elements need the event to go through on iOS 4, otherwise the selector menu won't open. // Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others) if (!deviceIsIOS || targetTagName !== 'select') { this.targetElement = null; event.preventDefault(); } return false; } if (deviceIsIOS && !deviceIsIOS4) { // Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled // and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42). scrollParent = targetElement.fastClickScrollParent; if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) { return true; } } // Prevent the actual click from going though - unless the target node is marked as requiring // real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted. if (!this.needsClick(targetElement)) { event.preventDefault(); this.sendClick(targetElement, event); } return false; }; /** * On touch cancel, stop tracking the click. * * @returns {void} */ FastClick.prototype.onTouchCancel = function() { this.trackingClick = false; this.targetElement = null; }; /** * Determine mouse events which should be permitted. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onMouse = function(event) { // If a target element was never set (because a touch event was never fired) allow the event if (!this.targetElement) { return true; } if (event.forwardedTouchEvent) { return true; } // Programmatically generated events targeting a specific element should be permitted if (!event.cancelable) { return true; } // Derive and check the target element to see whether the mouse event needs to be permitted; // unless explicitly enabled, prevent non-touch click events from triggering actions, // to prevent ghost/doubleclicks. if (!this.needsClick(this.targetElement) || this.cancelNextClick) { // Prevent any user-added listeners declared on FastClick element from being fired. if (event.stopImmediatePropagation) { event.stopImmediatePropagation(); } else { // Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2) event.propagationStopped = true; } // Cancel the event event.stopPropagation(); event.preventDefault(); return false; } // If the mouse event is permitted, return true for the action to go through. return true; }; /** * On actual clicks, determine whether this is a touch-generated click, a click action occurring * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or * an actual click which should be permitted. * * @param {Event} event * @returns {boolean} */ FastClick.prototype.onClick = function(event) { var permitted; // It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early. if (this.trackingClick) { this.targetElement = null; this.trackingClick = false; return true; } // Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target. if (event.target.type === 'submit' && event.detail === 0) { return true; } permitted = this.onMouse(event); // Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through. if (!permitted) { this.targetElement = null; } // If clicks are permitted, return true for the action to go through. return permitted; }; /** * Remove all FastClick's event listeners. * * @returns {void} */ FastClick.prototype.destroy = function() { var layer = this.layer; if (deviceIsAndroid) { layer.removeEventListener('mouseover', this.onMouse, true); layer.removeEventListener('mousedown', this.onMouse, true); layer.removeEventListener('mouseup', this.onMouse, true); } layer.removeEventListener('click', this.onClick, true); layer.removeEventListener('touchstart', this.onTouchStart, false); layer.removeEventListener('touchmove', this.onTouchMove, false); layer.removeEventListener('touchend', this.onTouchEnd, false); layer.removeEventListener('touchcancel', this.onTouchCancel, false); }; /** * Check whether FastClick is needed. * * @param {Element} layer The layer to listen on */ FastClick.notNeeded = function(layer) { var metaViewport; var chromeVersion; var blackberryVersion; var firefoxVersion; // Devices that don't support touch don't need FastClick if (typeof window.ontouchstart === 'undefined') { return true; } // Chrome version - zero for other browsers chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1]; if (chromeVersion) { if (deviceIsAndroid) { metaViewport = document.querySelector('meta[name=viewport]'); if (metaViewport) { // Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89) if (metaViewport.content.indexOf('user-scalable=no') !== -1) { return true; } // Chrome 32 and above with width=device-width or less don't need FastClick if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) { return true; } } // Chrome desktop doesn't need FastClick (issue #15) } else { return true; } } if (deviceIsBlackBerry10) { blackberryVersion = navigator.userAgent.match(/Version\/([0-9]*)\.([0-9]*)/); // BlackBerry 10.3+ does not require Fastclick library. // https://github.com/ftlabs/fastclick/issues/251 if (blackberryVersion[1] >= 10 && blackberryVersion[2] >= 3) { metaViewport = document.querySelector('meta[name=viewport]'); if (metaViewport) { // user-scalable=no eliminates click delay. if (metaViewport.content.indexOf('user-scalable=no') !== -1) { return true; } // width=device-width (or less than device-width) eliminates click delay. if (document.documentElement.scrollWidth <= window.outerWidth) { return true; } } } } // IE10 with -ms-touch-action: none or manipulation, which disables double-tap-to-zoom (issue #97) if (layer.style.msTouchAction === 'none' || layer.style.touchAction === 'manipulation') { return true; } // Firefox version - zero for other browsers firefoxVersion = +(/Firefox\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1]; if (firefoxVersion >= 27) { // Firefox 27+ does not have tap delay if the content is not zoomable - https://bugzilla.mozilla.org/show_bug.cgi?id=922896 metaViewport = document.querySelector('meta[name=viewport]'); if (metaViewport && (metaViewport.content.indexOf('user-scalable=no') !== -1 || document.documentElement.scrollWidth <= window.outerWidth)) { return true; } } // IE11: prefixed -ms-touch-action is no longer supported and it's recomended to use non-prefixed version // http://msdn.microsoft.com/en-us/library/windows/apps/Hh767313.aspx if (layer.style.touchAction === 'none' || layer.style.touchAction === 'manipulation') { return true; } return false; }; /** * Factory method for creating a FastClick object * * @param {Element} layer The layer to listen on * @param {Object} [options={}] The options to override the defaults */ FastClick.attach = function(layer, options) { return new FastClick(layer, options); }; if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) { // AMD. Register as an anonymous module. define(function() { return FastClick; }); } else if (typeof module !== 'undefined' && module.exports) { module.exports = FastClick.attach; module.exports.FastClick = FastClick; } else { window.FastClick = FastClick; } }());
describe('EvaluationTemplateResource', function () { var $httpBackend, factory; var SERVER_URL = 'http://dispatch.ru.is/h22/api/v1/'; var config = { 'Authorization': 'Basic t0k3n', 'Accept': 'application/json, text/plain, */*' }; var template = { ID: 1, Title: 'Sniðmát', TitleEN: 'Template', IntroText: 'Þetta er sniðmát', IntroTextEN: 'This is a template', CourseQuestions: [], TeacherQuestions: [] }; beforeEach(function () { module('EvalApp'); inject(function ($injector) { factory = $injector.get('EvaluationTemplateResource'); }); factory.init('t0k3n'); }); describe('Sever functions', function () { beforeEach(function () { inject(function ($injector) { $httpBackend = $injector.get('$httpBackend'); }); }); afterEach(function () { $httpBackend.flush(); $httpBackend.verifyNoOutstandingRequest(); $httpBackend.verifyNoOutstandingExpectation(); }); it('should get templates from server when getTemplates is called', function () { factory.getTemplates(); $httpBackend.expectGET(SERVER_URL + 'evaluationtemplates', config) .respond(200, []); }); it('should get template from server when getTemplate is called', function () { factory.getTemplate(1); $httpBackend.expectGET(SERVER_URL + 'evaluationtemplates/1', config) .respond(200, []); }); it('should post template to server when create is called', function () { factory.create(template); $httpBackend.expectPOST(SERVER_URL + 'evaluationtemplates', template, { 'Authorization': 'Basic t0k3n', 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json;charset=utf-8'}).respond(200); }); }); describe('set and getThisTemplate', function () { it('should return correct template when changed', function () { factory.setTemplate(template); var result = factory.getThisTemplate(); expect(result).toEqual(template); }); }); });
'use strict'; const path = require('path'); const Ekko = require('./server'); const yargs = require('yargs'); const { argv } = yargs; const configPath = argv.ekkoConfig || path.join(__dirname, 'config.js'); const ekko = new Ekko(configPath); ekko .start() .catch(() => true);
'use strict'; bg.ecard.Asset = {}; bg.ecard.Asset.Class = function(params, parent) { this.params = params; this.params.type = 'bg.ecard.Asset.Class'; } bg.ecard.Asset.Class.prototype.params = { type: 'bg.ecard.Asset.Class' } bg.ecard.Asset.Class.prototype.initClass = function() { app.log(this, 'initClass()'); this.state = new Object({ loaded: false }); } bg.ecard.Asset.Class.prototype.isLoaded = function() { //app.log(this, 'isLoaded()'); if (!this.state.loaded && this.state.loading) { return false; } else if (this.state.loaded) { return true; } //return this.state.loaded; } bg.ecard.Asset.Class.prototype.setState = function(states) { // app.log(this, 'setState()'); bg.ecard.utils.setState(this, states); } bg.ecard.Asset.Class.prototype.registerSprite = function(sprite) { } bg.ecard.utils.registerJS('bg.ecard.Asset.Class.js');
/** * @private * @param {Window} window * @param {string} svgId * @param {number} width * @param {number} height * @returns {void} */ function generateBase64(_window, svgId, width, height) { const svgNode = _window.document.getElementById(svgId); if (!svgNode) { return ''; } const cloneNode = svgNode.cloneNode(true); cloneNode.setAttribute('width', width); cloneNode.setAttribute('height', height); const svgText = cloneNode.outerHTML; const encoded = _window.encodeURIComponent(svgText).replace(/%([0-9A-F]{2})/g, (match, p1) => { return String.fromCharCode('0x' + p1); }); const base64SvgText = _window.btoa(encoded); return base64SvgText; } /** * @private * @param {Window} window * @param {string} base64SvgText * @param {number} width * @param {number} height * @returns {void} */ function toCanvas(_window, base64SvgText, width, height) { const src = 'data:image/svg+xml;charset=utf-8;base64,' + base64SvgText; const canvas = _window.document.createElement('canvas'); const context = canvas.getContext('2d'); const image = new _window.Image(); canvas.width = width; canvas.height = height; image.onload = () => { context.drawImage(image, 0, 0); _window.open(canvas.toDataURL('image/png'), '_blank'); }; image.src = src; } /** * @param {Window} window * @param {string} svgId * @param {number} width * @param {number} height * @returns {void} */ export default function download(_window, svgId, width, height) { const base64 = generateBase64(_window, svgId, width, height); toCanvas(_window, base64, width, height); }
/*global Backbone */ var app = app || {}; (function () { 'use strict'; app.Todo = Backbone.Model.extend({ defaults: { task: '' }, toggleCompleted: function () { this.save({ complete: !this.get('complete') }); }, sync: function (method, model, options) { model.attributes = _.omit(model.attributes, 'id'); Backbone.Model.prototype.sync.call(this, method, model, options); }, /* * */ url: function () { var path = this.id ? "/" + this.id : ""; return "/todos" + path; /*return "http://nztodo.app.dev/app_dev.php/todos/" + this.id;*/ }, toJSON: function () { return {todo: this.attributes}; } }); })();
import React from 'react'; import Layout from '../components/layout'; import { getAllProducts } from '../redux/actions/index' import { store } from '../redux/store'; export default () => { return ( <Layout title="home"> <h1 className="home-header">Order History</h1> </Layout> ); };
/** @namespace lsn */ ECMAScript.Extend('lsn', function (ecma) { var CActionDispatcher = ecma.action.ActionDispatcher; var proto = ecma.lang.createPrototype(CActionDispatcher); /** * @class InputListener */ this.InputListener = function (elem) { CActionDispatcher.apply(this); this.elem = ecma.dom.getElement(elem); this.setValue(); this.events = [ new ecma.dom.EventListener(elem, 'keydown', this.onKeyDown, this), new ecma.dom.EventListener(elem, 'focus', this.checkValue, this), new ecma.dom.EventListener(elem, 'blur', this.checkValue, this), new ecma.dom.EventListener(elem, 'propertychange', this.checkValue, this) ]; this.checkInterval = 75; this.checkTimeout = 10 * this.checkInterval; this.checkCount = 0; }; this.InputListener.prototype = proto; proto.setValue = function () { this.currentValue = ecma.dom.getValue(this.elem); }; proto.onKeyDown = function (event) { if (this.intervalId) return; this.intervalId = ecma.dom.setInterval(this.checkValue, this.checkInterval, this); }; proto.checkValue = function () { // ecma.console.log('check value'); var value = ecma.dom.getValue(this.elem); if (this.currentValue != value) { this.clearInterval(); var prevValue = this.currentValue; this.setValue(); this.dispatchAction('change', this.currentValue, prevValue); } else { this.checkCount++; if ((this.checkInterval * this.checkCount) > this.checkTimeout) { // ecma.console.log('-timeout'); this.clearInterval(); } } }; proto.clearInterval = function () { // ecma.console.log('-clear'); ecma.dom.clearInterval(this.intervalId); this.intervalId = null; this.checkCount = 0; }; /** * @function destroy */ proto.destroy = function () { this.clearInterval(); for (var i = 0; i < this.events.length; i++) { try { this.events[i].remove(); } catch (ex) { } } this.events = []; }; });
version https://git-lfs.github.com/spec/v1 oid sha256:50538607856d24295645ba34e9193b6b375a7bee19707de7239458264e05fbd3 size 43336
const { prefix } = require('../../config.json'); module.exports = function() { return { name: "help", description: "Lise de l'ensemble des commandes, ou des infos sur une commande spécifique.", aliases: ['commands'], usage: "[command name]", execute(message, args) { const {commands} = message.client; const data = []; if (args.length == 1){ data.push("Voici la liste des commandes :"); data.push(commands.map(command => command.name).join(", ")); data.push(`\nVous pouvez utiliser \`${prefix}help [command name]\` pour obtenir des informations sur une commande spécifique.`); } else{ if (!commands.has(args[1])) { return message.reply("Commande invalide."); } const command = commands.get(args[1]); data.push(`**Nom :** ${command.name}`); if (command.description) data.push(`**Description:** ${command.description}`); if (command.aliases) data.push(`**Alias :** ${command.aliases.join(', ')}`); if (command.usage) data.push(`**Utilisation :** ${prefix}${command.name} ${command.usage}`); data.push(`**Délai :** ${command.cooldown || 3} seconde(s)`); } message.author.send(data, { split: true }) .then(() => { if (message.channel.type !=='dm'){ message.channel.send("La liste des commandes vous a été envoyée en message privé."); } }) .catch(() => message.reply("Il semblerait que je ne puisse pas vous envoyer de message privé !")); } } }
(function () { 'use strict'; // Logs controller angular .module('logs') .controller('LogsController', LogsController); LogsController.$inject = ['$scope', '$state', 'Authentication', 'logResolve']; function LogsController ($scope, $state, Authentication, log) { var vm = this; vm.authentication = Authentication; vm.log = log; vm.error = null; vm.form = {}; vm.remove = remove; vm.save = save; // Remove existing Log function remove() { if (confirm('Tem certeza de que deseja excluir?')) { vm.log.$remove($state.go('logs.list')); } } // Save Log function save(isValid) { console.log('entrou'); if (!isValid) { $scope.$broadcast('show-errors-check-validity', 'vm.form.logForm'); return false; } // TODO: move create/update logic to service if (vm.log._id) { vm.log.$update(successCallback, errorCallback); } else { vm.log.$save(successCallback, errorCallback); } function successCallback(res) { $state.go('logs.list', { logId: res._id }); } function errorCallback(res) { vm.error = res.data.message; } } } }());
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require jquery.remotipart //= require moment //= require tinymce //= require tinymce-jquery //= require fullcalendar //= require bootstrap //= require_tree . //= require bootstrap/modal
/** * Copyright (c) 2008-2011 The Open Planning Project * * Published under the BSD license. * See https://github.com/opengeo/gxp/raw/master/license.txt for the full text * of the license. */ /** api: (define) * module = gxp.menu * class = LayerMenu * base_link = `Ext.menu.Menu <http://extjs.com/deploy/dev/docs/?class=Ext.menu.Menu>`_ */ Ext.namespace("gxp.menu"); /** api: constructor * .. class:: LayerMenu(config) * * A menu to control layer visibility. */ gxp.menu.LayerMenu = Ext.extend(Ext.menu.Menu, { /** api: config[layers] * ``GeoExt.data.LayerStore`` * The store containing layer records to be viewed in this menu. */ layers: null, /** private: method[initComponent] * Private method called to initialize the component. */ initComponent: function() { gxp.menu.LayerMenu.superclass.initComponent.apply(this, arguments); this.layers.on("add", this.onLayerAdd, this); this.onLayerAdd(); }, /** private: method[onRender] * Private method called during the render sequence. */ onRender : function(ct, position) { gxp.menu.LayerMenu.superclass.onRender.apply(this, arguments); }, /** private: method[beforeDestroy] * Private method called during the destroy sequence. */ beforeDestroy: function() { if (this.layers && this.layers.on) { this.layers.un("add", this.onLayerAdd, this); } delete this.layers; gxp.menu.LayerMenu.superclass.beforeDestroy.apply(this, arguments); }, /** private: method[onLayerAdd] * Listener called when records are added to the layer store. */ onLayerAdd: function() { this.removeAll(); // this.getEl().addClass("gxp-layer-menu"); // this.getEl().applyStyles({ // width: '', // height: '' // }); this.add( { iconCls: "gxp-layer-visibility", text: "Layer", canActivate: false }, "-" ); this.layers.each(function(record) { var layer = record.getLayer(); if(layer.displayInLayerSwitcher) { var item = new Ext.menu.CheckItem({ text: record.get("title"), checked: record.getLayer().getVisibility(), group: record.get("group"), listeners: { checkchange: function(item, checked) { record.getLayer().setVisibility(checked); } } }); if (this.items.getCount() > 2) { this.insert(2, item); } else { this.add(item); } } }, this); } }); Ext.reg('gxp_layermenu', gxp.menu.LayerMenu);
var readlineSync = require("readline-sync") var colors = require("colors") var net = require("net") var HOST = '127.0.0.1' var PORT = 8000 var client = null function OpenConnection(){ if (client) { console.log("--Connection is already open--".red) setTimeout(function () { menu() },0) return } client = new net.Socket() client.on("error", function (err) { client.destroy() client = null console.log("ERROR: connection could not be opened. Msg: %s".red, err.message) setTimeout(function(){ menu() },0) }) client.on("data",function (data) { console.log("Received: %s".cyan, data) setTimeout(function () { menu() },0) }) client.connect(PORT, HOST, function () { console.log("Connection opened successfully!".green) setTimeout(function () { menu() },0) }) } function SendData (data) { if (!client) { console.log('--Connection is not open or closed--'.red) setTimeout(function() { menu() }, 0); return } client.write(data) } function CloseConnection (){ if (!client) { console.log('--Connection is not open or closed--'.red) setTimeout(function() { menu() }, 0); return } client.destroy(); client = null console.log('Connection closed successfully!'.yellow) setTimeout(function() { menu() }, 0); } function menu (){ var lineRead = readlineSync.question('\n\nEnter option(1-Open, 2-Send, 3-Close, 4-Quit): ') switch (lineRead){ case '1': console.log('Option 1 selected') OpenConnection() break case '2': var data = readlineSync.question('Enter data to send:') SendData(data) break case '3': CloseConnection() break case '4': return break default: setTimeout(function() { menu() }, 0); } } setTimeout(function() { menu() }, 0);
#!/usr/bin/env node // WebSocket vs. Socket.IO example - common backend - from: // https://github.com/rsp/node-websocket-vs-socket.io // Copyright (c) 2015, 2016 Rafał Pocztarski // Released under MIT License (Expat) - see: // https://github.com/rsp/node-websocket-vs-socket.io/blob/master/LICENSE.md /*eslint-disable no-loop-func*/ var path = require('path'); var express = require('express'); var log = function (m) { console.error(new Date().toISOString()+' '+this.pre+m); } console.error("node-websocket-vs-socket.io\n" +"WebSocket vs. Socket.IO on Node.js with Express.js - see:\n" +"https://github.com/rsp/node-websocket-vs-socket.io#readme\n" +"Copyright (c) 2015, 2016 Rafał Pocztarski\n" +"Released under MIT License (Expat) - see:\n" +"https://github.com/rsp/node-websocket-vs-socket.io/blob/master/LICENSE.md\n"); // WebSocket: var ws = {app: express(), pre: "websocket app: ", log: log}; ws.ws = require('express-ws')(ws.app); ws.app.get('/', (req, res) => { ws.log('express connection - sending html'); res.sendFile(path.join(__dirname, 'ws.html')); }); ws.app.ws('/', (s, req) => { ws.log('incoming websocket connection'); for (var t = 0; t < 3; t++) setTimeout(() => { ws.log('sending message to client'); s.send(ws.pre+'message from server', ()=>{}); }, 1000*t); }); ws.app.listen(3001, () => ws.log('listening on http://localhost:3001/')); ws.log('starting server'); // Socket.IO: var si = {app: express(), pre: "socket.io app: ", log: log}; si.http = require('http').Server(si.app); si.io = require('socket.io')(si.http); si.app.get('/', (req, res) => { si.log('express connection - sending html'); res.sendFile(path.join(__dirname, 'si.html')); }); si.app.get('/forced', (req, res) => { si.log('express connection - sending html'); res.sendFile(path.join(__dirname, 'si-forced.html')); }); si.io.on('connection', s => { si.log('incoming socket.io connection'); for (var t = 0; t < 3; t++) setTimeout(() => { si.log('sending message to client'); s.emit('message', si.pre+'message from server'); }, 1000*t); }); si.http.listen(3002, () => si.log('listening on http://localhost:3002/')); si.log('starting server');
const ParserSymbol = require('./parser-symbol.js') const PrefixOperator = module.exports = class extends ParserSymbol { constructor (options) { super(options) } defaultNullDenotation (self, parser) { const item = this.clone() item.first = parser.expression(this.bindingPower) item.operatorType = ParserSymbol.OPERATOR_TYPE_UNARY return item } defaultLeftDenotation (self, left, parser) { throw new SyntaxError(`undefined left denotation`) } }
// usage: Ex. resWriteHead(status code, 'MIME type/internet media type'); module.exports = exports = function resWriteHead(status, contentType) { res.writeHead(status, { 'Content-Type': contentType }); };