<commit_before>import React from 'react'
import { storiesOf } from '@storybook/react'
import Wrapper from './Wrapper'
import Tabs, { Tab } from '../src/Tabs'

storiesOf('Tabs', module)
  .addDecorator(story =>(
    <Wrapper bg='#000'>
      {story()}
    </Wrapper>
  ))
  .addWithJSX('default', () => (
    <Tabs>
      <Tab>Dashboard</Tab>
      <Tab>Mobilizações</Tab>
    </Tabs>
  ))
  .addWithJSX('with Tab active', () => (
    <Tabs>
      <Tab active>Dashboard</Tab>
      <Tab>Mobilizações</Tab>
    </Tabs>
  ))
<commit_msg>chore(bonde-styleguide): use addons-knobs in tabs<commit_after>import React from 'react'
import { storiesOf } from '@storybook/react'
import { withKnobs, text, boolean } from '@storybook/addon-knobs/react'
import Wrapper from './Wrapper'
import Tabs, { Tab } from '../src/Tabs'

const withBG = (story) =>(<Wrapper bg='#000'>{story()}</Wrapper>)

storiesOf('Tabs', module)
  .addDecorator(withKnobs)
  .addDecorator(withBG)
  .addWithJSX('default', () => (
    <Tab active={boolean('Active', false)}>{text('Children', 'Dashboard')}</Tab>
  ))
  .addWithJSX('with any tabs', () => (
    <Tabs>
      <Tab>Dashboard</Tab>
      <Tab>Mobilizações</Tab>
      <Tab>Comunidades</Tab>
    </Tabs>
  ))
<|endoftext|>


<commit_before>// LA VUE

var GameView = Backbone.View.extend({

	el: '#app',

	events: {

		'click .answer': "onAnswer",
	},

	initialize : function() {
		$('#homeBox').empty();

		var that = this;
		this.game = new Game();
		this.DuoCollection = new DuoCollection();
		this.DuoCollection.fetch({
		success: function(){that.render()},
  });
},

	pickNewDuo: function () {

		//Génére un numero alétoire entre 0 et le nombre total de duos dans la collection (this.DuoCollection.length)
		var randomNumber = Math.floor(Math.random() * (this.DuoCollection.length - 0));

		// Stocke dans une variable le duo choisi grâce au numero alétoire
		var duo = this.DuoCollection.at(randomNumber);

		return duo;
	},

	onAnswer: function (e) {
		e.preventDefault();

		var button = $(e.currentTarget);
		// récupère la réponse cliquée
		var answer = button.attr('data-answer');
		// récupère l'id du duo concerné
		var duoCid = button.attr('data-cid');
		// récupère le duo dans la collection
		var duo = this.DuoCollection.get(duoCid).toJSON();
		// récupère la bonne réponse
		var rightAnswer = duo.actor.isPresent.toString();

		// test if right answer
		if (answer == rightAnswer) {
			this.game.set('score',this.game.get('score')+1);
		} else {
			this.game.set('score',this.game.get('score')-1);
		}

		// console.log(this.game.get('score'));
		// console.log(answer);
		// console.log(rightAnswer);

		// TODO Save score in model (game.score)
		// TODO Save score in localStorage

		// display next question
		this.render();
	},

	getQuestionBoxTemplate: function (duo) {

		var movie = duo.toJSON().movie;
		var actor = duo.toJSON().actor;

		var questionBoxTemplate = '\

\

\

Was '+actor.name+' in '+movie.title+' ?
\

\

\

'+actor.name+'
\

\

\

'+movie.title+'
\

\

\

\
						YES\
						NO\

\

\

\
		';

		return $(questionBoxTemplate);
	},

	render : function () {

		var duo = this.pickNewDuo();
		$questionBoxTemplate = this.getQuestionBoxTemplate(duo);

		$questionBox = this.$('#questionBox');

		$questionBox.empty();
		$questionBox.append($questionBoxTemplate);

	}
});
<commit_msg>Optimisation + not changing score when wrong answere<commit_after>// LA VUE

var GameView = Backbone.View.extend({

	el: '#app',

	events: {

		'click .answer': "onAnswer",
	},

	initialize : function() {
		$('#homeBox').empty();

		var that = this;
		this.game = new Game();
		this.DuoCollection = new DuoCollection();
		this.DuoCollection.fetch({
		success: function(){that.render()},
  });
},

	pickNewDuo: function () {

		//Génére un numero alétoire entre 0 et le nombre total de duos dans la collection (this.DuoCollection.length)
		var randomNumber = Math.floor(Math.random() * (this.DuoCollection.length - 0));

		// Stocke dans une variable le duo choisi grâce au numero alétoire
		var duo = this.DuoCollection.at(randomNumber);

		return duo;
	},

	onAnswer: function (e) {
		e.preventDefault();

		var button = $(e.currentTarget);
		// récupère la réponse cliquée
		var answer = button.attr('data-answer');
		// récupère l'id du duo concerné
		var duoCid = button.attr('data-cid');
		// récupère le duo dans la collection
		var duo = this.DuoCollection.get(duoCid).toJSON();
		// récupère la bonne réponse
		var rightAnswer = duo.actor.isPresent.toString();
		var score = this.game.get('score');

		// test if right answer
		if (answer == rightAnswer) {
			this.game.set('score',score+1);
		} else {

		}

		// console.log(score);
		// console.log(answer);
		// console.log(rightAnswer);

		// TODO Save score in model (game.score)
		// TODO Save score in localStorage

		// display next question
		this.render();
	},

	getQuestionBoxTemplate: function (duo) {

		var movie = duo.toJSON().movie;
		var actor = duo.toJSON().actor;

		var questionBoxTemplate = '\

\

\

Was '+actor.name+' in '+movie.title+' ?
\

\

\

'+actor.name+'
\

\

\

'+movie.title+'
\

\

\

\
						YES\
						NO\

\

\

\
		';

		return $(questionBoxTemplate);
	},

	render : function () {

		var duo = this.pickNewDuo();
		$questionBoxTemplate = this.getQuestionBoxTemplate(duo);

		$questionBox = this.$('#questionBox');

		$questionBox.empty();
		$questionBox.append($questionBoxTemplate);

	}
});
<|endoftext|>


<commit_before>//
// Checkout
//

Caboose.Store.Modules.Checkout = (function() {
  self = {
    templates: {
      address: JST['caboose_store/checkout/address'],
      login: JST['caboose_store/checkout/login'],
      payment: JST['caboose_store/checkout/payment'],
      lineItems: JST['caboose_store/checkout/line_items'],
      shipping: JST['caboose_store/checkout/shipping'],
      forms: {
        signin: JST['caboose_store/checkout/forms/signin'],
        register: JST['caboose_store/checkout/forms/register'],
        guest: JST['caboose_store/checkout/forms/guest']
      }
    }
  };

  //
  // Initialize
  //

  self.initialize = function() {
    switch (window.location.pathname.replace(/\/$/, "")) {
      case '/checkout':
      case '/checkout/step-one':
        self.step = 1;
        break;
      case '/checkout/step-two':
        self.step = 2;
        break;
    }

    self.$checkout = $('#checkout')
    if (!self.$checkout.length) return false;
    self.loggedIn = $('body').data('logged-in');

    // TODO refactor this
    if (self.loggedIn) {
      $.post('/checkout/attach-user', function(response) {
        self.fetch(self.render);
      });
    } else {
      self.fetch(self.render);
    }

    self.bindEventHandlers();
  };

  //
  // Fetch
  //

  self.fetch = function(callback) {
    $.get('/cart/items', function(response) {
      self.order = response.order

      if (self.step == 2) {
        $.get('/checkout/shipping', function(response) {
          self.shippingRates = response.rates;
          self.selectedRate = response.selected_rate;
          callback();
        });
      } else {
        callback();
      }
    });
  };

  //
  // Events
  //

  self.bindEventHandlers = function() {
    self.$checkout.on('click', '[data-login-action]', self.loginClickHandler);
    self.$checkout.on('submit', '#checkout-login form', self.loginSubmitHandler);
    self.$checkout.on('change', 'input[type=checkbox][name=use_as_billing]', self.useAsBillingHandler);
    self.$checkout.on('click', '#checkout-continue button', self.continueHandler);
    self.$checkout.on('click', '#checkout-complete button', self.completeHandler);
    self.$checkout.on('change', '#checkout-shipping select', self.shippingChangeHandler);
    self.$checkout.on('change', '#checkout-payment form#payment select', self.expirationChangeHandler);
    self.$checkout.on('submit', '#checkout-payment form#payment', self.paymentSubmitHandler);
    //self.$checkout.on('load', '#checkout-payment iframe#relay', self.relayLoadHandler);

    self.$checkout.on('load', 'iframe#relay', function(event) {
      console.log(event);
      console.log($(event.target).contents());
    });
    //$(window).on('message', self.relayHandler);
  };

  self.loginClickHandler = function(event) {
    $section = self.$login.children('section');

    switch ($(event.target).data('login-action')) {
      case 'signin':
        $section.empty().html(self.templates.forms.signin());
        break;
      case 'register':
        $section.empty().html(self.templates.forms.register());
        break;
      case 'continue':
        $section.empty().html(self.templates.forms.guest());
        break;
    };
  };

  self.loginSubmitHandler = function(event) {
    event.preventDefault();
    var $form = $(event.target);

    $.ajax({
      type: $form.attr('method'),
      url: $form.attr('action'),
      data: $form.serialize(),
      success: function(response) {
        if (response.error || (response.errors && response.errors.length > 0)) {
          if ($form.find('.message').length) {
            $form.find('.message').empty().addClass('error').text(response.error || response.errors[0]);
          } else {
            $form.append($('<span/>').addClass('message error').text(response.error || response.errors[0]));
          }
        } else {
          if (response.logged_in) {
            self.$login.after($('<p/>').addClass('alert').text('You are now signed in').css('text-align', 'center')).remove();
            $.post('/checkout/attach-user');
          } else {
            self.$login.after($('<p/>').addClass('alert').text('Email successfully saved').css('text-align', 'center')).remove();
          }
        }

        self.fetch();
      }
    });
  };

  self.useAsBillingHandler = function(event) {
    if (event.target.checked) {
      self.$address.find('#billing').hide();
    } else {
      self.$address.find('#billing').show();
    }
  };

  self.continueHandler = function(event) {
    $form = self.$address.find('form');

    if (!self.order.email && !self.order.customer_id) {
      alert('Please sign in, register or choose to continue as a guest');
      return false;
    }

    $.ajax({
      type: $form.attr('method'),
      url: $form.attr('action'),
      data: $form.serialize(),
      success: function(response) {
        if (response.success) {
          window.location = '/checkout/step-two';
        } else {
          $form.find('.message').remove();
          $form.find('#' + response.address + ' h3').append($('<span/>').addClass('message error').text(response.errors[0]));
        }
      }
    });
  };

  self.shippingChangeHandler = function(event) {
    if (event.target.value == "") return false;

    $.ajax({
      url: '/checkout/shipping',
      type: 'put',
      data: { shipping_code: event.target.value },
      success: function(response) {
        if (response.success) {
          self.order = response.order;
          self.renderLineItems();
          self.renderPayment();
        }
      }
    });
  };

  self.expirationChangeHandler = function(event) {
    var $form = $('#checkout-payment #payment')
      , month = $form.find('select[name=month]').val()
      , year = $form.find('select[name=year]').val();

    $form.find('#expiration').val(month + year);
  };

  self.completeHandler = function(event) {
    if (self.$payment.length) self.$payment.find('form').submit();
  };

  self.paymentSubmitHandler = function(event) {
    event.preventDefault();

    if (!self.order.shipping_code) {
      alert('Please choose a shipping method');
    } else {
      self.$checkout.off('submit', '#checkout-payment form#payment');
      $(event.target).addClass('loading').submit();
    }
  };

  self.relayHandler = function(event) {
    var data = event.originalEvent.data
      , $form = $('form#payment');

    console.log('Relay: ', data);
    console.log('Relay Form: ', $form);
    console.log(self.$payment, self.$payment.find('form'));
    console.log('------');
    if (!$form.length) return false;
    console.log('still in relay');
    console.log('------------');

    if (data.success == true) {
      window.location = '/checkout/thanks';
    } else {
      if ($form.find('.message').length) {
        $form.find('.message').empty().text(data.message);
      } else {
        $form.append($('<span/>').addClass('message error').text(data.message));
      }

      $form.removeClass('loading');
    }
  };

  //
  // Render
  //

  self.render = function() {
    self.$checkout.find('.loading').remove();
    self.renderLineItems();

    if (self.step == 1) {
      self.renderLogin();
      self.renderAddress();
    } else {
      self.renderShipping();
      self.renderPayment();
    }
  };

  self.renderLineItems = function() {
    self.$lineItems = self.$checkout.find('#checkout-line-items');
    if (!self.$lineItems.length) return false;
    self.$lineItems.empty().html(self.templates.lineItems({ order: self.order }));
  };

  self.renderLogin = function() {
    self.$login = self.$checkout.find('#checkout-login');
    if (self.loggedIn) self.$login.remove();
    if (self.loggedIn || !self.$login.length) return false;
    self.$login.html(self.templates.login());
    if (!self.order.email) self.$login.find('button[data-login-action="signin"]').click();
  };

  self.renderAddress = function() {
    self.$address = self.$checkout.find('#checkout-address');
    if (!self.$address.length) return false;

    self.$address.empty().html(self.templates.address({
      shippingAddress: self.order.shipping_address,
      billingAddress: self.order.billing_address,
      states: window.States
    }));
  };

  self.renderShipping = function() {
    self.$shipping = self.$checkout.find('#checkout-shipping');
    if (!self.$shipping.length) return false;

    self.$shipping.empty().html(self.templates.shipping({
      rates: self.shippingRates,
      selectedRate: self.selectedRate
    }));
  };

  //self.test = function() {
  //  var response = JSON.parse($('#response-embed').html())
  //    , $form = self.$payment.find('form');
  //  if (response.success == true) {
  //      window.location = '/checkout/thanks';
  //    } else {
  //      if ($form.find('.message').length) {
  //        $form.find('.message').empty().text(response.message);
  //      } else {
  //        $form.append($('<span/>').addClass('message error').text(response.message));
  //      }
  //
  //      $form.removeClass('loading');
  //    }
  //};

  self.renderPayment = function() {
    self.$payment = self.$checkout.find('#checkout-payment');
    if (!self.$payment.length) return false;
    self.$checkout.addClass('loading');

    $.get('/checkout/payment', function(response) {
      self.$payment.empty().html(self.templates.payment({ form: response }));
      self.expirationChangeHandler();
      self.$checkout.removeClass('loading');
      //self.test();
      self.$payment.find('iframe').on('load', function(event) {
        var $iframe = $(event.target)
          , $form = self.$payment.find($form);
        if (!$iframe.contents().find('#response').length || $form.length) return false;
        var response = JSON.parse($iframe.contents().find('#response').html());
        console.log(response);
        console.log('------');
        if (response.success == true) {
          window.location = '/checkout/thanks';
        } else {
          console.log($form);
          if ($form.find('.message').length) {
            $form.find('.message').empty().text(response.message);
          } else {
            $form.append($('<span/>').addClass('message error').text(response.message));
          }

          $form.find('.message');
          $form.removeClass('loading');
        }
      });
    });
  };

  return self
}).call(Caboose.Store);

