<commit_before>define(function (require) {

  var _ = require('underscore'),
      Store = require('stores/Store'),
      Machine = require('models/Machine');

  var _machines = {};
  var _isFetching = {};

  function fetchMachine(providerId, identityId, machineId){
    if(!_isFetching[machineId]) {
      _isFetching[machineId] = true;
      var machine = new Machine({id: machineId}, {
        provider_id: providerId,
        identity_id: identityId
      });

      machine.fetch().done(function () {
        _isFetching[machineId] = false;
         _machines[machineId] = machine;
        MachineStore.emitChange();
      });
    }
  }

  var MachineStore = {

    get: function (providerId, identityId, machineId) {
      console.warn("Function shouldn't be used...");
      if (!_machines[machineId]) {
        fetchMachine(providerId, identityId, machineId);
      }
      return _machines[machineId];
    }

  };

  _.extend(MachineStore, Store);

  return MachineStore;

});
<commit_msg>refactor machine store<commit_after>define(function (require) {

  var _ = require('underscore'),
      Dispatcher = require('dispatchers/Dispatcher'),
      Store = require('stores/Store'),
      Collection = require('collections/MachineCollection'),
      Constants = require('constants/ProviderMachineConstants');

  var _models = new Collection();
  var _modelsFor = {};
  var _isFetchingFor = {};

  //
  // CRUD Operations
  //

  var fetchModelsFor = function(imageId){
    if(!_modelsFor[imageId] && !_isFetchingFor[imageId]) {
      _isFetchingFor[imageId] = true;
      var models = new Collection();
      models.fetch({
        url: models.url + "?application__id=" + imageId
      }).done(function () {
        _isFetchingFor[imageId] = false;

        // add models to existing cache
        _models.add(models.models);

        _modelsFor[imageId] = models;
        ModelStore.emitChange();
      });
    }
  };

  function update(model) {
    var existingModel = _models.get(model);
    if (!existingModel) throw new Error("ProviderMachine doesn't exist.");
    _models.add(model, {merge: true});
  }

  //
  // Model Store
  //

  var ModelStore = {

    getProviderMachinesFor: function(image){
      if(!_modelsFor[image.id]) return fetchModelsFor(image.id);

      var machines = _models.filter(function(m){
        // filter out the machines not associated with the image
        return m.get('image').id === image.id;
      });

      return new Collection(machines);
    }

  };

  Dispatcher.register(function (dispatch) {
    var actionType = dispatch.action.actionType;
    var payload = dispatch.action.payload;
    var options = dispatch.action.options || options;

    switch (actionType) {

      case Constants.UPDATE_PROVIDER_MACHINE:
        update(payload.providerMachine);
        break;

      case Constants.EMIT_CHANGE:
        break;

      default:
        return true;
    }

    if(!options.silent) {
      ModelStore.emitChange();
    }

    return true;
  });

  _.extend(ModelStore, Store);

  return ModelStore;
});
<|endoftext|>


<commit_before>require('../spec_helper.js');
var Worker = require('../../src/worker.js'),
    Primus = require('primus'),
    domain = require('domain'),
    http = require('http');

describe("Worker", function() {
  var config = null,
      d = null,
      worker = null;

  beforeEach(function() {
    config = {
      relayServer: "http://example.com:12345",
      token: "my token"
    };
  });

  describe("connect", function() {
    beforeEach(function() {
      d = {
        on: sinon.stub(),
        run: sinon.stub()
      };
      sinon.stub(domain, 'create').returns(d);
      worker = new Worker(config);
      worker.connect();
    });

    it("runs inside a domain", function() {
      expect(d.run).to.have.been.calledOnce;
    });

    describe("socket builder", function() {
      var res = null,
          socket = null,
          conn = null,
          spec = {parser:'json'};

      beforeEach(function() {
        socket = {
          on: sinon.stub(),
          write: sinon.stub()
        };
        sinon.stub(Primus, 'createSocket').returns(function() {
          return socket;
        });
        res = {
          on: sinon.stub().yields(JSON.stringify(spec))
        };
        sinon.stub(http, 'get').yields(res);
        d.run.getCall(0).args[0]();
      });

      it("requests the primus spec", function() {
        var specURL = config.relayServer+'/primus/spec';
        expect(http.get.getCall(0).args[0]).to.eq(specURL);
      });

      afterEach(function() {
        Primus.createSocket.restore();
        http.get.restore();
      });
    });

    afterEach(function() {
      domain.create.restore();
    });
  });
});
<commit_msg>cover socket.on('data') behavior<commit_after>require('../spec_helper.js');
var Worker = require('../../src/worker.js'),
    Primus = require('primus'),
    domain = require('domain'),
    http = require('http');

describe("Worker", function() {
  var config = null,
      d = null,
      worker = null;

  beforeEach(function() {
    config = {
      relayServer: "http://example.com:12345",
      token: "my token"
    };
  });

  describe("connect", function() {
    beforeEach(function() {
      d = {
        on: sinon.stub(),
        run: sinon.stub()
      };
      sinon.stub(domain, 'create').returns(d);
      worker = new Worker(config);
      worker.connect();
    });

    it("runs inside a domain", function() {
      expect(d.run).to.have.been.calledOnce;
    });

    describe("socket builder", function() {
      var res = null,
          socket = null,
          conn = null,
          spec = {parser:'json'};

      beforeEach(function() {
        socket = {
          on: sinon.stub(),
          write: sinon.stub(),
          emit: {apply: sinon.stub()},
          reserved: sinon.stub()
        };
        sinon.stub(Primus, 'createSocket').returns(function() {
          return socket;
        });
        res = {
          on: sinon.stub().yields(JSON.stringify(spec))
        };
        sinon.stub(http, 'get').yields(res);
        d.run.getCall(0).args[0]();
      });

      it("requests the primus spec", function() {
        var specURL = config.relayServer+'/primus/spec';
        expect(http.get.getCall(0).args[0]).to.eq(specURL);
      });

      it("listens to the socket's 'data' event", function() {
        expect(socket.on.getCall(1).args[0]).to.eq('data');
      });

      describe("socket data event", function() {
        var fn = null;
        var data = null;
        beforeEach(function() {
          fn = socket.on.getCall(1).args[1];
          data = {args: ['event:name', {'my':'data'}]};
          fn(data);
        });
        it("checks if we will clash with a Primus reserved word", function() {
          expect(socket.reserved).to.have.been.calledWith('event:name');
        });
        it("applies the data to the socket's emit method", function() {
          expect(socket.emit.apply.getCall(0).args[0]).to.eq(socket);
          expect(socket.emit.apply.getCall(0).args[1]).to.eq(data.args);
        });

      });

      afterEach(function() {
        Primus.createSocket.restore();
        http.get.restore();
      });
    });

    afterEach(function() {
      domain.create.restore();
    });
  });
});
<|endoftext|>


<commit_before>/*global after, before, describe, it*/
'use strict';
var assert  = require('assert');
var grunt = require('grunt');
var path = require('path');
var sinon = require('sinon');

var statici18n = require('../tasks/statici18n');
statici18n(grunt);

describe('exists', function() {
  after(function() {
    grunt.log.warn.restore();
  });
  it('should nag and filter if the file is missing', function() {
    sinon.stub(grunt.log, 'warn');
    assert.equal(false, statici18n.exists('some/fake/file.txt'));
    sinon.assert.calledOnce(grunt.log.warn);
  });
  it('returns true with some real file', function() {
    var readme = path.join(__dirname, 'fixtures/app/static/data.json');
    assert.ok(statici18n.exists(readme));
  });
});

describe('save', function() {
  before(function() {
    sinon.stub(grunt.log, 'writeln');
    sinon.stub(grunt.file, 'write');
    var file = {
      dest: 'dest/file.txt',
      orig: { 'dest': 'dest' }
    };
    statici18n.save(file, 'content', 'es');
  });
  after(function() {
    grunt.file.write.restore();
    grunt.log.writeln.restore();
  });
  it('should call grunt.write', function() {
    sinon.assert.calledOnce(grunt.file.write);
  });
  it('should add lang to destination', function() {
    sinon.assert.calledWith(grunt.file.write, 'dest/es/file.txt', 'content');
  });
});

describe('static i18n task', function() {
  before(function(done) {
    var ChildProcess = require('cover-child-process').ChildProcess;
    var Blanket = require('cover-child-process').Blanket;
    var childProcess = new ChildProcess(new Blanket());
    var gruntExec = 'node ' + path.resolve('node_modules/.bin/grunt');
    var fixtures = path.join(__dirname, 'fixtures');
    childProcess.exec(gruntExec, {cwd: fixtures},  done);
  });
  var i18n = path.join(__dirname, 'fixtures', 'app', 'i18n');
  var fr = path.join(i18n, 'fr', 'static', 'data.json');
  var pt = path.join(i18n, 'pt_BR', 'static', 'data.json');
  var def = path.join(i18n, 'static', 'data.json');
  it('should create a file for each language', function() {
    assert.ok(grunt.file.exists(fr), 'Not found: ' + fr);
    assert.ok(grunt.file.exists(pt), 'Not found: ' + pt);
  });
  it('should create a non-language default', function() {
    assert.ok(grunt.file.exists(def), 'Not found: ' + def);
  });
  it('should not translate the default', function() {
    assert.equal('["Hello World"]\n', grunt.file.read(def));
  });
  it('should translate french', function() {
    assert.equal('["Bonjour tout le monde"]\n', grunt.file.read(fr));
  });
  it('should translate english', function() {
    assert.equal('["Olá mundo"]\n', grunt.file.read(pt));
  });
});
<commit_msg>Add some whitespace to tests<commit_after>/*global after, before, describe, it*/
'use strict';
var assert  = require('assert');
var grunt = require('grunt');
var path = require('path');
var sinon = require('sinon');

var statici18n = require('../tasks/statici18n');
statici18n(grunt);

describe('exists', function() {

  after(function() {
    grunt.log.warn.restore();
  });

  it('should nag and filter if the file is missing', function() {
    sinon.stub(grunt.log, 'warn');
    assert.equal(false, statici18n.exists('some/fake/file.txt'));
    sinon.assert.calledOnce(grunt.log.warn);
  });

  it('returns true with some real file', function() {
    var readme = path.join(__dirname, 'fixtures/app/static/data.json');
    assert.ok(statici18n.exists(readme));
  });

});

describe('save', function() {

  before(function() {
    sinon.stub(grunt.log, 'writeln');
    sinon.stub(grunt.file, 'write');
    var file = {
      dest: 'dest/file.txt',
      orig: { 'dest': 'dest' }
    };
    statici18n.save(file, 'content', 'es');
  });

  after(function() {
    grunt.file.write.restore();
    grunt.log.writeln.restore();
  });

  it('should call grunt.write', function() {
    sinon.assert.calledOnce(grunt.file.write);
  });

  it('should add lang to destination', function() {
    sinon.assert.calledWith(grunt.file.write, 'dest/es/file.txt', 'content');
  });

});

