<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/* eslint-disable no-console */

'use strict'
const MailParser = require('mailparser').MailParser
const simplesmtp = require('simplesmtp')
const P = require('../lib/promise')

const config = require('../config').getProperties()

const TEMPLATES_WITH_NO_CODE = new Set([
  'passwordResetEmail'
])

// SMTP half

var users = {}

function emailName(emailAddress) {
  var utf8Address = Buffer.from(emailAddress, 'binary').toString('utf-8')
  return utf8Address.split('@')[0]
}

module.exports = (printLogs) => {
  printLogs = printLogs || process.env.MAIL_HELPER_LOGS
  const console = printLogs ? global.console : {
    log() {},
    error() {}
  }
  return new P((resolve, reject) => {
    const smtp = simplesmtp.createSimpleServer(
      {
        SMTPBanner: 'FXATEST'
      },
      function (req) {
        var mp = new MailParser({ defaultCharset: 'utf-8' })
        mp.on('end',
          function (mail) {
            var link = mail.headers['x-link']
            var rc = mail.headers['x-recovery-code']
            var rul = mail.headers['x-report-signin-link']
            var uc = mail.headers['x-unblock-code']
            var vc = mail.headers['x-verify-code']
            var template = mail.headers['x-template-name']
            var name = emailName(mail.headers.to)
            if (vc) {
              console.log('\x1B[32m', link, '\x1B[39m')
            }
            else if (rc) {
              console.log('\x1B[34m', link, '\x1B[39m')
            }
            else if (uc) {
              console.log('\x1B[36mUnblock code:', uc, '\x1B[39m')
              console.log('\x1B[36mReport link:', rul, '\x1B[39m')
            }
            else if (TEMPLATES_WITH_NO_CODE.has(template)) {
              console.log(`Notification email: ${template}`)
            }
            else {
              console.error('\x1B[31mNo verify code match\x1B[39m')
              console.error(mail)
            }
            if (users[name]) {
              users[name].push(mail)
            } else {
              users[name] = [mail]
            }
          }
        )
        req.pipe(mp)
        req.accept()
      }
    )
    smtp.listen(config.smtp.port, config.smtp.host)

    // HTTP half

    var hapi = require('hapi')
    var api = new hapi.Server()
    api.connection({
      host: config.smtp.api.host,
      port: config.smtp.api.port
    })

    function loop(email, cb) {
      var mail = users[email]
      if (! mail) {
        return setTimeout(loop.bind(null, email, cb), 50)
      }
      cb(mail)
    }

    api.route(
      [
        {
          method: 'GET',
          path: '/mail/{email}',
          handler: function (request, reply) {
            loop(
              decodeURIComponent(request.params.email),
              function (emailData) {
                reply(emailData)
              }
            )
          }
        },
        {
          method: 'DELETE',
          path: '/mail/{email}',
          handler: function (request, reply) {
            delete users[decodeURIComponent(request.params.email)]
            reply()
          }
        }
      ]
    )

    api.start(function () {
      console.log('mail_helper started...')

      resolve({
        close() {
          return new P((resolve, reject) => {
            let smtpClosed = false
            let apiClosed = false
            smtp.server.end(() => {
              smtpClosed = true
              if (apiClosed) {
                resolve()
              }
            })
            api.stop(() => {
              apiClosed = true
              if (smtpClosed) {
                resolve()
              }
            })
          })
        }
      })
    })
  })
}
<commit_msg>chore(test): fix mail_helper to run if require.main is mail_helper (#1763)<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/* eslint-disable no-console */

'use strict'
const MailParser = require('mailparser').MailParser
const simplesmtp = require('simplesmtp')
const P = require('../lib/promise')

const config = require('../config').getProperties()

const TEMPLATES_WITH_NO_CODE = new Set([
  'passwordResetEmail'
])

// SMTP half

var users = {}

function emailName(emailAddress) {
  var utf8Address = Buffer.from(emailAddress, 'binary').toString('utf-8')
  return utf8Address.split('@')[0]
}

module.exports = (printLogs) => {
  printLogs = printLogs || process.env.MAIL_HELPER_LOGS
  const console = printLogs ? global.console : {
    log() {},
    error() {}
  }
  return new P((resolve, reject) => {
    const smtp = simplesmtp.createSimpleServer(
      {
        SMTPBanner: 'FXATEST'
      },
      function (req) {
        var mp = new MailParser({ defaultCharset: 'utf-8' })
        mp.on('end',
          function (mail) {
            var link = mail.headers['x-link']
            var rc = mail.headers['x-recovery-code']
            var rul = mail.headers['x-report-signin-link']
            var uc = mail.headers['x-unblock-code']
            var vc = mail.headers['x-verify-code']
            var template = mail.headers['x-template-name']
            var name = emailName(mail.headers.to)
            if (vc) {
              console.log('\x1B[32m', link, '\x1B[39m')
            }
            else if (rc) {
              console.log('\x1B[34m', link, '\x1B[39m')
            }
            else if (uc) {
              console.log('\x1B[36mUnblock code:', uc, '\x1B[39m')
              console.log('\x1B[36mReport link:', rul, '\x1B[39m')
            }
            else if (TEMPLATES_WITH_NO_CODE.has(template)) {
              console.log(`Notification email: ${template}`)
            }
            else {
              console.error('\x1B[31mNo verify code match\x1B[39m')
              console.error(mail)
            }
            if (users[name]) {
              users[name].push(mail)
            } else {
              users[name] = [mail]
            }
          }
        )
        req.pipe(mp)
        req.accept()
      }
    )
    smtp.listen(config.smtp.port, config.smtp.host)

    // HTTP half

    var hapi = require('hapi')
    var api = new hapi.Server()
    api.connection({
      host: config.smtp.api.host,
      port: config.smtp.api.port
    })

    function loop(email, cb) {
      var mail = users[email]
      if (! mail) {
        return setTimeout(loop.bind(null, email, cb), 50)
      }
      cb(mail)
    }

    api.route(
      [
        {
          method: 'GET',
          path: '/mail/{email}',
          handler: function (request, reply) {
            loop(
              decodeURIComponent(request.params.email),
              function (emailData) {
                reply(emailData)
              }
            )
          }
        },
        {
          method: 'DELETE',
          path: '/mail/{email}',
          handler: function (request, reply) {
            delete users[decodeURIComponent(request.params.email)]
            reply()
          }
        }
      ]
    )

    api.start(function () {
      console.log('mail_helper started...')

      resolve({
        close() {
          return new P((resolve, reject) => {
            let smtpClosed = false
            let apiClosed = false
            smtp.server.end(() => {
              smtpClosed = true
              if (apiClosed) {
                resolve()
              }
            })
            api.stop(() => {
              apiClosed = true
              if (smtpClosed) {
                resolve()
              }
            })
          })
        }
      })
    })
  })
}

if (require.main === module) {
  module.exports(true)
}
<|endoftext|>


<commit_before>import unrender from 'unrender';
import eventify from 'ngraph.events';
import appEvents from '../service/appEvents.js';

export default sceneController;

sceneController.attach = attachScene;
sceneController.detach = detachScene;

function sceneController(container) {
  var renderer, positions, graphModel;
  appEvents.on('positions', setPositions);
  appEvents.on('graphModel', setGraphModel);

  var api = {
    destroy: destroy
  };

  eventify(api);
  return api;

  function setGraphModel(_graphModel) {
    graphModel = _graphModel;
  }

  function setPositions(_positions) {
    positions = _positions;
    if (!renderer) renderer = unrender(container);
    renderer.particles(positions);

    var hitTest = renderer.hitTest();
    hitTest.on('over', handleOver);
  }

  function handleOver(indexes) {
    renderer.highlight(indexes, 0xff0000);
    api.fire('over', getHighlightModel(indexes));
  }

  function getHighlightModel(indexes) {
    return {
      total: indexes.length,
      snippet: indexes.slice(0, 20).map(toInfo),
      indexes: indexes
    };
  }

  function toInfo(x) {
    if (!graphModel) return x;
    return graphModel.getNodeInfo(x/3);
  }

  function destroy() {
    renderer.destroy();
    appEvents.off('positions', setPositions);
    renderer = null;
  }

  return api;
}

function detachScene(dom) {
  if (!dom.__sceneController) return;
  dom.__sceneController.destroy();
}

function attachScene(dom) {
  dom.__sceneController = sceneController(dom);
  return dom.__sceneController;
}
<commit_msg>Using only one element nearest to ray<commit_after>import unrender from 'unrender';
import eventify from 'ngraph.events';
import appEvents from '../service/appEvents.js';

export default sceneController;

sceneController.attach = attachScene;
sceneController.detach = detachScene;

function sceneController(container) {
  var renderer, positions, graphModel;
  appEvents.on('positions', setPositions);
  appEvents.on('graphModel', setGraphModel);

  var api = {
    destroy: destroy
  };

  eventify(api);
  return api;

  function setGraphModel(_graphModel) {
    graphModel = _graphModel;
  }

  function setPositions(_positions) {
    positions = _positions;
    if (!renderer) renderer = unrender(container);
    renderer.particles(positions);

    var hitTest = renderer.hitTest();
    hitTest.on('over', handleOver);
  }

  function handleOver(indexes, ray) {
    var nearestIndex = nearest(30, ray);
    renderer.highlight(nearestIndex, 0xff0000);
    api.fire('over', getHighlightModel(nearestIndex));

    function nearest(maxRadius, ray) {
      if (indexes.length === 0) return indexes;

      indexes.sort(byProximityToRay);

      var candidate = indexes[0];
      if (getDistance(candidate) < maxRadius) {
        return [candidate];
      }

      return [];

      function byProximityToRay(x, y) {
        var distX = getDistance(x), distY = getDistance(y);
        return distX - distY;
      }

      function getDistance(idx) {
        var x = positions[idx];
        var y = positions[idx + 1];
        var z = positions[idx + 2];
        var dx = ray.direction.x * (x - ray.origin.x);
        var dy = ray.direction.y * (y - ray.origin.y);
        var dz = ray.direction.z * (z - ray.origin.z);
        var directionDistance = dx + dy + dz;
        var vx = ray.direction.x * directionDistance + ray.origin.x;
        var vy = ray.direction.y * directionDistance + ray.origin.y;
        var vz = ray.direction.z * directionDistance + ray.origin.z;
        return (vx - x) * (vx - x) + (vy - y) * (vy - y) + (vz - z) * (vz - z);
      }
    }
  }

  function getHighlightModel(indexes) {
    return {
      total: indexes.length,
      snippet: indexes.slice(0, 20).map(toInfo),
      indexes: indexes
    };
  }

  function toInfo(x) {
    if (!graphModel) return x;
    return graphModel.getNodeInfo(x/3);
  }

  function destroy() {
    renderer.destroy();
    appEvents.off('positions', setPositions);
    renderer = null;
  }

  return api;
}

function detachScene(dom) {
  if (!dom.__sceneController) return;
  dom.__sceneController.destroy();
}

function attachScene(dom) {
  dom.__sceneController = sceneController(dom);
  return dom.__sceneController;
}
<|endoftext|>


<commit_before>

var all, one, itertools, functools, operator, array, sort, n;

itertools = require( "aureooms-js-itertools" );
functools = require( "aureooms-js-functools" );
operator = require( "aureooms-js-operator" );
array = require( "aureooms-js-array" );
sort = require( "aureooms-js-sort" );

one = function ( bdp, __f__, a, i, j, di, dj, expected ) {

	var out, i, outputordering;

	++n;

	out = bdp( __f__, a, i, j, di, dj, [] );

	outputordering = sort.lexicographical( sort.lexicographical( sort.increasing ) );

	array.sort( outputordering, out );
	array.sort( outputordering, expected );

	deepEqual( out, expected, n );

};

all = function ( name, algo ) {

	n = 0;

	test( name, function ( ) {

		var f, __f__;

		f = function ( i, a, b ) {
			return a[i] - b[i];
		};

		__f__ = functools.curry( f, 3 );

		one( algo, __f__, [], 0, 0, 1, 1, [] );

		one( algo, __f__, [ [0] ], 0, 1, 1, 1, [] );

		one( algo, __f__, [ [1] ], 0, 1, 1, 1, [] );

		one( algo, __f__, [ [0], [0], [0], [0] ], 0, 4, 1, 1, [] );

		one( algo, __f__, [ [1], [1], [1], [1] ], 0, 4, 1, 1, [] );

		one(
			algo,
			__f__,
			[ [0], [0], [1], [1] ],
			0, 4,
			1, 1,
			[
				[ [1], [0] ],
				[ [1], [0] ],
				[ [1], [0] ],
				[ [1], [0] ]
			]
		);

		one(
			algo,
			__f__,
			[ [0, 0.5], [0, 1], [1, 1], [1, 0.5] ],
			0, 4,
			1, 2,
			[
				[ [1, 1], [0, 1] ],
				[ [1, 1], [0, 0.5] ],
				[ [1, 0.5], [0, 0.5] ]
			]
		);

	});

};

[
	[
		"algo.__bdpdc__",
		algo.__bdpdc__(
			sort.__quickselect__( sort.hoare ), // select,
			functools.curry( operator.eq, 2 ),  // __eq__,
			functools.curry( operator.ne, 2 ),  // __ne__,
			operator.itemgetter( 0 ),           // color,
			array.split,                        // split,
			array.swap                          // swap
		)
	],

	[
		"algo.__bdpdn2__",
		algo.__bdpdn2__(
			operator.itemgetter( 0 ),           // color,
			array.split                         // split
		)
	]

].forEach( functools.partial( functools.star, null, [all] ) );
<commit_msg>complete test for bdp<commit_after>

var all, one, itertools, functools, operator, array, sort, n, random, shuffle;

itertools = require( "aureooms-js-itertools" );
functools = require( "aureooms-js-functools" );
operator = require( "aureooms-js-operator" );
random = require( "aureooms-js-random" );
array = require( "aureooms-js-array" );
sort = require( "aureooms-js-sort" );

shuffle = random.__shuffle__( random.__sample__( random.randint ) );

one = function ( bdp, __f__, a, i, j, di, dj, expected ) {

	var out, i, outputordering;

	++n;

	shuffle( a, i, j );

	out = bdp( __f__, a, i, j, di, dj, [] );

	outputordering = sort.lexicographical( sort.lexicographical( sort.increasing ) );

	array.sort( outputordering, out );
	array.sort( outputordering, expected );

	deepEqual( out, expected, n );

};

all = function ( name, algo ) {

	n = 0;

	test( name, function ( ) {

		var f, __f__;

		f = function ( i, a, b ) {
			return a[i] - b[i];
		};

		__f__ = functools.curry( f, 3 );

		one( algo, __f__, [], 0, 0, 1, 1, [] );

		one( algo, __f__, [ [0] ], 0, 1, 1, 1, [] );

		one( algo, __f__, [ [1] ], 0, 1, 1, 1, [] );

		one( algo, __f__, [ [0], [0], [0], [0] ], 0, 4, 1, 1, [] );

		one( algo, __f__, [ [1], [1], [1], [1] ], 0, 4, 1, 1, [] );

		one(
			algo,
			__f__,
			[ [0], [0], [1], [1] ],
			0, 4,
			1, 1,
			[
				[ [1], [0] ],
				[ [1], [0] ],
				[ [1], [0] ],
				[ [1], [0] ]
			]
		);

		one(
			algo,
			__f__,
			[ [0, 0.5], [0, 1], [1, 1], [1, 0.5] ],
			0, 4,
			1, 2,
			[
				[ [1, 1], [0, 1] ],
				[ [1, 1], [0, 0.5] ],
				[ [1, 0.5], [0, 0.5] ]
			]
		);

		one(
			algo,
			__f__,
			[ [0, 0.5, 1], [0, 1, 2], [1, 1, 1], [1, 0.5, 2] ],
			0, 4,
			1, 3,
			[
				[ [1, 1, 1], [0, 0.5, 1] ],
				[ [1, 0.5, 2], [0, 0.5, 1] ]
			]
		);

		one(
			algo,
			__f__,
			[ [0, 0.5, 1], [0, 1, 2], [1, 1, 1], [1, 0.5, 2], [1, 1, 1], [1, 0.5, 2] ],
			0, 6,
			1, 3,
			[
				[ [1, 1, 1], [0, 0.5, 1] ],
				[ [1, 0.5, 2], [0, 0.5, 1] ],
				[ [1, 1, 1], [0, 0.5, 1] ],
				[ [1, 0.5, 2], [0, 0.5, 1] ]
			]
		);

		one(
			algo,
			__f__,
			[ [0, 0.5, 1], [0, 1, 2], [1, 1, 1], [1, 0.5, 2], [1, 1, 3], [1, 1, 2] ],
			0, 6,
			1, 3,
			[
				[ [1, 1, 1], [0, 0.5, 1] ],
				[ [1, 0.5, 2], [0, 0.5, 1] ],
				[ [1, 1, 3], [0, 0.5, 1] ],
				[ [1, 1, 2], [0, 0.5, 1] ],
				[ [1, 1, 3], [0, 1, 2] ],
				[ [1, 1, 2], [0, 1, 2] ]
			]
		);

		one(
			algo,
			__f__,
			[ [0, 0.5, 1], [0, 1, 2], [1, 1, 1], [1, 0.5, 2], [1, 1, 3], [0, 105, 1], [0, 1, 20], [1, 1, 2] ],
			0, 8,
			1, 3,
			[
				[ [1, 1, 1], [0, 0.5, 1] ],
				[ [1, 0.5, 2], [0, 0.5, 1] ],
				[ [1, 1, 3], [0, 0.5, 1] ],
				[ [1, 1, 2], [0, 0.5, 1] ],
				[ [1, 1, 3], [0, 1, 2] ],
				[ [1, 1, 2], [0, 1, 2] ]
			]
		);

		one(
			algo,
			__f__,
			[ [0, 0.5, 1], [0, 1, 2], [0, 105, 1], [0, 1, 20], [1, 105, 20], [1, 105, 20], [1, 106, 20] ],
			0, 7,
			1, 3,
			[
				[ [1, 105, 20], [0, 0.5, 1] ],
				[ [1, 105, 20], [0, 1, 2] ],
				[ [1, 105, 20], [0, 105, 1] ],
				[ [1, 105, 20], [0, 1, 20] ],
				[ [1, 105, 20], [0, 0.5, 1] ],
				[ [1, 105, 20], [0, 1, 2] ],
				[ [1, 105, 20], [0, 105, 1] ],
				[ [1, 105, 20], [0, 1, 20] ],
				[ [1, 106, 20], [0, 0.5, 1] ],
				[ [1, 106, 20], [0, 1, 2] ],
				[ [1, 106, 20], [0, 105, 1] ],
				[ [1, 106, 20], [0, 1, 20] ]
			]
		);

		one(
			algo,
			__f__,
			[ [0, 0.5, 1], [0, 1, 2], [0, 105, 1], [0, 1, 20], [1, 105, 20], [1, 105, 20], [1, 106, 20], [0, 107, 1], [0, 107, 1] ],
			0, 9,
			1, 3,
			[
				[ [1, 105, 20], [0, 0.5, 1] ],
				[ [1, 105, 20], [0, 1, 2] ],
				[ [1, 105, 20], [0, 105, 1] ],
				[ [1, 105, 20], [0, 1, 20] ],
				[ [1, 105, 20], [0, 0.5, 1] ],
				[ [1, 105, 20], [0, 1, 2] ],
				[ [1, 105, 20], [0, 105, 1] ],
				[ [1, 105, 20], [0, 1, 20] ],
				[ [1, 106, 20], [0, 0.5, 1] ],
				[ [1, 106, 20], [0, 1, 2] ],
				[ [1, 106, 20], [0, 105, 1] ],
				[ [1, 106, 20], [0, 1, 20] ]
			]
		);

	});

};

[
	[
		"algo.__bdpdc__",
		algo.__bdpdc__(
			sort.__quickselect__( sort.partition ), // select,
			functools.curry( function ( i, v, a ) { // __eq__,
				return + ( v === a[i] );
			}, 3 ),
			functools.curry( function ( i, v, a ) { // __ne__,
				return + ( v !== a[i] );
			}, 3 ),
			operator.itemgetter( 0 ),               // color,
			array.split,                            // split,
			array.swap                              // swap
		)
	],

	[
		"algo.__bdpdn2__",
		algo.__bdpdn2__(
			operator.itemgetter( 0 ),           // color,
			array.split                         // split
		)
	]

].forEach( functools.partial( functools.star, null, [all] ) );
<|endoftext|>


<commit_before>/*eslint no-console:0 */
const request = require('request');
const monk = require('monk');
const fs = require('fs');
const mkdirp = require('mkdirp');
const path = require('path');

const CardService = require('../services/CardService.js');

function apiRequest(path) {
    const apiUrl = 'https://api.fiveringsdb.com/';

    return new Promise((resolve, reject) => {
        request.get(apiUrl + path, function(error, res, body) {
            if(error) {
                return reject(error);
            }

            resolve(JSON.parse(body));
        });
    });
}

function fetchImage(urlPath, id, imagePath, timeout) {
    setTimeout(function() {
        console.log('Downloading image for ' + id);
        var url = 'https://fiveringsdb.com/' + urlPath + id + '.jpg';
        request(url).pipe(fs.createWriteStream(imagePath));
    }, timeout);
}

let db = monk('mongodb://127.0.0.1:27017/throneteki');
let cardService = new CardService(db);

let fetchCards = apiRequest('cards')
    .then(cards => cardService.replaceCards(cards))
    .then(cards => {
        console.info(cards.length + ' cards fetched');

        let imageDir = path.join(__dirname, '..', '..', 'public', 'img', 'cards');
        mkdirp(imageDir);

        var i = 0;

        cards.forEach(function(card) {
            var imagePath = path.join(imageDir, card.id + '.jpg');
            //var imagePack = card.pack_cards[0].pack.id;
            //var imagesrc = 'static/cards/' + imagePack + '/';

            if(card.imagesrc && !fs.existsSync(imagePath)) {
                fetchImage(card.imagesrc, card.code, imagePath, i++ * 200);
            }
        });

        return cards;
    })
    .catch(() => {
        console.error('Unable to fetch cards');
    });

let fetchPacks = apiRequest('packs')
    .then(packs => cardService.replacePacks(packs))
    .then(packs => {
        console.info(packs.length + ' packs fetched');
    })
    .catch(() => {
        console.error('Unable to fetch packs');
    });

Promise.all([fetchCards, fetchPacks])
    .then(() => db.close())
    .catch(() => db.close());

<commit_msg>Fix fetchdata after merge<commit_after>/*eslint no-console:0 */
const request = require('request');
const monk = require('monk');
const fs = require('fs');
const mkdirp = require('mkdirp');
const path = require('path');

const CardService = require('../services/CardService.js');

function apiRequest(path) {
    const apiUrl = 'https://api.fiveringsdb.com/';

    return new Promise((resolve, reject) => {
        request.get(apiUrl + path, function(error, res, body) {
            if(error) {
                return reject(error);
            }

            resolve(JSON.parse(body));
        });
    });
}

function fetchImage(url, id, imagePath, timeout) {
    setTimeout(function() {
        console.log('Downloading image for ' + id);
        request(url).pipe(fs.createWriteStream(imagePath));
    }, timeout);
}

let db = monk('mongodb://127.0.0.1:27017/ringteki');
let cardService = new CardService(db);

let fetchCards = apiRequest('cards')
    .then(cards => cardService.replaceCards(cards.records))
    .then(cards => {
        console.info(cards.length + ' cards fetched');

        let imageDir = path.join(__dirname, '..', '..', 'public', 'img', 'cards');
        mkdirp(imageDir);

        var i = 0;

        cards.forEach(function(card) {
            var imagePath = path.join(imageDir, card.id + '.jpg');
            var imagesrc = card.pack_cards[0].image_url;

            if(imagesrc && !fs.existsSync(imagePath)) {
                fetchImage(imagesrc, card.id, imagePath, i++ * 200);
            }
        });

        return cards;
    })
    .catch(() => {
        console.error('Unable to fetch cards');
    });

let fetchPacks = apiRequest('packs')
    .then(packs => cardService.replacePacks(packs.records))
    .then(packs => {
        console.info(packs.length + ' packs fetched');
    })
    .catch(() => {
        console.error('Unable to fetch packs');
    });

Promise.all([fetchCards, fetchPacks])
    .then(() => db.close())
    .catch(() => db.close());

<|endoftext|>


<commit_before>var jsdom = require('../../lib/jsdom');
var path = require('path');

function again() {
  jsdom.env('test', [
    path.resolve(__dirname, '../jquery-fixtures/jquery-1.6.2.js'
  ], function(errors, window) {
    window.close();
    setTimeout(again, 0);
  });
}

again();
<commit_msg>Fix syntax by adding missing parenthesis.<commit_after>var jsdom = require('../../lib/jsdom');
var path = require('path');

function again() {
  jsdom.env('test', [
    path.resolve(__dirname, '../jquery-fixtures/jquery-1.6.2.js')
  ], function(errors, window) {
    window.close();
    setTimeout(again, 0);
  });
}

again();
<|endoftext|>


<commit_before>// documention for the Class name Curve for github doc
class Curve {

}
var getPath = function(startX, startY, endX, endY) {

    // M
    var AX = startX;
    var AY = startY;

    // L
    var BX = Math.abs(endX - startX) * 0.05 + startX;
    var BY = startY;

    // C
    var CX = startX + Math.abs(endX - startX) * curveFactor;
    var CY = startY;
    var DX = endX - Math.abs(endX - startX) * curveFactor;
    var DY = endY;
    var EX = - Math.abs(endX - startX) * 0.05 + endX;
    var EY = endY;

    // L
    var FX = endX;
    var FY = endY;

    // setting up the path string
    var path  = 'M' + AX + ',' + AY;
    path += ' L' + BX + ',' + BY;
    path += ' C' + CX + ',' + CY + ' ' + DX + ',' + DY + ' ' + EX + ',' + EY;
    path += ' L' + FX + ',' + FY;

    return path;

}

var addCurve = function(pathId,positions) {

    var path = getPath(positions[0],positions[1],positions[2],positions[3]);

    var html = '<path id="'+pathId+'" d="'+path+'" stroke="blue" stroke-width="2" fill="none"></path>';

    appendSVG(html);
}

var updateCurve = function(pathId,positions) {

    var path = getPath(positions[0],positions[1],positions[2],positions[3]);

    $('#'+pathId).attr("d",path);

}

var drawCurve = function(pathId,side,startX,startY,endX,endY) {

    var position = (side == 'right') ? [startX,startY,endX,endY] : [endX,endY,startX,startY]

    if($('#'+pathId).length) {

        // path already exists
        updateCurve(pathId,position);

    } else {

        // path doesn't exist
        addCurve(pathId,position);
    }

}

var snapOffCurve = function() {

}

var appendSVG = function(html) {

    $('svg').append(html);
    $("svg").html($("svg").html());

}

var removeCurve = function(id) {

    $('#'+id).remove();

}
<commit_msg>minimal modifications to make Linking class work. Refactoring needed!<commit_after>let curveFactor = 0.4;

let getPath = function(startX, startY, endX, endY) {

    // M
    var AX = startX;
    var AY = startY;

    // L
    var BX = Math.abs(endX - startX) * 0.05 + startX;
    var BY = startY;

    // C
    var CX = startX + Math.abs(endX - startX) * curveFactor;
    var CY = startY;
    var DX = endX - Math.abs(endX - startX) * curveFactor;
    var DY = endY;
    var EX = - Math.abs(endX - startX) * 0.05 + endX;
    var EY = endY;

    // L
    var FX = endX;
    var FY = endY;

    // setting up the path string
    var path  = 'M' + AX + ',' + AY;
    path += ' L' + BX + ',' + BY;
    path += ' C' + CX + ',' + CY + ' ' + DX + ',' + DY + ' ' + EX + ',' + EY;
    path += ' L' + FX + ',' + FY;

    return path;

}

var addCurve = function(pathId,positions) {

    var path = getPath(positions[0],positions[1],positions[2],positions[3]);

    const color = (lk.type == 'data') ? 'blue' : 'white';
    const weight = (lk.type == 'data') ? '2' : '3';

    var html = '<path id="'+pathId+'" d="'+path+'" stroke="'+color+'" stroke-width="'+weight+'" fill="none"></path>';

    appendSVG(html);
}

var updateCurve = function(pathId,positions) {

    var path = getPath(positions[0],positions[1],positions[2],positions[3]);

    $('#'+pathId).attr("d",path);

}

var drawCurve = function(id, side, a, b) {

    let position = (side == 'right')
        ? [a[0], a[1], b[0], b[1]]
        : [b[0], b[1], a[0], a[1]];

    if(path.exist(id)) {

        updateCurve(id, position);

    } else {

        addCurve(id, position);

    }

}

var appendSVG = function(html) {

    $('svg').append(html);
    $("svg").html($("svg").html());

}

var removeCurve = function(id) {

    $('#'+id).remove();

}
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Sat Sep 13 2014 18:48:29 GMT+0300 (EEST)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '../',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'bower_components/angular/angular.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'bower_components/angular-scroll/angular-scroll.js',
      '.tmp/snapscroll.css',
      '.tmp/snapscroll.js',
      'test/spec/**/*.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    plugins: [
      // 'karma-firefox-launcher',
      // 'karma-chrome-launcher',
      'karma-jasmine',
      'karma-phantomjs-launcher'
    ],

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: [
      // 'Chrome',
      // 'Firefox',
      'PhantomJS'
    ],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<commit_msg>as attribute: removed obsolete reference to angular-scroll js in karma.conf<commit_after>// Karma configuration
// Generated on Sat Sep 13 2014 18:48:29 GMT+0300 (EEST)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '../',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      'bower_components/angular/angular.js',
      'bower_components/angular-mocks/angular-mocks.js',
      '.tmp/snapscroll.css',
      '.tmp/snapscroll.js',
      'test/spec/**/*.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    plugins: [
      // 'karma-firefox-launcher',
      // 'karma-chrome-launcher',
      'karma-jasmine',
      'karma-phantomjs-launcher'
    ],

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: [
      // 'Chrome',
      // 'Firefox',
      'PhantomJS'
    ],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