<commit_msg>Update<commit_after>//
// Checkout
//

Caboose.Store.Modules.Checkout = (function() {
  self = {
    templates: {
      address: JST['caboose_store/checkout/address'],
      login: JST['caboose_store/checkout/login'],
      payment: JST['caboose_store/checkout/payment'],
      lineItems: JST['caboose_store/checkout/line_items'],
      shipping: JST['caboose_store/checkout/shipping'],
      forms: {
        signin: JST['caboose_store/checkout/forms/signin'],
        register: JST['caboose_store/checkout/forms/register'],
        guest: JST['caboose_store/checkout/forms/guest']
      }
    }
  };

  //
  // Initialize
  //

  self.initialize = function() {
    switch (window.location.pathname.replace(/\/$/, "")) {
      case '/checkout':
      case '/checkout/step-one':
        self.step = 1;
        break;
      case '/checkout/step-two':
        self.step = 2;
        break;
    }

    self.$checkout = $('#checkout')
    if (!self.$checkout.length) return false;
    self.loggedIn = $('body').data('logged-in');

    // TODO refactor this
    if (self.loggedIn) {
      $.post('/checkout/attach-user', function(response) {
        self.fetch(self.render);
      });
    } else {
      self.fetch(self.render);
    }

    self.bindEventHandlers();
  };

  //
  // Fetch
  //

  self.fetch = function(callback) {
    $.get('/cart/items', function(response) {
      self.order = response.order

      if (self.step == 2) {
        $.get('/checkout/shipping', function(response) {
          self.shippingRates = response.rates;
          self.selectedRate = response.selected_rate;
          callback();
        });
      } else {
        callback();
      }
    });
  };

  //
  // Events
  //

  self.bindEventHandlers = function() {
    self.$checkout.on('click', '[data-login-action]', self.loginClickHandler);
    self.$checkout.on('submit', '#checkout-login form', self.loginSubmitHandler);
    self.$checkout.on('change', 'input[type=checkbox][name=use_as_billing]', self.useAsBillingHandler);
    self.$checkout.on('click', '#checkout-continue button', self.continueHandler);
    self.$checkout.on('click', '#checkout-complete button', self.completeHandler);
    self.$checkout.on('change', '#checkout-shipping select', self.shippingChangeHandler);
    self.$checkout.on('change', '#checkout-payment form#payment select', self.expirationChangeHandler);
    self.$checkout.on('submit', '#checkout-payment form#payment', self.paymentSubmitHandler);
    //self.$checkout.on('load', '#checkout-payment iframe#relay', self.relayLoadHandler);

    self.$checkout.on('load', 'iframe#relay', function(event) {
      console.log(event);
      console.log($(event.target).contents());
    });
    //$(window).on('message', self.relayHandler);
  };

  self.loginClickHandler = function(event) {
    $section = self.$login.children('section');

    switch ($(event.target).data('login-action')) {
      case 'signin':
        $section.empty().html(self.templates.forms.signin());
        break;
      case 'register':
        $section.empty().html(self.templates.forms.register());
        break;
      case 'continue':
        $section.empty().html(self.templates.forms.guest());
        break;
    };
  };

  self.loginSubmitHandler = function(event) {
    event.preventDefault();
    var $form = $(event.target);

    $.ajax({
      type: $form.attr('method'),
      url: $form.attr('action'),
      data: $form.serialize(),
      success: function(response) {
        if (response.error || (response.errors && response.errors.length > 0)) {
          if ($form.find('.message').length) {
            $form.find('.message').empty().addClass('error').text(response.error || response.errors[0]);
          } else {
            $form.append($('<span/>').addClass('message error').text(response.error || response.errors[0]));
          }
        } else {
          if (response.logged_in) {
            self.$login.after($('<p/>').addClass('alert').text('You are now signed in').css('text-align', 'center')).remove();
            $.post('/checkout/attach-user');
          } else {
            self.$login.after($('<p/>').addClass('alert').text('Email successfully saved').css('text-align', 'center')).remove();
          }
        }

        self.fetch();
      }
    });
  };

  self.useAsBillingHandler = function(event) {
    if (event.target.checked) {
      self.$address.find('#billing').hide();
    } else {
      self.$address.find('#billing').show();
    }
  };

  self.continueHandler = function(event) {
    $form = self.$address.find('form');

    if (!self.order.email && !self.order.customer_id) {
      alert('Please sign in, register or choose to continue as a guest');
      return false;
    }

    $.ajax({
      type: $form.attr('method'),
      url: $form.attr('action'),
      data: $form.serialize(),
      success: function(response) {
        if (response.success) {
          window.location = '/checkout/step-two';
        } else {
          $form.find('.message').remove();
          $form.find('#' + response.address + ' h3').append($('<span/>').addClass('message error').text(response.errors[0]));
        }
      }
    });
  };

  self.shippingChangeHandler = function(event) {
    if (event.target.value == "") return false;

    $.ajax({
      url: '/checkout/shipping',
      type: 'put',
      data: { shipping_code: event.target.value },
      success: function(response) {
        if (response.success) {
          self.order = response.order;
          self.renderLineItems();
          self.renderPayment();
        }
      }
    });
  };

  self.expirationChangeHandler = function(event) {
    var $form = $('#checkout-payment #payment')
      , month = $form.find('select[name=month]').val()
      , year = $form.find('select[name=year]').val();

    $form.find('#expiration').val(month + year);
  };

  self.completeHandler = function(event) {
    if (self.$payment.length) self.$payment.find('form').submit();
  };

  self.paymentSubmitHandler = function(event) {
    event.preventDefault();

    if (!self.order.shipping_code) {
      alert('Please choose a shipping method');
    } else {
      self.$checkout.off('submit', '#checkout-payment form#payment');
      $(event.target).addClass('loading').submit();
    }
  };

  self.relayHandler = function(event) {
    var data = event.originalEvent.data
      , $form = $('form#payment');

    console.log('Relay: ', data);
    console.log('Relay Form: ', $form);
    console.log(self.$payment, self.$payment.find('form'));
    console.log('------');
    if (!$form.length) return false;
    console.log('still in relay');
    console.log('------------');

    if (data.success == true) {
      window.location = '/checkout/thanks';
    } else {
      if ($form.find('.message').length) {
        $form.find('.message').empty().text(data.message);
      } else {
        $form.append($('<span/>').addClass('message error').text(data.message));
      }

      $form.removeClass('loading');
    }
  };

  //
  // Render
  //

  self.render = function() {
    self.$checkout.find('.loading').remove();
    self.renderLineItems();

    if (self.step == 1) {
      self.renderLogin();
      self.renderAddress();
    } else {
      self.renderShipping();
      self.renderPayment();
    }
  };

  self.renderLineItems = function() {
    self.$lineItems = self.$checkout.find('#checkout-line-items');
    if (!self.$lineItems.length) return false;
    self.$lineItems.empty().html(self.templates.lineItems({ order: self.order }));
  };

  self.renderLogin = function() {
    self.$login = self.$checkout.find('#checkout-login');
    if (self.loggedIn) self.$login.remove();
    if (self.loggedIn || !self.$login.length) return false;
    self.$login.html(self.templates.login());
    if (!self.order.email) self.$login.find('button[data-login-action="signin"]').click();
  };

  self.renderAddress = function() {
    self.$address = self.$checkout.find('#checkout-address');
    if (!self.$address.length) return false;

    self.$address.empty().html(self.templates.address({
      shippingAddress: self.order.shipping_address,
      billingAddress: self.order.billing_address,
      states: window.States
    }));
  };

  self.renderShipping = function() {
    self.$shipping = self.$checkout.find('#checkout-shipping');
    if (!self.$shipping.length) return false;

    self.$shipping.empty().html(self.templates.shipping({
      rates: self.shippingRates,
      selectedRate: self.selectedRate
    }));
  };

  //self.test = function() {
  //  var response = JSON.parse($('#response-embed').html())
  //    , $form = self.$payment.find('form');
  //  if (response.success == true) {
  //      window.location = '/checkout/thanks';
  //    } else {
  //      if ($form.find('.message').length) {
  //        $form.find('.message').empty().text(response.message);
  //      } else {
  //        $form.append($('<span/>').addClass('message error').text(response.message));
  //      }
  //
  //      $form.removeClass('loading');
  //    }
  //};

  self.renderPayment = function() {
    self.$payment = self.$checkout.find('#checkout-payment');
    if (!self.$payment.length) return false;
    self.$checkout.addClass('loading');

    $.get('/checkout/payment', function(response) {
      self.$payment.empty().html(self.templates.payment({ form: response }));
      self.expirationChangeHandler();
      self.$checkout.removeClass('loading');
      //self.test();
      self.$payment.find('iframe').on('load', function(event) {
        var $iframe = $(event.target)
          , $form = self.$payment.find('form');
        if (!$iframe.contents().find('#response').length || $form.length) return false;
        var response = JSON.parse($iframe.contents().find('#response').html());
        console.log(response);
        console.log('------');
        if (response.success == true) {
          window.location = '/checkout/thanks';
        } else {
          console.log($form);
          if ($form.find('.message').length) {
            $form.find('.message').empty().text(response.message);
          } else {
            $form.append($('<span/>').addClass('message error').text(response.message));
          }

          $form.find('.message');
          $form.removeClass('loading');
        }
      });
    });
  };

  return self
}).call(Caboose.Store);

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 Scott Beck, all rights reserved
 *
 * Licensed under the MIT license
 *
 */
