<commit_before>import { find, findAll, render, click } from '@ember/test-helpers';
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import sinon from 'sinon';
import { run } from '@ember/runloop';

module('Integration | Component | swiper container', function(hooks) {
  setupRenderingTest(hooks);

  hooks.beforeEach(function() {
    this.actions = {};
    this.send = (actionName, ...args) =>
      this.actions[actionName].apply(this, args);
  });

  test('it renders', async function(assert) {
    await render(hbs`{{swiper-container}}`);
    assert.equal(find('*').textContent.trim(), '');

    await render(hbs`
      {{#swiper-container}}
        template block text
      {{/swiper-container}}
    `);
    assert.equal(find('*').textContent.trim(), 'template block text');
  });

  test('it set `noSwiping` via attribute and `options`', async function(assert) {
    let expected = false;

    this.set('noSwiping', expected);
    await render(
      hbs`{{swiper-container noSwiping=noSwiping registerAs=componentInstanceAttr}}`
    );

    assert.strictEqual(
      this.get('componentInstanceAttr._swiper.params.noSwiping'),
      expected,
      'Swiper instance `noSwiping` configured by `noSwiping` attribute'
    );

    this.set('options', { noSwiping: expected });
    await render(
      hbs`{{swiper-container options=options registerAs=componentInstanceOpts}}`
    );

    assert.strictEqual(
      this.get('componentInstanceOpts._swiper.params.noSwiping'),
      expected,
      'Swiper instance `noSwiping` configured by `options.noSwiping`'
    );
  });

  test('it should allow attributes to overwrite `options`', async function(assert) {
    let expected = 'fade';

    this.set('effect', expected);
    this.set('options', { effect: 'cube' });
    await render(
      hbs`{{swiper-container effect=effect options=options registerAs=componentInstanceAttr}}`
    );

    assert.strictEqual(
      this.get('componentInstanceAttr._swiper.params.effect'),
      expected,
      'Swiper instance configured by attribute not `options`'
    );
  });

  test('predefined classes are added', async function(assert) {
    await render(hbs`{{swiper-container}}`);
    assert.ok(find('.swiper-container'));
  });

  test('contains the wrapper', async function(assert) {
    await render(hbs`{{swiper-container id="swp-container"}}`);
    assert.ok(find('#swp-container').querySelector('.swiper-wrapper'));
  });

  test('pagination node is present if requested', async function(assert) {
    await render(hbs`{{swiper-container id="swp-container" pagination=false}}`);
    assert.notOk(
      find('#swp-container').querySelector('.swiper-pagination'),
      'pagination not rendered'
    );

    await render(hbs`{{swiper-container id="swp-container" pagination=true}}`);
    assert.ok(
      find('#swp-container').querySelector('.swiper-pagination'),
      'pagination is rendered'
    );

    await render(
      hbs`{{swiper-container pagination=".custom-pagination"}}<div class="custom-pagination"></div>`
    );
    assert.ok(
      find('.custom-pagination').classList.contains(
        'swiper-pagination-clickable'
      ),
      'custom pagination element selector configured'
    );

    await render(
      hbs`{{swiper-container pagination=(hash el=".custom-pagination")}}<div class="custom-pagination"></div>`
    );
    assert.ok(
      find('.custom-pagination').classList.contains(
        'swiper-pagination-clickable'
      ),
      'custom pagination object element selector configured'
    );

    this.set('opts', { pagination: { type: 'progressbar' } });
    await render(hbs`{{swiper-container id="swp-container" options=opts}}`);
    assert.ok(
      find('#swp-container').querySelector('.swiper-pagination-progressbar'),
      'pagination object rendered'
    );
  });

  test('navigation buttons are present if requested', async function(assert) {
    await render(hbs`{{swiper-container id="swp-container" navigation=false}}`);
    assert.notOk(find('#swp-container').querySelector('.swiper-button-next'));
    assert.notOk(find('#swp-container').querySelector('.swiper-button-prev'));

    await render(hbs`{{swiper-container id="swp-container" navigation=true}}`);
    assert.ok(find('#swp-container').querySelector('.swiper-button-next'));
    assert.ok(find('#swp-container').querySelector('.swiper-button-prev'));

    this.set('opts', { navigation: true });
    await render(hbs`{{swiper-container id="swp-container" options=opts}}`);
    assert.ok(find('#swp-container').querySelector('.swiper-button-next'));
    assert.ok(find('#swp-container').querySelector('.swiper-button-prev'));
  });

  test('it supports `effect` attribute', async function(assert) {
    await render(hbs`{{swiper-container id="swp-container" effect="fade"}}`);
    assert.ok(
      find('#swp-container.swiper-container-fade'),
      'Container has `fade` class'
    );
  });

  test('it destroys the Swiper instance when component element destroyed', async function(assert) {
    assert.expect(2);
    this.set('componentInstance', null);
    this.set('active', true);

    await render(
      hbs`{{#if active}}{{swiper-container registerAs=componentInstance}}{{/if}}`
    );

    run(() => {
      let componentInstance = this.get('componentInstance');
      assert.ok(componentInstance._swiper, 'Swiper intantiated');

      sinon
        .stub(componentInstance._swiper, 'destroy')
        .callsFake(() => assert.ok(true, 'destroy was called'))
        .callThrough();

      this.set('active', false);
    });
  });

  test('it removes all `slideChangeTransitionEnd` handlers when component element destroyed', async function(assert) {
    this.set('componentInstance', null);
    this.set('rendered', true);

    await render(
      hbs`{{#if rendered}}{{swiper-container registerAs=componentInstance}}{{/if}}`
    );

    let componentInstance = this.get('componentInstance');
    let swiperInstance = componentInstance._swiper;
    let originalDestroy = swiperInstance.destroy;
    let originalSwiperOff = swiperInstance.off;

    swiperInstance.off = (evt, ...args) => {
      if (evt === 'slideChangeTransitionEnd') {
        assert.ok(true, 'slideChangeTransitionEnd');
      }
      originalSwiperOff.apply(swiperInstance, [evt, ...args]);
    };

    swiperInstance.destroy = (...args) => {
      swiperInstance.off = originalSwiperOff;
      swiperInstance.destroy = originalDestroy;
      originalDestroy.apply(swiperInstance, ...args);
    };

    this.set('rendered', false); // trigger swipper destroy
  });

  test('it yields a slide component', async function(assert) {
    await render(
      hbs`{{#swiper-container as |container|}}{{container.slide}}{{/swiper-container}}`
    );
    assert.equal(findAll('.swiper-slide').length, 1, 'renders a single slide');
  });

  test('it activates the slide at index `currentSlide` on render', async function(assert) {
    await render(hbs`
      {{#swiper-container currentSlide=1}}
        {{swiper-slide}}
        {{swiper-slide}}
      {{/swiper-container}}`);

    let lastSlide = Array.from(findAll('.swiper-slide')).pop();

    assert.ok(
      lastSlide && lastSlide.classList.contains('swiper-slide-active'),
      'set slide at index 1 to active'
    );
  });

  test('it updates the active slide when `currentSlide` is updated', async function(assert) {
    this.set('currentSlide', 0);

    await render(hbs`
      {{#swiper-container currentSlide=currentSlide}}
        {{swiper-slide}}
        {{swiper-slide}}
      {{/swiper-container}}`);

    this.set('currentSlide', 1);

    let lastSlide = Array.from(findAll('.swiper-slide')).pop();

    assert.ok(
      lastSlide && lastSlide.classList.contains('swiper-slide-active'),
      'set slide at index 1 to active'
    );
  });

  test('it triggers `swiper.update()` when `updateFor` is updated', async function(assert) {
    this.set('updateFor', '');
    await render(hbs`
      {{swiper-container updateFor=updateFor registerAs=componentInstance}}`);

    let componentInstance = this.get('componentInstance');

    sinon
      .stub(componentInstance._swiper, 'update')
      .callsFake(() => assert.ok(true, 'called swiper.update'))
      .callThrough();

    this.set('updateFor', 'updateTranslate');
  });

  test('it subscribes `events` actions map as Swiper events', async function(assert) {
    this.actions.onBeforeDestroy = () => assert.ok(true);

    await render(hbs`
      {{swiper-container events=(hash beforeDestroy=(action "onBeforeDestroy"))}}`);
  });

  test('it supports manual swiper initialization when `init` event configured', async function(assert) {
    this.set('componentInstance', null);
    this.actions.onInit = () => assert.ok(true, 'invoked init handler');

    await render(hbs`
      {{swiper-container registerAs=componentInstance events=(hash init=(action "onInit"))}}`);
  });

  test('it triggers `autoplay` with custom `currentSlide`', async function(assert) {
    let run = false;

    this.actions.onAutoplay = () => {
      if (run) {
        return true;
      }

      let lastSlide = Array.from(findAll('.swiper-slide')).pop();

      assert.ok(
        lastSlide && lastSlide.classList.contains('swiper-slide-active'),
        'set slide at index 2 to active'
      );

      run = true;
    };

    await render(hbs`
      {{#swiper-container autoplay=(hash delay=10) currentSlide=1 events=(hash
        autoplay=(action "onAutoplay")) as |sc|}}
        {{swiper-slide}}
        {{swiper-slide}}
        {{swiper-slide}}
      {{/swiper-container}}
    `);
  });

  test('it exposes default swiper navigation controls to `navigation=true`', async function(assert) {
    await render(hbs`
      {{#swiper-container navigation=true}}
        {{swiper-slide}}
        {{swiper-slide}}
        {{swiper-slide}}
      {{/swiper-container}}
    `);

    assert.ok(find('.swiper-button-next'), 'rendered nav next button');
    assert.ok(find('.swiper-button-prev'), 'rendered nav prev button');

    let slides = Array.from(findAll('.swiper-slide'));

    await click('.swiper-button-next');

    assert.ok(
      slides[1].classList.contains('swiper-slide-active'),
      'next button click handled'
    );

    await click('.swiper-button-prev');

    assert.ok(
      slides[0].classList.contains('swiper-slide-active'),
      'previous button click handled'
    );
  });

  test('it applies custom navigation hash of control selectors', async function(assert) {
    await render(hbs`
      {{#swiper-container navigation=(hash nextEl=".is-next" prevEl=".is-last")}}
        {{swiper-slide}}
        {{swiper-slide}}
        {{swiper-slide}}
      {{/swiper-container}}
    `);

    assert.ok(find('.is-next'), 'rendered custom nav next button');
    assert.ok(find('.is-last'), 'rendered custom nav prev button');
  });

  test('it applies custom `navigation.disabledClass`', async function(assert) {
    await render(hbs`
      {{#swiper-container navigation=(hash disabledClass="is-disabled")}}
        {{swiper-slide}}
        {{swiper-slide}}
        {{swiper-slide}}
      {{/swiper-container}}
    `);

    assert.ok(find('.is-disabled'), 'rendered custom disabled class');
  });

  test('it provides swiper instance as context of `update`', async function(assert) {
    this.set('updateForValue', '');
    this.set('componentInstance', null);

    await render(
      hbs`{{swiper-container registerAs=componentInstance updateFor=updateForValue}}`
    );

    let swiperInstance = this.get('componentInstance._swiper');
    let originalUpdate = swiperInstance.update;
    swiperInstance.update = function() {
      assert.strictEqual(
        this,
        swiperInstance,
        'update invoked with swiper context'
      );
      swiperInstance.update = originalUpdate;
    };

    this.set('updateForValue', 'trigger update');
  });
});
<commit_msg>Creating a passing test for currentValue fix<commit_after>import { find, findAll, render, click, waitFor } from '@ember/test-helpers';
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
import sinon from 'sinon';
import { run } from '@ember/runloop';