describe('static i18n task', function() {

  before(function(done) {
    var ChildProcess = require('cover-child-process').ChildProcess;
    var Blanket = require('cover-child-process').Blanket;
    var childProcess = new ChildProcess(new Blanket());
    var gruntExec = 'node ' + path.resolve('node_modules/.bin/grunt');
    var fixtures = path.join(__dirname, 'fixtures');
    childProcess.exec(gruntExec, {cwd: fixtures},  done);
  });

  var i18n = path.join(__dirname, 'fixtures', 'app', 'i18n');
  var fr = path.join(i18n, 'fr', 'static', 'data.json');
  var pt = path.join(i18n, 'pt_BR', 'static', 'data.json');
  var def = path.join(i18n, 'static', 'data.json');

  it('should create a file for each language', function() {
    assert.ok(grunt.file.exists(fr), 'Not found: ' + fr);
    assert.ok(grunt.file.exists(pt), 'Not found: ' + pt);
  });

  it('should create a non-language default', function() {
    assert.ok(grunt.file.exists(def), 'Not found: ' + def);
  });

  it('should not translate the default', function() {
    assert.equal('["Hello World"]\n', grunt.file.read(def));
  });

  it('should translate french', function() {
    assert.equal('["Bonjour tout le monde"]\n', grunt.file.read(fr));
  });

  it('should translate english', function() {
    assert.equal('["Olá mundo"]\n', grunt.file.read(pt));
  });

});
<|endoftext|>


<commit_before>console.log("reading main.js starts");

requirejs.config({
  baseDir: '/js',
  paths: {
    'jquery': '/bower_components/jquery/dist/jquery.min',
    'tabzilla': 'https://mozorg.cdn.mozilla.net/tabzilla/tabzilla',
    // localization related
    'selectize': "/bower_components/selectize/dist/js/standalone/selectize.min",
    'localized': '/bower_components/webmaker-i18n/localized',
    'list': '/bower_components/listjs/dist/list.min',
    'fuzzySearch': '/bower_components/list.fuzzysearch.js/dist/list.fuzzysearch.min',
    'analytics': '/bower_components/webmaker-analytics/analytics',
    'localized': '/bower_components/webmaker-i18n/localized',
    'languages': '/bower_components/webmaker-language-picker/js/languages',
    //makerparty ones
    'masonry': '/bower_components/masonry/dist/masonry.pkgd.min', // live-updates
    'makeapi': '/bower_components/makeapi-client/src/make-api', // live-updates
    'quilt': '/bower_components/supportopen-quilt/dist/quilt', // live-updates
    // other UI stuff
    'jquery-colorbox': '/bower_components/jquery-colorbox/jquery.colorbox-min',
    'bootstrap-affix': '/bower_components/bootstrap/js/affix',
    'bootstrap-collapse': '/bower_components/bootstrap/js/collapse',
    'bootstrap-scrollspy': '/bower_components/bootstrap/js/scrollspy',
    'elastislide.modernizr': '/lib/elastislide/js/modernizr.custom.17475',
    'elastislide.jquerypp': '/lib/elastislide/js/jquerypp.custom',
    'elastislide': '/lib/elastislide/js/jquery.elastislide',
    'makerparty-ui': '/js/ui'
  },
  shim: {
    'tabzilla': ['jquery'],
    'jquery-colorbox': ['jquery'],
    'bootstrap-affix': ['jquery'],
    'bootstrap-collapse': ['jquery'],
    'bootstrap-scrollspy': ['jquery'],
    'elastislide.modernizr': ['jquery'],
    'elastislide.jquerypp': ['jquery', 'elastislide.modernizr' ],
    'elastislide': ['jquery', 'elastislide.modernizr', 'elastislide.jquerypp'],
    'quilt': ['jquery', 'makeapi', 'masonry'],
    'makerparty-ui': [
            'jquery',
            'jquery-colorbox',
            'bootstrap-affix',
            'bootstrap-collapse',
            'bootstrap-scrollspy',
            'elastislide.modernizr',
            'elastislide.jquerypp']
  }
});

require([
  'jquery',
  'quilt',
  'languages',
  'selectize',
  'elastislide',
  'makerparty-ui',
  'tabzilla'
], function($, quilt, languages) {
  'use strict';

  var quiltConfig = {
    tags: [ 'makerparty', 'maker party', '#makerparty' ],
    execution: 'or',
    limit: 50,
    duration: 7000,
    $preview: $( '#makePreview' )
  };
  quilt(quiltConfig);

  // Call this when the element is ready
  languages.ready({
    position: "top",
    arrow: "left"
  });

  //initialized language selectize
  $('select[name=supportedLocales]').selectize();
});

console.log("reading main.js ends");
<commit_msg>Only initiate Quilt on the /live-updates page<commit_after>console.log("reading main.js starts");

requirejs.config({
  baseDir: '/js',
  paths: {
    'jquery': '/bower_components/jquery/dist/jquery.min',
    'tabzilla': 'https://mozorg.cdn.mozilla.net/tabzilla/tabzilla',
    // localization related
    'selectize': "/bower_components/selectize/dist/js/standalone/selectize.min",
    'localized': '/bower_components/webmaker-i18n/localized',
    'list': '/bower_components/listjs/dist/list.min',
    'fuzzySearch': '/bower_components/list.fuzzysearch.js/dist/list.fuzzysearch.min',
    'analytics': '/bower_components/webmaker-analytics/analytics',
    'localized': '/bower_components/webmaker-i18n/localized',
    'languages': '/bower_components/webmaker-language-picker/js/languages',
    //makerparty ones
    'masonry': '/bower_components/masonry/dist/masonry.pkgd.min', // live-updates
    'makeapi': '/bower_components/makeapi-client/src/make-api', // live-updates
    'quilt': '/bower_components/supportopen-quilt/dist/quilt', // live-updates
    // other UI stuff
    'jquery-colorbox': '/bower_components/jquery-colorbox/jquery.colorbox-min',
    'bootstrap-affix': '/bower_components/bootstrap/js/affix',
    'bootstrap-collapse': '/bower_components/bootstrap/js/collapse',
    'bootstrap-scrollspy': '/bower_components/bootstrap/js/scrollspy',
    'elastislide.modernizr': '/lib/elastislide/js/modernizr.custom.17475',
    'elastislide.jquerypp': '/lib/elastislide/js/jquerypp.custom',
    'elastislide': '/lib/elastislide/js/jquery.elastislide',
    'makerparty-ui': '/js/ui'
  },
  shim: {
    'tabzilla': ['jquery'],
    'jquery-colorbox': ['jquery'],
    'bootstrap-affix': ['jquery'],
    'bootstrap-collapse': ['jquery'],
    'bootstrap-scrollspy': ['jquery'],
    'elastislide.modernizr': ['jquery'],
    'elastislide.jquerypp': ['jquery', 'elastislide.modernizr' ],
    'elastislide': ['jquery', 'elastislide.modernizr', 'elastislide.jquerypp'],
    'quilt': ['jquery', 'makeapi', 'masonry'],
    'makerparty-ui': [
            'jquery',
            'jquery-colorbox',
            'bootstrap-affix',
            'bootstrap-collapse',
            'bootstrap-scrollspy',
            'elastislide.modernizr',
            'elastislide.jquerypp']
  }
});

require([
  'jquery',
  'quilt',
  'languages',
  'selectize',
  'elastislide',
  'makerparty-ui',
  'tabzilla'
], function($, quilt, languages) {
  'use strict';

  // Call this when the element is ready
  languages.ready({
    position: "top",
    arrow: "left"
  });

  //initialized language selectize
  $('select[name=supportedLocales]').selectize();

  // we display Quilt on /live-updates page, so only initiate it on that page
  if ( $("body").hasClass("live-updates") ) {
    var quiltConfig = {
      tags: [ 'makerparty', 'maker party', '#makerparty' ],
      execution: 'or',
      limit: 50,
      duration: 7000,
      $preview: $( '#makePreview' )
    };
    quilt(quiltConfig);
  }
});

console.log("reading main.js ends");
<|endoftext|>


<commit_before>var vows = require('vows'),
	assert = require('assert'),
	gm = require('../lib/googlemaps');

vows.describe('staticmaps').addBatch({
	'Complex static map (Lock Haven, PA)': {
		topic: function(){
			markers = [
			    { 'location': '300 W Main St Lock Haven, PA' },
			    { 'location': '444 W Main St Lock Haven, PA',
			        'color': 'red',
			        'label': 'A',
			        'shadow': 'false',
			        'icon' : 'http://chart.apis.google.com/chart?chst=d_map_pin_icon&chld=cafe%7C996600'
			    }
			]

			styles = [
			    { 'feature': 'road', 'element': 'all', 'rules':
			        { 'hue': '0x00ff00' }
			    }
			]

			paths = [
			    { 'color': '0x0000ff', 'weight': '5', 'points':
			        [ '41.139817,-77.454439', '41.138621,-77.451596' ]
			    }
			]

			gm.staticMap('444 W Main St Lock Haven PA', 15, '500x400', this.callback, false, 'roadmap', markers, styles, paths);
		},
		'returns the expected static map URL': function(result, err){
			assert.equal(result , "http://maps.googleapis.com/maps/api/staticmap?center=444%20W%20Main%20St%20Lock%20Haven%20PA&zoom=15&size=500x400&maptype=roadmap&markers=%7C300%20W%20Main%20St%20Lock%20Haven%2C%20PA&markers=%7Ccolor%3Ared%7Clabel%3AA%7Cicon%3Ahttp%3A%2F%2Fchart.apis.google.com%2Fchart%3Fchst%3Dd_map_pin_icon%26chld%3Dcafe%257C996600%7Cshadow%3Afalse%7C444%20W%20Main%20St%20Lock%20Haven%2C%20PA&style=%7Cfeature%3Aroad%7Celement%3Aall%7Chue%3A0x00ff00&path=weight%3A5%7Ccolor%3A0x0000ff%7C41.139817%2C-77.454439%7C41.138621%2C-77.451596&sensor=false");
		}
	}
}).export(module);
<commit_msg>Update staticMap tests to account for IO<commit_after>var vows = require('vows'),
	assert = require('assert'),
	crypto = require('crypto'),
	gm = require('../lib/googlemaps');