/* jshint undef: true, unused: true */
/* global describe:false, it: false, beforeEach: false, expect: false */
(function () {
  'use strict';
  var libPath = '../index.js';
  describe("remix#exports", function () {
    it("should load without throwing errors", function () {
      (function () {
        require(libPath);
      })
      .should.not.throw();
    });
    it("should export correctly", function () {
      var lib = require(libPath);
      lib.remix.should.be.a('function');
      lib.ReMix.should.be.a('function');
    });
    describe("remix", function () {
      var lib = require(libPath);
      beforeEach(function () {
        this.re = new lib.ReMix();
      });
      it("should instantiate", function () {
        this.re.should.be.instanceof(lib.ReMix);
      });
      it("should accept regexp object", function () {
        var re = /foo/;
        this.re = new lib.ReMix(re);
        expect(this.re.toString()).to.equal('(foo)');
      });
      it("should accept string", function () {
        var str = 'foo';
        this.re = new lib.ReMix(null, str);
        expect(this.re.toString()).to.equal('(foo)');
      });
      it("should accept array", function () {
        var arr = ['foo', 'bar'];
        this.re = new lib.ReMix(null, arr);
        expect(this.re.toString()).to.equal('(foo)|(bar)');
      });
      it("should compile simple regexp", function () {
        var re = /foo/;
        this.re.add(re).compile()._regexn.should.deep.equal([new RegExp('(' + re.source + ')', 'g')]);
      });
      it("should compile multiple regexn", function () {
        this.re.add(/foo/, /bar/).compile()._regexn.should.deep.equal([/(foo)|(bar)/g]);
      });
      it("should match simple", function () {
        this.re.add(/(foo)o/).exec('fooo').should.deep.equal([['fooo', 'foo'], '',  0, 4]);
      });
      it("should match multiple", function () {
        var str = 'foobar';
        this.re.add(/(foo)/, /bar/);
        this.re.exec(str).should.deep.equal([['foo', 'foo'], '', 0, 3]);
        this.re.exec(str).should.deep.equal([['bar'], '', 1, 6]);
        this.re._regexn.should.deep.equal([/((foo))|(bar)/g]);
      });
      it("should match multiple sets", function () {
        var str = 'foooBarr';
        this.re.add(/(foo)o/, /(bar)r/i);
        this.re.exec(str).should.deep.equal([['fooo', 'foo'], '', 0, 4]);
        this.re.exec(str).should.deep.equal([['Barr', 'Bar'], '', 1, 8]);
        this.re._regexn.should.deep.equal([/((foo)o)/g, /((bar)r)/ig]);
      });
      it("should not combine mutiline", function () {
        this.re.add(/foo/, /bar/m).compile()._regexn.should.deep.equal([/(foo)/g, /(bar)/mg]);
      });
      it("should add named", function () {
        this.re.addNamed('foo', /foo/).compile()._regexn.should.deep.equal([/(foo)/g]);
      });
      it("should return named match", function () {
        var str = 'foo';
        this.re.add({name: 'foo.foo', re: /foo/});
        this.re.exec(str).should.deep.equal([['foo'], 'foo.foo', 0, 3]);
      });
      it("should not match", function () {
        this.re.add(/foo/).exec('bar').should.equal(false);
      });
      it("should test", function () {
        this.re.add(/foo/).test('foo').should.equal(true);
        this.re.test('bar').should.equal(false);
        this.re.test('foo').should.equal(true);
        this.re.test('bar').should.equal(false);
        this.re.test('bar').should.equal(false);
        this.re.test('foo').should.equal(true);
        this.re.test('bar').should.equal(false);
        this.re.test('bar').should.equal(false);
      });
      it("should restart on reject", function () {
        var str = 'foobarfoo';
        this.re.add(/(foo)/);
        this.re.exec(str).should.deep.equal([['foo', 'foo'], '', 0, 3]);
        this.re.reject(str);
        this.re.exec(str).should.deep.equal([['foo', 'foo'], '', 0, 3]);
        this.re.exec(str).should.deep.equal([['foo', 'foo'], '', 0, 9]);
      });
      it("should reject length", function () {
        var str = "fooooobarrrrrr";
        this.re.add(/(ooo|rrr)/);
        this.re.exec(str).should.deep.equal([['ooo', 'ooo'], '', 0, 4]);
        this.re.exec(str).should.deep.equal([['rrr', 'rrr'], '', 0, 11]);
        this.re.reject(str);
        this.re.exec(str).should.deep.equal([['ooo', 'ooo'], '', 0, 4]);
      });
      it("should reject multi", function () {
        var str = "fooooobarrrrrr";
        this.re.add(/(ooo)/, /rrr/);
        this.re.exec(str).should.deep.equal([['ooo', 'ooo'], '', 0, 4]);
        this.re.reject(str);
        this.re.exec(str).should.deep.equal([['ooo', 'ooo'], '', 0, 4]);
        this.re.exec(str).should.deep.equal([['rrr'], '', 1, 11]);
        this.re.reject(str);
        this.re.exec(str).should.deep.equal([['ooo', 'ooo'], '', 0, 4]);
      });
      it("should reject multi no-join", function () {
        var str = "fooooobarrrrrr";
        this.re.add(/ooo/, /rrr/i);
        this.re.exec(str).should.deep.equal([['ooo'], '', 0, 4]);
        this.re.reject(str);
        this.re.exec(str).should.deep.equal([['ooo'], '', 0, 4]);
        this.re.exec(str).should.deep.equal([['rrr'], '', 1, 11]);
        this.re.reject(str);
        this.re.exec(str).should.deep.equal([['ooo'], '', 0, 4]);
      });
      it("should allow named regex", function () {
        var str = 'foobar';
        this.re.add({name: "foo", re: new lib.ReMix(/foo/, /bar/)});
        this.re.exec(str).should.deep.equal([['foo'], 'foo', 0, 3]);
        this.re.exec(str).should.deep.equal([['bar'], 'foo', 1, 6]);
      });
    });
  });
})();<commit_msg>updated tests for changes. Removed test() method, doesn't really make sense with this module.<commit_after>/*
 * Copyright (C) 2014 Scott Beck, all rights reserved
 *
 * Licensed under the MIT license
 *
 */
/* jshint undef: true, unused: true */
/* global describe:false, it: false, beforeEach: false, expect: false */
(function () {
  'use strict';
  var libPath = '../index.js';
  describe("remix#exports", function () {
    it("should load without throwing errors", function () {
      (function () {
        require(libPath);
      })
      .should.not.throw();
    });
    it("should export correctly", function () {
      var lib = require(libPath);
      lib.remix.should.be.a('function');
      lib.ReMix.should.be.a('function');
    });
    describe("remix", function () {
      var lib = require(libPath);
      beforeEach(function () {
        this.re = new lib.ReMix();
      });
      it("should instantiate", function () {
        this.re.should.be.instanceof(lib.ReMix);
      });
      it("should accept regexp object", function () {
        var re = /foo/;
        this.re = new lib.ReMix(re);
        expect(this.re.toString()).to.equal('(foo)');
      });
      it("should accept string", function () {
        var str = 'foo';
        this.re = new lib.ReMix(null, str);
        expect(this.re.toString()).to.equal('(foo)');
      });
      it("should accept array", function () {
        var arr = ['foo', 'bar'];
        this.re = new lib.ReMix(null, arr);
        expect(this.re.toString()).to.equal('(foo)|(bar)');
      });
      it("should compile simple regexp", function () {
        var re = /foo/;
        this.re.add(re).compile().should.deep.equal([new RegExp('(' + re.source + ')', 'g')]);
      });
      it("should compile multiple regexn", function () {
        this.re.add(/foo/, /bar/).compile().should.deep.equal([/(foo)|(bar)/g]);
      });
      it("should match simple", function () {
        this.re.add(/(foo)o/).exec('fooo').should.deep.equal([['fooo', 'foo'], '',  0, 4]);
      });
      it("should match multiple", function () {
        var str = 'foobar';
        this.re.add(/(foo)/, /bar/);
        this.re.exec(str).should.deep.equal([['foo', 'foo'], '', 0, 3]);
        this.re.exec(str).should.deep.equal([['bar'], '', 1, 6]);
        this.re._regexn.should.deep.equal([/((foo))|(bar)/g]);
      });
      it("should match multiple sets", function () {
        var str = 'foooBarr';
        this.re.add(/(foo)o/, /(bar)r/i);
        this.re.exec(str).should.deep.equal([['fooo', 'foo'], '', 0, 4]);
        this.re.exec(str).should.deep.equal([['Barr', 'Bar'], '', 1, 8]);
        this.re._regexn.should.deep.equal([/((foo)o)/g, /((bar)r)/ig]);
      });
      it("should not combine mutiline", function () {
        this.re.add(/foo/, /bar/m).compile().should.deep.equal([/(foo)/g, /(bar)/mg]);
      });
      it("should add named", function () {
        this.re.addNamed('foo', /foo/).compile().should.deep.equal([/(foo)/g]);
      });
      it("should return named match", function () {
        var str = 'foo';
        this.re.add({name: 'foo.foo', re: /foo/});
        this.re.exec(str).should.deep.equal([['foo'], 'foo.foo', 0, 3]);
      });
      it("should not match", function () {
        this.re.add(/foo/).exec('bar').should.equal(false);
      });
      it("should allow named regex", function () {
        var str = 'foobar';
        this.re.add({name: "foo", re: new lib.ReMix(/foo/, /bar/)});
        this.re.exec(str).should.deep.equal([['foo'], 'foo', 0, 3]);
        this.re.exec(str).should.deep.equal([['bar'], 'foo', 1, 6]);
      });
    });
  });
})();<|endoftext|>