module('Integration | Component | swiper container', function(hooks) {
  setupRenderingTest(hooks);

  hooks.beforeEach(function() {
    this.actions = {};
    this.send = (actionName, ...args) =>
      this.actions[actionName].apply(this, args);
  });

  test('it renders', async function(assert) {
    await render(hbs`{{swiper-container}}`);
    assert.equal(find('*').textContent.trim(), '');

    await render(hbs`
      {{#swiper-container}}
        template block text
      {{/swiper-container}}
    `);
    assert.equal(find('*').textContent.trim(), 'template block text');
  });

  test('it set `noSwiping` via attribute and `options`', async function(assert) {
    let expected = false;

    this.set('noSwiping', expected);
    await render(
      hbs`{{swiper-container noSwiping=noSwiping registerAs=componentInstanceAttr}}`
    );

    assert.strictEqual(
      this.get('componentInstanceAttr._swiper.params.noSwiping'),
      expected,
      'Swiper instance `noSwiping` configured by `noSwiping` attribute'
    );

    this.set('options', { noSwiping: expected });
    await render(
      hbs`{{swiper-container options=options registerAs=componentInstanceOpts}}`
    );

    assert.strictEqual(
      this.get('componentInstanceOpts._swiper.params.noSwiping'),
      expected,
      'Swiper instance `noSwiping` configured by `options.noSwiping`'
    );
  });

  test('it should allow attributes to overwrite `options`', async function(assert) {
    let expected = 'fade';

    this.set('effect', expected);
    this.set('options', { effect: 'cube' });
    await render(
      hbs`{{swiper-container effect=effect options=options registerAs=componentInstanceAttr}}`
    );

    assert.strictEqual(
      this.get('componentInstanceAttr._swiper.params.effect'),
      expected,
      'Swiper instance configured by attribute not `options`'
    );
  });

  test('predefined classes are added', async function(assert) {
    await render(hbs`{{swiper-container}}`);
    assert.ok(find('.swiper-container'));
  });

  test('contains the wrapper', async function(assert) {
    await render(hbs`{{swiper-container id="swp-container"}}`);
    assert.ok(find('#swp-container').querySelector('.swiper-wrapper'));
  });

  test('pagination node is present if requested', async function(assert) {
    await render(hbs`{{swiper-container id="swp-container" pagination=false}}`);
    assert.notOk(
      find('#swp-container').querySelector('.swiper-pagination'),
      'pagination not rendered'
    );

    await render(hbs`{{swiper-container id="swp-container" pagination=true}}`);
    assert.ok(
      find('#swp-container').querySelector('.swiper-pagination'),
      'pagination is rendered'
    );

    await render(
      hbs`{{swiper-container pagination=".custom-pagination"}}<div class="custom-pagination"></div>`
    );
    assert.ok(
      find('.custom-pagination').classList.contains(
        'swiper-pagination-clickable'
      ),
      'custom pagination element selector configured'
    );

    await render(
      hbs`{{swiper-container pagination=(hash el=".custom-pagination")}}<div class="custom-pagination"></div>`
    );
    assert.ok(
      find('.custom-pagination').classList.contains(
        'swiper-pagination-clickable'
      ),
      'custom pagination object element selector configured'
    );

    this.set('opts', { pagination: { type: 'progressbar' } });
    await render(hbs`{{swiper-container id="swp-container" options=opts}}`);
    assert.ok(
      find('#swp-container').querySelector('.swiper-pagination-progressbar'),
      'pagination object rendered'
    );
  });

  test('navigation buttons are present if requested', async function(assert) {
    await render(hbs`{{swiper-container id="swp-container" navigation=false}}`);
    assert.notOk(find('#swp-container').querySelector('.swiper-button-next'));
    assert.notOk(find('#swp-container').querySelector('.swiper-button-prev'));

    await render(hbs`{{swiper-container id="swp-container" navigation=true}}`);
    assert.ok(find('#swp-container').querySelector('.swiper-button-next'));
    assert.ok(find('#swp-container').querySelector('.swiper-button-prev'));

    this.set('opts', { navigation: true });
    await render(hbs`{{swiper-container id="swp-container" options=opts}}`);
    assert.ok(find('#swp-container').querySelector('.swiper-button-next'));
    assert.ok(find('#swp-container').querySelector('.swiper-button-prev'));
  });

  test('it supports `effect` attribute', async function(assert) {
    await render(hbs`{{swiper-container id="swp-container" effect="fade"}}`);
    assert.ok(
      find('#swp-container.swiper-container-fade'),
      'Container has `fade` class'
    );
  });

  test('it destroys the Swiper instance when component element destroyed', async function(assert) {
    assert.expect(2);
    this.set('componentInstance', null);
    this.set('active', true);

    await render(
      hbs`{{#if active}}{{swiper-container registerAs=componentInstance}}{{/if}}`
    );

    run(() => {
      let componentInstance = this.get('componentInstance');
      assert.ok(componentInstance._swiper, 'Swiper intantiated');

      sinon
        .stub(componentInstance._swiper, 'destroy')
        .callsFake(() => assert.ok(true, 'destroy was called'))
        .callThrough();

      this.set('active', false);
    });
  });

  test('it removes all `slideChangeTransitionEnd` handlers when component element destroyed', async function(assert) {
    this.set('componentInstance', null);
    this.set('rendered', true);

    await render(
      hbs`{{#if rendered}}{{swiper-container registerAs=componentInstance}}{{/if}}`
    );

    let componentInstance = this.get('componentInstance');
    let swiperInstance = componentInstance._swiper;
    let originalDestroy = swiperInstance.destroy;
    let originalSwiperOff = swiperInstance.off;

    swiperInstance.off = (evt, ...args) => {
      if (evt === 'slideChangeTransitionEnd') {
        assert.ok(true, 'slideChangeTransitionEnd');
      }
      originalSwiperOff.apply(swiperInstance, [evt, ...args]);
    };

    swiperInstance.destroy = (...args) => {
      swiperInstance.off = originalSwiperOff;
      swiperInstance.destroy = originalDestroy;
      originalDestroy.apply(swiperInstance, ...args);
    };

    this.set('rendered', false); // trigger swipper destroy
  });

  test('it yields a slide component', async function(assert) {
    await render(
      hbs`{{#swiper-container as |container|}}{{container.slide}}{{/swiper-container}}`
    );
    assert.equal(findAll('.swiper-slide').length, 1, 'renders a single slide');
  });

  test('it activates the slide at index `currentSlide` on render', async function(assert) {
    await render(hbs`
      {{#swiper-container currentSlide=1}}
        {{swiper-slide}}
        {{swiper-slide}}
      {{/swiper-container}}`);

    let lastSlide = Array.from(findAll('.swiper-slide')).pop();

    assert.ok(
      lastSlide && lastSlide.classList.contains('swiper-slide-active'),
      'set slide at index 1 to active'
    );
  });

  test('it updates the active slide when `currentSlide` is updated', async function(assert) {
    this.set('currentSlide', 0);

    await render(hbs`
      {{#swiper-container currentSlide=currentSlide}}
        {{swiper-slide}}
        {{swiper-slide}}
      {{/swiper-container}}`);

    this.set('currentSlide', 1);

    let lastSlide = Array.from(findAll('.swiper-slide')).pop();

    assert.ok(
      lastSlide && lastSlide.classList.contains('swiper-slide-active'),
      'set slide at index 1 to active'
    );
  });

  test('it triggers `swiper.update()` when `updateFor` is updated', async function(assert) {
    this.set('updateFor', '');
    await render(hbs`
      {{swiper-container updateFor=updateFor registerAs=componentInstance}}`);

    let componentInstance = this.get('componentInstance');

    sinon
      .stub(componentInstance._swiper, 'update')
      .callsFake(() => assert.ok(true, 'called swiper.update'))
      .callThrough();

    this.set('updateFor', 'updateTranslate');
  });

  test('it updates the `currentSlide` when viewing and removing the last item', async function(assert) {
    this.set('itemList', ['item-1', 'item-2']);

    await render(hbs`
      {{#swiper-container
        navigation=true
        updateFor=itemList
        currentSlide=currentSlide
      }}
        {{#each itemList as |item|}}
          {{#swiper-slide}}
            <p class="{{item}}">{{item}}</p>
          {{/swiper-slide}}
        {{/each}}
      {{/swiper-container}}
    `);

    await click('.swiper-button-next');
    await waitFor('.swiper-slide-active .item-2');

    this.set('itemList', ['item-1']);
    await waitFor('.swiper-slide-active .item-1');

    assert.equal(this.get('currentSlide'), 0);
  });

  test('it subscribes `events` actions map as Swiper events', async function(assert) {
    this.actions.onBeforeDestroy = () => assert.ok(true);

    await render(hbs`
      {{swiper-container events=(hash beforeDestroy=(action "onBeforeDestroy"))}}`);
  });

  test('it supports manual swiper initialization when `init` event configured', async function(assert) {
    this.set('componentInstance', null);
    this.actions.onInit = () => assert.ok(true, 'invoked init handler');

    await render(hbs`
      {{swiper-container registerAs=componentInstance events=(hash init=(action "onInit"))}}`);
  });

  test('it triggers `autoplay` with custom `currentSlide`', async function(assert) {
    let run = false;

    this.actions.onAutoplay = () => {
      if (run) {
        return true;
      }

      let lastSlide = Array.from(findAll('.swiper-slide')).pop();

      assert.ok(
        lastSlide && lastSlide.classList.contains('swiper-slide-active'),
        'set slide at index 2 to active'
      );

      run = true;
    };

    await render(hbs`
      {{#swiper-container autoplay=(hash delay=10) currentSlide=1 events=(hash
        autoplay=(action "onAutoplay")) as |sc|}}
        {{swiper-slide}}
        {{swiper-slide}}
        {{swiper-slide}}
      {{/swiper-container}}
    `);
  });

  test('it exposes default swiper navigation controls to `navigation=true`', async function(assert) {
    await render(hbs`
      {{#swiper-container navigation=true}}
        {{swiper-slide}}
        {{swiper-slide}}
        {{swiper-slide}}
      {{/swiper-container}}
    `);

    assert.ok(find('.swiper-button-next'), 'rendered nav next button');
    assert.ok(find('.swiper-button-prev'), 'rendered nav prev button');

    let slides = Array.from(findAll('.swiper-slide'));

    await click('.swiper-button-next');

    assert.ok(
      slides[1].classList.contains('swiper-slide-active'),
      'next button click handled'
    );

    await click('.swiper-button-prev');

    assert.ok(
      slides[0].classList.contains('swiper-slide-active'),
      'previous button click handled'
    );
  });

  test('it applies custom navigation hash of control selectors', async function(assert) {
    await render(hbs`
      {{#swiper-container navigation=(hash nextEl=".is-next" prevEl=".is-last")}}
        {{swiper-slide}}
        {{swiper-slide}}
        {{swiper-slide}}
      {{/swiper-container}}
    `);

    assert.ok(find('.is-next'), 'rendered custom nav next button');
    assert.ok(find('.is-last'), 'rendered custom nav prev button');
  });

  test('it applies custom `navigation.disabledClass`', async function(assert) {
    await render(hbs`
      {{#swiper-container navigation=(hash disabledClass="is-disabled")}}
        {{swiper-slide}}
        {{swiper-slide}}
        {{swiper-slide}}
      {{/swiper-container}}
    `);

    assert.ok(find('.is-disabled'), 'rendered custom disabled class');
  });

  test('it provides swiper instance as context of `update`', async function(assert) {
    this.set('updateForValue', '');
    this.set('componentInstance', null);

    await render(
      hbs`{{swiper-container registerAs=componentInstance updateFor=updateForValue}}`
    );

    let swiperInstance = this.get('componentInstance._swiper');
    let originalUpdate = swiperInstance.update;
    swiperInstance.update = function() {
      assert.strictEqual(
        this,
        swiperInstance,
        'update invoked with swiper context'
      );
      swiperInstance.update = originalUpdate;
    };

    this.set('updateForValue', 'trigger update');
  });
});
<|endoftext|>