<|endoftext|>


<commit_before>
document.getElementById("id_logic_version").innerHTML = "Logic version: 2019.11.15.4";
document.getElementById("id_request").addEventListener("click", request_permission);
//-----------------------------------
function ok_f(result)
{
	if (result == "granted")
		window.addEventListener("deviceorientation", on_device_orientation);
	else
		alert("permission not granted");
}
//-----------------------------------
function not_ok_f(e)
{
	alert(e);
}
//-----------------------------------
if (typeof(DeviceOrientationEvent.requestPermission) === "function"){
}
else{
	window.addEventListener("deviceorientation", on_device_orientation);
}
//-----------------------------------
window.addEventListener("devicemotion", on_device_motion);

function request_permission()
{
	DeviceOrientationEvent.requestPermission().then(ok_f).catch(not_ok_f);
}

//--------------------------------
function on_device_orientation(e)
{
	document.getElementById("id_alpha").innerHTML = e.alpha;
	document.getElementById("id_beta").innerHTML = e.beta;
	document.getElementById("id_gamma").innerHTML = e.gamma;

	var canvas = document.getElementById("id_canvas");
	var context = canvas.getContext("2d");

	context.clearRect(0, 0, canvas.width, canvas.height);
	var R = 10;
	context.beginPath();
	context.arc(canvas.width / 2 + e.gamma / 90 *(canvas.width / 2-R),
				canvas.height / 2 + e.beta / 90 * (canvas.height / 2 - R),
				R, 0, 2 * Math.PI);
	context.stroke();

}
//--------------------------------
function on_device_motion(e)
{
	var acc_z = e.accelerationIncludingGravity.z;
	var acc_x = e.accelerationIncludingGravity.x;
	var acc_y = e.accelerationIncludingGravity.y;

	document.getElementById("id_acc_z").innerHTML = Math.round(acc_z * 100) / 100;
	document.getElementById("id_acc_x").innerHTML = Math.round(acc_x * 100) / 100;
	document.getElementById("id_acc_y").innerHTML = Math.round(acc_y * 100) / 100;

	document.getElementById("id_rot_x").innerHTML = -Math.round(Math.atan(acc_x / acc_z)* 180 / Math.PI * 100) / 100;
	document.getElementById("id_rot_y").innerHTML = Math.round(Math.atan(acc_y / acc_z)* 180 / Math.PI * 100) / 100;
}
//--------------------------------<commit_msg>Update orientation.js<commit_after>
document.getElementById("id_logic_version").innerHTML = "Logic version: 2019.11.15.5";
document.getElementById("id_request").addEventListener("click", request_permission);
//-----------------------------------
function ok_f(result)
{
	if (result == "granted")
		window.addEventListener("deviceorientation", on_device_orientation);
	else
		alert("permission not granted");
}
//-----------------------------------
function not_ok_f(e)
{
	alert(e);
}
//-----------------------------------
if (typeof(DeviceOrientationEvent.requestPermission) == "function"){
}
else{
	window.addEventListener("deviceorientation", on_device_orientation);
}
//-----------------------------------
window.addEventListener("devicemotion", on_device_motion);