vows.describe('staticmaps').addBatch({
	'Complex static map (Lock Haven, PA)': {
		topic: {
			'markers': [
			  { 'location': '300 W Main St Lock Haven, PA' },
			  { 'location': '444 W Main St Lock Haven, PA',
			    'color'   : 'red',
			    'label'   : 'A',
			    'shadow'  : 'false',
			    'icon'    : 'http://chart.apis.google.com/chart?chst=d_map_pin_icon&chld=cafe%7C996600'
			  }
			],

			'styles': [
			  { 'feature': 'road', 'element': 'all', 'rules':
			    { 'hue': '0x00ff00' }
			  }
			],

			'paths': [
			  { 'color': '0x0000ff', 'weight': '5', 'points':
			    [ '41.139817,-77.454439', '41.138621,-77.451596' ]
			  }
			]
    },

		'URL': {
			topic: function(options){
				return gm.staticMap('444 W Main St Lock Haven PA', 15, '500x400',
				                    false, false, 'roadmap', options.markers, options.styles, options.paths);
			},
			'returns the expected static map URL': function(result){
				assert.equal(result , "http://maps.googleapis.com/maps/api/staticmap?center=444%20W%20Main%20St%20" +
				                      "Lock%20Haven%20PA&zoom=15&size=500x400&maptype=roadmap&markers=%7C300%20W%2" +
				                      "0Main%20St%20Lock%20Haven%2C%20PA&markers=%7Ccolor%3Ared%7Clabel%3AA%7Cicon" +
				                      "%3Ahttp%3A%2F%2Fchart.apis.google.com%2Fchart%3Fchst%3Dd_map_pin_icon%26chl" +
				                      "d%3Dcafe%257C996600%7Cshadow%3Afalse%7C444%20W%20Main%20St%20Lock%20Haven%2" +
				                      "C%20PA&style=%7Cfeature%3Aroad%7Celement%3Aall%7Chue%3A0x00ff00&path=weight" +
				                      "%3A5%7Ccolor%3A0x0000ff%7C41.139817%2C-77.454439%7C41.138621%2C-77.451596&s" +
				                      "ensor=false");
			}
		},

		'PNG data': {
			topic: function(options){
				gm.staticMap('444 W Main St Lock Haven PA', 15, '500x400', this.callback, false, 'roadmap', options.markers, options.styles, options.paths);
			},
			'returns the expected static map PNG data': function(err, data){
				var md5 = crypto.createHash('md5');
				md5.update(data);
				assert.equal(md5.digest('hex') , 'e1c4533cd8f676f2aef58d7a28d9f773');
			}
		}
	}
}).export(module);
<|endoftext|>


<commit_before>"use strict";

/* globals app, utils, $ */

(function(window) {
	var delay, targetCard, currentCard, destroyDelay,
		events = 'mouseenter.card mouseleave.card',
		exitEvent = 'click.card',
		selector = 'a[href*="/user/"]:not(.profile-card a)',
		exitSelector = 'body:not(".profile-card")',
		regex = /(\/user\/([^/]+))(?:\/$|$)/;

	$(document).ready(function() {
		//Listen for events on body, we don't have to re-add on every ajaxify
		$(document.body).off(events, selector).on(events, selector, function(e) {
			var target = $(e.currentTarget),
				href = regex.exec(target.attr('href'));

			//Check if it's a valid link
			if (href && (!utils.invalidLatinChars.test(href[2]) && !utils.invalidUnicodeChars.test(href[2]))) {
				if (target.children('img')) {
					//Destroy tooltips added by NodeBB
					target.children('img').tooltip('destroy');
				}

				if (e.type === "mouseenter" && !target.is(currentCard)) {
					//If it's a mouseenter event, set a timeout to create a new card
					delay = setTimeout(function() {
						createCard(target, href[1]);
					}, 500);
					targetCard = target;
				} else {
					//Otherwise add some handlers for destroying a card
					if (target.is(currentCard)) {
						destroyDelay = setTimeout(function() {
							destroyCard(target);
						}, 500);

						target.data('bs.popover')['$tip'].off(events).on(events, function(e) {
							if (e.type === "mouseenter") {
								clearTimeout(destroyDelay);
							} else {
								destroyDelay = setTimeout(function() {
									destroyCard(target);
								}, 500);
							}
						});
					}

					//Also clear the timeout for creating a new card
					clearTimeout(delay);
					targetCard = null;
				}
			}
		});

		$(window).on('action:ajaxify.start', function() {
			if (delay) {
				clearTimeout(delay);
				delay = 0;
			}

			//Destroy any cards before ajaxifying
			if (currentCard) {
				destroyCard(currentCard);
			}

			targetCard = null;
		});
	});

	function destroyCard(target) {
		target.popover('destroy');
		currentCard = null;
	}

	function createCard(target, url) {
		var api = '/api' + url;
		$.ajax({
			url: api,
			success: function(result) {
				result.name = result.fullname || result.username;
				app.parseAndTranslate('cards/profile', result, function(html) {
					//If target is not the currentCard and if the target is the targetCard
					if (!target.is(currentCard) && target.is(targetCard)) {
						//If there's an existing card, destroy it
						if (currentCard) {
							destroyCard(currentCard);
						}

						// Bind chat button
						html.find('[component="account/chat"]').on('click', function() {
							socket.emit('modules.chats.hasPrivateChat', result.uid, function(err, roomId) {
								if (err) {
									return app.alertError(err.message);
								}
								if (roomId) {
									app.openChat(roomId);
								} else {
									app.newChat(result.uid);
								}
							});
						});

						//Create card
						target.popover({
							html: true,
							content: html,
							placement: calculatePopoverPosition(target),
							trigger: 'manual',
							container: 'body'
						}).popover('show').data('bs.popover')['$tip'].css('z-index', 1000000);

						$('.profile-card .timeago').timeago();
						$('.card-fab button').dropdown();
						utils.makeNumbersHumanReadable($('.profile-card .human-readable-number'));

						$('html').off(exitEvent).on(exitEvent, function() {
							if (currentCard) {
								destroyCard(currentCard);
							}
						});

						$('.profile-card').off(exitEvent).on(exitEvent, function(e) {
							e.stopPropagation();
						});

						currentCard = target;
					}
				});
			},
			cache: false
		});
	}

	app.createUserTooltips = function() {
		//override with empty function because we don't want this function to execute
		//so metal
	};

	function calculatePopoverPosition(target){
		var offset = target.offset();
		var width = $(document).width();
		var height = $(document).height();

		if (offset.left > 300) {
			return 'left';
		}

		if (width - offset.left > 300) {
			return 'right';
		}

		if (offset.top > 400) {
			return 'top';
		}

		if (height - offset.top > 400) {
			return 'bottom';
		}

		return 'right';
	}

})(window);
<commit_msg>Move some of this (horrible) code around<commit_after>"use strict";

/* globals app, utils, $ */

(function(window) {
	var delay, targetCard, currentCard, destroyDelay,
		events = 'mouseenter.card mouseleave.card',
		exitEvent = 'click.card',
		selector = 'a[href*="/user/"]:not(.profile-card a)',
		exitSelector = 'body:not(".profile-card")',
		regex = /(\/user\/([^/]+))(?:\/$|$)/;

	$(document).ready(function() {
		// Listen for events on body, we don't have to re-add on every ajaxify
		$(document.body).off(events, selector).on(events, selector, onEvent);

		$(window).on('action:ajaxify.start', function() {
			if (delay) {
				clearTimeout(delay);
				delay = 0;
			}

			// Destroy any cards before ajaxifying
			if (currentCard) {
				destroyCard(currentCard);
			}

			targetCard = null;
		});
	});

	function onEvent(e) {
		var target = $(e.currentTarget),
			href = regex.exec(target.attr('href'));

		// Check if it's a valid link
		if (href && (!utils.invalidLatinChars.test(href[2]) && !utils.invalidUnicodeChars.test(href[2]))) {
			// Destroy tooltips added by NodeBB
			if (target.children('img')) {
				target.children('img').tooltip('destroy');
			}

			// If it's a mouseenter event, set a timeout to create a new card
			if (e.type === "mouseenter" && !target.is(currentCard)) {
				delay = createCard(target, href[1]);
				targetCard = target;
			} else {
				// Otherwise add some handlers for destroying a card
				if (target.is(currentCard)) {
					destroyDelay = destroyCard(target);

					target.data('bs.popover')['$tip'].off(events).on(events, function(e) {
						if (e.type === "mouseenter") {
							clearTimeout(destroyDelay);
						} else {
							destroyDelay = destroyCard(target);
						}
					});
				}

				// Also clear the timeout for creating a new card
				clearTimeout(delay);
				targetCard = null;
			}
		}
	}

	function createCard(target, url) {
		return setTimeout(function() {
			var api = '/api' + url;
			$.ajax({
				url: api,
				success: function(result) {
					result.name = result.fullname || result.username;

					app.parseAndTranslate('cards/profile', result, function(cardHTML) {
						// If target is not the currentCard and if the target is the targetCard
						if (!target.is(currentCard) && target.is(targetCard)) {
							// If there's an existing card, destroy it
							if (currentCard) {
								destroyCard(currentCard);
							}

							// Bind chat button
							cardHTML.find('[component="account/chat"]').on('click', function() {
								socket.emit('modules.chats.hasPrivateChat', result.uid, function(err, roomId) {
									if (err) {
										return app.alertError(err.message);
									}
									if (roomId) {
										app.openChat(roomId);
									} else {
										app.newChat(result.uid);
									}
								});
							});

							// Create card
							target.popover({
								html: true,
								content: cardHTML,
								placement: calculatePopoverPosition(target),
								trigger: 'manual',
								container: 'body'
							}).popover('show').data('bs.popover')['$tip'].css('z-index', 1000000);

							// Bind some other stuff
							$('.profile-card .timeago').timeago();
							$('.card-fab button').dropdown();
							utils.makeNumbersHumanReadable($('.profile-card .human-readable-number'));

							// Bind exit events
							$('html').off(exitEvent).on(exitEvent, function() {
								if (currentCard) {
									destroyCard(currentCard);
								}
							});

							// I don't remember what this does
							$('.profile-card').off(exitEvent).on(exitEvent, function(e) {
								e.stopPropagation();
							});

							currentCard = target;
						}
					});
				},
				cache: false
			});
		}, 500);
	}

	function destroyCard(target) {
		return setTimeout(function() {
			target.popover('destroy');
			currentCard = null;
		}, 500);
	}

	function calculatePopoverPosition(target){
		var offset = target.offset();
		var width = $(document).width();
		var height = $(document).height();

		if (offset.left > 300) {
			return 'left';
		}

		if (width - offset.left > 300) {
			return 'right';
		}

		if (offset.top > 400) {
			return 'top';
		}

		if (height - offset.top > 400) {
			return 'bottom';
		}

		return 'right';
	}

	app.createUserTooltips = function() {
		// override with empty function because we don't want this function to execute
		// so metal
	};

})(window);
<|endoftext|>


<commit_before>// Enter your clientside JavaScript code for the single room page here

// You are allowed to use the code you produced during midterm 1 (app.js) instead
// of the following skeleton code

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