<commit_before>module.exports = {

  /**
  * Init the model for the ressource
  * @params String model name
  */
  initModel: function(model) {
    this.model = require('../models/'+ model);
  },

  /**
  * Create a new crud route
  * @params String || Object
  * @return Array routes object
  */
  initRoute: function(ressource) {
    var routes = new Array();

    if (typeof ressource == 'string') {
      // All functions && no auth
      routes[0] = this.newRoute('all', ressource, false);
      routes[1] = this.newRoute('read', ressource, false);
      routes[2] = this.newRoute('create', ressource, false);
      routes[3] = this.newRoute('update', ressource, false);
      routes[4] = this.newRoute('delete', ressource, false);
    }
    else if (typeof ressource == 'object') {
      // Just choose function
      for (var i = 0; i < ressource['endpoints'].length; i++) {
        routes.push(this.newRoute(ressource['endpoints'][i], ressource.data, ressource['auth']));
      }
    }

    return routes;
  },

  /**
  * Create route object for requester
  * @params String the action
  * @params String the name of the ressources
  * @params Array || Boolean is authenticate
  * @return route object
  */
  newRoute: function(action, ressource, auth) {
    var r = {
      controller: this,
      middleware: [],
      action    : action,
    };

    if(auth)
      r.middleware = (auth.indexOf(action) != -1) ? ['auth'] : [];

    switch(action) {
      case 'all':
        r.path = '/' + ressource;
        r.method = 'get';
        break;
      case 'read':
        r.path = '/' + ressource + '/:id';
        r.method = 'get';
        break;
      case 'create':
        r.path = '/' + ressource + '/';
        r.method = 'post';
        break;
      case 'update':
        r.path = '/' + ressource + '/:id/';
        r.method = 'put';
        break;
      case 'delete':
        r.path = '/' + ressource + '/:id/delete';
        r.method = 'delete';
        break;
      default:
         r.path = '/' + ress;ource;
         r.method = 'get'
    }

    return r;
  },

  /**
  * Create - Crud
  */
  create: function(req, res, next) {
    var new_data = req.body;

    this.model.create(new_data, function(err, data) {
      if (err) res.send(err);
      res.json(data);
      next(req, res);
    });
	},

  /**
  * Read - Crud
  */
	read: function(req, res, next) {
		this.model.findById(req.params.id, function(err, data) {
      if (err) res.send(err);
      if(!data) res.json({message : 'No data found'});
      res.json(data);
    });
	},

  /**
  * Update - Crud
  */
	update: function(req, res, next) {
    var self = this;

    delete req.body.id;
    delete req.body._id;

    self.model.update({ _id: req.params.id }, req.body, { multi: true }, function(err, data) {
      if(err) throw err;
      self.model.find({ _id: req.params.id}, function(err, data) {
        res.json(data);
      });
    });
	},

  /**
  * Delete - Crud
  */
	delete: function(req, res, next) {
		this.model.remove({ _id: req.params.id }, function(err, data) {
      if (err) res.send(err);
      res.json({message: 'Data deleted', status : true});
    });
	},

  /**
  * Get all - Crud
  */
	all: function(req, res, next) {
		this.model.find(function(err, data) {
      if (err) res.send(err);
      res.json(data);
      next(req, res);
    });
	}

};<commit_msg>clean and add auth === true<commit_after>module.exports = {

  /**
  * Init the model for the ressource
  * @params String model name
  */
  initModel: function(model) {
    this.model = require('../models/'+ model);
  },

  /**
  * Create a new crud route
  * @params String || Object
  * @return Array routes object
  */
  initRoute: function(ressource) {
    var routes = new Array();

    if (typeof ressource == 'string') {
      // All functions && no auth
      routes[0] = this.newRoute('all', ressource, false);
      routes[1] = this.newRoute('read', ressource, false);
      routes[2] = this.newRoute('create', ressource, false);
      routes[3] = this.newRoute('update', ressource, false);
      routes[4] = this.newRoute('delete', ressource, false);
    }
    else if (typeof ressource == 'object') {
      // Just choose function
      for (var i = 0; i < ressource['endpoints'].length; i++) {
        routes.push(this.newRoute(ressource['endpoints'][i], ressource.data, ressource['auth']));
      }
    }

    return routes;
  },

  /**
  * Create route object for requester
  * @params String the action
  * @params String the name of the ressources
  * @params Array || Boolean is authenticate
  * @return route object
  */
  newRoute: function(action, ressource, auth) {
    var r = {
      controller: this,
      middleware: [],
      action    : action,
    };

    if (auth)
      if (auth === true)
        r.middleware = ['auth'];
      else
        r.middleware = (auth.indexOf(action) != -1) ? ['auth'] : [];

    switch(action) {
      case 'all':
        r.path = '/' + ressource;
        r.method = 'get';
        break;
      case 'read':
        r.path = '/' + ressource + '/:id';
        r.method = 'get';
        break;
      case 'create':
        r.path = '/' + ressource + '/';
        r.method = 'post';
        break;
      case 'update':
        r.path = '/' + ressource + '/:id/';
        r.method = 'put';
        break;
      case 'delete':
        r.path = '/' + ressource + '/:id/delete';
        r.method = 'delete';
        break;
      default:
         r.path = '/' + ress;ource;
         r.method = 'get'
    }

    return r;
  },

  /**
  * Create - Crud
  */
  create: function(req, res, next) {
    var new_data = req.body;

    this.model.create(new_data, function(err, data) {
      if (err) res.send(err);
      res.json(data);
      next(req, res);
    });
	},

  /**
  * Read - Crud
  */
	read: function(req, res, next) {
		this.model.findById(req.params.id, function(err, data) {
      if (err) res.send(err);
      if(!data) res.json({message : 'No data found'});
      res.json(data);
    });
	},

  /**
  * Update - Crud
  */
	update: function(req, res, next) {
    var self = this;

    delete req.body.id;
    delete req.body._id;

    self.model.update({ _id: req.params.id }, req.body, { multi: true }, function(err, data) {
      if(err) throw err;
      self.model.find({ _id: req.params.id}, function(err, data) {
        res.json(data);
      });
    });
	},

  /**
  * Delete - Crud
  */
	delete: function(req, res, next) {
		this.model.remove({ _id: req.params.id }, function(err, data) {
      if (err) res.send(err);
      res.json({message: 'Data deleted', status : true});
    });
	},

  /**
  * Get all - Crud
  */
	all: function(req, res, next) {
		this.model.find(function(err, data) {
      if (err) res.send(err);
      res.json(data);
      next(req, res);
    });
	}

};<|endoftext|>


<commit_before>import Promise from 'bluebird';
import os from 'os';
import extend from 'xtend';
import { flatten, pick } from 'lodash';
import utils from '../../utils/utils';

const library = (lib) => {

    const peerFound = (peer) => (dispatch, getState) => {
        const me = getState().network.me;
        if (me.hostname !== peer.hostname) {
            dispatch({
                type: 'NETWORK/PEER_FOUND',
                payload: {
                    peer
                }
            });
            dispatch(lib.actions.tracks.find({ peer }));
        }
    };

    const setOutput = (newOutput) => (dispatch, getState) => {
        const state = getState();
        const { network : { output: prevOutput }, network : { me } } = state;

        // If the output has not changed, do nothing.
        if (prevOutput && prevOutput.hostname === newOutput.hostname) {
            return;
        }

        const getPlayerState = () => {

            const playerState = [
                'player',
                'queue',
                'queueCursor'
            ];

            return {
                ...pick(state, playerState),
                elapsed: lib.player.getCurrentTime()
            }
        };

        // Add the isLocal bool to the output object for convenience elsewhere.
        const isLocal = newOutput.hostname === me.hostname;
        const newOutputWithIsLocal = { ...newOutput, isLocal };

        // If output has swapped to our computer
        if (isLocal) {
            // Ask the previous output for us to be removed as an observer
            // This may fail if the other Museeks stops working.
            // If so, this is fine... Probably...
            lib.api.actions.network.disconnectAsOutput(prevOutput, {
                peer: utils.getMeWithIP(me, prevOutput)
            });

            // Dispatch the change event to update the ui
            // This has promise.resolve so we get fulfilled events
            // to match the other case.
            dispatch({
                type: 'NETWORK/SET_OUTPUT',
                payload: Promise.resolve(),
                meta: {
                    newOutput: newOutputWithIsLocal,
                    prevOutput
                }
            })

        } else { // If output has changed to another computer

            const meWithIP = utils.getMeWithIP(me, newOutput);
            const playerState = getPlayerState();
            const stateWithRemotePaths = {
                ...playerState,
                queue: playerState.queue.map((track) => track.owner.hostname === me.hostname
                    ? {
                        ...track,
                        path: lib.utils.trackEndpoint({
                            _id: track._id,
                            peer: me
                        }),
                        cover: lib.utils.coverEndpoint({
                            _id: track._id,
                            peer: me
                        }),
                        owner: meWithIP
                    })
                    : track
                );

            // We ask the output device to set us as an observer.
            dispatch({
                type: 'NETWORK/SET_OUTPUT',
                payload: lib.api.actions.network.connectAsOutput(newOutput, {
                    peer: meWithIP,
                    state: stateWithRemotePaths
                }),
                meta: {
                    newOutput: newOutputWithIsLocal,
                    prevOutput
                }
            });
        }
    };

    const connectAsOutput = ({ state, peer }) => (dispatch) => {
        console.log(state, peer)
        // Stop the player from playing
        dispatch(lib.actions.player.stop());

        // Apply the input's state

        // Set the queue
        dispatch(lib.actions.queue.setQueue(state.queue));

        // Load the track
        dispatch(lib.actions.player.load(state.queue[state.queueCursor]._id));

        // Set the play/pause/stop status
        if (state.player.playStatus === 'pause') {
            dispatch(lib.actions.player.pause());
        } else if (state.player.playStatus === 'stop') {
            dispatch(lib.actions.player.stop());
        } else if (state.player.playStatus === 'play') {
            dispatch(lib.actions.player.play());
        }

        // Set repeat
        dispatch(lib.actions.player.repeat(state.player.repeat));

        // Set Shuffle
        dispatch(lib.actions.player.shuffle(state.player.shuffle));

        // Set the elapsed time
        dispatch(lib.actions.player.jumpTo(state.elapsed));

        // Add the input computer as an observer
        dispatch(lib.actions.network.addObserver(peer));
    };

    const disconnectAsOutput = ({ peer }) => (dispatch) => {
        dispatch(removeObserver({ peer }));
    };

    const addObserver = ({ ip, hostname, platform }) => ({
        type: 'NETWORK/ADD_OBSERVER',
        payload: {
            peer: {
                ip,
                hostname,
                platform
            }
        }
    });

    const removeObserver = (peer) => ({
        type: 'NETWORK/REMOVE_OBSERVER',
        payload: {
            peer
        }
    });

    return {
        peerFound,
        setOutput,
        connectAsOutput,
        disconnectAsOutput,
        addObserver,
        removeObserver
    };
}