function request_permission()
{
	DeviceOrientationEvent.requestPermission().then(ok_f).catch(not_ok_f);
}

//--------------------------------
function on_device_orientation(e)
{
	document.getElementById("id_alpha").innerHTML = e.alpha;
	document.getElementById("id_beta").innerHTML = e.beta;
	document.getElementById("id_gamma").innerHTML = e.gamma;

	var canvas = document.getElementById("id_canvas");
	var context = canvas.getContext("2d");

	context.clearRect(0, 0, canvas.width, canvas.height);
	var R = 10;
	context.beginPath();
	context.arc(canvas.width / 2 + e.gamma / 90 *(canvas.width / 2-R),
				canvas.height / 2 + e.beta / 90 * (canvas.height / 2 - R),
				R, 0, 2 * Math.PI);
	context.stroke();

}
//--------------------------------
function on_device_motion(e)
{
	var acc_z = e.accelerationIncludingGravity.z;
	var acc_x = e.accelerationIncludingGravity.x;
	var acc_y = e.accelerationIncludingGravity.y;

	document.getElementById("id_acc_z").innerHTML = Math.round(acc_z * 100) / 100;
	document.getElementById("id_acc_x").innerHTML = Math.round(acc_x * 100) / 100;
	document.getElementById("id_acc_y").innerHTML = Math.round(acc_y * 100) / 100;

	document.getElementById("id_rot_x").innerHTML = -Math.round(Math.atan(acc_x / acc_z)* 180 / Math.PI * 100) / 100;
	document.getElementById("id_rot_y").innerHTML = Math.round(Math.atan(acc_y / acc_z)* 180 / Math.PI * 100) / 100;
}
//--------------------------------<|endoftext|>