<commit_before>angular.module('asics').controller('InvitationCtrl', [
    '$mdToast',
    '$q',
    '$scope',
    '$state',
    '$stateParams',
    'admin',
    function ($mdToast, $q, $scope, $state, $stateParams, admin) {
        $scope.guest = {};
        $scope.isAthlete = false;
        $scope.occupations = [
            'Atleta',
            'Staff de treinamento',
            'Federação/NOC',
            'Mídia',
            'Família/Amigo de atleta',
            'Diretor de corrida',
            'Representante do atleta',
            'Outro'
        ];

        $scope.athletes = [
            'Jordan Ernest BURROUGHS',
            'Saori YOSHIDA',
            'Yoshihide Kiryu',
            'Chirstophe Lemaitre',
            'Floria Guei',
            'Yohan Diniz',
            'Queen Harrison',
            'Candace Hill',
            'Lolo Jones',
            'Veronica Shanti Pereira',
            'Jieshi Neo',
            'Jared Tallent',
            'Bruno Rezende',
            'Gael Monfils',
            'CoCo Vandeweghe',
            'Steve Johnson',
            'Vasek Pospisil',
            'Gwen Jorgensen',
            'Kerri Walsh',
            'Ramu Tokashiki',
            'Alexandra Priscila do Nascimento'
        ];

        $scope.inviteGuest = function () {
            if ($scope.isAthlete)
                $scope.guest.occupation = 'Atleta Asics';
            admin.postInvite($scope.guest)
                .then(onInviteSuccess)
                .catch(errorToast)
            console.log($scope.guest);
        };

        function onInviteSuccess(guest) {
            successToast(guest);
            clearForm();
        }

        function errorToast(error) {
            console.error(error);

            $mdToast.show(
                $mdToast.simple()
                    .textContent("Erro ao enviar convite: " + error)
                    .position('top right')
                    .hideDelay(4000)
                    .theme('error-toast')
            );
        }

        function successToast(guest) {
            $mdToast.show(
                $mdToast.simple()
                    .textContent("Convite para " + guest.name + " enviado com sucesso!")
                    .position('top right')
                    .hideDelay(4000)
                    .theme('success-toast')
            );
            clearForm();
        }

        function clearForm() {
            $scope.guest = {
                email: '',
                name: '',
                occupation: '',
                language: 'PT'
            };

            $scope.adminForm.$setPristine();
            $scope.adminForm.email.$setUntouched();

            if($scope.adminForm.name)
                $scope.adminForm.name.$setUntouched();
            if($scope.adminForm.occupation)
                $scope.adminForm.occupation.$setUntouched();
        }

        $scope.$on('$viewContentLoaded', function () {
            clearForm();
        });
    }
]);
<commit_msg>removed console log<commit_after>angular.module('asics').controller('InvitationCtrl', [
    '$mdToast',
    '$q',
    '$scope',
    '$state',
    '$stateParams',
    'admin',
    function ($mdToast, $q, $scope, $state, $stateParams, admin) {
        $scope.guest = {};
        $scope.isAthlete = false;
        $scope.occupations = [
            'Atleta',
            'Staff de treinamento',
            'Federação/NOC',
            'Mídia',
            'Família/Amigo de atleta',
            'Diretor de corrida',
            'Representante do atleta',
            'Outro'
        ];

        $scope.athletes = [
            'Jordan Ernest BURROUGHS',
            'Saori YOSHIDA',
            'Yoshihide Kiryu',
            'Chirstophe Lemaitre',
            'Floria Guei',
            'Yohan Diniz',
            'Queen Harrison',
            'Candace Hill',
            'Lolo Jones',
            'Veronica Shanti Pereira',
            'Jieshi Neo',
            'Jared Tallent',
            'Bruno Rezende',
            'Gael Monfils',
            'CoCo Vandeweghe',
            'Steve Johnson',
            'Vasek Pospisil',
            'Gwen Jorgensen',
            'Kerri Walsh',
            'Ramu Tokashiki',
            'Alexandra Priscila do Nascimento'
        ];

        $scope.inviteGuest = function () {
            if ($scope.isAthlete)
                $scope.guest.occupation = 'Atleta Asics';
            admin.postInvite($scope.guest)
                .then(onInviteSuccess)
                .catch(errorToast)
        };

        function onInviteSuccess(guest) {
            successToast(guest);
            clearForm();
        }

        function errorToast(error) {
            console.error(error);

            $mdToast.show(
                $mdToast.simple()
                    .textContent("Erro ao enviar convite: " + error)
                    .position('top right')
                    .hideDelay(4000)
                    .theme('error-toast')
            );
        }

        function successToast(guest) {
            $mdToast.show(
                $mdToast.simple()
                    .textContent("Convite para " + guest.name + " enviado com sucesso!")
                    .position('top right')
                    .hideDelay(4000)
                    .theme('success-toast')
            );
            clearForm();
        }

        function clearForm() {
            $scope.guest = {
                email: '',
                name: '',
                occupation: '',
                language: 'PT'
            };

            $scope.adminForm.$setPristine();
            $scope.adminForm.email.$setUntouched();

            if($scope.adminForm.name)
                $scope.adminForm.name.$setUntouched();
            if($scope.adminForm.occupation)
                $scope.adminForm.occupation.$setUntouched();
        }

        $scope.$on('$viewContentLoaded', function () {
            clearForm();
        });
    }
]);
<|endoftext|>


<commit_before>/* Copyright (c) 2013-2015 Richard Rodger, MIT License */
/* jslint node:true, asi:true */
"use strict";

var fs      = require('fs');
var path    = require('path');
var _       = require('lodash');
var uuid    = require('node-uuid');
var levelup = require('level');
var levelQuery      = require('level-queryengine');
var jsonqueryEngine = require('jsonquery-engine');
var util = require('util');

var name    = "level-store";

module.exports = function(opts) {

    var desc;
    var dbmap = {};
    var seneca = this;

    opts = this.util.deepextend({
        folder: '.',
        valueEncoding: 'json',
        sync: false,
        fillCache: true
    }, opts);

    function fixquery(qent, q) {
        return null === q ? {} : _.isString(q) ? {id: q} : _.isString(q.id) ? q : q;
    }

    function filterdata(q, data) {
        for(var p in q) {
            if( !~p.indexOf('$') && q[p] != data[p] ) {
                return null;
            }
        }
        if( q.fields$ ) {
          data = _.omit(data, q.field$)
        }
        return data;
    }

    /**
     * sort$, skip$, limit$ and fields$ support.
     */
    function fixlist(q, list) {

        // sort first
        if (q.sort$) {
          for ( var sf in q.sort$ ) break;
          var sd = q.sort$[sf] < 0 ? -1 : 1

          list = _.sortBy(list, sf);
          if (sd == -1) {
              list.reverse()
          }

        }
        if (q.skip$) {
          list = list.slice(q.skip$)
        }

        if (q.limit$) {
          list = list.slice(0, q.limit$)
        }

        if (q.fields$) {
            list = _.map(list, function (item) {
                return _.pick(item, q.fields$);
            });
        }

        return list;
    }

    /**
    * Return if the folder exists, create otherwise.
    */
    function ensurefolder(folder, cb){
        fs.exists(folder, function(exists) {
          if( exists ) {
              return cb();
          }
          fs.mkdir(folder, function(err) {
            cb(err);
          });
        });
    }

    function makefolderpath(ent) {
        var canon = ent.canon$({object: true});

        var base  = canon.base;
        var name  = canon.name;

        var entfolder = (base ? base + '_' : '') + name;
        var folderpath = path.join(opts.folder, entfolder);
        return folderpath;
    }

    function error (done, win){
        return function(err, out){
          if (err)  {
              return done(err);
          }
          if (win) {
              return win(out);
          }
        }
    }

    /**
     * Get the levelup reference
     */
    var get_db = function get_db(ent, done) {
        var folder = makefolderpath(ent)
        var db = dbmap[folder];
        if (!db) {
          ensurefolder(folder, error(done, function(){
            db = dbmap[folder];
            if (db) {
                return done(null, db);
            }
            try {
                db = dbmap[folder] = levelQuery(levelup(folder, opts));
                db.query.use(jsonqueryEngine());
            } catch(e) {
                db = dbmap[folder];
                if (db) {
                    return done(null, db);
                }
                return done(e);
            }
            return done(null, db)
          }));
      } else {
          return done(null, db);
      }
    }

    var store = {
        name: name,

        close: function(args, done) {
            // Closes all the dbs
            seneca.util.recurse(_.values(dbmap), function(db, next) {
                db.close(next);
            }, done);
        },

        save: function(args, done) {

            var ent = args.ent
            var update = !!ent.id

            if (!update) {
                ent.id = void 0 != ent.id$ ? ent.id$ : uuid();
                delete(ent.id$)
            }

            get_db(ent, error(done, function(db) {
                    db.put(ent.id, ent.data$(false), function(err) {
                        seneca.log.debug('save/'+(update? 'update' : 'insert'), ent, desc);
                            done(null, ent);
                    });
                })
            );
        },

        load: function(args, done) {

            var qent = args.qent;
            var q    = args.q;
            var qq = fixquery(qent, q);

            if (qq.id) {
                get_db(qent, error(done, function(db) {
                    db.get( qq.id, function(err, data) {
                        if (err) {
                            if (err.notFound) {
                                return done(null, null);
                            }
                            return done(err);
                        }
                        var fent = qent.make$(data);
                        seneca.log.debug('load', q, fent, desc);
                        done(null, fent);
                    });
                }));
            } else {
              store.list(args, error(done, function(list){
                  done(null, list[0])
              }))
          }
        },

        remove: function(args, done) {

            var qent = args.qent;
            var q    = args.q;

            // all that match the query, of course
            var all  = q.all$; // default false
            var load  = _.isUndefined(q.load$) ? true : q.load$; // default true
            var qq = fixquery(qent,q);

            get_db(qent, error(done, function(db) {
                if( !_.isUndefined(qq.id) && load && !all ) {
                  db.get(qq.id, {fillCache:opts.fillCache}, function(err, data){
                      if (err) {
                          if (err.notFound) {
                              return done(null, null);
                          }
                          return done(err);
                      }
                      var fent = qent.make$(data);
                      do_remove(db, fent);
                  })
                } else {
                do_remove(db);
                }
            }));

            function do_remove(db, maybefent) {
                if ( _.isUndefined(qq.id) ) {
                    if (all) {
                        store.list(args, error(done, function(list) {
                            seneca.util.recurse(
                                list,
                                function(fent, next) {
                                  db.del(fent.id, {sync:opts.sync}, next);
                                },
                                function(err){
                                  seneca.log.debug('remove/all', q, desc);
                                  done(err);
                                }
                            );
                        }));
                    } else {
                        store.load(args, error(done, function(item){
                            if (item) {
                                db.del( item.id, {sync:opts.sync}, function(err){
                                    if( err ) return done(err);
                                    seneca.log.debug('remove/one', q, item, desc);
                                    done(null,item);
                                });
                            } else {
                                return done();
                            }
                        }));
                    }
            } else {
              db.del(qq.id, {sync:opts.sync}, function(err) {
                if (err) {
                    return done(err);
                }
                seneca.log.debug('remove/one', q, maybefent, desc);
                done(null, maybefent);
              })
            }
          }
        },

        list: function(args, done) {
            var qent = args.qent;
            var q    = args.q;

            get_db(qent, error(done, function(db){
                //var mq = metaquery(qent, q);
                var n = 1;
                var list = [];

                // saves the sorting / limit / skip / fields params
                var additionaParams = {
                    sort$: q.sort$,
                    limit$: q.limit$,
                    skip$: q.skip$,
                    fields$: q.fields$
                }
                // Remove the optional params from the query
                q = _.omit(q, ['sort$', 'limit$', 'skip$', 'fields$']);
                if (q.all$) { // useless
                    q = {};
                }

                db.query(q)
                    .on('data', function (data) {
                        if (filterdata( q, data ) ) {
                          list.push( qent.make$(data) )
                        }
                    })
                    .on('error', function (err) {
                        if(--n) throw new Error('errored:'+ n)
                        done(err)
                      })
                    .on('close', function () {
                    // do nothing, I guess
                    })
                    .on('end', function () {
                        if(--n) throw new Error('ended:'+ n);
                        // Order / skip / fields mngmt
                        list = fixlist(additionaParams, list)
                        seneca.log.debug('list', q, list.length, list[0],desc);
                        done(null,list);
                    });
            }))
        },

        native: function(args,done) {
            get_db(args.ent, function(err, db) {
                done(err, db);
            });
        }
    };

    var storedesc = seneca.store.init(seneca, opts, store);

    return {name:store.name, tag:storedesc.tag};
}
<commit_msg>2-space indents<commit_after>/* Copyright (c) 2013-2015 Richard Rodger, MIT License */
/* jslint node:true, asi:true */
"use strict";