export default library;
<commit_msg>syntax fix<commit_after>import Promise from 'bluebird';
import os from 'os';
import extend from 'xtend';
import { flatten, pick } from 'lodash';
import utils from '../../utils/utils';

const library = (lib) => {

    const peerFound = (peer) => (dispatch, getState) => {
        const me = getState().network.me;
        if (me.hostname !== peer.hostname) {
            dispatch({
                type: 'NETWORK/PEER_FOUND',
                payload: {
                    peer
                }
            });
            dispatch(lib.actions.tracks.find({ peer }));
        }
    };

    const setOutput = (newOutput) => (dispatch, getState) => {
        const state = getState();
        const { network : { output: prevOutput }, network : { me } } = state;

        // If the output has not changed, do nothing.
        if (prevOutput && prevOutput.hostname === newOutput.hostname) {
            return;
        }

        const getPlayerState = () => {

            const playerState = [
                'player',
                'queue',
                'queueCursor'
            ];

            return {
                ...pick(state, playerState),
                elapsed: lib.player.getCurrentTime()
            }
        };

        // Add the isLocal bool to the output object for convenience elsewhere.
        const isLocal = newOutput.hostname === me.hostname;
        const newOutputWithIsLocal = { ...newOutput, isLocal };

        // If output has swapped to our computer
        if (isLocal) {
            // Ask the previous output for us to be removed as an observer
            // This may fail if the other Museeks stops working.
            // If so, this is fine... Probably...
            lib.api.actions.network.disconnectAsOutput(prevOutput, {
                peer: utils.getMeWithIP(me, prevOutput)
            });

            // Dispatch the change event to update the ui
            // This has promise.resolve so we get fulfilled events
            // to match the other case.
            dispatch({
                type: 'NETWORK/SET_OUTPUT',
                payload: Promise.resolve(),
                meta: {
                    newOutput: newOutputWithIsLocal,
                    prevOutput
                }
            })

        } else { // If output has changed to another computer

            const meWithIP = utils.getMeWithIP(me, newOutput);
            const playerState = getPlayerState();

            const makeRemote = (track) => ({
                ...track,
                path: lib.utils.trackEndpoint({
                    _id: track._id,
                    peer: me
                }),
                cover: lib.utils.coverEndpoint({
                    _id: track._id,
                    peer: me
                }),
                owner: meWithIP
            });

            const queueWithRemotePaths = playerState.queue.map((track) => track.owner.hostname === me.hostname
                ? makeRemote(track)
                : track
            );

            const remoteState = {
                ...playerState,
                queue: queueWithRemotePaths
            }

            // We ask the output device to set us as an observer.
            dispatch({
                type: 'NETWORK/SET_OUTPUT',
                payload: lib.api.actions.network.connectAsOutput(newOutput, {
                    peer: meWithIP,
                    state: remoteState
                }),
                meta: {
                    newOutput: newOutputWithIsLocal,
                    prevOutput
                }
            });
        }
    };

    const connectAsOutput = ({ state, peer }) => (dispatch) => {
        console.log(state, peer)
        // Stop the player from playing
        dispatch(lib.actions.player.stop());

        // Apply the input's state

        // Set the queue
        dispatch(lib.actions.queue.setQueue(state.queue));

        // Load the track
        dispatch(lib.actions.player.load(state.queue[state.queueCursor]._id));

        // Set the play/pause/stop status
        if (state.player.playStatus === 'pause') {
            dispatch(lib.actions.player.pause());
        } else if (state.player.playStatus === 'stop') {
            dispatch(lib.actions.player.stop());
        } else if (state.player.playStatus === 'play') {
            dispatch(lib.actions.player.play());
        }

        // Set repeat
        dispatch(lib.actions.player.repeat(state.player.repeat));

        // Set Shuffle
        dispatch(lib.actions.player.shuffle(state.player.shuffle));

        // Set the elapsed time
        dispatch(lib.actions.player.jumpTo(state.elapsed));

        // Add the input computer as an observer
        dispatch(lib.actions.network.addObserver(peer));
    };

    const disconnectAsOutput = ({ peer }) => (dispatch) => {
        dispatch(removeObserver({ peer }));
    };

    const addObserver = ({ ip, hostname, platform }) => ({
        type: 'NETWORK/ADD_OBSERVER',
        payload: {
            peer: {
                ip,
                hostname,
                platform
            }
        }
    });

    const removeObserver = (peer) => ({
        type: 'NETWORK/REMOVE_OBSERVER',
        payload: {
            peer
        }
    });

    return {
        peerFound,
        setOutput,
        connectAsOutput,
        disconnectAsOutput,
        addObserver,
        removeObserver
    };
}

export default library;
<|endoftext|>


<commit_before>/* Author:
    RedDelicious
    Company: Kaleidos Open Source
*/

/* gettext dummy wrapper if not exists */

if (window.gettext === undefined) {
    window.gettext = function(text) {
        return text;
    };
}

if (window.interpolate === undefined) {
    window.interpolate = function(fmt, obj, named) {
        if (named) {
            return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])});
        } else {
            return fmt.replace(/%s/g, function(match){return String(obj.shift())});
        }
    };
}

$(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            !('/^(\/\/|http:|https:).*\/'.test(url)); // or any other URL that isn't scheme relative or absolute i.e relative.
    }

    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

/* Global macadjan  module namespace. */

var Macadjan = {}

Macadjan.Category = Backbone.Model.extend({});
Macadjan.SubCategory = Backbone.Model.extend({});

Macadjan.CategoryCollection = Backbone.Collection.extend({
    model: Macadjan.Category
});

Macadjan.SubCategoryCollection = Backbone.Collection.extend({
    model: Macadjan.SubCategory
});

Macadjan.categories = new Macadjan.CategoryCollection();
Macadjan.subCategories = new Macadjan.SubCategoryCollection();

Macadjan.Map = Backbone.View.extend({
    el: $("#map-block"),

    events: {},

    initializeControls: function() {
        this.navigationControl = new OpenLayers.Control.Navigation();
        this.layerSwitcherControl = new OpenLayers.Control.LayerSwitcher();
        this.panZoomControl = new OpenLayers.Control.PanZoomBar();
    },

    parseBounds: function() {
        var b = {
            "left": this.$el.data('map-bounds-left') || -20037508.34,
            "right": this.$el.data('map-bounds-right') || 20037508.34,
            "top": this.$el.data('map-bounds-top') || 20037508.34,
            "bottom": this.$el.data('map-bounds-bottom') || -20037508.34
        };

        return new OpenLayers.Bounds(b['left'], b['bottom'], b['right'], b['top']);
    },

    parseZoomLevels: function() {
        return 18;
    },

    parseUnits: function() {
        return "meters";
    },

    parseMaxResolution: function() {
        return 156543;
    },

    initialize: function() {
        _.bindAll(this);

        this.initializeControls();
        this.mapInitial = {
            projection: new OpenLayers.Projection('EPSG:4326'),
            controls: [
                this.navigationControl,
                this.layerSwitcherControl,
                this.panZoomControl
            ],
            maxExtent: this.parseBounds(),
            numZoomLevels: this.parseZoomLevels(),
            units:this.parseUnits(),
            maxResolution: this.parseMaxResolution()
        };

        this.map = new OpenLayers.Map(this.$el.attr('id'), this.mapInitial);

        this.osm = this.createOsmLayer();
        this.map.addLayer(this.osm);

        // Center map to initial coords
        this.centerMap();

        // Create points layer
        this.pointsLayer = this.createPointsLayer();
        this.map.addLayer(this.pointsLayer);

        // Create select control
        this.selectControl = this.createSelectControl(this.pointsLayer);
        this.map.addControl(this.selectControl);

        this.pointsLayer.events.on({
            "featureselected": this.onFeatureSelect,
            "featureunselected": this.onFeatureUnselect,
        });
    },

    onFeatureSelect: function(evt) {
        var feature = evt.feature;
        var content;

        if (!feature.cluster) {
            content = feature.attributes.title + '
' + feature.attributes.description;
        } else {
            content = '';
            var length = Math.min(feature.cluster.length, 50);
            for (var c = 0; c < length; c++) {
                content += feature.cluster[c].attributes.title + '
';
            }
            if (length < feature.cluster.length) {
                content += '(...)';
            }
        }
        var self = this;

        var popup = new OpenLayers.Popup.FramedCloud('featurePopup',
            feature.geometry.getBounds().getCenterLonLat(),
            new OpenLayers.Size(300, 100),
            content, null, true,
            function(evt) {
                var feature = this.feature;
                if (feature.layer) {
                    self.selectControl.unselect(feature);
                } else {
                    this.destroy();
                }
            }
        );

        popup.maxSize = new OpenLayers.Size(500, 300);
        feature.popup = popup;
        popup.feature = feature;
        map.addPopup(popup, true);
    },

    onFeatureUnselect: function(evt) {
        var feature = evt.feature;
        if (feature.popup) {
            popup.feature = null;
            map.removePopup(feature.popup);
            feature.popup.destroy();
            feature.popup = null;
        }
    },

    centerMap: function() {
        var initialLon = this.$el.data('initial-lon');
        var initialLat = this.$el.data('initial-lat');
        var initialZoom = this.$el.data('initial-zoom');

        this.map.setCenter(new OpenLayers.LonLat(initialLon, initialLat).transform(
            new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
            new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
        ), initialZoom);
    },

    createOsmLayer: function() {
        return new OpenLayers.Layer.OSM({
            transitionEffect: 'resize'
        })
    },

    createPointsLayer: function() {
        this.bboxStrategy = new OpenLayers.Strategy.BBOX();
        this.clusterStrategy = new OpenLayers.Strategy.Cluster({
            distance: 50,
            threshold: 5
        });

        this.protocol = new OpenLayers.Protocol.HTTP({
            url: this.$el.data('api-url'),
            params: {'features': '|||'},
            format: new OpenLayers.Format.Text(),
        });

        var pointsLayerInitial = {
            strategies: [
                this.bboxStrategy,
                this.clusterStrategy
            ],
            protocol: this.protocol,
            //~ styleMap: new OpenLayers.StyleMap({
                //~ "default": cluster_style,
                //~ "select": {
                    //~ fillColor: "#8aeeef",
                    //~ strokeColor: "#32a8a9"
                //~ }
            //~ })
        };

        return new OpenLayers.Layer.Vector("POIs", pointsLayerInitial);
    },

    createSelectControl: function(layer) {
        return new OpenLayers.Control.SelectFeature(layer);
    }
});