<commit_before>/*
 * drawing.js -- manipulating <canvas > elements for great justice.
 * requires jquery
 **/

var courier = courier || {};

courier.drawing = (function() { // begin courier namespace

    function Field(width, height, jq) {
      this.jq = jq;
      this.actual_width = jq[0].width;
      this.actual_height = jq[0].width;
      this.width = width;
      this.height = height;
      this.ctx = jq[0].getContext('2d');
    }
    Field.prototype.withTransform = function(cb) {
      var ctx = this.ctx;
      ctx.save();
      // we have:
      // lower left is 0, height
      // upper right is width, 0
      // we want:
      // lower left corner to be 0, 0
      // upper right corner to be 1000, 1000
      ctx.translate(0, this.actual_height);
      ctx.scale((this.actual_width/this.width), -(this.actual_height/this.height));
      cb(ctx);
      ctx.restore();
    };
    Field.prototype.drawRobot = function(rob) {
      // Renders a robot at location with rotation and a certain color.
      // Not really a proper robot object; more like a dictionary that the
      // server returns. See FieldObject.field_info()
      var ctx = this.ctx;
      ctx.save();
          ctx.translate(rob.location[0], rob.location[1]);
          ctx.rotate(-rob.rotation);
          ctx.beginPath();
          ctx.moveTo(0, 25);
          ctx.lineTo(15, -15);
          ctx.lineTo(0, -10);
          ctx.lineTo(-15, -15);
          ctx.fill();
          ctx.rotate(-rob.turret_rot);
          ctx.beginPath();
          ctx.moveTo(0,0);
          ctx.lineTo(0, 30);
          ctx.stroke();
          if (rob.scan_mode == "robots") {
            // Scanning for robots
            ctx.beginPath();
            ctx.lineTo(0, 0);
            ctx.arc(0, 0,
                rob.scanrange, // radius
                3.14/2-rob.scan_width, // left
                3.14/2+rob.scan_width, // right
                false); // anticlockwise?
            ctx.lineTo(0, 0);
            ctx.stroke();
          } else if (rob.scan_mode == "wall") {
            // Sonar ping for wall
            for (var i = 5; i>0; i--) {
              ctx.beginPath();
              ctx.arc(0, 0, rob.scanrange*i/5, 3.14/2+0.2, 3.14/2-0.2, true);
              ctx.stroke();
            }
          }
          ctx.rotate(rob.turret_rot);
      ctx.restore();
    };
    Field.prototype.render = function(field) {
      // This gets run at every field update.
      // field: {"width": 1024, heigth: 1025,
      //    "objects": [ # see FieldObject.field_info() in fieldobject.py, robot.py
      //           {'type': 'robot', 'location': [23, 35], ...}
      //        ]
      // }
      var self = this;
      var ctx = this.jq[0].getContext('2d');

      ctx.clearRect(0,0,this.width,this.height);
      this.withTransform(
        function() {
          for (var i=0,l=field.objects.length; i<l; i++) {
            switch (field.objects[i].type) {
              case 'robot':
                self.drawRobot(field.objects[i]);
                break;
              case 'object':
                // default
                break;
            }
          }
        });
    };

    function followField(m, jq) {
      // We'll set up our field so that when M updates, the <canvas /> in jq
      // will too.
      var f = new Field(m.field_size[0], m.field_size[1], jq);
      var fdat;
      m.onFieldUpdate(
        function(field_dat) {
          fdat = field_dat;
        });
      window.setInterval(
          function() {
            if (typeof fdat != 'undefined') {
              f.render(fdat);
            }
          }, 1000*m.speed);
    }

    return {
      followField: followField
    };
})(); // end courier namespace
<commit_msg>Souped up the animation<commit_after>/*
 * drawing.js -- manipulating <canvas > elements for great justice.
 * requires jquery
 **/

var courier = courier || {};

courier.drawing = (function() { // begin courier namespace

    function Field(width, height, jq) {
      this.jq = jq;
      this.actual_width = jq[0].width;
      this.actual_height = jq[0].width;
      this.width = width;
      this.height = height;
      this.ctx = jq[0].getContext('2d');
    }
    Field.prototype.withTransform = function(cb) {
      var ctx = this.ctx;
      ctx.save();
      // we have:
      // lower left is 0, height
      // upper right is width, 0
      // we want:
      // lower left corner to be 0, 0
      // upper right corner to be 1000, 1000
      ctx.translate(0, this.actual_height);
      ctx.scale((this.actual_width/this.width), -(this.actual_height/this.height));
      cb(ctx);
      ctx.restore();
    };
    Field.prototype.drawRobot = function(rob) {
      // Renders a robot at location with rotation and a certain color.
      // Not really a proper robot object; more like a dictionary that the
      // server returns. See FieldObject.field_info()
      var ctx = this.ctx;
      ctx.save();
          ctx.translate(rob.location[0], rob.location[1]);
          ctx.rotate(-rob.rotation);
          ctx.beginPath();
          ctx.moveTo(0, 25);
          ctx.lineTo(15, -15);
          ctx.lineTo(0, -10);
          ctx.lineTo(-15, -15);
          ctx.fill();
          ctx.rotate(-rob.turret_rot);
          ctx.beginPath();
          ctx.moveTo(0,0);
          ctx.lineTo(0, 30);
          ctx.stroke();
          if (rob.scan_mode == "robots") {
            // Scanning for robots
            ctx.beginPath();
            ctx.lineTo(0, 0);
            ctx.arc(0, 0,
                rob.scanrange, // radius
                3.14/2-rob.scan_width, // left
                3.14/2+rob.scan_width, // right
                false); // anticlockwise?
            ctx.lineTo(0, 0);
            ctx.stroke();
          } else if (rob.scan_mode == "wall") {
            // Sonar ping for wall
            for (var i = 5,r; i>0; i--) {
              r = Math.random()/2 + 0.5;
              ctx.beginPath();
              ctx.arc(0, 0, rob.scanrange*i/5*r, 3.14/2+0.2, 3.14/2-0.2, true);
              ctx.stroke();
            }
          }
          ctx.rotate(rob.turret_rot);
      ctx.restore();
    };
    Field.prototype.render = function(field) {
      // This gets run at every field update.
      // field: {"width": 1024, heigth: 1025,
      //    "objects": [ # see FieldObject.field_info() in fieldobject.py, robot.py
      //           {'type': 'robot', 'location': [23, 35], ...}
      //        ]
      // }
      var self = this;
      var ctx = this.jq[0].getContext('2d');

      ctx.clearRect(0,0,this.width,this.height);
      this.withTransform(
        function() {
          for (var i=0,l=field.objects.length; i<l; i++) {
            switch (field.objects[i].type) {
              case 'robot':
                self.drawRobot(field.objects[i]);
                break;
              case 'object':
                // default
                break;
            }
          }
        });
    };

    function followField(m, jq) {
      // We'll set up our field so that when M updates, the <canvas /> in jq
      // will too.
      var f = new Field(m.field_size[0], m.field_size[1], jq);
      var fdat;
      m.onFieldUpdate(
        function(field_dat) {
          fdat = field_dat;
        });
      window.setInterval(
          function() {
            if (typeof fdat != 'undefined') {
              f.render(fdat);
            }
          }, 1000*m.speed);
    }

    return {
      followField: followField
    };
})(); // end courier namespace
<|endoftext|>


<commit_before>'use strict';

var istanbul = require('browserify-istanbul');
var isparta = require('isparta');

module.exports = function(config) {

  config.set({

    basePath: '../',
    frameworks: ['jasmine', 'browserify'],
    preprocessors: {
      'app/js/**/*.js': ['browserify', 'babel', 'coverage']
    },
    browsers: ['Chrome'],
    reporters: ['progress', 'coverage'],

    autoWatch: true,

    browserify: {
      debug: true,
      transform: [
        'partialify',
        'bulkify',
        istanbul({
          instrumenter: isparta,
          ignore: ['**/node_modules/**', '**/test/**']
        })
      ],
    },

    proxies: {
      '/': 'http://localhost:9876/'
    },

    urlRoot: '/__karma__/',

    files: [
      // 3rd-party resources
      'node_modules/angular/angular.min.js',
      'node_modules/angular-mocks/angular-mocks.js',

      // app-specific code
      'app/js/main.js',

      // test files
      'test/unit/**/*.js'
    ]

  });

};<commit_msg>Removed unused comma<commit_after>'use strict';

var istanbul = require('browserify-istanbul');
var isparta = require('isparta');