var fs      = require('fs');
var path    = require('path');
var _       = require('lodash');
var uuid    = require('node-uuid');
var levelup = require('level');
var levelQuery      = require('level-queryengine');
var jsonqueryEngine = require('jsonquery-engine');
var util = require('util');

var name    = "level-store";

module.exports = function(opts) {

  var desc;
  var dbmap = {};
  var seneca = this;

  opts = this.util.deepextend({
    folder: '.',
    valueEncoding: 'json',
    sync: false,
    fillCache: true
  }, opts);

  function fixquery(qent, q) {
    return null === q ? {} : _.isString(q) ? {id: q} : _.isString(q.id) ? q : q;
  }

  function filterdata(q, data) {
    for(var p in q) {
      if( !~p.indexOf('$') && q[p] != data[p] ) {
        return null;
      }
    }
    if( q.fields$ ) {
      data = _.omit(data, q.field$)
    }
    return data;
  }

  /**
   * sort$, skip$, limit$ and fields$ support.
   */
  function fixlist(q, list) {

    // sort first
    if (q.sort$) {
      for ( var sf in q.sort$ ) break;
      var sd = q.sort$[sf] < 0 ? -1 : 1

      list = _.sortBy(list, sf);
      if (sd == -1) {
        list.reverse()
      }

    }
    if (q.skip$) {
      list = list.slice(q.skip$)
    }

    if (q.limit$) {
      list = list.slice(0, q.limit$)
    }

    if (q.fields$) {
      list = _.map(list, function (item) {
        return _.pick(item, q.fields$);
      });
    }

    return list;
  }

  /**
   * Return if the folder exists, create otherwise.
   */
  function ensurefolder(folder, cb){
    fs.exists(folder, function(exists) {
      if( exists ) {
        return cb();
      }
      fs.mkdir(folder, function(err) {
        cb(err);
      });
    });
  }

  function makefolderpath(ent) {
    var canon = ent.canon$({object: true});

    var base  = canon.base;
    var name  = canon.name;

    var entfolder = (base ? base + '_' : '') + name;
    var folderpath = path.join(opts.folder, entfolder);
    return folderpath;
  }

  function error (done, win){
    return function(err, out){
      if (err)  {
        return done(err);
      }
      if (win) {
        return win(out);
      }
    }
  }

  /**
   * Get the levelup reference
   */
  var get_db = function get_db(ent, done) {
    var folder = makefolderpath(ent)
    var db = dbmap[folder];
    if (!db) {
      ensurefolder(folder, error(done, function(){
        db = dbmap[folder];
        if (db) {
          return done(null, db);
        }
        try {
          db = dbmap[folder] = levelQuery(levelup(folder, opts));
          db.query.use(jsonqueryEngine());
        } catch(e) {
          db = dbmap[folder];
          if (db) {
            return done(null, db);
          }
          return done(e);
        }
        return done(null, db)
      }));
    } else {
      return done(null, db);
    }
  }

  var store = {
    name: name,

    close: function(args, done) {
      // Closes all the dbs
      seneca.util.recurse(_.values(dbmap), function(db, next) {
        db.close(next);
      }, done);
    },

    save: function(args, done) {

      var ent = args.ent
      var update = !!ent.id

      if (!update) {
        ent.id = void 0 != ent.id$ ? ent.id$ : uuid();
        delete(ent.id$)
      }

      get_db(ent, error(done, function(db) {
        db.put(ent.id, ent.data$(false), function(err) {
          seneca.log.debug('save/'+(update? 'update' : 'insert'), ent, desc);
          done(null, ent);
        });
      })
            );
    },

    load: function(args, done) {

      var qent = args.qent;
      var q    = args.q;
      var qq = fixquery(qent, q);

      if (qq.id) {
        get_db(qent, error(done, function(db) {
          db.get( qq.id, function(err, data) {
            if (err) {
              if (err.notFound) {
                return done(null, null);
              }
              return done(err);
            }
            var fent = qent.make$(data);
            seneca.log.debug('load', q, fent, desc);
            done(null, fent);
          });
        }));
      } else {
        store.list(args, error(done, function(list){
          done(null, list[0])
        }))
      }
    },

    remove: function(args, done) {

      var qent = args.qent;
      var q    = args.q;

      // all that match the query, of course
      var all  = q.all$; // default false
      var load  = _.isUndefined(q.load$) ? true : q.load$; // default true
      var qq = fixquery(qent,q);

      get_db(qent, error(done, function(db) {
        if( !_.isUndefined(qq.id) && load && !all ) {
          db.get(qq.id, {fillCache:opts.fillCache}, function(err, data){
            if (err) {
              if (err.notFound) {
                return done(null, null);
              }
              return done(err);
            }
            var fent = qent.make$(data);
            do_remove(db, fent);
          })
        } else {
          do_remove(db);
        }
      }));

      function do_remove(db, maybefent) {
        if ( _.isUndefined(qq.id) ) {
          if (all) {
            store.list(args, error(done, function(list) {
              seneca.util.recurse(
                list,
                function(fent, next) {
                  db.del(fent.id, {sync:opts.sync}, next);
                },
                function(err){
                  seneca.log.debug('remove/all', q, desc);
                  done(err);
                }
              );
            }));
          } else {
            store.load(args, error(done, function(item){
              if (item) {
                db.del( item.id, {sync:opts.sync}, function(err){
                  if( err ) return done(err);
                  seneca.log.debug('remove/one', q, item, desc);
                  done(null,item);
                });
              } else {
                return done();
              }
            }));
          }
        } else {
          db.del(qq.id, {sync:opts.sync}, function(err) {
            if (err) {
              return done(err);
            }
            seneca.log.debug('remove/one', q, maybefent, desc);
            done(null, maybefent);
          })
        }
      }
    },

    list: function(args, done) {
      var qent = args.qent;
      var q    = args.q;

      get_db(qent, error(done, function(db){
        //var mq = metaquery(qent, q);
        var n = 1;
        var list = [];

        // saves the sorting / limit / skip / fields params
        var additionaParams = {
          sort$: q.sort$,
          limit$: q.limit$,
          skip$: q.skip$,
          fields$: q.fields$
        }
        // Remove the optional params from the query
        q = _.omit(q, ['sort$', 'limit$', 'skip$', 'fields$']);
        if (q.all$) { // useless
          q = {};
        }

        db.query(q)
          .on('data', function (data) {
            if (filterdata( q, data ) ) {
              list.push( qent.make$(data) )
            }
          })
          .on('error', function (err) {
            if(--n) throw new Error('errored:'+ n)
            done(err)
          })
          .on('close', function () {
            // do nothing, I guess
          })
          .on('end', function () {
            if(--n) throw new Error('ended:'+ n);
            // Order / skip / fields mngmt
            list = fixlist(additionaParams, list)
            seneca.log.debug('list', q, list.length, list[0],desc);
            done(null,list);
          });
      }))
    },

    native: function(args,done) {
      get_db(args.ent, function(err, db) {
        done(err, db);
      });
    }
  };

  var storedesc = seneca.store.init(seneca, opts, store);

  return {name:store.name, tag:storedesc.tag};
}
<|endoftext|>


<commit_before>var jpegSize = require('jpeg-size');
var tessel = require('tessel');
var test = require('tinytap');
var async = require('async');
var cameralib = require('../');

var portname = process.argv[2] || 'A';

var camera;
async.series([
  test('Connecting to camera module', function (t) {
    camera = cameralib.use(tessel.port[portname], {}, function (err, camera) {
      console.log('callback')
      t.ok(camera, 'The camera module object was not returned');
      t.equal(err, undefined, 'There was an error connecting');
      t.end();
    });
  }),

  test('Set Resolution - vga', function (t) {
    camera.setResolution('vga', function () {
      camera.getResolution(function (err, resolution) {
        t.equal(resolution, 'vga', "resolution not set correctly");
        t.end();
      });
    });
  }),

  test('Set Resolution - qvga', function (t) {
    camera.setResolution('qvga', function () {
      camera.getResolution(function (err, resolution) {
        t.equal(resolution, 'qvga', "resolution not set correctly");
        t.end();
      });
    });
  }),

  test('Set Resolution - qqvga', function (t) {
    camera.setResolution('qqvga', function () {
      camera.getResolution(function (err, resolution) {
        t.equal(resolution, 'qqvga', "resolution not set correctly");
        t.end();
      });
    });
  }),

  test('Set Invalid Resolution - xxyyxx', function (t) {
    camera.setResolution('xxyyxx', function (err) {
      t.equal(err.message, "Resolution: xxyyxx is invalid. Valid resolutions are vga, qvga, qqvga", "invalid resolution should throw an error");
      t.end();
    });
  }),

  test('Set Compression - 0', function (t) {
    camera.setCompression(0, function () {
      camera.getCompression(function (err, compression) {
        t.equal(compression, 0, "compression not set correctly");
        t.end();
      });
    });
  }),

  test('Set Compression - 1', function (t) {
    camera.setCompression(1, function () {
      camera.getCompression(function (err, compression) {
        t.equal(compression, 1, "compression not set correctly");
        t.end();
      });
    });
  }),

  test('Set Invalid Compression - 3.14', function (t) {
    camera.setCompression(3.14, function (err) {
      t.equal(err.message, "Compression: 3.14 is invalid. Valid compressions are between 0 and 1", "invalid resolution should throw an error");
      t.end();
    });
  }),

  test('Take a picture', function (t) {
    camera.setResolution('vga', function () {
      camera.takePicture(function (err, image) {
        var size = jpegSize(image);
        t.equal(size.height, 480, "picture not taken correctly");
        t.equal(size.width, 640, "picture not taken correctly");
        t.end();
        camera.disable();
      })
    })
  }),

  test('Take multiple pictures', function (t) {
    function validatePicture (image, size) {
      t.equal(size.height, 480, "picture not taken correctly");
      t.equal(size.width, 640, "picture not taken correctly");
    };

    camera.setResolution('vga', function () {
      camera.takePicture(function(err, image) {
        camera.takePicture(function(err, image) {
          validatePicture(image, jpegSize(image));
          t.end();
        });
        validatePicture(image, jpegSize(image));
      });
      camera.takePicture(function(err, image) {
        validatePicture(image, jpegSize(image));
      });
    })
  }),

  ], function(err) {
    console.log('error running tests', err);
  }
);<commit_msg>Adds test count to camera tests.<commit_after>var jpegSize = require('jpeg-size');
var tessel = require('tessel');
var test = require('tinytap');
var async = require('async');
var cameralib = require('../');

var portname = process.argv[2] || 'A';

test.count(11);