Macadjan.map = new Macadjan.Map();

Macadjan.MainView = Backbone.View.extend({
    el: $("body"),

    events: {},

    initialize: function() {
        _.bindAll(this);
        this.container = this.$(".main-container");
    },
});

Macadjan.main = new Macadjan.MainView();

<commit_msg>Add clustering and refresh<commit_after>/* Author:
    RedDelicious
    Company: Kaleidos Open Source
*/

/* gettext dummy wrapper if not exists */

if (window.gettext === undefined) {
    window.gettext = function(text) {
        return text;
    };
}

if (window.interpolate === undefined) {
    window.interpolate = function(fmt, obj, named) {
        if (named) {
            return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])});
        } else {
            return fmt.replace(/%s/g, function(match){return String(obj.shift())});
        }
    };
}

$(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            !('/^(\/\/|http:|https:).*\/'.test(url)); // or any other URL that isn't scheme relative or absolute i.e relative.
    }

    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});

/* Global macadjan  module namespace. */

var Macadjan = {}

Macadjan.Category = Backbone.Model.extend({});
Macadjan.SubCategory = Backbone.Model.extend({});

Macadjan.CategoryCollection = Backbone.Collection.extend({
    model: Macadjan.Category
});

Macadjan.SubCategoryCollection = Backbone.Collection.extend({
    model: Macadjan.SubCategory
});

Macadjan.categories = new Macadjan.CategoryCollection();
Macadjan.subCategories = new Macadjan.SubCategoryCollection();

Macadjan.Map = Backbone.View.extend({
    el: $("#map-block"),

    events: {},

    initializeControls: function() {
        this.navigationControl = new OpenLayers.Control.Navigation();
        this.layerSwitcherControl = new OpenLayers.Control.LayerSwitcher();
        this.panZoomControl = new OpenLayers.Control.PanZoomBar();
    },

    parseBounds: function() {
        var b = {
            "left": this.$el.data('map-bounds-left') || -20037508.34,
            "right": this.$el.data('map-bounds-right') || 20037508.34,
            "top": this.$el.data('map-bounds-top') || 20037508.34,
            "bottom": this.$el.data('map-bounds-bottom') || -20037508.34
        };

        return new OpenLayers.Bounds(b['left'], b['bottom'], b['right'], b['top']);
    },

    parseZoomLevels: function() {
        return 18;
    },

    parseUnits: function() {
        return "meters";
    },

    parseMaxResolution: function() {
        return 156543;
    },

    initialize: function() {
        _.bindAll(this);

        this.initializeControls();
        this.mapInitial = {
            projection: new OpenLayers.Projection('EPSG:4326'),
            controls: [
                this.navigationControl,
                this.layerSwitcherControl,
                this.panZoomControl
            ],
            maxExtent: this.parseBounds(),
            numZoomLevels: this.parseZoomLevels(),
            units:this.parseUnits(),
            maxResolution: this.parseMaxResolution()
        };

        this.map = new OpenLayers.Map(this.$el.attr('id'), this.mapInitial);

        this.osm = this.createOsmLayer();
        this.map.addLayer(this.osm);

        // Center map to initial coords
        this.centerMap();

        // Create points layer
        this.pointsLayer = this.createPointsLayer();
        this.map.addLayer(this.pointsLayer);

        // Create select control
        this.selectControl = this.createSelectControl(this.pointsLayer);
        this.map.addControl(this.selectControl);

        this.pointsLayer.events.on({
            "featureselected": this.onFeatureSelect,
            "featureunselected": this.onFeatureUnselect,
        });
    },

    onFeatureSelect: function(evt) {
        var feature = evt.feature;
        var content;

        if (!feature.cluster) {
            content = feature.attributes.title + '
' + feature.attributes.description;
        } else {
            content = '';
            var length = Math.min(feature.cluster.length, 50);
            for (var c = 0; c < length; c++) {
                content += feature.cluster[c].attributes.title + '
';
            }
            if (length < feature.cluster.length) {
                content += '(...)';
            }
        }
        var self = this;

        var popup = new OpenLayers.Popup.FramedCloud('featurePopup',
            feature.geometry.getBounds().getCenterLonLat(),
            new OpenLayers.Size(300, 100),
            content, null, true,
            function(evt) {
                var feature = this.feature;
                if (feature.layer) {
                    self.selectControl.unselect(feature);
                } else {
                    this.destroy();
                }
            }
        );

        popup.maxSize = new OpenLayers.Size(500, 300);
        feature.popup = popup;
        popup.feature = feature;
        map.addPopup(popup, true);
    },

    onFeatureUnselect: function(evt) {
        var feature = evt.feature;
        if (feature.popup) {
            popup.feature = null;
            map.removePopup(feature.popup);
            feature.popup.destroy();
            feature.popup = null;
        }
    },

    centerMap: function() {
        var initialLon = this.$el.data('initial-lon');
        var initialLat = this.$el.data('initial-lat');
        var initialZoom = this.$el.data('initial-zoom');

        this.map.setCenter(new OpenLayers.LonLat(initialLon, initialLat).transform(
            new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
            new OpenLayers.Projection("EPSG:900913") // to Spherical Mercator Projection
        ), initialZoom);
    },

    createOsmLayer: function() {
        return new OpenLayers.Layer.OSM({
            transitionEffect: 'resize'
        })
    },

    createPointsLayer: function() {
        this.bboxStrategy = new OpenLayers.Strategy.BBOX();
        this.clusterStrategy = new OpenLayers.Strategy.Cluster({
            distance: 50,
            threshold: 5
        });
        this.refreshStrategy = new OpenLayers.Strategy.Refresh({
            force: true,
            active: true,
        });

        this.protocol = new OpenLayers.Protocol.HTTP({
            url: this.$el.data('api-url'),
            params: {'features': '|||'},
            format: new OpenLayers.Format.Text(),
        });

        this.style = new OpenLayers.Style({
            pointRadius: "${radius}",
            //fillColor: "#cc6633",
            fillColor: "#cc1111",
            fillOpacity: 0.9,
            //strokeColor: "#ffcc66",
            strokeColor: "#cc1111",
            strokeWidth: 10,
            strokeOpacity: 0.4,
            label: "${count}",
            fontColor: "#ffffff",
        },{
            context: {
                radius: function(feature) {
                    return Math.min(Math.max(feature.attributes.count, 10), 50);
                },
                count: function(feature) {
                    return feature.attributes.count;
                }
            }
        });

        var pointsLayerArgs = {
            strategies: [
                this.bboxStrategy,
                this.clusterStrategy,
                this.refreshStrategy,
            ],
            protocol: this.protocol,
             styleMap: new OpenLayers.StyleMap({
                 "default": this.style,
                 "select": {
                     fillColor: "#8aeeef",
                     strokeColor: "#32a8a9"
                 }
             })
        };

        return new OpenLayers.Layer.Vector("POIs", pointsLayerArgs);
    },

    createSelectControl: function(layer) {
        return new OpenLayers.Control.SelectFeature(layer);
    }
});

Macadjan.map = new Macadjan.Map();

Macadjan.MainView = Backbone.View.extend({
    el: $("body"),

    events: {},

    initialize: function() {
        _.bindAll(this);
        this.container = this.$(".main-container");
    },
});

Macadjan.main = new Macadjan.MainView();

<|endoftext|>


<commit_before>const MarketContractOraclize = artifacts.require("TestableMarketContractOraclize");
const MarketCollateralPool = artifacts.require("MarketCollateralPool");
const MarketToken = artifacts.require("MarketToken");
const CollateralToken = artifacts.require("CollateralToken");
const OrderLib = artifacts.require("OrderLib");
const Helpers = require('./helpers/Helpers.js')

// test to ensure callback gas is within limits when settling contracts
contract('MarketContractOraclize.CallBackExpiration', function(accounts) {
    let orderLib;
    let tradeHelper;
    let collateralPool;
    let collateralToken;
    let marketToken;
    let marketContract;

    const accountMaker = accounts[0];

    before(async function() {
        collateralPool = await MarketCollateralPool.deployed();
        marketToken = await MarketToken.deployed();
        marketContract = await MarketContractOraclize.deployed();
        orderLib = await OrderLib.deployed();
        collateralToken = await CollateralToken.deployed();
        tradeHelper = await Helpers.TradeHelper(MarketContractOraclize, OrderLib, CollateralToken, MarketCollateralPool);
    })

    it("gas used by Oraclize callback is within specified limit", async function() {
        const marketContractExpirationInTenSeconds = Math.floor(Date.now() / 1000) + 10;
        const priceFloor = 1;
        const priceCap = 1000000; // 10k USD
        let gasLimit = 6500000;  // gas limit for development network
        let block = web3.eth.getBlock("latest");
        if (block.gasLimit > 7000000) {  // coverage network
            gasLimit = block.gasLimit;
        }
        let txReceipt = null;  // Oraclize callback transaction receipt
        MarketContractOraclize.new(
            "ETHUSD-10",
            marketToken.address,
            collateralToken.address,
            [priceFloor, priceCap, 2, 1, marketContractExpirationInTenSeconds],
            "URL",
            "json(https://api.kraken.com/0/public/Ticker?pair=ETHUSD).result.XETHZUSD.c.0",
            { gas: gasLimit, value: web3.toWei('.1', 'ether'), accountMaker}
        ).then(async function(deployedMarketContract) {

            let oraclizeCallbackGasCost = await deployedMarketContract.QUERY_CALLBACK_GAS.call();
            let contractSettledEvent = deployedMarketContract.ContractSettled();
            contractSettledEvent.watch(async (err, response) => {
                if (err) {
                    console.log(err);
                };

                assert.equal(response.event, 'ContractSettled');
                txReceipt = await web3.eth.getTransactionReceipt(response.transactionHash);
                console.log("Oraclize callback gas used : " + txReceipt.gasUsed);
                assert.isBelow(txReceipt.gasUsed, oraclizeCallbackGasCost,
                               "Callback tx claims to have used more gas than allowed!");
                contractSettledEvent.stopWatching();
                return response;
            });
        });

        let waitForContractSettledEvent = ms => new Promise((r, j) => {
            var check = () => {
              if (txReceipt)
                r()
              else if((ms -= 1000) < 0)
                j('Oraclize time out!')
              else
                setTimeout(check, 1000)
            }
            setTimeout(check, 1000)
        });

        await waitForContractSettledEvent(30000);
        console.log(txReceipt);
        assert.notEqual(txReceipt, null, "Oraclize callback did not arrive. Please increase QUERY_CALLBACK_GAS!");

    })
});
<commit_msg>test/GasOraclize: Update test case for Oraclize callback.<commit_after>const MarketContractOraclize = artifacts.require("TestableMarketContractOraclize");
const MarketCollateralPool = artifacts.require("MarketCollateralPool");
const MarketToken = artifacts.require("MarketToken");
const CollateralToken = artifacts.require("CollateralToken");
const OrderLib = artifacts.require("OrderLib");
const Helpers = require('./helpers/Helpers.js')