module.exports = function(config) {

  config.set({

    basePath: '../',
    frameworks: ['jasmine', 'browserify'],
    preprocessors: {
      'app/js/**/*.js': ['browserify', 'babel', 'coverage']
    },
    browsers: ['Chrome'],
    reporters: ['progress', 'coverage'],

    autoWatch: true,

    browserify: {
      debug: true,
      transform: [
        'partialify',
        'bulkify',
        istanbul({
          instrumenter: isparta,
          ignore: ['**/node_modules/**', '**/test/**']
        })
      ]
    },

    proxies: {
      '/': 'http://localhost:9876/'
    },

    urlRoot: '/__karma__/',

    files: [
      // 3rd-party resources
      'node_modules/angular/angular.min.js',
      'node_modules/angular-mocks/angular-mocks.js',

      // app-specific code
      'app/js/main.js',

      // test files
      'test/unit/**/*.js'
    ]

  });

};
<|endoftext|>


<commit_before>var textarea = document.getElementById("queryarea");
var cm = CodeMirror.fromTextArea(textarea, {
mode:  "application/sparql-query",
matchBrackets: true,
lineNumbers: true
});
cm.refresh();

var submit_query = function(query) {
  var html = "";
  var begin = moment();
  console.log(query);
  $("#errortext").hide();
  $.post("/api/queryclassdot", query, function(data) {

      var end = moment();
      var duration = moment.duration(end - begin);
      $("#elapsed").text(duration.milliseconds() + " ms");
      console.log(data);

      d3.select("#mynetwork svg").remove();

      var graph = DotParser.parse(data);
      console.log(graph);
      var width=900;
      var height=500;
      var svg = d3.select("#mynetwork").append("svg")
      .attr("width", width)
      .attr("height", height);

      var edges = [];
      var nodes = [];
      var nodenames = [];
      var childs = graph.children;
      for (var i=0; i<childs.length; i++) {
        var e = childs[i];
        if (e.edge_list == null) {
          var n = e.node_id.id;
          if (nodenames.indexOf(n) == -1) {
            nodenames.push(n);
            nodes.push({name: n, color: e.attr_list[0].eq});
          } else {
            nodes[nodenames.indexOf(n)].color = e.attr_list[0].eq;
          }
          continue;
        }
        var n1 = e.edge_list[0].id;
        var n2 = e.edge_list[1].id;
        if (nodenames.indexOf(n1) == -1) {
          nodenames.push(n1);
          nodes.push({name: n1});
        }
        if (nodenames.indexOf(n2) == -1) {
          nodenames.push(n2);
          nodes.push({name: n2});
        }

        edges.push({
          source: nodenames.indexOf(n1),
          target: nodenames.indexOf(n2),
          name: e.attr_list[0].eq,
          left: false,
          right: true,
          weight: 1
        });
      }

      console.log(nodes);
      console.log(edges);

      var force = d3.layout.force()
        .gravity(.05)
        .distance(200)
        .charge(-600)
        .size([width, height]);
      force
        .nodes(nodes)
        .links(edges)
        .start();

      var node = svg.selectAll(".node")
        .data(nodes)
        .enter().append("g")
        .attr("class", "node")
        .style("fill", function(d) {
            console.log(d);
            if (d.color != null) {
            return d.color;
            } else {
            return "#333";
            }
            })
      .call(force.drag);

      node.append("circle")
        .attr("r","10");

      node.append("text")
        .attr("dx", 12)
        .attr("dy", ".35em")
        .text(function(d) { return d.name; });

      // build the arrow.
      svg.append("svg:defs").selectAll("marker")
        .data(["end"])      // Different link/path types can be defined here
        .enter().append("svg:marker")    // This section adds in the arrows
        .attr("id", String)
        .attr("viewBox", "0 -5 10 10")
        .attr("refX", 15)
        .attr("refY", -1.5)
        .attr("markerWidth", 6)
        .attr("markerHeight", 6)
        .attr("orient", "auto")
        .append("svg:path")
        .attr("d", "M0,-5L10,0L0,5");

      // add the links and the arrows
      var path = svg.append("svg:g").selectAll("path")
        .data(edges)
        .enter().append("svg:path")
        .attr("class", "link")
        .attr("marker-end", "url(#end)")
        .attr("id", function(d,i) { return 'edge'+i;});

      var edgelabels = svg.selectAll(".edgelabel")
        .data(edges)
        .enter()
        .append('text')
        .style("pointer-events", "none")
        .attr({'class':'edgelabel',
            'id':function(d,i){return 'edgelabel'+i},
            'dx':50,
            'dy':-5,
            'font-size':18,
            'fill':'#aaa'});
      edgelabels.append('textPath')
        .attr('xlink:href',function(d,i) {return '#edge'+i})
        .style("pointer-events", "none")
        .text(function(d,i){return d.name})

      force.on("tick", function() {

          node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
          // handles to link and node element groups
          path.attr('d', function(d) {
              var deltaX = d.target.x - d.source.x,
              deltaY = d.target.y - d.source.y,
              dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY),
              normX = deltaX / dist,
              normY = deltaY / dist,
              sourcePadding = 5;
              targetPadding = 5;
              sourceX = d.source.x + (sourcePadding * normX),
              sourceY = d.source.y + (sourcePadding * normY),
              targetX = d.target.x - (targetPadding * normX),
              targetY = d.target.y - (targetPadding * normY);
              return 'M' + sourceX + ',' + sourceY + 'L' + targetX + ',' + targetY;
              });

          edgelabels.attr('transform',function(d,i){
              if (d.target.x<d.source.x){
                bbox = this.getBBox();
                rx = bbox.x+bbox.width/2;
                ry = bbox.y+bbox.height/2;
                return 'rotate(180 '+rx+' '+ry+')';
               } else {
                return 'rotate(0)';
               }
          });
      });

  }).fail(function(e) {
    $("#errortext").show();
    $("#errortext > p").text(e.responseText);
    });
}

// init collapsible parts
$('.collapsible').collapsible();

$('.button-collapse').sideNav({
menuWidth: 350, // Default is 240
}
);

// https://davidwalsh.name/javascript-debounce-function
function debounce(func, wait, immediate) {
  var timeout;
  return function() {
    var context = this, args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
};

var postponed_eval = debounce(function() {
    submit_query(cm.getValue())
    }, 500);

cm.on("change", postponed_eval);

// run once
var querytext = $("#queryarea").val();
submit_query(querytext);

$("#query_vavselect").click(function(event) {
    cm.setValue("SELECT ?vav WHERE {\n\t?vav rdf:type brick:VAV .\n};");
    cm.setSize("100%", Math.max(300, cm.lineCount()*25));
    event.preventDefault();
    });
$("#query_tempselect").click(function(event) {
    cm.setValue("SELECT ?sensor ?room\nWHERE {\n\t?sensor rdf:type/rdfs:subClassOf* brick:Zone_Temperature_Sensor .\n\t?room rdf:type brick:Room .\n\t?vav rdf:type brick:VAV .\n\t?zone rdf:type brick:HVAC_Zone .\n\n\t?vav bf:feeds+ ?zone .\n\t?zone bf:hasPart ?room .\n\t{\n\t\t?sensor bf:isPointOf ?vav .\n\t\tOR\n\t\t?sensor bf:isPointOf ?room . \n\t}\n};");
    cm.setSize("100%", Math.max(300, cm.lineCount()*25));
    cm.refresh();
    event.preventDefault();
    });
$("#query_vavcmd").click(function(event) {
    cm.setValue("SELECT ?vlv_cmd ?vav\nWHERE {\n\t{\n\t\t?vlv_cmd rdf:type brick:Reheat_Valve_Command .\n\t\tOR\n\t\t?vlv_cmd rdf:type brick:Cooling_Valve_Command .\n\t}\n\t?vav rdf:type brick:VAV .\n\t?vav bf:hasPoint+ ?vlv_cmd .\n};");
    cm.setSize("100%", Math.max(300, cm.lineCount()*25));
    event.preventDefault();
    });
$("#query_floors").click(function(event) {
    cm.setValue("SELECT ?floor ?room ?zone\nWHERE {\n\t?floor rdf:type brick:Floor .\n\t?room rdf:type brick:Room .\n\t?zone rdf:type brick:HVAC_Zone .\n\t?room bf:isPartOf+ ?floor .\n\t?room bf:isPartOf+ ?zone .\n};");
    cm.setSize("100%", Math.max(300, cm.lineCount()*25));
    event.preventDefault();
    });
<commit_msg>be more repulsive!<commit_after>var textarea = document.getElementById("queryarea");
var cm = CodeMirror.fromTextArea(textarea, {
mode:  "application/sparql-query",
matchBrackets: true,
lineNumbers: true
});
cm.refresh();

var submit_query = function(query) {
  var html = "";
  var begin = moment();
  console.log(query);
  $("#errortext").hide();
  $.post("/api/queryclassdot", query, function(data) {

      var end = moment();
      var duration = moment.duration(end - begin);
      $("#elapsed").text(duration.milliseconds() + " ms");
      console.log(data);

      d3.select("#mynetwork svg").remove();

      var graph = DotParser.parse(data);
      console.log(graph);
      var width=900;
      var height=500;
      var svg = d3.select("#mynetwork").append("svg")
      .attr("width", width)
      .attr("height", height);

      var edges = [];
      var nodes = [];
      var nodenames = [];
      var childs = graph.children;
      for (var i=0; i<childs.length; i++) {
        var e = childs[i];
        if (e.edge_list == null) {
          var n = e.node_id.id;
          if (nodenames.indexOf(n) == -1) {
            nodenames.push(n);
            nodes.push({name: n, color: e.attr_list[0].eq});
          } else {
            nodes[nodenames.indexOf(n)].color = e.attr_list[0].eq;
          }
          continue;
        }
        var n1 = e.edge_list[0].id;
        var n2 = e.edge_list[1].id;
        if (nodenames.indexOf(n1) == -1) {
          nodenames.push(n1);
          nodes.push({name: n1});
        }
        if (nodenames.indexOf(n2) == -1) {
          nodenames.push(n2);
          nodes.push({name: n2});
        }

        edges.push({
          source: nodenames.indexOf(n1),
          target: nodenames.indexOf(n2),
          name: e.attr_list[0].eq,
          left: false,
          right: true,
          weight: 1
        });
      }

      console.log(nodes);
      console.log(edges);

      var force = d3.layout.force()
        .gravity(.05)
        .distance(250)
        .charge(-1000)
        .size([width, height]);
      force
        .nodes(nodes)
        .links(edges)
        .start();

      var node = svg.selectAll(".node")
        .data(nodes)
        .enter().append("g")
        .attr("class", "node")
        .style("fill", function(d) {
            console.log(d);
            if (d.color != null) {
            return d.color;
            } else {
            return "#333";
            }
            })
      .call(force.drag);

      node.append("circle")
        .attr("r","10");

      node.append("text")
        .attr("dx", 12)
        .attr("dy", ".35em")
        .text(function(d) { return d.name; });

      // build the arrow.
      svg.append("svg:defs").selectAll("marker")
        .data(["end"])      // Different link/path types can be defined here
        .enter().append("svg:marker")    // This section adds in the arrows
        .attr("id", String)
        .attr("viewBox", "0 -5 10 10")
        .attr("refX", 15)
        .attr("refY", -1.5)
        .attr("markerWidth", 6)
        .attr("markerHeight", 6)
        .attr("orient", "auto")
        .append("svg:path")
        .attr("d", "M0,-5L10,0L0,5");

      // add the links and the arrows
      var path = svg.append("svg:g").selectAll("path")
        .data(edges)
        .enter().append("svg:path")
        .attr("class", "link")
        .attr("marker-end", "url(#end)")
        .attr("id", function(d,i) { return 'edge'+i;});

      var edgelabels = svg.selectAll(".edgelabel")
        .data(edges)
        .enter()
        .append('text')
        .style("pointer-events", "none")
        .attr({'class':'edgelabel',
            'id':function(d,i){return 'edgelabel'+i},
            'dx':50,
            'dy':-5,
            'font-size':18,
            'fill':'#aaa'});
      edgelabels.append('textPath')
        .attr('xlink:href',function(d,i) {return '#edge'+i})
        .style("pointer-events", "none")
        .text(function(d,i){return d.name})

      force.on("tick", function() {

          node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
          // handles to link and node element groups
          path.attr('d', function(d) {
              var deltaX = d.target.x - d.source.x,
              deltaY = d.target.y - d.source.y,
              dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY),
              normX = deltaX / dist,
              normY = deltaY / dist,
              sourcePadding = 5;
              targetPadding = 5;
              sourceX = d.source.x + (sourcePadding * normX),
              sourceY = d.source.y + (sourcePadding * normY),
              targetX = d.target.x - (targetPadding * normX),
              targetY = d.target.y - (targetPadding * normY);
              return 'M' + sourceX + ',' + sourceY + 'L' + targetX + ',' + targetY;
              });

          edgelabels.attr('transform',function(d,i){
              if (d.target.x<d.source.x){
                bbox = this.getBBox();
                rx = bbox.x+bbox.width/2;
                ry = bbox.y+bbox.height/2;
                return 'rotate(180 '+rx+' '+ry+')';
               } else {
                return 'rotate(0)';
               }
          });
      });

  }).fail(function(e) {
    $("#errortext").show();
    $("#errortext > p").text(e.responseText);
    });
}