var camera;
async.series([
  test('Connecting to camera module', function (t) {
    camera = cameralib.use(tessel.port[portname], {}, function (err, camera) {
      console.log('callback')
      t.ok(camera, 'The camera module object was not returned');
      t.equal(err, undefined, 'There was an error connecting');
      t.end();
    });
  }),

  test('Set Resolution - vga', function (t) {
    camera.setResolution('vga', function () {
      camera.getResolution(function (err, resolution) {
        t.equal(resolution, 'vga', "resolution not set correctly");
        t.end();
      });
    });
  }),

  test('Set Resolution - qvga', function (t) {
    camera.setResolution('qvga', function () {
      camera.getResolution(function (err, resolution) {
        t.equal(resolution, 'qvga', "resolution not set correctly");
        t.end();
      });
    });
  }),

  test('Set Resolution - qqvga', function (t) {
    camera.setResolution('qqvga', function () {
      camera.getResolution(function (err, resolution) {
        t.equal(resolution, 'qqvga', "resolution not set correctly");
        t.end();
      });
    });
  }),

  test('Set Invalid Resolution - xxyyxx', function (t) {
    camera.setResolution('xxyyxx', function (err) {
      t.equal(err.message, "Resolution: xxyyxx is invalid. Valid resolutions are vga, qvga, qqvga", "invalid resolution should throw an error");
      t.end();
    });
  }),

  test('Set Compression - 0', function (t) {
    camera.setCompression(0, function () {
      camera.getCompression(function (err, compression) {
        t.equal(compression, 0, "compression not set correctly");
        t.end();
      });
    });
  }),

  test('Set Compression - 1', function (t) {
    camera.setCompression(1, function () {
      camera.getCompression(function (err, compression) {
        t.equal(compression, 1, "compression not set correctly");
        t.end();
      });
    });
  }),

  test('Set Invalid Compression - 3.14', function (t) {
    camera.setCompression(3.14, function (err) {
      t.equal(err.message, "Compression: 3.14 is invalid. Valid compressions are between 0 and 1", "invalid resolution should throw an error");
      t.end();
    });
  }),

  test('Take a picture', function (t) {
    camera.setResolution('vga', function () {
      camera.takePicture(function (err, image) {
        var size = jpegSize(image);
        t.equal(size.height, 480, "picture not taken correctly");
        t.equal(size.width, 640, "picture not taken correctly");
        t.end();
        camera.disable();
      })
    })
  }),

  test('Take multiple pictures', function (t) {
    function validatePicture (image, size) {
      t.equal(size.height, 480, "picture not taken correctly");
      t.equal(size.width, 640, "picture not taken correctly");
    };

    camera.setResolution('vga', function () {
      camera.takePicture(function(err, image) {
        camera.takePicture(function(err, image) {
          validatePicture(image, jpegSize(image));
          t.end();
        });
        validatePicture(image, jpegSize(image));
      });
      camera.takePicture(function(err, image) {
        validatePicture(image, jpegSize(image));
      });
    })
  }),

  ], function(err) {
    console.log('error running tests', err);
  }
);<|endoftext|>


<commit_before>(function (Vue, _, queryString) {
  Vue.component('wallpaper-search', {
    data: {
      isDirty: false,

      // Search defaults
      search: {
        order: 'latest',
        purities: []
      },

      // Mappings
      purityMappings: {
        sfw: 'SFW',
        sketchy: 'Sketchy',
        nsfw: 'NSFW'
      },
      orderMappings: {
        latest: 'Recency',
        score: 'Relevance',
        popular: 'Popularity',
        random: 'Random'
      },

      myObj: {
        myArr: []
      },
      myArr: []
    },

    created: function () {
      console.log('wallpaper search component ready');

      this.$on('wallpaperSearchDidChange', function () {
        console.log('wallpaperSearchDidChange created');
      });
      this.$watch('search.purities', function () {
        console.log(arguments);
      });
    },

    ready: function () {
      this.$on('wallpaperSearchDidChange', function () {
        console.log('wallpaperSearchDidChange ready');
      });
    },

    methods: {
      togglePurity: function (purity, e) {
        e.preventDefault();

        console.log('toggling', purity);

        var index = this.search.purities.indexOf(purity);
        if (index === -1) {
          this.search.purities.push(purity);
        } else {
          this.search.purities.$remove(index);
        }
      },

      toggleInclusion: function (collection, index, e) {
        e.preventDefault();
        collection[index].included = ( ! collection[index].included);
      }
    },

    computed: {
      currentOrder: function () {
        return this.orderMappings[this.search.order];
      },

      toQueryString: function () {
        console.log('toQueryString called');
        return queryString.stringify(this.search);
      }
    }
  });
})(Vue, _, queryString);
<commit_msg>Define toQueryStringObject<commit_after>(function (Vue, _, queryString) {
  Vue.component('wallpaper-search', {
    data: {
      isDirty: false,

      // Search defaults
      search: {
        order: 'latest',
        purities: [],
        facets: {
          categories: [],
          tags: []
        }
      },

      // Mappings
      purityMappings: {
        sfw: 'SFW',
        sketchy: 'Sketchy',
        nsfw: 'NSFW'
      },
      orderMappings: {
        latest: 'Recency',
        score: 'Relevance',
        popular: 'Popularity',
        random: 'Random'
      },

      myObj: {
        myArr: []
      },
      myArr: []
    },

    created: function () {
      console.log('wallpaper search component ready');

      this.$on('wallpaperSearchDidChange', function () {
        console.log('wallpaperSearchDidChange created');
      });
      this.$watch('search.purities', function () {
        console.log(arguments);
      });
    },

    ready: function () {
      this.$on('wallpaperSearchDidChange', function () {
        console.log('wallpaperSearchDidChange ready');
      });
    },

    methods: {
      togglePurity: function (purity, e) {
        e.preventDefault();

        var index = this.search.purities.indexOf(purity);
        if (index === -1) {
          this.search.purities.push(purity);
        } else {
          if (this.search.purities.length > 1) {
            // Must select at least one purity
            this.search.purities.$remove(index);
          }
        }
      },

      toggleInclusion: function (collection, index, e) {
        e.preventDefault();
        collection[index].included = ( ! collection[index].included);
      },

      toQueryStringObject: function () {
        return _.omit({
          'order': this.search.order,
          'purity[]': this.search.purities,
          'tags[]': _.chain(this.search.facets.tags).where({ included: true }).pluck('id').valueOf(),
          'categories[]': _.chain(this.search.facets.categories).where({ included: true }).pluck('id').valueOf()
        }, _.isEmpty);
      }
    },

    computed: {
      currentOrder: function () {
        return this.orderMappings[this.search.order];
      },

      toQueryString: function () {
        return queryString.stringify(this.toQueryStringObject());
      }
    }
  });
})(Vue, _, queryString);
<|endoftext|>


<commit_before>'use strict';
var request = require('supertest');
var jsonServer = require('../');
var fs = require('fs');

describe('Server', function(){

	/* ===== sample data ===== */
	var dbSample = {
		posts: [{ id: 1, title: "json-server", author: "typicode" }],
		comments: [{ id: 1, body: "some comment", postId: 1 }],
		mongoposts: [{ _id: 1, title: "json-server", author: "typicode" }]
	};

	var db = dbSample;
	var dbJsonPost1 = { id: 1, title: "json-server", author: "typicode" };
	var dbJsonPost1Changed = { id: 1, title: "gulp-json-srv", author: "grafgenerator" };

	var routes = {
	  '/api/': '/',
	  '/blog/:resource/:id/show': '/:resource/:id'
	};

	/* ===== tests running helpers ===== */
	var chainedRun = function(server, url, asserts, currentIndex, done){
		var assert = asserts[currentIndex];
		var lastAssert = currentIndex == asserts.length - 1;

		var r = request(url || server.instance);
		var r2 = assert(r, server);

		r2.end(function(err, res){
			if(err) {
				server.kill();
				return done(err);
			}
			if(lastAssert){
				server.kill();
				done();
			}
			else {
				chainedRun(server, url, asserts, currentIndex + 1, done);
			}
		});
	};

	var startHelper = function(options, serverUrl, done, assertFns){
		var server = jsonServer.start(options || {});
		var asserts = Array.isArray(assertFns) ? assertFns : [ assertFns ];

		if(asserts.length === 0){
			throw 'No asserts provided in test';
		}

		chainedRun(server, serverUrl, asserts, 0, done);
	};

	/* ===== main tests fixture =====*/
	describe('#start()', function(){

		beforeEach(function(){
			db = dbSample;

			fs.writeFileSync('./db.json', fs.readFileSync('sample/db.json'));
			fs.writeFileSync('test/db.json', fs.readFileSync('sample/db.json'));
			fs.writeFileSync('test/changed_db.json', fs.readFileSync('sample/changed_db.json'));
		});

		it('should start server with default options (file "db.json" on port 3000)', function(done){
			startHelper(null, 'http://localhost:3000', done, function(request){
				return request.get('/posts')
					.expect(200, db.posts);
			});
		});

		it('should start server from specific file on specific port', function(done){
			startHelper({ data: 'test/db.json', port: 3001}, 'http://localhost:3001', done, function(request){
				return request.get('/comments')
					.expect(200, db.comments);
			});
		});

		it('should start server in memory db', function(done){
			startHelper({ data: db }, null, done, function(request){
				return request.get('/db')
					.expect(200, db);
			});
		});

		it('should return 404 when json file not exist', function(done){
			startHelper({ data: 'test/db1.json' }, null, done, function(request){
				return request.get('/posts')
					.expect(404, {});
			});
		});

		it('should be able to change base API URL', function(done){
			startHelper({ data: db, baseUrl: '/api' }, null, done, function(request){
				return request.get('/api/db')
					.expect(200, db);
			});
		});

		it('should not be available on root after changing base API URL', function(done){
			startHelper({ data: db, baseUrl: '/api' }, null, done, function(request){
				return request.get('/db')
					.expect(404, {});
			});
		});

		it('should be able to use rewrite rules', function(done){
			startHelper({ data: db, rewriteRules: routes }, null, done, function(request){
				return request.get('/blog/posts/1/show')
					.expect(200, db.posts[0]);
			});
		});

		it('should get a post with mongodb\'s _id' , function(done){
			startHelper({ data: db, id: '_id' }, null, done, function(request){
				return request.get('/mongoposts/1')
					.expect(200, db.mongoposts[0]);
			});
		});

		it('should return 404 for mongopost if default id option' , function(done){
			startHelper({ data: db }, null, done, function(request){
				return request.get('/mongoposts/1')
					.expect(404, {});
			});
		});

		/* ===== reload testing ===== */
		it('should reload default file when no arguments passed to reload method while serving file', function(done){
			startHelper({}, null, done, [
					function(request){
						return request.get('/posts/1')
							.expect(200, dbJsonPost1);
					},
					function(request, server){
						fs.writeFileSync('db.json', fs.readFileSync('test/changed_db.json'));

						server.reload();

						return request.get('/posts/1')
							.expect(200, dbJsonPost1Changed);
					}
				]
			);
		});

		it('should leave in-memory DB as is when no arguments passed reload method', function(done){
			startHelper({ data: db }, null, done, [
					function(request){
						return request.get('/posts/1')
							.expect(200, dbJsonPost1);
					},
					function(request, server){
						server.reload();

						return request.get('/posts/1')
							.expect(200, dbJsonPost1);
					}
				]
			);
		});

		it('should reload specified file when it passed to reload method while serving file', function(done){
			startHelper({}, null, done, [
					function(request){
						return request.get('/posts/1')
							.expect(200, dbJsonPost1);
					},
					function(request, server){
						server.reload('test/changed_db.json');

						return request.get('/posts/1')
							.expect(200, dbJsonPost1Changed);
					}
				]
			);
		});

		it('should reload specified file when it passed to reload method while serving in-memory DB', function(done){
			startHelper({ data: db }, null, done, [
					function(request){
						return request.get('/posts/1')
							.expect(200, dbJsonPost1);
					},
					function(request, server){
						server.reload('test/changed_db.json');

						return request.get('/posts/1')
							.expect(200, dbJsonPost1Changed);
					}
				]
			);
		});

		it('should reload in-memory DB when new object passed to reload method', function(done){
			startHelper({ data: db }, null, done, [
					function(request){
						return request.get('/posts/1')
							.expect(200, dbJsonPost1);
					},
					function(request, server){
						var newDb = { posts: [dbJsonPost1Changed]};
						server.reload(newDb);

						return request.get('/posts/1')
							.expect(200, dbJsonPost1Changed);
					}
				]
			);
		});

		it('should reload in-memory DB when original DB object modified', function(done){
			startHelper({ data: db }, null, done, [
					function(request){
						return request.get('/posts/1')
							.expect(200, dbJsonPost1);
					},
					function(request, server){
						db.posts[0] = dbJsonPost1Changed;

						return request.get('/posts/1')
							.expect(200, dbJsonPost1Changed);
					}
				]
			);
		});
	});
});
<commit_msg>refactoring before adding new tests<commit_after>'use strict';
var request = require('supertest');
var jsonServer = require('../');
var fs = require('fs');