// test to ensure callback gas is within limits when settling contracts
contract('MarketContractOraclize.CallBackExpiration', function(accounts) {
    let orderLib;
    let tradeHelper;
    let collateralPool;
    let collateralToken;
    let marketToken;
    let marketContract;

    const accountMaker = accounts[0];

    before(async function() {
        collateralPool = await MarketCollateralPool.deployed();
        marketToken = await MarketToken.deployed();
        marketContract = await MarketContractOraclize.deployed();
        orderLib = await OrderLib.deployed();
        collateralToken = await CollateralToken.deployed();
        tradeHelper = await Helpers.TradeHelper(MarketContractOraclize, OrderLib, CollateralToken, MarketCollateralPool);
    })

    it("gas used by Oraclize callback is within specified limit", async function() {
        const marketContractExpirationInTenSeconds = Math.floor(Date.now() / 1000) + 10;
        const priceFloor = 1;
        const priceCap = 1000000; // 10k USD
        let gasLimit = 6500000;  // gas limit for development network
        let block = web3.eth.getBlock("latest");
        if (block.gasLimit > 7000000) {  // coverage network
            gasLimit = block.gasLimit;
        }
        let txReceipt = null;  // Oraclize callback transaction receipt

        MarketContractOraclize.new(
            "ETHUSD-10",
            marketToken.address,
            collateralToken.address,
            [priceFloor, priceCap, 2, 1, marketContractExpirationInTenSeconds],
            "URL",
            "json(https://api.kraken.com/0/public/Ticker?pair=ETHUSD).result.XETHZUSD.c.0",
            { gas: gasLimit, value: web3.toWei('.1', 'ether'), accountMaker}
        ).then(async function(deployedMarketContract) {
            let oraclizeCallbackGasCost = await deployedMarketContract.QUERY_CALLBACK_GAS.call();
            let contractSettledEvent = deployedMarketContract.ContractSettled();
            let updatedLastPriceEvent = deployedMarketContract.UpdatedLastPrice();

            contractSettledEvent.watch(async (err, response) => {
                if (err) {
                    console.log(err);
                };
                assert.equal(response.event, 'ContractSettled');
                txReceipt = await web3.eth.getTransactionReceipt(response.transactionHash);
                console.log("Oraclize callback gas used : " + txReceipt.gasUsed);
                assert.isBelow(txReceipt.gasUsed, oraclizeCallbackGasCost,
                               "Callback tx claims to have used more gas than allowed!");
                contractSettledEvent.stopWatching();
            });

            updatedLastPriceEvent.watch(async (err, response) => {
                if (err) {
                    console.log(err);
                };
                assert.equal(response.event, 'UpdatedLastPrice');
                await web3.eth.getTransactionReceipt(response.transactionHash);
                updatedLastPriceEvent.stopWatching();
            });
        });

    let waitForContractSettledEvent = ms => new Promise((r, j) => {
        var check = () => {
          if (txReceipt)
            r()
          else if((ms -= 1000) < 0)
            j('Oraclize time out!')
          else {
            setTimeout(check, 1000);
          }
        }
        setTimeout(check, 1000)
    });

    await waitForContractSettledEvent(30000);
    assert.notEqual(txReceipt, null, "Oraclize callback did not arrive. Please increase QUERY_CALLBACK_GAS!");

    })
});
<|endoftext|>


<commit_before><commit_msg>updated myclinic-drawer-forms<commit_after><|endoftext|>


<commit_before>conference = {{ conference_data|safe }};