// init collapsible parts
$('.collapsible').collapsible();

$('.button-collapse').sideNav({
menuWidth: 350, // Default is 240
}
);

// https://davidwalsh.name/javascript-debounce-function
function debounce(func, wait, immediate) {
  var timeout;
  return function() {
    var context = this, args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
};

var postponed_eval = debounce(function() {
    submit_query(cm.getValue())
    }, 500);

cm.on("change", postponed_eval);

// run once
var querytext = $("#queryarea").val();
submit_query(querytext);

$("#query_vavselect").click(function(event) {
    cm.setValue("SELECT ?vav WHERE {\n\t?vav rdf:type brick:VAV .\n};");
    cm.setSize("100%", Math.max(300, cm.lineCount()*25));
    event.preventDefault();
    });
$("#query_tempselect").click(function(event) {
    cm.setValue("SELECT ?sensor ?room\nWHERE {\n\t?sensor rdf:type/rdfs:subClassOf* brick:Zone_Temperature_Sensor .\n\t?room rdf:type brick:Room .\n\t?vav rdf:type brick:VAV .\n\t?zone rdf:type brick:HVAC_Zone .\n\n\t?vav bf:feeds+ ?zone .\n\t?zone bf:hasPart ?room .\n\t{\n\t\t?sensor bf:isPointOf ?vav .\n\t\tOR\n\t\t?sensor bf:isPointOf ?room . \n\t}\n};");
    cm.setSize("100%", Math.max(300, cm.lineCount()*25));
    cm.refresh();
    event.preventDefault();
    });
$("#query_vavcmd").click(function(event) {
    cm.setValue("SELECT ?vlv_cmd ?vav\nWHERE {\n\t{\n\t\t?vlv_cmd rdf:type brick:Reheat_Valve_Command .\n\t\tOR\n\t\t?vlv_cmd rdf:type brick:Cooling_Valve_Command .\n\t}\n\t?vav rdf:type brick:VAV .\n\t?vav bf:hasPoint+ ?vlv_cmd .\n};");
    cm.setSize("100%", Math.max(300, cm.lineCount()*25));
    event.preventDefault();
    });
$("#query_floors").click(function(event) {
    cm.setValue("SELECT ?floor ?room ?zone\nWHERE {\n\t?floor rdf:type brick:Floor .\n\t?room rdf:type brick:Room .\n\t?zone rdf:type brick:HVAC_Zone .\n\t?room bf:isPartOf+ ?floor .\n\t?room bf:isPartOf+ ?zone .\n};");
    cm.setSize("100%", Math.max(300, cm.lineCount()*25));
    event.preventDefault();
    });
<|endoftext|>


<commit_before>basePath = '../';

files = [
  JASMINE,
  JASMINE_ADAPTER,
  'https://maps.googleapis.com/maps/api/js?sensor=false',
  'http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js',
  'test/lib/angular/angular.js',
  'test/lib/angular/angular-mocks.js',
  'src/module.js',
  'src/directives/*.js',
  'src/services/*.js',
  'src/controllers/*.js',
  'test/unit/**/*.js'
];

autoWatch = true;
singleRun = false;
browsers = ['Firefox', 'PhantomJS'];
reportSlowerThan = 500;

preprocessors = {
  'src/**/*.js': 'coverage'
};

reporters = ['progress', 'coverage'];

coverageReporter = {
  type : 'html',
  dir : 'test/coverage/'
};

<commit_msg>Tired of issues with Firefox disconnecting.<commit_after>basePath = '../';

files = [
  JASMINE,
  JASMINE_ADAPTER,
  'https://maps.googleapis.com/maps/api/js?sensor=false',
  'http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js',
  'test/lib/angular/angular.js',
  'test/lib/angular/angular-mocks.js',
  'src/module.js',
  'src/directives/*.js',
  'src/services/*.js',
  'src/controllers/*.js',
  'test/unit/**/*.js'
];

autoWatch = true;
singleRun = false;
browsers = ['PhantomJS'];
reportSlowerThan = 500;

preprocessors = {
  'src/**/*.js': 'coverage'
};

reporters = ['progress', 'coverage'];

coverageReporter = {
  type : 'html',
  dir : 'test/coverage/'
};

<|endoftext|>


<commit_before>var m3u8   = require('../parser'),
    sinon  = require('sinon'),
    should = require('should');

describe('parser', function() {
  it('should error if not valid M3U first line', function(done) {
    var parser = getParser();

    parser.on('error', function(error) {
      error.message.should.include('Non-valid M3U file. First line: ');
      done();
    });
    parser.write('NOT VALID\n');
  });

  describe('#parseLine', function() {
    it('should call known tags', function() {
      var parser = getParser();
      var mock   = sinon.mock(parser);
      mock.expects('EXT-X-MEDIA').once().returns(45);

      parser.parseLine('#EXT-X-MEDIA:GROUP-ID="600k", LANGUAGE="eng"');
      mock.verify();
    });

    it('should set data on m3u on unknown tags', function() {
      var parser = getParser();

      parser.parseLine('#THIS-IS-A-TAG:some value');
      parser.m3u.get('THIS-IS-A-TAG').should.eql('some value');
    });
  });

  describe('#addItem', function() {
    it('should make currentItem the added item', function() {
      var parser = getParser();

      var item = new m3u8.M3U.PlaylistItem;
      parser.addItem(item);
      parser.currentItem.should.eql(item);
    });
  });

  describe('#EXTINF', function() {
    it('should create a new Playlist item', function() {
      var parser = getParser();

      parser.EXTINF('4.5,some title');
      parser.currentItem.constructor.name.should.eql('PlaylistItem');
      parser.currentItem.get('duration').should.eql(4.5);
      parser.currentItem.get('title').should.eql('some title');
    });
  });

  describe('#EXT-X-BYTERANGE', function() {
    it('should set byteRange on currentItem', function() {
      var parser = getParser();

      parser.EXTINF('4.5,');
      parser['EXT-X-BYTERANGE']('45@90');
      parser.currentItem.get('byteRange').should.eql('45@90');
    });
  });

  describe('#EXT-X-STREAM-INF', function() {
    it('should create a new Stream item', function() {
      var parser = getParser();

      parser['EXT-X-STREAM-INF']('NAME="I am a stream!"');
      parser.currentItem.constructor.name.should.eql('StreamItem');
      parser.currentItem.get('name').should.eql('I am a stream!');
    });
  });

  describe('#EXT-X-I-FRAME-STREAM-INF', function() {
    it('should create a new Iframe Stream item', function() {
      var parser = getParser();

      parser['EXT-X-I-FRAME-STREAM-INF']('NAME="I am an iframe stream!"');
      parser.currentItem.constructor.name.should.eql('IframeStreamItem');
      parser.currentItem.get('name').should.eql('I am an iframe stream!');
    });
  });

  describe('#EXT-X-MEDIA-INF', function() {
    it('should create a new Media item', function() {
      var parser = getParser();

      parser['EXT-X-MEDIA']('NAME="I am a media item!"');
      parser.currentItem.constructor.name.should.eql('MediaItem');
      parser.currentItem.get('name').should.eql('I am a media item!');
    });
  });

  describe('#parseAttributes', function() {
    it('should return an array of key-values', function() {
      var parser = getParser();

      var keyValues = parser.parseAttributes(
        'KEY="I, am a value",RESOLUTION=640x360,FORCED=NO'
      );
      keyValues[0].key.should.eql('KEY');
      keyValues[0].value.should.eql('"I, am a value"');
      keyValues[2].value.should.eql('NO');
    });
  });
});

function getParser() {
  var parser = m3u8.createStream();

  return parser;
}
<commit_msg>add test for parseLine split only on first colon<commit_after>var m3u8   = require('../parser'),
    sinon  = require('sinon'),
    should = require('should');

describe('parser', function() {
  it('should error if not valid M3U first line', function(done) {
    var parser = getParser();

    parser.on('error', function(error) {
      error.message.should.include('Non-valid M3U file. First line: ');
      done();
    });
    parser.write('NOT VALID\n');
  });

  describe('#parseLine', function() {
    it('should call known tags', function() {
      var parser = getParser();
      var mock   = sinon.mock(parser);
      mock.expects('EXT-X-MEDIA').once().returns(45);

      parser.parseLine('#EXT-X-MEDIA:GROUP-ID="600k", LANGUAGE="eng"');
      mock.verify();
    });

    it('should set data on m3u on unknown tags', function() {
      var parser = getParser();

      parser.parseLine('#THIS-IS-A-TAG:some value');
      parser.m3u.get('THIS-IS-A-TAG').should.eql('some value');
    });

    it('should split on first colon only', function() {
      var parser = getParser();

      parser.parseLine('#THIS-IS-A-TAG:http://www.ted.com');
      parser.m3u.get('THIS-IS-A-TAG').should.eql('http://www.ted.com');
    });
  });

  describe('#addItem', function() {
    it('should make currentItem the added item', function() {
      var parser = getParser();

      var item = new m3u8.M3U.PlaylistItem;
      parser.addItem(item);
      parser.currentItem.should.eql(item);
    });
  });

  describe('#EXTINF', function() {
    it('should create a new Playlist item', function() {
      var parser = getParser();

      parser.EXTINF('4.5,some title');
      parser.currentItem.constructor.name.should.eql('PlaylistItem');
      parser.currentItem.get('duration').should.eql(4.5);
      parser.currentItem.get('title').should.eql('some title');
    });
  });

  describe('#EXT-X-BYTERANGE', function() {
    it('should set byteRange on currentItem', function() {
      var parser = getParser();

      parser.EXTINF('4.5,');
      parser['EXT-X-BYTERANGE']('45@90');
      parser.currentItem.get('byteRange').should.eql('45@90');
    });
  });

  describe('#EXT-X-STREAM-INF', function() {
    it('should create a new Stream item', function() {
      var parser = getParser();

      parser['EXT-X-STREAM-INF']('NAME="I am a stream!"');
      parser.currentItem.constructor.name.should.eql('StreamItem');
      parser.currentItem.get('name').should.eql('I am a stream!');
    });
  });

  describe('#EXT-X-I-FRAME-STREAM-INF', function() {
    it('should create a new Iframe Stream item', function() {
      var parser = getParser();

      parser['EXT-X-I-FRAME-STREAM-INF']('NAME="I am an iframe stream!"');
      parser.currentItem.constructor.name.should.eql('IframeStreamItem');
      parser.currentItem.get('name').should.eql('I am an iframe stream!');
    });
  });

  describe('#EXT-X-MEDIA-INF', function() {
    it('should create a new Media item', function() {
      var parser = getParser();

      parser['EXT-X-MEDIA']('NAME="I am a media item!"');
      parser.currentItem.constructor.name.should.eql('MediaItem');
      parser.currentItem.get('name').should.eql('I am a media item!');
    });
  });

  describe('#parseAttributes', function() {
    it('should return an array of key-values', function() {
      var parser = getParser();

      var keyValues = parser.parseAttributes(
        'KEY="I, am a value",RESOLUTION=640x360,FORCED=NO'
      );
      keyValues[0].key.should.eql('KEY');
      keyValues[0].value.should.eql('"I, am a value"');
      keyValues[2].value.should.eql('NO');
    });
  });
});

function getParser() {
  var parser = m3u8.createStream();

  return parser;
}
<|endoftext|>


<commit_before>/*jslint indent: 2 */
/*global window: false, document: false, chrome: false, $: false, createTag: false, createLink: false*/
"use strict";

(function () {

  function createTimerLink(task, moreClass) {
    var link = createLink('toggl-button github '+moreClass);
    link.addEventListener("click", function (e) {
      chrome.extension.sendMessage({
        type: 'timeEntry',
        description: task
      });
      link.innerHTML = "Started...";
    });
    return link;
  }

  function addLinkToDiscussion() {
    var titleElem = $('.discussion-topic-title');
    if (titleElem === null) return;

    var numElem = $('.pull-head .pull-number > a, .issue-head .number > strong');
    var title = titleElem.innerHTML;
    if (numElem !== null) title = numElem.innerHTML + " " + title;

    var wrap = createTag('div', 'toggl infobar-widget');
    wrap.appendChild(createTimerLink(title, 'button minibutton'));
    $(".discusion-topic-infobar").appendChild(wrap);
  }

  chrome.extension.sendMessage({type: 'activate'}, function (response) {
    if (response.success) {
      addLinkToDiscussion();
    }
  });

}());
<commit_msg>JSLint warnings removed<commit_after>/*jslint indent: 2 */
/*global window: false, document: false, chrome: false, $: false, createTag: false, createLink: false*/
"use strict";

(function () {

  function createTimerLink(task, moreClass) {
    var link = createLink('toggl-button github ' + moreClass);
    link.addEventListener("click", function (e) {
      chrome.extension.sendMessage({
        type: 'timeEntry',
        description: task
      });
      link.innerHTML = "Started...";
    });
    return link;
  }

  function addLinkToDiscussion() {
    var titleElem = $('.discussion-topic-title'), numElem, title, wrap;
    if (titleElem === null) {
      return;
    }

    numElem = $('.pull-head .pull-number > a, .issue-head .number > strong');
    title = titleElem.innerHTML;
    if (numElem !== null) {
      title = numElem.innerHTML + " " + title;
    }

    wrap = createTag('div', 'toggl infobar-widget');
    wrap.appendChild(createTimerLink(title, 'button minibutton'));
    $(".discusion-topic-infobar").appendChild(wrap);
  }

  chrome.extension.sendMessage({type: 'activate'}, function (response) {
    if (response.success) {
      addLinkToDiscussion();
    }
  });

}());
<|endoftext|>


<commit_before>// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-09-07 using
// generator-karma 0.9.0

module.exports = function(config) {
  'use strict';

  config.set({
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // base path, that will be used to resolve files and exclude
    basePath: '../',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      // bower:js
      'bower_components/jquery/dist/jquery.js',
      'bower_components/bootstrap/dist/js/bootstrap.js',
      'bower_components/angular/angular.js',
      'bower_components/angular-ui-bootstrap-bower/ui-bootstrap-tpls.js',
      'bower_components/angular-translate/angular-translate.js',
      'bower_components/angular-ui-grid/ui-grid.js',
      'bower_components/bootstrap-material-design/dist/js/material.js',
      'bower_components/bootstrap-material-design/dist/js/ripples.js',
      'bower_components/jquery-ui/ui/jquery-ui.js',
      'bower_components/Chart.js/Chart.js',
      'bower_components/angular-chart.js/dist/angular-chart.js',
      'bower_components/angular-utf8-base64/angular-utf8-base64.js',
      'bower_components/angular-base64-upload/src/angular-base64-upload.js',
      'bower_components/angular-ui-slider/src/slider.js',
      'bower_components/arrive/src/arrive.js',
      'bower_components/angular-clipboard/angular-clipboard.js',
      'bower_components/angular-animate/angular-animate.js',
      'bower_components/angular-aria/angular-aria.js',
      'bower_components/angular-messages/angular-messages.js',
      'bower_components/angular-material/angular-material.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'bower_components/karma-read-json/karma-read-json.js',
      // endbower
      'app/openCompareEditorApp.js',
      'app/editor/openCompareEditor.js',
      'app/**/*.js',
      //'test/mock/**/*.js',
      //{ pattern: 'test/spec/fixtures/foopcm1.json', watched: true, served: true, included: false },
      { pattern: 'app/test/*.json', watched: true, served: true, included: false },
      'test/spec/**/*.js'
    ],

    // list of files / patterns to exclude
    exclude: [
    ],

    // web server port
    port: 9001,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: [
	 'PhantomJS',
	 'Chrome'
    ],

    // Which plugins to enable
    plugins: [
      'karma-phantomjs-launcher',
      'karma-chrome-launcher',
      'karma-jasmine'
    ],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    colors: true,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // Uncomment the following lines if you are using grunt's server to run the tests
    // proxies: {
      // '/': 'http://localhost:9001/'
    // },
    // URL root prevent conflicts with the site root
    // urlRoot: '_karma_'
  });
};
<commit_msg>Chrome for Travis<commit_after>// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-09-07 using
// generator-karma 0.9.0