const app = {
    strokeStyle: 'black',
    isDrawing: false,
    history: [],

    socket: io(),
    // get id fron url
    id: window.location.pathname.split('/')[2],

    // will be overwritten by brushes
    draw: function() {},

    clearCanvas: function() {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    },

    /**
     * Takes an array of arrays of lineSegments
     * and draws them on canvas
     * @param history
     */
    replayHistory: function(history) {
        history.forEach(this.drawLine.bind(this));
    },

    /**
     * Takes an array of lineSegments that form a path
     * and draws them on canvas
     * @param lineSegs
     */
    drawLine: function(lineSegs) {
        if (lineSegs.length == 0) return;
        this.ctx.beginPath();
        this.selectBrush(lineSegs[0].brushName);
        lineSegs.forEach(seg => {
            this.draw(seg.strokeStyle, seg.x, seg.y);
        });
        this.ctx.closePath();
    },

    clearHandler: function(e, no) {
        this.clearCanvas();
        this.history = [];
        if (!no)
            this.socket.emit("clear", this.id);
    },

    paletteHandler: function(e) {
        if (!e.target.classList.contains('p-color')) return;
        this.strokeStyle = e.target.dataset.color;
        // console.log(e.target.dataset.color);
    },

    // TODO
    rgbPickerHandler: function(e) {
        // if (!e.target.classList.contains('p-color')) return;
        // this.strokeStyle = e.target.dataset.color;
        // console.log("hai premuto rgbpicker");
        let rgbInsertedColor = document.getElementById('rgb').value;
        // if (rgbInsertedColor.length = 7)
            this.strokeStyle = this.colorHexToRgb(rgbInsertedColor);
    },

    colorHexToRgb: function(color) {
        if (color.length != 7) {
            console.log("Invalid color");
            document.getElementById('rgb').value = "not valid";
            return;
        }

        console.log("rbgcolorpicker");
        let red = color.substr(1, 2);
        red = parseInt(red, 16);
        // console.log("red: " + red);
        let green = color.substr(3, 2);
        // console.log("b4 green: ", green);
        green = parseInt(green, 16);
        // console.log("green: " + green);
        let blue = color.substr(5, 2);
        blue = parseInt(blue, 16);
        // console.log("blue: " + blue);
        return "rgb(" + red + ", " + green + ", " + blue + ")";
    },

    setupBrushes: function() {
        const brushToolbar = document.getElementById('brush-toolbar');
        this.brushes = window.brushes;

        // extend disc brush
        const randomDiscBrush = Object.create(this.brushes[1]);
        randomDiscBrush.name = "Random Disc";
        randomDiscBrush.getRadius = function() {
                return getRandomInt(10, 30)
            },
            randomDiscBrush.getOpacity = function() {
                return Math.random()
            },

            this.brushes.push(randomDiscBrush);

        // extend star brush
        const randomStarBrush = Object.create(this.brushes[2]);
        randomStarBrush.name = "Random Star";
        randomStarBrush.getOptions = function() {
            return {
                length: 15,
                angle: getRandomInt(0, 180),
                width: getRandomInt(1, 10),
                opacity: Math.random(),
                scale: getRandomInt(1, 20) / 10,
                color: ('rgb(' + getRandomInt(0, 255) + ',' + getRandomInt(0, 255) + ',' + getRandomInt(0, 255) + ')')
            }
        };

        this.brushes.push(randomStarBrush);

        //add brush buttons
        this.brushes.forEach(b => {
            const btn = document.createElement('BUTTON');
            btn.id = b.name;
            btn.textContent = b.name;
            btn.addEventListener('click', this.brushHandler.bind(this));
            brushToolbar.appendChild(btn)
        });
    },

    getBrushByName: function(brushName) {
        const brush = this.brushes.find(b => {
            return b.name === brushName;
        });

        return brush;
    },

    selectBrush: function(brushName) {
        const brush = this.getBrushByName(brushName);

        if (typeof brush === 'undefined') {
            console.log(`could not find brush ${brushName}`);
            this.draw = function(strokeStyle, x, y) {
                this.ctx.lineJoin = this.ctx.lineCap = 'round';
                this.ctx.strokeStyle = strokeStyle;
                this.ctx.lineTo(x, y);
                this.ctx.stroke();
            };
        } else {
            this.currentBrushName = brushName;
            this.draw = brush.draw.bind(brush, this.ctx);
        }
    },

    brushHandler: function(e) {
        this.selectBrush(e.currentTarget.id);
    },

    setStatus: function(status) {
        this.statusEl.innerHTML = status;
    },

    setupSocket: function() {

        let room = this;

        room.socket.on("connect", function() {
            room.socket.emit("join", room.id);
        });
        room.socket.on("clear", function() {
            room.clearHandler(null, true);
        });
        room.socket.on("draw", function(message) {
            room.history.push(message.stroke);

            room.ctx.beginPath();

            room.selectBrush(message.stroke[0].brushName);
            for (let p of message.stroke)
                room.draw(p.strokeStyle, p.x, p.y);

            room.ctx.closePath();
        });
        room.socket.on("load-history", function(message) {

            room.history = message.history;
            room.replayHistory(room.history);

        });
    },

    init: function() {
        this.canvas = document.getElementById('canvas');
        this.ctx = canvas.getContext('2d');

        // add drawing listeners
        this.canvas.addEventListener('mousedown', e => {
            this.history.push([]);
            this.isDrawing = true;
            this.canvas.style.cursor = 'crosshair';
            this.ctx.beginPath();
            this.ctx.moveTo(e.offsetX, e.offsetY);
        });

        this.canvas.addEventListener('mousemove', e => {
            if (!this.isDrawing) return;
            const hisIdx = this.history.length - 1;
            this.history[hisIdx].push({
                brushName: this.currentBrushName,
                x: e.offsetX ,
                y: e.offsetY ,
                strokeStyle: this.strokeStyle,
            });
            this.draw(this.strokeStyle, e.offsetX, e.offsetY);
        });

        this.canvas.addEventListener('mouseup', e => {
            this.ctx.closePath();
            this.canvas.style.cursor = 'auto';
            this.isDrawing = false;
            this.socket.emit("draw", {

                stroke: this.history[this.history.length - 1]

            });
        });

        const btn = document.getElementById('clearButton');
        btn.addEventListener('click', this.clearHandler.bind(this));

        // no need to keep a reference after we add the listener
        const palette = document.getElementById('palette');
        palette.addEventListener('click', this.paletteHandler.bind(this));

        // document.getElementById('rgb').value = "not valid";
        const rgbTextField = document.getElementById("rgb");
        rgbTextField.addEventListener("click", function() {
            // console.log("hai clickato");
            rgbTextField.value = "";

        });

        const rgbPickerButton = document.getElementById('rgbPickerButton');
        rgbPickerButton.addEventListener('click', this.rgbPickerHandler.bind(this));

        // const rgbPickerButton = document.getElementById("rgbPickerButton");
        // rgbPickerButton.addEventListener('click', function(e) {
        //    console.log("hai premuto rgbPickerButton");
        // });

        this.setupBrushes();
        this.selectBrush('Pen');

        this.setupSocket();
    }
};

app.init();
<commit_msg>implemented undo and redo buttons<commit_after>// Enter your clientside JavaScript code for the single room page here

// You are allowed to use the code you produced during midterm 1 (app.js) instead
// of the following skeleton code

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

const app = {
    strokeStyle: 'black',
    isDrawing: false,
    history: [],
    undohistory: [],

    socket: io(),
    // get id fron url
    id: window.location.pathname.split('/')[2],

    // will be overwritten by brushes
    draw: function() {},

    clearCanvas: function() {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    },

    /**
     * Takes an array of arrays of lineSegments
     * and draws them on canvas
     * @param history
     */
    replayHistory: function(history) {
        history.forEach(this.drawLine.bind(this));
    },

    /**
     * Takes an array of lineSegments that form a path
     * and draws them on canvas
     * @param lineSegs
     */
    drawLine: function(lineSegs) {
        if (lineSegs.length == 0) return;
        this.ctx.beginPath();
        this.selectBrush(lineSegs[0].brushName);
        lineSegs.forEach(seg => {
            this.draw(seg.strokeStyle, seg.x, seg.y);
        });
        this.ctx.closePath();
    },

    clearHandler: function(e, no) {
        this.clearCanvas();
        this.history = [];
        if (!no)
            this.socket.emit("clear", this.id);
    },

    paletteHandler: function(e) {
        if (!e.target.classList.contains('p-color')) return;
        this.strokeStyle = e.target.dataset.color;
        // console.log(e.target.dataset.color);
    },

    undoHandler: function(e) {
        if (!this.history.length) return;
        this.undohistory.push(this.history.pop());
        this.clearCanvas();
        this.replayHistory(this.history);
    },

    redoHandler: function (e) {
        if (!this.undohistory.length) return;
        this.history.push(this.undohistory.pop());
        this.clearCanvas();
        this.replayHistory(this.history);
    },

    rgbPickerHandler: function(e) {
        // if (!e.target.classList.contains('p-color')) return;
        // this.strokeStyle = e.target.dataset.color;
        // console.log("hai premuto rgbpicker");
        let rgbInsertedColor = document.getElementById('rgb').value;
        // if (rgbInsertedColor.length = 7)
            this.strokeStyle = this.colorHexToRgb(rgbInsertedColor);
    },

    colorHexToRgb: function(color) {
        if (color.length != 7) {
            console.log("Invalid color");
            document.getElementById('rgb').value = "not valid";
            return;
        }

        console.log("rbgcolorpicker");
        let red = color.substr(1, 2);
        red = parseInt(red, 16);
        // console.log("red: " + red);
        let green = color.substr(3, 2);
        // console.log("b4 green: ", green);
        green = parseInt(green, 16);
        // console.log("green: " + green);
        let blue = color.substr(5, 2);
        blue = parseInt(blue, 16);
        // console.log("blue: " + blue);
        return "rgb(" + red + ", " + green + ", " + blue + ")";
    },

    setupBrushes: function() {
        const brushToolbar = document.getElementById('brush-toolbar');
        this.brushes = window.brushes;

        // extend disc brush
        const randomDiscBrush = Object.create(this.brushes[1]);
        randomDiscBrush.name = "Random Disc";
        randomDiscBrush.getRadius = function() {
                return getRandomInt(10, 30)
            },
            randomDiscBrush.getOpacity = function() {
                return Math.random()
            },

            this.brushes.push(randomDiscBrush);

        // extend star brush
        const randomStarBrush = Object.create(this.brushes[2]);
        randomStarBrush.name = "Random Star";
        randomStarBrush.getOptions = function() {
            return {
                length: 15,
                angle: getRandomInt(0, 180),
                width: getRandomInt(1, 10),
                opacity: Math.random(),
                scale: getRandomInt(1, 20) / 10,
                color: ('rgb(' + getRandomInt(0, 255) + ',' + getRandomInt(0, 255) + ',' + getRandomInt(0, 255) + ')')
            }
        };

        this.brushes.push(randomStarBrush);

        //add brush buttons
        this.brushes.forEach(b => {
            const btn = document.createElement('BUTTON');
            btn.id = b.name;
            btn.textContent = b.name;
            btn.addEventListener('click', this.brushHandler.bind(this));
            brushToolbar.appendChild(btn)
        });
    },

    getBrushByName: function(brushName) {
        const brush = this.brushes.find(b => {
            return b.name === brushName;
        });

        return brush;
    },

    selectBrush: function(brushName) {
        const brush = this.getBrushByName(brushName);

        if (typeof brush === 'undefined') {
            console.log(`could not find brush ${brushName}`);
            this.draw = function(strokeStyle, x, y) {
                this.ctx.lineJoin = this.ctx.lineCap = 'round';
                this.ctx.strokeStyle = strokeStyle;
                this.ctx.lineTo(x, y);
                this.ctx.stroke();
            };
        } else {
            this.currentBrushName = brushName;
            this.draw = brush.draw.bind(brush, this.ctx);
        }
    },

    brushHandler: function(e) {
        this.selectBrush(e.currentTarget.id);
    },

    setStatus: function(status) {
        this.statusEl.innerHTML = status;
    },

    setupSocket: function() {

        let room = this;

        room.socket.on("connect", function() {
            room.socket.emit("join", room.id);
        });
        room.socket.on("clear", function() {
            room.clearHandler(null, true);
        });
        room.socket.on("draw", function(message) {
            room.history.push(message.stroke);

            room.ctx.beginPath();

            room.selectBrush(message.stroke[0].brushName);
            for (let p of message.stroke)
                room.draw(p.strokeStyle, p.x, p.y);

            room.ctx.closePath();
        });
        room.socket.on("load-history", function(message) {

            room.history = message.history;
            room.replayHistory(room.history);

        });
    },

    init: function() {
        this.canvas = document.getElementById('canvas');
        this.ctx = canvas.getContext('2d');

        // add drawing listeners
        this.canvas.addEventListener('mousedown', e => {
            this.history.push([]);
            this.isDrawing = true;
            this.canvas.style.cursor = 'crosshair';
            this.ctx.beginPath();
            this.ctx.moveTo(e.offsetX, e.offsetY);
        });

        this.canvas.addEventListener('mousemove', e => {
            if (!this.isDrawing) return;
            const hisIdx = this.history.length - 1;
            this.history[hisIdx].push({
                brushName: this.currentBrushName,
                x: e.offsetX ,
                y: e.offsetY ,
                strokeStyle: this.strokeStyle,
            });
            this.draw(this.strokeStyle, e.offsetX, e.offsetY);
        });

        this.canvas.addEventListener('mouseup', e => {
            this.ctx.closePath();
            this.canvas.style.cursor = 'auto';
            this.isDrawing = false;
            this.socket.emit("draw", {

                stroke: this.history[this.history.length - 1]

            });
        });

        const btn = document.getElementById('clearButton');
        btn.addEventListener('click', this.clearHandler.bind(this));

        // no need to keep a reference after we add the listener
        const palette = document.getElementById('palette');
        palette.addEventListener('click', this.paletteHandler.bind(this));

        // document.getElementById('rgb').value = "not valid";
        const rgbTextField = document.getElementById("rgb");
        rgbTextField.addEventListener("click", function() {
            // console.log("hai clickato");
            rgbTextField.value = "#";

        });

        const rgbPickerButton = document.getElementById('rgbPickerButton');
        rgbPickerButton.addEventListener('click', this.rgbPickerHandler.bind(this));

        // const rgbPickerButton = document.getElementById("rgbPickerButton");
        // rgbPickerButton.addEventListener('click', function(e) {
        //    console.log("hai premuto rgbPickerButton");
        // });

        // undo
        const undoButton = document.getElementById('undoButton');
        undoButton.addEventListener('click', this.undoHandler.bind(this));

        const redoButton = document.getElementById('redoButton');
        redoButton.addEventListener('click', this.redoHandler.bind(this));

        this.setupBrushes();
        this.selectBrush('Pen');

        this.setupSocket();
    }
};