describe('Server', function(){

	/* ===== sample data ===== */
	var dbSample = {
		posts: [{ id: 1, title: "json-server", author: "typicode" }],
		comments: [{ id: 1, body: "some comment", postId: 1 }],
		mongoposts: [{ _id: 1, title: "json-server", author: "typicode" }]
	};

	var db = dbSample;
	var dbJsonPost1 = { id: 1, title: "json-server", author: "typicode" };
	var dbJsonPost1Changed = { id: 1, title: "gulp-json-srv", author: "grafgenerator" };

	var routes = {
	  '/api/': '/',
	  '/blog/:resource/:id/show': '/:resource/:id'
	};

	/* ===== tests running helpers ===== */
	var chainedRun = function(server, url, asserts, currentIndex, done){
		var assert = asserts[currentIndex];
		var lastAssert = currentIndex == asserts.length - 1;

		var r = request(url || server.instance);
		var r2 = assert(r, server);

		r2.end(function(err, res){
			if(err) {
				server.kill();
				return done(err);
			}
			if(lastAssert){
				server.kill();
				done();
			}
			else {
				chainedRun(server, url, asserts, currentIndex + 1, done);
			}
		});
	};

	var basicServerStartHelper = function(options, serverUrl, done, assertFns, serverStartRoutine){
		var server = serverStartRoutine(options);
		var asserts = Array.isArray(assertFns) ? assertFns : [ assertFns ];

		if(asserts.length === 0){
			throw 'No asserts provided in test';
		}

		chainedRun(server, serverUrl, asserts, 0, done);
	};

	var startHelper = function(options, serverUrl, done, assertFns){
		basicServerStartHelper(options, serverUrl, done, assertFns, function(opts){
			return jsonServer.start(opts || {});
		});
	};

	/* ===== main tests fixture =====*/
	describe('#start()', function(){

		beforeEach(function(){
			db = dbSample;

			fs.writeFileSync('./db.json', fs.readFileSync('sample/db.json'));
			fs.writeFileSync('test/db.json', fs.readFileSync('sample/db.json'));
			fs.writeFileSync('test/changed_db.json', fs.readFileSync('sample/changed_db.json'));
		});

		it('should start server with default options (file "db.json" on port 3000)', function(done){
			startHelper(null, 'http://localhost:3000', done, function(request){
				return request.get('/posts')
					.expect(200, db.posts);
			});
		});

		it('should start server from specific file on specific port', function(done){
			startHelper({ data: 'test/db.json', port: 3001}, 'http://localhost:3001', done, function(request){
				return request.get('/comments')
					.expect(200, db.comments);
			});
		});

		it('should start server in memory db', function(done){
			startHelper({ data: db }, null, done, function(request){
				return request.get('/db')
					.expect(200, db);
			});
		});

		it('should return 404 when json file not exist', function(done){
			startHelper({ data: 'test/db1.json' }, null, done, function(request){
				return request.get('/posts')
					.expect(404, {});
			});
		});

		it('should be able to change base API URL', function(done){
			startHelper({ data: db, baseUrl: '/api' }, null, done, function(request){
				return request.get('/api/db')
					.expect(200, db);
			});
		});

		it('should not be available on root after changing base API URL', function(done){
			startHelper({ data: db, baseUrl: '/api' }, null, done, function(request){
				return request.get('/db')
					.expect(404, {});
			});
		});

		it('should be able to use rewrite rules', function(done){
			startHelper({ data: db, rewriteRules: routes }, null, done, function(request){
				return request.get('/blog/posts/1/show')
					.expect(200, db.posts[0]);
			});
		});

		it('should get a post with mongodb\'s _id' , function(done){
			startHelper({ data: db, id: '_id' }, null, done, function(request){
				return request.get('/mongoposts/1')
					.expect(200, db.mongoposts[0]);
			});
		});

		it('should return 404 for mongopost if default id option' , function(done){
			startHelper({ data: db }, null, done, function(request){
				return request.get('/mongoposts/1')
					.expect(404, {});
			});
		});
	});

	describe('#reload()', function(){

		beforeEach(function(){
			db = dbSample;

			fs.writeFileSync('./db.json', fs.readFileSync('sample/db.json'));
			fs.writeFileSync('test/db.json', fs.readFileSync('sample/db.json'));
			fs.writeFileSync('test/changed_db.json', fs.readFileSync('sample/changed_db.json'));
		});

		/* ===== reload testing ===== */
		it('should reload default file when no arguments passed to reload method while serving file', function(done){
			startHelper({}, null, done, [
					function(request){
						return request.get('/posts/1')
							.expect(200, dbJsonPost1);
					},
					function(request, server){
						fs.writeFileSync('db.json', fs.readFileSync('test/changed_db.json'));

						server.reload();

						return request.get('/posts/1')
							.expect(200, dbJsonPost1Changed);
					}
				]
			);
		});

		it('should leave in-memory DB as is when no arguments passed reload method', function(done){
			startHelper({ data: db }, null, done, [
					function(request){
						return request.get('/posts/1')
							.expect(200, dbJsonPost1);
					},
					function(request, server){
						server.reload();

						return request.get('/posts/1')
							.expect(200, dbJsonPost1);
					}
				]
			);
		});

		it('should reload specified file when it passed to reload method while serving file', function(done){
			startHelper({}, null, done, [
					function(request){
						return request.get('/posts/1')
							.expect(200, dbJsonPost1);
					},
					function(request, server){
						server.reload('test/changed_db.json');

						return request.get('/posts/1')
							.expect(200, dbJsonPost1Changed);
					}
				]
			);
		});

		it('should reload specified file when it passed to reload method while serving in-memory DB', function(done){
			startHelper({ data: db }, null, done, [
					function(request){
						return request.get('/posts/1')
							.expect(200, dbJsonPost1);
					},
					function(request, server){
						server.reload('test/changed_db.json');

						return request.get('/posts/1')
							.expect(200, dbJsonPost1Changed);
					}
				]
			);
		});

		it('should reload in-memory DB when new object passed to reload method', function(done){
			startHelper({ data: db }, null, done, [
					function(request){
						return request.get('/posts/1')
							.expect(200, dbJsonPost1);
					},
					function(request, server){
						var newDb = { posts: [dbJsonPost1Changed]};
						server.reload(newDb);

						return request.get('/posts/1')
							.expect(200, dbJsonPost1Changed);
					}
				]
			);
		});

		it('should reload in-memory DB when original DB object modified', function(done){
			startHelper({ data: db }, null, done, [
					function(request){
						return request.get('/posts/1')
							.expect(200, dbJsonPost1);
					},
					function(request, server){
						db.posts[0] = dbJsonPost1Changed;

						return request.get('/posts/1')
							.expect(200, dbJsonPost1Changed);
					}
				]
			);
		});
	});

	describe('#pipe()', function(){

	});
});
<|endoftext|>


<commit_before>/**
 * Non-OpenLayers, totally HTML format Box div
 *
 * Taken directly from PlainBox in ImageBoxer
 */

