code
stringlengths
2
1.05M
import Character from './Character.js'; import Film from './Film.js'; import Planet from './Planet.js'; const Query = ` type Query { character(id: Int!): Character! film(id: Int!): Film! planet(id: Int!): Planet! characters: [Character!] films: [Film!] planets: [Planet!] } `; export default [Query, Character, Film, Planet];
module.exports = { port: 3000, salt: '1:W_E.=V[+3 V>@P]^SmJ|j]2eG>{Ov>) $[%J(RlOqH8h++wKugFtOSUFG7o6fT', secret: '=+SU]9LloDzT*sI-lpL1y#i6[bX2HnWG}?4%`dV;n vX<b2:.T1+Aw#gJ|nZick^', redis: { host: '127.0.0.1', port: 6379 }, static_path: '/static', mongoUri: 'mongodb://127.0.0.1:27017/guide' };
var iDiagnose = {}; function getQueryVariable(variable) { var query = window.location.search.substring(1); var vars = query.split('&'); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split('='); if (decodeURIComponent(pair[0]) == variable) { return decodeURIComponent(pair[1]); } } console.log('Query variable %s not found', variable); } iDiagnose.gatherAnswers = function () { var questionParams = [ '' ], saveToLocal = function (key, value) { if (!value && !key) { throw new Error('argument error'); } if (window.localStorage) { localStorage.setItem(key, JSON.stringify(value)); } else { Cookie.write(key, JSON.stringify(value)); } }, getFromLocal = function (key) { var value = window.localStorage? localStorage.getItem(key): Cookie.read(key); if (value && value !== 'undefined') { return JSON.parse(value); } else { return []; } }; location. }; iDiagnose.gatherAnswers();
var Firebase = window.Firebase; var FirebaseAuthClient = window.FirebaseAuthClient; var App = window.App; export default Ember.Route.extend({ beforeModel: function(transition) { App.set('firebase', new Firebase(window.FIREBASE_ROOT)); if (!this.controllerFor('login').get('token')) { var loginController = this.controllerFor('login'); loginController.set('attemptedTransition', transition); this.transitionTo('login'); } } });
'use strict'; let aws = require('../config/aws'); let user = require('./user')(aws); module.exports.handler = function(event, context, callback) { // request from API Gateway console.log("Dispatch request from API Gateway: ", JSON.stringify(event)); // validate requester role Check if authAccountid is authorized const authorizedJudge = new Promise((resolve, reject) => { if (!event.authAccountid) { reject(new Error("400 Bad Request: " + JSON.stringify(event))); } else { user.getOneUser({ accountid: event.authAccountid, }).then(data => { // Authorized: Admin if (data.role === "Admin") { resolve(); } else { reject(new Error(`403 Unauthorized request: The role of the requester ${event.authAccountid} is ${data.role}`)); } }).catch(err => { reject(err); }); } }); switch (event.op) { case "me": user.getOneUser({ accountid: event.authAccountid, }).then(response => { return callback(null, response); }).catch(err => { return callback(err, null); }); break; case "listUsers": // GET /api/v1/mgnt/users/[?startKey=<startKey>] // Authenticated: Yes authorizedJudge.then(() => { return user.listUsers({ startKey: event.startKey, }); }).then(response => { return callback(null, response); }).catch(err => { return callback(err, null); }); break; case "updateOneUser": // PUT /api/v1/mgnt/users/ // Authenticated: Yes authorizedJudge.then(() => { return user.updateOneUser({ accountid: event.accountid, username: event.username, email: event.email, role: event.role, }); }).then(response => { return callback(null, response); }).catch(err => { return callback(err, null); }); break; case "deleteOneUser": // DELETE /api/v1/mgnt/users/<accountid> // Authenticated: Yes authorizedJudge.then(() => { return user.deleteOneUser({ accountid: event.accountid, }); }).then(response => { return callback(null, response); }).catch(err => { return callback(err, null); }); break; default: let error = new Error("400 Bad Request: " + JSON.stringify(event)); return callback(error, null); } };
function ConsoleCommandSender(log) { this.name = 'Server'; this.log = log; } ConsoleCommandSender.prototype.sendMessage = function(message) { this.log(message); }; function enable(api) { var split; process.stdin.resume(); process.stdin.on('data', function(chunk) { split = chunk.toString().split(/\s+/); api.fire('command', { name: split[0], args: split.slice(1, split.length), sender: new ConsoleCommandSender(api.log) }); }); } module.exports = { enable: enable };
export const aperture = {"viewBox":"0 0 8 8","children":[{"name":"path","attribs":{"d":"M4 0c-.69 0-1.34.19-1.91.5l3.22 2.34.75-2.25c-.6-.36-1.31-.59-2.06-.59zm-2.75 1.13c-.76.73-1.25 1.74-1.25 2.88 0 .25.02.48.06.72l3.09-2.22-1.91-1.38zm5.63.13l-1.22 3.75h2.19c.08-.32.16-.65.16-1 0-1.07-.44-2.03-1.13-2.75zm-4.72 3.22l-1.75 1.25c.55 1.13 1.6 1.99 2.88 2.22l-1.13-3.47zm1.56 1.53l.63 1.97c1.33-.12 2.46-.88 3.09-1.97h-3.72z"}}]};
'use strict'; /*jshint asi: true */ var test = require('tap').test var readproctab = require('../').readproctab function inspect(obj, depth) { console.error(require('util').inspect(obj, false, depth || 5, true)); } function bycmd(proctab) { return proctab.reduce(function (acc, p) { acc[p.cmd] = p; return acc; }, {}) } test('\ndefault flags', function (t) { var data = [], ended; var stream = readproctab( { interval: 50 }) .on('data', [].push.bind(data)) .on('end', function () { var bc = bycmd(data[0]); var proc = bc.node; t.equal(data.length, 2, 'pushed two readproctabs') t.ok(data[0].length > 10, 'first data point has at least 10 processes') t.ok(proc.environ.length > 0, 'includes environ for node process') t.end() }) setTimeout(stream.end.bind(stream), 140); }) test('\ncustom flags', function (t) { var data = [], ended; var flags = readproctab.flagsFillAll ^ readproctab.flags.PROC_FILLENV; var stream = readproctab( { interval: 50, flags: flags }) .on('data', [].push.bind(data)) .on('end', function () { var bc = bycmd(data[0]); var proc = bc.node; t.equal(data.length, 2, 'pushed two readproctabs') t.ok(data[0].length > 10, 'first data point has at least 10 processes') t.equal(proc.environ.length, 0, 'does not include environ for node process') t.end() }) setTimeout(stream.end.bind(stream), 140); })
var chai = require('chai') var expect = chai.expect var sinon = require('sinon') var proxyquire = require('proxyquire') var q = require('q') var testUtils = require('../test-utils') chai.use(require('sinon-chai')) describe('Helpers', function () { var storageMock var helpers beforeEach(function () { storageMock = { teams: { get: sinon.stub().returns(q({admins: ['rick']})) } } helpers = proxyquire('../../src/lib/helpers', { './storage': storageMock }) }) it('should export direct address listeners', function () { expect(helpers.directAddress).to.equal('direct_mention,direct_message,mention') }) describe('isAdminMessage', function () { var message beforeEach(function () { message = { team: 'rickandmorty', user: 'rick' } }) it('should call callback if user is admin', function () { return helpers.isAdminMessage(message) .then(function (result) { expect(storageMock.teams.get).to.have.been.calledWith(message.team) expect(result).to.be.true }) }) it('should not call callback if user is not admin', function () { message.user = 'morty' return helpers.isAdminMessage(message) .then(function (result) { expect(storageMock.teams.get).to.have.been.calledWith(message.team) expect(result).to.be.false }) }) it('should reply if there was an error', function () { var error = new Error('GAZORPAZORP') storageMock.teams.get.returns(q.reject(error)) return testUtils.promiseFail(helpers.isAdminMessage(message)) .catch(function (err) { expect(err).to.equal(error) }) }) }) describe('onlyAdmin', function () { var cb var message var botMock beforeEach(function () { cb = sinon.stub() message = { team: 'rickandmorty', user: 'rick' } botMock = { reply: sinon.stub() } }) it('should call callback if user is admin', function () { return helpers.onlyAdmin(cb)(botMock, message) .then(function () { expect(storageMock.teams.get).to.have.been.calledWith(message.team) expect(cb).to.have.been.calledWith(botMock, message) expect(botMock.reply).not.to.have.been.called }) }) it('should not call callback if user is not admin', function () { message.user = 'morty' return helpers.onlyAdmin(cb)(botMock, message) .then(function () { expect(storageMock.teams.get).to.have.been.calledWith(message.team) expect(cb).not.to.have.been.called expect(botMock.reply).to.have.been.calledWithMatch(message, new RegExp('^Sorry')) }) }) it('should reply if there was an error', function () { var error = new Error('GAZORPAZORP') storageMock.teams.get.returns(q.reject(error)) return helpers.onlyAdmin(cb)(botMock, message) .then(function () { expect(storageMock.teams.get).to.have.been.calledWith(message.team) expect(cb).not.to.have.been.called expect(botMock.reply).to.have.been.calledWithMatch(message, new RegExp('^Whoops')) }) }) }) describe('formatUserId', function () { it('should format known user', function () { expect(helpers.formatUserId('<@c17>')).to.equal('c17') }) it('should strip @ from unknown users', function () { expect(helpers.formatUserId('@c17')).to.equal('c17') }) }) })
'use strict'; var Forestry = require('forestry'), File = require('vinyl'), path = require('path'); function findExistingFile (file, tree) { return tree.find(function (n) { return n.data.path === file.path; }); } function getParentPath(childPath) { var parentPath = path.resolve(childPath, '../'); if (parentPath !== childPath) { return parentPath; } return path.parse(childPath).root; } function findParentFolder (file, tree) { var parentPath = getParentPath(file.path); return tree.find(function (n) { return n.data.path === parentPath; }); } function createInitialTree() { var base = path.parse(process.cwd()).root; return new Forestry.Node(new File({ cwd: base, base: base, path: base })); } function decodeNode(node) { if (node.data.stat && node.data.stat.isFile) { return { cwd: node.data.cwd, base: node.data.base, path: node.data.path, relative: node.data.relative, name: path.basename(node.data.path), isFile: node.data.stat ? node.data.stat.isFile() : false, isDirectory: node.data.stat ? node.data.stat.isDirectory() : true }; } return node.data; } function FileTree(transform) { this._tree = null; this._transform = transform; } FileTree.prototype = { addFileToTree: function (file) { this._tree = this._tree || createInitialTree(); var found = findExistingFile(file, this._tree), newNode; if (found) { found.data = file; return; } found = findParentFolder(file, this._tree) || this.addFileToTree(new File({ cwd: file.cwd, base: file.base, path: getParentPath(file.path) })); newNode = new Forestry.Node(file); found.addChild(newNode); return newNode; }, getTree: function (file) { var self = this; if (!this._tree) { return null; } var treeFrag = this._tree; while (treeFrag.children.length === 1) { treeFrag = treeFrag.children[0]; } treeFrag = treeFrag.clone(function (file) { return file.clone(); }); if (self._transform) { treeFrag = self._transform(treeFrag, file); } return treeFrag; }, getNonCircularTree: function () { var tree = this.getTree(); if (tree) { return tree.map(decodeNode); } return null; } }; module.exports = FileTree;
import React from 'react' import Helmet from 'react-helmet' import { PageContent } from 'components' import { ArticlesLayout, SeriesList } from 'blog/components' export default () => ( <PageContent> <ArticlesLayout> <Helmet> <title>Article Series</title> </Helmet> <h1>Article Series!</h1> <SeriesList /> </ArticlesLayout> </PageContent> )
'use strict'; import React from 'react'; import {Button} from 'react-bootstrap'; require('styles/Show.scss'); class ShowComponent extends React.Component { constructor(props, context) { super(props, context); this.state = { corn: {} }; } yesHandler() { this.increment(); this.getRandom(); } noHandler() { this.getRandom(); } getRandom() { fetch('http://localhost:3000/corns/random', { credentials: 'same-origin', mode: 'no-cors' }) .then((res) => { return res.json(); }).then((json) => { json.previewImages = []; for (let i = 1; i <= json.thumbsCount; ++i) { json.previewImages.push(json.img.replace('{index}', i)); } json.previewImage = json.previewImages[0]; this.setState({corn: json}); this.slideImages(); }); } slideImages() { if (this.interval) clearInterval(this.interval); let num = 0; this.interval = window.setInterval(() => { let index = (num % this.state.corn.thumbsCount) + 1; this.state.corn.previewImage = this.state.corn.previewImages[index]; this.setState({corn: this.state.corn}); num++; }, 1000); } increment() { fetch('http://localhost:3000/corns/increment', { method: 'POST', body: JSON.stringify({category: this.state.corn.category}), headers: { 'Accept': 'application/json', 'content-type': 'application/json' }, credentials: 'same-origin' }); } componentWillMount() { this.getRandom(); } render() { return ( <div className="show-component"> <div className="container"> <h1>{this.state.corn.name}</h1> <img src={this.state.corn.previewImage}/> {/* <div dangerouslySetInnerHTML={{ __html: this.state.corn.iframe }}></div> */} <Button className="col-md-6" onClick={this.yesHandler.bind(this)}>YES</Button> <Button className="col-md-6" onClick={this.noHandler.bind(this)}>NO</Button> </div> </div> ); } } ShowComponent.displayName = 'ShowComponent'; // Uncomment properties you need // ShowComponent.propTypes = {}; // ShowComponent.defaultProps = {}; export default ShowComponent;
#!/usr/bin/env node require('node-env-file')( `${__dirname}/../.env` ) const MyObj = Object.create( require('../lib/MyObject'), { input: { value: process.argv[2] } } ), Bcrypt = require('bcrypt') MyObj.P( Bcrypt.hash, [ MyObj.input, parseInt( process.env.SALT ) ] ) .then( console.log ) .catch( e => console.log( e.stack || e ) )
import { uid, ktv } from '../../../utils'; import ACTION_TYPES from './action-types'; const STATUS = [ 'FETCHING', ]; // // export default Object.assign(ktv(STATUS, uid), ACTION_TYPES);
function checkArrayLength(array, length){ if(array.length === length){ return array; } else { throw "invalid number of elements"; }; }; function sampleElement(inputObject){ var alength = inputObject.length; return inputObject[(Math.floor(Math.random() * alength))] } function Die(inputLetters){ this.letters = checkArrayLength(inputLetters, 6); this.setLetter = function(){ this.letter = sampleElement(this.letters); } this.setLetter(); }
var caminte = require('caminte'); var Schema = caminte.Schema; var mysql_user = process.env.mysql_user; var mysql_password = process.env.mysql_password; var mysql_host = process.env.mysql_host; var mysql_db = process.env.mysql_db; var config = { driver : "mysql", host : mysql_host, port : "3306", username : mysql_user, password : mysql_password, database : mysql_db }; var schema = new Schema(config.driver, config); var Post = schema.define('Post', { title: { type: schema.String, limit: 255 }, content: { type: schema.Text }, params: { type: schema.JSON }, date: { type: schema.Date, default: Date.now }, published: { type: schema.Boolean, default: false, index: true } }); var User = schema.define('User', { name: String, bio: schema.Text, approved: Boolean, joinedAt: Date, age: Number }); //relations User.hasMany(Post, {as: 'posts', foreignKey: 'userId'}); Post.belongsTo(User, {as: 'author', foreignKey: 'userId'}); module.exports = schema;
var searchData= [ ['sestado',['SEstado',['../_s_juego_8h.html#a700cd4eb8f1695daf7b74a3b5088ad94',1,'SJuego.h']]] ];
var test = require("test"); var a = require("a"); test.assert(a, "Should load an empty module with comments.");
'use strict' let hidePhaseView = Backbone.View.extend({ tagName: "div", className: "modal-dialog", initialize: function(data) { this.data = data || undefined; }, events: { "click #close": "close", "click #delete": "hidephases" }, close: function() { $('#dialog-crud').modal('hide') }, hidephases: function (e){ e.preventDefault(); let id = $("#phase-id").val(); let dialog = new hidePhaseView({title: new Array(S.collection.get("phases").get(id).toJSON())}); //Update let model = S.collection.get("phases").get(id); model.set({'isactive': false}); let options = { error: (error) => { $('#dialog-crud').modal('hide'); S.logger("bg-danger", "Couldn't Phase Delete", true); }, success: (model, reponse) => { S.collection.get("phases").remove(model) $('#dialog-crud').modal('hide'); let phaseView = new PhaseView(); phaseView.render(); S.logger("bg-success", "Delete Phase Succesfully", true); }, wait: true, headers: S.addAuthorizationHeader().headers, url: S.fixUrl(model.url()) } let campaign = S.collection.get("phases"); S.collection.get("phases").add(model) .sync("update", model, options); }, render: function(){ let template = $("#phase-modal-hide").html(); let compiled = Handlebars.compile(template); this.$el.html(compiled(this.data)); $("#dialog-crud").html(this.$el); }, });
describe('graph_03', function() { const assert = chai.assert const styles = testGlobals.styles const logTime = testGlobals.logTime const stringifyCondensed = testGlobals.stringifyCondensed const approxEquals = KerasJS.testUtils.approxEquals const layers = KerasJS.layers const testParams = { layers: [ { branch: 0, layerClass: 'Conv2D', attrs: { name: 'layer_0_0', filters: 4, kernel_size: 3, strides: 1, padding: 'valid', data_format: 'channels_last', dilation_rate: 1, activation: 'relu', use_bias: true }, inbound: [], outbound: ['layer_1'] }, { branch: 1, layerClass: 'Conv2D', attrs: { name: 'layer_1_0', filters: 4, kernel_size: 3, strides: 1, padding: 'valid', data_format: 'channels_last', dilation_rate: 1, activation: 'relu', use_bias: true }, inbound: [], outbound: ['layer_1'] }, { branch: [0, 1], layerClass: 'Multiply', attrs: { name: 'layer_1' }, inbound: ['layer_0_0', 'layer_1_0'], outbound: [] } ] } const key = 'graph_03' before(function() { console.log(`\n%c${key}`, styles.h1) }) /********************************************************* * CPU *********************************************************/ describe('CPU', function() { const title = `[CPU] ${testParams.layers.map(layer => layer.layerClass).join('-')}` let branch_0 = [] let branch_1 = [] let mergeLayer before(function() { console.log('\n%cCPU', styles.h2) console.log(`\n%c${title}`, styles.h3) let weightsIndexOffset = 0 for (let i = 0; i < testParams.layers.length; i++) { const layerConfig = testParams.layers[i] const attrs = Object.assign(layerConfig.attrs) const layerInstance = new layers[layerConfig.layerClass](attrs) const weightsArr = TEST_DATA[key].weights .slice(weightsIndexOffset, weightsIndexOffset + layerInstance.params.length) .map(w => new KerasJS.Tensor(w.data, w.shape)) weightsIndexOffset += layerInstance.params.length layerInstance.setWeights(weightsArr) if (layerConfig.branch === 0) { branch_0.push(layerInstance) } else if (layerConfig.branch === 1) { branch_1.push(layerInstance) } else { mergeLayer = layerInstance } } // run dummy data once through to cache shape inference data, etc. let empty_0 = new KerasJS.Tensor([], TEST_DATA[key].inputs[0].shape) for (let i = 0; i < branch_0.length; i++) { empty_0 = branch_0[i].call(empty_0) } let empty_1 = new KerasJS.Tensor([], TEST_DATA[key].inputs[1].shape) for (let i = 0; i < branch_1.length; i++) { empty_1 = branch_1[i].call(empty_1) } let empty = mergeLayer.call([empty_0, empty_1]) }) it(title, function() { let t_0 = new KerasJS.Tensor(TEST_DATA[key].inputs[0].data, TEST_DATA[key].inputs[0].shape) let t_1 = new KerasJS.Tensor(TEST_DATA[key].inputs[1].data, TEST_DATA[key].inputs[1].shape) console.log('%cin (branch 0)', styles.h4, stringifyCondensed(t_0.tensor)) console.log('%cin (branch 1)', styles.h4, stringifyCondensed(t_1.tensor)) const startTime = performance.now() for (let i = 0; i < branch_0.length; i++) { t_0 = branch_0[i].call(t_0) } for (let i = 0; i < branch_1.length; i++) { t_1 = branch_1[i].call(t_1) } let t = mergeLayer.call([t_0, t_1]) const endTime = performance.now() console.log('%cout', styles.h4, stringifyCondensed(t.tensor)) logTime(startTime, endTime) const dataExpected = new Float32Array(TEST_DATA[key].expected.data) const shapeExpected = TEST_DATA[key].expected.shape assert.deepEqual(t.tensor.shape, shapeExpected) assert.isTrue(approxEquals(t.tensor, dataExpected)) }) }) /********************************************************* * GPU *********************************************************/ describe('GPU', function() { const title = `[GPU] ${testParams.layers.map(layer => layer.layerClass).join('-')}` let branch_0 = [] let branch_1 = [] let mergeLayer before(function() { console.log('\n%cGPU', styles.h2) console.log(`\n%c${title}`, styles.h3) let weightsIndexOffset = 0 for (let i = 0; i < testParams.layers.length; i++) { const layerConfig = testParams.layers[i] const layerInstance = new layers[layerConfig.layerClass](Object.assign(layerConfig.attrs, { gpu: true })) const weightsArr = TEST_DATA[key].weights .slice(weightsIndexOffset, weightsIndexOffset + layerInstance.params.length) .map(w => new KerasJS.Tensor(w.data, w.shape)) weightsIndexOffset += layerInstance.params.length layerInstance.setWeights(weightsArr) layerInstance.inbound = layerConfig.inbound layerInstance.outbound = layerConfig.outbound if (layerConfig.branch === 0) { branch_0.push(layerInstance) } else if (layerConfig.branch === 1) { branch_1.push(layerInstance) } else { mergeLayer = layerInstance } } // run dummy data once through to cache shape inference data, etc. let empty_0 = new KerasJS.Tensor([], TEST_DATA[key].inputs[0].shape) for (let i = 0; i < branch_0.length; i++) { empty_0 = branch_0[i].call(empty_0) } let empty_1 = new KerasJS.Tensor([], TEST_DATA[key].inputs[1].shape) for (let i = 0; i < branch_1.length; i++) { empty_1 = branch_1[i].call(empty_1) } let empty = mergeLayer.call([empty_0, empty_1]) }) it(title, function() { let t_0 = new KerasJS.Tensor(TEST_DATA[key].inputs[0].data, TEST_DATA[key].inputs[0].shape) let t_1 = new KerasJS.Tensor(TEST_DATA[key].inputs[1].data, TEST_DATA[key].inputs[1].shape) console.log('%cin (branch 0)', styles.h4, stringifyCondensed(t_0.tensor)) console.log('%cin (branch 1)', styles.h4, stringifyCondensed(t_1.tensor)) const startTime = performance.now() for (let i = 0; i < branch_0.length; i++) { t_0 = branch_0[i].call(t_0) } for (let i = 0; i < branch_1.length; i++) { t_1 = branch_1[i].call(t_1) } let t = mergeLayer.call([t_0, t_1]) const endTime = performance.now() console.log('%cout', styles.h4, stringifyCondensed(t.tensor)) logTime(startTime, endTime) const dataExpected = new Float32Array(TEST_DATA[key].expected.data) const shapeExpected = TEST_DATA[key].expected.shape assert.deepEqual(t.tensor.shape, shapeExpected) assert.isTrue(approxEquals(t.tensor, dataExpected)) }) }) })
import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import Reports from '../../../components/rpt/production/Reports'; import * as Actions from '../../../actions/rpt/production/Actions'; function mapStateToProps(state) { return { ProdRpt: state.ProdReports }; } function mapDispatchToProps(dispatch) { return bindActionCreators(Actions, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(Reports);
/* * 1Derscore.js v0.1.3 * A whole mess of useful functional programming helpers without extending any built-in object for The One Developers <1Devs/> * * http://ali.md/1derscore * License: http://alimd.mit-license.org/ */ (function (root, doc, undef) { // encapsulate all variables so they don't become global vars 'use strict'; // set javascript engine to strict mode var _ = root._ = root._ || {}; /** * Console polyfill * @return {[type]} [description] */ _.con = (function(){ if(root.console && root.console.log) return root.console; var prop, method, con = {}, empty = {}, dummy = function() {}, properties = 'memory'.split(','), methods = ('assert,clear,count,debug,dir,dirxml,error,exception,group,' + 'groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,' + 'table,time,timeEnd,timeStamp,trace,warn').split(','); while (prop = properties.pop()) if(!con[prop]) con[prop] = empty; while (method = methods.pop()) if(!con[method]) con[method] = dummy; return con; })(); /** * IE version detection * @return {Number} version of ie or undefined */ _.ie = (function(){ var ver = -1, // Return value assumes failure. ua = root.navigator.userAgent, msie = ua.indexOf('MSIE '), trident = ua.indexOf('Trident/'), // IE 11 (or newer) rv = trident>0 ? ua.indexOf('rv:') : undef; if (msie > 0) // IE 10 or older => return version number return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10); // IE 11 (or newer) => return version number return trident>0 ? parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10) : undef; })(); /** * Find current script src path * @return {[type]} the path or `undefined` if can't find */ _.getScriptPath = function(){ if(!doc.currentScript){ if(window.console) console.warn('Cannot find current script path for load external file :('); return undef; } return doc.currentScript.src; }; /** * Find current script directory path. * @return {Script} the path */ _.getScriptDirectory = function(){ var src = _.getScriptPath() || '', slashPos = src.lastIndexOf('/'); if(slashPos===-1) return ''; return src.substring(0, slashPos+1); }; /** * Convert a number in rage of [x1, x2] to range of [y1, y2] * @param {Number} x Input number * @param {Array} arr Range: [x1,x2,y1,y2] * @param {Boolean} protect Protect y between [y1, y2] * @return {Number} calculated `y` in range */ _.getInRange = Math.getInRange = function (x, arr, protect) { var y = ((arr[3] - arr[2]) * (x - arr[0])) / (arr[1] - arr[0]) + arr[2]; if(protect) y = y < arr[2] ? arr[2] : (y > arr[3] ? arr[3] : y); return y; }; /** * Get selected in docuemnt * @return {object} selected object or text in ie */ var getSelectionItem = (function(gs, s){ return root[gs] || doc[gs] || function(){ return doc[s] && doc[s].createRange().text; }; })('getSelection', 'selection'); _.getSelection = function () { return getSelectionItem(); }; /** * Get selected text in docuemnt * @return {string} selected text */ _.getSelectionText = function () { return _.getSelection().toString(); }; /** * Simple way to clone an object * @param {Object} obj Target object * @return {Object} New object instance */ _.cloneObj = function (obj) { return JSON.parse(JSON.stringify(obj)); }; })(window, document);
export function RoutesRun ($rootScope, $state, $auth, AclService, $timeout, API, ContextService, moment) { 'ngInject' AclService.resume() /*eslint-disable */ let deregisterationCallback = $rootScope.$on('$stateChangeStart', function (event, toState) { if (toState.data && toState.data.auth) { if (!$auth.isAuthenticated()) { event.preventDefault() return $state.go('login') } } $rootScope.bodyClass = 'hold-transition login-page' }) function stateChange () { $timeout(function () { // fix sidebar var neg = $('.main-header').outerHeight() + $('.main-footer').outerHeight() var window_height = $(window).height() var sidebar_height = $('.sidebar').height() if ($('body').hasClass('fixed')) { $('.content-wrapper, .right-side').css('min-height', window_height - $('.main-footer').outerHeight()) } else { if (window_height >= sidebar_height) { $('.content-wrapper, .right-side').css('min-height', window_height - neg) } else { $('.content-wrapper, .right-side').css('min-height', sidebar_height) } } // get user current context if ($auth.isAuthenticated() && !$rootScope.me) { ContextService.getContext() .then((response) => { response = response.plain() $rootScope.me = response.data }) } }) } $rootScope.$on('$destroy', deregisterationCallback) $rootScope.$on('$stateChangeSuccess', stateChange) /*eslint-enable */ }
import test from 'tape'; import React from 'react'; import {mount} from 'enzyme'; import ArcSeries from 'plot/series/arc-series'; import {testRenderWithProps, GENERIC_XYPLOT_SERIES_PROPS} from '../test-utils'; import ArcSeriesExample from '../../showcase/radial-chart/arc-series-example'; testRenderWithProps(ArcSeries, GENERIC_XYPLOT_SERIES_PROPS); test('ArcSeries: Showcase Example - ArcSeriesExample', t => { const $ = mount(<ArcSeriesExample />); t.equal($.text(), 'UPDATE-4-2024-4-2024', 'should find the right text content'); // multiplied by two to account for shadow listeners t.equal($.find('.rv-xy-plot__series--arc').length, 4, 'should find the right number of series'); t.equal($.find('.rv-xy-plot__series--arc path').length, 2 * 8, 'with the right number of arc in them'); t.end(); });
/* globals module require */ "use strict"; const SimpleMovieProvider = require("./simple-movie-provider"); const DetailMovieProvider = require("./detail-movie-provider"); module.exports = { getSimpleMovieProvider() { return SimpleMovieProvider.getImdbSimpleMovies(); }, getDetailMovieProvider() { return DetailMovieProvider.getImdbDetailMovies(); } };
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ /*globals installedChunks hotAddUpdateChunk parentHotUpdateCallback importScripts XMLHttpRequest $require$ $hotChunkFilename$ $hotMainFilename$ */ module.exports = function() { function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disable-line no-unused-vars hotAddUpdateChunk(chunkId, moreModules); if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules); } //$semicolon function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars importScripts($require$.p + $hotChunkFilename$); } function hotDownloadManifest(callback) { // eslint-disable-line no-unused-vars return new Promise(function(resolve, reject) { if(typeof XMLHttpRequest === "undefined") return reject(new Error("No browser support")); try { var request = new XMLHttpRequest(); var requestPath = $require$.p + $hotMainFilename$; request.open("GET", requestPath, true); request.timeout = 10000; request.send(null); } catch(err) { return reject(err); } request.onreadystatechange = function() { if(request.readyState !== 4) return; if(request.status === 0) { // timeout reject(new Error("Manifest request to " + requestPath + " timed out.")); } else if(request.status === 404) { // no update available resolve(); } else if(request.status !== 200 && request.status !== 304) { // other failure reject(new Error("Manifest request to " + requestPath + " failed.")); } else { // success try { var update = JSON.parse(request.responseText); } catch(e) { reject(e); return; } resolve(update); } } }); } function hotDisposeChunk(chunkId) { //eslint-disable-line no-unused-vars delete installedChunks[chunkId]; } };
/** * Catalog node */ 'use strict'; /** * Module dependencies. */ var errors = require('../errors'); var utils = require('../utils'); /** * Initialize a new `CatalogNode` client. */ function CatalogNode(consul) { this.consul = consul; } /** * Lists nodes in a given DC */ CatalogNode.prototype.list = function(opts, callback) { if (!callback) { callback = opts; opts = {}; } else if (typeof opts === 'string') { opts = { dc: opts }; } opts = utils.normalizeKeys(opts); var req = { name: 'catalog.node.list', path: '/catalog/nodes', }; utils.options(req, opts); this.consul._get(req, utils.body, callback); }; /** * Lists the services provided by a node */ CatalogNode.prototype.services = function(opts, callback) { if (typeof opts === 'string') { opts = { node: opts }; } opts = utils.normalizeKeys(opts); var req = { name: 'catalog.node.services', path: '/catalog/node/{node}', params: { node: opts.node }, }; if (!opts.node) { return callback(this.consul._err(errors.Validation('node required'), req)); } utils.options(req, opts); this.consul._get(req, utils.body, callback); }; /** * Module Exports. */ exports.CatalogNode = CatalogNode;
import npm from './npm' import nuget from './nuget' export default (name) => { if (npm.isPackageFile(name)) return npm if (nuget.isPackageFile(name)) return nuget }
module.exports = { servers: { one: { host: 'The IP for your Digital Oceans, AWS, or EC2 ', // Your IP for Linux test or production server IP username: 'root', // pem: '/home/user/.ssh/id_rsa', // mup doesn't support '~' alias for home directory // password: 'your password for your droplet after you change it', // or leave blank for authenticate from ssh-agent // opts: { // (optional) // port: 22, // }, } }, meteor: { // name: 'the name of you app goes here', path: './', // lets you add docker volumes (optional) // // volumes: { // passed as '-v /host/path:/container/path' to the docker run command // // "/host/path": "/container/path", // "/second/host/path": "/second/container/path" // }, docker: { image:'kadirahq/meteord:base', // image: 'abernix/meteord:base', // use this image if using Meteor 1.4+ (optional) // lets you add/overwrite any parameter on the docker run command (optional) // // args:[ // "--link=myCustomMongoDB:myCustomMongoDB", // linking example // "--memory-reservation 200M" // memory reservation example // ] }, servers: { one: {}, two: {}, three: {} // list of servers to deploy, from the 'servers' list }, buildOptions: { // (--server-only--) Skip building mobile apps even if mobile platforms have been added. (optional) // serverOnly: true, // (--architecture--) Builds the server for a different architecture // // than your developer machine's architecture. // architecture: 'os.linux.x86_64', // (--debug--) Build in debug mode (don't minify, etc). (optional) // // debug: true, // (--server--) Location where mobile builds connect to the Meteor server. // server: 'http://example.com:80', // Use this if you using a domain name // server: 'http://xxx.xx.xxx.xx:80', // Use this if you dont have a domain name or sub domain name // server: 'http://sub.example.com:80', // Use this if you using a sub domain name // default (optional) // // cleanAfterBuild: true, // (--directory--) Output a directory (rather than a tarball) for the // // application server bundle. If the output location exists, it will be // // recursively deleted first. Defaults to /tmp/<uuid> (optional) // // buildLocation: '/my/build/folder', // (--mobile-settings--) Set optional data for the initial value of // // Meteor.settings in your mobile application. A new value for // // Meteor.settings can be set later by the server as part of hot code push. (optional) // // mobileSettings: { // yourMobileSetting: "setting value" // } // (--allow-incompatible-update--) Allow packages in your project to be // // upgraded or downgraded to versions that are potentially incompatible // // with the current versions, if required to satisfy all package version // // constraints. (optional) // }, env: { // You can even use NoIP for this as long you point the domain to your // // IP on your server. // // ROOT_URL: 'http://xxx.xx.xxx.xx', // use this if you dont have a domain name or sub domain ROOT_URL: 'http://example.com', // Use this if you using a domain name // ROOT_URL: 'http://sub.example.com', // Use this if you using a sub domain name MONGO_URL: 'mongodb://localhost/meteor' }, // log: { // (optional) // driver: 'syslog', // opts: { // "syslog-address":'udp://syslogserverurl.com:1234' // } // }, // ssl: { // port: 443, // crt: 'bundle.crt', // key: 'private.key', // }, deployCheckWaitTime: 60 // default 10 }, mongo: { // (optional) oplog: true, port: 27017, servers: { one: {}, }, }, };
angular.module('module_downloadManager') .factory('$localeDurations', [function () { return { 'one': { year: '{} year', month: '{} month', week: '{} week', day: '{} day', hour: '{}h', minute: '{}m', second: '{}s', millisecond: '{} millisecond' }, 'other': { year: '{} years', month: '{} months', week: '{} weeks', day: '{} days', hour: '{}h', minute: '{}m', second: '{}s', millisecond: '{} milliseconds' } }; }]) /* * module_downloadManager_torrentsTable */ .controller('module_downloadManager_torrentsTable', function ($scope, webservice_downloadManager, config) { $scope.torrents = {}; // A dictionnary of torrents $scope.torrentInfo = null; $scope.loading = 0; $scope.orderBy = '-created_time'; $scope.update_torrent = function(torrent) { $scope.torrents[torrent.id] = torrent; torrent.progress = torrent.downloaded / torrent.length; torrent.remaining_time = (torrent.length - torrent.downloaded) / torrent.download_speed; torrent.last_update = Date.now(); $scope.downloaded = 0; $scope.uploaded = 0; $scope.download_speed = 0; $scope.upload_speed = 0; angular.forEach($scope.torrents, function(torrent, id) { $scope.downloaded += torrent.downloaded; $scope.uploaded += torrent.uploaded; $scope.download_speed += torrent.download_speed; $scope.upload_speed += torrent.upload_speed; }); }; $scope.getAll = function() { $scope.loading++; webservice_downloadManager.getAll().success(function(data) { $scope.torrents = {}; data.forEach(function(torrent) { $scope.update_torrent(torrent); }); $scope.loading--; }); }; $scope.remove = function(torrent) { if (confirm("Remove '" + torrent.name + "' ?") === true) { $scope.loading++; webservice_downloadManager.remove(torrent.id).success(function(data) { $('#module_downloadManager_torrentsTable_Modal_Info').modal('hide'); $scope.loading--; }); } }; $scope.showInfo = function(torrent) { $scope.torrentInfo = torrent.id; if(!torrent.last_update || !torrent.peers || !torrent.files) { $scope.loading++; webservice_downloadManager.get(torrent.id).success(function(torrent) { $scope.update_torrent(torrent); $('#module_downloadManager_torrentsTable_Modal_Info').modal('show'); $scope.loading--; }); } else { $('#module_downloadManager_torrentsTable_Modal_Info').modal('show'); } }; $scope.showAdd = function() { $('#module_downloadManager_torrentsTable_Modal_Add').modal('show'); }; $scope.addTorrentSuccess = function() { $('#module_downloadManager_torrentsTable_Modal_Add').modal('hide'); }; /* Launch first update */ $scope.getAll(); /* Real-time update logic */ var socket = io(config.backend.url + 'download'); socket.on('update', function(torrent_id, data) { $scope.$apply(function() { if(torrent_id) { $scope.update_torrent(data); } else { data.forEach(function(torrent) { $scope.update_torrent(torrent); }); } }); }); socket.on('remove', function(torrent_id) { if(!torrent_id) { return; } $scope.$apply(function() { delete $scope.torrents[torrent_id]; }); }); });
MINI_MAP= { "index" : "1", "data": { "1": { "areaSize" :"{{0,1024},{0,922}}", "height": "922", "width": "1024" }, "2": { "areaSize" :"{{0,1536},{0,1383}}", "height": "1383", "width": "1536" }, "3": { "areaSize" :"{{0,2048},{0,1844}}", "height": "1844", "width": "2048" }, "4": { "areaSize" :"{{0,2560},{0,2305}}", "height": "2305", "width": "2560" }, "5": { "areaSize" :"{{0,3072},{0,2766}}", "height": "2766", "width": "3072" } }, "right_bottom": { "point2d": { "xpos": "745", "ypos": "849" }, "point3d": { "xpos": "21.5212", "ypos": "0.0", "zpos": "-142.718" } }, "roleInitialize": { "point2d": { "xpos": "798", "ypos": "523" }, "point3d": { "xpos": "45.2622", "ypos": "0.0", "zpos": "3.1499" } }, "top_left": { "point2d": { "xpos": "206", "ypos": "65" }, "point3d": { "xpos": "-221.082", "ypos": "0.0", "zpos": "209.4" } } }
#!/usr/bin/env node 'use strict'; const Chalk = require('chalk'); const log = console.log; const hive = require('../handlers/hive'); const QuickSearch = require('../handlers/quick_search'); const Log = require('../utils/log_utils'); const Utils = require('../utils/utils'); const GradleUtils = require('../utils/gradle_utils'); const Constants = require('../utils/constants'); const Install = require('../tasks/install'); function handle(found, info, mainGradleFilePath) { if (found.length > 0) { Log.title(`${Chalk.yellow(info.repository.url)} is already in the main build.gradle`); } else { const result = GradleUtils.findLineToInsertDependency(info.repository) const lineText = GradleUtils.getRepositoryLine(info.repository.server, info.repository.url) GradleUtils.insertLineInFile(mainGradleFilePath, lineText, result); // pretty print the lines log(Chalk.green(lineText.trim())); // }).catch(err => { // log(`\nYou are missing the following lines in your main ${Chalk.green('build.gradle')} `) // log(Chalk.yellow(Constants.ALL_PROJECTS_EMPTY_TEMPLATE)) // log(`\nAfter you add the lines, re-run the drone command`) // }); } } function handleRepositoryInjection(info) { if (info.repository.url) { const mainGradleFilePath = GradleUtils.mainGradleFilePath(); const found = Utils.findStringInFileSync(info.repository.url, mainGradleFilePath) handle(found, info, mainGradleFilePath) } } function findLineAndInsertDependency(module, dep, gradleFilePath) { const result = GradleUtils.findLineToInsertLibrary(module); // get the full line to insert in the file const line = hive.getCompileLine(dep) // insert the line in fht file GradleUtils.insertLineInFile(gradleFilePath, line, result); // pretty print the lines return line.trim(); } function injectDependency(dep, dependenciesLength, module, gradleFilePath) { const found = Utils.findStringInFileSync(dep.dependency, gradleFilePath) if (found.length === 0) { const resultLine = findLineAndInsertDependency(module, dep, gradleFilePath); Log.title(`Inserted: ${Chalk.green(resultLine.trim())}`) } else { Log.titleError(`${Chalk.green(dep.dependency)} is already there @ line ${found[0].line}`) } } function handleGradleDependencyInjection(appModule, dependencies, gradleFilePath) { if (GradleUtils.gradleFileExistsIn(appModule)) { var actions = dependencies.map(dep => { return injectDependency(dep, dependencies.length, appModule, gradleFilePath); }) Promise.all(actions); } else { Log.titleError(`Can't find this gradle file`) log(gradleFilePath) } } function handleSearchResponse(results, appModule, library) { const bestMatch = QuickSearch.findBestMatch(results, library) if (bestMatch) { hive.getWithVersions(bestMatch) .then(info => { handleRepositoryInjection(info); const gradlePath = GradleUtils.gradleFilePath(appModule); handleGradleDependencyInjection(appModule, info.dependencies, gradlePath); }); } else { Log.titleError(`Couldnt find ${library}`); } } function handleInsertion(libraries, appModule) { libraries.forEach(library => { QuickSearch.search(library) .then(results => { handleSearchResponse(results, appModule, library); }) }) } // Main code // const self = module.exports = { init: (input) => { if (input.length <= 1) { Log.titleError(`You need to specify the module`); return; } const appModule = input[input.length-1]; const libraries = input.splice(0, input.length-1) handleInsertion(libraries, appModule); // Install.downloadDependencies() } };
/* eslint-disable no-nested-ternary */ /* eslint-disable no-shadow */ import React, { Component } from 'react'; import styled from 'styled-components'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { FlatList, View, ScrollView } from 'react-native'; import { ButtonGroup, Card, Icon } from 'react-native-elements'; import { SafeAreaView } from 'react-navigation'; import { Button, ViewContainer, LoadingContainer, NotificationListItem, } from 'components'; import { colors, fonts, normalize, getHeaderForceInset } from 'config'; import { t } from 'utils'; import { getUnreadNotifications, getParticipatingNotifications, getAllNotifications, markAsRead, markRepoAsRead, getNotificationsCount, markAllNotificationsAsRead, } from '../index'; const mapStateToProps = state => ({ unread: state.notifications.unread, participating: state.notifications.participating, all: state.notifications.all, issue: state.issue.issue, locale: state.auth.locale, isPendingUnread: state.notifications.isPendingUnread, isPendingParticipating: state.notifications.isPendingParticipating, isPendingAll: state.notifications.isPendingAll, isPendingMarkAllNotificationsAsRead: state.notifications.isPendingMarkAllNotificationsAsRead, }); const mapDispatchToProps = dispatch => bindActionCreators( { getUnreadNotifications, getParticipatingNotifications, getAllNotifications, markAsRead, markRepoAsRead, getNotificationsCount, markAllNotificationsAsRead, }, dispatch ); const StyledSafeAreaView = styled(SafeAreaView).attrs({ forceInset: getHeaderForceInset('Notifications'), })` background-color: ${colors.greyLight}; `; const ButtonGroupWrapper = styled.View` background-color: ${colors.greyLight}; padding-top: 10; padding-bottom: 10; margin-bottom: 15; `; const StyledButtonGroup = styled(ButtonGroup).attrs({ containerStyle: { height: 30, marginTop: 0, marginBottom: 0, marginLeft: 15, marginRight: 15, }, textStyle: { ...fonts.fontPrimaryBold, }, selectedTextStyle: { color: colors.black, }, })``; const RepositoryContainer = styled(Card).attrs({ containerStyle: { padding: 0, marginTop: 0, marginBottom: 25, }, })``; const HeaderContainer = styled.View` flex-direction: row; align-items: center; padding-left: 5; padding-vertical: 8; background-color: ${colors.greyLight}; `; const RepositoryOwnerAvatar = styled.Image` border-radius: 13; width: 26; height: 26; `; const RepositoryTitle = styled.Text` color: ${colors.primaryDark}; ${fonts.fontPrimarySemiBold}; margin-left: 10; flex: 1; `; const MarkAsReadIconRepo = styled.TouchableOpacity` flex: 0.15; justify-content: center; align-items: center; `; const Container = styled.View` flex: 1; background-color: transparent; `; const TextContainer = styled.View` flex: 1; align-items: center; justify-content: center; `; const NoneTitle = styled.Text` padding-horizontal: 15; font-size: ${normalize(16)}; text-align: center; ${fonts.fontPrimary}; `; const MarkAllAsReadButtonContainer = styled.View` margin-top: 0; margin-bottom: 20; `; const ContentBlock = styled.View` flex: 1; `; const NotificationsType = { UNREAD: 0, PARTICIPATING: 1, ALL: 2, }; class Notifications extends Component { props: { getUnreadNotifications: Function, getParticipatingNotifications: Function, getAllNotifications: Function, markAsRead: Function, markRepoAsRead: Function, getNotificationsCount: Function, markAllNotificationsAsRead: Function, unread: Array, participating: Array, all: Array, locale: string, isPendingUnread: boolean, isPendingParticipating: boolean, isPendingAll: boolean, isPendingMarkAllNotificationsAsRead: boolean, navigation: Object, }; constructor(props) { super(props); this.state = { type: NotificationsType.UNREAD, contentBlockHeight: null, }; this.switchType = this.switchType.bind(this); this.notifications = this.notifications.bind(this); this.isLoading = this.isLoading.bind(this); } componentDidMount() { this.getNotifications(); } componentWillReceiveProps(nextProps) { const pendingType = this.getPendingType(); if ( !nextProps.isPendingMarkAllNotificationsAsRead && this.props.isPendingMarkAllNotificationsAsRead && !this.isLoading() ) { this.getNotificationsForCurrentType()(); } if (!nextProps[pendingType] && this.props[pendingType]) { this.props.getNotificationsCount(); } } getImage(repoName) { const notificationForRepo = this.notifications().find( notification => notification.repository.full_name === repoName ); return notificationForRepo.repository.owner.avatar_url; } getNotifications() { this.props.getUnreadNotifications(); this.props.getParticipatingNotifications(); this.props.getAllNotifications(); this.props.getNotificationsCount(); } getNotificationsForCurrentType() { const { getUnreadNotifications, getParticipatingNotifications, getAllNotifications, } = this.props; const { type } = this.state; switch (type) { case NotificationsType.UNREAD: return getUnreadNotifications; case NotificationsType.PARTICIPATING: return getParticipatingNotifications; case NotificationsType.ALL: return getAllNotifications; default: return null; } } getSortedRepos = () => { const updateTimeMap = {}; this.notifications().forEach(notification => { const repoName = notification.repository.full_name; updateTimeMap[repoName] = updateTimeMap[repoName] || notification.update_time; }); return Object.keys(updateTimeMap).sort((a, b) => { return new Date(a) - new Date(b); }); }; getPendingType = () => { const { type } = this.state; switch (type) { case NotificationsType.UNREAD: return 'isPendingUnread'; case NotificationsType.PARTICIPATING: return 'isPendingParticipating'; case NotificationsType.ALL: return 'isPendingAll'; default: return null; } }; navigateToRepo = fullName => { const { navigation } = this.props; navigation.navigate('Repository', { repoId: fullName, }); }; saveContentBlockHeight = e => { const { height } = e.nativeEvent.layout; this.setState({ contentBlockHeight: height }); }; keyExtractor = (item, index) => { return index; }; isLoading() { const { unread, participating, all, isPendingUnread, isPendingParticipating, isPendingAll, } = this.props; const { type } = this.state; switch (type) { case NotificationsType.UNREAD: return unread && isPendingUnread; case NotificationsType.PARTICIPATING: return participating && isPendingParticipating; case NotificationsType.ALL: return all && isPendingAll; default: return false; } } notifications() { const { unread, participating, all } = this.props; const { type } = this.state; switch (type) { case NotificationsType.UNREAD: return unread; case NotificationsType.PARTICIPATING: return participating; case NotificationsType.ALL: return all; default: return []; } } switchType(selectedType) { const { unread, participating, all } = this.props; if (this.state.type !== selectedType) { this.setState({ type: selectedType, }); } if (selectedType === NotificationsType.UNREAD && unread.length === 0) { this.props.getUnreadNotifications(); } else if ( selectedType === NotificationsType.PARTICIPATING && participating.length === 0 ) { this.props.getParticipatingNotifications(); } else if (selectedType === NotificationsType.ALL && all.length === 0) { this.props.getAllNotifications(); } if (this.notifications().length > 0) { this.notificationsList.scrollToOffset({ x: 0, y: 0, animated: false, }); } } navigateToThread(notification) { const { markAsRead, navigation } = this.props; markAsRead(notification.id); navigation.navigate('Issue', { issueURL: notification.subject.url.replace(/pulls\/(\d+)$/, 'issues/$1'), isPR: notification.subject.type === 'PullRequest', locale: this.props.locale, }); } navigateToRepo = fullName => { const { navigation } = this.props; navigation.navigate('Repository', { repoId: fullName, }); }; renderItem = ({ item }) => { const { markAsRead, markRepoAsRead, markAllNotificationsAsRead, } = this.props; const { type } = this.state; const notifications = this.notifications().filter( notification => notification.repository.full_name === item ); const isFirstItem = this.getSortedRepos().indexOf(item) === 0; const isFirstTab = type === 0; return ( <View> {isFirstItem && isFirstTab && ( <MarkAllAsReadButtonContainer> <Button icon={{ name: 'check', type: 'octicon' }} onPress={() => markAllNotificationsAsRead()} title={t('Mark all as read')} /> </MarkAllAsReadButtonContainer> )} <RepositoryContainer> <HeaderContainer> <RepositoryOwnerAvatar source={{ uri: this.getImage(item), }} /> <RepositoryTitle onPress={() => this.navigateToRepo(item)}> {item} </RepositoryTitle> <MarkAsReadIconRepo onPress={() => markRepoAsRead(item)}> <Icon color={colors.greyDark} size={28} name="check" type="octicon" /> </MarkAsReadIconRepo> </HeaderContainer> <ScrollView> {notifications.map(notification => ( <NotificationListItem key={notification.id} notification={notification} iconAction={notificationID => markAsRead(notificationID)} navigationAction={notify => this.navigateToThread(notify)} navigation={this.props.navigation} /> ))} </ScrollView> </RepositoryContainer> </View> ); }; render() { const { type, contentBlockHeight } = this.state; const { locale } = this.props; const sortedRepos = this.getSortedRepos(); const isRetrievingNotifications = this.isLoading() && this.notifications().length === 0; const isLoadingNewNotifications = this.isLoading() && this.notifications().length > 0; return ( <ViewContainer> <Container> <StyledSafeAreaView /> <ButtonGroupWrapper> <StyledButtonGroup onPress={this.switchType} selectedIndex={type} buttons={[ t('Unread', locale), t('Participating', locale), t('All', locale), ]} /> </ButtonGroupWrapper> <ContentBlock onLayout={this.saveContentBlockHeight}> {isRetrievingNotifications && ( <TextContainer height={contentBlockHeight}> <LoadingContainer animating={isRetrievingNotifications} text={t('Retrieving notifications', locale)} center /> </TextContainer> )} {!isRetrievingNotifications && ( <FlatList ref={ref => { this.notificationsList = ref; }} removeClippedSubviews={false} onRefresh={this.getNotificationsForCurrentType()} refreshing={isLoadingNewNotifications} data={sortedRepos} keyExtractor={this.keyExtractor} renderItem={this.renderItem} ListEmptyComponent={ !isLoadingNewNotifications && ( <TextContainer height={contentBlockHeight}> <NoneTitle> {t( "You don't have any notifications of this type", locale )} </NoneTitle> </TextContainer> ) } /> )} </ContentBlock> </Container> </ViewContainer> ); } } export const NotificationsScreen = connect(mapStateToProps, mapDispatchToProps)( Notifications );
'use strict'; var redis = require('redis'); module.exports = function() { return redis.createClient({ ip: process.env.IP, port: 6379 }); };
/** * @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'devtools', 'ku', { title: 'زانیاری توخم', dialogName: 'ناوی پەنجەرەی دیالۆگ', tabName: 'ناوی بازدەر تاب', elementId: 'ناسنامەی توخم', elementType: 'جۆری توخم' } );
// Copyright IBM Corp. 2014,2016. All Rights Reserved. // Node module: loopback-boot // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT var boot = require('../'); var fs = require('fs-extra'); var path = require('path'); var expect = require('chai').expect; var sandbox = require('./helpers/sandbox'); var appdir = require('./helpers/appdir'); // add coffee-script to require.extensions require('coffee-script/register'); var SIMPLE_APP = path.join(__dirname, 'fixtures', 'simple-app'); describe('compiler', function() { beforeEach(sandbox.reset); beforeEach(appdir.init); function expectCompileToThrow(err, options, done) { if (typeof options === 'function') { done = options; options = undefined; } boot.compile(options || appdir.PATH, function(err) { expect(function() { if (err) throw err; }).to.throw(err); done(); }); } function expectCompileToNotThrow(options, done) { if (typeof options === 'function') { done = options; options = undefined; } boot.compile(options || appdir.PATH, function(err) { expect(function() { if (err) throw err; }).to.not.throw(); done(); }); } describe('from options', function() { var options, instructions, appConfig; beforeEach(function(done) { options = { application: { port: 3000, host: '127.0.0.1', restApiRoot: '/rest-api', foo: { bar: 'bat' }, baz: true, }, models: { 'foo-bar-bat-baz': { dataSource: 'the-db', }, }, dataSources: { 'the-db': { connector: 'memory', defaultForType: 'db', }, }, }; boot.compile(options, function(err, context) { if (err) return done(err); appConfig = context.instructions.application; instructions = context.instructions; done(); }); }); it('has port setting', function() { expect(appConfig).to.have.property('port', 3000); }); it('has host setting', function() { expect(appConfig).to.have.property('host', '127.0.0.1'); }); it('has restApiRoot setting', function() { expect(appConfig).to.have.property('restApiRoot', '/rest-api'); }); it('has other settings', function() { expect(appConfig).to.have.property('baz', true); expect(appConfig.foo, 'appConfig.foo').to.eql({ bar: 'bat', }); }); it('has models definition', function() { expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.eql({ name: 'foo-bar-bat-baz', config: { dataSource: 'the-db', }, definition: undefined, sourceFile: undefined, }); }); it('has datasources definition', function() { expect(instructions.dataSources).to.eql(options.dataSources); }); describe('with custom model definitions', function(done) { var dataSources = { 'the-db': { connector: 'memory' }, }; it('loads model without definition', function(done) { var instruction = boot.compile({ appRootDir: appdir.PATH, models: { 'model-without-definition': { dataSource: 'the-db', }, }, modelDefinitions: [], dataSources: dataSources, }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models[0].name) .to.equal('model-without-definition'); expect(instructions.models[0].definition).to.equal(undefined); expect(instructions.models[0].sourceFile).to.equal(undefined); done(); }); }); it('loads coffeescript models', function(done) { var modelScript = appdir.writeFileSync( 'custom-models/coffee-model-with-definition.coffee', ''); boot.compile({ appRootDir: appdir.PATH, models: { 'coffee-model-with-definition': { dataSource: 'the-db', }, }, modelDefinitions: [ { definition: { name: 'coffee-model-with-definition', }, sourceFile: modelScript, }, ], dataSources: dataSources, }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models[0].name) .to.equal('coffee-model-with-definition'); expect(instructions.models[0].definition).to.eql({ name: 'coffee-model-with-definition', }); expect(instructions.models[0].sourceFile).to.equal(modelScript); done(); }); }); it('handles sourceFile path without extension (.js)', function(done) { var modelScript = appdir.writeFileSync( 'custom-models/model-without-ext.coffee', ''); boot.compile({ appRootDir: appdir.PATH, models: { 'model-without-ext': { dataSource: 'the-db', }, }, modelDefinitions: [{ definition: { name: 'model-without-ext', }, sourceFile: pathWithoutExtension(modelScript), }], dataSources: dataSources, }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models[0].name).to.equal('model-without-ext'); expect(instructions.models[0].sourceFile).to.equal(modelScript); done(); }); }); it('handles sourceFile path without extension (.coffee)', function(done) { var modelScript = appdir.writeFileSync( 'custom-models/model-without-ext.coffee', ''); boot.compile({ appRootDir: appdir.PATH, models: { 'model-without-ext': { dataSource: 'the-db', }, }, modelDefinitions: [{ definition: { name: 'model-without-ext', }, sourceFile: pathWithoutExtension(modelScript), }], dataSources: dataSources, }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models[0].name).to.equal('model-without-ext'); expect(instructions.models[0].sourceFile).to.equal(modelScript); done(); }); }); it('sets source file path if the file exist', function(done) { var modelScript = appdir.writeFileSync( 'custom-models/model-with-definition.js', ''); boot.compile({ appRootDir: appdir.PATH, models: { 'model-with-definition': { dataSource: 'the-db', }, }, modelDefinitions: [ { definition: { name: 'model-with-definition', }, sourceFile: modelScript, }, ], dataSources: dataSources, }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models[0].name).to.equal('model-with-definition'); expect(instructions.models[0].definition).not.to.equal(undefined); expect(instructions.models[0].sourceFile).to.equal(modelScript); done(); }); }); it('does not set source file path if the file does not exist.', function(done) { boot.compile({ appRootDir: appdir.PATH, models: { 'model-with-definition-with-falsey-source-file': { dataSource: 'the-db', }, }, modelDefinitions: [ { definition: { name: 'model-with-definition-with-falsey-source-file', }, sourceFile: appdir.resolve('custom-models', 'file-does-not-exist.js'), }, ], dataSources: dataSources, }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models[0].name) .to.equal('model-with-definition-with-falsey-source-file'); expect(instructions.models[0].definition).not.to.equal(undefined); expect(instructions.models[0].sourceFile).to.equal(undefined); done(); }); }); it('does not set source file path if no source file supplied.', function(done) { boot.compile({ appRootDir: appdir.PATH, models: { 'model-with-definition-without-source-file-property': { dataSource: 'the-db', }, }, modelDefinitions: [ { definition: { name: 'model-with-definition-without-source-file-property', }, // sourceFile is not set }, ], dataSources: dataSources, }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models[0].name) .to.equal('model-with-definition-without-source-file-property'); expect(instructions.models[0].definition).not.to.equal(undefined); expect(instructions.models[0].sourceFile).to.equal(undefined); done(); }); }); it('loads models defined in `models` only.', function(done) { boot.compile({ appRootDir: appdir.PATH, models: { 'some-model': { dataSource: 'the-db', }, }, modelDefinitions: [ { definition: { name: 'some-model', }, }, { definition: { name: 'another-model', }, }, ], dataSources: dataSources, }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models.map(getNameProperty)) .to.eql(['some-model']); done(); }); }); }); }); describe('from directory', function(done) { it('loads config files', function(done) { boot.compile(SIMPLE_APP, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.eql({ name: 'User', config: { dataSource: 'db', }, definition: undefined, sourceFile: undefined, }); done(); }); }); it('merges datasource configs from multiple files', function(done) { appdir.createConfigFilesSync(); appdir.writeConfigFileSync('datasources.local.json', { db: { local: 'applied' }, }); var env = process.env.NODE_ENV || 'development'; appdir.writeConfigFileSync('datasources.' + env + '.json', { db: { env: 'applied' }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; var db = instructions.dataSources.db; expect(db).to.have.property('local', 'applied'); expect(db).to.have.property('env', 'applied'); var expectedLoadOrder = ['local', 'env']; var actualLoadOrder = Object.keys(db).filter(function(k) { return expectedLoadOrder.indexOf(k) !== -1; }); expect(actualLoadOrder, 'load order').to.eql(expectedLoadOrder); done(); }); }); it('supports .js for custom datasource config files', function(done) { appdir.createConfigFilesSync(); appdir.writeFileSync('datasources.local.js', 'module.exports = { db: { fromJs: true } };'); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; var db = instructions.dataSources.db; expect(db).to.have.property('fromJs', true); done(); }); }); it('merges new Object values', function(done) { var objectValue = { key: 'value' }; appdir.createConfigFilesSync(); appdir.writeConfigFileSync('datasources.local.json', { db: { nested: objectValue }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; var db = instructions.dataSources.db; expect(db).to.have.property('nested'); expect(db.nested).to.eql(objectValue); done(); }); }); it('deeply merges Object values', function(done) { appdir.createConfigFilesSync({}, { email: { transport: { host: 'localhost', }, }, }); appdir.writeConfigFileSync('datasources.local.json', { email: { transport: { host: 'mail.example.com', }, }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; var email = instructions.dataSources.email; expect(email.transport.host).to.equal('mail.example.com'); done(); }); }); it('deeply merges Array values of the same length', function(done) { appdir.createConfigFilesSync({}, { rest: { operations: [ { template: { method: 'POST', url: 'http://localhost:12345', }, }, ], }, }); appdir.writeConfigFileSync('datasources.local.json', { rest: { operations: [ { template: { url: 'http://api.example.com', }, }, ], }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; var rest = instructions.dataSources.rest; expect(rest.operations[0].template).to.eql({ method: 'POST', // the value from datasources.json url: 'http://api.example.com', // overriden in datasources.local.json }); done(); }); }); it('merges Array properties', function(done) { var arrayValue = ['value']; appdir.createConfigFilesSync(); appdir.writeConfigFileSync('datasources.local.json', { db: { nested: arrayValue }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; var db = instructions.dataSources.db; expect(db).to.have.property('nested'); expect(db.nested).to.eql(arrayValue); done(); }); }); it('does not cache loaded values', function(done) { appdir.createConfigFilesSync(); appdir.writeConfigFileSync('middleware.json', { 'strong-error-handler': { params: { debug: false }}, }); appdir.writeConfigFileSync('middleware.development.json', { 'strong-error-handler': { params: { debug: true }}, }); // Here we load main config and merge it with DEV overrides var bootOptions = { appRootDir: appdir.PATH, env: 'development', phases: ['load'], }; var productionBootOptions = { appRootDir: appdir.PATH, env: 'production', phases: ['load'], }; boot.compile(bootOptions, function(err, context) { var config = context.configurations.middleware; expect(config['strong-error-handler'].params.debug, 'debug in development').to.equal(true); boot.compile(productionBootOptions, function(err, context2) { var config = context2.configurations.middleware; expect(config['strong-error-handler'].params.debug, 'debug in production').to.equal(false); done(); }); }); }); it('allows env specific model-config json', function(done) { appdir.createConfigFilesSync(); appdir.writeConfigFileSync('model-config.local.json', { foo: { dataSource: 'db' }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.have.property('name', 'foo'); done(); }); }); it('allows env specific model-config json to be merged', function(done) { appdir.createConfigFilesSync(null, null, { foo: { dataSource: 'mongo', public: false }}); appdir.writeConfigFileSync('model-config.local.json', { foo: { dataSource: 'db' }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.have.property('name', 'foo'); expect(instructions.models[0].config).to.eql({ dataSource: 'db', public: false, }); done(); }); }); it('allows env specific model-config js', function(done) { appdir.createConfigFilesSync(); appdir.writeFileSync('model-config.local.js', 'module.exports = { foo: { dataSource: \'db\' } };'); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.have.property('name', 'foo'); done(); }); }); it('refuses to merge Array properties of different length', function(done) { appdir.createConfigFilesSync({ nest: { array: [], }, }); appdir.writeConfigFileSync('config.local.json', { nest: { array: [ { key: 'value', }, ], }, }); expectCompileToThrow(/array values of different length.*nest\.array/, done); }); it('refuses to merge Array of different length in Array', function(done) { appdir.createConfigFilesSync({ key: [[]], }); appdir.writeConfigFileSync('config.local.json', { key: [['value']], }); expectCompileToThrow(/array values of different length.*key\[0\]/, done); }); it('returns full key of an incorrect Array value', function(done) { appdir.createConfigFilesSync({ toplevel: [ { nested: [], }, ], }); appdir.writeConfigFileSync('config.local.json', { toplevel: [ { nested: ['value'], }, ], }); expectCompileToThrow( /array values of different length.*toplevel\[0\]\.nested/, done); }); it('refuses to merge incompatible object properties', function(done) { appdir.createConfigFilesSync({ key: [], }); appdir.writeConfigFileSync('config.local.json', { key: {}, }); expectCompileToThrow(/incompatible types.*key/, done); }); it('refuses to merge incompatible array items', function(done) { appdir.createConfigFilesSync({ key: [[]], }); appdir.writeConfigFileSync('config.local.json', { key: [{}], }); expectCompileToThrow(/incompatible types.*key\[0\]/, done); }); it('merges app configs from multiple files', function(done) { appdir.createConfigFilesSync(); appdir.writeConfigFileSync('config.local.json', { cfgLocal: 'applied' }); var env = process.env.NODE_ENV || 'development'; appdir.writeConfigFileSync('config.' + env + '.json', { cfgEnv: 'applied' }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; var appConfig = instructions.application; expect(appConfig).to.have.property('cfgLocal', 'applied'); expect(appConfig).to.have.property('cfgEnv', 'applied'); var expectedLoadOrder = ['cfgLocal', 'cfgEnv']; var actualLoadOrder = Object.keys(appConfig).filter(function(k) { return expectedLoadOrder.indexOf(k) !== -1; }); expect(actualLoadOrder, 'load order').to.eql(expectedLoadOrder); done(); }); }); it('supports .js for custom app config files', function(done) { appdir.createConfigFilesSync(); appdir.writeFileSync('config.local.js', 'module.exports = { fromJs: true };'); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; var appConfig = instructions.application; expect(appConfig).to.have.property('fromJs', true); done(); }); }); it('supports `appConfigRootDir` option', function(done) { appdir.createConfigFilesSync({ port: 3000 }); var customDir = path.resolve(appdir.PATH, 'custom'); fs.mkdirsSync(customDir); fs.renameSync( path.resolve(appdir.PATH, 'config.json'), path.resolve(customDir, 'config.json')); boot.compile({ appRootDir: appdir.PATH, appConfigRootDir: path.resolve(appdir.PATH, 'custom'), }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.application).to.have.property('port'); done(); }); }); it('supports `dsRootDir` option', function(done) { appdir.createConfigFilesSync(); var customDir = path.resolve(appdir.PATH, 'custom'); fs.mkdirsSync(customDir); fs.renameSync( path.resolve(appdir.PATH, 'datasources.json'), path.resolve(customDir, 'datasources.json')); boot.compile({ appRootDir: appdir.PATH, dsRootDir: path.resolve(appdir.PATH, 'custom'), }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.dataSources).to.have.property('db'); done(); }); }); it('supports `modelsRootDir` option', function(done) { appdir.createConfigFilesSync(); appdir.writeConfigFileSync('custom/model-config.json', { foo: { dataSource: 'db' }, }); boot.compile({ appRootDir: appdir.PATH, modelsRootDir: path.resolve(appdir.PATH, 'custom'), }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.have.property('name', 'foo'); done(); }); }); it('includes boot/*.js scripts', function(done) { appdir.createConfigFilesSync(); var initJs = appdir.writeFileSync('boot/init.js', 'module.exports = function(app) { app.fnCalled = true; };'); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); }); }); it('supports `bootDirs` option', function(done) { appdir.createConfigFilesSync(); var initJs = appdir.writeFileSync('custom-boot/init.js', 'module.exports = function(app) { app.fnCalled = true; };'); boot.compile({ appRootDir: appdir.PATH, bootDirs: [path.dirname(initJs)], }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); }); }); it('should resolve relative path in `bootDirs`', function(done) { appdir.createConfigFilesSync(); var initJs = appdir.writeFileSync('custom-boot/init.js', 'module.exports = function(app) { app.fnCalled = true; };'); boot.compile({ appRootDir: appdir.PATH, bootDirs: ['./custom-boot'], }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); }); }); it('should resolve non-relative path in `bootDirs`', function(done) { appdir.createConfigFilesSync(); var initJs = appdir.writeFileSync('custom-boot/init.js', ''); boot.compile({ appRootDir: appdir.PATH, bootDirs: ['custom-boot'], }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); }); }); it('ignores index.js in `bootDirs`', function(done) { appdir.createConfigFilesSync(); appdir.writeFileSync('custom-boot/index.js', ''); boot.compile({ appRootDir: appdir.PATH, bootDirs: ['./custom-boot'], }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.bootScripts).to.have.length(0); done(); }); }); it('prefers coffeescript over json in `appRootDir/bootDir`', function(done) { appdir.createConfigFilesSync(); var coffee = appdir.writeFileSync('./custom-boot/init.coffee', ''); appdir.writeFileSync('./custom-boot/init.json', {}); boot.compile({ appRootDir: appdir.PATH, bootDirs: ['./custom-boot'], }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.bootScripts).to.eql([coffee]); done(); }); }); it('prefers coffeescript over json in `bootDir` non-relative path', function(done) { appdir.createConfigFilesSync(); var coffee = appdir.writeFileSync('custom-boot/init.coffee', ''); appdir.writeFileSync('custom-boot/init.json', ''); boot.compile({ appRootDir: appdir.PATH, bootDirs: ['custom-boot'], }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.bootScripts).to.eql([coffee]); done(); }); }); it('supports `bootScripts` option', function(done) { appdir.createConfigFilesSync(); var initJs = appdir.writeFileSync('custom-boot/init.js', 'module.exports = function(app) { app.fnCalled = true; };'); boot.compile({ appRootDir: appdir.PATH, bootScripts: [initJs], }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); }); }); it('should remove duplicate scripts', function(done) { appdir.createConfigFilesSync(); var initJs = appdir.writeFileSync('custom-boot/init.js', 'module.exports = function(app) { app.fnCalled = true; };'); boot.compile({ appRootDir: appdir.PATH, bootDirs: [path.dirname(initJs)], bootScripts: [initJs], }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); }); }); it('should resolve relative path in `bootScripts`', function(done) { appdir.createConfigFilesSync(); var initJs = appdir.writeFileSync('custom-boot/init.js', 'module.exports = function(app) { app.fnCalled = true; };'); boot.compile({ appRootDir: appdir.PATH, bootScripts: ['./custom-boot/init.js'], }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); }); }); it('should resolve non-relative path in `bootScripts`', function(done) { appdir.createConfigFilesSync(); var initJs = appdir.writeFileSync('custom-boot/init.js', ''); boot.compile({ appRootDir: appdir.PATH, bootScripts: ['custom-boot/init.js'], }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); }); }); it('resolves missing extensions in `bootScripts`', function(done) { appdir.createConfigFilesSync(); var initJs = appdir.writeFileSync('custom-boot/init.js', ''); boot.compile({ appRootDir: appdir.PATH, bootScripts: ['./custom-boot/init'], }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); }); }); it('resolves missing extensions in `bootScripts` in module relative path', function(done) { appdir.createConfigFilesSync(); var initJs = appdir.writeFileSync( 'node_modules/custom-boot/init.js', ''); boot.compile({ appRootDir: appdir.PATH, bootScripts: ['custom-boot/init'], }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); }); }); it('resolves module relative path for `bootScripts`', function(done) { appdir.createConfigFilesSync(); var initJs = appdir.writeFileSync('node_modules/custom-boot/init.js', ''); boot.compile({ appRootDir: appdir.PATH, bootScripts: ['custom-boot/init.js'], }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.bootScripts).to.eql([initJs]); done(); }); }); it('explores `bootScripts` in app relative path', function(done) { appdir.createConfigFilesSync(); var appJs = appdir.writeFileSync('./custom-boot/init.js', ''); appdir.writeFileSync('node_modules/custom-boot/init.js', ''); boot.compile({ appRootDir: appdir.PATH, bootScripts: ['custom-boot/init.js'], }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.bootScripts).to.eql([appJs]); done(); }); }); it('ignores models/ subdirectory', function(done) { appdir.createConfigFilesSync(); appdir.writeFileSync('models/my-model.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.bootScripts).to.not.have.property('models'); done(); }); }); it('throws when models-config.json contains 1.x `properties`', function(done) { appdir.createConfigFilesSync({}, {}, { foo: { properties: { name: 'string' }}, }); expectCompileToThrow(/unsupported 1\.x format/, done); }); it('throws when model-config.json contains 1.x `options.base`', function(done) { appdir.createConfigFilesSync({}, {}, { Customer: { options: { base: 'User' }}, }); expectCompileToThrow(/unsupported 1\.x format/, done); }); it('loads models from `./models`', function(done) { appdir.createConfigFilesSync({}, {}, { Car: { dataSource: 'db' }, }); appdir.writeConfigFileSync('models/car.json', { name: 'Car' }); appdir.writeFileSync('models/car.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.eql({ name: 'Car', config: { dataSource: 'db', }, definition: { name: 'Car', }, sourceFile: path.resolve(appdir.PATH, 'models', 'car.js'), }); done(); }); }); it('loads coffeescript models from `./models`', function(done) { appdir.createConfigFilesSync({}, {}, { Car: { dataSource: 'db' }, }); appdir.writeConfigFileSync('models/car.json', { name: 'Car' }); appdir.writeFileSync('models/car.coffee', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.eql({ name: 'Car', config: { dataSource: 'db', }, definition: { name: 'Car', }, sourceFile: path.resolve(appdir.PATH, 'models', 'car.coffee'), }); done(); }); }); it('supports `modelSources` option', function(done) { appdir.createConfigFilesSync({}, {}, { Car: { dataSource: 'db' }, }); appdir.writeConfigFileSync('custom-models/car.json', { name: 'Car' }); appdir.writeFileSync('custom-models/car.js', ''); boot.compile({ appRootDir: appdir.PATH, modelSources: ['./custom-models'], }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.eql({ name: 'Car', config: { dataSource: 'db', }, definition: { name: 'Car', }, sourceFile: path.resolve(appdir.PATH, 'custom-models', 'car.js'), }); done(); }); }); it('supports `sources` option in `model-config.json`', function(done) { appdir.createConfigFilesSync({}, {}, { _meta: { sources: ['./custom-models'], }, Car: { dataSource: 'db' }, }); appdir.writeConfigFileSync('custom-models/car.json', { name: 'Car' }); appdir.writeFileSync('custom-models/car.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.eql({ name: 'Car', config: { dataSource: 'db', }, definition: { name: 'Car', }, sourceFile: path.resolve(appdir.PATH, 'custom-models', 'car.js'), }); done(); }); }); it('supports sources relative to node_modules', function(done) { appdir.createConfigFilesSync({}, {}, { User: { dataSource: 'db' }, }); boot.compile({ appRootDir: appdir.PATH, modelSources: [ 'loopback/common/models', 'loopback/common/dir-does-not-exist', ], }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0]).to.eql({ name: 'User', config: { dataSource: 'db', }, definition: require('loopback/common/models/user.json'), sourceFile: require.resolve('loopback/common/models/user.js'), }); done(); }); }); it('resolves relative path in `modelSources` option', function(done) { appdir.createConfigFilesSync({}, {}, { Car: { dataSource: 'db' }, }); appdir.writeConfigFileSync('custom-models/car.json', { name: 'Car' }); var appJS = appdir.writeFileSync('custom-models/car.js', ''); boot.compile({ appRootDir: appdir.PATH, modelSources: ['./custom-models'], }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0].sourceFile).to.equal(appJS); done(); }); }); it('resolves module relative path in `modelSources` option', function(done) { appdir.createConfigFilesSync({}, {}, { Car: { dataSource: 'db' }, }); appdir.writeConfigFileSync('node_modules/custom-models/car.json', { name: 'Car' }); var appJS = appdir.writeFileSync( 'node_modules/custom-models/car.js', ''); boot.compile({ appRootDir: appdir.PATH, modelSources: ['custom-models'], }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0].sourceFile).to.equal(appJS); done(); }); }); it('resolves relative path in `sources` option in `model-config.json`', function(done) { appdir.createConfigFilesSync({}, {}, { _meta: { sources: ['./custom-models'], }, Car: { dataSource: 'db' }, }); appdir.writeConfigFileSync('custom-models/car.json', { name: 'Car' }); var appJS = appdir.writeFileSync('custom-models/car.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0].sourceFile).to.equal(appJS); done(); }); }); it('resolves module relative path in `sources` option in model-config.json', function(done) { appdir.createConfigFilesSync({}, {}, { _meta: { sources: ['custom-models'], }, Car: { dataSource: 'db' }, }); appdir.writeConfigFileSync('node_modules/custom-models/car.json', { name: 'Car' }); var appJS = appdir.writeFileSync( 'node_modules/custom-models/car.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models).to.have.length(1); expect(instructions.models[0].sourceFile).to.equal(appJS); done(); }); }); it('handles model definitions with no code', function(done) { appdir.createConfigFilesSync({}, {}, { Car: { dataSource: 'db' }, }); appdir.writeConfigFileSync('models/car.json', { name: 'Car' }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models).to.eql([{ name: 'Car', config: { dataSource: 'db', }, definition: { name: 'Car', }, sourceFile: undefined, }]); done(); }); }); it('excludes models not listed in `model-config.json`', function(done) { appdir.createConfigFilesSync({}, {}, { Car: { dataSource: 'db' }, }); appdir.writeConfigFileSync('models/car.json', { name: 'Car' }); appdir.writeConfigFileSync('models/bar.json', { name: 'Bar' }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; var models = instructions.models.map(getNameProperty); expect(models).to.eql(['Car']); done(); }); }); it('includes models used as Base models', function(done) { appdir.createConfigFilesSync({}, {}, { Car: { dataSource: 'db' }, }); appdir.writeConfigFileSync('models/car.json', { name: 'Car', base: 'Vehicle', }); appdir.writeConfigFileSync('models/vehicle.json', { name: 'Vehicle', }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; var models = instructions.models; var modelNames = models.map(getNameProperty); expect(modelNames).to.eql(['Vehicle', 'Car']); expect(models[0].config).to.equal(undefined); done(); }); }); it('excludes pre-built base models', function(done) { appdir.createConfigFilesSync({}, {}, { Car: { dataSource: 'db' }, }); appdir.writeConfigFileSync('models/car.json', { name: 'Car', base: 'Model', }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; var modelNames = instructions.models.map(getNameProperty); expect(modelNames).to.eql(['Car']); done(); }); }); it('sorts models, base models first', function(done) { appdir.createConfigFilesSync({}, {}, { Vehicle: { dataSource: 'db' }, FlyingCar: { dataSource: 'db' }, Car: { dataSource: 'db' }, }); appdir.writeConfigFileSync('models/car.json', { name: 'Car', base: 'Vehicle', }); appdir.writeConfigFileSync('models/vehicle.json', { name: 'Vehicle', }); appdir.writeConfigFileSync('models/flying-car.json', { name: 'FlyingCar', base: 'Car', }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; var modelNames = instructions.models.map(getNameProperty); expect(modelNames).to.eql(['Vehicle', 'Car', 'FlyingCar']); done(); }); }); it('detects circular Model dependencies', function(done) { appdir.createConfigFilesSync({}, {}, { Vehicle: { dataSource: 'db' }, Car: { dataSource: 'db' }, }); appdir.writeConfigFileSync('models/car.json', { name: 'Car', base: 'Vehicle', }); appdir.writeConfigFileSync('models/vehicle.json', { name: 'Vehicle', base: 'Car', }); expectCompileToThrow(/cyclic dependency/i, done); }); it('uses file name as default value for model name', function(done) { appdir.createConfigFilesSync({}, {}, { Car: { dataSource: 'db' }, }); appdir.writeConfigFileSync('models/car.json', {}); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; var modelNames = instructions.models.map(getNameProperty); expect(modelNames).to.eql(['Car']); done(); }); }); it('uses `OrderItem` as default model name for file with name `order-item`', function(done) { appdir.createConfigFilesSync({}, {}, { OrderItem: { dataSource: 'db' }, }); appdir.writeConfigFileSync('models/order-item.json', {}); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; var modelNames = instructions.models.map(getNameProperty); expect(modelNames).to.eql(['OrderItem']); done(); }); }); it('uses `OrderItem` as default model name for file with name `order_item`', function(done) { appdir.createConfigFilesSync({}, {}, { OrderItem: { dataSource: 'db' }, }); appdir.writeConfigFileSync('models/order_item.json', {}); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; var modelNames = instructions.models.map(getNameProperty); expect(modelNames).to.eql(['OrderItem']); done(); }); }); it('uses `OrderItem` as default model name for file with name `order item`', function(done) { appdir.createConfigFilesSync({}, {}, { OrderItem: { dataSource: 'db' }, }); appdir.writeConfigFileSync('models/order item.json', {}); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; var modelNames = instructions.models.map(getNameProperty); expect(modelNames).to.eql(['OrderItem']); done(); }); }); it('overrides `default model name` by `name` in model definition', function(done) { appdir.createConfigFilesSync({}, {}, { overrideCar: { dataSource: 'db' }, }); appdir.writeConfigFileSync('models/car.json', { name: 'overrideCar' }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; var modelNames = instructions.models.map(getNameProperty); expect(modelNames).to.eql(['overrideCar']); done(); }); }); it('overwrites model with same default name', function(done) { appdir.createConfigFilesSync({}, {}, { 'OrderItem': { dataSource: 'db' }, }); appdir.writeConfigFileSync('models/order-item.json', { properties: { price: { type: 'number' }, }, }); appdir.writeFileSync('models/order-item.js', ''); appdir.writeConfigFileSync('models/orderItem.json', { properties: { quantity: { type: 'number' }, }, }); var appJS = appdir.writeFileSync('models/orderItem.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models).to.eql([{ name: 'OrderItem', config: { dataSource: 'db', }, definition: { name: 'OrderItem', properties: { quantity: { type: 'number' }, }, }, sourceFile: appJS, }]); done(); }); }); it('overwrites model with same name in model definition', function(done) { appdir.createConfigFilesSync({}, {}, { 'customOrder': { dataSource: 'db' }, }); appdir.writeConfigFileSync('models/order1.json', { name: 'customOrder', properties: { price: { type: 'number' }, }, }); appdir.writeFileSync('models/order1.js', ''); appdir.writeConfigFileSync('models/order2.json', { name: 'customOrder', properties: { quantity: { type: 'number' }, }, }); var appJS = appdir.writeFileSync('models/order2.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.models).to.eql([{ name: 'customOrder', config: { dataSource: 'db', }, definition: { name: 'customOrder', properties: { quantity: { type: 'number' }, }, }, sourceFile: appJS, }]); done(); }); }); it('returns a new copy of JSON data', function(done) { appdir.createConfigFilesSync(); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; instructions.application.modified = true; boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.application).to.not.have.property('modified'); done(); }); }); }); describe('for mixins', function() { describe(' - mixinDirs', function(done) { function verifyMixinIsFoundViaMixinDirs(sourceFile, mixinDirs, done) { var appJS = appdir.writeFileSync(sourceFile, ''); boot.compile({ appRootDir: appdir.PATH, mixinDirs: mixinDirs, }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.mixins[0].sourceFile).to.eql(appJS); done(); }); } it('supports `mixinDirs` option', function(done) { verifyMixinIsFoundViaMixinDirs('custom-mixins/other.js', ['./custom-mixins'], done); }); it('resolves relative path in `mixinDirs` option', function(done) { verifyMixinIsFoundViaMixinDirs('custom-mixins/other.js', ['./custom-mixins'], done); }); it('resolves module relative path in `mixinDirs` option', function(done) { verifyMixinIsFoundViaMixinDirs( 'node_modules/custom-mixins/other.js', ['custom-mixins'], done); }); }); describe(' - mixinSources', function() { beforeEach(function() { appdir.createConfigFilesSync({}, {}, { Car: { dataSource: 'db' }, }); appdir.writeConfigFileSync('models/car.json', { name: 'Car', mixins: { 'TimeStamps': {}}, }); }); function verifyMixinIsFoundViaMixinSources(sourceFile, mixinSources, done) { var appJS = appdir.writeFileSync(sourceFile, ''); boot.compile({ appRootDir: appdir.PATH, mixinSources: mixinSources, }, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.mixins[0].sourceFile).to.eql(appJS); done(); }); } it('supports `mixinSources` option', function(done) { verifyMixinIsFoundViaMixinSources('mixins/time-stamps.js', ['./mixins'], done); }); it('resolves relative path in `mixinSources` option', function(done) { verifyMixinIsFoundViaMixinSources('custom-mixins/time-stamps.js', ['./custom-mixins'], done); }); it('resolves module relative path in `mixinSources` option', function(done) { verifyMixinIsFoundViaMixinSources( 'node_modules/custom-mixins/time-stamps.js', ['custom-mixins'], done); }); it('supports `mixins` option in `model-config.json`', function(done) { appdir.createConfigFilesSync({}, {}, { _meta: { mixins: ['./custom-mixins'], }, Car: { dataSource: 'db', }, }); var appJS = appdir.writeFileSync('custom-mixins/time-stamps.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.mixins[0].sourceFile).to.eql(appJS); done(); }); }); it('sets by default `mixinSources` to `mixins` directory', function(done) { var appJS = appdir.writeFileSync('mixins/time-stamps.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.mixins[0].sourceFile).to.eql(appJS); done(); }); }); it('loads only mixins used by models', function(done) { var appJS = appdir.writeFileSync('mixins/time-stamps.js', ''); appdir.writeFileSync('mixins/foo.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.mixins).to.have.length(1); expect(instructions.mixins[0].sourceFile).to.eql(appJS); done(); }); }); it('loads mixins from model using mixin name in JSON file', function(done) { var appJS = appdir.writeFileSync('mixins/time-stamps.js', ''); appdir.writeConfigFileSync('mixins/time-stamps.json', { name: 'Timestamping', }); appdir.writeConfigFileSync('models/car.json', { name: 'Car', mixins: { 'Timestamping': {}}, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.mixins).to.have.length(1); expect(instructions.mixins[0].sourceFile).to.eql(appJS); done(); }); }); it('loads mixin only once for dirs common to mixinDirs & mixinSources', function(done) { var appJS = appdir.writeFileSync( 'custom-mixins/time-stamps.js', ''); var options = { appRootDir: appdir.PATH, mixinDirs: ['./custom-mixins'], mixinSources: ['./custom-mixins'], }; boot.compile(options, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.mixins).to.have.length(1); expect(instructions.mixins[0].sourceFile).to.eql(appJS); done(); }); }); it('loads mixin from mixinSources, when it is also found in mixinDirs', function(done) { appdir.writeFileSync('mixinDir/time-stamps.js', ''); var appJS = appdir.writeFileSync('mixinSource/time-stamps.js', ''); var options = { appRootDir: appdir.PATH, mixinDirs: ['./mixinDir'], mixinSources: ['./mixinSource'], }; boot.compile(options, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.mixins).to.have.length(1); expect(instructions.mixins[0].sourceFile).to.eql(appJS); done(); }); }); it('loads mixin from the most recent mixin definition', function(done) { appdir.writeFileSync('mixins1/time-stamps.js', ''); var mixins2 = appdir.writeFileSync('mixins2/time-stamps.js', ''); var options = { appRootDir: appdir.PATH, mixinSources: ['./mixins1', './mixins2'], }; boot.compile(options, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.mixins).to.have.length(1); expect(instructions.mixins[0].sourceFile).to.eql(mixins2); done(); }); }); }); describe('name normalization', function() { var options; beforeEach(function() { options = { appRootDir: appdir.PATH, mixinDirs: ['./custom-mixins'] }; appdir.writeFileSync('custom-mixins/foo.js', ''); appdir.writeFileSync('custom-mixins/time-stamps.js', ''); appdir.writeFileSync('custom-mixins/camelCase.js', ''); appdir.writeFileSync('custom-mixins/PascalCase.js', ''); appdir.writeFileSync('custom-mixins/space name.js', ''); }); it('supports classify', function(done) { options.normalization = 'classify'; boot.compile(options, function(err, context) { if (err) return done(err); var instructions = context.instructions; var mixins = instructions.mixins; var mixinNames = mixins.map(getNameProperty); expect(mixinNames).to.eql([ 'CamelCase', 'Foo', 'PascalCase', 'SpaceName', 'TimeStamps', ]); done(); }); }); it('supports dasherize', function(done) { options.normalization = 'dasherize'; boot.compile(options, function(err, context) { if (err) return done(err); var instructions = context.instructions; var mixins = instructions.mixins; var mixinNames = mixins.map(getNameProperty); expect(mixinNames).to.eql([ 'camel-case', 'foo', 'pascal-case', 'space-name', 'time-stamps', ]); done(); }); }); it('supports custom function', function(done) { var normalize = function(name) { return name.toUpperCase(); }; options.normalization = normalize; boot.compile(options, function(err, context) { if (err) return done(err); var instructions = context.instructions; var mixins = instructions.mixins; var mixinNames = mixins.map(getNameProperty); expect(mixinNames).to.eql([ 'CAMELCASE', 'FOO', 'PASCALCASE', 'SPACE NAME', 'TIME-STAMPS', ]); done(); }); }); it('supports none', function(done) { options.normalization = 'none'; boot.compile(options, function(err, context) { if (err) return done(err); var instructions = context.instructions; var mixins = instructions.mixins; var mixinNames = mixins.map(getNameProperty); expect(mixinNames).to.eql([ 'camelCase', 'foo', 'PascalCase', 'space name', 'time-stamps', ]); done(); }); }); it('supports false', function(done) { options.normalization = false; boot.compile(options, function(err, context) { if (err) return done(err); var instructions = context.instructions; var mixins = instructions.mixins; var mixinNames = mixins.map(getNameProperty); expect(mixinNames).to.eql([ 'camelCase', 'foo', 'PascalCase', 'space name', 'time-stamps', ]); done(); }); }); it('defaults to classify', function(done) { boot.compile(options, function(err, context) { if (err) return done(err); var instructions = context.instructions; var mixins = instructions.mixins; var mixinNames = mixins.map(getNameProperty); expect(mixinNames).to.eql([ 'CamelCase', 'Foo', 'PascalCase', 'SpaceName', 'TimeStamps', ]); done(); }); }); it('throws error for invalid normalization format', function(done) { options.normalization = 'invalidFormat'; expectCompileToThrow(/Invalid normalization format - "invalidFormat"/, options, done); }); }); it('overrides default mixin name, by `name` in JSON', function(done) { appdir.writeFileSync('mixins/foo.js', ''); appdir.writeConfigFileSync('mixins/foo.json', { name: 'fooBar' }); var options = { appRootDir: appdir.PATH, mixinDirs: ['./mixins'], }; boot.compile(options, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.mixins[0].name).to.eql('fooBar'); done(); }); }); it('extends definition from JSON with same file name', function(done) { var appJS = appdir.writeFileSync('custom-mixins/foo-bar.js', ''); appdir.writeConfigFileSync('custom-mixins/foo-bar.json', { description: 'JSON file name same as JS file name', }); appdir.writeConfigFileSync('custom-mixins/FooBar.json', { description: 'JSON file name same as normalized name of mixin', }); var options = { appRootDir: appdir.PATH, mixinDirs: ['./custom-mixins'], normalization: 'classify', }; boot.compile(options, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.mixins).to.eql([ { name: 'FooBar', description: 'JSON file name same as JS file name', sourceFile: appJS, }, ]); }); done(); }); }); }); describe('for middleware', function() { function testMiddlewareRegistration(middlewareId, sourceFile, done) { var json = { initial: {}, custom: {}, }; json.custom[middlewareId] = { params: 'some-config-data', }; appdir.writeConfigFileSync('middleware.json', json); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.middleware).to.eql({ phases: ['initial', 'custom'], middleware: [ { sourceFile: sourceFile, config: { phase: 'custom', params: 'some-config-data', }, }, ], }); done(); }); } var sourceFileForUrlNotFound; beforeEach(function() { fs.copySync(SIMPLE_APP, appdir.PATH); sourceFileForUrlNotFound = require.resolve( 'loopback/server/middleware/url-not-found'); }); it('emits middleware instructions', function(done) { testMiddlewareRegistration('loopback/server/middleware/url-not-found', sourceFileForUrlNotFound, done); }); it('emits middleware instructions for fragment', function(done) { testMiddlewareRegistration('loopback#url-not-found', sourceFileForUrlNotFound, done); }); it('supports `middlewareRootDir` option', function(done) { var middlewareJson = { initial: {}, custom: { 'loopback/server/middleware/url-not-found': { params: 'some-config-data', }, }, }; var customDir = path.resolve(appdir.PATH, 'custom'); fs.mkdirsSync(customDir); fs.writeJsonSync(path.resolve(customDir, 'middleware.json'), middlewareJson); boot.compile({ appRootDir: appdir.PATH, middlewareRootDir: customDir, }, function(err, context) { var instructions = context.instructions; expect(instructions.middleware).to.eql({ phases: ['initial', 'custom'], middleware: [ { sourceFile: sourceFileForUrlNotFound, config: { phase: 'custom', params: 'some-config-data', }, }, ], }); done(); }); }); it('fails when a module middleware cannot be resolved', function(done) { appdir.writeConfigFileSync('middleware.json', { final: { 'loopback/path-does-not-exist': {}, }, }); expectCompileToThrow(/path-does-not-exist/, done); }); it('does not fail when an optional middleware cannot be resolved', function(done) { appdir.writeConfigFileSync('middleware.json', { final: { 'loopback/path-does-not-exist': { optional: 'this middleware is optional', }, }, }); expectCompileToNotThrow(done); }); it('fails when a module middleware fragment cannot be resolved', function(done) { appdir.writeConfigFileSync('middleware.json', { final: { 'loopback#path-does-not-exist': {}, }, }); expectCompileToThrow(/path-does-not-exist/, done); }); it('does not fail when an optional middleware fragment cannot be resolved', function(done) { appdir.writeConfigFileSync('middleware.json', { final: { 'loopback#path-does-not-exist': { optional: 'this middleware is optional', }, }, }); expectCompileToNotThrow(done); }); it('resolves paths relatively to appRootDir', function(done) { appdir.writeFileSync('my-middleware.js', ''); appdir.writeConfigFileSync('./middleware.json', { routes: { // resolves to ./my-middleware.js './my-middleware': {}, }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.middleware).to.eql({ phases: ['routes'], middleware: [{ sourceFile: path.resolve(appdir.PATH, 'my-middleware.js'), config: { phase: 'routes' }, }], }); done(); }); }); it('merges config.params', function(done) { appdir.writeConfigFileSync('./middleware.json', { routes: { './middleware': { params: { key: 'initial value', }, }, }, }); appdir.writeConfigFileSync('./middleware.local.json', { routes: { './middleware': { params: { key: 'custom value', }, }, }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expectFirstMiddlewareParams(instructions).to.eql({ key: 'custom value', }); done(); }); }); it('merges config.enabled', function(done) { appdir.writeConfigFileSync('./middleware.json', { routes: { './middleware': { params: { key: 'initial value', }, }, }, }); appdir.writeConfigFileSync('./middleware.local.json', { routes: { './middleware': { enabled: false, }, }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.middleware.middleware[0].config) .to.have.property('enabled', false); done(); }); }); function verifyMiddlewareConfig(done) { boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.middleware.middleware) .to.eql([ { sourceFile: path.resolve(appdir.PATH, 'middleware'), config: { phase: 'routes', params: { key: 'initial value', }, }, }, { sourceFile: path.resolve(appdir.PATH, 'middleware'), config: { phase: 'routes', params: { key: 'custom value', }, }, }, ]); done(); }); } it('merges config.params array to array', function(done) { appdir.writeConfigFileSync('./middleware.json', { routes: { './middleware': [{ params: { key: 'initial value', }, }], }, }); appdir.writeConfigFileSync('./middleware.local.json', { routes: { './middleware': [{ params: { key: 'custom value', }, }], }, }); verifyMiddlewareConfig(done); }); it('merges config.params array to object', function(done) { appdir.writeConfigFileSync('./middleware.json', { routes: { './middleware': { params: { key: 'initial value', }, }, }, }); appdir.writeConfigFileSync('./middleware.local.json', { routes: { './middleware': [{ params: { key: 'custom value', }, }], }, }); verifyMiddlewareConfig(done); }); it('merges config.params object to array', function(done) { appdir.writeConfigFileSync('./middleware.json', { routes: { './middleware': [{ params: { key: 'initial value', }, }], }, }); appdir.writeConfigFileSync('./middleware.local.json', { routes: { './middleware': { params: { key: 'custom value', }, }, }, }); verifyMiddlewareConfig(done); }); it('merges config.params array to empty object', function(done) { appdir.writeConfigFileSync('./middleware.json', { routes: { './middleware': {}, }, }); appdir.writeConfigFileSync('./middleware.local.json', { routes: { './middleware': [{ params: { key: 'custom value', }, }], }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.middleware.middleware) .to.eql([ { sourceFile: path.resolve(appdir.PATH, 'middleware'), config: { phase: 'routes', params: { key: 'custom value', }, }, }, ]); }); done(); }); it('merges config.params array to array by name', function(done) { appdir.writeConfigFileSync('./middleware.json', { routes: { './middleware': [{ name: 'a', params: { key: 'initial value', }, }], }, }); appdir.writeConfigFileSync('./middleware.local.json', { routes: { './middleware': [{ name: 'a', params: { key: 'custom value', }, }, { params: { key: '2nd value', }, }], }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.middleware.middleware) .to.eql([ { sourceFile: path.resolve(appdir.PATH, 'middleware'), config: { name: 'a', phase: 'routes', params: { key: 'custom value', }, }, }, { sourceFile: path.resolve(appdir.PATH, 'middleware'), config: { phase: 'routes', params: { key: '2nd value', }, }, }, ]); done(); }); }); it('flattens sub-phases', function(done) { appdir.writeConfigFileSync('middleware.json', { 'initial:after': {}, 'custom:before': { 'loopback/server/middleware/url-not-found': { params: 'some-config-data', }, }, 'custom:after': {}, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.middleware.phases, 'phases') .to.eql(['initial', 'custom']); expect(instructions.middleware.middleware, 'middleware') .to.eql([{ sourceFile: require.resolve( 'loopback/server/middleware/url-not-found'), config: { phase: 'custom:before', params: 'some-config-data', }, }]); done(); }); }); it('supports multiple instances of the same middleware', function(done) { appdir.writeFileSync('my-middleware.js', ''); appdir.writeConfigFileSync('middleware.json', { 'final': { './my-middleware': [ { params: 'first', }, { params: 'second', }, ], }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.middleware.middleware) .to.eql([ { sourceFile: path.resolve(appdir.PATH, 'my-middleware.js'), config: { phase: 'final', params: 'first', }, }, { sourceFile: path.resolve(appdir.PATH, 'my-middleware.js'), config: { phase: 'final', params: 'second', }, }, ]); done(); }); }); it('supports shorthand notation for middleware paths', function(done) { appdir.writeConfigFileSync('middleware.json', { 'final': { 'loopback#url-not-found': {}, }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.middleware.middleware[0].sourceFile).to.equal( require.resolve('loopback/server/middleware/url-not-found')); done(); }); }); it('supports shorthand notation for relative paths', function(done) { appdir.writeConfigFileSync('middleware.json', { 'routes': { './middleware/index#myMiddleware': {}, }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.middleware.middleware[0].sourceFile) .to.equal(path.resolve(appdir.PATH, './middleware/index.js')); expect(instructions.middleware.middleware[0]).have.property( 'fragment', 'myMiddleware'); done(); }); }); it('supports shorthand notation when the fragment name matches a property', function(done) { appdir.writeConfigFileSync('middleware.json', { 'final': { 'loopback#errorHandler': {}, }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.middleware.middleware[0]).have.property( 'sourceFile', pathWithoutIndex(require.resolve('loopback'))); expect(instructions.middleware.middleware[0]).have.property( 'fragment', 'errorHandler'); done(); }); }); it('resolves modules relative to appRootDir', function() { var HANDLER_FILE = 'node_modules/handler/index.js'; appdir.writeFileSync( HANDLER_FILE, 'module.exports = function(req, res, next) { next(); }'); appdir.writeConfigFileSync('middleware.json', { 'initial': { 'handler': {}, }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.middleware.middleware[0]).have.property( 'sourceFile', pathWithoutIndex(appdir.resolve(HANDLER_FILE))); done(); }); }); it('prefers appRootDir over node_modules for middleware', function(done) { var appJS = appdir.writeFileSync('./my-middleware.js', ''); appdir.writeFileSync('node_modules/my-middleware.js', ''); appdir.writeConfigFileSync('middleware.json', { 'routes': { './my-middleware': {}, }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.middleware.middleware).to.have.length(1); expect(instructions.middleware.middleware[0]).have.property( 'sourceFile', appJS); done(); }); }); it('does not treat module relative path as `appRootDir` relative', function(done) { appdir.writeFileSync('./my-middleware.js', ''); var moduleJS = appdir.writeFileSync( 'node_modules/my-middleware.js', ''); appdir.writeConfigFileSync('middleware.json', { 'routes': { 'my-middleware': {}, }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.middleware.middleware).to.have.length(1); expect(instructions.middleware.middleware[0]).have.property( 'sourceFile', moduleJS); done(); }); }); it('loads middleware from coffeescript in appRootdir', function(done) { var coffee = appdir.writeFileSync('my-middleware.coffee', ''); appdir.writeConfigFileSync('middleware.json', { 'routes': { './my-middleware': {}, }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.middleware.middleware[0]).have.property( 'sourceFile', coffee); done(); }); }); it('loads coffeescript from middleware under node_modules', function(done) { var file = appdir.writeFileSync( 'node_modules/my-middleware/index.coffee', ''); appdir.writeFileSync('node_modules/my-middleware/index.json', ''); appdir.writeConfigFileSync('middleware.json', { 'routes': { 'my-middleware': {}, }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.middleware.middleware).to.have.length(1); expect(instructions.middleware.middleware[0]).have.property( 'sourceFile', pathWithoutIndex(file)); done(); }); }); it('prefers coffeescript over json for relative middleware path', function(done) { var coffee = appdir.writeFileSync('my-middleware.coffee', ''); appdir.writeFileSync('my-middleware.json', ''); appdir.writeConfigFileSync('middleware.json', { 'routes': { './my-middleware': {}, }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.middleware.middleware).to.have.length(1); expect(instructions.middleware.middleware[0]).have.property( 'sourceFile', coffee); done(); }); }); it('prefers coffeescript over json for module relative middleware path', function(done) { var coffee = appdir.writeFileSync('node_modules/my-middleware.coffee', ''); appdir.writeFileSync('node_modules/my-middleware.json', ''); appdir.writeConfigFileSync('middleware.json', { 'routes': { 'my-middleware': {}, }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.middleware.middleware).to.have.length(1); expect(instructions.middleware.middleware[0]).have.property( 'sourceFile', coffee); done(); }); }); describe('config with relative paths in params', function() { var RELATIVE_PATH_PARAMS = [ '$!./here', '$!../there', ]; var absolutePathParams; beforeEach(function resolveRelativePathParams() { absolutePathParams = RELATIVE_PATH_PARAMS.map(function(p) { return appdir.resolve(p.slice(2)); }); }); it('converts paths in top-level array items', function(done) { givenMiddlewareEntrySync({ params: RELATIVE_PATH_PARAMS }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expectFirstMiddlewareParams(instructions) .to.eql(absolutePathParams); done(); }); }); it('converts paths in top-level object properties', function(done) { givenMiddlewareEntrySync({ params: { path: RELATIVE_PATH_PARAMS[0], }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expectFirstMiddlewareParams(instructions) .to.eql({ path: absolutePathParams[0] }); done(); }); }); it('converts path value when params is a string', function(done) { givenMiddlewareEntrySync({ params: RELATIVE_PATH_PARAMS[0] }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expectFirstMiddlewareParams(instructions) .to.eql(absolutePathParams[0]); done(); }); }); it('converts paths in nested properties', function(done) { givenMiddlewareEntrySync({ params: { nestedObject: { path: RELATIVE_PATH_PARAMS[0], }, nestedArray: RELATIVE_PATH_PARAMS, }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expectFirstMiddlewareParams(instructions) .to.eql({ nestedObject: { path: absolutePathParams[0], }, nestedArray: absolutePathParams, }); done(); }); }); it('does not convert values not starting with `./` or `../`', function(done) { var PARAMS = ['$!.somerc', '$!/root', '$!hello!']; givenMiddlewareEntrySync({ params: PARAMS }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expectFirstMiddlewareParams(instructions).to.eql(PARAMS); done(); }); }); }); }); describe('for components', function() { it('loads component configs from multiple files', function(done) { appdir.createConfigFilesSync(); appdir.writeConfigFileSync('component-config.json', { debug: { option: 'value' }, }); appdir.writeConfigFileSync('component-config.local.json', { debug: { local: 'applied' }, }); var env = process.env.NODE_ENV || 'development'; appdir.writeConfigFileSync('component-config.' + env + '.json', { debug: { env: 'applied' }, }); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; var component = instructions.components[0]; expect(component).to.eql({ sourceFile: require.resolve('debug'), config: { option: 'value', local: 'applied', env: 'applied', }, }); done(); }); }); it('supports `componentRootDir` option', function(done) { var componentJson = { debug: { option: 'value', }, }; var customDir = path.resolve(appdir.PATH, 'custom'); fs.mkdirsSync(customDir); fs.writeJsonSync( path.resolve(customDir, 'component-config.json'), componentJson); boot.compile({ appRootDir: appdir.PATH, componentRootDir: path.resolve(appdir.PATH, 'custom'), }, function(err, context) { if (err) return done(err); var instructions = context.instructions; var component = instructions.components[0]; expect(component).to.eql({ sourceFile: require.resolve('debug'), config: { option: 'value', }, }); done(); }); }); it('loads component relative to appRootDir', function(done) { appdir.writeConfigFileSync('./component-config.json', { './index': {}, }); var appJS = appdir.writeConfigFileSync('index.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.components[0]).have.property( 'sourceFile', appJS ); done(); }); }); it('loads component relative to node modules', function(done) { appdir.writeConfigFileSync('component-config.json', { 'mycomponent': {}, }); var js = appdir.writeConfigFileSync('node_modules/mycomponent/index.js', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.components[0]).have.property( 'sourceFile', js ); done(); }); }); it('retains backward compatibility for non-relative path in `appRootDir`', function(done) { appdir.writeConfigFileSync('component-config.json', { 'my-component/component.js': {}, }); appdir.writeConfigFileSync('./my-component/component.js', ''); expectCompileToThrow( 'Cannot resolve path \"my-component/component.js\"', done); }); it('prefers coffeescript over json for relative path component', function(done) { appdir.writeConfigFileSync('component-config.json', { './component': {}, }); var coffee = appdir.writeFileSync('component.coffee', ''); appdir.writeFileSync('component.json', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.components).to.have.length(1); expect(instructions.components[0]).have.property( 'sourceFile', coffee); done(); }); }); it('prefers coffeescript over json for module relative component path', function(done) { appdir.writeConfigFileSync('component-config.json', { 'component': {}, }); var coffee = appdir.writeFileSync('node_modules/component.coffee', ''); appdir.writeFileSync('node_modules/component.json', ''); boot.compile(appdir.PATH, function(err, context) { if (err) return done(err); var instructions = context.instructions; expect(instructions.components).to.have.length(1); expect(instructions.components[0]).have.property( 'sourceFile', coffee); done(); }); }); }); }); function getNameProperty(obj) { return obj.name; } function givenMiddlewareEntrySync(config) { appdir.writeConfigFileSync('middleware.json', { initial: { // resolves to ./middleware.json './middleware': config, }, }); } function expectFirstMiddlewareParams(instructions) { return expect(instructions.middleware.middleware[0].config.params); } function pathWithoutExtension(value) { return path.join( path.dirname(value), path.basename(value, path.extname(value))); } function pathWithoutIndex(filePath) { return filePath.replace(/[\\\/]index\.[^.]+$/, ''); }
'use strict'; //Fixed rates service used to communicate Fixed rates REST endpoints angular.module('fixed-rates').factory('FixedRates', ['$resource', function($resource) { return $resource('fixed-rates/:fixedRateId', { fixedRateId: '@_id' }, { update: { method: 'PUT' } }); } ]);
/* * jQuery File Upload User Interface Plugin 9.6.1 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /* jshint nomen:false */ /* global define, require, window */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ 'jquery', 'tmpl', './jquery.fileupload-image', './jquery.fileupload-audio', './jquery.fileupload-video', './jquery.fileupload-validate' ], factory); } else if (typeof exports === 'object') { // Node/CommonJS: factory( require('jquery'), require('tmpl') ); } else { // Browser globals: factory( window.jQuery, window.tmpl ); } }(function ($, tmpl) { 'use strict'; $.blueimp.fileupload.prototype._specialOptions.push( 'filesContainer', 'uploadTemplateId', 'downloadTemplateId' ); // The UI version extends the file upload widget // and adds complete user interface interaction: $.widget('blueimp.fileupload', $.blueimp.fileupload, { options: { // By default, files added to the widget are uploaded as soon // as the user clicks on the start buttons. To enable automatic // uploads, set the following option to true: autoUpload: false, // The ID of the upload template: uploadTemplateId: 'template-upload', // The ID of the download template: downloadTemplateId: 'template-download', // The container for the list of files. If undefined, it is set to // an element with class "files" inside of the widget element: filesContainer: undefined, // By default, files are appended to the files container. // Set the following option to true, to prepend files instead: prependFiles: false, // The expected data type of the upload response, sets the dataType // option of the $.ajax upload requests: dataType: 'json', // Error and info messages: messages: { unknownError: 'Unknown error' }, // Function returning the current number of files, // used by the maxNumberOfFiles validation: getNumberOfFiles: function () { return this.filesContainer.children() .not('.processing').length; }, // Callback to retrieve the list of files from the server response: getFilesFromResponse: function (data) { if (data.result && $.isArray(data.result.files)) { return data.result.files; } return []; }, // The add callback is invoked as soon as files are added to the fileupload // widget (via file input selection, drag & drop or add API call). // See the basic file upload widget for more information: add: function (e, data) { if (e.isDefaultPrevented()) { return false; } var $this = $(this), that = $this.data('blueimp-fileupload') || $this.data('fileupload'), options = that.options; data.context = that._renderUpload(data.files) .data('data', data) .addClass('processing'); options.filesContainer[ options.prependFiles ? 'prepend' : 'append' ](data.context); that._forceReflow(data.context); that._transition(data.context); data.process(function () { return $this.fileupload('process', data); }).always(function () { data.context.each(function (index) { $(this).find('.size').text( that._formatFileSize(data.files[index].size) ); }).removeClass('processing'); that._renderPreviews(data); }).done(function () { data.context.find('.start').prop('disabled', false); if ((that._trigger('added', e, data) !== false) && (options.autoUpload || data.autoUpload) && data.autoUpload !== false) { data.submit(); } }).fail(function () { if (data.files.error) { data.context.each(function (index) { var error = data.files[index].error; if (error) { $(this).find('.error').text(error); } }); } }); }, // Callback for the start of each file upload request: send: function (e, data) { if (e.isDefaultPrevented()) { return false; } var that = $(this).data('blueimp-fileupload') || $(this).data('fileupload'); if (data.context && data.dataType && data.dataType.substr(0, 6) === 'iframe') { // Iframe Transport does not support progress events. // In lack of an indeterminate progress bar, we set // the progress to 100%, showing the full animated bar: data.context .find('.progress').addClass( !$.support.transition && 'progress-animated' ) .attr('aria-valuenow', 100) .children().first().css( 'width', '100%' ); } return that._trigger('sent', e, data); }, // Callback for successful uploads: done: function (e, data) { if (e.isDefaultPrevented()) { return false; } var that = $(this).data('blueimp-fileupload') || $(this).data('fileupload'), getFilesFromResponse = data.getFilesFromResponse || that.options.getFilesFromResponse, files = getFilesFromResponse(data), template, deferred; if (data.context) { data.context.each(function (index) { var file = files[index] || {error: 'Empty file upload result'}; deferred = that._addFinishedDeferreds(); that._transition($(this)).done( function () { var node = $(this); template = that._renderDownload([file]) .replaceAll(node); that._forceReflow(template); that._transition(template).done( function () { data.context = $(this); that._trigger('completed', e, data); that._trigger('finished', e, data); deferred.resolve(); } ); } ); }); } else { template = that._renderDownload(files)[ that.options.prependFiles ? 'prependTo' : 'appendTo' ](that.options.filesContainer); that._forceReflow(template); deferred = that._addFinishedDeferreds(); that._transition(template).done( function () { data.context = $(this); that._trigger('completed', e, data); that._trigger('finished', e, data); deferred.resolve(); } ); } }, // Callback for failed (abort or error) uploads: fail: function (e, data) { if (e.isDefaultPrevented()) { return false; } var that = $(this).data('blueimp-fileupload') || $(this).data('fileupload'), template, deferred; if (data.context) { data.context.each(function (index) { if (data.errorThrown !== 'abort') { var file = data.files[index]; file.error = file.error || data.errorThrown || data.i18n('unknownError'); deferred = that._addFinishedDeferreds(); that._transition($(this)).done( function () { var node = $(this); template = that._renderDownload([file]) .replaceAll(node); that._forceReflow(template); that._transition(template).done( function () { data.context = $(this); that._trigger('failed', e, data); that._trigger('finished', e, data); deferred.resolve(); } ); } ); } else { deferred = that._addFinishedDeferreds(); that._transition($(this)).done( function () { $(this).remove(); that._trigger('failed', e, data); that._trigger('finished', e, data); deferred.resolve(); } ); } }); } else if (data.errorThrown !== 'abort') { data.context = that._renderUpload(data.files)[ that.options.prependFiles ? 'prependTo' : 'appendTo' ](that.options.filesContainer) .data('data', data); that._forceReflow(data.context); deferred = that._addFinishedDeferreds(); that._transition(data.context).done( function () { data.context = $(this); that._trigger('failed', e, data); that._trigger('finished', e, data); deferred.resolve(); } ); } else { that._trigger('failed', e, data); that._trigger('finished', e, data); that._addFinishedDeferreds().resolve(); } }, // Callback for upload progress events: progress: function (e, data) { if (e.isDefaultPrevented()) { return false; } var progress = Math.floor(data.loaded / data.total * 100); if (data.context) { data.context.each(function () { $(this).find('.progress') .attr('aria-valuenow', progress) .children().first().css( 'width', progress + '%' ); }); } }, // Callback for global upload progress events: progressall: function (e, data) { if (e.isDefaultPrevented()) { return false; } var $this = $(this), progress = Math.floor(data.loaded / data.total * 100), globalProgressNode = $this.find('.fileupload-progress'), extendedProgressNode = globalProgressNode .find('.progress-extended'); if (extendedProgressNode.length) { extendedProgressNode.html( ($this.data('blueimp-fileupload') || $this.data('fileupload')) ._renderExtendedProgress(data) ); } globalProgressNode .find('.progress') .attr('aria-valuenow', progress) .children().first().css( 'width', progress + '%' ); }, // Callback for uploads start, equivalent to the global ajaxStart event: start: function (e) { if (e.isDefaultPrevented()) { return false; } var that = $(this).data('blueimp-fileupload') || $(this).data('fileupload'); that._resetFinishedDeferreds(); that._transition($(this).find('.fileupload-progress')).done( function () { that._trigger('started', e); } ); }, // Callback for uploads stop, equivalent to the global ajaxStop event: stop: function (e) { if (e.isDefaultPrevented()) { return false; } var that = $(this).data('blueimp-fileupload') || $(this).data('fileupload'), deferred = that._addFinishedDeferreds(); $.when.apply($, that._getFinishedDeferreds()) .done(function () { that._trigger('stopped', e); }); that._transition($(this).find('.fileupload-progress')).done( function () { $(this).find('.progress') .attr('aria-valuenow', '0') .children().first().css('width', '0%'); $(this).find('.progress-extended').html('&nbsp;'); deferred.resolve(); } ); }, processstart: function (e) { if (e.isDefaultPrevented()) { return false; } $(this).addClass('fileupload-processing'); }, processstop: function (e) { if (e.isDefaultPrevented()) { return false; } $(this).removeClass('fileupload-processing'); }, // Callback for file deletion: destroy: function (e, data) { if (e.isDefaultPrevented()) { return false; } var that = $(this).data('blueimp-fileupload') || $(this).data('fileupload'), removeNode = function () { that._transition(data.context).done( function () { $(this).remove(); that._trigger('destroyed', e, data); } ); }; if (data.url) { data.dataType = data.dataType || that.options.dataType; $.ajax(data).done(removeNode).fail(function () { that._trigger('destroyfailed', e, data); }); } else { removeNode(); } } }, _resetFinishedDeferreds: function () { this._finishedUploads = []; }, _addFinishedDeferreds: function (deferred) { if (!deferred) { deferred = $.Deferred(); } this._finishedUploads.push(deferred); return deferred; }, _getFinishedDeferreds: function () { return this._finishedUploads; }, // Link handler, that allows to download files // by drag & drop of the links to the desktop: _enableDragToDesktop: function () { var link = $(this), url = link.prop('href'), name = link.prop('download'), type = 'application/octet-stream'; link.bind('dragstart', function (e) { try { e.originalEvent.dataTransfer.setData( 'DownloadURL', [type, name, url].join(':') ); } catch (ignore) { } }); }, _formatFileSize: function (bytes) { if (typeof bytes !== 'number') { return ''; } if (bytes >= 1000000000) { return (bytes / 1000000000).toFixed(2) + ' GB'; } if (bytes >= 1000000) { return (bytes / 1000000).toFixed(2) + ' MB'; } return (bytes / 1000).toFixed(2) + ' KB'; }, _formatBitrate: function (bits) { if (typeof bits !== 'number') { return ''; } if (bits >= 1000000000) { return (bits / 1000000000).toFixed(2) + ' Gbit/s'; } if (bits >= 1000000) { return (bits / 1000000).toFixed(2) + ' Mbit/s'; } if (bits >= 1000) { return (bits / 1000).toFixed(2) + ' kbit/s'; } return bits.toFixed(2) + ' bit/s'; }, _formatTime: function (seconds) { var date = new Date(seconds * 1000), days = Math.floor(seconds / 86400); days = days ? days + 'd ' : ''; return days + ('0' + date.getUTCHours()).slice(-2) + ':' + ('0' + date.getUTCMinutes()).slice(-2) + ':' + ('0' + date.getUTCSeconds()).slice(-2); }, _formatPercentage: function (floatValue) { return (floatValue * 100).toFixed(2) + ' %'; }, _renderExtendedProgress: function (data) { return this._formatBitrate(data.bitrate) + ' | ' + this._formatTime( (data.total - data.loaded) * 8 / data.bitrate ) + ' | ' + this._formatPercentage( data.loaded / data.total ) + ' | ' + this._formatFileSize(data.loaded) + ' / ' + this._formatFileSize(data.total); }, _renderTemplate: function (func, files) { if (!func) { return $(); } var result = func({ files: files, formatFileSize: this._formatFileSize, options: this.options }); if (result instanceof $) { return result; } return $(this.options.templatesContainer).html(result).children(); }, _renderPreviews: function (data) { data.context.find('.preview').each(function (index, elm) { $(elm).append(data.files[index].preview); }); }, _renderUpload: function (files) { return this._renderTemplate( this.options.uploadTemplate, files ); }, _renderDownload: function (files) { return this._renderTemplate( this.options.downloadTemplate, files ).find('a[download]').each(this._enableDragToDesktop).end(); }, _startHandler: function (e) { e.preventDefault(); var button = $(e.currentTarget), template = button.closest('.template-upload'), data = template.data('data'); button.prop('disabled', true); if (data && data.submit) { data.submit(); } }, _cancelHandler: function (e) { e.preventDefault(); var template = $(e.currentTarget) .closest('.template-upload,.template-download'), data = template.data('data') || {}; data.context = data.context || template; if (data.abort) { data.abort(); } else { data.errorThrown = 'abort'; this._trigger('fail', e, data); } }, _deleteHandler: function (e) { e.preventDefault(); var button = $(e.currentTarget); this._trigger('destroy', e, $.extend({ context: button.closest('.template-download'), type: 'DELETE' }, button.data())); }, _forceReflow: function (node) { return $.support.transition && node.length && node[0].offsetWidth; }, _transition: function (node) { var dfd = $.Deferred(); if ($.support.transition && node.hasClass('fade') && node.is(':visible')) { node.bind( $.support.transition.end, function (e) { // Make sure we don't respond to other transitions events // in the container element, e.g. from button elements: if (e.target === node[0]) { node.unbind($.support.transition.end); dfd.resolveWith(node); } } ).toggleClass('in'); } else { node.toggleClass('in'); dfd.resolveWith(node); } return dfd; }, _initButtonBarEventHandlers: function () { var fileUploadButtonBar = this.element.find('.fileupload-buttonbar'), filesList = this.options.filesContainer; this._on(fileUploadButtonBar.find('.start'), { click: function (e) { e.preventDefault(); filesList.find('.start').click(); } }); this._on(fileUploadButtonBar.find('.cancel'), { click: function (e) { e.preventDefault(); filesList.find('.cancel').click(); } }); this._on(fileUploadButtonBar.find('.delete'), { click: function (e) { e.preventDefault(); filesList.find('.toggle:checked') .closest('.template-download') .find('.delete').click(); fileUploadButtonBar.find('.toggle') .prop('checked', false); } }); this._on(fileUploadButtonBar.find('.toggle'), { change: function (e) { filesList.find('.toggle').prop( 'checked', $(e.currentTarget).is(':checked') ); } }); }, _destroyButtonBarEventHandlers: function () { this._off( this.element.find('.fileupload-buttonbar') .find('.start, .cancel, .delete'), 'click' ); this._off( this.element.find('.fileupload-buttonbar .toggle'), 'change.' ); }, _initEventHandlers: function () { this._super(); this._on(this.options.filesContainer, { 'click .start': this._startHandler, 'click .cancel': this._cancelHandler, 'click .delete': this._deleteHandler }); this._initButtonBarEventHandlers(); }, _destroyEventHandlers: function () { this._destroyButtonBarEventHandlers(); this._off(this.options.filesContainer, 'click'); this._super(); }, _enableFileInputButton: function () { this.element.find('.fileinput-button input') .prop('disabled', false) .parent().removeClass('disabled'); }, _disableFileInputButton: function () { this.element.find('.fileinput-button input') .prop('disabled', true) .parent().addClass('disabled'); }, _initTemplates: function () { var options = this.options; options.templatesContainer = this.document[0].createElement( options.filesContainer.prop('nodeName') ); if (tmpl) { if (options.uploadTemplateId) { options.uploadTemplate = tmpl(options.uploadTemplateId); } if (options.downloadTemplateId) { options.downloadTemplate = tmpl(options.downloadTemplateId); } } }, _initFilesContainer: function () { var options = this.options; if (options.filesContainer === undefined) { options.filesContainer = this.element.find('.files'); } else if (!(options.filesContainer instanceof $)) { options.filesContainer = $(options.filesContainer); } }, _initSpecialOptions: function () { this._super(); this._initFilesContainer(); this._initTemplates(); }, _create: function () { this._super(); this._resetFinishedDeferreds(); if (!$.support.fileInput) { this._disableFileInputButton(); } }, enable: function () { var wasDisabled = false; if (this.options.disabled) { wasDisabled = true; } this._super(); if (wasDisabled) { this.element.find('input, button').prop('disabled', false); this._enableFileInputButton(); } }, disable: function () { if (!this.options.disabled) { this.element.find('input, button').prop('disabled', true); this._disableFileInputButton(); } this._super(); } }); }));
var objectToHtml = (function () { "use strict"; function objectProperties(object) { var name, value, properties = []; for (name in object) { if (object.hasOwnProperty(name)) { try { value = object[name]; } catch (e) { value = e; } properties.push({ name: name, value: value }); } } return properties; } function isEventAttribute(element, attributeName) { return attributeName.substr(0, 2) === "on" && element[attributeName] !== undefined; } function objectToHtml(elementState) { var nameProperty = objectProperties(elementState).filter(function (property) { return property.name !== "c" && property.name !== "s" && property.name !== "e" && property.name !== "t"; })[0], contentProperty = elementState.c || [], styleProperty = elementState.s, eventProperty = elementState.e, textProperty = elementState.t, tagName = nameProperty.name, attributesMap = nameProperty.value || {}, element; element = document.createElement(tagName); if (textProperty) { element.textContent = textProperty; } objectProperties(attributesMap).filter(function (attribute) { if (isEventAttribute(element, attribute.name)) { throw new Error("Set events using e: {eventName: function...}"); } return attribute; }).forEach(function (attribute) { element.setAttribute(attribute.name, attribute.value); }); objectProperties(styleProperty).forEach(function (style) { element.style[style.name] = style.value; }); objectProperties(eventProperty).forEach(function (event) { element.addEventListener(event.name, event.value); }); contentProperty.map(objectToHtml).forEach(function (childElement) { element.appendChild(childElement); }); return element; } return objectToHtml; }(this));
import React from 'react' const GraphQLErrorList = ({errors}) => ( <div> <h1>GraphQL Error</h1> {errors.map(error => ( <pre key={error.message}>{error.message}</pre> ))} </div> ) export default GraphQLErrorList
import React, { Component } from "react"; import Slider from "rc-slider"; import "rc-slider/assets/index.css"; import Tooltip from "rc-tooltip"; const handle = props => { const { value, dragging, index, ...restProps } = props; return ( <Tooltip prefixCls="rc-slider-tooltip" overlay={value} visible={dragging} placement="top" key={index} > <Handle value={value} {...restProps} /> </Tooltip> ); }; const Handle = Slider.Handle; export default class AddData extends Component { state = { hubName: "", width: "40", height: "40", team: "", numberPlayer: "", teams: [], error: false, errorTeam: false, errorNumberTeam: false, freq: 2 }; addToTeamList(e) { if (this.state.teams.includes(this.state.team)) { alert("Cette team existe déjà"); this.setState({ team: "" }); return; } else if (this.state.team === "") { alert("Une team doit obligatoirement avoir un nom"); return; } else if (this.state.teams.length > 7) { alert("Vous avez atteint le nombre maximum de team possible"); return; } else if (this.state.team.includes("*")) { alert("Le nom de team ne peut pas comprendre un *"); return; } else { this.setState({ teams: [...this.state.teams, this.state.team], team: "" }); } e.preventDefault(); } submitForm(e) { e.preventDefault(); if (this.state.numberPlayer < 1 || this.state.numberPlayer > 100) { this.setState({ errorTeam: true }); return; } else if (this.state.teams.length < 1 || this.state.teams.length > 8) { this.setState({ errorNumberTeam: true, errorTeam: false }); return; } else { if ( this.state.hubName === "" || this.state.width === "" || this.state.height === "" ) { this.setState({ error: true, errorNumberTeam: true, errorTeam: true }); } else { const teamName = this.state.teams.join("*"); const url = "game.html?hubname=" + this.state.hubName + "&width=" + this.state.width + "&height=" + this.state.height + "&team=" + teamName + "&number=" + this.state.numberPlayer + "&freq=" + this.state.freq; window.location.replace(url); } } } onChangeFreq = value => { this.setState({ freq: value }); }; render() { return ( <form> <h2 className="title is-4">Creer une nouvelle partie</h2> <div className="field"> <label className="label">HubName</label> <p className="control"> <input className="input" type="text" value={this.state.hubName} onChange={e => { this.setState({ hubName: e.target.value }); }} /> </p> </div> <div className="field"> <label className="label">Largeur de la map</label> <p className="control"> <input className="input" type="number" value={this.state.width} onChange={e => { this.setState({ width: e.target.value }); }} /> </p> </div> <div className="field"> <label className="label">Hauteur de la map</label> <p className="control"> <input className="input" type="number" value={this.state.height} onChange={e => { this.setState({ height: e.target.value }); }} /> </p> </div> <label className="label">Nom de team</label> <div className="field has-addons"> <p className="control is-expanded"> <input className="input" type="text" value={this.state.team} placeholder="Minimum 1 teams" onChange={e => { this.setState({ team: e.target.value }); }} /> </p> <p className="control"> <button className="button is-success" onClick={e => { e.preventDefault(); this.addToTeamList(e); }} > Ajouter une team </button> </p> </div> <div className="content"> <ul> {this.state.teams.map((team, key) => { return ( <li key={key}> {team} </li> ); })} </ul> </div> <div className="field"> <label className="label">Nombre de joueurs par team</label> <p className="control"> <input className="input" type="number" value={this.state.numberPlayer} onChange={e => { this.setState({ numberPlayer: e.target.value }); }} /> </p> </div> <div className="field"> <label className="label">Fréquence</label> <div className="columns"> <div className="column is-half"> <Slider min={2} max={100} onChange={this.onChangeFreq} value={this.state.freq} handle={handle} /> </div> </div> </div> <div className="field is-grouped"> <p className="control"> <button className="button is-primary" type="submit" onClick={e => { e.preventDefault(); this.submitForm(e); }} > Creer la partie </button> </p> <p className="control"> <button className="button is-warning" onClick={e => { e.preventDefault(); window.location.reload(); }} > Retour </button> </p> </div> {this.state.error ? <div className="notification is-danger"> Veuillez remplir tous les champs </div> : ""} {this.state.errorTeam ? <div className="notification is-danger"> Vous devez rentrer entre 1 et 100 joueurs par team </div> : ""} {this.state.errorNumberTeam ? <div className="notification is-danger"> Vous devez rentrer entre 1 et 7 teams. </div> : ""} </form> ); } }
import { select, selectAll } from 'd3-selection'; const flipAxisAndUpdatePCP = (config, pc, axis) => function(dimension) { pc.flip(dimension); pc.brushReset(dimension); // select(this.parentElement) pc.selection .select('svg') .selectAll('g.axis') .filter(d => d === dimension) .transition() .duration(config.animationTime) .call(axis.scale(config.dimensions[dimension].yscale)); pc.render(); }; export default flipAxisAndUpdatePCP;
angular.module('Loan').service("LoanService", function ($http, $q, $mdDialog, ErrorService) { function edit(loan, cb) { return $mdDialog.show({ controller: 'LoanEditCtrl', controllerAs: 'loanEdit', templateUrl: 'loan/edit.html', locals: { items: loan } }).then(function () { cb() }); } function abort(loan, cb) { return $mdDialog.show({ controller: 'ConfirmCtrl', templateUrl: 'modals/confirmAbort.html', locals: { items: { item: loan.companyId.name } } }).then(function () { loan.aborted = true; create(loan).then(cb); }); } function revert(loan, cb) { return $mdDialog.show({ controller: 'ConfirmCtrl', templateUrl: 'modals/confirmRevert.html', locals: { items: { item: loan.companyId.name } } }).then(function () { loan.aborted = false; loan.endDate = null; create(loan).then(cb); }); } function returned(loan, cb) { return $mdDialog.show({ controller: 'ConfirmReturnCtrl', templateUrl: 'modals/confirmReturn.html', locals: { items: angular.copy(loan) } }).then(function (loan) { create(loan).then(cb); }); } function create(loan) { let id; if (loan._id) id = loan._id; else id = ""; var canceller = $q.defer(); var request = $http({ url: "/api/loans/" + id, method: "POST", data: { loan: loan }, timeout: canceller.promise }); return httpReq(request); } function postComment(id, comment) { var canceller = $q.defer(); var request = $http({ url: "/api/loans/" + id + "/comment", method: "POST", data: { comment: comment }, timeout: canceller.promise }); return httpReq(request); } function getList(search) { var canceller = $q.defer(); var request = $http({ url: "/api/loans", method: "GET", params: search, timeout: canceller.promise }); return httpReq(request); } function get(loan_id) { var canceller = $q.defer(); var request = $http({ url: "/api/loans/" + loan_id, method: "GET", timeout: canceller.promise }); return httpReq(request); } function getById(id) { var canceller = $q.defer(); var request = $http({ url: "/api/loans", method: "GET", params: { id: id }, timeout: canceller.promise }); return httpReq(request); } function remove(id) { var canceller = $q.defer(); var request = $http({ url: "/api/loans/" + id, method: "DELETE", timeout: canceller.promise }); return httpReq(request); } function httpReq(request) { var promise = request.then( function (response) { return response.data; }, function (response) { console.log(response); if (response.status >= 0) ErrorService.display(response); }); promise.abort = function () { canceller.resolve(); }; promise.finally(function () { console.info("Cleaning up object references."); promise.abort = angular.noop; canceller = request = promise = null; }); return promise; } return { edit: edit, abort: abort, revert: revert, returned: returned, create: create, postComment: postComment, getList: getList, remove: remove, get: get, getById: getById } });
var fs = require('fs'), gulp = require('gulp'), eslint = require('gulp-eslint') Karma = require('karma').Server; ; var paths = { src: 'src/**/*.js', test: 'spec/**/*Spec.js' }; gulp.task('dev-lint', function() { return gulp.src([paths.src, paths.test]) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failOnError()); }); gulp.task('ci-lint', function() { return gulp.src([paths.src, paths.test]) .pipe(eslint()) .pipe(eslint.format('checkstyle', function(data) { fs.writeFileSync('checkstyle.xml', data, 'utf8'); })) }); gulp.task('dev-karma', function(done) { new Karma({ configFile: __dirname + '/karma.conf.js', singleRun: false, reporters: [ 'progress', 'coverage' ], coverageReporter: { type: 'html' }, browsers: [ 'Chrome' ], }, done).start(); }); gulp.task('ci-karma', function(done) { new Karma({ configFile: __dirname + '/karma.conf.js', singleRun: true, reporters: [ 'junit', 'coverage' ], coverageReporter: { type: 'cobertura' }, browsers: [ 'Chrome', 'Firefox' ], }, done).start(); }); gulp.task('ci-travis', function(done) { new Karma({ configFile: __dirname + '/karma.conf.js', singleRun: true, reporters: [ 'progress', 'coverage' ], coverageReporter: { type: 'lcov' }, browsers: [ 'Firefox' ], }, done).start(); });
import { test } from 'qunit'; import moduleForAcceptance from 'first-ember-project/tests/helpers/module-for-acceptance'; import Ember from 'ember'; let StubMapsService = Ember.Service.extend({ getMapElement() { return document.createElement('div'); } }); moduleForAcceptance('Acceptance | list-rentals', { beforeEach() { this.application.register('service:stubMaps', StubMapsService); this.application.inject('component:location-map', 'maps', 'service:stubMaps'); } }); test('should redirect to rentals route', function(assert) { visit('/'); andThen(function() { assert.equal(currentURL(), '/rentals', 'should redirect automatically'); }); }); test('should list available rentals.', function(assert) { visit('/'); andThen(function() { assert.equal(find('.listing').length, 3, 'should see 3 listings'); }); }); test('should link to information about the company', function(assert) { visit('/'); click('a:contains("About")'); andThen(function() { assert.equal(currentURL(), '/about', 'should navigate to about page'); }); }); test('should link to contact information', function(assert) { visit('/'); click('a:contains("Contact")'); andThen(function() { assert.equal(currentURL(), '/contact', 'should navigate to contact page'); }); }); test('should filter the list of rentals by city', function(assert) { visit('/'); fillIn('.list-filter input', 'seattle'); keyEvent('.list-filter input', 'keyup', 70); andThen(function(){ assert.equal(find('.listing').length, 1, 'should show 1 listing'); assert.equal(find('.listing .location:contains("Seattle")').length, 1, 'should contain 1 listing with location Seattle'); }); }); test('should show details for a specific rental', function(assert) { visit('/rentals'); click('a:contains("Grand Old Mansion")'); andThen(function() { assert.equal(currentURL(), '/rentals/grand-old-mansion', 'should navigate to show route'); assert.equal(find('.show-listing h2').text(), "Grand Old Mansion", 'should list rental title'); assert.equal(find('.description').length, 1, 'should list a description of the property'); }); });
function position(posicao){ location.href = posicao; }
var q = require('q'); var fs = require('fs'); var path = require('path'); var modbusMap = require('ljswitchboard-modbus_map').getConstants(); var async = require('async'); var lj_apps_win_registry_info = require('lj-apps-win-registry-info'); var driver_const = require('ljswitchboard-ljm_driver_constants'); var getLJAppsRegistryInfo = lj_apps_win_registry_info.getLJAppsRegistryInfo; var ljAppNames = lj_apps_win_registry_info.ljAppNames; var ljm_ffi_req = require('ljm-ffi'); var ljm_ffi = ljm_ffi_req.load(); var net = require('net'); var DEBUG_MANUAL_IP_CHECKING = false; function getLogger(bool) { return function logger() { if(bool) { console.log.apply(console, arguments); } }; } var debugMIC = getLogger(DEBUG_MANUAL_IP_CHECKING); function getAvailableConnectionsOperations(self) { /** * Available Connection Types: */ function checkForUSBConnectivity(bundle) { var defered = q.defer(); var connectionStatus = { 'type': 'USB', 'isConnectable': false, // Can another process als use this connection? 'isConnected': false, // Is this the currently active connection? 'isAvailable': false, // Is this an available connection type? 'id': undefined, } var isConnected = false; // Determine whether or not the current connection type is USB. if(self.savedAttributes.connectionTypeName === 'USB') { connectionStatus.isConnected = true; // This is the currently active connection. } if(connectionStatus.isConnected) { connectionStatus.isConnectable = false; // USB devices, only 1 active connection. connectionStatus.isAvailable = true; // This device is available via USB. connectionStatus.id = self.savedAttributes.serialNumber.toString(); bundle.connections.push(connectionStatus); defered.resolve(bundle); } else { // ljm_ffi var id = self.savedAttributes.serialNumber.toString(); connectionStatus.id = self.savedAttributes.serialNumber.toString(); var dt = self.savedAttributes.deviceTypeName; var ct = 'USB'; function closeFinished(data) { defered.resolve(bundle); } function openFinished(data) { if(data.ljmError === 0) { connectionStatus.isConnectable = true; connectionStatus.isAvailable = true; bundle.connections.push(connectionStatus); ljm_ffi.LJM_Close.async(data.handle, closeFinished); } else { // connectionStatus.isConnectable = false; // connectionStatus.isAvailable = false; // bundle.connections.push(connectionStatus); defered.resolve(bundle); } } ljm_ffi.LJM_OpenS.async(dt, ct, id, 0, openFinished); } return defered.promise; } function isIPConnectable(ip) { var defered = q.defer(); var socket = new net.Socket(); var results = []; var closed = false; var connectionnTimedOut = false; function handleTimeout() { debugMIC('in handleTimeout'); connectionnTimedOut = true; setImmediate(processClose); } var timeout = setTimeout(handleTimeout, 2000); function processClose() { closed = true; var isConnectable = true; if(results.indexOf('error') >= 0) { isConnectable = false; } if(connectionnTimedOut) { isConnectable = false; } else { clearTimeout(timeout); } socket.destroy(); socket.unref(); defered.resolve(isConnectable); } socket.on('connect', function(data) { debugMIC('in connect'); results.push('connect'); setImmediate(function() { socket.end(); }); }); socket.on('close', function(data) { debugMIC('in close'); results.push('close'); if(!closed) { setImmediate(processClose); } // debugMIC('closing socket'); }) socket.on('error', function(data) { debugMIC('in error'); results.push('error'); // console.log('error', data); }) socket.on('end', function(data) { debugMIC('in end'); results.push('end'); if(!closed) { setImmediate(processClose); } // console.log('Disconnected from device.'); }); socket.connect({port:502, host:ip}); return defered.promise; } function checkForEthernetConnectivity(bundle) { var defered = q.defer(); var connectionStatus = { 'type': 'Ethernet', 'isConnectable': false, // Can another process als use this connection? 'isConnected': false, // Is this the currently active connection? 'isAvailable': false, // Is this an available connection type? 'id': undefined, } var isConnected = false; // Determine whether or not the current connection type is Ethernet. if(self.savedAttributes.connectionTypeName === 'Ethernet') { connectionStatus.isConnected = true; // This is the currently active connection. } if(connectionStatus.isConnected) { connectionStatus.id = self.savedAttributes.ipAddress; isIPConnectable(self.savedAttributes.ipAddress) .then(function(isConnectable) { connectionStatus.isConnectable = isConnectable; // Ethernet devices, 2 active connections, aka we need to check. connectionStatus.isAvailable = true; // This device is available via Ethernet. bundle.connections.push(connectionStatus); defered.resolve(bundle); }); // Interesting state. This open/close command breaks LJM. // var dt = self.savedAttributes.deviceTypeName; // var ct = 'Ethernet'; // var id = self.savedAttributes.ipAddress; // function closeFinished(data) { // defered.resolve(bundle); // } // function openFinished(data) { // if(data.ljmError === 0) { // connectionStatus.isConnectable = true; // connectionStatus.isAvailable = true; // bundle.connections.push(connectionStatus); // ljm_ffi.LJM_Close.async(data.handle, closeFinished); // } else { // connectionStatus.isConnectable = false; // connectionStatus.isAvailable = true; // bundle.connections.push(connectionStatus); // defered.resolve(bundle); // } // } // ljm_ffi.LJM_OpenS.async(dt, ct, id, 0, openFinished); } else { self.cRead('ETHERNET_IP') .then(function(cachedEthIPRes) { if(cachedEthIPRes.isReal) { var id = cachedEthIPRes.val; connectionStatus.id = cachedEthIPRes.val; isIPConnectable(id) .then(function(isConnectable) { connectionStatus.isConnectable = isConnectable; // Ethernet devices, 2 active connections, aka we need to check. connectionStatus.isAvailable = true; // This device is available via Ethernet. bundle.connections.push(connectionStatus); defered.resolve(bundle); }); // var dt = self.savedAttributes.deviceTypeName; // var ct = 'Ethernet'; // function closeFinished(data) { // defered.resolve(bundle); // } // function openFinished(data) { // if(data.ljmError === 0) { // connectionStatus.isConnectable = true; // connectionStatus.isAvailable = true; // bundle.connections.push(connectionStatus); // ljm_ffi.LJM_Close.async(data.handle, closeFinished); // } else { // connectionStatus.isConnectable = false; // connectionStatus.isAvailable = true; // bundle.connections.push(connectionStatus); // defered.resolve(bundle); // } // } // ljm_ffi.LJM_OpenS.async(dt, ct, id, 0, openFinished); } else { defered.resolve(bundle); } }, function(err) { defered.resolve(bundle); }); } return defered.promise; } function checkForWiFiConnectivity(bundle) { var defered = q.defer(); var connectionStatus = { 'type': 'WiFi', 'isConnectable': false, // Can another process als use this connection? 'isConnected': false, // Is this the currently active connection? 'isAvailable': false, // Is this an available connection type? 'id': undefined, } var isConnected = false; // Determine whether or not the current connection type is WiFi. if(self.savedAttributes.connectionTypeName === 'WiFi') { connectionStatus.isConnected = true; // This is the currently active connection. } if(connectionStatus.isConnected) { // connectionStatus.isConnectable = false; // WiFi devices, 1 active connection. // connectionStatus.isAvailable = true; // This device is available via WiFi. // connectionStatus.id = self.savedAttributes.ipAddress; // bundle.connections.push(connectionStatus); // defered.resolve(bundle); connectionStatus.id = self.savedAttributes.ipAddress; isIPConnectable(self.savedAttributes.ipAddress) .then(function(isConnectable) { connectionStatus.isConnectable = isConnectable; // WiFi devices, 1 active connections (maybe more in the future), aka we need to check. connectionStatus.isAvailable = true; // This device is available via WiFi. bundle.connections.push(connectionStatus); defered.resolve(bundle); }); } else { self.cReadMany(['WIFI_STATUS','WIFI_IP']) .then(function(cachedResults) { var WIFI_STATUS,WIFI_IP; cachedResults.forEach(function(result) { if(result.name === 'WIFI_STATUS') { WIFI_STATUS = result; } else if(result.name === 'WIFI_IP') { WIFI_IP = result; } }); if(WIFI_STATUS.isConnected) { var id = WIFI_IP.val; connectionStatus.id = WIFI_IP.val; isIPConnectable(id) .then(function(isConnectable) { connectionStatus.isConnectable = isConnectable; connectionStatus.isAvailable = true; bundle.connections.push(connectionStatus); defered.resolve(bundle); }); // var dt = self.savedAttributes.deviceTypeName; // var ct = 'WiFi'; // function closeFinished(data) { // defered.resolve(bundle); // } // function openFinished(data) { // if(data.ljmError === 0) { // connectionStatus.isConnectable = true; // connectionStatus.isAvailable = true; // bundle.connections.push(connectionStatus); // ljm_ffi.LJM_Close.async(data.handle, closeFinished); // } else { // connectionStatus.isConnectable = false; // connectionStatus.isAvailable = true; // bundle.connections.push(connectionStatus); // defered.resolve(bundle); // } // } // ljm_ffi.LJM_OpenS.async(dt, ct, id, 0, openFinished); } else { defered.resolve(bundle); } }, function(err) { defered.resolve(bundle); }); } return defered.promise; } this.getAvailableConnectionTypes = function() { var defered = q.defer(); var productType = self.savedAttributes.productType; var bundle = { 'connections': [], } function finishFunc(res) { cachedAvailableConnectionTypes.connectionsRes = res; cachedAvailableConnectionTypes.queryTime = new Date(); cachedAvailableConnectionTypes.cached = true; defered.resolve(res); } if(productType === 'T4') { checkForUSBConnectivity(bundle) .then(checkForEthernetConnectivity) .then(finishFunc); } else if(productType === 'T7') { checkForUSBConnectivity(bundle) .then(checkForEthernetConnectivity) .then(finishFunc); } else if(productType === 'T7-Pro') { checkForUSBConnectivity(bundle) .then(checkForEthernetConnectivity) .then(checkForWiFiConnectivity) .then(finishFunc); } else { checkForUSBConnectivity(bundle) .then(finishFunc); } return defered.promise; }; /* This is the cached version of the get available connection types function */ var cachedAvailableConnectionTypes = { connectionsRes: [], queryTime: new Date(), cached: false, }; this.cGetAvailableConnectionTypes = function() { if(cachedAvailableConnectionTypes.cached) { var curTime = new Date(); var fiveMin = 1000*60*5; // 1k ms, 60 sec/min, 5min if(curTime - cachedAvailableConnectionTypes.queryTime > fiveMin) { return self.getAvailableConnectionTypes(); } else { var defered = q.defer(); defered.resolve(cachedAvailableConnectionTypes.connectionsRes); return defered.promise; } } else { return self.getAvailableConnectionTypes(); } } } module.exports.get = getAvailableConnectionsOperations;
'use strict' const test = require('tape') const SolidResponse = require('solid-web-client/lib/models/response') const acls = require('../../src/index') // solid-permissions module const resourceUrl = 'https://example.com/resource1' const sinon = require('sinon') const deleteSpy = sinon.spy() const mockWebClient = { head: (url) => { let response = new SolidResponse() response.url = url response.acl = 'resource1.acl' return Promise.resolve(response) }, del: deleteSpy } test('clearPermissions() test', t => { let aclUrl = 'https://example.com/resource1.acl' acls.clearPermissions(resourceUrl, mockWebClient) .then(() => { t.ok(deleteSpy.calledWith(aclUrl), 'should result in a DELETE call to the .acl url') t.end() }) .catch(err => { console.log(err) t.fail() }) })
'use strict'; /* http://docs.angularjs.org/guide/dev_guide.e2e-testing */ describe('ShoppingCart App', function() { describe('Cart list view', function() { beforeEach(function() { browser.get('app/index.html'); }); it('should filter the cart list as a user types into the search box', function() { var cartList = element.all(by.repeater('cart in carts')); var query = element(by.model('query')); expect(cartList.count()).toBe(6); query.sendKeys('software'); expect(cartList.count()).toBe(1); query.clear(); query.sendKeys('what'); expect(cartList.count()).toBe(5); }); }); });
/* eslint-disable no-unused-vars, arrow-body-style */ module.exports = { up: (queryInterface, Sequelize) => { /* Add altering commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkInsert('Person', [{ name: 'John Doe', isBetaMember: false }], {}); */ return queryInterface.bulkInsert('Role', [ { name: 'administator', description: 'administrates', createdAt: new Date(), updatedAt: new Date(), }, { name: 'staff', description: 'staffs', createdAt: new Date(), updatedAt: new Date(), }, { name: 'employment', description: 'employs', createdAt: new Date(), updatedAt: new Date(), }, { name: 'volunteer', description: 'volunteers', createdAt: new Date(), updatedAt: new Date(), }, ]); }, down: (queryInterface, Sequelize) => { /* Add reverting commands here. Return a promise to correctly handle asynchronicity. Example: return queryInterface.bulkDelete('Person', null, {}); */ return queryInterface.bulkDelete('Role', null, {}); } };
'use strict'; var sass = require('node-sass'); var data = '#hello {\n color: #08c; }\n'; const result = sass.renderSync({ data: data }).css.toString(); if (result === data) { console.log('ok'); }
import Armor from './Armor'; import DamageTypes from '../DamageTypes'; /** Amount of protection provided by armor */ var AMOUNT = 2; /** * Provides moderate protection against physical attacks */ export default class MediumArmor extends Armor { /** * @override */ getReduction(type) { return (type === DamageTypes.MELEE_PHYSICAL || type === DamageTypes.RANGED_PHYSICAL) ? AMOUNT : 0; } /** * @override */ getFriendlyDescription() { return `Reduces normal weapon damage by ${AMOUNT}`; } }
'use strict'; //Setting up route angular.module('codehubblogs').config(['$stateProvider', function($stateProvider) { // Codehubblogs state routing $stateProvider. state('listCodehubblogs', { url: '/codehubblogs', templateUrl: 'modules/codehubblogs/views/list-codehubblogs.client.view.html' }). state('createCodehubblog', { url: '/codehubblogs/create', templateUrl: 'modules/codehubblogs/views/create-codehubblog.client.view.html' }). state('viewCodehubblog', { url: '/codehubblogs/:codehubblogId', templateUrl: 'modules/codehubblogs/views/view-codehubblog.client.view.html' }). state('editCodehubblog', { url: '/codehubblogs/:codehubblogId/edit', templateUrl: 'modules/codehubblogs/views/edit-codehubblog.client.view.html' }); } ]);
/* * React.js Starter Kit * Copyright (c) 2014 Konstantin Tarkus (@koistya), KriaSoft LLC. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ 'use strict'; import React from 'react'; import ExecutionEnvironment from 'react/lib/ExecutionEnvironment'; import AppActions from '../../actions/AppActions'; var NavigationMixin = { componentDidMount() { if (ExecutionEnvironment.canUseDOM) { window.addEventListener('popstate', this.handlePopState); window.addEventListener('click', this.handleClick); } }, componentWillUnmount() { window.removeEventListener('popstate', this.handlePopState); window.removeEventListener('click', this.handleClick); }, handlePopState(event) { if (event.state) { var path = event.state.path; // TODO: Replace current location // replace(path, event.state); } else { AppActions.navigateTo(window.location.pathname); } }, handleClick(event) { if (event.button === 1 || event.metaKey || event.ctrlKey || event.shiftKey || event.defaultPrevented) { return; } // Ensure link var el = event.target; while (el && el.nodeName !== 'A') { el = el.parentNode; } if (!el || el.nodeName !== 'A') { return; } // Ignore if tag has // 1. "download" attribute // 2. rel="external" attribute if (el.getAttribute('download') || el.getAttribute('rel') === 'external') { return; } // Ensure non-hash for the same path var link = el.getAttribute('href'); if (el.pathname === location.pathname && (el.hash || '#' === link)) { return; } // Check for mailto: in the href if (link && link.indexOf('mailto:') > -1) { return; } // Check target if (el.target) { return; } // X-origin var origin = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : ''); if (!(el.href && el.href.indexOf(origin) === 0)) { return; } // Rebuild path var path = el.pathname + el.search + (el.hash || ''); event.preventDefault(); AppActions.loadPage(path, () => { AppActions.navigateTo(path); }); } }; module.exports = NavigationMixin;
version https://git-lfs.github.com/spec/v1 oid sha256:a92d66dc03be7a70aaeec898345e55d264dd3011b47eb1e85956220caa5afd97 size 2527050
"use strict"; var _ = require('underscorem'); var apf = require('./apf'); var objectstate = require('./objectstate'); exports.make = function(dataDir, schema, ol, cb){ _.assertLength(arguments, 4); var apState; var ap; apState = require('./ap_state').make(schema, ol); //var inv = require('./inverse').make(); //var broadcaster = require('./broadcast').make(schema); //inv.setBroadcaster(broadcaster) //apState.external.setBroadcaster(broadcaster) //TODO apf load should go straight to OLE ol.propertyIndex.endIndexAttaching() apf.load(dataDir, schema, ol.readers, ol.getLatestVersionId(), function(aph){ apState.setAp(aph) cb(apState.external, aph.close.bind(aph)) }) }
$(document).ready(function() { $('#file-list tr.ls').click(function(e) { e.preventDefault(); $('*').addClass('cursor-wait'); window.location = '?ls='+$(this).attr('data-href'); }); $('#file-list tr.dl').click(function(e) { e.preventDefault(); $('*').addClass('cursor-wait'); window.location = '?dl='+$(this).attr('data-href')+'&size='+$(this).attr('data-size'); setTimeout(function() { $('*').removeClass('cursor-wait'); }, 2000); }); $('.breadcrumb a').click(function(e) { $('*').addClass('cursor-wait'); }); $('.active>a, .disabled>a').click(function(e) { e.preventDefault(); }); });
'use strict'; var Dispatcher = require('../dispatcher/appDispatcher'); var Promise = require('es6-promise').Promise; var ClientsStore = require('../stores/clientsStore'); var ClientsApi = require('../api/clientsApi'); var ActionTypes = require('../constants/actionTypes'); var ClientActions = { getClients: function () { ClientsApi .get('/api/clients') .then(function (clients) { Dispatcher.handleViewAction({ actionType: ActionTypes.RECEIVE_CLIENTS, clients: clients }); }) .catch(function() { Dispatcher.handleViewAction({ actionType: ActionTypes.RECEIVE_ERROR, error: 'There was a problem getting the clients' }); }); } }; module.exports = ClientActions;
version https://git-lfs.github.com/spec/v1 oid sha256:8652a96237d642dd98f52e8b6b5b5d60ba19476df2dcc433e7e623f3e47964a1 size 20912
const Joi = require('joi'); const Boom = require('boom'); const authService = require('../../services/auth'); module.exports.login = { description: 'Login with member credentials', validate: { payload: { username: Joi.string().required().min(2, 'utf8'), password: Joi.string().required().min(8, 'utf8'), }, }, handler(request, reply) { return authService.validatePassword(request.payload.username, request.payload.password) .then((member) => { if (!member) { return reply('Unauthorized').code(403); } return reply({ token: authService.getToken(member) }); }) .catch(err => reply(Boom.badImplementation('Login failed', err))); }, };
import React, { Component } from 'react' import CheckCircle from 'material-ui/svg-icons/action/check-circle' import { green500 } from 'material-ui/styles/colors' class IconOk extends Component { constructor(props) { super(props) } render() { return ( <CheckCircle color={green500} /> ) } } export default IconOk
import Init from '../../src/js/init' describe('Init Module', () => { it('has a function named init', () => { expect(typeof Init.init).toBe('function') }) })
define(['require'], function (require) { var isDebugging = false, nativeKeys = Object.keys, hasOwnProperty = Object.prototype.hasOwnProperty, toString = Object.prototype.toString, system, treatAsIE8 = false, console = console ? console : undefined; //see http://patik.com/blog/complete-cross-browser-console-log/ // Tell IE9 to use its built-in console if (Function.prototype.bind && (typeof console === 'object' || typeof console === 'function') && typeof console.log === 'object') { try { ['log', 'info', 'warn', 'error', 'assert', 'dir', 'clear', 'profile', 'profileEnd'] .forEach(function(method) { console[method] = this.call(console[method], console); }, Function.prototype.bind); } catch (ex) { treatAsIE8 = true; } } // callback for dojo's loader // note: if you wish to use Durandal with dojo's AMD loader, // currently you must fork the dojo source with the following // dojo/dojo.js, line 1187, the last line of the finishExec() function: // (add) signal("moduleLoaded", [module.result, module.mid]); // an enhancement request has been submitted to dojo to make this // a permanent change. To view the status of this request, visit: // http://bugs.dojotoolkit.org/ticket/16727 if (require.on) { require.on("moduleLoaded", function (module, mid) { system.setModuleId(module, mid); }); } // callback for require.js loader if (typeof requirejs !== 'undefined') { requirejs.onResourceLoad = function (context, map, depArray) { system.setModuleId(context.defined[map.id], map.id); }; } var noop = function() { }; var log = function() { try { // Modern browsers if (typeof console !== 'undefined' && typeof console.log === 'function') { // Opera 11 if (window.opera) { var i = 0; while (i < arguments.length) { console.log('Item ' + (i + 1) + ': ' + arguments[i]); i++; } } // All other modern browsers else if ((Array.prototype.slice.call(arguments)).length === 1 && typeof Array.prototype.slice.call(arguments)[0] === 'string') { console.log((Array.prototype.slice.call(arguments)).toString()); } else { console.log(Array.prototype.slice.call(arguments)); } } // IE8 else if ((!Function.prototype.bind || treatAsIE8) && typeof console !== 'undefined' && typeof console.log === 'object') { Function.prototype.call.call(console.log, console, Array.prototype.slice.call(arguments)); } // IE7 and lower, and other old browsers } catch(ignore) {} }; var logError = function(error) { throw error; }; system = { version:"1.2.0", noop: noop, getModuleId: function(obj) { if (!obj) { return null; } if (typeof obj === 'function') { return obj.prototype.__moduleId__; } if (typeof obj === 'string') { return null; } return obj.__moduleId__; }, setModuleId: function (obj, id) { if (!obj) { return; } if (typeof obj === 'function') { obj.prototype.__moduleId__ = id; return; } if (typeof obj === 'string') { return; } obj.__moduleId__ = id; }, debug: function(enable) { if (arguments.length === 1) { isDebugging = enable; if (isDebugging) { this.log = log; this.error = logError; this.log('Debug mode enabled.'); } else { this.log('Debug mode disabled.'); this.log = noop; this.error = noop; } } else { return isDebugging; } }, isArray: function(obj) { return toString.call(obj) === '[object Array]'; }, log: noop, error: noop, defer: function(action) { return $.Deferred(action); }, guid: function() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); }, acquire: function() { var modules = Array.prototype.slice.call(arguments, 0); return this.defer(function(dfd) { require(modules, function() { var args = arguments; setTimeout(function() { dfd.resolve.apply(dfd, args); }, 1); }); }).promise(); } }; system.keys = nativeKeys || function(obj) { if (obj !== Object(obj)) { throw new TypeError('Invalid object'); } var keys = []; for (var key in obj) { if (hasOwnProperty.call(obj, key)) { keys[keys.length] = key; } } return keys; }; return system; });
'use strict'; /** * Module dependencies. */ var passport = require('passport'); module.exports = function(app) { // User Routes var users = require('../../app/controllers/users'); var admin = require('../../app/controllers/admin'); app.route('/users/me').get(users.me); app.route('/users').get(users.requiresLogin, users.list).put(users.requiresLogin, users.update); app.route('/users/:userId').get(users.requiresLogin, users.read).put(users.requiresLogin, users.adminUpdate); app.route('/users/:userId/password').post(users.requiresLogin, users.changePassword); app.route('/users/accounts').delete(users.removeOAuthProvider); app.route('/users/view').get(users.requiresLogin, users.applicantView); app.route('/users/check/uniqueUsername').post(users.uniqueUsername); // Setting up the users api app.route('/auth/:campId/signup').post(users.signup); app.route('/auth/signin').post(users.signin); app.route('/auth/signout').get(users.signout); app.route('/camps').get(users.getCamps); app.route('/camps/:campId').get(users.getCamp); // Setting the facebook oauth routes app.route('/auth/facebook').get(passport.authenticate('facebook', { scope: ['email'] })); app.route('/auth/facebook/callback').get(users.oauthCallback('facebook')); // Setting the twitter oauth routes app.route('/auth/twitter').get(passport.authenticate('twitter')); app.route('/auth/twitter/callback').get(users.oauthCallback('twitter')); // Setting the google oauth routes app.route('/auth/google').get(passport.authenticate('google', { scope: [ 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email' ] })); app.route('/auth/google/callback').get(users.oauthCallback('google')); // Setting the linkedin oauth routes app.route('/auth/linkedin').get(passport.authenticate('linkedin')); app.route('/auth/linkedin/callback').get(users.oauthCallback('linkedin')); // Finish by binding the user middleware app.param('userId', users.userByID); // Finish by binding the bootcamp middleware app.param('campId', admin.campByID); //Finish by binding the test middleware app.param('testId', admin.testByID); };
/* eslint-env mocha */ import setup, { reducer, SEND_MIDI_MESSAGE, RECEIVE_MIDI_MESSAGE, SET_LISTENING_DEVICES } from '../../src'; import MidiApi from 'web-midi-test-api'; import unique from 'lodash.uniq'; import sinon from 'sinon'; import { applyMiddleware, createStore, combineReducers } from 'redux'; import createLogger from 'redux-logger'; const debug = false; const messageConverter = () => next => action => { if (action.type === 'NOT_A_MIDI_MESSAGE') { return next({...action, type: SEND_MIDI_MESSAGE}); } return next(action); }; describe('MIDI I/O', () => { let store, api, actions; const collector = ({getState}) => (next) => (action) => { actions.push(action); return next(action); }; beforeEach(() => { actions = []; const logger = createLogger({colors: false}); api = new MidiApi(); const {inputMiddleware, outputMiddleware} = setup({requestMIDIAccess: api.requestMIDIAccess}); store = createStore(combineReducers({midi: reducer}), applyMiddleware(inputMiddleware, messageConverter, outputMiddleware, collector, ...(debug ? [logger] : []))); return new Promise(resolve => setImmediate(resolve)); }); it('should see no devices to begin with', () => { store.getState() .should.have.deep.property('midi.devices') .which.deep.equals([]); }); it('should listen to no devices to begin with', () => { store.getState() .should.have.deep.property('midi.listeningDevices') .which.deep.equals([]); }); describe('with mock I/O devices', () => { let device; beforeEach(() => { device = api.createMIDIDevice({ numberOfInputs: 1, numberOfOutputs: 1, name: 'Mock MIDI device', manufacturer: 'motiz88', version: '1.1.1' }); }); it('should see devices', () => { store.getState() .should.have.deep.property('midi.devices') .which.is.an('array'); const devices = store.getState().midi.devices; for (let device of devices) { device.should.deep.match({manufacturer: 'motiz88', version: '1.1.1', state: 'connected', connection: 'closed'}); device.should.have.property('name') .which.is.a('string') .with.match(/^Mock MIDI device/); } const types = devices.map(device => device.type); types.should.include('output'); types.should.include('input'); unique(devices.map(device => device.id)) .should.have.length(2); }); it('should see devices added later', () => { device = api.createMIDIDevice({ numberOfInputs: 1, numberOfOutputs: 1, name: 'Other mock MIDI device', manufacturer: 'motiz88', version: '1.1.1' }); store.getState() .should.have.deep.property('midi.devices') .which.is.an('array'); const devices = store.getState().midi.devices; for (let device of devices) { device.should.deep.match({manufacturer: 'motiz88', version: '1.1.1', state: 'connected', connection: 'closed'}); } const names = devices.map(device => device.name); names.should.include.something.to.match(/^Mock MIDI device/); names.should.include.something.to.match(/^Other mock MIDI device/); const types = devices.map(device => device.type); types.filter(t => t === 'output') .should.have.length(2); types.filter(t => t === 'input') .should.have.length(2); unique(devices.map(device => device.id)) .should.have.length(4); }); it('should receive message when listening on device', () => { const devices = store.getState().midi.devices; const inputs = devices.filter(device => device.type === 'input'); const inputIds = inputs.map(device => device.id); store.dispatch({ type: SET_LISTENING_DEVICES, payload: inputs.map(device => device.id) }); actions = []; device.outputs[0].send([0x80, 0x7f, 0x7f], 1234); actions.should.deep.equal([{ type: RECEIVE_MIDI_MESSAGE, payload: {data: new Uint8Array([0x80, 0x7f, 0x7f]), timestamp: 1234, device: inputIds[0]} }]); }); it('should not receive message when not listening', () => { store.dispatch({ type: SET_LISTENING_DEVICES, payload: [] }); actions = []; device.outputs[0].send([0x80, 0x7f, 0x7f]); actions.should.be.empty; }); it('should send message to a valid device', () => { const devices = store.getState().midi.devices; const outputs = devices.filter(device => device.type === 'output'); const outputIds = outputs.map(device => device.id); device.inputs[0].onmidimessage = sinon.spy(); store.dispatch({ type: SEND_MIDI_MESSAGE, payload: {data: [0x80, 0x7f, 0x7f], timestamp: 1234, device: outputIds[0]} }); device.inputs[0].onmidimessage.should.have.been.calledWith({data: new Uint8Array([0x80, 0x7f, 0x7f]), receivedTime: 1234}); }); it('should pick up on actions created by later middleware', () => { const devices = store.getState().midi.devices; const outputs = devices.filter(device => device.type === 'output'); const outputIds = outputs.map(device => device.id); device.inputs[0].onmidimessage = sinon.spy(); store.dispatch({ type: 'NOT_A_MIDI_MESSAGE', payload: {data: [0x80, 0x7f, 0x7f], timestamp: 1234, device: outputIds[0]} }); device.inputs[0].onmidimessage.should.have.been.called; }); }); });
'use strict'; /** * Module dependencies */ var acl = require('acl'); // Using the memory backend acl = new acl(new acl.memoryBackend()); /** * Invoke Pieces Permissions */ exports.invokeRolesPolicies = function () { acl.allow([{ roles: ['admin'], allows: [{ resources: '/api/pieces', permissions: '*' }, { resources: '/api/pieces/:pieceId', permissions: '*' }] }, { roles: ['user'], allows: [{ resources: '/api/pieces', permissions: ['get', 'post'] }, { resources: '/api/pieces/:pieceId', permissions: ['get'] }] }, { roles: ['guest'], allows: [{ resources: '/api/pieces', permissions: ['get'] }, { resources: '/api/pieces/:pieceId', permissions: ['get'] }] }]); }; /** * Check If Pieces Policy Allows */ exports.isAllowed = function (req, res, next) { var roles = (req.user) ? req.user.roles : ['guest']; // If an Piece is being processed and the current user created it then allow any manipulation if (req.piece && req.user && req.piece.user && req.piece.user.id === req.user.id) { return next(); } // Check for user roles acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function (err, isAllowed) { if (err) { // An authorization error occurred return res.status(500).send('Unexpected authorization error'); } else { if (isAllowed) { // Access granted! Invoke next middleware return next(); } else { return res.status(403).json({ message: 'User is not authorized' }); } } }); };
var express = require('express'); router = express.Router(); _ = require('underscore'); router.get('/', function (req, res) { var data = req.app.locals.data; var now = new Date(); for (job in data) { var title = data[job].title; slug = title.replace(/\s+/g, '-').toLowerCase(); data[job].slug = slug; nd = new Date(data[job].dateClosing); data[job].dateClosingString = nd; } res.render('index', {data, now}); }); router.get('/open-jobs', function (req, res) { var data = req.app.locals.data; var now = new Date(); for (job in data) { var title = data[job].title; slug = title.replace(/\s+/g, '-').toLowerCase(); data[job].slug = slug; nd = new Date(data[job].dateClosing); data[job].dateClosingString = nd; } res.render('open-jobs', {data, now}); }); router.get('/job/:reference/:title', function(req, res) { var data = req.app.locals.data; res.render('job', { job : _.findWhere(data, {reference: req.params.reference}), jobString : JSON.stringify(_.findWhere(data, {reference: req.params.reference})), jobID : [req.params.reference] }); }); router.get('/api/:reference', function(req, res) { var data = req.app.locals.data; res.json(_.findWhere(data, {reference: req.params.reference})); }); module.exports = router;
var url = require('url'); var colours = require('colors'); var config = { textus : { port : 8080, base : null }, es : { host : "127.0.0.1", protocol : "http", port : 9200, timeout : 60000 }, mailgun : { key : null, from : "no-reply@textus.okfn.org" } }; /** * Module to handle reading of configuration, including sensible defaults and the ability to * override from the command line. */ module.exports = exports = { /** * @returns a configuration object */ conf : function(options) { console.log("\nConfiguring Textus : "); var argParser = require('optimist') .usage('Usage: $0 [options]') .alias('p', 'port') .describe('p', 'Textus HTTP server port, if applicable - overridden by PORT') .alias('e', 'esHost') .describe('e', 'ElasticSearch host - overridden by BONSAI_INDEX_URL') .describe('mailgunKey', 'Mailgun API key - overridden by MAILGUN_API_KEY') .describe( 'baseUrl', 'Base URL of the textus server, i.e. http://mytextus.org used when constructing password reminder links and similar - overridden by TEXTUS_BASE_URL') .alias('r', 'esProtocol').describe('r', 'ElasticSearch protocol [http|https] - overridden by BONSAI_INDEX_URL.').alias('t', 'esPort') .describe('t', 'ElasticSearch port number - overridden by BONSAI_INDEX_URL.').alias('i', 'esIndex') .describe('i', 'ElasticSearch index name - overridden by BONSAI_INDEX_URL')['default']({ p : 8080, t : 9200, r : 'http', e : '127.0.0.1', i : 'textus' }); var args = argParser.argv; if (options) { for ( var prop in options) { if (options.hasOwnProperty(prop)) { args[prop] = options[prop]; } } } if (args.help) { console.log(argParser.help()); process.exit(0); } if (args.port) { config.textus.port = parseInt(args.port, 10); } if (args.esHost) { config.es.host = args.esHost; } if (args.esProtocol) { config.es.protocol = args.esProtocol; } if (args.esPort) { config.es.port = parseInt(args.esPort, 10); } if (args.esIndex) { config.es.index = args.esIndex; } if (args.mailgunKey) { config.mailgun.key = args.mailgunKey; } if (args.baseUrl) { config.textus.base = args.baseUrl; } // Heroku configuration: override config with contents of env variables if // they exist. if (process.env.TEXTUS_BASE_URL) { config.textus.base = process.env.TEXTUS_BASE_URL; console.log("\tTEXTUS_BASE_URL".yellow + " = " + config.textus.base.green); } if (process.env.MAILGUN_API_KEY) { config.mailgun.key = process.env.MAILGUN_API_KEY; console.log("\tMAILGUN_API_KEY".yellow + " = " + config.mailgun.key.green); } if (process.env.PORT) { config.textus.port = parseInt(process.env.PORT, 10); } if (process.env.BONSAI_INDEX_URL) { esUrl = url.parse(process.env.BONSAI_INDEX_URL); config.es.protocol = esUrl.protocol.slice(0, -1); config.es.host = esUrl.hostname; config.es.port = (typeof esUrl.port !== 'undefined' && esUrl.port !== null) ? parseInt(esUrl.port, 10) : 80; config.es.index = esUrl.pathname.slice(1); console.log("\tBONSAI_INDEX_URL".yellow + " = " + process.env.BONSAI_INDEX_URL.green); } console.log("\tElastic Search".yellow + " = ", JSON.stringify(config.es, null, 0).green); if (config.mailgun.key === null) { console.log("\tMAILGUN_API_KEY".yellow + " : " + "No mailgun API key set, email functionality unavailable!".red + "\n\tTo fix this set the MAILGUN_API_KEY environment variable appropriately, " + "\n\tor specify with --mailgunKey on the command line."); } if (config.textus.base === null) { console.log("\tTEXTUS_BASE_URL".yellow + " : " + "Textus base URL will be extracted from first request to API".cyan); } return config; } };
$(document).ready(function () { get_data = function (page) { //Filter var email = $('#txt_email').val(); var type = $('#sel_type').val(); var credit_log_type = $('#sel_credit_log_type').val(); var status = $('#sel_status').val(); var order = $('#sel_order').val(); //End Filter $.ajax({ url: base_url + 'credit_log/get_data', type: 'POST', data: { page: page, email: email, type: type, credit_log_type: credit_log_type, status: status, order: order }, dataType: 'json', success: function (result) { $('#div_hidden').empty(); $('#table_content').empty(); $('#table_content').append("\ <tr>\ <th>No</th>\ <th>Email</th>\ <th>Credit Log Type</th>\ <th>Amount</th>\ <th>Type</th>\ <th>Description</th>\ <th>Status</th>\ <th>Date</th>\ <th>Action</th>\ </tr>\ "); if (result['result'] === 'r1') { //Set Paging var no = 1; var size = result['size']; var total_page = result['totalpage']; var class_page = ".page"; if (page > 1) { no = parseInt(1) + (parseInt(size) * (parseInt(page) - parseInt(1))); } writePaging(total_page, page, class_page); last_page = total_page; //End Set Paging for (var x = 0; x < result['total']; x++) { //Type var type = "Add"; if(result['type'][x] == 2){ type = "Deduct"; } //End Type //Status var status = "Request"; if(result['status'][x] == 1){ status = "Paid"; } //End Status //Date var date = "Created <br/> on <strong>" + result['cretime'][x] + "</strong>"; if (result['modby'][x] != null) { date += "<br/><br/> Modified by <strong>" + result['modby'][x] + "</strong> <br/> on <strong>" + result['modtime'][x] + "</strong>"; } //End Date //Action var action = ""; if(result['allowed_edit'] && result['type'][x] == 1){ action += "<a href='#' id='btn_edit" + result['id'][x] + "' class='fa fa-pencil-square-o'></a> &nbsp;"; } //End Action $('#table_content').append("\ <tr>\ <td>" + (parseInt(no) + parseInt(x)) + "</td>\ <td>" + result['email'][x] + "</td>\ <td>" + result['credit_log_type'][x] + "</td>\ <td>" + result['amount'][x] + "</td>\ <td>" + type + "</td>\ <td>" + result['description'][x] + "</td>\ <td>" + status + "</td>\ <td>" + date + "</td>\ <td>" + action + "</td>\ </tr>"); //Set Object ID $('#div_hidden').append("\ <input type='hidden' id='object" + x + "' value='" + result['id'][x] + "' />\ "); total_data++; //End Set Object ID } set_edit(); } else { $('#table_content').append("\ <tr>\ <td colspan='9'><strong style='color:red;'>" + result['message'] + "</strong></td>\ </tr>"); } } }); }; set_edit = function () { var id = []; for (var x = 0; x < total_data; x++) { id[x] = $('#object' + x).val(); } $.each(id, function (x, val) { $(document).off('click', '#btn_edit' + val); $(document).on('click', '#btn_edit' + val, function (event) { event.preventDefault(); set_state("edit"); $.ajax({ url: base_url + 'credit_log/get_specific_data', type: 'POST', data:{ id: val }, dataType: 'json', success: function (result) { if (result['result'] === 'r1') { $("#txt_data_id").val(val); $("#txt_data_id_customer").val(result['id_customer']); $("#txt_data_id_reseller").val(result['id_reseller']); $("#txt_data_email").val(result['email']); $("#txt_data_amount").val(result['amount']); $("#sel_data_status").val(result['status']); $('#modal_data').modal('show'); } else { alert("Error in connection"); $('#modal_data').modal('hide'); } } }); }); }); }; set_state = function (x) { state = x; if (x == "add") { $('#modal_data_title').html("Add Credit Log"); $('.form_data').val(''); $(".form-add").show(); $(".form-edit").hide(); $('#txt_data_email').prop('readonly', false); $('#txt_data_amount').prop('readonly', false); $('#error_container').hide(); $('#error_container_message').empty(); } else { $('#modal_data_title').html("Edit Credit Log"); $('.form_data').val(''); $(".form-add").hide(); $(".form-edit").show(); $('#txt_data_email').prop('readonly', true); $('#txt_data_amount').prop('readonly', true); $('#error_container').hide(); $('#error_container_message').empty(); } }; add_data = function (email, type, amount) { $.ajax({ url: base_url + 'credit_log/add_data', type: 'POST', data: { email: email, type: type, amount: amount }, dataType: 'json', beforeSend: function () { $('#error_container').hide(); $('#error_container_message').empty(); }, success: function (result) { if (result['result'] === 'r1') { $('#modal_data').modal('hide'); get_data(page); } else { $('#error_container').show(); $('#error_container_message').append(result['result_message']); } } }); }; edit_data = function (id, id_customer, id_reseller, amount, status) { $.ajax({ url: base_url + 'credit_log/edit_data', type: 'POST', data: { id: id, id_customer: id_customer, id_reseller: id_reseller, amount: amount, status: status }, dataType: 'json', beforeSend: function () { $('#error_container').hide(); $('#error_container_message').empty(); }, success: function (result) { if (result['result'] === 'r1') { $('#modal_data').modal('hide'); get_data(page); } else { $('#error_container').show(); $('#error_container_message').append(result['result_message']); } } }); }; });
// @flow import { createSelector } from 'reselect' import type { State } from 'types/state' const selectHeader = (state: State) => state.HeaderContainer const makeSelectisOpenDropdown = () => createSelector( selectHeader, s => s.isOpenDropdown ) const makeSelectisOpenSearchField = () => createSelector( selectHeader, s => s.isOpenSearchField ) export { selectHeader, makeSelectisOpenDropdown, makeSelectisOpenSearchField }
const webpack = require('webpack'); const helpers = require('./helpers'); /* * Plugins */ const CopyWebpackPlugin = require('copy-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ExtractTextWebpackPlugin = require('extract-text-webpack-plugin'); const autoprefixer = require('autoprefixer'); const METADATA = { title: '[app_name] Website', baseUrl: '/' }; module.exports = { metadata: METADATA, resolve: { extensions: ['', '.js', '.jsx'], root: helpers.root('src'), modulesDirectories: ['node_modules'], alias: { 'jquery': 'jquery/src/jquery.js', 'typed.js': 'typed.js/js/typed.js' } }, context: helpers.root('src'), module: { preLoaders: [ { test: /(\.jsx|\.js)$/, include: helpers.root('src'), loader: 'eslint' } ], loaders: [ { test: /\.(jsx|js)$/, include: helpers.root('src'), loaders: ['babel'] }, { test: /\.s?(c)ss$/, loader: 'style!css!postcss!sass' }, { test: /\.(ttf|png|jpe?g|eot|woff2?)$/, //loader: 'file?name=/[path][name].[ext]', loaders: [ 'file?hash=sha512&digest=hex&name=/[path][hash:6].[ext]', 'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false' ] } ] }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(true), new webpack.optimize.CommonsChunkPlugin({ name: 'vendor' }), new CopyWebpackPlugin([ { from: 'assets/images/logo-midtrans-color.png', to: 'assets/images' }, { from: 'assets/images/success.png', to: 'assets/images' }, { from: 'assets/images/failed.png', to: 'assets/images' }, ]), new HtmlWebpackPlugin({ template: './index.html', chunksSortMode: helpers.packageSort([ 'vendor', 'app' ]) }) ], postcss: [autoprefixer], node: { global: 'window', crypto: 'empty', module: false, clearImmediate: false, setImmediate: false } };
ng.module('smart-table', []).run(['$templateCache', function ($templateCache) { $templateCache.put('template/smart-table/pagination.html', '<nav ng-if="numPages && pages.length >= 2"><ul class="pagination">' + '<li ng-repeat="page in pages" ng-class="{active: page==currentPage}"><a href="javascript: void(0);" ng-click="selectPage(page)">{{page}}</a></li>' + '</ul></nav>'); }]);
Ext.define('Rally.apps.portfolioitemcosttracking.LowestLevelPortfolioRollupItem',{ extend: 'Rally.apps.portfolioitemcosttracking.RollupItem', processChildren: function(){ this._rollupDataToolTip = this.getTooltip(); if (this._notEstimated && this.getPreliminaryBudget() > this.getActualCostRollup()){ this._rollupDataRemainingCost = this.getPreliminaryBudget() - this.getActualCostRollup(); this._rollupDataTotalCost = this._rollupDataActualCost + this._rollupDataRemainingCost; } else { this._rollupDataRemainingCost = this._rollupDataTotalCost - this._rollupDataActualCost; } }, addChild: function(child){ if (!this.children){ this.children = []; this._rollupDataTotalCost = 0; //Need to clear this out becuase this is preliminary budget if there are no children this._rollupDataActualCost = 0; this._rollupDataRemainingCost = 0; this.__totalUnits = 0; this.__actualUnits = 0; } this.children.push(child); this.__totalUnits += child.__totalUnits || 0; this.__actualUnits += child.__actualUnits || 0; this._notEstimated = (this.__totalUnits === 0); this._rollupDataActualCost += child._rollupDataActualCost; this._rollupDataTotalCost += child._rollupDataTotalCost; this._rollupDataRemainingCost = this._rollupDataTotalCost - this._rollupDataActualCost; if (!this.projectCosts || !this.projectCosts[child.Project._ref]){ this.projectCosts = this._updateProjectNameAndCostHash(this.projectCosts, child.Project); } }, _updateProjectNameAndCostHash: function(projectCosts, project){ projectCosts = projectCosts || {}; var name = project._refObjectName, cost = Rally.apps.portfolioitemcosttracking.PortfolioItemCostTrackingSettings.getCostPerUnit(project._ref); if (Rally.apps.portfolioitemcosttracking.PortfolioItemCostTrackingSettings.isProjectUsingNormalizedCost(project._ref)){ name = "normalized (default)"; } projectCosts[name] = cost; return projectCosts; } });
export function timeAgo (time) { const between = Date.now() / 1000 - Number(time/1000) if (between>2592000) { return formatDate(time) } if (between < 3600) { return pluralize(~~(between / 60), ' 分钟前') } else if (between < 86400) { return pluralize(~~(between / 3600), ' 小时前') } else { return pluralize(~~(between / 86400), ' 天前') } } function pluralize (time, label) { if (time === 1) { return time + label } return time + label } function formatDate(time) { var date = new Date(time); var Y = date.getFullYear() + '-'; var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'; var D = date.getDate(); return Y+M+D; }
/* jshint -W117, -W030 */ require('../../../app/services/article'); describe('Article-factory', function () { var subject; beforeEach(function () { bard.appModule('svc.article'); bard.inject(this, 'occurances', 'categoryFactory'); bard.mockService(categoryFactory, { createLabels: undefined }); bard.inject(this, 'articleFactory'); subject = articleFactory; }); describe('getColumnConfig', function () { describe('with items', function () { it('should call update the categories', function () { subject.getColumnConfig('ledger', [1, 2, 3]); expect(categoryFactory.createLabels).to.have.been.called; }); }); context('getOptions', function () { it('should call the function from the service', function () { var user = { getOccurances: function () { return 'wrongcall'; }, getColumnConfig: subject.getColumnConfig }; var columns = user.getColumnConfig('budget'); var result = _.find(columns, ['prop', 'occurance']).options; expect(result).not.to.eql('wrongcall'); }); }); }); describe('categories', function () { it('should return the most updated categories on getColumn', function () { var columns = subject.getColumnConfig('budget'); var result = _.find(columns,['prop', 'category']).options; expect(result).to.eql([]); categoryFactory.createLabels.restore(); //NOTE: sinon on bower seems to be broken sinon.stub(categoryFactory, 'createLabels').returns(['a', 'b', 'c', 'd']); var columns = subject.getColumnConfig('budget', [{}, {}, {}]); result = _.find(columns,['prop', 'category']).options; expect(result).to.eql(['a', 'b', 'c', 'd']); }); }); });
const Client = require('./Client'); const Thread = require('./Thread'); const SOFA = require('sofa-js'); class Bot { constructor() { this.client = new Client(this); this.rootThread = new Thread(this); for (let [name, schema] of Object.entries(SOFA.schemas)) { let handlerName = "on" + name; this[handlerName] = function (cb) { let pattern = "SOFA::" + name + ":"; this.rootThread.hear(pattern, null, cb); }; } this.threads = {}; } thread(name) { if (!this.threads.hasOwnProperty(name)) { this.threads[name] = new Thread(this); } return this.threads[name]; } hear(pattern, cb) { this.rootThread.hear(pattern, null, cb); } onClientMessage(session, message) { if (this.onEvent) { this.onEvent(session, message); } let heard = false; if (session.thread) { heard = session.thread.onClientMessage(session, message); } if (!heard) { heard = this.rootThread.onClientMessage(session, message); } return heard; } } module.exports = Bot;
d3.multilineText = function() { var lineHeight = 1.4; var horizontalAlign = 'center'; // 'left', 'center', or 'right' var verticalAlign = 'center'; // 'top', 'center', or 'bottom' var paddingTop = 10; var paddingBottom = 10; var paddingLeft = 10; var paddingRight = 10; var textAnchorsByHorizontalAlign = { 'center': 'middle', 'left': 'start', 'right': 'end' }; function my(selection) { selection.each(function(d, i) { var text = d3.select(this), lines = d.text.split(/\n/), lineCount = lines.length, lineI, line, y; text.attr({ 'text-anchor': textAnchorsByHorizontalAlign[horizontalAlign], 'fill': 'black', transform: function(d) { return 'translate(' + translateX(d) + ',' + translateY(d) + ')'; }, }); for (lineI = 0; lineI < lineCount; lineI++) { line = lines[lineI]; text.append('tspan') .attr({ 'x': 0, 'y': lineTspanY(lineI, lineCount) }) .attr(lineTspanAttrs()) .text(line); } }); } function translateX(d) { switch (horizontalAlign) { case 'center': return d.w / 2; case 'left': return paddingLeft; case 'right': return d.w - paddingRight; } } function translateY(d) { switch (verticalAlign) { case 'center': return d.h / 2; case 'top': return paddingTop; case 'bottom': return d.h - paddingBottom; } } function lineTspanY(lineI, lineCount) { var y; switch (verticalAlign) { case 'center': y = (lineI - (lineCount - 1) / 2) * lineHeight; break; case 'top': y = lineI * lineHeight; break; case 'bottom': y = -((lineCount - 1) - lineI) * lineHeight; break; } return y ? y + 'em' : 0; } function lineTspanAttrs() { switch (verticalAlign) { case 'center': return {dy: '.35em'}; case 'top': return {dy: '1em'}; case 'bottom': return {dy: 0}; } } my.lineHeight = function(value) { if (!arguments.length) return lineHeight; lineHeight = value; return my; }; my.horizontalAlign = function(value) { if (!arguments.length) return horizontalAlign; horizontalAlign = value; return my; }; my.verticalAlign = function(value) { if (!arguments.length) return verticalAlign; verticalAlign = value; return my; }; my.paddingTop = function(value) { if (!arguments.length) return paddingTop; paddingTop = value; return my; }; my.paddingRight = function(value) { if (!arguments.length) return paddingRight; paddingRight = value; return my; }; my.paddingBottom = function(value) { if (!arguments.length) return paddingBottom; paddingBottom = value; return my; }; my.paddingLeft = function(value) { if (!arguments.length) return paddingLeft; paddingLeft = value; return my; }; return my; }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const pip_services3_commons_node_1 = require("pip-services3-commons-node"); const pip_services3_commons_node_2 = require("pip-services3-commons-node"); const pip_services3_commons_node_3 = require("pip-services3-commons-node"); const pip_services3_commons_node_4 = require("pip-services3-commons-node"); const pip_services3_commons_node_5 = require("pip-services3-commons-node"); const pip_services3_commons_node_6 = require("pip-services3-commons-node"); const pip_services3_commons_node_7 = require("pip-services3-commons-node"); const pip_services3_commons_node_8 = require("pip-services3-commons-node"); const SystemEventV1Schema_1 = require("../data/version1/SystemEventV1Schema"); class EventLogCommandSet extends pip_services3_commons_node_1.CommandSet { constructor(logic) { super(); this._logic = logic; // Register commands to the database this.addCommand(this.makeGetEventsCommand()); this.addCommand(this.makeLogEventCommand()); } makeGetEventsCommand() { return new pip_services3_commons_node_2.Command("get_events", new pip_services3_commons_node_5.ObjectSchema(true) .withOptionalProperty('filter', new pip_services3_commons_node_6.FilterParamsSchema()) .withOptionalProperty('paging', new pip_services3_commons_node_7.PagingParamsSchema()), (correlationId, args, callback) => { let filter = pip_services3_commons_node_3.FilterParams.fromValue(args.get("filter")); let paging = pip_services3_commons_node_4.PagingParams.fromValue(args.get("paging")); this._logic.getEvents(correlationId, filter, paging, callback); }); } makeLogEventCommand() { return new pip_services3_commons_node_2.Command("log_event", new pip_services3_commons_node_5.ObjectSchema(true) .withOptionalProperty('eventlog', new SystemEventV1Schema_1.SystemEventV1Schema()) .withOptionalProperty('event', new SystemEventV1Schema_1.SystemEventV1Schema()), (correlationId, args, callback) => { let event = args.get("event") || args.get("eventlog"); event.time = pip_services3_commons_node_8.DateTimeConverter.toNullableDateTime(event.time); this._logic.logEvent(correlationId, event, callback); }); } } exports.EventLogCommandSet = EventLogCommandSet; //# sourceMappingURL=EventLogCommandSet.js.map
// MODULES // var // Expectation library: chai = require( 'chai' ), // Mock server parameters: params = require( './../../app/params.js' ), // Module to be tested: handler = require( './../../app/routes/api.version.js' ); // VARIABLES // var expect = chai.expect, assert = chai.assert; // TESTS // describe( 'app/routes/api/version', function tests() { 'use strict'; // SETUP // var response; beforeEach( function() { response = { status: function( status ) { return this; }, send: function( body ) { return this; } }; }); // TESTS // it( 'should export a function', function test() { expect( handler ).to.be.a( 'function' ); }); it( 'should have an arity of 2', function test() { assert.strictEqual( handler.length, 2 ); }); it( 'should return a 200 status', function test() { response.status = function( status ) { assert.strictEqual( status, 200 ); return this; }; handler( {}, response ); }); it( 'should return mock version information', function test() { response.send = function( body ) { assert.deepEqual( JSON.parse( body ), params.VERSION ); return this; }; handler( {}, response ); }); });
require('./node_modules/coffee-script/lib/coffee-script/register'); require('./gulpfile.coffee');
var webpack = require('webpack') var fileName = require('./package').name var plugins = [] if (process.env.MINIFY) { fileName += '.min' plugins.push( new webpack.optimize.UglifyJsPlugin() ) } module.exports = { devtool: 'source-map', entry: './index.js', output: { filename: 'dist/' + fileName + '.js', library: 'moxios', libraryTarget: 'umd' }, externals: { 'axios': 'axios' }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['es2015'], plugins: ['add-module-exports'] } } ] } }
module.exports = function(status) { return status ? 'text-success' : 'text-danger'; };
'use strict'; var servicesModule = angular.module('myApp').controller('ServicesCtrl', function ($scope) { $(document).on('click', '#close-preview', function(){ $('.image-preview').popover('hide'); // Hover befor close the preview $('.image-preview').hover( function () { $('.image-preview').popover('show'); }, function () { $('.image-preview').popover('hide'); } ); }); $(function() { // Create the close button var closebtn = $('<button/>', { type:"button", text: 'x', id: 'close-preview', style: 'font-size: initial;', }); closebtn.attr("class","close pull-right"); // Set the popover default content $('.image-preview').popover({ trigger:'manual', html:true, title: "<strong>Preview</strong>"+$(closebtn)[0].outerHTML, content: "There's no image", placement:'bottom' }); // Clear event $('.image-preview-clear').click(function(){ $('.image-preview').attr("data-content","").popover('hide'); $('.image-preview-filename').val(""); $('.image-preview-clear').hide(); $('.image-preview-input input:file').val(""); $(".image-preview-input-title").text("Browse"); }); // Create the preview image $(".image-preview-input input:file").change(function (){ var img = $('<img/>', { id: 'dynamic', width:250, height:200 }); var file = this.files[0]; var reader = new FileReader(); // Set preview image into the popover data-content reader.onload = function (e) { $(".image-preview-input-title").text("Change"); $(".image-preview-clear").show(); $(".image-preview-filename").val(file.name); img.attr('src', e.target.result); $(".image-preview").attr("data-content",$(img)[0].outerHTML).popover("show"); } reader.readAsDataURL(file); }); }); /* add new customer */ $scope.postNewService = function () { }; // init $scope.sort = { sortingOrder : 'id', reverse : false }; $scope.gap = 0; $scope.filteredItems = []; $scope.groupedItems = []; $scope.itemsPerPage = 10; $scope.pagedItems = []; $scope.currentPage = 0; $scope.items = [ {"id":1,"name":"name 1","description":"description 1","surname":"surname 1"}, {"id":2,"name":"name 2","description":"description 1","surname":"surname 2"}, {"id":3,"name":"name 3","description":"description 1","surname":"surname 3"}, {"id":4,"name":"name 4","description":"description 1","surname":"surname 4"}, {"id":5,"name":"name 5","description":"description 1","surname":"surname 5"}, {"id":6,"name":"name 6","description":"description 1","surname":"surname 6"}, {"id":7,"name":"name 7","description":"description 1","surname":"surname 7"}, {"id":8,"name":"name 8","description":"description 1","surname":"surname 8"}, {"id":9,"name":"name 9","description":"description 1","surname":"surname 9"}, {"id":10,"name":"name 10","description":"description 1","surname":"surname 10"}, {"id":11,"name":"name 11","description":"description 1","surname":"surname 11"}, {"id":12,"name":"name 12","description":"description 1","surname":"surname 12"} ]; var searchMatch = function (haystack, needle) { if (!needle) { return true; } return haystack.toLowerCase().indexOf(needle.toLowerCase()) !== -1; }; // init the filtered items $scope.search = function () { $scope.filteredItems = $filter('filter')($scope.items, function (item) { for(var attr in item) { if (searchMatch(item[attr], $scope.query)) return true; } return false; }); // take care of the sorting order if ($scope.sort.sortingOrder !== '') { $scope.filteredItems = $filter('orderBy')($scope.filteredItems, $scope.sort.sortingOrder, $scope.sort.reverse); } $scope.currentPage = 0; // now group by pages $scope.groupToPages(); }; // calculate page in place $scope.groupToPages = function () { $scope.pagedItems = []; for (var i = 0; i < $scope.filteredItems.length; i++) { if (i % $scope.itemsPerPage === 0) { $scope.pagedItems[Math.floor(i / $scope.itemsPerPage)] = [ $scope.filteredItems[i] ]; } else { $scope.pagedItems[Math.floor(i / $scope.itemsPerPage)].push($scope.filteredItems[i]); } } }; $scope.range = function (size,start, end) { var ret = []; console.log(size,start, end); if (size < end) { end = size; start = size-$scope.gap; } for (var i = start; i < end; i++) { ret.push(i); } console.log(ret); return ret; }; $scope.prevPage = function () { if ($scope.currentPage > 0) { $scope.currentPage--; } }; $scope.nextPage = function () { if ($scope.currentPage < $scope.pagedItems.length - 1) { $scope.currentPage++; } }; $scope.setPage = function () { $scope.currentPage = this.n; }; $scope.search(); }); servicesModule.$inject = ['$scope', '$filter']; servicesModule.directive("customSort", function() { return { restrict: 'A', transclude: true, scope: { order: '=', sort: '=' }, template : ' <a ng-click="sort_by(order)" style="color: #555555;">'+ ' <span ng-transclude></span>'+ ' <i ng-class="selectedCls(order)"></i>'+ '</a>', link: function(scope) { // change sorting order scope.sort_by = function(newSortingOrder) { var sort = scope.sort; if (sort.sortingOrder == newSortingOrder){ sort.reverse = !sort.reverse; } sort.sortingOrder = newSortingOrder; }; scope.selectedCls = function(column) { if(column == scope.sort.sortingOrder){ return ('icon-chevron-' + ((scope.sort.reverse) ? 'down' : 'up')); } else{ return'icon-sort' } }; }// end link } });
(function () { 'use strict'; angular .module('users') .factory('UserMembershipsService', UserMembershipsService); /* @ngInject */ function UserMembershipsService($resource) { return $resource('/api/users/memberships/:type', { type: '@type' }, { post: { method: 'POST' } }); } }());
import test from 'ava'; import sinon from 'sinon'; import { createToneAdapter } from '../index'; test('should invoke chain on source with rest of args, and then Tone.Master', t => { const expected = ['a', 'b', 'c']; const chain = sinon.spy(); const toneAdapter = createToneAdapter({ Master: 'c', }); toneAdapter.chainToMaster({ chain }, 'a', 'b'); const result = chain.lastCall.args; t.deepEqual(result, expected); });
'use strict'; $(document).ready(function() { //Our categories of beer //ipa, strongAle, stoutPorter, lagerPilsner, scotch, pale, //wheat, belgian, sour, bock, misc var ipa = [[ 'Imperial IPA', 'American IPA', 'English IPA', 'Wet Hop Ale', 'Imperial Red', 'Irish Red' ], 'ipa']; var strongAle = [[ 'American Strong Pale', 'Wheatwine', 'BBL Aged Strong', 'American Imperial Porter', 'Old Ale', 'Braggot', 'BBL Aged Dark', 'American Barleywine', 'British Barleywine', 'BBL Aged', 'Aged Beer', 'Strong Ale', 'Malt Liquor' ], 'strongAle']; var stoutPorter = [[ 'American Stout', 'Sweet Stout', 'Cream Ale', 'Dry Irish Stout', 'American Imperial Stout', 'Export Stout', 'Oatmeal Stout', 'Stout', 'Coffee Beer', 'Baltic Porter', 'English Brown', 'Robust Porter', 'Brown Porter', 'American Brown' ], 'stoutPorter']; var lagerPilsner = [[ 'Vienna Lager', 'Oktoberfest', 'American Dark Lager', 'German Pilsener', 'Kölsch', 'International Pilsener', 'American Premium Lager', 'American Pilsener', 'Bohemian Pilsener', 'Märzen', 'American Lager', 'California Common', 'Black Ale', 'Schwarzbier', 'Euro Dark' ], 'lagerPilsner']; var scotch = [[ 'Scottish Export', 'Scotch Ale' ], 'scotch']; var pale = [[ 'Special Bitter', 'English Dark Mild', 'Amber', 'Bitter', 'Bière de Garde', 'English Pale Mild', 'Blonde', 'ESB', 'Austrailian Pale', 'English Pale', 'American Pale', 'German Rye', 'Rye Ale' ], 'pale']; var wheat = [[ 'Witbier', 'Wheat Ale', 'Dunkelweizen', 'Hefeweizen', 'Bernsteinfarbenesweizen' ], 'wheat']; var belgian = [[ 'Belgian Pale', 'Belgian Blonde', 'Belgian Dubbel', 'Belgian Pale Strong', 'American/Belgian Dark', 'Belgian Dark Strong', 'Belgian Ale', 'Belgian Tripel', 'Saison', 'American/Belgian Pale' ], 'belgian']; var sour = [[ 'BBL Aged Sour', 'Sour', 'Brett', 'Berlinerweisse' ], 'sour']; var bock = [[ 'Doppelbock', 'Maibock', 'Bock', 'Weizenbock', 'Altbier' ], 'bock']; var misc = [[ 'Specialty', 'Spice Beer', 'Pumpkin Beer', 'Smoke Beer', 'Fruit Beer', 'Fruit Wheat Ale', 'Common Cider', 'New England Cider', 'Experimental Beer', 'Flavored Malt Beverage', 'Experimental Beer' ], 'misc']; var styles = [ipa, strongAle, stoutPorter, lagerPilsner, scotch, pale, wheat, belgian, sour, bock, misc]; //Get the user's history from local storage var history = []; if(localStorage.beerHistory) { history = JSON.parse(localStorage.beerHistory); } //Get the style category from our app that the beer belongs to var getBeerStyle = function(beer) { for (var i = 0; i < styles.length; i++) { for (var j = 0; j < styles[i][0].length; j++) { if (styles[i][0][j] === beer.style.shortName) { return styles[i][1]; } } } return false; }; //Render the user's history to the page var renderHistory = function() { var listing; var beerLink; var beerABV; var beerIBU; $('.beer-grid-table').append('<thead><tr><th>Name</th><th>Brewery</th><th>Style</th><th>ABV</th><th class="ibuTH">IBU</th></tr></thead>'); history.forEach(function(beer) { var beerStyle = getBeerStyle(beer); beerABV = beer.abv; beerIBU = beer.ibu; if(!beerABV) { beerABV = '???'; } if(!beerIBU) { beerIBU = '???'; } beerLink = '<a href="./beer.html?id=' + beer.id + '&style=' + beerStyle + '">' + beer.nameDisplay + '</a>'; console.log(beerLink); listing = '<tr class="beer-list-item"><td class="name">' + beerLink + '</td>' + '<td>' + beer.breweries[0].name + '</td>' + '<td>' + beer.style.shortName + '</td>' + '<td>' + beerABV + '</td>' + '<td>' + beerIBU + '</td>' + '</tr>'; console.log(listing); $('.beer-grid-table').append(listing); }); }; renderHistory(); });
/* * Copyright (c) 2015 Sylvain Peyrefitte * * This file is part of mstsc.js. * * mstsc.js is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ (function () { /** * Mouse button mapping * @param button {integer} client button number */ function mouseButtonMap (button) { switch (button) { case 0: return 1 case 2: return 2 default: return 0 } }; /** * Mstsc client * Input client connection (mouse and keyboard) * bitmap processing * @param canvas {canvas} rendering element */ function Client (canvas) { this.canvas = canvas // create renderer this.render = new Mstsc.Canvas.create(this.canvas) this.socket = null this.activeSession = false this.install() } Client.prototype = { install: function () { var self = this // bind mouse move event this.canvas.addEventListener('mousemove', function (e) { if (!self.socket) return var offset = Mstsc.elementOffset(self.canvas) self.socket.emit('mouse', e.clientX - offset.left, e.clientY - offset.top, 0, false) e.preventDefault || !self.activeSession() return false }) this.canvas.addEventListener('mousedown', function (e) { if (!self.socket) return var offset = Mstsc.elementOffset(self.canvas) self.socket.emit('mouse', e.clientX - offset.left, e.clientY - offset.top, mouseButtonMap(e.button), true, self.canvas.toDataURL()) e.preventDefault() return false }) this.canvas.addEventListener('mouseup', function (e) { if (!self.socket || !self.activeSession) return var offset = Mstsc.elementOffset(self.canvas) self.socket.emit('mouse', e.clientX - offset.left, e.clientY - offset.top, mouseButtonMap(e.button), false) e.preventDefault() return false }) this.canvas.addEventListener('contextmenu', function (e) { if (!self.socket || !self.activeSession) return var offset = Mstsc.elementOffset(self.canvas) self.socket.emit('mouse', e.clientX - offset.left, e.clientY - offset.top, mouseButtonMap(e.button), false) e.preventDefault() return false }) this.canvas.addEventListener('DOMMouseScroll', function (e) { if (!self.socket || !self.activeSession) return var isHorizontal = false var delta = e.detail var step = Math.round(Math.abs(delta) * 15 / 8) var offset = Mstsc.elementOffset(self.canvas) self.socket.emit('wheel', e.clientX - offset.left, e.clientY - offset.top, step, delta > 0, isHorizontal) e.preventDefault() return false }) this.canvas.addEventListener('mousewheel', function (e) { if (!self.socket || !self.activeSession) return var isHorizontal = Math.abs(e.deltaX) > Math.abs(e.deltaY) var delta = isHorizontal ? e.deltaX : e.deltaY var step = Math.round(Math.abs(delta) * 15 / 8) var offset = Mstsc.elementOffset(self.canvas) self.socket.emit('wheel', e.clientX - offset.left, e.clientY - offset.top, step, delta > 0, isHorizontal) e.preventDefault() return false }) // bind keyboard event window.addEventListener('keydown', function (e) { if (!self.socket || !self.activeSession) return self.socket.emit('scancode', Mstsc.scancode(e), true) e.preventDefault() return false }) window.addEventListener('keyup', function (e) { if (!self.socket || !self.activeSession) return self.socket.emit('scancode', Mstsc.scancode(e), false) e.preventDefault() return false }) return this }, /** * connect * @param ip {string} ip target for rdp * @param domain {string} microsoft domain * @param username {string} session username * @param password {string} session password * @param next {function} asynchrone end callback */ connect: function (next) { // compute socket.io path (cozy cloud integration) var parts = document.location.pathname.split('/'), base = parts.slice(0, parts.length - 1).join('/') + '/', path = base + 'socket.io' // start connection var self = this // this.socket = io(window.location.protocol + "//" + window.location.host, { "path": path}).on('rdp-connect', function() { this.socket = io(window.location.protocol + '//' + window.location.host).on('rdp-connect', function () { // this event can be occured twice (RDP protocol stack artefact) console.log('[WebRDP] connected') self.activeSession = true }).on('rdp-bitmap', function (bitmap) { console.log('[WebRDP] bitmap update bpp : ' + bitmap.bitsPerPixel) self.render.update(bitmap) }).on('title', function (data) { document.title = data }).on('headerBackground', function (data) { document.getElementById('header').style.backgroundColor = data }).on('header', function (data) { document.getElementById('header').innerHTML = data }).on('rdp-close', function () { next(null) console.log('[WebRDP] close') self.activeSession = false }).on('rdp-error', function (err) { next(err) console.log('[WebRDP] error : ' + err.code + '(' + err.message + ')') self.activeSession = false }) // emit infos event this.socket.emit('infos', { screen: { width: this.canvas.width, height: this.canvas.height }, locale: Mstsc.locale() }) } } Mstsc.client = { create: function (canvas) { return new Client(canvas) } } })()
import StarMarketContract from '../../../../build/contracts/StarMarket.json' import store from '../../../store' const contract = require('truffle-contract') export function revokeBid(starIndex) { let web3 = store.getState().web3.web3Instance // Double-check web3's status. if (typeof web3 !== 'undefined') { return function(dispatch) { // Using truffle-contract we create the starMarket object. const starMarket = contract(StarMarketContract) starMarket.setProvider(web3.currentProvider) // Declaring this for later so we can chain functions on StarMarket. var starMarketInstance // Get current ethereum wallet. web3.eth.getCoinbase((error, coinbase) => { // Log errors, if any. if (error) { console.error(error); } starMarket.deployed().then(function(instance) { starMarketInstance = instance starMarketInstance.withdrawBidForStar(starIndex, {from: coinbase, gas: 200000}).then(function(result) { console.log('revoke bid for star', result); }) }) }) } } else { console.error('Web3 is not initialized.'); } }
'use strict'; /** * Module dependencies. */ var _ = require('lodash'), defaultAssets = require('./config/assets/default'), testAssets = require('./config/assets/test'), fs = require('fs'), path = require('path'); module.exports = function (grunt) { // Project Configuration grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), env: { test: { NODE_ENV: 'development' }, dev: { NODE_ENV: 'development' }, prod: { NODE_ENV: 'production' } }, watch: { serverViews: { files: defaultAssets.server.views, options: { livereload: true } }, serverJS: { files: _.union(defaultAssets.server.gruntConfig, defaultAssets.server.allJS), tasks: ['jshint'], options: { livereload: true } }, clientViews: { files: defaultAssets.client.views, options: { livereload: true } }, clientJS: { files: defaultAssets.client.js, tasks: ['jshint'], options: { livereload: true } }, clientCSS: { files: defaultAssets.client.css, tasks: ['csslint'], options: { livereload: true } }, clientSCSS: { files: defaultAssets.client.sass, tasks: ['sass', 'csslint'], options: { livereload: true } }, clientLESS: { files: defaultAssets.client.less, tasks: ['less', 'csslint'], options: { livereload: true } } }, nodemon: { dev: { script: 'server.js', options: { nodeArgs: ['--debug'], ext: 'js,html', watch: _.union(defaultAssets.server.gruntConfig, defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config) } } }, concurrent: { default: ['nodemon', 'watch'], debug: ['nodemon', 'watch', 'node-inspector'], options: { logConcurrentOutput: true } }, jshint: { all: { src: _.union(defaultAssets.server.gruntConfig, defaultAssets.server.allJS, defaultAssets.client.js, testAssets.tests.server, testAssets.tests.client, testAssets.tests.e2e), options: { jshintrc: true, node: true, mocha: true, jasmine: true } } }, csslint: { options: { csslintrc: '.csslintrc' }, all: { src: defaultAssets.client.css } }, ngAnnotate: { production: { files: { 'public/dist/application.js': defaultAssets.client.js } } }, uglify: { production: { options: { mangle: false }, files: { 'public/dist/application.min.js': 'public/dist/application.js' } } }, cssmin: { combine: { files: { 'public/dist/application.min.css': defaultAssets.client.css } } }, sass: { dist: { files: [{ expand: true, src: defaultAssets.client.sass, ext: '.css', rename: function (base, src) { return src.replace('/scss/', '/css/'); } }] } }, less: { dist: { files: [{ expand: true, src: defaultAssets.client.less, ext: '.css', rename: function (base, src) { return src.replace('/less/', '/css/'); } }] } }, 'node-inspector': { custom: { options: { 'web-port': 1337, 'web-host': 'localhost', 'debug-port': 5858, 'save-live-edit': true, 'no-preload': true, 'stack-trace-limit': 50, 'hidden': [] } } }, mochaTest: { src: testAssets.tests.server, options: { reporter: 'spec' } }, karma: { unit: { configFile: 'karma.conf.js' } }, protractor: { options: { configFile: 'protractor.conf.js', keepAlive: true, noColor: false }, e2e: { options: { args: {} // Target-specific arguments } } }, copy: { localConfig: { src: 'config/env/local.example.js', dest: 'config/env/local.js', filter: function () { return !fs.existsSync('config/env/local.js'); } } } }); // Load NPM tasks require('load-grunt-tasks')(grunt); // Making grunt default to force in order not to break the project. grunt.option('force', true); // Make sure upload directory exists grunt.task.registerTask('mkdir:upload', 'Task that makes sure upload directory exists.', function () { // Get the callback var done = this.async(); grunt.file.mkdir(path.normalize(__dirname + '/modules/users/client/img/profile/uploads')); done(); }); // Connect to the MongoDB instance and load the models grunt.task.registerTask('mongoose', 'Task that connects to the MongoDB instance and loads the application models.', function () { // Get the callback var done = this.async(); // Use mongoose configuration var mongoose = require('./config/lib/mongoose.js'); // Connect to database mongoose.connect(function (db) { done(); }); }); grunt.task.registerTask('server', 'Starting the server', function () { // Get the callback var done = this.async(); var path = require('path'); var app = require(path.resolve('./config/lib/app')); var server = app.start(function () { done(); }); }); // Lint CSS and JavaScript files. grunt.registerTask('lint', ['sass', 'less', 'jshint', 'csslint']); // Lint project files and minify them into two production files. grunt.registerTask('build', ['env:dev', 'lint', 'ngAnnotate', 'uglify', 'cssmin']); // Run the project tests grunt.registerTask('test', ['env:test', 'lint', 'mkdir:upload', 'copy:localConfig', 'server', 'mochaTest', 'karma:unit']); grunt.registerTask('test:server', ['env:test', 'lint', 'server', 'mochaTest']); grunt.registerTask('test:client', ['env:test', 'lint', 'server', 'karma:unit']); // Run the project in development mode grunt.registerTask('default', ['env:dev', 'lint', 'mkdir:upload', 'copy:localConfig', 'concurrent:default']); // Run the project in debug mode grunt.registerTask('debug', ['env:dev', 'lint', 'mkdir:upload', 'copy:localConfig', 'concurrent:debug']); // Run the project in production mode grunt.registerTask('prod', ['build', 'env:prod', 'mkdir:upload', 'copy:localConfig', 'concurrent:default']); };
/** * @description This module provides the basic functions of Lychee. */ lychee = { title : document.title, version : '3.1.6', versionCode : '030106', updatePath : '//update.electerious.com/index.json', updateURL : 'https://github.com/electerious/Lychee', website : 'http://lychee.electerious.com', publicMode : false, viewMode : false, checkForUpdates : '1', sortingPhotos : '', sortingAlbums : '', location : '', dropbox : false, dropboxKey : '', content : $('.content'), imageview : $('#imageview') } lychee.init = function() { api.post('Session::init', {}, function(data) { // Check status // 0 = No configuration // 1 = Logged out // 2 = Logged in if (data.status===2) { // Logged in lychee.sortingPhotos = data.config.sortingPhotos || '' lychee.sortingAlbums = data.config.sortingAlbums || '' lychee.dropboxKey = data.config.dropboxKey || '' lychee.location = data.config.location || '' lychee.checkForUpdates = data.config.checkForUpdates || '1' // Show dialog when there is no username and password if (data.config.login===false) settings.createLogin() } else if (data.status===1) { // Logged out lychee.checkForUpdates = data.config.checkForUpdates || '1' lychee.setMode('public') } else if (data.status===0) { // No configuration lychee.setMode('public') header.dom().hide() lychee.content.hide() $('body').append(build.no_content('cog')) settings.createConfig() return true } $(window).bind('popstate', lychee.load) lychee.load() }) } lychee.login = function(data) { let user = data.username let password = data.password let params = { user, password } api.post('Session::login', params, function(data) { if (data===true) { window.location.reload() } else { // Show error and reactive button basicModal.error('password') } }) } lychee.loginDialog = function() { let msg = lychee.html` <p class='signIn'> <input class='text' name='username' autocomplete='username' type='text' placeholder='username' autocapitalize='off' autocorrect='off'> <input class='text' name='password' autocomplete='current-password' type='password' placeholder='password'> </p> <p class='version'>Lychee $${ lychee.version }<span> &#8211; <a target='_blank' href='$${ lychee.updateURL }'>Update available!</a><span></p> ` basicModal.show({ body: msg, buttons: { action: { title: 'Sign In', fn: lychee.login }, cancel: { title: 'Cancel', fn: basicModal.close } } }) if (lychee.checkForUpdates==='1') lychee.getUpdate() } lychee.logout = function() { api.post('Session::logout', {}, function() { window.location.reload() }) } lychee.goto = function(url = '') { url = '#' + url history.pushState(null, null, url) lychee.load() } lychee.load = function() { let albumID = '' let photoID = '' let hash = document.location.hash.replace('#', '').split('/') $('.no_content').remove() contextMenu.close() multiselect.close() if (hash[0]!=null) albumID = hash[0] if (hash[1]!=null) photoID = hash[1] if (albumID && photoID) { // Trash data photo.json = null // Show Photo if (lychee.content.html()==='' || (header.dom('.header__search').length && header.dom('.header__search').val().length!==0)) { lychee.content.hide() album.load(albumID, true) } photo.load(photoID, albumID) } else if (albumID) { // Trash data photo.json = null // Show Album if (visible.photo()) view.photo.hide() if (visible.sidebar() && (albumID==='0' || albumID==='f' || albumID==='s' || albumID==='r')) sidebar.toggle() if (album.json && albumID==album.json.id) view.album.title() else album.load(albumID) } else { // Trash albums.json when filled with search results if (search.hash!=null) { albums.json = null search.hash = null } // Trash data album.json = null photo.json = null // Hide sidebar if (visible.sidebar()) sidebar.toggle() // Show Albums if (visible.photo()) view.photo.hide() lychee.content.show() albums.load() } } lychee.getUpdate = function() { const success = function(data) { if (data.lychee.version>parseInt(lychee.versionCode)) $('.version span').show() } $.ajax({ url : lychee.updatePath, success : success }) } lychee.setTitle = function(title, editable) { document.title = lychee.title + ' - ' + title header.setEditable(editable) header.setTitle(title) } lychee.setMode = function(mode) { $('#button_settings, #button_trash_album, .button_add, .header__divider').remove() $('#button_trash, #button_move, #button_star').remove() $('#button_share, #button_share_album') .removeClass('button--eye') .addClass('button--share') .find('use') .attr('xlink:href', '#share') $(document) .off('click', '.header__title--editable') .off('touchend', '.header__title--editable') .off('contextmenu', '.photo') .off('contextmenu', '.album') .off('drop') Mousetrap .unbind([ 'u' ]) .unbind([ 's' ]) .unbind([ 'f' ]) .unbind([ 'r' ]) .unbind([ 'd' ]) .unbind([ 't' ]) .unbind([ 'command+backspace', 'ctrl+backspace' ]) .unbind([ 'command+a', 'ctrl+a' ]) if (mode==='public') { lychee.publicMode = true } else if (mode==='view') { Mousetrap.unbind([ 'esc', 'command+up' ]) $('#button_back, a#next, a#previous').remove() $('.no_content').remove() lychee.publicMode = true lychee.viewMode = true } } lychee.animate = function(obj, animation) { let animations = [ [ 'fadeIn', 'fadeOut' ], [ 'contentZoomIn', 'contentZoomOut' ] ] if (!obj.jQuery) obj = $(obj) for (let i = 0; i < animations.length; i++) { for (let x = 0; x < animations[i].length; x++) { if (animations[i][x]==animation) { obj.removeClass(animations[i][0] + ' ' + animations[i][1]).addClass(animation) return true } } } return false } lychee.retinize = function(path = '') { let extention = path.split('.').pop() let isPhoto = extention!=='svg' if (isPhoto===true) { path = path.replace(/\.[^/.]+$/, '') path = path + '@2x' + '.' + extention } return { path, isPhoto } } lychee.loadDropbox = function(callback) { if (lychee.dropbox===false && lychee.dropboxKey!=null && lychee.dropboxKey!=='') { loadingBar.show() let g = document.createElement('script') let s = document.getElementsByTagName('script')[0] g.src = 'https://www.dropbox.com/static/api/1/dropins.js' g.id = 'dropboxjs' g.type = 'text/javascript' g.async = 'true' g.setAttribute('data-app-key', lychee.dropboxKey) g.onload = g.onreadystatechange = function() { let rs = this.readyState if (rs && rs!=='complete' && rs!=='loaded') return lychee.dropbox = true loadingBar.hide() callback() } s.parentNode.insertBefore(g, s) } else if (lychee.dropbox===true && lychee.dropboxKey!=null && lychee.dropboxKey!=='') { callback() } else { settings.setDropboxKey(callback) } } lychee.getEventName = function() { let touchendSupport = (/Android|iPhone|iPad|iPod/i).test(navigator.userAgent || navigator.vendor || window.opera) && ('ontouchend' in document.documentElement) let eventName = (touchendSupport===true ? 'touchend' : 'click') return eventName } lychee.escapeHTML = function(html = '') { // Ensure that html is a string html += '' // Escape all critical characters html = html.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#039;') .replace(/`/g, '&#96;') return html } lychee.html = function(literalSections, ...substs) { // Use raw literal sections: we don’t want // backslashes (\n etc.) to be interpreted let raw = literalSections.raw let result = '' substs.forEach((subst, i) => { // Retrieve the literal section preceding // the current substitution let lit = raw[i] // If the substitution is preceded by a dollar sign, // we escape special characters in it if (lit.slice(-1)==='$') { subst = lychee.escapeHTML(subst) lit = lit.slice(0, -1) } result += lit result += subst }) // Take care of last literal section // (Never fails, because an empty template string // produces one literal section, an empty string) result += raw[raw.length - 1] return result } lychee.error = function(errorThrown, params, data) { console.error({ description : errorThrown, params : params, response : data }) loadingBar.show('error', errorThrown) }
var NwBuilder = require('node-webkit-builder') , nw = new NwBuilder({ files: [ __dirname + '/../**' , '!' + __dirname + '/../**/*.iml' , '!' + __dirname + '/../cache/**' , '!' + __dirname + '/../build/**' , '!' + __dirname + '/../node_modules/node-webkit-builder/**' , '!' + __dirname + '/../node_modules/jade/**' , '!' + __dirname + '/../node_modules/filesize/**' , '!' + __dirname + '/../node_modules/orchestra-client/node_modules/.bin/**' , '!' + __dirname + '/../node_modules/orchestra-client/node_modules/gulp*/**' , '!' + __dirname + '/../node_modules/orchestra-client/node_modules/express/**' , '!' + __dirname + '/../node_modules/orchestra-client/node_modules/tiny-lr/**' , '!' + __dirname + '/../node_modules/orchestra-client/node_modules/jshint-stylish/**' ], version: '0.11.6', //platforms: ['osx32', 'osx64', 'win32', 'win64'] platforms: ['osx64', 'win64'] }); //Log stuff you want nw.on('log', console.log); // Build returns a promise nw.build().then(function () { console.log('all done!'); }).catch(function (error) { console.error(error); });
import { combineReducers } from 'redux'; import LibraryReducer from './LibraryReducer'; import SelectionReducer from './SelectionReducer'; export default combineReducers ({ libraries: LibraryReducer, selectedLibraryId: SelectionReducer });
var express = require('express'); var app = express(); var ThaliAclDb = require('thali-acl'); // TODO: Make this configurable app.get('/usersperrole:role', function (req, res) { }); var server = app.listen(8085); // TODO: Make configurable
import React from 'react'; import {mount} from 'enzyme'; import {UsersPage} from './UsersPage'; //Using the undecorated component (In order to be able to test the component itself without having to deal with the decorator) function setup() { const props = { actions: { loadUsers: () => { //This is a mock/spy of loadUsers function return Promise.resolve(); } }, users: [ { id: 'some-id-1', name: 'Test User 1', email: 'testinguser@makingsense.com', createdAt: '2017-01-20' }, { id: 'some-id-2', name: 'Test User 2', email: 'testinguser2@makingsense.com', createdAt: '2017-01-21' } ], user: { id: '', name: '', email: '', createdAt: '' } }; return mount(<UsersPage {...props} />); } describe('Users Page', () => { it('Basic subcomponents rendering & count', () => { const wrapper = setup(); expect(wrapper.find('h1').text()).toEqual('Users List'); //The h1 text should be Users List expect(wrapper.find('Link').exists()).toBe(true); expect(wrapper.find('UserList').length).toEqual(1); //There has to be one UserList component. expect(wrapper.find('Modal').length).toEqual(1); //There has to be one Modal component. expect(wrapper.find('User').length).toEqual(2); //There has to be one User component. }); });
version https://git-lfs.github.com/spec/v1 oid sha256:46317a572666f86d2380818e2d525bda73ad34284562a265686846e1c70e5c92 size 50083
/* * 寻找发帖水王 * 一个数组,存在一个元素,个数超过数组个数的一般,找出该数 * 将复杂文件简化为小问题,然后再逐步解决这些小问题 */ function findMoreHalf (arr) { var candiate, nTime=0; for(var i=0; i<arr.length; i++) { if (nTime === 0) { candiate = arr[i]; nTime++; } else { if (candiate === arr[i]) { nTime++; } else { nTime--; } } } return candiate; } module.exports = { method1: findMoreHalf, }
var webpack = require('webpack') var DevServer = require('webpack-dev-server') var base = require('./demo-base') var webConfig = base('vue', true) var weexConfig = base('weex', true) var port = process.env.DEMO_PORT | 3456 webConfig.entry = { app: [ './demo/src/render.js', './demo/src/app.js', 'webpack/hot/dev-server', 'webpack-dev-server/client/?http://0.0.0.0:' + port ] } webConfig.plugins.push(new webpack.HotModuleReplacementPlugin()) // weex 版跑在 playground,里不需要热替换 weexConfig.entry = { app: ['./demo/src/app.js'] } new DevServer(webpack([webConfig, weexConfig]), { port: port, host: '0.0.0.0', // disable host check to avoid `Invalid Host header` issue disableHostCheck: true, hot: true, stats: { colors: true } }).listen('' + port, '0.0.0.0') console.log('Project is running at http://0.0.0.0:' + port + '/')
/** * # GameServer * Copyright(c) 2018 Stefano Balietti * MIT Licensed * * Parses incoming messages and emits correspondings events * * Contains methods that are instantiated / overwritten * by two inheriting classes: * * - `AdminServer` * - `PlayerServer` * * TODO: clearNode parameter is still flying around. */ "use strict"; // ## Global scope module.exports = GameServer; const util = require('util'); const EventEmitter = require('events').EventEmitter; util.inherits(GameServer, EventEmitter); const jwt = require('jsonwebtoken'); const Logger = require('./Logger'); const SocketManager = require('./SocketManager'); const GameMsgGenerator = require('./GameMsgGenerator'); const SocketIo = require('./sockets/SocketIo'); const SocketDirect = require('./sockets/SocketDirect'); const ngc = require('nodegame-client'); const GameMsg = ngc.GameMsg; /** * ### GameServer.codes * * Success and error numerical codes. For internal use only. */ GameServer.codes = { OPERATION_OK: 0, DUPLICATED_CLIENT_ID: -1, ROOM_NOT_FOUND: -2, INVALID_CLIENT_ID: -3 }; /** * ## GameServer constructor * * Creates a new instance of GameServer * * @param {object} options Configuration object * @param {ServerChannel} channel Reference to the parent channel */ function GameServer(options, channel) { EventEmitter.call(this); this.setMaxListeners(0); /** * ### GameServer.options * * Reference to the user options defined in the server channel */ this.options = options; /** * ### GameServer.channel * * Reference to the _ServerChannel_ in which the game server is created * * @see ServerChannel */ this.channel = channel; /** * ### GameServer.servernode * * Reference to the _ServerNode_ * * @see ServerNode */ this.servernode = this.channel.servernode; /** * ### GameServer.registry * * Reference to _ChannelRegistry_ inside the server channel * * @see GameServer.channel * @see ChannelRegistry */ this.registry = channel.registry; /** * ### GameServer.session * * The session ID as created by the channel. */ this.session = channel.session; /** * ### GameServer.endpoint * * The endpoint under which the server is reachable */ this.endpoint = '/' + options.endpoint; /** * ### GameServer.name * * The name of the server */ this.name = options.name; /** * ### GameServer.serverid * * A random id for the server */ this.serverid = '' + Math.random()*1000000000; /** * ### GameServer.sysLogger * * Logger of system events */ this.sysLogger = Logger.get('channel', { name: this.name }); /** * ### GameServer.msgLogger * * Logger of incoming / outgoing game messages */ this.msgLogger = Logger.get('messages', { name: this.name }); /** * ### GameServer.socket * * Socket manager for the server * * @see SocketManager */ this.socketManager = new SocketManager(this); /** * ### GameServer.msg * * Game message generator * * @see GameMsgGenerator */ this.msg = new GameMsgGenerator(this); /** * ### GameServer.partner * * The partner game server (Admin or Player) * * @see AdminServer * @see PlayerServer */ this.partner = null; /** * ### GameServer.sio * * Reference to the Socket.io App in the ServerNode * * @see ServerNode * @see ServerChannel */ this.sio = channel.sio; /** * ### GameServer.authCb * * An authorization callback */ this.authCb = null; /** * ### GameServer.accessDeniedUrl * * The url of the page to which unauthorized clients will be redirected */ this.accessDeniedUrl = options.accessDeniedUrl; /** * ### GameServer.generateClientId * * Client IDs generator callback. */ this.generateClientId = null; /** * ### GameServer.enableReconnections * * If TRUE, clients can reconnect to same game room * * Clients will be matched with previous game history based on * the clientId found in their cookies. */ this.enableReconnections = !!options.enableReconnections; /** * ### GameServer.antiSpoofing * * If TRUE, server asks clients to send along their sid in each msg */ this.antiSpoofing = !!options.antiSpoofing; } // ## GameServer methods /** * ### GameServer.setPartner * * Sets a twin server, i.e. AdminServer for PlayerServer and viceversa * * @param {object} server The partner server */ GameServer.prototype.setPartner = function(server) { this.partner = server; }; /** * ### GameServer.listen * * Attaches standard, and custom listeners */ GameServer.prototype.listen = function() { var sio, direct, socket_count; socket_count = 0; if (this.options.sockets) { // Open Socket.IO. if (this.options.sockets.sio) { sio = new SocketIo(this); sio.attachListeners(); this.socketManager.registerSocket(sio); socket_count++; } // Open Socket Direct. if (this.options.sockets.direct) { direct = new SocketDirect(this); this.socketManager.registerSocket(direct); socket_count++; } } if (!socket_count) { this.sysLogger.log('No open sockets', 'warn'); } this.attachListeners(); this.attachCustomListeners(); }; /** * ### GameServer.secureParse * * Parses a stringified message into a GameMsg * * @param {string} msgString A string to transform in `GameMSg` * * @return {boolean|GameMsg} The parsed game message, or FALSE * if parsing fails. * * @see GameServer.validateGameMsg */ GameServer.prototype.secureParse = function(msgString) { var gameMsg; try { gameMsg = new GameMsg(JSON.parse(msgString)); } catch(e) { this.sysLogger.log((this.ADMIN_SERVER ? 'Admin' : 'Player') + 'Server.secureParse: malformed msg ' + 'received: ' + e, 'error'); return false; } return gameMsg; }; /** * ### GameServer.validateGameMsg * * Validates the structure of an incoming Game Msg * * Performs the following operations: * * - verifies that _from_, _action_, and _target_ are non-empty strings, * - checks if the sender exists. * * Logs the outcome of the operation. * * _to_ and _from_ are validated separately. * * @param {GameMsg} gameMsg The game msg to validate * * @return {boolean|GameMsg} The parsed game message, or FALSE * if the msg is invalid or from an unknown sender. * * @see GameServer.validateRecipient * @see GameServer.validateSender */ GameServer.prototype.validateGameMsg = function(gameMsg) { var server; server = this.ADMIN_SERVER ? 'Admin' : 'Player'; if (gameMsg.from.trim() === '') { this.sysLogger.log(server + 'Server.validateGameMsg: Received msg ' + 'but msg.from is empty.', 'error'); return false; } if ('string' !== typeof gameMsg.target) { this.sysLogger.log(server + 'Server.validateGameMsg: Received msg ' + 'but msg.target is not string.', 'error'); return false; } if (gameMsg.target.trim() === '') { this.sysLogger.log(server + 'Server.validateGameMsg: Received msg ' + 'but msg.target is empty.', 'error'); return false; } if ('string' !== typeof gameMsg.action) { this.sysLogger.log(server + 'Server.validateGameMsg: Received msg ' + 'but msg.action is not string.', 'error'); return false; } if (gameMsg.action.trim() === '') { this.sysLogger.log(server + 'Server.validateGameMsg: Received msg ' + 'but msg.action is empty.', 'error'); return false; } if ('string' !== typeof gameMsg.session) { this.sysLogger.log(server + 'Server.validateGameMsg: Received msg ' + 'but msg.session is not string. Found: ' + gameMsg.session, 'error'); return false; } // Checking if the FROM field is known. if (!this.channel.registry.clients.exist(gameMsg.from)) { this.sysLogger.log(server + 'Server.validateGameMsg: Received msg ' + 'from unknown client: ' + gameMsg.from, 'error'); return false; } return gameMsg; }; /** * ### GameServer.onMessage * * Parses an incoming string into a GameMsg, and emits it as an event. * * This method must be called by a socket to notify an incoming message. * * @param {GameMsg} msg the incoming game message * @param {string} msgToLog Optional. The string representing the * game message as it will appear in the logs. Default: msg will * will be stringified. * * @see GameServer.secureParse * @see GameServer.validateRecipient */ GameServer.prototype.onMessage = function(msg, msgToLog) { var i, recipientList; var origSession, origStage, origFrom; // Logs the msg (if different from string, it will be stringified). this.msgLogger.log(msg, 'in', msgToLog); msg = this.validateGameMsg(msg); if (!msg) return; msg = this.validateRecipient(msg); if (!msg) return; msg = this.validateSender(msg); if (!msg) return; // Parsing successful, and recipient validated. // If gameMsg.to is an array, validate and send to each element separately. if (Object.prototype.toString.call(msg.to) === '[object Array]') { recipientList = msg.to; for (i in recipientList) { if (recipientList.hasOwnProperty(i)) { msg.to = recipientList[i]; msg = this.validateRecipient(msg); if (!msg) continue; this.sysLogger.log(msg.toEvent() + ' ' + msg.from + '-> ' + msg.to); // Save properties that might be changed by the // obfuscation in the emit handler. origSession = msg.session; origStage = msg.stage; origFrom = msg.from; this.emit(msg.toEvent(), msg); // Restore the properties. msg.session = origSession; msg.stage = origStage; msg.from = origFrom; } } } else { this.sysLogger.log(msg.toEvent() + ' ' + msg.from + '-> ' + msg.to); this.emit(msg.toEvent(), msg); } }; /** * ### GameServer.onDisconnect * * Handles client disconnections * * This method is called by a socket (Direct or SIO) when * it detects the client's disconnection. * * @param {string} sid The socket id of the client * @param {Socket} socket The sockect object * * @emit disconnect */ GameServer.prototype.onDisconnect = function(sid, socket) { var client, roomName, room; client = this.registry.clients.sid.get(sid); if (!client) { throw new Error('GameServer.onDisconnect: sid not found: ' + sid); } // Remove client from its room: roomName = this.registry.getClientRoom(client.id); room = this.channel.gameRooms[roomName]; if (!room) { // This can happen with transports different from websockets. // They can trigger another disconnect event after first disconnect. throw new Error( 'GameServer.onDisconnect: Could not determine room for ' + 'disconnecting ' + (this.ADMIN_SERVER ? 'admin' : 'player') + ': ' + client.id, 'error'); } // TODO: is this what we should do? Isn't enough to mark disconnected? room.clients.remove(client.id); // MODS. if (!room.haveDisconnected) room.haveDisconnected = {}; room.haveDisconnected[client.id] = client; // END MODS. this.registry.markDisconnected(client.id); // We need to write it down explicetely // because .stage and .stageLevel could be overwritten. client.disconnectedStage = client.stage; client.disconnectedStageLevel = client.stageLevel; // Emit so that it can be handled different by Admin and Player Server. this.emit('disconnect', client, room); }; /** * ### GameServer.onShutdown * * Callback when the server is shut down * * TODO: implement it */ GameServer.prototype.onShutdown = function() { this.sysLogger.log("GameServer is shutting down."); // TODO save state to disk }; /** * ### GameServer.attachCustomListeners * * Abstract method that will be overwritten by inheriting classes */ GameServer.prototype.attachCustomListeners = function() {}; /** * ### GameServer.notifyRoomConnection * * Send notifications when a clients connects to a room * * Abstract method that will be overwritten by inheriting classes * * @param {object} clientObj The connecting client * @param {object} room The game room object */ GameServer.prototype.notifyRoomConnection = function(clientObj, room) {}; /** * ### GameServer.notifyRoomDisconnection * * Send notifications when a clients disconnects from a room * * Abstract method that will be overwritten by inheriting classes * * @param {object} clientObj The disconnecting client * @param {object} room The game room object */ GameServer.prototype.notifyRoomDisconnection = function(clientObj, room) {}; /** * ### GameServer.onConnect * * Send a HI msg to the client, and log its arrival * * This method is called by a socket upon receiving a new connection. * * @param {string} socketId The id of the socket connection * @param {Socket} socketObj The socket object (Direct or SIO) * @param {object} handshake The Socket handshake data. * @param {string} clientType The type of the client (player, bot, etc.) * @param {string} startingRoom Optional. The name of the room in which * the client is to be placed. Default: Waiting or Requirements room * @param {string} clientId Optional. Specifies the client id * * @return {boolean} TRUE on success * * @see GameServer.handleReconnectingClient * @see GameServer.handleConnectingClient */ GameServer.prototype.onConnect = function(socketId, socketObj, handshake, clientType, startingRoom, clientId) { var decoded, res, clientObj; var cookies; var newConnection, invalidSessionCookie, clearNode; var tmpSid, tmpId, tmpType; newConnection = true; invalidSessionCookie = false; if (!handshake.headers || !handshake.headers.cookie) cookies = {}; else cookies = parseCookies(handshake.headers.cookie); decoded = {}; // Try to decode JWT only if auth or no-auth-cookie is on. let info = this.channel.gameInfo; // The order matters: logics/bots may connect earlier, // before info.auth is available. if (cookies && cookies.nodegame_token && ((info.auth && info.auth.enabled) || info.channel.noAuthCookie)) { // Parses cookie and logs errors. decoded = this.decodeJWT(cookies.nodegame_token); if (!decoded) decoded = {}; } // If a valid identification cookie is found, it will be used. if (decoded.session !== this.channel.session) { invalidSessionCookie = true; } else if (decoded.clientId) { clientId = decoded.clientId; } // Socket.io connections can by-pass http authorization, and would // be treated as new connections. This enforces cookie authorization // also for socket.io connections. if (socketObj.name !== 'direct') { res = this.channel.gameInfo.auth; if (res && res.enabled && (!clientId || invalidSessionCookie)) { // Warns and disconnect client if auth failed. this.disposeUnauthorizedClient(socketId, socketObj); return false; } else { // It looks like it is a "not-clean" reconnection. // Let's stop the game immediately after HI. clearNode = true; } } // Set default clientType. if (!clientType) { if (this.ADMIN_SERVER) clientType = 'admin'; else clientType = 'player'; } // Authorization check, if an authorization function is defined. if (this.authCb) { res = this.authCb(this, { // For retro-compatibility. TODO: remove in future version. headers: handshake.headers, handshake: handshake, query: handshake.query, cookies: cookies, room: startingRoom, clientId: clientId, clientType: clientType, validSessionCookie: !invalidSessionCookie }); if (!res) { // Warns and disconnect client if auth failed. this.disposeUnauthorizedClient(socketId, socketObj); return false; } } // A custom callback can assign / overwrite the value of clientId. if (this.generateClientId) { res = this.generateClientId(this, { // For retro-compatibility. TODO: remove in future version. headers: handshake.headers, handshake: handshake, query: handshake.query, cookies: cookies, room: startingRoom, clientId: clientId, validSessionCookie: !invalidSessionCookie, socketId: socketId }); // If clientId is not string (for a failure or because the custom // id generator function did no accept the connection) the connection // is disposed, exactly as it was not authorized. if (res && 'string' !== typeof res) { this.sysLogger.log('GameServer.handleConnectingClient: ' + 'generateClientId did not return a valid id for incoming ' + (this.ADMIN_SERVER ? 'admin' : 'player' ), 'error'); return GameServer.codes.INVALID_CLIENT_ID; } // Assign client id. clientId = res; } // Generate a new id if none was given. if (!clientId) clientId = this.registry.generateClientId(); // See if a match in the registry is found. clientObj = this.registry.getClient(clientId); // If not, generate a new unique object. if (!clientObj) { // Specify admin here to avoid missclassification. clientObj = this.registry.addClient(clientId, { admin: this.ADMIN_SERVER || false }); } // Decorate: the clientObj can be altered by a user-defined callback. if (this.decorateClientObj) { tmpId = clientObj.id; tmpSid = clientObj.sid; tmpType = clientObj.clientType; this.decorateClientObj(clientObj, { // For retro-compatibility. TODO: remove in future version. headers: handshake.headers, handshake: handshake, query: handshake.query, cookies: cookies, room: startingRoom, clientId: clientId, validSessionCookie: !invalidSessionCookie, socketId: socketId }); // Some properties cannot be changed. if (clientObj.id !== tmpId || clientObj.sid !== tmpSid || clientObj.admin !== this.ADMIN_SERVER || clientObj.clientType !== tmpType) { throw new Error('GameServer.onConnect: ' + 'decorateClientObj cannot alter properties: ' + 'id, sid, admin, clientType.'); } } // Check if it is a reconnection. if (this.enableReconnections) { if (clientObj.allowReconnect === false) { this.disposeUnauthorizedClient(socketId, socketObj); return false; } // Client must have connected at least once. if (clientObj.connected || clientObj.disconnected) { res = this.handleReconnectingClient(clientObj, socketObj, socketId, clearNode); // TODO: if reconnection fails should the client be kicked out? // If reconnection failed, it will be treated as a new connection. newConnection = res !== GameServer.codes.OPERATION_OK; } } // New connection. if (newConnection) { // Add new connection properties to clientObj. clientObj.admin = this.ADMIN_SERVER || false; clientObj.clientType = clientType; clientObj.sid = socketId; res = this.handleConnectingClient(clientObj, socketObj, startingRoom, clearNode); } // In case of failure, dispose of the client. if (res !== GameServer.codes.OPERATION_OK) { // Warns and disconnect client if auth failed. this.disposeUnauthorizedClient(socketId, socketObj); return false; } return true; }; /** * ### GameServer.handleConnectingClient * * Handles a client (supposedly) connecting for the first time to the channel * * @param {object} clientObj The client object * @param {Socket} socketObj The socket object (Direct or SIO) * @param {string} startingRoom Optional. The name of the room in which * the client is to be placed. Default: Waiting or Requirements room * @param {boolean} clearNode If TRUE, sends a msg to STOP current game, * immediately after a connection is established. Default: FALSE * * @return {number} A numeric code describing the outcome of the operation. * * @see GameServer.codes * @see GameServer.handleReconnectingClient * @see GameServer.registerClient */ GameServer.prototype.handleConnectingClient = function( clientObj, socketObj, startingRoom, clearNode) { var res; // If not startingRoom is provided, // put the client in the requirements or waiting room. if (!startingRoom) { if (this.ADMIN_SERVER) { startingRoom = this.channel.garageRoom.name; } else { // If there are multiple levels in the game, // gameInfo.requirements and .waitingRoom points // to the first level. if (this.channel.gameInfo.requirements && this.channel.gameInfo.requirements.enabled) { startingRoom = this.channel.requirementsRoom.name; } else { startingRoom = this.channel.waitingRoom.name; } } } // Register the client in the socket, mark connected, place in room. res = this.registerClient(clientObj, socketObj, startingRoom, clearNode); if (res === GameServer.codes.OPERATION_OK) { // Let each Admin and Player Server registering the new connection. this.sysLogger.log('channel ' + this.channel.name + ' ' + (this.ADMIN_SERVER ? 'admin' : 'player') + ' connected: ' + clientObj.id); this.emit('connecting', clientObj, startingRoom); } return res; }; /** * ### GameServer.handleReconnectingClient * * Handles a reconnecting client. * * @param {object} clientObj The client object * @param {Socket} socketObj The socket object (Direct or SIO) * @param {string} socketId The id of the socket connection * @param {boolean} clearNode If TRUE, sends a msg to STOP current game, * immediately after a connection is established. Default: FALSE * * @return {number} A numeric code describing the outcome of the operation. * * @see GameServer.codes * @see GameServer.handleConnectingClient * @see GameServer.registerClient */ GameServer.prototype.handleReconnectingClient = function(clientObj, socketObj, socketId, clearNode) { var sys, clientId, returningRoom, res; var gameMsg, globalLookup, oldInfo; clientId = clientObj.id; sys = this.sysLogger; // It can happen that when the client disconnected the previous time, // its disconnection was not registered by the server (can happen // with ajax). We do it here. if (!clientObj.disconnected) { sys.log('GameServer.handleReconnectingClient: Reconnecting ' + (this.ADMIN_SERVER ? 'admin' : 'player' ) + ' that ' + 'was not marked as disconnected: ' + clientId, 'warn'); // Mark disconnected and try to resume the connection. gameMsg = { to: clientId }; globalLookup = false; // TODO: The method needs a game msg: update it. oldInfo = this.socketManager.resolveClientAndSocket(gameMsg, globalLookup); if (!oldInfo.success) { // The client will be treated as a new connection, // and a warning will be sent. return GameServer.codes.ROOM_NOT_FOUND; } // Force disconnection of old socket. oldInfo.socket.disconnect(oldInfo.sid); } // Set the new socket id in clientObj. clientObj.sid = socketId; returningRoom = this.registry.getClientRoom(clientId); // The old room must be still existing. if (!this.channel.gameRooms[returningRoom]) { sys.log('GameServer.handleReconnectingClient: ' + 'Room no longer existing for re-connecting ' + (this.ADMIN_SERVER ? 'admin' : 'player' ) + ': ' + clientId, 'error'); this.socketManager.send(this.msg.create({ target: ngc.constants.target.ALERT, to: clientId, text: 'The game room you are looking for is not ' + 'existing any more. You will be redirected to ' + 'the initial room.' })); return GameServer.codes.ROOM_NOT_FOUND; } res = this.registerClient(clientObj, socketObj, returningRoom, clearNode); if (res === GameServer.codes.OPERATION_OK) { // Let Admin and Player Server handle the new connection. sys.log('channel ' + this.channel.name + ' ' + (this.ADMIN_SERVER ? 'admin' : 'player') + ' re-connected: ' + clientId); this.emit('re-connecting', clientObj, returningRoom); } return res; }; /** * ### GameServer.registerClient * * Registers a client with the socket manager, marks connected, and sends HI * * @param {object} clientObj The client object * @param {Socket} socketObj The socket object (Direct or SIO) * @param {string} room Optional. The name of the room in which * the client is to be placed. * @param {boolean} clearNode If TRUE, sends a msg to STOP current game, * immediately after a connection is established. Default: FALSE * * @return {number} A numeric code describing the outcome of the operation. * * @see GameServer.codes * @see GameServer.handleReconnectingClient * @see GameServer.registerClient */ GameServer.prototype.registerClient = function(clientObj, socketObj, room, clearNode) { let clientId = clientObj.id; let socketId = clientObj.sid; // Officially register the client in the socket manager. this.socketManager.registerClient(clientId, socketObj); if (!this.channel.placeClient(clientObj, room)) { return GameServer.codes.ROOM_NOT_FOUND; } // Mark client as connected in the registry. this.registry.markConnected(clientId); // Notify the client of its ID. this.welcomeClient(clientId, socketId, clearNode); // Connected time. clientObj.connectTime = new Date(); return GameServer.codes.OPERATION_OK; }; /** * ### GameServer.welcomeClient * * Sends a HI msg to the client, and logs its arrival * * @param {string} clientId The id of the connecting client * @param {string} socketId The socket id of the connecting client * @param {boolean} clearNode If TRUE, sends a msg to STOP current game, * immediately after a connection is established. Default: FALSE */ GameServer.prototype.welcomeClient = function(clientId, socketId, clearNode) { // TODO: not used for now. see if we need it later. // if (clearNode) { // this.socketManager.send(this.msg.create({ // target: ngc.constants.target.GAMECOMMAND, // to: clientId, // text: 'stop' // })); // } this.socketManager.send(this.msg.create({ target: 'HI', to: clientId, data: { player: { id: clientId, sid: socketId, admin: this.ADMIN_SERVER }, channel: { name: this.channel.name, isDefault: this.channel.defaultChannel ? true : undefined }, antiSpoofing: this.antiSpoofing && this.socketManager.isRemote(socketId) } })); }; /** * ### GameServer.disposeUnauthorizedClient * * Sends a REDIRECT message to the access denied page * * Cannot send ALERT because it gets destroyed by the REDIRECT. * * @param {string} socketObj The socket id of the connection * @param {string} socketObj The socket (IO, Direct) object * * @see GameServer.getAccessDeniedUrl * * TODO: add an error code in the query string. Need to adapt page as well */ GameServer.prototype.disposeUnauthorizedClient = function(socketId, socketObj) { var to, connStr; to = ngc.constants.UNAUTH_PLAYER; connStr = "Unauthorized client. Socket id: <" + socketId + ">"; this.sysLogger.log(connStr, 'warn'); // TODO: This could avoid updating any index at all when a new client // is inserted. However, there are problems of missing indexes to move // clients to a new room (e.g. requirements). // // If the client is being disposed immediately after a failed // // connection, we need to register it manually in the sid registry. // // This way, when it actually disconnects, no error is raised. // r = this.channel.registry.clients; // if (!r.sid.get(socketId)) r.sid._add(socketId, (r.db.length-1)); // We need to send an HI message in any case because otherwise // the client will discard the messages. socketObj.send(this.msg.create({ target: ngc.constants.target.HI, to: to, data: this.getAccessDeniedUrl(), text: 'redirect' }), socketId); }; /** * ### GameServer.authorization * * Sets the authorization function called on every new connection * * When called, the function receives two parameters: * * - the channel parameter * - an object literal with more information, such as cookies and other headers * * @param {function} cb The callback function */ GameServer.prototype.authorization = function(cb) { if ('function' !== typeof cb) { throw new TypeError('GameServer.authorization: cb must be ' + 'function. Found: ' + cb); } this.authCb = cb; }; /** * ### GameServer.clientIdGenerator * * Sets the function decorating client objects * * By default a client object contains the following keys: "id", * "sid", "admin", and "clientType". This function can add as many * other properties as needed. However, "id", "sid", and "admin" can * never be modified. * * The callback function receives two parameters: * * - the standard client object * - an object literal with more information, such as headers and cookies * * @param {function} cb The callback function */ GameServer.prototype.clientIdGenerator = function(cb) { if ('function' !== typeof cb) { throw new TypeError('GameServer.clientIdGenerator: cb must be ' + 'function. Found: ' + cb); } this.generateClientId = cb; }; /** * ### GameServer.clientObjDecorator * * Sets the function for decorating the client object * * The callback function receives two parameters: * * - the standard client object * - an object literal with more information, such as client ids, and cookies * * @param {function} cb The callback function */ GameServer.prototype.clientObjDecorator = function(cb) { if ('function' !== typeof cb) { throw new TypeError('GameServer.clientObjDecorator: cb must be ' + 'function. Found: ' + cb); } this.decorateClientObj = cb; }; /** * ### GameServer.getAccessDeniedUrl * * Returns the url for unauthorized access to the server. * * @return {string|null} The url to the access denied page, if defined */ GameServer.prototype.getAccessDeniedUrl = function() { return this.accessDeniedUrl; }; /** * ### GameServer.validateRecipient * * Validates the _to_ field of a game msg * * The original object is modified. The _to_ field will be adjusted according to * the permissions currently granted to the sender of the message. * * The syntattic validitity of the _GameMsg_ object should be checked before * invoking this method, which evaluates the semantic meaning of the _to_ * field. * * @param {GameMsg} gameMsg The message to validate * * @return {GameMsg|false} The validated/updated game msg, or FALSE, if invalid */ GameServer.prototype.validateRecipient = function(gameMsg) { var server, errStr, opts; var _name, _to; errStr = ''; opts = this.options; server = this.ADMIN_SERVER ? 'Admin' : 'Player'; if ('string' === typeof gameMsg.to) { if (gameMsg.to.trim() === '') { this.sysLogger.log(server + 'Server.validateRecipient: ' + 'msg.to is empty.', 'error'); return false; } // TODO: avoid cascading and use else if instead. if (gameMsg.to === 'ALL' && !opts.canSendTo.all) { errStr += 'ALL/'; gameMsg.to = 'CHANNEL'; } if (gameMsg.to === 'CHANNEL' && !opts.canSendTo.ownChannel) { errStr += 'CHANNEL/'; gameMsg.to = 'ROOM'; } if (gameMsg.to === 'ROOM' && !opts.canSendTo.ownRoom) { this.sysLogger.log(server + 'Server.validateRecipient: ' + 'sending to "' + errStr + 'ROOM" is not allowed.', 'error'); return false; } if ((gameMsg.to.lastIndexOf('CHANNEL_', 0) === 0)) { if (!opts.canSendTo.anyChannel) { this.sysLogger.log(server + 'Server.validateRecipient: ' + 'sending to "CHANNEL_" is not allowed.', 'error'); return false; } // Extract channel name from _to_ field. _name = gameMsg.to.substr(8); // Fetch channel object. _to = this.channel.servernode.channels[_name]; if (!_to) { this.sysLogger.log(server + 'Server.validateRecipient: ' + gameMsg.to + ' points to an unexisting ' + 'channel.', 'error'); return false; } // Encapsulate validated channel data in the message. gameMsg._originalTo = gameMsg.to; gameMsg._to = _to; gameMsg.to = 'CHANNEL_X'; } if ((gameMsg.to.lastIndexOf('ROOM_', 0) === 0)) { if (!opts.canSendTo.anyRoom) { this.sysLogger.log(server + 'Server.validateRecipient: ' + 'sending to "ROOM_" is not allowed.', 'error'); return false; } // Extract room id from _to_ field. _name = gameMsg.to.substr(5); // Fetch channel object. _to = this.channel.servernode.rooms[_name]; if (!_to) { this.sysLogger.log(server + 'Server.validateRecipient: ' + gameMsg.to + ' points to an unexisting ' + 'room.', 'error'); return false; } // Encapsulate validated channel data in the message. gameMsg._originalTo = gameMsg.to; gameMsg._to = _to; gameMsg.to = 'ROOM_X'; } // Otherwise it's either SERVER (always allowed) or a client ID, which // will be checked at a later point. } else if (Object.prototype.toString.call(gameMsg.to) === '[object Array]') { if (gameMsg.to.length > opts.maxMsgRecipients) { this.sysLogger.log(server + 'Server.validateRecipient: ' + 'number of recipients exceeds limit. ' + gameMsg.to.length + '>' + opts.maxMsgRecipients, 'error'); return false; } } else { this.sysLogger.log(server + 'Server.validateRecipient: ' + 'gameMsg.to is neither string nor array. Found: ' + gameMsg.to, 'error'); return false; } return gameMsg; }; /** * ### GameServer.decodeJWT * * Tries to decode a jwt token and catches the possible error * * @param {string} token The encrypted token * * @return {object|boolean} The decoded token, or FALSE on failure * * @see GameServer.channel.secret */ GameServer.prototype.decodeJWT = function(token) { try { return jwt.verify(token, this.channel.secret); } catch(e) { this.sysLogger.log((this.ADMIN_SERVER ? 'Admin' : 'Player') + 'Server: decoding jwt failed. Error: ' + e, 'error'); return false; } }; /** * ### GameServer.validateSender * * Validates the _from_ field of a game msg * * The original object is modified. The _from_ field remains unchanged, but * adds the room name of the sender under __roomName_, the name * of the channel under __channelName_, and the socket id under __sid_. * * The syntattic validitity of the _GameMsg_ object should be checked before * invoking this method, which evaluates only if the sender exists. * * @param {GameMsg} gameMsg The message to validate * * @return {GameMsg|false} The validated/updated game msg, or FALSE, if invalid */ GameServer.prototype.validateSender = function(gameMsg) { var server, errStr, opts; var _room; errStr = ''; opts = this.options; server = this.ADMIN_SERVER ? 'Admin' : 'Player'; if ('string' !== typeof gameMsg.from) { this.sysLogger.log(server + 'Server.validateSender: msg.from must be ' + 'string.', 'error'); return false; } _room = this.channel.registry.getClientRoom(gameMsg.from); if (!_room) { this.sysLogger.log(server + 'Server.validateSender: sender was not ' + 'found in any room: ' + gameMsg.toEvent() + ' - ' + gameMsg.from + '.', 'error'); return false; } gameMsg._roomName = _room; gameMsg._channelName = this.channel.name; gameMsg._sid = this.channel.registry.getClient(gameMsg.from).sid; return gameMsg; }; /** * ### GameServer.attachListeners * * Attaches listeners shared by both servers. */ GameServer.prototype.attachListeners = function() { var that = this, sys = this.sysLogger, action = ngc.constants.action, // say = action.SAY + '.', // set = action.SET + '.', get = action.GET + '.'; // #### get.LANG // It sends the object of language objects for the game back to the client. this.on(get + 'LANG', function(msg) { var room, roomName; var response, serverName; if (msg.to === 'SERVER') { // Get the room of the player to infer the game. roomName = msg._roomName || that.registry.getClientRoom(msg.from); room = that.channel.gameRooms[roomName]; if (!room) { serverName = that.ADMIN_SERVER ? 'Admin' : 'Player'; sys.log(serverName + '.on.get.LANG: Could not determine room ' + 'of sender: ' + msg.from, 'error'); return; } response = that.msg.create({ target: 'LANG', from: 'SERVER', to: msg.from, data: that.servernode.info.games[room.gameName].languages }); that.socketManager.send2client(response); } }); }; // ## Helper methods /** * ### parseCookies * * Parses the cookie string and returns a cookies object * * @param {string} cookieString The cookie string * * @return {object} An object containing a map of cookie-values * * Kudos to: * http://commandlinefanatic.com/cgi-bin/showarticle.cgi?article=art013 */ function parseCookies(cookieString) { return cookieString.split(';') .map(cookieMap) .reduce(cookieReduce, {}); } function cookieMap(x) { return x.trim().split('='); } function cookieReduce(a, b) { a[ b[ 0 ] ] = b[ 1 ]; return a; }
var SetOperatorNode = require("../SetOperatorNode"); module.exports = (function () { var o = function (graph) { SetOperatorNode.apply(this, arguments); var that = this, superDrawFunction = that.draw; this.styleClass("complementof") .type("owl:complementOf"); this.draw = function (element) { superDrawFunction(element); var symbol = element.append("g").classed("embedded", true); symbol.append("circle") .attr("class", "symbol") .classed("fineline", true) .attr("r", 10); symbol.append("path") .attr("class", "nofill") .attr("d", "m -7,-1.5 12,0 0,6") .attr("transform", "scale(.5)"); symbol.attr("transform", "translate(-" + (that.radius() - 15) / 100 + ",-" + (that.radius() - 15) / 100 + ")"); that.postDrawActions(); }; }; o.prototype = Object.create(SetOperatorNode.prototype); o.prototype.constructor = o; return o; }());
'use strict'; module.exports = { env: { es6: true, }, parserOptions: { ecmaFeatures: { experimentalObjectRestSpread: true, }, ecmaVersion: 2017, sourceType: 'module', }, rules: { // require braces around arrow function bodies 'arrow-body-style': 'error', // require parentheses around arrow function arguments 'arrow-parens': ['error', 'as-needed'], // enforce consistent spacing before and after the arrow in arrow functions 'arrow-spacing': 'error', // require super() calls in constructors 'constructor-super': 'error', // enforce consistent spacing around * operators in generator functions 'generator-star-spacing': ['error', 'after'], // disallow reassigning class members 'no-class-assign': 'error', // disallow arrow functions where they could be confused with comparisons 'no-confusing-arrow': ['error', { allowParens: true }], // disallow reassigning const variables 'no-const-assign': 'error', // disallow duplicate class members 'no-dupe-class-members': 'error', // disallow duplicate module imports 'no-duplicate-imports': 'off', // disallow new operators with the Symbol object 'no-new-symbol': 'error', // disallow specified modules when loaded by import 'no-restricted-imports': 'off', // disallow this/super before calling super() in constructors 'no-this-before-super': 'error', // disallow unnecessary computed property keys in object literals 'no-useless-computed-key': 'error', // disallow unnecessary constructors 'no-useless-constructor': 'error', // disallow renaming import, export, and destructured assignments to the same name 'no-useless-rename': 'error', // require let or const instead of var 'no-var': 'error', // require or disallow method and property shorthand syntax for object literals 'object-shorthand': ['error', 'always', { avoidQuotes: true }], // require arrow functions as callbacks 'prefer-arrow-callback': ['error', { allowNamedFunctions: true }], // require const declarations for variables that are never reassigned after declared 'prefer-const': 'error', // require destructuring from arrays and/or objects 'prefer-destructuring': ['error', { AssignmentExpression: { array: true, object: true, }, VariableDeclarator: { array: false, object: true, }, }, { enforceForRenamedProperties: false, }], // disallow parseInt() in favor of binary, octal, and hexadecimal literals 'prefer-numeric-literals': 'error', // require rest parameters instead of arguments 'prefer-rest-params': 'error', // require spread operators instead of .apply() 'prefer-spread': 'error', // require template literals instead of string concatenation 'prefer-template': 'error', // require generator functions to contain yield 'require-yield': 'error', // enforce spacing between rest and spread operators and their expressions 'rest-spread-spacing': 'error', // enforce sorted import declarations within modules 'sort-imports': 'off', // require symbol descriptions 'symbol-description': 'error', // require or disallow spacing around embedded expressions of template strings 'template-curly-spacing': 'error', // require or disallow spacing around the * in yield* expressions 'yield-star-spacing': ['error', 'after'], }, };