app.init();
<|endoftext|>


<commit_before>$(document).ready(function () {

    var accommodationForm = [
        '
' +
            '
' +
            '
' +
            '
' +
                '

' +
                '
' +
                '+ Добавить тип комнаты' +
            '
' +
            '
' +
                '
' +
                'x Убрать вариант проживания' +
            '
' +
        '
'
    ].join();

    var col1 = [
        '
' +
            'Город' +
            '
' +
            '<select class="form-control city">' +
            '</select>' +
        '
' +
        '
' +
            'Гостиница' +
            '
' +
            '<select class="form-control hotel">' +
            '</select>' +
        '
' +
        '
' +
            'Дата заселения' +
            '
' +
            '<input type="text" placeholder="dd-mm-yyyy" class="form-control moveIn"/>' +
        '
' +
        '
' +
            'Дата выезда' +
            '
' +
            '<input type="text" placeholder="dd-mm-yyyy" class="form-control moveOut"/>' +
        '
'
    ].join();

    var room = [
        '
' +
            '
' +
                'Тип комнаты
' +
                '<select class="form-control roomType">' +
                '</select>' +
            '
' +
            '
' +
                'Кол-во номеров
' +
                '<input type="text" placeholder="Кол-во номеров" class="form-control roomsAmount"/>' +
            '
' +
            '
' +
                'x' +
            '
' +
        '
'
    ].join();

    var labelAcc    = 'accommodation';
    var labelRoom   = 'room';

    var accIds = [];
    var accId = $('#playground>.accommodationForm').size();

    var roomIds = [];
    var roomId  = $('#rooms>.roomForm').size();

    var example = [
        {
            city: "",
            hotel: "",
            moveIn: moment,
            moveOut: moment(),
            rooms: [
                {
                    type: "",
                    amount: 0,
                    prisePerOne: 0,
                    prisePerAll: 0
                }
            ],
            prisePerDay: 0,
            priseTotal: 0
        }
    ];

    addAcc = function () {

        var city;
        var hotel;
        var moveIn;
        var moveOut;

        city        = labelAcc + "_city_" + accId;
        hotel       = labelAcc + "_hotel_" + accId;
        moveIn      = labelAcc + "_moveIn_" + accId;
        moveOut     = labelAcc + "_moveOut_" + accId;

        // accommodation
        var form = $(accommodationForm);
        var col  = $(col1);

        form.attr('id', 'accommodationForm_'+accId);

        $('.city', col).attr({
            'id': city,
            'name': city
        });

        $('.hotel', col).attr({
            'id': hotel,
            'name': hotel
        });

        $('.moveIn', col).attr({
            'id': moveIn,
            'name': moveIn
        }).datepicker({format : "dd-mm-yyyy"});

        $('.moveOut', col).attr({
            'id': moveOut,
            'name': moveOut
        }).datepicker({format : "dd-mm-yyyy"});

        $('.addRoom', form).attr('onclick', 'addRoom('+accId+');');

        $('.removeAcc', form).attr('onclick', 'removeAcc('+accId+');');

        // drop-down lists init
        var cities = $('#cities').html();
        var hotels = $('#hotels').html();

        // lists into fields
        $('.city', col).html(cities);
        $('.hotel', col).html(hotels);

        // fields into form
        $('.placeForCol1', form).html(col);

        // publish
        $('#playground').append(form);

        accIds.push(accId);

        accId++;

        return false;
    };

    removeAcc = function(accId) {

        $('#accommodationForm_'+accId).remove();

        var index   = accIds.indexOf(accId);
        var inList  = index > -1;
        if (inList) accIds.splice(index, 1);

        return false;
    };

    addRoom = function(accId) {

        var rm = $(room);

        var roomType;
        var roomsAmount;

        roomType    = labelRoom + "_roomType_" + accId + "_" +roomId;

        roomsAmount = labelRoom + "_roomAmount_" + accId + "_" + roomId ;

        var roomList = $('#roomList').html();

        $('.roomType', rm).html(roomList);
        rm.attr('id', 'roomForm_'+roomId);

        $('.roomType', rm).attr({
            'id': roomType,
            'name': roomType
        });

        $('.roomsAmount', rm).attr({
            'id': roomsAmount,
            'name': roomsAmount
        });
        $('.removeRoom', rm).attr('onclick', 'removeRoom('+accId+', '+roomId+');');

        $('#rooms', '#accommodationForm_'+accId).append(rm);

        roomIds.push(roomId);

        roomId++;

        return false;
    };

    removeRoom = function (accId, roomId) {

        $('#'+labelRoom+'_roomType_'+accId+'_'+roomId).closest('.roomForm').remove();
        var index   = roomIds.indexOf(roomId);
        var inList  = index > -1;
        if (inList) roomIds.splice(index, 1);

        return false;

    };

    checkout = function () {

        var data = parseStuff();

        $.getJSON('/api/hotels', function (prises) {

            var completeData = countStuff(data, prises);

            $.ajax({
                url: "/test",
                type: "POST",
                dataType: "json",
                data: JSON.stringify(completeData),
                contentType: "application/json",
                cache: false,
                timeout: 5000,
                complete: function() {
                    //called when complete
                    console.log('process complete');
                },

                success: function(data) {
                    console.log('process sucess');
                    $('#myModal').modal('show');
                    $('#checkoutData').html(JSON.stringify(data, null, '\t'));
                },

                error: function(err) {
                    console.log('process error');
                    console.log(err);
                }
            });
        });
    };

    function parseStuff () {

        var accs = [];

        accIds.forEach(function (aid) {

            var city        = $("#" + labelAcc + "_city_" + aid);
            var hotel       = $("#" + labelAcc + "_hotel_" + aid);
            var moveIn      = $("#" + labelAcc + "_moveIn_" + aid);
            var moveOut     = $("#" + labelAcc + "_moveOut_" + aid);

            var momentIn, momentOut;

            // checks if acc has such fuekd and creates moment date obj
            if (moveIn.length) momentIn = moment(moveIn.val(), "DD-MM-YYYY");

            if (moveOut.length) momentOut = moment(moveOut.val(), "DD-MM-YYYY");

            var daysWithinAcc = momentOut.diff(momentIn, 'days');

            var rooms = [];

            roomIds.forEach(function (rid) {

                var roomType    = $("#" + labelRoom + "_roomType_" + aid + "_" + rid);
                var roomsAmount = $("#" + labelRoom + "_roomAmount_" + aid + "_" + rid);

                if (roomType.length || roomsAmount.length) {

                    rooms.push({
                        type: roomType.val(),
                        amount: roomsAmount.val(),
                        prisePerRoomPerDay: 0,
                        prisePerAllRoomsPerDay: 0
                    });
                }
            });

            accs.push({
                city: city.val(),
                hotel: hotel.val(),
                days: daysWithinAcc,
                moveIn: moveIn.val(),
                moveOut: moveOut.val(),
                rooms: rooms,
                prisePerDay: 0,
                priseTotal: 0
            });

        });

        return accs;
    }

    function countStuff (data, prises) {

        var accs = data;

        accs.forEach(function (acc) {

            var prisePerRoomPerDay = 0;
            var prisePerAllRoomsPerDay = 0;
            var prisePerDay = 0;
            var priseTotal = 0;

            acc.rooms.forEach(function (r) {

                prises.forEach(function (pr) {

                    if (pr.hotelCodename == acc.hotel) {

                        // prise per day for current toomType and hotel
                        prisePerRoomPerDay = pr.roomType[0][r.type].eur;
                    }
                });

                // prise per all days within room
                prisePerAllRoomsPerDay = r.amount * prisePerRoomPerDay;

                // prise per all rooms per one day
                prisePerDay += prisePerAllRoomsPerDay;

                r.prisePerRoomPerDay = prisePerRoomPerDay;
                r.prisePerAllRoomsPerDay = prisePerAllRoomsPerDay;
            });

            priseTotal = prisePerDay * acc.days;

            acc.prisePerDay = prisePerDay;
            acc.priseTotal = priseTotal;

        });

        return accs;
    }
});<commit_msg>little fixes<commit_after>$(document).ready(function () {

    var accommodationForm = [
        '
' +
            '
' +
            '
' +
            '
' +
                '

' +
                '
' +
                '+ Добавить тип комнаты' +
            '
' +
            '
' +
                '
' +
                'x Убрать вариант проживания' +
            '
' +
        '
'
    ].join();

    var col1 = [
        '
' +
            'Город' +
            '
' +
            '<select class="form-control city">' +
            '</select>' +
        '
' +
        '
' +
            'Гостиница' +
            '
' +
            '<select class="form-control hotel">' +
            '</select>' +
        '
' +
        '
' +
            'Дата заселения' +
            '
' +
            '<input type="text" placeholder="dd-mm-yyyy" class="form-control moveIn"/>' +
        '
' +
        '
' +
            'Дата выезда' +
            '
' +
            '<input type="text" placeholder="dd-mm-yyyy" class="form-control moveOut"/>' +
        '
'
    ].join();

    var room = [
        '
' +
            '
' +
                'Тип комнаты
' +
                '<select class="form-control roomType">' +
                '</select>' +
            '
' +
            '
' +
                'Кол-во номеров
' +
                '<input type="text" placeholder="Кол-во номеров" class="form-control roomsAmount"/>' +
            '
' +
            '
' +
                'x' +
            '
' +
        '
'
    ].join();

    var labelAcc    = 'accommodation';
    var labelRoom   = 'room';

    var accIds = [];
    var accId = $('#playground>.accommodationForm').size();

    var roomIds = [];
    var roomId  = $('#rooms>.roomForm').size();

    var example = [
        {
            city: "",
            hotel: "",
            moveIn: moment,
            moveOut: moment(),
            rooms: [
                {
                    type: "",
                    amount: 0,
                    prisePerOne: 0,
                    prisePerAll: 0
                }
            ],
            prisePerDay: 0,
            priseTotal: 0
        }
    ];

    addAcc = function () {

        var city;
        var hotel;
        var moveIn;
        var moveOut;

        city        = labelAcc + "_city_" + accId;
        hotel       = labelAcc + "_hotel_" + accId;
        moveIn      = labelAcc + "_moveIn_" + accId;
        moveOut     = labelAcc + "_moveOut_" + accId;

        // accommodation
        var form = $(accommodationForm);
        var col  = $(col1);

        form.attr('id', 'accommodationForm_'+accId);

        $('.city', col).attr({
            'id': city,
            'name': city
        });

        $('.hotel', col).attr({
            'id': hotel,
            'name': hotel
        });

        $('.moveIn', col).attr({
            'id': moveIn,
            'name': moveIn
        }).datepicker({format : "dd-mm-yyyy"});

        $('.moveOut', col).attr({
            'id': moveOut,
            'name': moveOut
        }).datepicker({format : "dd-mm-yyyy"});

        $('.addRoom', form).attr('onclick', 'addRoom('+accId+');');

        $('.removeAcc', form).attr('onclick', 'removeAcc('+accId+');');

        // drop-down lists init
        var cities = $('#cities').html();
        var hotels = $('#hotels').html();

        // lists into fields
        $('.city', col).html(cities);
        $('.hotel', col).html(hotels);

        // fields into form
        $('.placeForCol1', form).html(col);

        // publish
        $('#playground').append(form);

        accIds.push(accId);

        accId++;

        return false;
    };

    removeAcc = function(accId) {

        $('#accommodationForm_'+accId).remove();

        var index   = accIds.indexOf(accId);
        var inList  = index > -1;
        if (inList) accIds.splice(index, 1);

        return false;
    };

    addRoom = function(accId) {

        var rm = $(room);

        var roomType;
        var roomsAmount;

        roomType    = labelRoom + "_roomType_" + accId + "_" +roomId;

        roomsAmount = labelRoom + "_roomAmount_" + accId + "_" + roomId ;

        var roomList = $('#roomList').html();

        $('.roomType', rm).html(roomList);
        rm.attr('id', 'roomForm_'+roomId);

        $('.roomType', rm).attr({
            'id': roomType,
            'name': roomType
        });

        $('.roomsAmount', rm).attr({
            'id': roomsAmount,
            'name': roomsAmount
        });
        $('.removeRoom', rm).attr('onclick', 'removeRoom('+accId+', '+roomId+');');

        $('#rooms', '#accommodationForm_'+accId).append(rm);

        roomIds.push(roomId);

        roomId++;

        return false;
    };

    removeRoom = function (accId, roomId) {

        $('#'+labelRoom+'_roomType_'+accId+'_'+roomId).closest('.roomForm').remove();
        var index   = roomIds.indexOf(roomId);
        var inList  = index > -1;
        if (inList) roomIds.splice(index, 1);

        return false;

    };

    checkout = function () {

        var data = parseStuff();

        $.getJSON('/api/hotels', function (prises) {

            var completeData = countStuff(data, prises);

            $.ajax({
                url: "/test",
                type: "POST",
                dataType: "json",
                data: JSON.stringify(completeData),
                contentType: "application/json",
                cache: false,
                timeout: 5000,
                complete: function() {
                    //called when complete
                    console.log('process complete');
                },

                success: function(data) {
                    console.log('process sucess');
                    $('#myModal').modal('show');
                    $('#checkoutData').html(JSON.stringify(data, null, '\t'));
                },

                error: function(err) {
                    console.log('process error');
                    console.log(err);
                }
            });
        });
    };

    function parseStuff () {

        var accs = [];

        accIds.forEach(function (aid) {

            var city        = $("#" + labelAcc + "_city_" + aid);
            var hotel       = $("#" + labelAcc + "_hotel_" + aid);
            var moveIn      = $("#" + labelAcc + "_moveIn_" + aid);
            var moveOut     = $("#" + labelAcc + "_moveOut_" + aid);

            var momentIn, momentOut;

            // checks if acc has such fuekd and creates moment date obj
            if (moveIn.length) momentIn = moment(moveIn.val(), "DD-MM-YYYY");

            if (moveOut.length) momentOut = moment(moveOut.val(), "DD-MM-YYYY");

            var daysWithinAcc = momentOut.diff(momentIn, 'days');

            var rooms = [];

            roomIds.forEach(function (rid) {

                var roomType    = $("#" + labelRoom + "_roomType_" + aid + "_" + rid);
                var roomsAmount = $("#" + labelRoom + "_roomAmount_" + aid + "_" + rid);

                if (roomType.length || roomsAmount.length) {

                    rooms.push({
                        type: roomType.val(),
                        amount: roomsAmount.val()
                    });
                }
            });

            accs.push({
                city: city.val(),
                hotel: hotel.val(),
                days: daysWithinAcc,
                moveIn: moveIn.val(),
                moveOut: moveOut.val(),
                rooms: rooms
            });

        });

        return accs;
    }

    function countStuff (data, prises) {

        var accs = data;

        var priseTotal = 0;

        accs.forEach(function (acc) {

            var prisePerRoomPerDay = 0;
            var prisePerAllRoomsPerDay = 0;
            var prisePerDay = 0;
            var prisePerAcc = 0;

            acc.rooms.forEach(function (r) {

                prises.forEach(function (pr) {

                    if (pr.hotelCodename == acc.hotel) {

                        // prise per day for current toomType and hotel
                        prisePerRoomPerDay = pr.roomType[0][r.type].eur;
                    }
                });

                // prise per all days within room
                prisePerAllRoomsPerDay = r.amount * prisePerRoomPerDay;

                // prise per all rooms per one day
                prisePerDay += prisePerAllRoomsPerDay;

                r.prisePerRoomPerDay = prisePerRoomPerDay;
                r.prisePerAllRoomsPerDay = prisePerAllRoomsPerDay;
            });

            prisePerAcc = prisePerDay * acc.days;
            priseTotal += prisePerAcc;

            acc.prisePerDay = prisePerDay;
            acc.prisePerAcc = prisePerAcc;

        });

        return {
            totalPriseForAccs: priseTotal,
            accs: accs
        };
    }
});<|endoftext|>