function _render_tags(tags, selected) {
    if(!selected)
        selected = [];

    var wrapper = $('

');

    var category_wrappers = {};
    var reverse = {};
    for(var category in conference.tags) {
        // reverse map, tag -> category
        for(var ix=0; ix<conference.tags[category].length; ix++)
            reverse[conference.tags[category][ix]] = category;

        // category, trigger
        var trigger = $('
' + category + '
');
        trigger.click(function(e) {
            e.preventDefault();
            $(this).next().toggle();
        });
        wrapper.append(trigger);

        // wrapper for the category tags
        var w = $('

');
        w.hide();
        category_wrappers[category] = w;
        wrapper.append(w);
    }

    for(var ix=0; ix<tags.length; ix++) {
        if(Object.prototype.toString.call(tags[ix]) === '[object Array]') {
            var t = tags[ix][0];
            var label = tags[ix][1];
        }
        else {
            var t = tags[ix];
            var label = t;
        }
        var a = $('' + label + '');
        var w = category_wrappers[reverse[t]];
        w.append(a);
        if(selected.indexOf(t) != -1) {
            a.addClass('selected');
            w.show();
        }
    }

    return wrapper;
}
function setup_conference_fields(ctx) {
    ctx = ctx || document;
    var tfields = $('.tag-field', ctx);
    if(tfields.length) {
        tfields.tagit({
            tagSource: function(search, showChoices) {
                if(!conference)
                    return;
                var needle = search.term.toLowerCase();
                var tags = [];
                for(var tag in conference.taggeditems) {
                    if(tag.toLowerCase().indexOf(needle) != -1)
                        tags.push(tag);
                }
                showChoices(tags);
            }
        });
        if(conference) {
            var tags = [];
            for(var key in conference.taggeditems) {
                tags.push(key);
            }
            tags.sort(function(a, b) {
                var a = a.toLowerCase();
                var b = b.toLowerCase();
                return a == b ? 0 : (a < b ? -1 : 1);
            });
            tfields.each(function() {
                var tag_field = $(this);
                var wrapper = _render_tags(tags, tag_field.tagit('assignedTags'));
                wrapper.find('a.tag').click(function(e) {
                    e.preventDefault();
                    $(this)
                        .parents('.field')
                        .children('.tag-field')
                        .tagit('createTag', this.innerHTML);
                });
                tag_field.
                    parent()
                    .children('ul.tagit')
                    .after(wrapper);
            });
        }
    }
    var tfields = $('.readonly-tag-field');
    if(tfields.length && conference) {
        var tags = [];
        for(var key in conference.taggeditems) {
            if(conference.taggeditems[key]['talk'] > 0) {
                tags.push([key, key + ' (' + conference.taggeditems[key]['talk'] +')']);
            }
        }
        tags.sort(function(a, b) {
            var a = a[0].toLowerCase();
            var b = b[0].toLowerCase();
            return a == b ? 0 : (a < b ? -1 : 1);
        });
        tfields
            .not('[data-conference-init]')
            .attr('data-conference-init', '1')
            .each(function() {
                var tag_field = $(this);
                var selected = $(this).val().split(',');
                $(selected).each(function(ix, v) {
                    selected[ix] = v.replace(new RegExp('"', 'g'), '');
                });
                var wrapper = _render_tags(tags, selected);
                wrapper.find('a.tag').click(function(e) {
                    var e = $(this);
                    var input = e.parents('.field').children('input');
                    var name = e.attr('data-tag');
                    var v = input.val();
                    if(v.indexOf(name) == -1) {
                        v = '"' + name + '",' + v;
                        e.addClass('selected');
                    }
                    else {
                        var r = new RegExp('"' + name + '",?');
                        v = v.replace(r, '');
                        e.removeClass('selected');
                    }
                    if(v.substr(v.length-1) == ',')
                        v = v.slice(0, -1);
                    input.val(v).change();
                    return false;
                });

                tag_field.after(wrapper);
            });
    }
    var mfields = $('.markedit-widget', ctx);
    if(mfields.length) {
        mfields.markedit({
            'preview_markup': '

',
            'toolbar': {
                'layout': 'heading bold italic bulletlist | link quote code image '
            }
        }).blur();
    }
    $('.pseudo-radio', ctx).click(function(e) {
        var pseudo = $(this);
        var p = pseudo.parent();
        var input = $('input[type=hidden]', p);
        input.val(pseudo.attr('data-value'));
        input.change();
        $('.pseudo-radio', p).removeClass('checked');
        pseudo.addClass('checked');
    });
    $('.pseudo-radio-field input', ctx).each(function() {
        var initial = $(this).val();
        $('.pseudo-radio', $(this).parent()).removeClass('checked');
        $('.pseudo-radio[data-value=' + initial + ']', $(this).parent()).addClass('checked');
    });
}
$(function() {
    setup_conference_fields();
});

<commit_msg>WIP inizio refactoring per ridurre la latenza nel rendering dei field<commit_after>conference = {{ conference_data|safe }};

function select_tag(field, tag, mode) {
    mode = mode || "toggle";
    field = $(field);
    if(!field.hasClass('all-tags')) {
        field = field.next();
        if(!field.hasClass('all-tags'))
            return false;
    }

    var t = field.find('.tag[data-tag=' + tag + ']');
    if(!t.length)
        return false;

    var input = field
        .parents('.field')
        .children('input');

    if(mode == "exclusive") {
        field
            .find('.tag')
                .removeClass('selected')
                .end()
            .children('div')
                .hide()
        input.val('');
        mode = 'add';
    }
    if(mode == "toggle") {
        mode = input.val().indexOf(tag) == -1 ? 'add': 'remove';
    }
    var wrapper = t.parent();
    if(mode == "add") {
        t.addClass('selected');
        wrapper.show();
    }
    else if(mode == "remove") {
        t.removeClass('selected');
        /*
        if(wrapper.children('.tag.selected').length == 0) {
            wrapper.hide();
        }
        */
    }
    else {
        return false;
    }

    var v = input.val();
    var found = v.indexOf(tag) != -1;
    if(!found && mode == "add") {
        v = '"' + tag + '",' + v;
    }
    else if(found && mode == "remove") {
        var r = new RegExp('"' + tag + '",?');
        v = v.replace(r, '');
    }
    if(v.substr(v.length-1) == ',')
        v = v.slice(0, -1);

    input.val(v).change();

    return true;
}
function _render_tags(tags, selected) {
    if(!selected)
        selected = [];

    var wrapper = $('

');

    var category_wrappers = {};
    var reverse = {};
    for(var category in conference.tags) {
        // reverse map, tag -> category
        for(var ix=0; ix<conference.tags[category].length; ix++)
            reverse[conference.tags[category][ix]] = category;

        // category, trigger
        var trigger = $('
' + category + '
');
        trigger.click(function(e) {
            e.preventDefault();
            $(this).next().toggle();
        });
        wrapper.append(trigger);

        // wrapper for the category tags
        var w = $('

');
        w.hide();
        category_wrappers[category] = w;
        wrapper.append(w);
    }

    for(var ix=0; ix<tags.length; ix++) {
        if(Object.prototype.toString.call(tags[ix]) === '[object Array]') {
            var t = tags[ix][0];
            var label = tags[ix][1];
        }
        else {
            var t = tags[ix];
            var label = t;
        }
        var a = $('' + label + '');
        var w = category_wrappers[reverse[t]];
        w.append(a);
        if(selected.indexOf(t) != -1) {
            a.addClass('selected');
            w.show();
        }
    }

    return wrapper;
}
function _setup_readonly_tag_field(tag_field) {
        var tags = [];
        for(var key in conference.taggeditems) {
            if(conference.taggeditems[key]['talk'] > 0) {
                tags.push([key, key + ' (' + conference.taggeditems[key]['talk'] +')']);
            }
        }
        tags.sort(function(a, b) {
            var a = a[0].toLowerCase();
            var b = b[0].toLowerCase();
            return a == b ? 0 : (a < b ? -1 : 1);
        });

        var selected = tag_field.val().split(',');
        $(selected).each(function(ix, v) {
            selected[ix] = v.replace(new RegExp('"', 'g'), '');
        });
        var wrapper = _render_tags(tags, selected);
        wrapper.find('a.tag').click(function(e) {
            select_tag(tag_field, $(this).attr('data-tag'));
            return false;
        });

        tag_field.after(wrapper);
}
function setup_tag_field(field) {
    field = $(field);
    var check = field.data('data-conference-init');
    if(check)
        return;
    field.data('data-conference-init', 1);
    if(field.hasClass('tag-field')) {

    }
    else if(field.hasClass('readonly-tag-field')) {
        _setup_readonly_tag_field(field);
    }
}
function setup_conference_fields(ctx) {
    ctx = ctx || document;
    var tfields = $('.tag-field', ctx);
    if(tfields.length) {
        tfields.tagit({
            tagSource: function(search, showChoices) {
                if(!conference)
                    return;
                var needle = search.term.toLowerCase();
                var tags = [];
                for(var tag in conference.taggeditems) {
                    if(tag.toLowerCase().indexOf(needle) != -1)
                        tags.push(tag);
                }
                showChoices(tags);
            }
        });
        if(conference) {
            var tags = [];
            for(var key in conference.taggeditems) {
                tags.push(key);
            }
            tags.sort(function(a, b) {
                var a = a.toLowerCase();
                var b = b.toLowerCase();
                return a == b ? 0 : (a < b ? -1 : 1);
            });
            tfields.each(function() {
                var tag_field = $(this);
                var wrapper = _render_tags(tags, tag_field.tagit('assignedTags'));
                wrapper.find('a.tag').click(function(e) {
                    e.preventDefault();
                    $(this)
                        .parents('.field')
                        .children('.tag-field')
                        .tagit('createTag', this.innerHTML);
                });
                tag_field.
                    parent()
                    .children('ul.tagit')
                    .after(wrapper);
            });
        }
    }
    $('.readonly-tag-field').each(function() { setup_tag_field(this) });

    var mfields = $('.markedit-widget', ctx);
    if(mfields.length) {
        mfields.markedit({
            'preview_markup': '

',
            'toolbar': {
                'layout': 'heading bold italic bulletlist | link quote code image '
            }
        }).blur();
    }
    $('.pseudo-radio', ctx).click(function(e) {
        var pseudo = $(this);
        var p = pseudo.parent();
        var input = $('input[type=hidden]', p);
        input.val(pseudo.attr('data-value'));
        input.change();
        $('.pseudo-radio', p).removeClass('checked');
        pseudo.addClass('checked');
    });
    $('.pseudo-radio-field input', ctx).each(function() {
        var initial = $(this).val();
        $('.pseudo-radio', $(this).parent()).removeClass('checked');
        $('.pseudo-radio[data-value=' + initial + ']', $(this).parent()).addClass('checked');
    });
}
$(function() {
    setup_conference_fields();
});

<|endoftext|>


<commit_before>#!/usr/bin/env node

var NODE_TEST_PAGE = _multiline(function() {/*
__SCRIPT__

*/});

var BROWSER_TEST_PAGE = _multiline(function() {/*
<!DOCTYPE html><title>test</title>
<meta name="viewport" content="width=device-width, user-scalable=no">
<meta charset="utf-8">

__SCRIPT__

*/});

var fs   = require("fs");
var argv = process.argv.slice(2);
var WebModuleLib = process.argv[1].split("/").slice(0, -2).join("/") + "/lib/"; // "WebModule/lib/"
var Module = require(WebModuleLib + "Module.js");

put();

function put() {
    var verbose = true;
    var releaseBuild = false;
    var deps = Module.getDependencies(releaseBuild);

    if (verbose) {
//      console.log("\u001b[31m" + "packages: " + JSON.stringify(deps.packages, null, 2) + "\u001b[0m");
        console.log("\u001b[32m" + "tree: "     + JSON.stringify(deps.tree,     null, 2) + "\u001b[0m");
        console.log("\u001b[33m" + "modules: "  + JSON.stringify(deps.modules,  null, 2) + "\u001b[0m");
        console.log("files: "                   + JSON.stringify(deps.files,    null, 2));
    }
    var currentPackageJSON = JSON.parse(fs.readFileSync("package.json"));
    var pages = _createTestPage(deps.files, currentPackageJSON); // { browser, node }

    if ( !fs["existsSync"]("test") ) {
        console.error("\u001b[31m" + "ERROR. test/ directory not found." + "\u001b[0m");
    } else {
        if (verbose) {
            console.log( "update test/index.html: \n    "    + pages.browser.replace(/\n/g, "\n    " ) );
            console.log( "update test/index.node.js: \n    " + pages.node.replace(/\n/g, "\n    " ) );
        }
        fs.writeFileSync("test/index.html", pages.browser);
        fs.writeFileSync("test/index.node.js", pages.node);
    }
}

function _createTestPage(files,         // @arg Object - { all, node, worker, browser, label }
                         packagejson) { // @arg Object - package.json
                                        // @ret String

    var webmodule = packagejson["webmodule"];
    var requireFiles      = _uniqueArray(files.node.concat(webmodule["source"]).map(_node)).unique;
    var scriptFiles       = _uniqueArray(files.browser.concat(webmodule["source"]).map(_browser)).unique;
    var importScriptFiles = _uniqueArray(files.worker.concat(webmodule["source"]).map(_worker)).unique;

    var browserPage = BROWSER_TEST_PAGE;
    var nodePage = NODE_TEST_PAGE;

    if ( /(all|worker)/i.test( webmodule.target.join(" ") ) ) {
        importScriptFiles.push('importScripts(MESSAGE.BASE_DIR + "../' + webmodule.output + '");');
        importScriptFiles.push('importScripts(MESSAGE.BASE_DIR + "./testcase.js");');
        browserPage = browserPage.replace("__IMPORT_SCRIPTS__", importScriptFiles.join("\n    "));
    } else {
        browserPage = browserPage.replace("__IMPORT_SCRIPTS__", "");
    }
    if ( /(all|browser)/i.test( webmodule.target.join(" ") ) ) { // browser ready module
        scriptFiles.push('');
        scriptFiles.push('');
        browserPage = browserPage.replace("__SCRIPT__", scriptFiles.join("\n"));
    } else {
        browserPage = browserPage.replace("__SCRIPT__", "");
    }
    if ( /(all|node)/i.test( webmodule.target.join(" ") ) ) { // node ready module
        requireFiles.push('require("../' + webmodule.output + '");');
        requireFiles.push('require("./testcase.js");');
        nodePage = NODE_TEST_PAGE.replace("__SCRIPT__", requireFiles.join("\n"));
    } else {
        nodePage = NODE_TEST_PAGE.replace("__SCRIPT__", "");
    }
    return { browser: browserPage, node: nodePage };

    function _node(file)    { return 'require("../' + file + '");'; }
    function _worker(file)  { return 'importScripts(MESSAGE.BASE_DIR + "../' + file + '");'; }
    function _browser(file) { return ''; }
}

function _uniqueArray(source) { // @arg Array
                                // @ret Object - { unique:Array, dup:Array }
    var unique = [], dup = [], i = 0, iz = source.length;

    for (; i < iz; ++i) {
        if (unique.indexOf(source[i]) >= 0) {
            dup.push(source[i]);
        } else {
            unique.push(source[i]);
        }
    }
    return { unique: unique, dup: dup };
}

function _multiline(fn) { // @arg Function:
                          // @ret String:
    return (fn + "").split("\n").slice(1, -1).join("\n");
}

<commit_msg>add WorkerConsole polyfill<commit_after>#!/usr/bin/env node

var NODE_TEST_PAGE = _multiline(function() {/*
__SCRIPT__

*/});

var BROWSER_TEST_PAGE = _multiline(function() {/*
<!DOCTYPE html><title>test</title>
<meta name="viewport" content="width=device-width, user-scalable=no">
<meta charset="utf-8">

__SCRIPT__

*/});

var fs   = require("fs");
var argv = process.argv.slice(2);
var WebModuleLib = process.argv[1].split("/").slice(0, -2).join("/") + "/lib/"; // "WebModule/lib/"
var Module = require(WebModuleLib + "Module.js");

put();

function put() {
    var verbose = true;
    var releaseBuild = false;
    var deps = Module.getDependencies(releaseBuild);

    if (verbose) {
//      console.log("\u001b[31m" + "packages: " + JSON.stringify(deps.packages, null, 2) + "\u001b[0m");
        console.log("\u001b[32m" + "tree: "     + JSON.stringify(deps.tree,     null, 2) + "\u001b[0m");
        console.log("\u001b[33m" + "modules: "  + JSON.stringify(deps.modules,  null, 2) + "\u001b[0m");
        console.log("files: "                   + JSON.stringify(deps.files,    null, 2));
    }
    var currentPackageJSON = JSON.parse(fs.readFileSync("package.json"));
    var pages = _createTestPage(deps.files, currentPackageJSON); // { browser, node }

    if ( !fs["existsSync"]("test") ) {
        console.error("\u001b[31m" + "ERROR. test/ directory not found." + "\u001b[0m");
    } else {
        if (verbose) {
            console.log( "update test/index.html: \n    "    + pages.browser.replace(/\n/g, "\n    " ) );
            console.log( "update test/index.node.js: \n    " + pages.node.replace(/\n/g, "\n    " ) );
        }
        fs.writeFileSync("test/index.html", pages.browser);
        fs.writeFileSync("test/index.node.js", pages.node);
    }
}

function _createTestPage(files,         // @arg Object - { all, node, worker, browser, label }
                         packagejson) { // @arg Object - package.json
                                        // @ret String

    var webmodule = packagejson["webmodule"];
    var requireFiles      = _uniqueArray(files.node.concat(webmodule["source"]).map(_node)).unique;
    var scriptFiles       = _uniqueArray(files.browser.concat(webmodule["source"]).map(_browser)).unique;
    var importScriptFiles = _uniqueArray(files.worker.concat(webmodule["source"]).map(_worker)).unique;

    var browserPage = BROWSER_TEST_PAGE;
    var nodePage = NODE_TEST_PAGE;

    if ( /(all|worker)/i.test( webmodule.target.join(" ") ) ) {
        importScriptFiles.push('importScripts(MESSAGE.BASE_DIR + "../' + webmodule.output + '");');
        importScriptFiles.push('importScripts(MESSAGE.BASE_DIR + "./testcase.js");');
        browserPage = browserPage.replace("__IMPORT_SCRIPTS__", importScriptFiles.join("\n    "));
    } else {
        browserPage = browserPage.replace("__IMPORT_SCRIPTS__", "");
    }
    if ( /(all|browser)/i.test( webmodule.target.join(" ") ) ) { // browser ready module
        scriptFiles.push('');
        scriptFiles.push('');
        browserPage = browserPage.replace("__SCRIPT__", scriptFiles.join("\n"));
    } else {
        browserPage = browserPage.replace("__SCRIPT__", "");
    }
    if ( /(all|node)/i.test( webmodule.target.join(" ") ) ) { // node ready module
        requireFiles.push('require("../' + webmodule.output + '");');
        requireFiles.push('require("./testcase.js");');
        nodePage = NODE_TEST_PAGE.replace("__SCRIPT__", requireFiles.join("\n"));
    } else {
        nodePage = NODE_TEST_PAGE.replace("__SCRIPT__", "");
    }
    return { browser: browserPage, node: nodePage };

    function _node(file)    { return 'require("../' + file + '");'; }
    function _worker(file)  { return 'importScripts(MESSAGE.BASE_DIR + "../' + file + '");'; }
    function _browser(file) { return ''; }
}

function _uniqueArray(source) { // @arg Array
                                // @ret Object - { unique:Array, dup:Array }
    var unique = [], dup = [], i = 0, iz = source.length;

    for (; i < iz; ++i) {
        if (unique.indexOf(source[i]) >= 0) {
            dup.push(source[i]);
        } else {
            unique.push(source[i]);
        }
    }
    return { unique: unique, dup: dup };
}

function _multiline(fn) { // @arg Function:
                          // @ret String:
    return (fn + "").split("\n").slice(1, -1).join("\n");
}

<|endoftext|>


<commit_before>var Module = require('../lib/Module'),
    Datasource = require('../lib/Datasource'),
    Q = require('q');

describe('Module', function () {
  var mod,
      moduleConfig,
      moduleData,
      deferred;

  beforeEach(function () {
    moduleConfig = {
      'title': 'test',
      'format': {
        'type': 'number'
      },
      'module-type': 'kpi',
      'value-attribute': 'specific_data',
      'data-source': {
        'data-group': 'transactional-services',
        'data-type': 'summaries',
        'query-params': {
          'sort_by': '_timestamp:descending',
          'filter_by': [
            'service_id:bis-accounts-filing',
            'type:seasonally-adjusted'
          ]
        }
      }
    };

    moduleData = [
      {
        '_quarter_start_at': '2013-07-01T00:00:00+00:00',
        '_timestamp': '2013-07-01T00:00:00+00:00',
        'end_at': '2014-07-01T00:00:00+00:00',
        'specific_data': 1
      },
      {
        '_quarter_start_at': '2013-04-01T00:00:00+00:00',
        '_timestamp': '2013-07-01T00:00:00+00:00',
        'end_at': '2014-07-01T00:00:00+00:00',
        'specific_data': 2
      },
      {
        '_quarter_start_at': '2013-01-01T00:00:00+00:00',
        '_timestamp': '2013-07-01T00:00:00+00:00',
        'end_at': '2014-07-01T00:00:00+00:00',
        'specific_data': 1
      }
    ];

    sinon.spy(Datasource);

    mod = new Module(moduleConfig);

    deferred = Q.defer();

    sinon.stub(Datasource.prototype, 'getData').returns(deferred.promise);
  });

  afterEach(function () {
    Datasource.prototype.getData.restore();
  });

  describe('init', function () {

    it('sets the moduleConfig to the moduleConfig property', function () {
      mod.moduleConfig.should.eql(moduleConfig);
    });

    it('sets a datasource for the module', function () {
      mod.dataSource.should.be.instanceOf(Datasource);
    });

    it('sets a module axes', function () {
      mod.axes.should.eql({
        x: {
          format: 'date',
          key: [
            '_quarter_start_at',
            'end_at'
          ],
          label: 'Quarter'
        },
        y: [{
          format: {
            type: 'number'
          },
          key: 'specific_data',
          label: 'test'
        }]
      });
    });

  });

  describe('isSupported', function () {

    it('retuns true for supported modules', function () {
      mod.isSupported('realtime').should.equal(true);
      mod.isSupported('kpi').should.equal(true);
      mod.isSupported('single_timeseries').should.equal(true);
      mod.isSupported('user_satisfaction_graph').should.equal(true);
    });

    it('returns false for unsupported modules', function () {
      mod.isSupported('something_unsupported').should.equal(false);
    });

  });

  describe('getData', function () {

    it('calls getData on the dataSource', function () {
      mod.getData();

      Datasource.prototype.getData.should.have.been.calledOnce;
    });

    it('sets the response to the dataSource property', function () {
      deferred.resolve({
        data: moduleData
      });

      return mod.getData().then(function () {
        mod.dataSource.data.should.equal(moduleData);
      });
    });

  });

  describe('resolve()', function () {

    it('gets the data for a module and sets it to the dataSource property', function () {
      deferred.resolve({
        data: moduleData
      });

      return mod.resolve()
        .then(function () {
          mod.dataSource.data.should.eql(moduleData);
        });
    });

    it('rejects the promise if the module is not supported (so cant resolve)', function () {

      mod.moduleConfig['module-type'] = 'something_unsupported';

      return mod.resolve().should.be.rejected;
    });

  });
});
<commit_msg>Added extra tests to cover module axes<commit_after>var Module = require('../lib/Module'),
    Datasource = require('../lib/Datasource'),
    Q = require('q');

describe('Module', function () {
  var mod,
      moduleConfig,
      moduleData,
      deferred;

  beforeEach(function () {
    moduleConfig = {
      'title': 'test',
      'format': {
        'type': 'number'
      },
      'module-type': 'kpi',
      'value-attribute': 'specific_data',
      'data-source': {
        'data-group': 'transactional-services',
        'data-type': 'summaries',
        'query-params': {
          'sort_by': '_timestamp:descending',
          'filter_by': [
            'service_id:bis-accounts-filing',
            'type:seasonally-adjusted'
          ]
        }
      }
    };

    moduleData = [
      {
        '_quarter_start_at': '2013-07-01T00:00:00+00:00',
        '_timestamp': '2013-07-01T00:00:00+00:00',
        'end_at': '2014-07-01T00:00:00+00:00',
        'specific_data': 1
      },
      {
        '_quarter_start_at': '2013-04-01T00:00:00+00:00',
        '_timestamp': '2013-07-01T00:00:00+00:00',
        'end_at': '2014-07-01T00:00:00+00:00',
        'specific_data': 2
      },
      {
        '_quarter_start_at': '2013-01-01T00:00:00+00:00',
        '_timestamp': '2013-07-01T00:00:00+00:00',
        'end_at': '2014-07-01T00:00:00+00:00',
        'specific_data': 1
      }
    ];

    sinon.spy(Datasource);

    mod = new Module(moduleConfig);

    deferred = Q.defer();

    sinon.stub(Datasource.prototype, 'getData').returns(deferred.promise);
  });

  afterEach(function () {
    Datasource.prototype.getData.restore();
  });

  describe('init', function () {

    it('sets the moduleConfig to the moduleConfig property', function () {
      mod.moduleConfig.should.eql(moduleConfig);
    });

    it('sets a datasource for the module', function () {
      mod.dataSource.should.be.instanceOf(Datasource);
    });

    describe('module axes', function () {

      it('should return with axes data for the KPI module', function () {
        mod.axes.x.should.eql({
          'label': 'Quarter',
          'key': ['_quarter_start_at', 'end_at'],
          'format': 'date'
        });

        mod.axes.y.should.eql([{
          label: 'test',
          key: 'specific_data',
          format: {
            type: 'number'
          }
        }]);
      });

      it('should return with axes data for the SINLE_TIMESERIES module', function () {
        moduleConfig.axes = {
          x: {
            label: 'Date',
            key: ['_start_at', '_end_at'],
            format: 'date'
          }
        };
        moduleConfig['module-type'] = 'single_timeseries';
        moduleConfig['format-options'] = {
          'type': 'number'
        };

        mod = new Module(moduleConfig);

        mod.axes.x.should.eql({
          'label': 'Date',
          'key': ['_start_at', '_end_at'],
          'format': 'date'
        });

        mod.axes.y.should.eql([{
          key: 'specific_data',
          format: {
            type: 'number'
          }
        }]);
      });

      it('should assume axis unit is integer if not specified', function () {
        moduleConfig.axes = {
          'y': [{
            'label': 'User satisfaction',
            'key': 'satisfaction:sum',
            'format': 'percent'
          }, {'key': 'respondents', 'label': 'Number of respondents'}],
          'x': {'label': 'Date', 'key': ['_start_at', '_end_at'], 'format': 'date'}
        };
        moduleConfig['module-type'] = 'single_timeseries';

        mod = new Module(moduleConfig);

        mod.axes.y.should.eql([
          {
            'label': 'User satisfaction',
            'key': 'specific_data',
            'format': 'percent'
          },
          {
            'key': 'respondents',
            'label': 'Number of respondents',
            'format': {
              type: 'integer'
            }
          }
        ]);
      });

      it('should return with axes data for the REALTIME module', function () {
        moduleConfig['module-type'] = 'realtime';

        mod = new Module(moduleConfig);

        mod.axes.x.should.eql({
          'label': 'Time',
          'key': '_timestamp',
          'format': 'time'
        });

        mod.axes.y.should.eql([{
          key: 'unique_visitors',
          format: 'integer',
          label: 'Number of unique visitors'
        }]);
      });

    });

  });

  describe('isSupported', function () {

    it('retuns true for supported modules', function () {
      mod.isSupported('realtime').should.equal(true);
      mod.isSupported('kpi').should.equal(true);
      mod.isSupported('single_timeseries').should.equal(true);
      mod.isSupported('user_satisfaction_graph').should.equal(true);
    });

    it('returns false for unsupported modules', function () {
      mod.isSupported('something_unsupported').should.equal(false);
    });

  });

  describe('getData', function () {

    it('calls getData on the dataSource', function () {
      mod.getData();

      Datasource.prototype.getData.should.have.been.calledOnce;
    });

    it('sets the response to the dataSource property', function () {
      deferred.resolve({
        data: moduleData
      });

      return mod.getData().then(function () {
        mod.dataSource.data.should.equal(moduleData);
      });
    });

  });

  describe('resolve()', function () {

    it('gets the data for a module and sets it to the dataSource property', function () {
      deferred.resolve({
        data: moduleData
      });

      return mod.resolve()
        .then(function () {
          mod.dataSource.data.should.eql(moduleData);
        });
    });

    it('rejects the promise if the module is not supported (so cant resolve)', function () {

      mod.moduleConfig['module-type'] = 'something_unsupported';

      return mod.resolve().should.be.rejected;
    });

  });
});
<|endoftext|>