module.exports = function(config) {
  'use strict';

  config.set({
    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    // base path, that will be used to resolve files and exclude
    basePath: '../',

    // testing framework to use (jasmine/mocha/qunit/...)
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      // bower:js
      'bower_components/jquery/dist/jquery.js',
      'bower_components/bootstrap/dist/js/bootstrap.js',
      'bower_components/angular/angular.js',
      'bower_components/angular-ui-bootstrap-bower/ui-bootstrap-tpls.js',
      'bower_components/angular-translate/angular-translate.js',
      'bower_components/angular-ui-grid/ui-grid.js',
      'bower_components/bootstrap-material-design/dist/js/material.js',
      'bower_components/bootstrap-material-design/dist/js/ripples.js',
      'bower_components/jquery-ui/ui/jquery-ui.js',
      'bower_components/Chart.js/Chart.js',
      'bower_components/angular-chart.js/dist/angular-chart.js',
      'bower_components/angular-utf8-base64/angular-utf8-base64.js',
      'bower_components/angular-base64-upload/src/angular-base64-upload.js',
      'bower_components/angular-ui-slider/src/slider.js',
      'bower_components/arrive/src/arrive.js',
      'bower_components/angular-clipboard/angular-clipboard.js',
      'bower_components/angular-animate/angular-animate.js',
      'bower_components/angular-aria/angular-aria.js',
      'bower_components/angular-messages/angular-messages.js',
      'bower_components/angular-material/angular-material.js',
      'bower_components/angular-mocks/angular-mocks.js',
      'bower_components/karma-read-json/karma-read-json.js',
      // endbower
      'app/openCompareEditorApp.js',
      'app/editor/openCompareEditor.js',
      'app/**/*.js',
      //'test/mock/**/*.js',
      //{ pattern: 'test/spec/fixtures/foopcm1.json', watched: true, served: true, included: false },
      { pattern: 'app/test/*.json', watched: true, served: true, included: false },
      'test/spec/**/*.js'
    ],

    // list of files / patterns to exclude
    exclude: [
    ],

    // web server port
    port: 9001,

    // Start these browsers, currently available:
    // - Chrome
    // - ChromeCanary
    // - Firefox
    // - Opera
    // - Safari (only Mac)
    // - PhantomJS
    // - IE (only Windows)
    browsers: [
	 'PhantomJS',
	// 'Chrome'
    ],

    // Which plugins to enable
    plugins: [
      'karma-phantomjs-launcher',
      'karma-chrome-launcher',
      'karma-jasmine'
    ],

    // Continuous Integration mode
    // if true, it capture browsers, run tests and exit
    singleRun: false,

    colors: true,

    // level of logging
    // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,

    // Uncomment the following lines if you are using grunt's server to run the tests
    // proxies: {
      // '/': 'http://localhost:9001/'
    // },
    // URL root prevent conflicts with the site root
    // urlRoot: '_karma_'
  });
};
<|endoftext|>


<commit_before>var assert = require('assert');
var Gherkin = require('..');