<commit_before>
var q = require('q');
var device_curator = require('../lib/device_curator');
var utils = require('./utils/utils');
var qExec = utils.qExec;
var labjack_nodejs = require('labjack-nodejs');
var ljDevice = labjack_nodejs.getDeviceRef();
var ljm = labjack_nodejs.driver();
var modbus_map = require('ljswitchboard-modbus_map').getConstants();

var device;

var criticalError = false;
var stopTest = function(test, err) {
	test.ok(false, err);
	criticalError = true;
	test.done();
};

var deviceFound = false;
var performTests = true;

var firmware_links = require('./firmware_links');
var fws = firmware_links.firmwareLinks.T7;
var driver_const = require('ljswitchboard-ljm_driver_constants');
var device_events = driver_const.device_curator_constants;
var DEVICE_DISCONNECTED = device_events.DEVICE_DISCONNECTED;
var DEVICE_RECONNECTED = device_events.DEVICE_RECONNECTED;

var device_tests = {
	'setUp': function(callback) {
		if(criticalError) {
			process.exit(1);
		} else {
			callback();
		}
	},
	'tearDown': function(callback) {
		callback();
	},
	'createDevice': function(test) {
		console.log('');
		console.log('**** t7_upgrade_test ****');
		try {
			device = new device_curator.device();
		} catch(err) {
			stopTest(test, err);
		}
		test.done();
	},
	'openDevice': function(test) {
		var td = {
			'dt': 'LJM_dtT7',
			'ct': 'LJM_ctUSB',
			'id': 'LJM_idANY'
		};
		// td.ct = 'LJM_ctWIFI';
		// td.id = 470010548;

		device.open(td.dt, td.ct, td.id)
		.then(function(res) {
			console.log(
				"  - Opened T7:",
				res.productType,
				res.connectionTypeName,
				res.serialNumber,
				parseFloat(res.FIRMWARE_VERSION.toFixed(4))
			);
			deviceFound = true;
			test.done();
		}, function(err) {
			console.log("  - Failed to open device", ljm.errToStrSync(err));
			performTests = false;
			test.done();
		});
	},
	'checkDeviceInfo': function(test) {
		device.getDeviceAttributes()
		.then(function(res) {
			var keys = Object.keys(res);
			test.strictEqual(res.deviceType, 7);
			test.strictEqual(res.deviceTypeString, 'LJM_dtT7');
			test.done();
		});
	},
	'upgradeFirmware': function(test) {
		var fwVersionNum = 1.0176;
		var fwURL = fws[fwVersionNum.toFixed(4)];
		console.log('fwURL', fwURL);
		var lastPercent = 0;
		var percentListener = function(value) {
			var defered = q.defer();
			// console.log("  - ", value.toString() + '%');
			lastPercent = value;
			defered.resolve();
			return defered.promise;
		};
		var stepListener = function(value) {
			var defered = q.defer();
			console.log("  - " + value.toString());
			defered.resolve();
			return defered.promise;
		};
		var deviceDisconnectEventReceived = false;
		var deviceReconnectEventReceived = false;
		device.on(DEVICE_DISCONNECTED, function(data) {
			console.log('  - Device disconnected');
			deviceDisconnectEventReceived = true;
		});
		device.on(DEVICE_RECONNECTED, function(data) {
			console.log('  - Device reconnected');
			deviceReconnectEventReceived = true;
		});

		device.updateFirmware(fwURL, percentListener, stepListener)
		.then(
			function(res) {
				// The result is a new device object
				// console.log('Upgrade Success', res);
				// console.log('Number of created devices', ljDevice.getNumCreatedDevices());
				test.strictEqual(lastPercent, 100, 'Highest Percentage isnt 100%');
				var ljmDevice = device.getDevice();
				// console.log(
				// 	'Reading device FW version',
				// 	ljmDevice.handle,
				// 	ljmDevice.deviceType,
				// 	ljmDevice.isHandleValid
				// );

				// Make sure that the device disconnect & reconnect events get
				// fired.
				test.ok(deviceDisconnectEventReceived, 'Disconnect event should have been detected');
				test.ok(deviceReconnectEventReceived, 'Reconnect event should have been detected');
				device.read('FIRMWARE_VERSION')
				.then(function(res) {
					test.strictEqual(res.toFixed(4), fwVersionNum.toFixed(4), 'Firmware Not Upgraded');
					test.done();
				});
			}, function(err) {
				console.log("Failed to upgrade (upgrade test)", err);
				console.log('');
				console.log('');
				test.ok(true, 'Failed to upgrade device: ' + JSON.stringify(err));
				device.read('DEVICE_NAME_DEFAULT')
				.then(function(res) {
					console.log('Device is still responding to messages', res);
					test.done();
				}, function(err) {
					console.log('Device is not responding anymore', err);
					test.done();
				});
			}
		);
	},
	'closeDevice': function(test) {
		// setTimeout(function() {
			device.close()
			.then(function() {
				test.done();
			}, function(err) {
				console.log("Failure");
				test.ok(false);
				test.done();
			});
		// }, 5000);

	},
};