var Box=Monomyth.Class.extend({
	init:function(args){
		this.DOM=$("

");
		this.DOM.addClass("boxer_plainbox");

		this.userOptions=$("

");
		this.userOptions.addClass("boxer_plainbox_useroptions");

		this.DOM.append(this.userOptions);

		this.closeButton=$("X");
		this.closeButton.addClass("boxer_plainbox_close");
		this.userOptions.append(this.closeButton);
		this.closeButton.bind("click",{obj:this},this.hideSelf);
	},
	makeDrag:function(){
		//store latest css data in case the user resizes box outside of window
		this.DOM.data("lastLeft",this.DOM.css("left"));
		this.DOM.data("lastTop",this.DOM.css("top"));
		this.DOM.draggable({
			start:function(e,ui){
				if (ui.position) {
					if ((ui.position.top > 0)&&(ui.position.left>0)) {
						$(this).data("lastLeft", $(this).css("left"));
						$(this).data("lastTop", $(this).css("top"));
					}
				}
			},
			stop:function(e,ui){
				if((ui.position.top>0)&&(ui.position.left>0)){
					$(this).data("lastLeft",$(this).css("left"));
					$(this).data("lastTop",$(this).css("top"));
				}
			}
		});
		this.DOM.resizable({
			handles:'all',
			start:function(e,ui){
				if((ui.position.top<0)||(ui.position.left<0)){
					$(this).css("left",$(this).data("lastLeft"));
					$(this).css("top",$(this).data("lastTop"));
				} else {
					$(this).data("lastLeft",$(this).css("left"));
					$(this).data("lastTop",$(this).css("top"));
				}
			},
			stop:function(e,ui){
				if((ui.position.top<0)||(ui.position.left<0)){
					$(this).css("left",$(this).data("lastLeft"));
					$(this).css("top",$(this).data("lastTop"));
				} else {
					$(this).data("lastLeft",$(this).css("left"));
					$(this).data("lastTop",$(this).css("top"));
				}
		}});

	},
	zoom:function(e,val){

		var obj=e.data.obj;

		switch(val){
			case 1:
				//change location
				var left=parseInt(obj.DOM.css("left"),10)*args.val;
				obj.DOM.css("left",left+"px");
				var top=parseInt(obj.DOM.css("top"),10)*args.val;
				obj.DOM.css("top",top+"px");

				//change size
				obj.DOM.width((obj.DOM.width()*args.val));
				obj.DOM.height((obj.DOM.height()*args.val));
				break;
			case 0:
				//change location
				var left=parseInt(obj.DOM.css("left"),10)/args.val;
				obj.DOM.css("left",left+"px");
				var top=parseInt(obj.DOM.css("top"),10)/args.val;
				obj.DOM.css("top",top+"px");
				//change size
				obj.DOM.width((obj.DOM.width()/args.val));
				obj.DOM.height((obj.DOM.height()/args.val));
				break;
		}

	},
	hideSelf:function(e){
		e.stopPropagation();
		e.data.obj.DOM.hide();
	},
	getValues:function(){
		if(this.DOM){
			return {
				x:parseInt(this.DOM.css('left'),10),
				y:parseInt(this.DOM.css('top'),10),
				ox:this.DOM.offset().left,
				oy:this.DOM.offset().top,
				w:this.DOM.width(),
				h:this.DOM.height()
			};
		}
	}
});

/**
Selector Box

specifically for placing bounding box on Canvas

grantd
**/

var SelectorBox=Box.extend({
	init:function(args){
		this.$super(args);
		this.userOptions.show();
		//this.changeButton=$("Convert to BW");
		// this.userOptions.append(this.changeButton);
		// 		this.changeButton.bind("click",{obj:this},this.setColorRegion);
		$("body").bind("ImageDoneWorking",{obj:this},function(e,off){
			//get rid of box on canvas
			var obj=e.data.obj;
			if(off) obj.DOM.hide();
		});

		args.loc.append(this.DOM);
		//$("body").bind("zoom",{obj:this},this.zoom);
	},
	setColorRegion:function(e){
		var obj=e.data.obj;
		var values=obj.getValues();
		obj.DOM.trigger("RegionSet",[values]);
	}
});

/**Blob box **/

var BlobBox=Box.extend({
	init:function(args){
		this.$super(args);

		//this.imageObj=args.imageObj;

		this.DOM.attr("id",function(e){
			return "BlobbyBoxey_"+$(".blobbox").length;
		});

		//change CSS style
		this.DOM.removeClass("boxer_plainbox");
		this.DOM.addClass("blobbox");

		//add Options
		this.resizeOn=false;
		this.dragOn=false;

		this.editB=$("Edit");
		this.editB.bind("click",{obj:this},this.edit);
		this.editB.appendTo(this.userOptions);
		/**
		this.editResize=$("Resize");
		this.editResize.addClass("boxer_blob_resize");
		this.resizeOn=false;
		this.editResize.bind("click",{obj:this},this.setResize);

		this.editMove=$("Move");
		this.editMove.addClass("boxer_blob_drag");
		this.dragOn=false;
		this.editMove.bind("click",{obj:this},this.setDrag);
		this.editResize.appendTo(this.userOptions);
		this.editMove.appendTo(this.userOptions);
		**/
		this.DOM.width(args.width);
		this.DOM.height(args.height);
		this.DOM.css("left",args.left+'px');
		this.DOM.css("top",args.top+'px');
		this.DOM.appendTo(args.loc);
		this.optionsON=false;

		//this.DOM.bind("click",{obj:this},function(e){
			//var obj=e.data.obj;
			/**if(obj.optionsON){
				obj.userOptions.hide();
				obj.optionsON=false;
			} else {
				obj.userOptions.show();
				obj.optionsON=true;
			}**/
		//	obj.setResize(e);
			//obj.setDrag(e);
	//	});

	},
	zoomCanvas:function(e,val){
		var obj=e.data.obj;
		var data=obj.imageObj.getZoomLevel();
		var zoom=data.zoomLevel;

		if((val>0)&&(zoom>0)){
			//zoom in
			var left=parseInt(obj.DOM.css("left"),10)*2;
			var top=parseInt(obj.DOM.css("top"),10)*2;
			obj.DOM.css("left",left+"px");
			obj.DOM.css("top",top+"px");
			obj.DOM.width(obj.DOM.width()*2);
			obj.DOM.height(obj.DOM.height()*2);
		} else if(zoom<5){
			//zoom out
			var left=parseInt(obj.DOM.css("left"),10)/2;
			var top=parseInt(obj.DOM.css("top"),10)/2;
			obj.DOM.css("left",left+"px");
			obj.DOM.css("top",top+"px");
			obj.DOM.width(obj.DOM.width()/2);
			obj.DOM.height(obj.DOM.height()/2);
		}

	},
	setResize:function(e){
		var obj=e.data.obj;
		if(!obj.resize){
			obj.DOM.resizable({
				handles:"all"
			});
			obj.DOM.resizable("disable");
			obj.resize=true;
		}
		if(obj.resizeOn){
			obj.DOM.resizable("disable");
			obj.resizeOn=false;
		} else {
			obj.DOM.resizable('enable');
			obj.resizeOn=true;
		}

	},
	setDrag:function(){
		if(!obj.drag){
			obj.DOM.draggable({
				handles:"all"
			});
			obj.DOM.draggable("disable");
			obj.drag=true;
		}
	},
	// setDrag:function(e){
	// 		var obj=e.data.obj;
	// 		if(!obj.drag){
	// 			obj.DOM.draggable({
	// 				handles:"all"
	// 			});
	// 			obj.DOM.draggable("disable");
	// 			obj.drag=true;
	// 		}
	// 		if(obj.dragOn){
	// 			obj.DOM.draggable("disable");
	// 			obj.dragOn=false;
	// 		} else {
	// 			obj.DOM.draggable('enable');
	// 			obj.dragOn=true;
	// 		}
	// 	},
	edit:function(e){
		var obj=e.data.obj;
		$(".blobbox.active").draggable('disable');
		$(".blobbox.active").removeClass("active");

		obj.DOM.addClass("active");

		obj.editB.text("Done");
		obj.editB.unbind("click",obj.edit);
		obj.editB.bind("click",{obj:obj},obj.doneEdit);
		obj.DOM.draggable('enable');
	},
	doneEdit:function(e){
		var obj=e.data.obj;

		obj.DOM.removeClass("active");
		obj.editB.text("Edit");
		obj.editB.unbind("click",obj.doneEdit);
		obj.editB.bind("click",{obj:obj},obj.edit);
		obj.DOM.draggable('disable');
	}
});<commit_msg>JGD<commit_after><|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');

Blend.defineClass('Builder.commands.build.webapp.Builder', {
    extend: 'Builder.commands.build.AnalyzerBase',
    /**
     * Build the Development version of the application
     * @returns {undefined}
     */
    buildDevelVersion: function () {
        var me = this;
        /**
         * Build steps:
         * [1] Clean the build folder. This is done by the base before getting here.
         * [2] Deploy the mandatory blend resources, font icons and images. (blend folder)
         * [3] Deploy blend's JavaScript files (blend folder)
         * [4] Deploy application's js files
         * @returns {Boolean}
         */
        me.deployIconFonts();
        me.deployScriptsAndStyleSheets();
        me.createDevIndex();

    },
    createDevIndex: function () {
        var me = this,
                headers = Template.renderDevHeaders(
                        Template.renderMetaTags(me.project.meta),
                        Template.renderStyleSheets(me.project.stylesheets),
                        Template.renderScripts(me.project.scripts)
                        ),
                index = Template.renderIndex(me.project.indexTemplate, {
                    name: me.project.name,
                    headers: headers
                }),
                indexFile = me.project.getBuildFolder(me.project.indexTemplate);
        Logger.info('Deploying: ' + indexFile);
        fs.writeFileSync(indexFile, index);
    },
    deployScriptsAndStyleSheets: function () {
        var me = this, target, scripts = [], stylesheets = [];
        Blend.foreach(me.depMap, function (item, cname) {
            target = me.getTargetPathAndUrl(item.classFile);
            if (target) {
                FileUtils.copyFile(target.srcFile, target.destFile);
                scripts.push({
                    src: target.url
                });
                Logger.info('Deploying: ', target.url);
            }
            if (item.cssFile) {
                target = me.getTargetPathAndUrl(item.cssFile);
                FileUtils.copyFile(target.srcFile, target.destFile);
                stylesheets.push({
                    src: target.url
                })
                Logger.info('Deploying: ', target.url);
            }
        });
        me.project.scripts = scripts.concat(me.project.scripts);
        me.project.stylesheets = stylesheets.concat(me.project.stylesheets);

        target = me.getTargetPathAndUrl(me.project.getSourceFolder('bootstrap.js'));
        FileUtils.copyFile(target.srcFile, target.destFile);
    },
    getTargetPathAndUrl: function (file) {
        var me = this, dst, srcFile, destFile,
                sdkPath = Blend.getSDKFolder(),
                prjPath = me.project.getProjectFolder();
        if (file.startsWith(sdkPath)) {
            dst = file.replace(Blend.fixPath(sdkPath + '/'), 'blend/');
            srcFile = file;
            destFile = me.project.getBuildFolder(dst);
        } else {
            dst = file.replace(Blend.fixPath(prjPath), '');
            srcFile = file;
            destFile = me.project.getBuildFolder(dst);
        }
        return {
            srcFile: srcFile,
            destFile: destFile,
            url: dst.split(path.sep).join('/')
        }
    }
});

<commit_msg>Fixed faulty asset list creation<commit_after>var fs = require('fs');
var path = require('path');

Blend.defineClass('Builder.commands.build.webapp.Builder', {
    extend: 'Builder.commands.build.AnalyzerBase',
    /**
     * Build the Development version of the application
     * @returns {undefined}
     */
    buildDevelVersion: function () {
        var me = this;
        /**
         * Build steps:
         * [1] Clean the build folder. This is done by the base before getting here.
         * [2] Deploy the mandatory blend resources, font icons and images. (blend folder)
         * [3] Deploy blend's JavaScript files (blend folder)
         * [4] Deploy application's js files
         * @returns {Boolean}
         */
        me.deployIconFonts();
        me.deployDevScriptsAndStyleSheets();
        me.createDevIndex();

    },
    /**
     * Created the index file for the development mode
     * @returns {undefined}
     */
    createDevIndex: function () {
        var me = this,
                headers = Template.renderDevHeaders(
                        Template.renderMetaTags(me.project.meta),
                        Template.renderStyleSheets(me._stylesheets.concat(me.project.stylesheets)),
                        Template.renderScripts(me._scripts.concat(me.project.scripts))
                        ),
                index = Template.renderIndex(me.project.getProjectFolder(me.project.indexTemplate), {
                    name: me.project.name,
                    headers: headers
                }),
                indexFile = me.project.getBuildFolder(me.project.indexTemplate);
        Logger.info('Deploying: ' + indexFile);
        fs.writeFileSync(indexFile, index);
    },
    /**
     * Deploys the scripts and stylesheets in the dev mode
     */
    deployDevScriptsAndStyleSheets: function () {
        var me = this, target, scripts = [], stylesheets = [];
        Blend.foreach(me.depMap, function (item, cname) {
            target = me.getTargetPathAndUrl(item.classFile);
            if (target) {
                FileUtils.copyFile(target.srcFile, target.destFile);
                scripts.push({
                    src: target.url
                });
                Logger.info('Deploying: ', target.url);
            }
            if (item.cssFile) {
                target = me.getTargetPathAndUrl(item.cssFile);
                FileUtils.copyFile(target.srcFile, target.destFile);
                stylesheets.push({
                    src: target.url
                })
                Logger.info('Deploying: ', target.url);
            }
        });
        me._scripts = scripts;
        me._stylesheets = stylesheets;

        target = me.getTargetPathAndUrl(me.project.getSourceFolder('bootstrap.js'));
        FileUtils.copyFile(target.srcFile, target.destFile);
    },
    /**
     * Translates the deployment path
     */
    getTargetPathAndUrl: function (file) {
        var me = this, dst, srcFile, destFile,
                sdkPath = Blend.getSDKFolder(),
                prjPath = me.project.getProjectFolder();
        if (file.startsWith(sdkPath)) {
            dst = file.replace(Blend.fixPath(sdkPath + '/'), 'blend/');
            srcFile = file;
            destFile = me.project.getBuildFolder(dst);
        } else {
            dst = file.replace(Blend.fixPath(prjPath), '');
            srcFile = file;
            destFile = me.project.getBuildFolder(dst);
        }
        return {
            srcFile: srcFile,
            destFile: destFile,
            url: dst.split(path.sep).join('/')
        }
    }
});

<|endoftext|>