describe('Parser', function () {
  it("parses a simple feature", function () {
    var parser = new Gherkin.Parser(new Gherkin.AstBuilder());
    var scanner = new Gherkin.TokenScanner("Feature: hello");
    var matcher = new Gherkin.TokenMatcher();
    var ast = parser.parse(scanner, matcher);
    assert.deepEqual(ast, {
      type: 'Feature',
      tags: [],
      location: { line: 1, column: 1 },
      language: 'en',
      keyword: 'Feature',
      name: 'hello',
      description: undefined,
      background: undefined,
      scenarioDefinitions: [],
      comments: []
    });
  });

  it("parses multiple features", function () {
    var parser = new Gherkin.Parser(new Gherkin.AstBuilder());
    var matcher = new Gherkin.TokenMatcher();
    var ast1 = parser.parse(new Gherkin.TokenScanner("Feature: hello"), matcher);
    var ast2 = parser.parse(new Gherkin.TokenScanner("Feature: hello again"), matcher);

    assert.deepEqual(ast1, {
      type: 'Feature',
      tags: [],
      location: { line: 1, column: 1 },
      language: 'en',
      keyword: 'Feature',
      name: 'hello',
      description: undefined,
      background: undefined,
      scenarioDefinitions: [],
      comments: []
    });
    assert.deepEqual(ast2, {
      type: 'Feature',
      tags: [],
      location: { line: 1, column: 1 },
      language: 'en',
      keyword: 'Feature',
      name: 'hello again',
      description: undefined,
      background: undefined,
      scenarioDefinitions: [],
      comments: []
    });
  });

  it("parses feature after parse error", function () {
    var parser = new Gherkin.Parser(new Gherkin.AstBuilder());
    var matcher = new Gherkin.TokenMatcher();
    assert.throws(function() { parser.parse(new Gherkin.TokenScanner("# a comment\n" +
								     "Feature: Foo\n" +
								     "  Scenario: Bar\n" +
								     "    Given x\n" +
								     "      ```\n" +
								     "      unclosed docstring\n"),
					    matcher) },
		  Gherkin.ParserException);
    var ast = parser.parse(new Gherkin.TokenScanner("Feature: Foo\n" +
						    "  Scenario: Bar\n" +
						    "    Given x\n" +
						    "      \"\"\"\n" +
						    "      closed docstring\n" +
						    "      \"\"\""),
			   matcher);

    assert.deepEqual(ast, {
      type: 'Feature',
      tags: [],
      location: { line: 1, column: 1 },
      language: 'en',
      keyword: 'Feature',
      name: 'Foo',
      description: undefined,
      background: undefined,
      scenarioDefinitions: [{
        description: undefined,
        keyword: 'Scenario',
        location: { line: 2, column: 3 },
        name: 'Bar',
        steps: [{
          argument: {
            content: 'closed docstring',
            contentType: '',
            location: { line: 4, column: 7 },
            type: 'DocString',
          },
          keyword: 'Given ',
          location: { line: 3, column: 5 },
          text: 'x',
          type: 'Step' }],
        tags: [],
        type: 'Scenario' }],
      comments: []
    });
  });
});
<commit_msg>Make it possible to initialise the matcher with a language.<commit_after>var assert = require('assert');
var Gherkin = require('..');

describe('Parser', function () {
  it("parses a simple feature", function () {
    var parser = new Gherkin.Parser(new Gherkin.AstBuilder());
    var scanner = new Gherkin.TokenScanner("Feature: hello");
    var matcher = new Gherkin.TokenMatcher();
    var ast = parser.parse(scanner, matcher);
    assert.deepEqual(ast, {
      type: 'Feature',
      tags: [],
      location: { line: 1, column: 1 },
      language: 'en',
      keyword: 'Feature',
      name: 'hello',
      description: undefined,
      background: undefined,
      scenarioDefinitions: [],
      comments: []
    });
  });

  it("parses multiple features", function () {
    var parser = new Gherkin.Parser(new Gherkin.AstBuilder());
    var matcher = new Gherkin.TokenMatcher();
    var ast1 = parser.parse(new Gherkin.TokenScanner("Feature: hello"), matcher);
    var ast2 = parser.parse(new Gherkin.TokenScanner("Feature: hello again"), matcher);

    assert.deepEqual(ast1, {
      type: 'Feature',
      tags: [],
      location: { line: 1, column: 1 },
      language: 'en',
      keyword: 'Feature',
      name: 'hello',
      description: undefined,
      background: undefined,
      scenarioDefinitions: [],
      comments: []
    });
    assert.deepEqual(ast2, {
      type: 'Feature',
      tags: [],
      location: { line: 1, column: 1 },
      language: 'en',
      keyword: 'Feature',
      name: 'hello again',
      description: undefined,
      background: undefined,
      scenarioDefinitions: [],
      comments: []
    });
  });

  it("parses feature after parse error", function () {
    var parser = new Gherkin.Parser(new Gherkin.AstBuilder());
    var matcher = new Gherkin.TokenMatcher();
    assert.throws(function() { parser.parse(new Gherkin.TokenScanner("# a comment\n" +
								     "Feature: Foo\n" +
								     "  Scenario: Bar\n" +
								     "    Given x\n" +
								     "      ```\n" +
								     "      unclosed docstring\n"),
					    matcher) },
		  Gherkin.ParserException);
    var ast = parser.parse(new Gherkin.TokenScanner("Feature: Foo\n" +
						    "  Scenario: Bar\n" +
						    "    Given x\n" +
						    "      \"\"\"\n" +
						    "      closed docstring\n" +
						    "      \"\"\""),
			   matcher);

    assert.deepEqual(ast, {
      type: 'Feature',
      tags: [],
      location: { line: 1, column: 1 },
      language: 'en',
      keyword: 'Feature',
      name: 'Foo',
      description: undefined,
      background: undefined,
      scenarioDefinitions: [{
        description: undefined,
        keyword: 'Scenario',
        location: { line: 2, column: 3 },
        name: 'Bar',
        steps: [{
          argument: {
            content: 'closed docstring',
            contentType: '',
            location: { line: 4, column: 7 },
            type: 'DocString',
          },
          keyword: 'Given ',
          location: { line: 3, column: 5 },
          text: 'x',
          type: 'Step' }],
        tags: [],
        type: 'Scenario' }],
      comments: []
    });
  });

  it("can change the default language", function () {
    var parser = new Gherkin.Parser(new Gherkin.AstBuilder());
    var matcher = new Gherkin.TokenMatcher("no");
    var scanner = new Gherkin.TokenScanner("Egenskap: i18n support");
    var ast = parser.parse(scanner, matcher);
    assert.deepEqual(ast, {
      type: 'Feature',
      tags: [],
      location: { line: 1, column: 1 },
      language: 'no',
      keyword: 'Egenskap',
      name: 'i18n support',
      description: undefined,
      background: undefined,
      scenarioDefinitions: [],
      comments: []
    });
  });
});
<|endoftext|>


<commit_before>var assert = require('assert');
let api = require("../../src/math/power.js");
describe("Math", function() {
    describe("Power", function() {
        it("power to zero", function() {
            assert.equal(1, api.power(2, 0));
        });
        it("power to positive number", function() {
            assert.equal(32, api.power(2, 5));
        });
        it("power to negative number", function() {
            assert.equal(0.03125, api.power(2, -5));
        });
        it("power of negative number", function() {
            assert.equal(-32, api.power(-2, 5));
        });
        it("power of negative number with even exponent", function() {
            assert.equal(16, api.power(-2, 4));
        });
    });
});
<commit_msg>adding more tests<commit_after>var assert = require('assert');
let api = require("../../src/math/power.js");
describe("Math", function() {
    describe("Power", function() {
        it("power to zero", function() {
            assert.equal(1, api.power(2, 0));
        });
        it("power of +ve int to +ve int", function() {
            assert.equal(32, api.power(2, 5));
        });
        it("power of +ve int to -ve int", function() {
            assert.equal(0.03125, api.power(2, -5));
        });
        it("power of -ve int to +ve int odd", function() {
            assert.equal(-32, api.power(-2, 5));
        });
        it("power of -ve int to +ve int even", function() {
            assert.equal(16, api.power(-2, 4));
        });
        it("power of -ve int to -ve int odd", function() {
            assert.equal(-0.03125, api.power(-2, -5));
        });
        it("power of -ve int to -ve int even", function() {
            assert.equal(0.0625, api.power(-2, -4));
        });
    });
});
<|endoftext|>


<commit_before>import document from 'global/document';

import QUnit from 'qunit';
import sinon from 'sinon';
import videojs from 'video.js';

import plugin from '../src/plugin';

const Player = videojs.getComponent('Player');

QUnit.test('the environment is sane', function(assert) {
  assert.strictEqual(typeof Array.isArray, 'function', 'es5 exists');
  assert.strictEqual(typeof sinon, 'object', 'sinon exists');
  assert.strictEqual(typeof videojs, 'function', 'videojs exists');
});

// // QUnit.module('videojs-ogvjs', {

// //   beforeEach() {
// //     this.fixture = document.getElementById('qunit-fixture');
// //     this.video = document.createElement('video');
// //     this.fixture.appendChild(this.video);
// //     this.player = new Player();

// //     // Mock the environment's timers because certain things - particularly
// //     // player readiness - are asynchronous in video.js 5.
// //     this.clock = sinon.useFakeTimers();
// //   },

// //   afterEach() {
// //     this.player.dispose();
// //     this.clock.restore();
// //   }
// // });

// QUnit.test('registers itself with video.js', function(assert) {
//   assert.ok(
//     typeof videojs.getTech('Ogvjs'),
//     'function',
//     'videojs-ogvjs plugin is a function'
//   );

//   assert.strictEqual(
//     Player.prototype.ogvjs,
//     plugin,
//     'videojs-ogvjs plugin was registered'
//   );

//   this.player.ogvjs();

//   // Tick the clock forward enough to trigger the player to be "ready".
//   this.clock.tick(1);

//   assert.ok(
//     this.player.hasClass('vjs-ogvjs'),
//     'the plugin adds a class to the player'
//   );
// });
<commit_msg>Disable a bit more of the tests<commit_after>// import document from 'global/document';

import QUnit from 'qunit';
import sinon from 'sinon';
import videojs from 'video.js';

// import plugin from '../src/plugin';

// const Player = videojs.getComponent('Player');

QUnit.test('the environment is sane', function(assert) {
  assert.strictEqual(typeof Array.isArray, 'function', 'es5 exists');
  assert.strictEqual(typeof sinon, 'object', 'sinon exists');
  assert.strictEqual(typeof videojs, 'function', 'videojs exists');
});

// // QUnit.module('videojs-ogvjs', {

// //   beforeEach() {
// //     this.fixture = document.getElementById('qunit-fixture');
// //     this.video = document.createElement('video');
// //     this.fixture.appendChild(this.video);
// //     this.player = new Player();

// //     // Mock the environment's timers because certain things - particularly
// //     // player readiness - are asynchronous in video.js 5.
// //     this.clock = sinon.useFakeTimers();
// //   },

// //   afterEach() {
// //     this.player.dispose();
// //     this.clock.restore();
// //   }
// // });

// QUnit.test('registers itself with video.js', function(assert) {
//   assert.ok(
//     typeof videojs.getTech('Ogvjs'),
//     'function',
//     'videojs-ogvjs plugin is a function'
//   );

//   assert.strictEqual(
//     Player.prototype.ogvjs,
//     plugin,
//     'videojs-ogvjs plugin was registered'
//   );

//   this.player.ogvjs();

//   // Tick the clock forward enough to trigger the player to be "ready".
//   this.clock.tick(1);

//   assert.ok(
//     this.player.hasClass('vjs-ogvjs'),
//     'the plugin adds a class to the player'
//   );
// });
<|endoftext|>