var tests = {};
var functionKeys = Object.keys(device_tests);
var getTest = function(testFunc, key) {
	var execTest = function(test) {
		// console.log("  > t7_basic_test - " + key);
		if(performTests) {
			testFunc(test);
		} else {
			console.log("  * Not Executing!!");
			try {
				test.done();
			} catch(err) {
				console.log("HERE", err);
			}
		}
	};
	return execTest;
};
functionKeys.forEach(function(functionKey) {
	if ((functionKey !== 'setUp') && (functionKey !== 'tearDown')) {
		tests[functionKey] = getTest(device_tests[functionKey], functionKey);
	} else {
		tests[functionKey] = device_tests[functionKey];
	}
});
exports.tests = tests;<commit_msg>Changed a print statement.<commit_after>
var q = require('q');
var device_curator = require('../lib/device_curator');
var utils = require('./utils/utils');
var qExec = utils.qExec;
var labjack_nodejs = require('labjack-nodejs');
var ljDevice = labjack_nodejs.getDeviceRef();
var ljm = labjack_nodejs.driver();
var modbus_map = require('ljswitchboard-modbus_map').getConstants();

var device;

var criticalError = false;
var stopTest = function(test, err) {
	test.ok(false, err);
	criticalError = true;
	test.done();
};

var deviceFound = false;
var performTests = true;

var firmware_links = require('./firmware_links');
var fws = firmware_links.firmwareLinks.T7;
var driver_const = require('ljswitchboard-ljm_driver_constants');
var device_events = driver_const.device_curator_constants;
var DEVICE_DISCONNECTED = device_events.DEVICE_DISCONNECTED;
var DEVICE_RECONNECTED = device_events.DEVICE_RECONNECTED;

var device_tests = {
	'setUp': function(callback) {
		if(criticalError) {
			process.exit(1);
		} else {
			callback();
		}
	},
	'tearDown': function(callback) {
		callback();
	},
	'createDevice': function(test) {
		console.log('');
		console.log('**** t7_upgrade_test ****');
		try {
			device = new device_curator.device();
		} catch(err) {
			stopTest(test, err);
		}
		test.done();
	},
	'openDevice': function(test) {
		var td = {
			'dt': 'LJM_dtT7',
			'ct': 'LJM_ctUSB',
			'id': 'LJM_idANY'
		};
		// td.ct = 'LJM_ctWIFI';
		// td.id = 470010548;

		device.open(td.dt, td.ct, td.id)
		.then(function(res) {
			console.log(
				"  - Opened T7:",
				res.productType,
				res.connectionTypeName,
				res.serialNumber,
				parseFloat(res.FIRMWARE_VERSION.toFixed(4))
			);
			deviceFound = true;
			test.done();
		}, function(err) {
			console.log("  - Failed to open device", ljm.errToStrSync(err));
			performTests = false;
			test.done();
		});
	},
	'checkDeviceInfo': function(test) {
		device.getDeviceAttributes()
		.then(function(res) {
			var keys = Object.keys(res);
			test.strictEqual(res.deviceType, 7);
			test.strictEqual(res.deviceTypeString, 'LJM_dtT7');
			test.done();
		});
	},
	'upgradeFirmware': function(test) {
		var fwVersionNum = 1.0176;
		var fwURL = fws[fwVersionNum.toFixed(4)];
		console.log('  - fwURL (in test file)', fwURL);
		var lastPercent = 0;
		var percentListener = function(value) {
			var defered = q.defer();
			// console.log("  - ", value.toString() + '%');
			lastPercent = value;
			defered.resolve();
			return defered.promise;
		};
		var stepListener = function(value) {
			var defered = q.defer();
			console.log("  - " + value.toString());
			defered.resolve();
			return defered.promise;
		};
		var deviceDisconnectEventReceived = false;
		var deviceReconnectEventReceived = false;
		device.on(DEVICE_DISCONNECTED, function(data) {
			console.log('  - Device disconnected');
			deviceDisconnectEventReceived = true;
		});
		device.on(DEVICE_RECONNECTED, function(data) {
			console.log('  - Device reconnected');
			deviceReconnectEventReceived = true;
		});

		device.updateFirmware(fwURL, percentListener, stepListener)
		.then(
			function(res) {
				// The result is a new device object
				// console.log('Upgrade Success', res);
				// console.log('Number of created devices', ljDevice.getNumCreatedDevices());
				test.strictEqual(lastPercent, 100, 'Highest Percentage isnt 100%');
				var ljmDevice = device.getDevice();
				// console.log(
				// 	'Reading device FW version',
				// 	ljmDevice.handle,
				// 	ljmDevice.deviceType,
				// 	ljmDevice.isHandleValid
				// );

				// Make sure that the device disconnect & reconnect events get
				// fired.
				test.ok(deviceDisconnectEventReceived, 'Disconnect event should have been detected');
				test.ok(deviceReconnectEventReceived, 'Reconnect event should have been detected');
				device.read('FIRMWARE_VERSION')
				.then(function(res) {
					test.strictEqual(res.toFixed(4), fwVersionNum.toFixed(4), 'Firmware Not Upgraded');
					test.done();
				});
			}, function(err) {
				console.log("Failed to upgrade (upgrade test)", err);
				console.log('');
				console.log('');
				test.ok(true, 'Failed to upgrade device: ' + JSON.stringify(err));
				device.read('DEVICE_NAME_DEFAULT')
				.then(function(res) {
					console.log('Device is still responding to messages', res);
					test.done();
				}, function(err) {
					console.log('Device is not responding anymore', err);
					test.done();
				});
			}
		);
	},
	'closeDevice': function(test) {
		// setTimeout(function() {
			device.close()
			.then(function() {
				test.done();
			}, function(err) {
				console.log("Failure");
				test.ok(false);
				test.done();
			});
		// }, 5000);

	},
};

var tests = {};
var functionKeys = Object.keys(device_tests);
var getTest = function(testFunc, key) {
	var execTest = function(test) {
		// console.log("  > t7_basic_test - " + key);
		if(performTests) {
			testFunc(test);
		} else {
			console.log("  * Not Executing!!");
			try {
				test.done();
			} catch(err) {
				console.log("HERE", err);
			}
		}
	};
	return execTest;
};
functionKeys.forEach(function(functionKey) {
	if ((functionKey !== 'setUp') && (functionKey !== 'tearDown')) {
		tests[functionKey] = getTest(device_tests[functionKey], functionKey);
	} else {
		tests[functionKey] = device_tests[functionKey];
	}
});
exports.tests = tests;<|endoftext|>


<commit_before>'use strict';
describe.only("high level REST requests on JugglingDB", function () {
    var schema;
    before(function (done) {
        _.each(require.cache, function (mod, modName) {
            if (~modName.indexOf('formage') || ~modName.indexOf('mongoose') || ~modName.indexOf('jugglingdb'))
                delete require.cache[modName];
        });
        var formage = require('../index');
        var Schema = require("jugglingdb").Schema;
        schema = new Schema("mssql", {host: "(LocalDB)\\v11.0", database: "maskar"});
        if (!schema.connect)
            schema = new Schema("memory");
        schema.on("connected", function () {
            var express = require('express');
            var app = express();
            var AppliesTo = schema.define("AppliesTo", {
                AppliesToID: {type: Number, primaryKey: true},
                Title: {type: String, limit: 100},
                Identifier: {type: String, limit: 100},
                Editable: {type: Number}
            });
            AppliesTo.validatesPresenceOf('Title');
            formage.init(app, express, {AppliesTo: AppliesTo}, {
                title: 'Formage Example',
                default_section: 'Main',
                admin_users_gui: true,
                db_layer_type: 'jugglingdb'
            });
            mock_req_proto.app = module.admin_app = app.admin_app;
            done()
        });
    });

    describe("pages", function () {
        it("Mock test document page", function (done) {
            var mock_req = _.defaults({
                url: "/model/AppliesTo/document/new",
                method: "GET"
            }, mock_req_proto);
            var mock_res = _.defaults({ req: mock_req }, mock_res_proto);

            mock_res.render = function (view, options) {
                view.should.equal("document.jade");
                should.exist(options);
                done()
            };

            module.admin_app.handle(mock_req, mock_res);
        });

        it("test document - post simple", function (done) {
            var mock_req = _.defaults({
                url: "/model/AppliesTo/document/new",
                method: "POST",
                body: {
                    Title: "gaga5",
                    Identifier: "asdf",
                    Editable: "1"
                },
                path: ""
            }, mock_req_proto);
            var mock_res = _.defaults({ req: mock_req }, mock_res_proto);

            mock_res.redirect = function (path) {
                should.not.exist(mock_res._status);
                Number(1).should.equal(arguments.length);
                done();
            };

            module.admin_app.handle(mock_req, mock_res);
        });

        it("test document - post - failing validation", function (done) {
            var mock_req = _.defaults({
                url: "/model/AppliesTo/document/new",
                method: "POST",
                body: {
                    Identifier: "asdf",
                    Editable: "1"
                },
                path: ""
            }, mock_req_proto);
            var mock_res = _.defaults({ req: mock_req }, mock_res_proto);

            mock_res.render = function (view, options) {
                view.should.equal("document.jade");
                should.exist(options.errors.Title);
                Number(422).should.equal(mock_res._status);
                done();
            };

            module.admin_app.handle(mock_req, mock_res);
        });

        xit("test document - post progressive", function (done) {
            var mock_req = _.defaults({
                url: "/json/model/AppliesTo/document/new",
                method: "POST",
                body: {
                    string_req: "gaga",
                    enum: "",
                    "object.object.object.nested_string_req" : "gigi"
                },
                path: ""
            }, mock_req_proto);
            var mock_res = _.defaults({ req: mock_req }, mock_res_proto);

            mock_res.json = function (status, data) {
                status.should.equal(205);
                data.label.should.equal(mock_req.body.string_req);
                done();
            };

            module.admin_app.handle(mock_req, mock_res);
        });

        it("Mock test model page", function (done) {
            var mock_req = _.defaults({
                url: "/model/AppliesTo/",
                query: {start: "2"},
                method: "GET"
            }, mock_req_proto);
            var mock_res = _.defaults({ req: mock_req }, mock_res_proto);

            mock_res.render = function (view, options) {
                view.should.equal("model.jade");
                should.exist(options);
                this.req.app.render(view, options, function (err, doc) {
                    should.exist(doc);
                    done(err);
                });
            };

            module.admin_app.handle(mock_req, mock_res);
        });

        it("Mock test models page", function (done) {
            var mock_req = _.defaults({
                url: "/",
                method: "GET"
            }, mock_req_proto);
            var mock_res = _.defaults({ req: mock_req }, mock_res_proto);

            mock_res.render = function (view, options) {
                view.should.equal("models.jade");
                should.exist(options);
                this.req.app.render(view, options, function (err, doc) {
                    should.exist(doc);
                    done(err);
                });
            };

            module.admin_app.handle(mock_req, mock_res);
        });

        xit("Mock test admin user page post", function (done) {
            var mock_req = _.defaults({
                url: "/model/Admin_Users/document/new",
                body: {username: "admin" + Math.random()},
                method: "POST",
                path: ""
            }, mock_req_proto);

            var mock_res = _.defaults({
                req: mock_req
            }, mock_res_proto);

            mock_res.redirect = function (p) {
                should.exist(p);
                done();
            };

            module.admin_app.handle(mock_req, mock_res);
        });
    });

    after(function () {
        if (schema.disconnect) schema.disconnect();
    });
});
<commit_msg>But not just jugglingDB<commit_after>'use strict';
describe("high level REST requests on JugglingDB", function () {
    var schema;
    before(function (done) {
        _.each(require.cache, function (mod, modName) {
            if (~modName.indexOf('formage') || ~modName.indexOf('mongoose') || ~modName.indexOf('jugglingdb'))
                delete require.cache[modName];
        });
        var formage = require('../index');
        var Schema = require("jugglingdb").Schema;
        schema = new Schema("mssql", {host: "(LocalDB)\\v11.0", database: "maskar"});
        if (!schema.connect)
            schema = new Schema("memory");
        schema.on("connected", function () {
            var express = require('express');
            var app = express();
            var AppliesTo = schema.define("AppliesTo", {
                AppliesToID: {type: Number, primaryKey: true},
                Title: {type: String, limit: 100},
                Identifier: {type: String, limit: 100},
                Editable: {type: Number}
            });
            AppliesTo.validatesPresenceOf('Title');
            formage.init(app, express, {AppliesTo: AppliesTo}, {
                title: 'Formage Example',
                default_section: 'Main',
                admin_users_gui: true,
                db_layer_type: 'jugglingdb'
            });
            mock_req_proto.app = module.admin_app = app.admin_app;
            done()
        });
    });

    describe("pages", function () {
        it("Mock test document page", function (done) {
            var mock_req = _.defaults({
                url: "/model/AppliesTo/document/new",
                method: "GET"
            }, mock_req_proto);
            var mock_res = _.defaults({ req: mock_req }, mock_res_proto);

            mock_res.render = function (view, options) {
                view.should.equal("document.jade");
                should.exist(options);
                done()
            };

            module.admin_app.handle(mock_req, mock_res);
        });

        it("test document - post simple", function (done) {
            var mock_req = _.defaults({
                url: "/model/AppliesTo/document/new",
                method: "POST",
                body: {
                    Title: "gaga5",
                    Identifier: "asdf",
                    Editable: "1"
                },
                path: ""
            }, mock_req_proto);
            var mock_res = _.defaults({ req: mock_req }, mock_res_proto);

            mock_res.redirect = function (path) {
                should.not.exist(mock_res._status);
                Number(1).should.equal(arguments.length);
                done();
            };

            module.admin_app.handle(mock_req, mock_res);
        });

        it("test document - post - failing validation", function (done) {
            var mock_req = _.defaults({
                url: "/model/AppliesTo/document/new",
                method: "POST",
                body: {
                    Identifier: "asdf",
                    Editable: "1"
                },
                path: ""
            }, mock_req_proto);
            var mock_res = _.defaults({ req: mock_req }, mock_res_proto);

            mock_res.render = function (view, options) {
                view.should.equal("document.jade");
                should.exist(options.errors.Title);
                Number(422).should.equal(mock_res._status);
                done();
            };

            module.admin_app.handle(mock_req, mock_res);
        });

        xit("test document - post progressive", function (done) {
            var mock_req = _.defaults({
                url: "/json/model/AppliesTo/document/new",
                method: "POST",
                body: {
                    string_req: "gaga",
                    enum: "",
                    "object.object.object.nested_string_req" : "gigi"
                },
                path: ""
            }, mock_req_proto);
            var mock_res = _.defaults({ req: mock_req }, mock_res_proto);

            mock_res.json = function (status, data) {
                status.should.equal(205);
                data.label.should.equal(mock_req.body.string_req);
                done();
            };

            module.admin_app.handle(mock_req, mock_res);
        });

        it("Mock test model page", function (done) {
            var mock_req = _.defaults({
                url: "/model/AppliesTo/",
                query: {start: "2"},
                method: "GET"
            }, mock_req_proto);
            var mock_res = _.defaults({ req: mock_req }, mock_res_proto);

            mock_res.render = function (view, options) {
                view.should.equal("model.jade");
                should.exist(options);
                this.req.app.render(view, options, function (err, doc) {
                    should.exist(doc);
                    done(err);
                });
            };

            module.admin_app.handle(mock_req, mock_res);
        });

        it("Mock test models page", function (done) {
            var mock_req = _.defaults({
                url: "/",
                method: "GET"
            }, mock_req_proto);
            var mock_res = _.defaults({ req: mock_req }, mock_res_proto);

            mock_res.render = function (view, options) {
                view.should.equal("models.jade");
                should.exist(options);
                this.req.app.render(view, options, function (err, doc) {
                    should.exist(doc);
                    done(err);
                });
            };

            module.admin_app.handle(mock_req, mock_res);
        });

        xit("Mock test admin user page post", function (done) {
            var mock_req = _.defaults({
                url: "/model/Admin_Users/document/new",
                body: {username: "admin" + Math.random()},
                method: "POST",
                path: ""
            }, mock_req_proto);

            var mock_res = _.defaults({
                req: mock_req
            }, mock_res_proto);

            mock_res.redirect = function (p) {
                should.exist(p);
                done();
            };

            module.admin_app.handle(mock_req, mock_res);
        });
    });

    after(function () {
        if (schema.disconnect) schema.disconnect();
    });
});
<|endoftext|>


<commit_before>require('./styles/app.scss');
require('jquery');
require('bootstrap');

var io = require('socket.io-client');
var Swipe = require('swipejs');

var dayStr = location.href.substring(location.href.lastIndexOf("/") + 1)
var day = dayStr.length ? +dayStr : null;
var overallVisitors = $('#overallVisitors');
var dailyVisitors = $('#dailyVisitors');
var swipe = new Swipe(document.getElementById('slider'), {
    startSlide: sanitizeDay(day),
    speed: 400,
    continuous: false,
    disableScroll: false
});

$(".nav-icon.left").click(swipe.prev);
$(".nav-icon.right").click(swipe.next);

var names = ["Kristina", "Markus", "Fabian"];
swapNames();
if(window.location.pathname.indexOf("/about") === 0) {
    setInterval(swapNames, 5000);
}

var mailPre = "knechtcraft", mailDomain = "gmail.com";
$("#mail").text(mailPre + "@" + mailDomain);

var socket = io('/');
socket.on('newVisitor', function (data) {
    console.log(data);
    dailyVisitors.text(data.dailyVisitors);
    overallVisitors.text(data.overallVisitors);
});

function sanitizeDay(incDay) {
    if (incDay == null || isNaN(incDay)) {
        return ((new Date()).getDay() + 6) % 7;
    } else {
        if (incDay < 0) {
            incDay = 7 + (incDay % 7);
        }
        return incDay % 7;
    }
}

window.onkeyup = function (e) {
    var key = e.keyCode ? e.keyCode : e.which;

    if (key == 37) {
        swipe.prev();
    } else if (key == 39) {
        swipe.next();
    }
};

function swapNames() {
    shuffle(names);
    $("#name0").html(names[0]);
    $("#name1").html(names[1]);
    $("#name2").html(names[2]);
}

/**
 * Shuffles array in place.
 * @param {Array} a items The array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length; i; i--) {
        j = Math.floor(Math.random() * i);
        x = a[i - 1];
        a[i - 1] = a[j];
        a[j] = x;
    }
}<commit_msg>Removed unnecessary slash.<commit_after>require('./styles/app.scss');
require('jquery');
require('bootstrap');

var io = require('socket.io-client');
var Swipe = require('swipejs');

var dayStr = location.href.substring(location.href.lastIndexOf("/") + 1)
var day = dayStr.length ? +dayStr : null;
var overallVisitors = $('#overallVisitors');
var dailyVisitors = $('#dailyVisitors');
var swipe = new Swipe(document.getElementById('slider'), {
    startSlide: sanitizeDay(day),
    speed: 400,
    continuous: false,
    disableScroll: false
});

$(".nav-icon.left").click(swipe.prev);
$(".nav-icon.right").click(swipe.next);

var names = ["Kristina", "Markus", "Fabian"];
swapNames();
if(window.location.pathname.indexOf("/about") === 0) {
    setInterval(swapNames, 5000);
}

var mailPre = "knechtcraft", mailDomain = "gmail.com";
$("#mail").text(mailPre + "@" + mailDomain);

var socket = io();
socket.on('newVisitor', function (data) {
    console.log(data);
    dailyVisitors.text(data.dailyVisitors);
    overallVisitors.text(data.overallVisitors);
});

function sanitizeDay(incDay) {
    if (incDay == null || isNaN(incDay)) {
        return ((new Date()).getDay() + 6) % 7;
    } else {
        if (incDay < 0) {
            incDay = 7 + (incDay % 7);
        }
        return incDay % 7;
    }
}

window.onkeyup = function (e) {
    var key = e.keyCode ? e.keyCode : e.which;

    if (key == 37) {
        swipe.prev();
    } else if (key == 39) {
        swipe.next();
    }
};

function swapNames() {
    shuffle(names);
    $("#name0").html(names[0]);
    $("#name1").html(names[1]);
    $("#name2").html(names[2]);
}

/**
 * Shuffles array in place.
 * @param {Array} a items The array containing the items.
 */
function shuffle(a) {
    var j, x, i;
    for (i = a.length; i; i--) {
        j = Math.floor(Math.random() * i);
        x = a[i - 1];
        a[i - 1] = a[j];
        a[j] = x;
    }
}<|endoftext|>